1

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.

4

1 回答 1

1

我的问题解决了。在 C 中处理字节时,不要将字节 (char) 与字符串混淆,就像我正在处理字节数组 (char data[]) 以及当我尝试write使用长度为 strlen(data) 的方法在串行端口上写入这些字节时,我只得到那些不为空的字节。strlen在看到第一个空字符后返回数据的长度\0,因为这个我没有得到我想要的输出。我所做的是,如果我想写数据,char data[] = {0, 4}那么我会做这样的事情:

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

告诉write函数写入 2 个字节。这将写入 0 和 4,如果我这样写:

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

这会写NOTHING

还有一件事,如果您想在串行端口上写入不可打印的字符(从字节值 0 到 32),请确保您已将串行端口配置为原始输入和输出。看看这个指南:

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

于 2013-12-13T12:43:25.723 回答