栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Linux上用C读写串口

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Linux上用C读写串口

我已经解决了我的问题,所以我在这里发布了正确的代码,以防有人需要类似的东西。

开放港口

int USB = open( "/dev/ttyUSB0", O_RDWR| O_NOCTTY );

设定参数

struct termios tty;struct termios tty_old;memset (&tty, 0, sizeof tty);if ( tcgetattr ( USB, &tty ) != 0 ) {   std::cout << "Error " << errno << " from tcgetattr: " << strerror(errno) << std::endl;}tty_old = tty;cfsetospeed (&tty, (speed_t)B9600);cfsetispeed (&tty, (speed_t)B9600);tty.c_cflag     &=  ~PARENB; // Make 8n1tty.c_cflag     &=  ~CSTOPB;tty.c_cflag     &=  ~CSIZE;tty.c_cflag     |=  CS8;tty.c_cflag     &=  ~CRTSCTS;// no flow controltty.c_cc[VMIN]   =  1;       // read doesn't blocktty.c_cc[VTIME]  =  5;       // 0.5 seconds read timeouttty.c_cflag     |=  CREAD | CLOCAL;     // turn on READ & ignore ctrl linescfmakeraw(&tty);tcflush( USB, TCIFLUSH );if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {   std::cout << "Error " << errno << " from tcsetattr" << std::endl;}

unsigned char cmd[] = "INIT r";int n_written = 0,    spot = 0;do {    n_written = write( USB, &cmd[spot], 1 );    spot += n_written;} while (cmd[spot-1] != 'r' && n_written > 0);

绝对没有必要每个字节写一个字节,也可以正常

int n_written = write( USB, cmd, sizeof(cmd) -1)
工作。

最后, 阅读

int n = 0,    spot = 0;char buf = '';char response[1024];memset(response, '', sizeof response);do {    n = read( USB, &buf, 1 );    sprintf( &response[spot], "%c", buf );    spot += n;} while( buf != 'r' && n > 0);if (n < 0) {    std::cout << "Error reading: " << strerror(errno) << std::endl;}else if (n == 0) {    std::cout << "Read nothing!" << std::endl;}else {    std::cout << "Response: " << response << std::endl;}

这个为我工作。谢谢你们!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/408626.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号