串口c编程接收数据
Iam使用简单的c程序从通过UART发送数据的传感器接收数据。在Ubuntu中工作。程序非常简单,如下所示:串口c编程接收数据,c,C,Iam使用简单的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> #includ
#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);
}
在继续while循环5-8次后,则不接收数据。程序不会退出(仅在运行状态下),但不会打印数据
如何使该程序连续接收数据…(无限次)buf在哪里定义?这不是真正的代码。我能看出来,因为您发布的内容缺少一个变量声明,而且当有人注意到您很快就抛出了一个变量声明时。张贴你的实际代码。此外,如果在5-8次之后停止,请使用调试器并逐步检查代码,以了解在6-9次时发生了什么。同意。实际编译并真正代表问题的Post代码。但是……您是否需要向调制解调器断言任何流量控制信号或XON?您是否希望程序退出?听起来像是在给我读
read
。。确定您的传感器一直在生成数据?还应检查read
是否返回-1char buf[1024]。。。res=读取(fd,buf,1024);buf[res]=0代码>-->读取(fd,buf,1024-1)代码>
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