我用C語言編寫的Linux串口工作下面是我的UART設置在C Linux的串行端口工作,不能夠得到充分的數據
int fd;
struct termios tty_attributes;
fd = open(comport, O_RDWR | O_NOCTTY | O_SYNC | O_NONBLOCK);
if(fd < 0)
{
perror("open comport error.\n");
exit(EXIT_FAILURE);
}
else
{
if(tcgetattr(fd, &tty_attributes) == -1)
{
perror("tcgetattr termios function error.\n");
exit(EXIT_FAILURE);
}
tty_attributes.c_lflag = 0;
tty_attributes.c_oflag = 0;
tty_attributes.c_iflag = 0;
tty_attributes.c_cflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
tty_attributes.c_cflag |= CS8;
tty_attributes.c_cflag |= CLOCAL;
tty_attributes.c_cflag &= ~CREAD;
tty_attributes.c_oflag &= ~OPOST;
tty_attributes.c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
tty_attributes.c_cc[VMIN] = SIZE_STR_FRAME;
cfsetospeed(&tty_attributes, BAUDRATE); //setting communication speed and other attributes
cfsetispeed(&tty_attributes, BAUDRATE);
tcflush(fd, TCIOFLUSH);
tcsetattr(fd, TCSANOW, &tty_attributes); //change immediately
return fd;
}
}
而下面是我的代碼用於讀取的幀
char* frame_read(int fd)
{
char *ret = NULL;
int read_ret_val;
struct timeval time_val;
if (fd < 0)
{
printf("Before read over comm channel, channel must be initialize\n");
exit(EXIT_FAILURE);
}
memset(frame, 0, SIZE);
fd_set rfds; //read file discriptors
int return_val;
FD_SET(fd, &rfds);
setReceiveMode(fd, TRUE);
tcflush(fd, TCIFLUSH);
tcflush(fd, TCOFLUSH); //flush previous values
return_val = select((fd) + 1, &rfds, NULL, NULL, &time_val);
if (return_val == -1)
{
perror("select");
exit(EXIT_FAILURE);
}
else if (return_val)
{
usleep(100 * 1000);
read_ret_val = read(fd, frame, SIZE);
if (read_ret_val < 0)
{
perror("read");
exit(EXIT_FAILURE);
}
ret = frame;
//printf("inside else if of read\n");
}
}
我有一個GPS模塊與所述UART連接,並且當我與小型機檢查我得到的全幀,但是當我接收通過UART(使用此代碼)我得到前16個字節ö NLY。 任何人都可以指出我的錯誤。? 這裏波特率是9600,幀是64字節,SIZE是64字節,我用的緩衝區也是64字節。請原諒我格式化錯誤,如果有的話。
我的main.c文件
int main(int argc, char *argv[])
{
int i=0,j=0;
char *readb;
unsigned char data[34];
static int fd = -1;
struct struct_base_gps *gps;
int command=0;
char COMM_PORTNAME[13];
strcpy(COMM_PORTNAME, argv[1]);// give the first port number for GPS receiving
if((fd = init_comm_channel(COMM_PORTNAME)) < 0)
{
exit(EXIT_FAILURE);
printf("port is not opened\n");
}
else
{
printf("port is open for communication:\n");
readb = frame_read(fd);
for (i=0;i<=34;i++)
{
data[i] = *(readb +j);
printf("the data is %x\n",data[i]);
j++;
}
}
close (fd);
}
爲SIZE是 的#define SIZE 64 和幀是 炭幀[64];
感謝您的反饋,我更新了代碼。
此外,更新幀圖片,我在終端以及與程序。可能它會清除更多。
Received the data from UART by program
與您的問題無關,但在使用之前需要清除描述符集'rfds'。一個集合基本上是一個包含一個數組的結構,如果你沒有在集合上使用'FD_ZERO',你的第一件事就是數據將被初始化並且因此具有* indeterminate *值。 'time_val'也是同樣的問題,它必須被初始化爲你想要的超時時間。 –
至於你的問題,你需要創建一個[最小化,完整和可驗證的例子](http://stackoverflow.com/help/mcve)並告訴我們。包括你如何調用這些函數和你使用的變量的定義。例如,什麼是「框架」?什麼是「尺寸」? –
最後,通過串行通訊發送的數據是* streaming *。沒有固定的消息邊界或數據包。如果你需要,你需要自己實現它。這也意味着一次調用'read'我不會讀完整的消息(「frame」),或者它可能讀取多於一條消息(如果存在多個緩衝區)。您需要循環讀取,直到您收到至少一條消息,並且能夠在單個「讀取」調用中處理多個消息(並且最後一條消息可能是部分消息)。 –