繁体   English   中英

Linux中的串行端口通信返回错误答案

[英]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");
}

我在这里有几个问题:

  1. 在我运行程序后,它可以正确执行,但是当我再次尝试运行它时,它将停止在“我正在读取数据...”,即使重新启动计算机也无法启动。 一段时间后,它允许我再次执行程序。
  2. 程序返回数据后,它应该向我发送十六进制数据,例如A7、9F等,但这给了我整数值。
  3. 我应该如何清除缓冲区数组以释放内存

任何人都可以帮助解决这些问题吗?

'int n =读取(fd,缓冲区,sizeof(缓冲区));' 返回读入n的字节数,然后忽略该字节数(除了检查负错误值之外),并假定缓冲区已完全填充。 这是一个错误,因为recv()通常不等待请求的字节数,因为串行端口提供字节流,而不是“缓冲区”或“消息”。

printf(“ Hex:%x \\ n”,buffer [i]); 将显示整数,因为您用%x指定了整数。 请仔细查看printf格式代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM