[英]Serial port communication in linux returns wrong answers
我正在尝试创建一个Linux ubuntu程序,该程序将从tty串行端口(Windows中的COM端口)读取数据。 我没有使用USB适配器,而是实际的COM端口。 到目前为止,这是我的交流代码:
int OpenPort(void)
{
int fd; // file description for sp
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_SYNC);
if(fd == -1) // port not opened
{
printf("Error:\n%s.\n", strerror(errno));
}
else
{
fcntl(fd, F_SETFL, 0);
printf("Success.\n");
}
return(fd);
} // Open sp
void Communicate(void)
{
struct termios settings;
tcgetattr( fd, &settings );
cfsetispeed(&settings, B9600); // Set bouds
cfsetospeed(&settings, B9600);
settings.c_cflag &= ~PARENB; // set no parity, stop bits, data bits
settings.c_cflag &= ~CSTOPB;
settings.c_cflag &= ~CSIZE;
settings.c_cflag |= CS8;
tcflush( fd, TCIFLUSH );
if (tcsetattr(fd, TCSAFLUSH, &settings)!= 0)
{
printf("Error message");
}
//Create byte array
unsigned char send_bytes[] = { 0x1, 0x6, 0x2, 0xAA, 0x2, 0x3, 0xB8, 0x4 };
write(fd, send_bytes, sizeof(send_bytes)); // Send data
printf("Data sent. \n");
char buffer[64]; // buffer to receive data
printf("I'm reading data...\n");
int n = read(fd, buffer, sizeof(buffer));
if (n < 0)
printf("Failed to read\n");
int i;
printf("Showing data...\n");
for(i=0; i<sizeof(buffer); i++)
{
printf("Hex: %x\n", buffer[i]);
}
printf("Closing...\n");
close(fd);
printf("All done!\n");
}
我在这里有几个问题:
任何人都可以帮助解决这些问题吗?
'int n =读取(fd,缓冲区,sizeof(缓冲区));' 返回读入n的字节数,然后忽略该字节数(除了检查负错误值之外),并假定缓冲区已完全填充。 这是一个错误,因为recv()通常不等待请求的字节数,因为串行端口提供字节流,而不是“缓冲区”或“消息”。
printf(“ Hex:%x \\ n”,buffer [i]); 将显示整数,因为您用%x指定了整数。 请仔细查看printf格式代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.