Linux下串口编程
时间:2010-08-27 来源:小明的技术博客
老板让我研究一下UPS的控制,貌似在Linux下面没有相应的监控软件,UPS和电脑通信时候使用的是串口(RS232),所以先对Linux串口编程了解一下。
因为只是设计串口传输数据,而不需要串口来处理,那么使用原始模式(Raw Mode)方式来通讯。
串口操作需要的头文件:
#include <stdio.h> /*标准输入输出定义*/ #include <stdlib.h> /*标准函数库定义*/ #include <unistd.h> /*Unix 标准函数定义*/ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> /*文件控制定义*/ #include <termios.h> /*PPSIX 终端控制定义*/ #include <errno.h> /*错误号定义*/
首先需要打开串口
在 Linux 下串口文件是位于 /dev 下的
串口一 为 /dev/ttyS0
串口二 为 /dev/ttyS1
打开串口是通过使用标准的文件打开函数操作:
int fd; /*以读写方式打开串口*/ fd = open( "/dev/ttyS0", O_RDWR); if (-1 == fd){ /* 不能打开串口一*/ perror(" 打开错误!"); }
然后对串口设置
串口设置设计的结构体如下:
struct termio { unsigned short c_iflag; /* 输入模式标志 */ unsigned short c_oflag; /* 输出模式标志 */ unsigned short c_cflag; /* 控制模式标志*/ unsigned short c_lflag; /* local mode flags */ unsigned char c_line; /* line discipline */ unsigned char c_cc[NCC]; /* control characters */ };
这里仅对常用的设置进行介绍:
1.波特率设置:
struct termios Opt; tcgetattr(fd, &Opt); tcflush(fd,TCIFLUSH); cfsetispeed(&Opt,B19200); /*设置为19200Bps*/ cfsetospeed(&Opt,B19200);
2.校验位和停止位设置
常用的一般是8N0
Opt.c_cflag |= CS8; //设置数据位 Opt.c_cflag &= ~PARENB; Opt.c_oflag &= ~(OPOST); Opt.c_cflag &= ~CSTOPB; Opt.c_lflag &= ~(ICANON|ISIG|ECHO|IEXTEN); Opt.c_iflag &= ~(INPCK|BRKINT|ICRNL|ISTRIP|IXON);
Opt.c_cc[VMIN] = 0; Opt.c_cc[VTIME] = 0;
3.写入配置
if (tcsetattr(fd,TCSANOW,&Opt) != 0) //装载初始化参数 { perror("SetupSerial!\n"); close(fd); return -1; }
测试串口
char buf[20]; for(;;) { len = write(fd, buf, 1); //写串口 if(len > 0) { read(fd, buf, sizeof(buf)); //读串口数据 printf("buf %s\n", buf); //输出读到的数据 } usleep(100000); }
参考资料:
http://www.ibm.com/developerworks/cn/linux/l-serials/index.html
http://opengroup.org/onlinepubs/007908775/xsh/termios.h.html
http://hi.baidu.com/zy6666/blog/item/998da20e2c4634eb37d1220d.html
相关阅读 更多 +
排行榜 更多 +