这是这个原始post的后续问题:
RaspBerryPi RS-232的麻烦
我根据接受的答案对代码进行了更改,terminal现在设置为阻止和规范input。 read()现在可以按照预期工作,除了第一次读取(通常是一些额外的随机符号和一些好的数据混合在一起)之外,我从激光测距仪获得的单行数据代表了我期望看到的。
不过,现在我有一个问题,如果读取的次数太多,激光测距仪会进入非工作状态,停止通讯,只能通过重新上电重置。 这种情况发生在设备上只有4次读取,而且我还没有能够完成8次以上的读取。 读取全部是同时进行还是跨越多个程序启动都无关紧要。
如何在Linux中使用C从串口读取数据?
UART初始化:防止UART拉高RTS
用C写串口读写
我可以使用USB到串口适配器从VMWare Fusion与我的开发板交谈吗?
如何获得串行COM端口的状态
int main(){ int uart0_filestream = -1; int loop,i,sentBytes; int isError,rx_length; unsigned char rx_buffer[256]; uart0_filestream = open("/dev/ttyAMA0",O_RDWR | O_NOCTTY | O_NDELAY); fcntl(uart0_filestream,F_SETFL,0); if(uart0_filestream == -1){ printf("ERROR: Unable to open UARTn"); checkerror(errno); exit(1); } struct termios options; isError = tcgetattr(uart0_filestream,&options); if(isError < 0){ printf("ERROR: tcgetattr Failed.n"); checkerror(errno); exit(1); } //set c ontrol options and baud options.c_cflag |= (CLOCAL | CREAD); cfsetispeed(&options,B19200); cfsetospeed(&options,B19200); //set 8 data bits,1 stop bit,no parity options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; //set input options options.c_iflag |= (INPCK | ISTRIP); //strip parity options.c_iflag &= ~(IXON | IXOFF | IXANY); //turn off software flow control //set canonical input processing options.c_lflag |= (ICANON | ECHO | ECHOE); tcflush(uart0_filestream,TCIFLUSH); isError = tcsetattr(uart0_filestream,TCSANow,&options); if(isError < 0){ printf("ERROR: tcsetattr Failed.n"); checkerror(errno); exit(1); } //read() successfully returns expected data,with the exception of the first //read. Reading more than 6-8 times,regardless of same session or restarting //program puts LRF in non-working state which requires a power cycle to fix for(i=0; i<4;i++ ){ rx_length = read(uart0_filestream,(void*)rx_buffer,255); if(rx_length < 0){ printf("ERROR: read() Failed.n"); checkerror(errno); } if(rx_length > 0){ printf("rx_lentgh = %i:t ",rx_length); for(loop=0; loop<rx_length; loop++){ printf("%c",rx_buffer[loop]); } printf("n"); } } //writing once has no affect,sending command has no affect //looping the write,eventually 'something' gets to the LRF //but it puts it in the same state as when reading too many //times and have to power cycle for(i = 0; i<8; i++){ sentBytes = write(uart0_filestream,"on",2); if(sentBytes < 2){ printf("ERROR: write() Failed.n"); checkerror(errno); } } close(uart0_filestream); }
我不相信它是测距仪,因为我可以运行minicom,它会不断显示输出成功。
正如我的代码的评论中指出的那样,我也有麻烦写任何命令到激光测距仪。 每个命令由单个字符组成,后面跟着一个新行。 一次写入没有影响,但多次循环可以使设备处于与读取次数相同的状态。
我已经阅读了Posix的串行编程指南 ,并尝试了不同的标志组合,我相信这可能会影响阅读或写作,但没有成功。
使用boost.asio是否可以使用标记和空格?
发送一个rest字节与Windows COM端口
如何检测属于gsm / 3G调制解调器的tty是数据还是控制端口?
通过蓝牙/ RFCOMM / SPP发送二进制数据将0x0A转换为0x0D 0x0A
[编辑]这个主要建议是我的尴尬 – 认为字符串是“o / n”。
发送的数据量是短1。
// sentBytes = write(uart0_filestream,2); // if(sentBytes < 2){ sentBytes = write(uart0_filestream,3); if(sentBytes < 3){
轻微:不清楚为什么读取缓冲区减少1(sizeof rx_buffer是256)。 read()不会附加一个