Linux 串口读数据没反应(rx和tx线短接)
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <pthread.h>
#define MODEMDEVICE "/dev/ttyS0"
#define CR 0x0D
//g++ -finput-charset=GBK -o main main.cpp
int main(int argc, char* argv[])
{
int fd,c, res;
struct termios newtio;
char buf[255];
printf("open comm:%s ",MODEMDEVICE);
fd = open(MODEMDEVICE, O_RDWR|O_NONBLOCK); // | O_NDELAY
if (fd <0)
{
perror(MODEMDEVICE);
exit(-1);
}
printf("ok\n");
printf("tcgetattr ");
if(tcgetattr(fd,&newtio) < 0)
{
perror("tcgetattr");
}
printf("ok\n");
newtio.c_cflag = B19200|CS8|CREAD|HUPCL|CRTSCTS;
newtio.c_iflag = IGNBRK|IGNPAR|0;
newtio.c_oflag &=~(INLCR|IGNCR|ICRNL);
newtio.c_oflag &=~(ONLCR|OCRNL);
newtio.c_oflag = 0;
newtio.c_lflag = 0;
memset(newtio.c_cc,0,sizeof(newtio.c_cc));
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 5;
/*No parity (8N1):*/
newtio.c_cflag &= ~CSIZE;
newtio.c_cflag |= CS8;
newtio.c_cflag &= ~PARENB;
newtio.c_iflag &= ~INPCK;
newtio.c_cflag &= ~CSTOPB;
cfsetispeed(&newtio,B19200);
cfsetospeed(&newtio,B19200);
newtio.c_iflag &= ~(IXON|IXOFF|IXANY);
tcflush(fd, TCIFLUSH);
printf("tcsetattr ");
if(tcsetattr(fd,TCSANOW,&newtio)<0)
{
perror("tcsetattr");
}
printf("ok\n");
memset(&newtio,0,sizeof(newtio));
if(tcgetattr(fd,&newtio) < 0)
{
perror("tcgetattr");
}
memset(buf,0,sizeof(buf));
sprintf(buf,"AT+CMGF=0%c",CR);
printf("write:%s\n",buf);
int n = write(fd, buf, strlen(buf));
printf("%d ok\n",n);
while(1)
{
printf("read\n");
res = read(fd,buf,255);
if(res>0){
buf[res]=0;
printf("read:%s:%d\n", buf, res);
}
else
{
printf("no data\n");
}
sleep(1);
}
}
上面是Linux下的测试代码,测试系统是RedHad 5.4 64bit
上面这段代码write没问题发送了10个字节过去,read没有读取到数据,用block进行接收,就一直堵在read这里,用no block接收,就接收到 -1
我怀疑没有真正打开串口,在window下搭建了一个虚拟机,然后在虚拟机里面运行这段代码,用AccessPort进行监控,没有收到设置串口参数的事件,也没有收到write发送的数据,非常诡异。