返回信息流想要主机跟底下板子通过串口通信。主机的串口程序在linux下用c实现。
1.板子上的串口通过串口调试工具查看是没问题的。
2.在linux下面编程调试,板子发送了数据程序不能立即收到。当板子发了一段时间数据后重开一接收程序则会收到很多数据,如果此时再运行原程序则能正常收发。
4.麻烦高手帮忙解决下。是不是因为串口在初始化的时候有握手信息呢?
3.其中相关代码如下:
int open_serial(int k)
{
int fd;
if(k==0)
{
fd = open("/dev/ttyS0",O_RDWR|O_NOCTTY);
perror("open /dev/ttyS0");
}
else
{
fd = open("/dev/ttyS1",O_RDWR|O_NOCTTY);
perror("open /dev/ttyS1");
}
if(fd == -1)
return -1;
else
return fd;
}
void init_ttyS(int fd)
{
struct termios options;
bzero(&options,sizeof(options));//clean old setting
/*set baud rate*/
tcgetattr(fd,&options);
cfsetispeed(&options,B9600);
cfsetospeed(&options,B9600);
tcsetattr(fd,TCSANOW,&options);
/*set flags*/
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= ~CS8;
/*set raw mode*/
options.c_lflag &= ~(ICANON | ECHO| ECHOE |ISIG);//input
options.c_oflag &= ~OPOST;//output
tcflush(fd,TCIFLUSH);
}
int main()
{
int len;
BYTE a[1024];
if((fd=open_serial(0))==-1)
perror("open tty error");
init_ttyS(fd);
while(1)
{
len=read(fd,a,1024);
printf("%d\n",len);
}
return 0;
}
这是一条镜像帖。来源:北邮人论坛 / cpp / #17614同步于 2008/12/16
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖
【求助】串口通信问题
dolphin
2008/12/16镜像同步2 回复
订阅后,新回复会通过你的通知中心匿名送达。
2 条回复
【 在 dolphin (小鱼@花花) 的大作中提到: 】
: 标 题: 【求助】串口通信问题
: 发信站: 北邮人论坛 (Tue Dec 16 22:15:05 2008), 站内
:
: 想要主机跟底下板子通过串口通信。主机的串口程序在linux下用c实现。
: 1.板子上的串口通过串口调试工具查看是没问题的。
: 2.在linux下面编程调试,板子发送了数据程序不能立即收到。当板子发了一段时间数据后重开一接收程序则会收到很多数据,如果此时再运行原程序则能正常收发。
: 4.麻烦高手帮忙解决下。是不是因为串口在初始化的时候有握手信息呢?
: 3.其中相关代码如下:
: int open_serial(int k)
: {
: int fd;
: if(k==0)
: {
: fd = open("/dev/ttyS0",O_RDWR|O_NOCTTY);
: perror("open /dev/ttyS0");
: }
: else
: {
: fd = open("/dev/ttyS1",O_RDWR|O_NOCTTY);
: perror("open /dev/ttyS1");
: }
: if(fd == -1)
: return -1;
: else
: return fd;
: }
: void init_ttyS(int fd)
: {
: struct termios options;
: bzero(&options,sizeof(options));//clean old setting
:
: /*set baud rate*/
: tcgetattr(fd,&options);
: cfsetispeed(&options,B9600);
: cfsetospeed(&options,B9600);
: tcsetattr(fd,TCSANOW,&options);
你在这个地方设置只是设置了串口的波特率而已,后面设置的奇偶校验和数据位并没有效吧,把设置拿到后面.
: /*set flags*/
: options.c_cflag &= ~PARENB;
: options.c_cflag &= ~CSTOPB;
: options.c_cflag &= ~CSIZE;
: options.c_cflag |= ~CS8;
: /*set raw mode*/
: options.c_lflag &= ~(ICANON | ECHO| ECHOE |ISIG);//input
: options.c_oflag &= ~OPOST;//output
这里最好加上 options.c_cflag |=(CLOCAL | CREAD);
分别是非控制模式和使能接受
: tcflush(fd,TCIFLUSH);
: }
: int main()
: {
: int len;
: BYTE a[1024];
:
: if((fd=open_serial(0))==-1)
: perror("open tty error");
: init_ttyS(fd);
: while(1)
: {
: len=read(fd,a,1024);
~~~~~~~~~~~~~~~~~~~~~~~
接受这么大的数据最好不要直接这样子read,可以用一个while循环来读,或者用ioctl查询一下.
: printf("%d\n",len);
: }
: return 0;
: }
:
:
: --
:
: ※ 来源:·北邮人论坛 http://forum.byr.edu.cn·[FROM: 59.64.136.*]