首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

Linux下串口遇到的有关问题

2012-05-03 
Linux下串口遇到的问题#include stdio.h#include stdlib.h#include unistd.h#include sys/types.h

Linux下串口遇到的问题
#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 <string.h>
#include <sys/ioctl.h>

int comfd,msglen;
char *dev = "/dev/ttyS0";
struct termios comterm;
#define BUFFERSIZE 64
char combuf[BUFFERSIZE];

int main(int argc, char* argv[])
{

//comfd = open( "/dev/ttyS0", O_RDWR);//打开串口

if((comfd = open(dev,O_RDWR|O_NOCTTY|O_NDELAY)) < 0)
{
printf("Can't open serial port!\n");
return -1;
}

//comterm
tcgetattr(comfd,&comterm);
bzero(&comterm,sizeof(struct termios));

comterm.c_cflag |= CLOCAL|CREAD;
comterm.c_cflag &= ~CSIZE; 
comterm.c_cflag |= CS8;
comterm.c_cflag &= ~PARENB;
comterm.c_cflag &=CSTOPB;
comterm.c_cc[VTIME] = 0;
comterm.c_cc[VMIN] = 0;



fcntl(comfd, F_SETFL, FNDELAY);//设置串口为非阻塞

tcflush(comfd,TCIOFLUSH);//清除输入、输出缓冲区

tcsetattr(comfd,TCSANOW,&comterm);//激活生效
cfsetispeed(&comterm,B9600);
cfsetospeed(&comterm,B9600);

int length = 0;
//
while(1)
{
//memset(combuf,'\0',sizeof(combuf));
length = strlen("AB01BA10");
printf("Write data size %d Data is %s\n",sizeof(combuf),combuf);
if(write(comfd,"AB01BA10",length) < 0)
{
printf("Send Failed!\n");
}
printf("Send Data!\n");
sleep(1);
printf("\n");

memset(combuf,'\0',sizeof(combuf));
printf("Receive Data ");
msglen = 0;
ioctl(comfd,FIONREAD,&msglen);
if (msglen>0)
{
msglen = read(comfd,combuf,msglen);
combuf[msglen]=0;
printf(combuf);
printf("\n");
}
else
{
printf("Receive Failed\n");
}
printf("\n\n");
sleep(2);
}
close(comfd);
return 0;
}

程序在Fedora下能编译通过,运行也是正常的,但与windows上的串口调试工具没法交互数据……
串口调试工具设置为:波特率:9600,校验位NONE,数据位8,停止位1
用各种进制数据试都没法通信,还望请教各位高手……

[解决办法]
在linux下可用的话,在windows下没道理不好用。
[解决办法]
LZ关注一下硬件流控, 看看是不是两头设置的不宜样。 另外 XON/XOFF也需要注意下。

热点排行