[英]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.