我正在尝试创建一个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");
}
我有几个问题:
任何人都可以帮助解决这些问题吗?
答案 0 :(得分:0)
&#39; int n = read(fd,buffer,sizeof(buffer));&#39;返回n中读取的字节数,然后忽略,(除了检查负的错误值),并假设缓冲区已完全填满。这是一个错误,因为recv()通常不会等待请求的字节数,因为串行端口提供字节流,而不是“缓冲区”。或者&#39;消息&#39;。
printf(&#34; Hex:%x \ n&#34;,buffer [i]);将显示整数,因为您指定了带有%x的整数。仔细查看printf格式代码。