linux下串口驱动测试程序

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

linux下串口驱动测试程序

2009-12-26 20:42:20| 分类:技术| 标签:|字号大中小订阅

【转载时请注明文章出处:】

为了测试串口驱动,我们需要用串口驱动测试程序先向串口写入数据,然后再从串口读出来,以证明串口驱动的正确性。下面我们来分析一下串口驱动测试

程序的流程。

1、串口程序需要的头文件

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

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

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

#include

#include

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

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

#include /*错误号定义*/

2、打开串口设备fd = open( "/dev/ttyS0", O_RDWR); 我们以/dev/ttyS0即

一般机子上的COM1为例。

3、设置串口设备:

串口设备的设置主要通过struct termio的结构体来完成:

struct termio

{ unsigned short c_iflag; /* 输入模式标志 */

unsigned short c_oflag; /* 输出模式标志 */

unsigned short c_cflag; /* 控制模式标志*/

unsigned short c_lflag; /* 当前模式标志 */

unsigned char c_line; /* line discipline */

unsigned char c_cc[NCC]; /* 控制字 */

};

我们用下面函数实现具体的串口设置:

int setup_port(int fd, int baud, int databits, int parity, int stopbits)

{

struct termio term_attr;

if (ioctl(fd, TCGETA, &term_attr) < 0) { //将fd所对应的终端信息存入

termio结构,得到当前配置

return -1;

}

memcpy(&oterm_attr, &term_attr, sizeof(struct termio)); //保持当前配置

到oterm_attr,用于系统恢复

term_attr.c_iflag &= ~(INLCR | IGNCR | ICRNL | ISTRIP);

term_attr.c_oflag &= ~(OPOST | ONLCR | OCRNL);

term_attr.c_lflag &= ~(ISIG | ECHO | ICANON | NOFLSH);

term_attr.c_cflag &= ~CBAUD;

term_attr.c_cflag |= CREAD | speed_to_flag(baud); //设置波特率

/

/标志各种标志可选范围

term_attr.c_cflag &= ~(CSIZE); //设置数据位长度

switch (databits) {

case 5:

term_attr.c_cflag |= CS5; //设置数据位长度为5,下同

break;

case 6:

term_attr.c_cflag |= CS6;

break;

case 7:

term_attr.c_cflag |= CS7;

break;

case 8:

default:

term_attr.c_cflag |= CS8;

break;

}

switch (parity) { //设置奇偶校验位

case 1:

term_attr.c_cflag |= (PARENB | PARODD); //奇校验

break;

case 2:

term_attr.c_cflag |= PARENB; //偶校验

term_attr.c_cflag &= ~(PARODD);

break;

case 0:

default:

term_attr.c_cflag &= ~(PARENB); //不校验

break;

}

switch (stopbits) { //设置停止位

case 2: //有停止位为两位,下同

term_attr.c_cflag |= CSTOPB;

break;

case 1:

default:

term_attr.c_cflag &= ~CSTOPB;

break;

}

term_attr.c_cc[VMIN] = 1; //更新设置,并且立即完成

term_attr.c_cc[VTIME] = 0; //设置超时

if (ioctl(fd, TCSETAW, &term_attr) < 0) { //将更改后的属性加载到设

备中

return -1;

}

if (ioctl(fd, TCFLSH, 2) < 0) { //将输入输出队列全部发出,

清空串口中队列

return -1;

}

return 0;

}

4、向串口写入数据:

while ( (len = read(0, buf, MAX_BUF_SIZE)) > 0 ) { if (len == 1) { //如果当前缓冲区为空,则写入停止

位,发送

buf[0] = MY_END_CHAR;

buf[1] = 0;

write_data(fd, buf, len);

break;

}

i = write_data(fd, buf, len); //发送缓冲区内容

if (i == 0) {

fprintf(stderr, "Send data error!\n");

break;

}

}

5、从串口读数据:

len = MAX_BUF_SIZE;

while (1) {

i = read_data(fd, buf, len); //从串口读取数据

if (i > 0) {

//count += i;

//fprintf(stderr, "Recv %d byte\n", i);

相关文档
最新文档