如何用中断串口读取串口? [英] How to read serial with interrupt serial?
问题描述
我正在尝试在Linux中阅读NMEA消息.但我无法获得完整的消息:
I'm trying to read NMEA message in Linux. But I can't get a completely message:
54.441,V,,,,,0.00,0.00,010720,,,N*42
$GPVTG,0.00,T,,M,0.00,N,0.00,K,N*32
$GPGGA,020954.441,,,,,0,0,,,M,,M,,*43
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,1,1,00*79
$GLGSV,1,1,00*65
$GPGLL,,,,,020954.441,V,N*71
$GP
第一行和最后一行是一条消息,但已被拆分.我的事,这是由睡眠1秒引起的.而且这根本不对.我想我应该使用中断串行.
The first line and last line is the one message but it have been splited. I thing, It's cause by sleep 1 second. And It's not right at all. I think I should use interrupt serial.
我的想法是,当数据进入时,中断串行将运行一个读取串行并处理它的功能.之后,系统将休眠直到下一条消息.我搜索了一些材料,但这没有帮助.
My idea is when data in come, interrupt serial will run a function which read serial and handle it. After that, system will sleep until next message. I searched some material but It's doesn't help.
这是我的新代码,它不起作用:
This is my new code and it's not working:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <sys/signal.h>
#include <errno.h>
#include <termios.h>
void signal_handler_IO ();
int fd;
int connected;
struct termios termAttr;
struct sigaction saio;
int main(int argc, char *argv[])
{
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open port\n");
exit(1);
}
saio.sa_handler = signal_handler_IO;
saio.sa_flags = 0;
saio.sa_restorer = NULL;
sigaction(SIGIO,&saio,NULL);
fcntl(fd, F_SETFL, FNDELAY);
fcntl(fd, F_SETOWN, getpid());
fcntl(fd, F_SETFL, O_ASYNC );
tcgetattr(fd,&termAttr);
cfsetispeed(&termAttr,B9600);
cfsetospeed(&termAttr,B9600);
termAttr.c_cflag &= ~PARENB;
termAttr.c_cflag &= ~CSTOPB;
termAttr.c_cflag &= ~CSIZE;
termAttr.c_cflag |= CS8;
termAttr.c_cflag |= (CLOCAL | CREAD);
termAttr.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
termAttr.c_iflag &= ~(IXON | IXOFF | IXANY);
termAttr.c_oflag &= ~OPOST;
tcsetattr(fd,TCSANOW,&termAttr);
printf("UART1 configured....\n");
while(1){
sleep(1);
}
close(fd);
exit(0);
}
void signal_handler_IO ()
{
FILE *csv;
char buff [1024];
int n = read(fd, &buff, sizeof(buff));
char * token = strtok(buff, ",");
csv=fopen("csvfile.csv","w");
while( token != NULL ) {
fprintf(csv,"%s\n",token);
token = strtok(NULL, ",");
}
fclose(csv);
}
我现在应该做什么?
推荐答案
NMEA消息为行,以'\ n'
结尾.
NMEA message are lines, ending with a '\n'
.
将 read()
更改为 fgets()
(使用 fopen()
打开)并读取为 line 放入 string 中,以便以后进行 strtok()
处理.
Change read()
to fgets()
(open using fopen()
) and read as a line into a string for later strtok()
processing.
另请参阅 @Craig Estey 的想法.
这篇关于如何用中断串口读取串口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!