1.问题背景:
使用linux开发板与电脑串口助手间进行收发通信,发现每次发送数据需要在数据后加入换行符后linux板的串口读取线程才有反应,读取串口数据。
未配置前的通信串口最后一次数据加入换行符:
log串口:检测到换行符后一次显示所有数据
2.解决方法
在串口配置参数struct termios options中增加
options.c_lflag &= ~(ICANON | ECHO | ECHOE);
不加换行符:
log串口:
增加换行符:
3.完整代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/select.h>
/*打开串口*/
static int open_port(char *dev)
{
/* send_break = 0, dev = /dev/ttyS0 raw = 0 */
struct termios options;
int fd;
fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd < 0)
{
perror("Can't open serial port");
return -1;
}
// 配置串口参数
tcgetattr(fd, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
//增加这一行解决没有换行符不显示问题
options.c_lflag &= ~(ICANON | ECHO | ECHOE);
tcsetattr(fd, TCSANOW, &options);
return fd;
}
static void *uart_read(void *arg)
{
char receive_buf[255] = {0};
int recv_len = 0;
int fd = *(int *)arg;
while (1)
{
recv_len = read(fd, receive_buf, sizeof(receive_buf) - 1);
if (recv_len > 0)
{
printf("Receive_len=%d\n", recv_len);
printf("Received: %.*s\n", recv_len, receive_buf);
}
usleep(10 * 1000);
}
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
// 打开串口设备
fd = open_port("/dev/ttyS3");
if (fd == -1)
{
printf("open err\n");
exit(1);
}
else
{
printf("open uart\n");
}
int ret;
pthread_t tid1;
ret = pthread_create(&tid1, NULL, uart_read, &fd);
while(1)
{
}
return 0;
}