23,121
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#define BAUDRATE B115200
#define MODEMDEVICE "/dev/ttyS3"
int main()
{
int fd,c=0,res,i;// i 是循环变量
struct termios oldtio,newtio;
char buf[256];
printf("start ...\n");
fd = open(MODEMDEVICE,O_RDWR|O_NOCTTY); // 打开pc的com2端口
if(fd<0)
{
printf("flag1 ...\n");
perror(MODEMDEVICE);
printf("flag2...\n");
exit(1);
}
printf("open...\n");
tcgetattr(fd,&oldtio);//将目前终端机参数保存至oldtio
bzero(&newtio,sizeof(newtio));//清楚newtio
newtio.c_cflag = BAUDRATE|CS8|CLOCAL|CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = ICANON;//设置为正规模式
tcflush(fd,TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);//新的term iOS作为通信端口参数
printf("reading...\n");
//while(1)
//{
res = read(fd,buf,80);
printf("res=%d\n",res); //查看res返回值
perror("read:\n"); //打印错误信息
buf[res] = '\0';
for(i=0;i<res;i++)
{
printf("num %d ,the data is %d\n",i,buf[i]);
}
//}
printf("colse...\n");
close(fd);
tcsetattr(fd,TCSANOW,&oldtio);//恢复旧端口参数
return 0;
}