簡體   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