Chinaunix首页 | 论坛 | 博客
  • 博客访问: 47023
  • 博文数量: 17
  • 博客积分: 425
  • 博客等级: 下士
  • 技术积分: 152
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-04 23:37
文章分类

全部博文(17)

文章存档

2011年(17)

分类: LINUX

2011-07-19 09:50:20

串口操作需要的头文件

#include /*标准输入输出定义*/

#include /*标准函数库定义*/

#include /*Unix 标准函数定义*/

#include

#include

#include /*文件控制定义*/

#include /*PPSIX 终端控制定义*/

#include /*错误号定义*/

在 Linux 下串口文件是位于 /dev 下的

串口一 为 /dev/ttyS0

串口二 为 /dev/ttyS1

打开串口是通过使用标准的文件打开函数操作:

int fd;

/*以读写方式打开串口*/

fd = open( "/dev/ttyS0", O_RDWR);

if (-1 == fd){

/* 不能打开串口一*/

perror(" 提示错误!");

}

最基本的设置串口包括波特率设置,效验位和停止位设置。

串口的设置主要是设置 struct termios 结构体的各成员值。

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 */

};

设置这个结构体很复杂,我这里就只说说常见的一些设置:

波特率设置

下面是修改波特率的代码:

struct termios Opt;

tcgetattr(fd, &Opt);

cfsetispeed(&Opt,B19200); /*设置为19200Bps*/

cfsetospeed(&Opt,B19200);

tcsetattr(fd,TCANOW,&Opt);

设置波特率的例子函数:

/**

*@brief 设置串口通信速率

*@param fd 类型 int 打开串口的文件句柄

*@param speed 类型 int 串口速度

*@return void

*/

int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,

B38400, B19200, B9600, B4800, B2400, B1200, B300, };

int name_arr[] = {38400, 19200, 9600, 4800, 2400, 1200, 300, 38400,

19200, 9600, 4800, 2400, 1200, 300, };

void set_speed(int fd, int speed){

int i;

int status;

struct termios Opt;

tcgetattr(fd, &Opt);

for ( i= 0; i < sizeof(speed_arr) / sizeof(int); i++) {

if (speed == name_arr[i]) {

tcflush(fd, TCIOFLUSH);

cfsetispeed(&Opt, speed_arr[i]);

cfsetospeed(&Opt, speed_arr[i]);

status = tcsetattr(fd1, TCSANOW, &Opt);

if (status != 0) {

perror("tcsetattr fd1");

return;

}

tcflush(fd,TCIOFLUSH);

}

}

}

原文地址:http://www.51testing.com/?uid-238554-action-spacelist-type-blog-page-1

阅读(579) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~