80,350
社区成员
发帖
与我相关
我的任务
分享
int nCount, nTotal, i;
struct termios oldtio, newtio;
char *dev ="/dev/ttyGS2";
if ((fd = open(dev, O_RDWR | O_NOCTTY))<0)
{
printf("err: can't open serial port!\n");
return -1;
}
tcgetattr(fd, &oldtio); /* save current serial port settings */
setTermios(&newtio, B115200);
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &newtio);
write(fd, "AT+CGMI\n", 8);
//nCount=write(fd, argv[2], strlen(argv[2]));
printf("send data\n");
sleep(1);
tcsetattr(fd, TCSANOW, &oldtio);
close(fd);
return 0;
接收:
fd = open("/dev/ttyGS2", O_RDWR);
if (fd == -1)
return -1;
printf("hello, Serial port is OK\n");
// 读取串口当前属性
tcgetattr(fd, &attr);
// 设置最少接收字符个数为0
attr.c_cc[VMIN] = 0;
// 不处理iflag、oflag和lflag
attr.c_iflag = 0;
attr.c_oflag = 0;
attr.c_lflag = 0;
// 设置波特率为9600,字符长度为8位,偶校验,允许接收
attr.c_cflag = B115200 | CS8 | CREAD;
// 设置串口属性
tcsetattr(fd, TCSANOW, &attr);
//write(fd, "AT+CGMI", 8);
// 清除监测集合
FD_ZERO(&fds);
// 将串口句柄加入到监测集合中
FD_SET(fd, &fds);
// 设置超时为5秒
tv.tv_sec = 5;
tv.tv_usec = 0;
// 监测串口是否有数据接收到,超时为5秒
if (select(fd+1, &fds, NULL, NULL, &tv) <= 0)
{
printf("receive null!!\n");
return -1;
}
// 接收最多100个字符
nread=read(fd, buf, 512);
printf("readlength=%d\n", nread);
buf[nread]='\0';
printf("%s\n", buf);
// 关闭串口
close(fd);
return 0;