主题 : 适用于友善所有arm开发板的串口编程示例(Linux) 复制链接 | 浏览器收藏 | 打印
这个阶段正是我事业的上升期,我怎么能走得开呢?
级别: 精灵王
UID: 3197
精华: 3
发帖: 770
金钱: 6995 两
威望: 5398 点
贡献值: 21 点
综合积分: 1600 分
注册时间: 2008-12-30
最后登录: 2010-12-31
楼主  发表于: 2009-04-10 16:13

 适用于友善所有arm开发板的串口编程示例(Linux)

管理提醒: 本帖被 qq2440 从 micro2440技术交流专区 移动到本区(2013-11-18)
本程序摘自最新Linux示例(光盘中的\linux\exapmples.tgz解压出来可得此文件)

说明:comtest程序是友善之臂早期开发的一个串口测试程序,它其实是一个十分简易的串口终端程序,类似于linux中的minicom,该程序与硬件无关,因此相同的代码不仅适用于任何Arm-linux开发板平台,也可以在PC linux上运行使用,方法都是完全一样的。通过该程序你可以了解串口编程的一些常见关键设置,对于linux下串口编程很有帮助和借鉴意义,该程序虽然十分短小,但设计极为严谨巧妙,我们对此就不详细解释了,下面是它的完整源代码:

注:本程序版权归属友善之臂所有,任何单位或个人转载或复制均需注明出处,且不得用于商业用途。


# include <stdio.h>
# include <stdlib.h>
# include <termio.h>
# include <unistd.h>
# include <fcntl.h>
# include <getopt.h>
# include <time.h>
# include <errno.h>
# include <string.h>
static void Error(const char *Msg)
{
    fprintf (stderr, "%s\n", Msg);
    fprintf (stderr, "strerror() is %s\n", strerror(errno));
    exit(1);
}
static void Warning(const char *Msg)
{
     fprintf (stderr, "Warning: %s\n", Msg);
}

static int SerialSpeed(const char *SpeedString)
{
    int SpeedNumber = atoi(SpeedString);
#   define TestSpeed(Speed) if (SpeedNumber == Speed) return B##Speed
    TestSpeed(1200);
    TestSpeed(2400);
    TestSpeed(4800);
    TestSpeed(9600);
    TestSpeed(19200);
    TestSpeed(38400);
    TestSpeed(57600);
    TestSpeed(115200);
    TestSpeed(230400);
    Error("Bad speed");
    return -1;
}
static void PrintUsage(void)
{
   fprintf(stderr, "comtest - interactive program of comm port\n");
   fprintf(stderr, "press [ESC] 3 times to quit\n\n");
   fprintf(stderr, "Usage: comtest [-d device] [-t tty] [-s speed] [-7] [-c] [-x] [-o] [-h]\n");
   fprintf(stderr, "         -7 7 bit\n");
   fprintf(stderr, "         -x hex mode\n");
   fprintf(stderr, "         -o output to stdout too\n");
   fprintf(stderr, "         -c stdout output use color\n");
   fprintf(stderr, "         -h print this help\n");
   exit(-1);
}
static inline void WaitFdWriteable(int Fd)
{
    fd_set WriteSetFD;
    FD_ZERO(&WriteSetFD);
    FD_SET(Fd, &WriteSetFD);
    if (select(Fd + 1, NULL, &WriteSetFD, NULL, NULL) < 0) {
   Error(strerror(errno));
    }
 
}
int main(int argc, char **argv)
{
    int CommFd, TtyFd;
    struct termios TtyAttr;
    struct termios BackupTtyAttr;
    int DeviceSpeed = B115200;
    int TtySpeed = B115200;
    int ByteBits = CS8;
    const char *DeviceName = "/dev/ttyS0";
    const char *TtyName = "/dev/tty";
    int OutputHex = 0;
    int OutputToStdout = 0;
    int UseColor = 0;
    opterr = 0;
    for (;;) {
        int c = getopt(argc, argv, "d:s:t:7xoch");
        if (c == -1)
            break;
        switch(c) {
        case 'd':
            DeviceName = optarg;
            break;
        case 't':
            TtyName = optarg;
            break;
        case 's':
     if (optarg[0] == 'd') {
  DeviceSpeed = SerialSpeed(optarg + 1);
     } else if (optarg[0] == 't') {
  TtySpeed = SerialSpeed(optarg + 1);
     } else
             TtySpeed = DeviceSpeed = SerialSpeed(optarg);
            break;
 case 'o':
     OutputToStdout = 1;
     break;
 case '7':
     ByteBits = CS7;
     break;
        case 'x':
            OutputHex = 1;
            break;
 case 'c':
     UseColor = 1;
     break;
        case '?':
        case 'h':
        default:
     PrintUsage();
        }
    }
    if (optind != argc)
        PrintUsage();
    CommFd = open(DeviceName, O_RDWR, 0);
    if (CommFd < 0)
 Error("Unable to open device");
    if (fcntl(CommFd, F_SETFL, O_NONBLOCK) < 0)
      Error("Unable set to NONBLOCK mode");

    memset(&TtyAttr, 0, sizeof(struct termios));
    TtyAttr.c_iflag = IGNPAR;
    TtyAttr.c_cflag = DeviceSpeed | HUPCL | ByteBits | CREAD | CLOCAL;
    TtyAttr.c_cc[VMIN] = 1;
    if (tcsetattr(CommFd, TCSANOW, &TtyAttr) < 0)
        Warning("Unable to set comm port");
    TtyFd = open(TtyName, O_RDWR | O_NDELAY, 0);
    if (TtyFd < 0)
 Error("Unable to open tty");
    TtyAttr.c_cflag = TtySpeed | HUPCL | ByteBits | CREAD | CLOCAL;
    if (tcgetattr(TtyFd, &BackupTtyAttr) < 0)
 Error("Unable to get tty");
    if (tcsetattr(TtyFd, TCSANOW, &TtyAttr) < 0)
 Error("Unable to set tty");

    for (;;) {
 unsigned char Char = 0;
 fd_set ReadSetFD;
 void OutputStdChar(FILE *File) {
     char Buffer[10];
     int Len = sprintf(Buffer, OutputHex ? "%.2X  " : "%c", Char);
     fwrite(Buffer, 1, Len, File);
 }
 FD_ZERO(&ReadSetFD);
 FD_SET(CommFd, &ReadSetFD);
 FD_SET( TtyFd, &ReadSetFD);
# define max(x,y) ( ((x) >= (y)) ? (x) : (y) )
 if (select(max(CommFd, TtyFd) + 1, &ReadSetFD, NULL, NULL, NULL) < 0) {
     Error(strerror(errno));
 }
# undef max
 if (FD_ISSET(CommFd, &ReadSetFD)) {
     while (read(CommFd, &Char, 1) == 1) {
  WaitFdWriteable(TtyFd);
  if (write(TtyFd, &Char, 1) < 0) {
        Error(strerror(errno));
  }
  if (OutputToStdout) {
      if (UseColor)
   fwrite("\x1b[01;34m", 1, 8, stdout);
      OutputStdChar(stdout);
      if (UseColor)
   fwrite("\x1b[00m", 1, 8, stdout);
      fflush(stdout);
  }
     }
 }
 if (FD_ISSET(TtyFd, &ReadSetFD)) {
     while (read(TtyFd, &Char, 1) == 1) {
         static int EscKeyCount = 0;
  WaitFdWriteable(CommFd);
         if (write(CommFd, &Char, 1) < 0) {
        Error(strerror(errno));
  }
  if (OutputToStdout) {
      if (UseColor)
   fwrite("\x1b[01;31m", 1, 8, stderr);
      OutputStdChar(stderr);
      if (UseColor)
   fwrite("\x1b[00m", 1, 8, stderr);
      fflush(stderr);
         }
        if (Char == '\x1b') {
                    EscKeyCount ++;
                    if (EscKeyCount >= 3)
                        goto ExitLabel;
                } else
                    EscKeyCount = 0;
     }
        }
    }
ExitLabel:
    if (tcsetattr(TtyFd, TCSANOW, &BackupTtyAttr) < 0)
 Error("Unable to set tty");
    return 0;
}


编译脚本:

在arm平台上:
本脚本适用于最新编译器arm-linux-gcc-4.3.2 with  EABI
#!/bin/bash
arm-linux-gcc -Wall -O3 -o armcomtest com_test.c
arm-linux-strip --strip-all armcomtest
编译可得到armcomtest执行程序(所有友善的开发板均已经包含此执行程序)
使用其他编译器,可以这样:
arm-linux-gcc -o armcomtest com_test.c


在x86平台:
gcc -o comtest com_test.c
可以编译出comtest程序,它相当于一个微型的minicom

该程序运行后的退出方式:连续按三次"ESC"按键(就是你的PC键盘)



级别: 新手上路
UID: 3843
精华: 0
发帖: 3
金钱: 30 两
威望: 30 点
贡献值: 0 点
综合积分: 6 分
注册时间: 2009-02-12
最后登录: 2009-05-04
1楼  发表于: 2009-04-26 19:15
可以给些详细点的代码注释吗?因为我初学的,看到晕了~~
级别: 侠客
UID: 9105
精华: 0
发帖: 95
金钱: 755 两
威望: 307 点
贡献值: 0 点
综合积分: 190 分
注册时间: 2009-09-17
最后登录: 2017-09-13
2楼  发表于: 2009-09-30 19:56
看不懂
级别: 侠客
UID: 26755
精华: 0
发帖: 101
金钱: 505 两
威望: 101 点
贡献值: 0 点
综合积分: 202 分
注册时间: 2010-08-13
最后登录: 2017-09-13
3楼  发表于: 2010-08-20 23:11
得试试我的串口程序
级别: 新手上路
UID: 32711
精华: 0
发帖: 1
金钱: 5 两
威望: 1 点
贡献值: 0 点
综合积分: 2 分
注册时间: 2010-11-19
最后登录: 2011-04-11
4楼  发表于: 2010-11-22 01:25
得到comtest和 x86comtest两个文件后,一个在linux下运行,一个在开发板?
执行的时候为什么一点反应都 没呢