我正在使用简单的c程序从传感器接收数据,该传感器通过UART发送数据。在Ubuntu工作。程序简单如下所示:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#include <net/if.h>
#include <unistd.h>
#include <sys/ioctl.h>
#define BAUDRATE B9600 // Change as needed, keep B
#define MODEMDEVICE "/dev/ttyS0"
#define _POSIX_SOURCE 1 /* POSIX compliant source */
#define FALSE 0
#define TRUE 1
main()
{
int fd, c, res;
char buf[1024];
struct termios oldtio, newtio;
fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd < 0)
{
perror(MODEMDEVICE);
exit(-1);
}
bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */
newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
/* Raw output */
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;
/* now clean the modem line and activate the settings for the port */
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
while (TRUE) { /* loop continuously */
memset(buf,0,1024);
res = read(fd, buf, 1024);
buf[res] = 0; /* set end of string, so we can printf */
printf("%s\n", buf);
}
tcsetattr(fd, TCSANOW, &oldtio);
}
这个程序正在运行,但它会收到一些数据,如:
abcdef,234.456,678.234,w,e,123.5566,78.90,12344.567,3456.789
abcdef,234.456,678.234,w,e,123.5566,78.90,12344.567,3456.789
abcdef,234.456,678.234,w,e,123.5566,78.90,12344.567,3456.789
abcdef,234.456,678.234,w,e,123.5566,78.90,12344.567,3456.789
abcdef,234.456,678.234,w,e,123.5566,78.90,12344.567,3456.789
abcdef,234.456,678.234,w,e,123.5566,78.90,12344.567,3456.789
abcdef,234.456,678.234,w,e,123.5566,78.90,12344.567,3456.789
继续循环5-8次后,它没有接收数据。程序不退出(它只会处于运行状态),但数据不会打印。
如何让这个程序连续接收数据......(无限次)