简体   繁体   中英

Reading NULL character from Serial Port Linux C

I have read many questions and answers but didn't find any solution. May be my question is not right but I need some guidance. I am using serial port in Linux which is reading data from my Arduino device. Whenever I want to send data from Arduino to Linux, I first send two bytes which indicate the total bytes which will come from Arduino. I convert these two bytes to integer value and start reading data from Serial Port. Say, I want to send 300 bytes from Ardiuno to Linux, I will just write {1, 44} first and then convert this 1 and 44 byte into int by the following formula:

char data[] = {1, 44};
int to_read = data[0]
to_read = to_read << 8;
to_read = to_read | data[1];
return to_read;

this will give me 300 int value, this is working like charm. but problem comes when I have to read data less then 255. Say I want to read 100 bytes, then first two bytes will be {0, 100}. 0 is null character, serial port doesn't process it (I manually wrote 0s to serial port, it always give me 0 bytes written), and my all sequence goes wrong. So my question is can I read null characters from serial port OR someone please give me better solution..

thanks in Advance.

I got my problem solved. When working on bytes in C, don't confuse bytes (char) with string like I was treating bytes array (char data[]) and When I was trying to write these bytes on serial port with write method with length of strlen(data), I was only getting those bytes which were not null. strlen returns the length of data after seeing first null character that is \\0 , because of this I was not getting my desired output. What I did is that, If I want to write data char data[] = {0, 4} then I will do something like this:

char data[] = {0, 4};
write(serial_port_fd, data, 2);

told the write function to write 2 bytes. This will write 0 and 4, If I write something like this:

char data[] = {0, 4}
write(serial_port_fd, data, strlen(data));

this will write NOTHING .

One more thing, If you want to write non printable characters (which are from byte value 0 to 32) on Serial Port, then make sure that you have configured your Serial Port for raw input and ouput. Have a look on this guide:

http://www.cmrr.umn.edu/~strupp/serial.html#config

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM