Y
Y
yaponchik2015-05-22 16:20:26
C++ / C#
yaponchik, 2015-05-22 16:20:26

What is the correct way to work with UNION in C?

The ADUC814 controls the AD7793 ADC and communicates via RS232 to another AT89C51 MCU.
Previously, I operated only with 3 bytes, received them and transmitted them in this way:

union
    {
        unsigned long uD;
        unsigned char uData[4];
    } uDataUnion;
char i = 0;
uDataUnion.uData[0] = uDataUnion.uData[1] = 
uDataUnion.uData[2] = uDataUnion.uData[3] = 0x00;
for (i = 1; i <= 3; ++i)
    { 
        SPIDAT = 0x00;
        while (!ISPI);
        uDataUnion.uData[i] = SPIDAT;  // запоминает принятый от AD7793 очередн. байт
        ISPI = 0;   
    }
for (i = 3; i >= 0; --i)
    {
        Putc(kGainUnion.kGainArr[i]);
    }

Experimentally, I found out that the data is correctly "glued" only when we set the zero element of the array to zero in the union, and write the bytes from the 1st to the 3rd, i.e. in fact, for a 3-byte number, I used a 4-byte one.
Now to the question.
At this stage, I needed to pre-process the ADC codes before sending:
union
    {
        unsigned long int kGain;
        unsigned char kGainArr[4];
    } kGainUnion;
kGainUnion.kGain = ((2147483648 - pow(2, (31-gain))) + (uDataUnion.uD * pow(2, (7-gain))));

the result of this operation takes 4 bytes, so for its correct "gluing" I need the 5th byte, equal to 0x00.
KEIL C51 cannot handle data larger than 4 bytes, so there is a transmission problem. How can I make this easier? and Why UNION doesn't work correctly, i.e. account for

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Martyanov, 2015-05-22
@vilgeforce

It is not entirely clear what you mean by "gluing" and what is the final task.
As I understand it, you read three bytes from the AD7793, save them. Then treat these three bytes as a 32-bit value (higher 8 bits are zeros), perform mathematical operations on them and send the result somewhere?

A
Alexander, 2015-05-22
@baybak

Check if the compiler works correctly with a null array element. On pic compilers for 64-bit machines, this problem occurs.
You can work through the pointer (char*)kGainUnion

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question