Linux 串口读数据没反应(rx和tx线短接)

happymgp4 2011-10-20 02:41:57
#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发送的数据,非常诡异。
...全文
791 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
happymgp 2011-10-24
  • 打赏
  • 举报
回复
xen程序占了/dev/ttyS0端口


也就是Xen把ttyS0占用了。

修改/etc/grub.conf文件
#boot=/dev/sda
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title Red Hat Enterprise Linux Server (2.6.18-53.el5xen)
root (hd0,0)
kernel /xen.gz-2.6.18-53.el5
module /vmlinuz-2.6.18-53.el5xen ro root=LABEL=/ rhgb quiet xencons=off
module /initrd-2.6.18-8.el5xen.img

保存后重启!
#dmesg |grep tty

显示:serial8250:ttyS0 at I/O Ox3f8 (irq=0) is a 16550A
happymgp4 2011-10-24
  • 打赏
  • 举报
回复
没人回复,只能自己结贴了

23,118

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧