linux平台下的串口程序网上比比皆是,这里是自己参考资料写的。

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <fcntl.h>#include <termios.h>#include "debug-msg.h"/** if you have a usb serial converter, specify it to 1 */#define USB_SERIAL 0/** * open_port - Open a serial port * * @param port : The port number, eg, open_port(1) will open com1 * * @return Return fd if success, otherwise will return -1 with some msg. */int open_port(int port){ int fd = -1; /* File descriptor for the port, we return it. */ int ret; char device[13] = {0}; /* ??? sizeof("/dev/ttyUSB0")=12 */ if (port < 1 || port > 4) error_ret("Sorry, the port number must be 1~4."); if (USB_SERIAL) sprintf(device, "/dev/ttyUSB%d", port-1); else sprintf(device, "/dev/ttyS%d", port-1); //printf("%s %d/n", device, sizeof(device)); fd = open(device, O_RDWR | O_NOCTTY | O_NDELAY); if (fd == -1) unix_error_ret("Unable to open the port"); /* block */ ret = fcntl(fd, F_SETFL, 0); if (ret < 0) unix_error_ret("fcntl"); ret = isatty(STDIN_FILENO); if (ret == 0) error_ret("Standard input is not a terminal device."); debug_msg("Open the port success!/n"); return fd;}/** * close_port - Close the port * * @param fd : The file description returned by open_port(). * * @return Return 0 if success, return -1 with some msg if error happens. */int close_port(int fd){ if(close(fd) < 0) unix_error_ret("Unable to close the port."); debug_msg("Close the port success!/n"); return 0;}/** * setup_port - Configure the port, eg. baud rate, data bits,etc. * * @param fd : The serial port * @param speed : The baud rate * @param data_bits : The data bits * @param parity : The parity bits * @param stop_bits : The stop bits * * @return Return 0 if everything is OK, otherwise -1 with some error msg. */int setup_port(int fd, int speed, int data_bits, int parity, int stop_bits){ int speed_arr[] = {B115200, B9600, B38400, B19200, B4800}; int name_arr[] = {115200, 9600, 38400, 19200, 4800}; struct termios opt; int ret=-1; int i=0; int len=0; ret = tcgetattr(fd, &opt); /* get the port attr */ if (ret < 0) unix_error_ret("Unable to get the attribute"); opt.c_cflag |= (CLOCAL | CREAD); /* enable the receiver, set local mode */ opt.c_cflag &= ~CSIZE; /* mask the character size bits*/ /* baud rate */ len = sizeof(speed_arr) / sizeof(int); for (i = 0; i < len; i++) { if (speed == name_arr[i]) { cfsetispeed(&opt, speed_arr[i]); cfsetospeed(&opt, speed_arr[i]); } if (i == len) error_ret("Unsupported baud rate."); } /* data bits */ switch (data_bits) { case 8: opt.c_cflag |= CS8; break; case 7: opt.c_cflag |= CS7; break; default: error_ret("Unsupported data bits."); } /* parity bits */ switch (parity) { case 'N': case 'n': opt.c_cflag &= ~PARENB; opt.c_cflag &= ~INPCK; /* ?? */ break; case 'O': case 'o': opt.c_cflag|=(INPCK|ISTRIP); /*enable parity check, strip parity bits*/ opt.c_cflag |= (PARODD | PARENB); break; case 'E': case 'e': opt.c_cflag|=(INPCK|ISTRIP); /*enable parity check, strip parity bits*/ opt.c_cflag |= PARENB; opt.c_cflag &= ~PARODD; break; default: error_ret("Unsupported parity bits."); } /* stop bits */ switch (stop_bits) { case 1: opt.c_cflag &= ~CSTOPB; break; case 2: opt.c_cflag |= CSTOPB; break; default: error_ret("Unsupported stop bits."); } /* raw input */ opt.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); /* raw ouput */ opt.c_oflag &= ~OPOST; tcflush(fd, TCIFLUSH); opt.c_cc[VTIME] = 0; /* time out */ opt.c_cc[VMIN] = 0; /* minimum number of characters to read */ ret = tcsetattr(fd, TCSANOW, &opt); /* update it now */ if (ret < 0) unix_error_ret("Unable to setup the port."); debug_msg("Setup the port OK!/n"); return 0; /* everything is OK! */}</termios.h></fcntl.h></unistd.h></string.h></stdlib.h></stdio.h>

测试函数如下:

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <unistd.h>#include <pthread.h>#include <signal.h>#include "debug-msg.h"#include "serialport.h"pthread_t write_tid; /**< write thread */pthread_t read_tid; /**< read thread */char *buf = "Are you going to die? "; /**< The data we write to the port. *//** data we receive */char tmp[512];/** * write_port_thread - A thread that write data to the port * * @param argc : Here means the port(specified by the fd). * * @note * This is only a test, not the @e really one. */void *write_port_thread(void *argc){ int ret; int fd; int i = 3; fd = (int)argc; //while (i--) while (1) { debug_msg("writing... "); ret = write(fd, buf, strlen(buf)); if (ret < 0) pthread_exit(NULL); write(fd, "/r/n", 2); debug_msg("write: %d/n", ret); sleep(1); } pthread_exit(NULL);}/** * read_port_thread - Thread that read data from the port * * @param argc : Here means the port(specified by the fd). * * @note * This function has not tested yet. */void *read_port_thread(void *argc){ int num; int ret; int fd; fd = (int)argc; while ((num = read(fd, tmp, 512)) > 0) { debug_msg("read: %d/n", num); tmp[num+1] = '/0'; printf("%s/n", tmp); } if (ret < 0) pthread_exit(NULL); debug_msg("read: %d/n", ret); pthread_exit(NULL);}/** * sig_handle - Handle the INT signal. * * @param sig_num : The signal. * @note * This function is not used. */void sig_handle(int sig_num){ debug_msg("catch signal %d/n", sig_num); exit(0);}int main(void){ int fd; int ret; //signal(SIGINT, sig_handle); fd = open_port(1); /* open the port(com1) */ if (fd < 0) exit(0); ret = setup_port(fd, 115200, 8, 'N', 1); if (ret<0) exit="" ret="pthread_create(&write_tid," null="" write_port_thread="" if="" 0="" unix_error_exit="" write="" thread="" error="" 0="" ret="pthread_create(&read_tid," null="" read_port_thread="" if="" 0="" unix_error_exit="" read="" thread="" error="" pthread_join="" null="" null="" close_port="" return="" 0=""> </0)></signal.h></pthread.h></unistd.h></string.h></stdlib.h></stdio.h>

另外那个头文件是我经常使用的,现在还在不断更新、修改中,也放到这里吧:

#ifndef _DEBUG_MSG_H#define _DEBUG_MSG_H#include <stdio.h> /* perror() */#include <string.h> /* strerror() */#include <errno.h> /* errno *//*** * Print the error msg is one thing * but print the msg is another!! *//** * @def error_exit * @brief A macro that prints the @a error msg and exit. */#define error_exit(error) / do{ / fprintf(stderr, "%s/n", error); / exit(0); / } while(0)/** * @def error_ret * @brief A macro that prints the @a error msg and return -1. */#define error_ret(error) / do{ / fprintf(stderr, "%s/n", error); / return -1; / } while(0)/** * @def unix_error_exit * @brief A macro that prints the @a error msg(with errno) and then exit. * I put 'unix' before the 'function' name because I am using 'errno'. */#define unix_error_exit(error) / do{ / fprintf(stderr, "%s Info[%d]:%s/n", / error, errno, strerror(errno)); / exit(1); / } while(0)/** * @def unix_error_ret * @brief A macro that prints the @a error msg(with errno) and then return -1. * I put 'unix' before the 'function' name because I am using 'errno'. */#define unix_error_ret(error) / do{ / fprintf(stderr, "%s Info[%d]:%s/n", / error, errno, strerror(errno)); / return -1; / } while(0)/* error handle ,detail version *//* it can show the file,function and the line *//** * @def unix_print_error * @brief A macro that prints the @a error msg(with errno) and then exit. * I put 'unix' before the 'function' name because I am using 'errno'. * This error handle(detail version) can show the @p file, @p function * and @p line where the @a error happens. * @note I do not often use this 'function' in my program. */#define unix_print_error(error) / do { / fprintf(stderr, "Oh God!/nFile:%s Line:%d Function:%s:/n", / __FILE__, __LINE__, __func__); / perror(error); / exit(0); / } while(0)/* DEBUG=0 will show nothing */#ifndef DEBUG#define DEBUG 1 /**< we debug all the time */#endif/** * @def debug_msg * @brief A macro that prints the debug msg, as the same with @a printf. * */#if DEBUG > 0#define debug_msg(fmt, ...) / fprintf(stdout, fmt, ##__VA_ARGS__)#else#define debug_msg(fmt,...)#endif /* DEBUG */#ifndef TRACE#define TRACE 1 /**< we trace all the time */#endif/** * @def debug_trace * @brief A macro that traces the @p file, @p function and @p line. * */#if TRACE > 0#define debug_trace(trace) / fprintf(stdout, "%s File:%s Line:%d Func:%s./n", / trace, __FILE__, __LINE__, __func__)#else#define debug_trace(trace)#endif#endif /* _DEBUG_MSG_H */</errno.h></string.h></stdio.h>

测试如下:

虚拟机fc9,使用物理串口(可以在vm中设置的),在tty1上运行该程序,在tty2上运行minicom,短接串口线2、3脚,可以看到在minicom中输出了程序发送的字符串。实际环境中没有测试,因为开发板上只有一个串口。

也可以参考这篇文章:http://www.latelee.org/programming-under-linux/90-serialport-programming.html

完整代码下载地址:serialport-latelee.org.tar.bz2

(如不能下载,请到http://www.latelee.org/programming-under-linux/90-serialport-programming.html页面下载,支持原创,从你做起。)

木草山人

linux下串口程序测试相关推荐

  1. 解决Windows下Arm下Linux下Qt4程序的中文乱码问题

    解决Windows下Arm下Linux下Qt4程序的中文乱码问题 ################################################################### ...

  2. linux设备驱动,tty串口编程 如何查看linux下串口是否可用?串口名称等

    如何查看linux下串口是否可用?串口名称等? http://zhidao.baidu.com/question/419148559.html 查看串口是否可用,可以对串口发送数据比如对com1口,e ...

  3. Linux 下串口编程(C++ 程序设计)

    串口通信是最简单的通信方式.即使在USB 非常流行的今天,依然保留了串行通信的方式.网络上已经有大量关于Linux下 C++ 串口编程的文章,但是我依然要写这篇博文.因为网络上的资料不是内容太多,就是 ...

  4. Linux下串口调试及使用shell编程接收数据

    串口简介 串行口是计算机一种常用的接口,具有连接线少,通讯简单,得到广泛的使用.常用的串口是 RS-232-C 接口(又称 EIA RS-232-C)它是在 1970 年由美国电子工业协会(EIA)联 ...

  5. ZedBoard--(5)嵌入式Linux下的DMA测试(Direct Register Mode)(PS + PL)

    ZedBorad–(5)嵌入式Linux下的DMA测试(PS+PL) 本文将详细介绍如何在ZedBorad上使用AXI接口的DMA IP核.(文末会给出测试代码的下载链接) DDR控制器.AXI DM ...

  6. Linux下使用Speedtest测试网速教程

    Linux下使用Speedtest测试网速教程 文章目录: 一.通过Speedtest官网直接测试网络速度 二.通过下载源码,在命令行中测试网速 1.下载安装 2.Speedtest的参数使用: 有时 ...

  7. linux实验串行端口程序设计,Linux下串口编程心得(转)

    最近一段时间,需要完成项目中关于Linux下使用串口的一个部分,现在开帖记录过程点滴. 项目的要求是这样的,Qt应用程序主要完成数据采集和发送功能,一开始在google中海搜关键字"Qt串口 ...

  8. 性能测试入门(六)windows及Linux下做压力测试的注册表设置

    windows及Linux下做压力测试的注册表设置 from: http://www.cnblogs.com/tianzhiliang/articles/2400176.html TcpTimedWa ...

  9. read接收不全linux,linux下串口读写有关问题 read 一次读不全(5)

    当前位置:我的异常网» Linux/Unix » linux下串口读写有关问题 read 一次读不全 linux下串口读写有关问题 read 一次读不全(5) www.myexceptions.net ...

最新文章

  1. 模组使用之NB-IoT模组的工作模式、PSM、DRX和eDRX状态说明
  2. golang copy函数
  3. 聊聊Java中的并发队列中 有界队列和无界队列的区别
  4. python综合学习七之TensorFlow初识
  5. 获取客户端浏览器信息
  6. 最短路径问题(信息学奥赛一本通-T1342)
  7. PHP获取input中的值相同报错,laravel单元测试之phpUnit中old()函数报错解决_php实例...
  8. HDU - 1286 找新朋友(欧拉函数)解题
  9. C++读取和写入文件(fstream等)
  10. Python新闻网站项目-7.Django内容后台管理系统管理开发
  11. 深度学习模型加速方法
  12. UE4 虚幻引擎 Metahuman怎么导入到项目中
  13. 简单的木马编写之服务端篇
  14. YouTube上的版权保护
  15. 前端基础总结--CSS
  16. Java 1.4(打印表格)编写程序,显示以下表格。
  17. AE502 112种创意视频字幕动画呼出线框文字标题效果包括PR预设与扩展脚本ae模板
  18. Win10 用户管理中无法删除唯一的administrators组用户
  19. DNS是什么意思有什么作用了
  20. 点石互动--kyw之:Google优化圣经翻译

热门文章

  1. centos7安装python3_详解Centos7升级python 2.7至Python 3.7
  2. 使用XAMPP轻松建站(下)
  3. DaDa英语宣布12月31日起全面停止所有外教服务
  4. 优酷《追光吧!》正式开播 风度、实力成关键词
  5. 腾讯否认“PC端QQ秀下线”:只是在聊天窗口被折叠
  6. 三七互娱Q3归母净利润超预告上限,三大战略迎提速契机
  7. 心玮医疗发布75万股权回购计划 用于招揽和激励员工等
  8. 格力电器上半年净利94.57亿元,同比增长48.64%
  9. 昨天晚上,我在按摩店睡觉,一觉醒来,我的车不是我的了!
  10. 继扫楼推广后,P图病历也可发起筹款,水滴筹回应...