walnutcy

ubuntu 串口通信 应用编程

0
阅读(6057)

没找到ubuntu下用的图形串口工具,装一个minicom,使用不太习惯。
就顺便找了下串口编程相关的。
主要参考文档:http://www.ibm.com/developerworks/cn/linux/l-serials/index.html

串口操作需要的头文件

#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 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);


在原文中,作者提供了代码下载,http://www.ibm.com/developerworks/cn/linux/l-serials/main.c

直接编译的话,需要自己定义FALSE, TRUE。
#define FALSE 0
#define TRUE  1


我编译后实测,是可以用的,后期主要考虑看有没有办法集成一个界面,
没做过linux下的界面编程,有空了尝试下。