[英]Can write to, but can't read from serial port ttyS0 in linux C program
我正在嘗試學習如何使用 C 在 Linux 中對 ttyS0 串行端口進行編程。我有另一台機器連接到我的串行端口,大約每兩秒發送 5f 和 6f 的交替十六進制值。 我已經與其他端口監控應用程序驗證了這些值出現在端口上。 在我的代碼中,我將阻塞read()用於 10 個字符長度的緩沖區。 盡管我的另一台機器仍在發送數據,但read() 將永遠阻塞。 如果我包括fcntl(fd, F_SETFL, FNDELAY); 將 read() 設置為非阻塞 read() 總是以 -1 的值返回,這意味着 UART 緩沖區中沒有數據,我的 for 循環代碼只是打印出緩沖區中的隨機值。 所以簡而言之,我的假設是我的代碼沒有讀取 ttyS0,我不知道為什么。 下面是我的代碼,希望有人會看到是什么導致了我的問題並讓我直截了當。 順便說一句,我使用的是 Scientific Linux,我相信 ttyS0 是 com 端口 1,就像在 RedHat 和 Fedora 中一樣。 下面是我運行代碼時的輸出。 它似乎可以毫無問題地寫入 COM 端口,但讀取時卻說它不可用。 另外很明顯,我打印的緩沖區只是隨機值,而不是已讀入的數據。謝謝
hello world
hi again
write error: : Success
wrote 4 bytes
number of bytes read is -1
read error:: Resource temporarily unavailable
4 8 120 -99 -73 -65 41 -120 4 8
should of put something out
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
int main()
{
printf("hello world\n");
int n;
int fd;
char c;
int bytes;
char buffer[10];
char *bufptr;
int nbytes;
int tries;
int x;
struct termios options;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if(fd == -1)
{
perror("open_port: Unable to open:");
}
else
{
fcntl(fd, F_SETFL, 0);
printf("hi again\n");
}
tcgetattr(fd, &options);
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~( ICANON | ECHO | ECHOE |ISIG );
options.c_iflag &= ~(IXON | IXOFF | IXANY );
options.c_oflag &= ~OPOST;
tcsetattr(fd, TCSANOW, &options);
write(fd, "ATZ\r",4);
printf(" wrote\n");
bufptr = buffer;
fcntl(fd, F_SETFL, FNDELAY);
bytes = read(fd, bufptr, sizeof(buffer));
printf("number of bytes read is %d\n", bytes);
perror ("read error:");
for (x = 0; x < 10 ; x++)
{
c = buffer[x];
printf("%d ",c);
}
close(fd);
//puts(buffer[0]);
printf("\nshould of put something out \n");
return (0);
}
嘗試設置MIN
和/或TIME
值:
/*...*/
options.c_cc[VMIN] = 1; //read() will return after receiving 1 character
options.c_cc[VTIME] = 0; // == 0 - infinite timeout, != 0 - sets timeout in deciseconds
/*...*/
tcsetattr(fd, TCSANOW, &options);
給定的示例將設置您的 read() 在獲取任何符號后返回並無限期地等待輸入。 當然,您可以根據需要使用這些參數(例如,如果需要,將 MIN 設置為 10)。
您可能想要刪除fcntl(fd, F_SETFL, FNDELAY);
呼吁這個工作雖然。
在離開程序之前保存以前的 termios 設置並恢復它們也是明智的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.