Sending characters through the serial port including zero-value bytes

5

I'm doing an application in which I need to send via an external hardware an array of characters (declared as unsigned char ) that contains commands and times.

With the commands I have no problem, since each command corresponds to a unsigned char ('A', 'B', etc.). The problem is with time.

The time is stored in a unsigned short int variable that I access byte to through a t vector of unsigned char , using the following union :

union tempos {
    unsigned short int tempo; //16 bits ou 2 bytes
    unsigned char t[2]; //8 bits ou 1 byte [cada posição]
}temp;

So, an example of the array structure of unsigned char that I should send is the following:

[cabeçalho] [comando1] [comando2] [byte1 do tempo1 (temp.t[0])] [byte2 do tempo1 (temp.t[1])] [comando 3] 

The problem is when one of the bytes of time is equal to 0, since 0 corresponds to NULL in the ASCII table and NULL is the character that marks the end of a vector of char . So when this condition occurs my array does not end up being formed (because there is a NULL ) and consequently it is not transferred correctly via serial.

Edited (added an important comment to the body of the question):

WriteFile(hComm,Buffer,strlen(Buffer),&bytesEscritos,NULL);

The shipping code is this. hComm is the serial configuration variable, Buffer the array of unsigned char that I want to send, the third parameter is the size of the array, the fourth is the number of bytes written and the last one is an overlapping configuration . The problem is that Buffer does not have the value it should due to NULL corresponding to 0. For example, instead of having #ABTTCD@ , where A , B , C and D are commands and T each of the time bytes, Buffer is #ABT or #AB depending on which of the bytes of time is 0.

    
asked by anonymous 12.11.2014 / 01:31

1 answer

1

Your problem is with the statement you are using:

WriteFile(hComm,Buffer,strlen(Buffer),&bytesEscritos,NULL);

Note that the strlen will return the size to the first byte with zero value and that's where your problem is. Do not use strlen to do this ! You need to use another way to measure the size of what you want to send, something that can accept values 0 within your Buffer .

The way to measure size will probably consist of the sum of the size of each of the terms, where a term can be a header, a command or a union element. It seems to me that the header and the command always has size 1 ( sizeof(unsigned char) ) and the union always has size 2 ( sizeof(temp) ). Just add everything.

Obviously, if what you send at this point is always in the #ABTTCD@ format, where A , B , C , D , and each T has exactly one byte, it seems to me trivial to define that the value of the third parameter should always be 8.

    
12.11.2014 / 08:16