Mac OS/Linux系统下实现串口通信

最近参加了一个机器人比赛,机器人部分装置需要靠Arduino板来控制,一共两块不同型号的Arduino板,这两块板需要进行通信,还需要分别和电脑上的c++程序通信。我的电脑是Mac Pro 2016款,在Mac系统下实现了串口通信。Mac系统下的很多问题其实和Linux系统下的相似问题的解决方法类似。

  1. 了解串口通信原理,搜索关键词“Linux系统c++实现串口通信例程”,有很多文档和教程可以学习。
  2. 提供一段历程代码。
#include     <stdio.h>      /*标准输入输出定义*/
#include     <stdlib.h>     /*标准函数库定义*/
#include     <unistd.h>     /*Unix 标准函数定义*/
#include     <sys/types.h>
#include     <sys/stat.h>
#include     "string.h"
#include     <fcntl.h>      /*文件控制定义*/
#include     <termios.h>    /*PPSIX 终端控制定义*/
#include     <errno.h>      /*错误号定义*/
#define FALSE  -1
#define TRUE   0
/*********************************************************************/
int OpenDev(char *Dev)
{
    int fd = open( Dev, O_RDWR | O_NOCTTY );         //| O_NOCTTY | O_NDELAY
    if (-1 == fd)
    {
        perror("Can't Open Serial Port");
        return -1;
    }
    else
        return fd;
}
/**
 *@brief  设置串口通信速率
 *@param  fd     类型 int  打开串口的文件句柄
 *@param  speed  类型 int  串口速度
 *@return  void
 */
int speed_arr[] = { B38400, B19200, B9600, B4800, B2400, B1200, B300,
    B38400, B19200, B9600, B4800, B2400, B1200, B300, };
int name_arr[] = {38400,  19200,  9600,  4800,  2400,  1200,  300, 38400,
    19200,  9600, 4800, 2400, 1200,  300, };
void set_speed(int fd, int speed)
{
    int   i;
    int   status;
    struct termios   Opt;
    tcgetattr(fd, &Opt);
    for ( i= 0;  i < sizeof(speed_arr) / sizeof(int);  i++) {
        if  (speed == name_arr[i]) {
            tcflush(fd, TCIOFLUSH);
            cfsetispeed(&Opt, speed_arr[i]);
            cfsetospeed(&Opt, speed_arr[i]);
            status = tcsetattr(fd, TCSANOW, &Opt);
            if  (status != 0) {
                perror("tcsetattr fd1");
                return;
            }
            tcflush(fd,TCIOFLUSH);
        }
    }
}
/**
 *@brief   设置串口数据位,停止位和效验位
 *@param  fd     类型  int  打开的串口文件句柄
 *@param  databits 类型  int 数据位   取值 为 7 或者8
 *@param  stopbits 类型  int 停止位   取值为 1 或者2
 *@param  parity  类型  int  效验类型 取值为N,E,O,,S
 */
int set_Parity(int fd,int databits,int stopbits,int parity)
{
    struct termios options;
    options.c_lflag  &= ~(ICANON | ECHO | ECHOE | ISIG);  /*Input*/
    options.c_oflag  &= ~OPOST;   /*Output*/
    if  ( tcgetattr( fd,&options)  !=  0) {
        perror("SetupSerial 1");
        return(FALSE);
    }
    options.c_cflag &= ~CSIZE;
    switch (databits) /*设置数据位数*/
    {
        case 7:
            options.c_cflag |= CS7;
            break;
        case 8:
            options.c_cflag |= CS8;
            break;
        default:
            fprintf(stderr,"Unsupported data size/n"); return (FALSE);
    }
    switch (parity)
    {
        case 'n':
        case 'N':
            options.c_cflag &= ~PARENB;   /* Clear parity enable */
            options.c_iflag &= ~INPCK;     /* Enable parity checking */
            break;
        case 'o':
        case 'O':
            options.c_cflag |= (PARODD | PARENB); /* 设置为奇效验*/
            options.c_iflag |= INPCK;             /* Disnable parity checking */
            break;
        case 'e':
        case 'E':
            options.c_cflag |= PARENB;     /* Enable parity */
            options.c_cflag &= ~PARODD;   /* 转换为偶效验*/
            options.c_iflag |= INPCK;       /* Disnable parity checking */
            break;
        case 'S':
        case 's':  /*as no parity*/
            options.c_cflag &= ~PARENB;
            options.c_cflag &= ~CSTOPB;break;
        default:
            fprintf(stderr,"Unsupported parity/n");
            return (FALSE);
    }
    /* 设置停止位*/
    switch (stopbits)
    {
        case 1:
            options.c_cflag &= ~CSTOPB;
            break;
        case 2:
            options.c_cflag |= CSTOPB;
            break;
        default:
            fprintf(stderr,"Unsupported stop bits/n");
            return (FALSE);
    }
    /* Set input parity option */
    if (parity != 'n')
        options.c_iflag |= INPCK;
    tcflush(fd,TCIFLUSH);
    options.c_cc[VTIME] = 150; /* 设置超时15 seconds*/
    options.c_cc[VMIN] = 0; /* Update the options and do it NOW */
    if (tcsetattr(fd,TCSANOW,&options) != 0)
    {
        perror("SetupSerial 3");
        return (FALSE);
    }
    return (TRUE);
}
int main(int argc, char **argv)
{

    int fd, fd2;
    int nread, nwrite;
    char buff[512];
    char buu = 'a';
    char buu2 ;
    char buu3 = 'c';
    char *dev  = "/dev/cu.usbmodem14311"; //串口二
    char *dev2 = "/dev/cu.usbmodem14331";
    fd = OpenDev(dev);
    fd2 = OpenDev(dev2);
    set_speed(fd,9600);
    set_speed(fd2, 9600);
    if (set_Parity(fd,8,1,'N') == FALSE)
    {
        printf("Set Parity Error/n");
        exit (0);
    }
    if (set_Parity(fd2,8,1,'N') == FALSE)
    {
        printf("Set Parity Error/n");
        exit (0);
    }
    printf("look1\n");
    sleep(10);
    nwrite = write(fd, &buu, 1);
    //buff[nread+1] = '\0';
    printf("%d\n%c\n", nwrite, buu);
    sleep(10);
    printf("Look2\n");
    nread = read(fd, &buu2, 1);
    //buff[nread+1] = '\0';
    printf("%d\n%c\n", nread, buu2);

    sleep(10);
    printf("Look3\n");
    nwrite = write(fd2, &buu2, 1);
    printf("%d\n%c\n", nwrite, buu2);

    sleep(10);
    printf("Look4\n");
    nread = read(fd2, &buu2, 1);
    //buff[nread+1] = '\0';
    printf("%d\n%c\n", nread, buu2);

    sleep(10);
    printf("Look5\n");
    nwrite = write(fd2, &buu2, 1);
    printf("%d\n%c\n", nwrite, buu2);

    sleep(10);
    printf("Look6\n");
    nread = read(fd2, &buu2, 1);
    //buff[nread+1] = '\0';
    printf("%d\n%c\n", nread, buu2);

//    }
    //printf("Look\n");
      close(fd);
    //exit (0);
}
  1. 以上代码比较重要的几个函数的解释:首先dev[]和dev2[]需要记录串口(设备)的名字。查看设备名字的方法,打开终端,进入/dev目录下,使用命令ls查看当下连接的串口名字。
  2. fd = OpenDev(dev),打开端口函数,确保串口名字没有问题就可以
  3. set_speed(),设置串口波特率参数,注意查询参数,否则会出现通信问题
  4. set_Parity(),设置奇偶校验位参数,注意查询参数,否则就出现通信问题
  5. 接下来就是使用read()函数进行串口的读,write()函数进行串口的写
  6. read()函数和write()函数传入的参数都是三个,fd选择哪一个串口,char *读取或者写入的字符,第三个参数表示字符的长度。具体使用前可以详细了解一下函数
  7. nread和nwrite用来记录read()和write()函数的返回值,读取或者写入正常的话返回的是读取或者写入字符的长度,否则返回负值
  8. 后面的程序是我写的,加了很多的sleep()函数,这个点是很多教程上都没有写到的,一般使用串口通信的时候,一边是电脑,一边是其他的硬件设备(这里以Arduino板为例),两边相互连接。在起始的时候,硬件需要和电脑进行连接,所以这个时候程序最好不要一运行就读取或者写入串口。就拿读取为例,电脑上的程序读取的时刻,Arduino板由于与电脑连接初始化还没完成,因此板上的Serial.print(‘z’)程序还未正式运行,未向串口写入东西,当Arduino板运行写入程序的时刻,电脑程序已经运行了读取的语句,导致电脑无法从串口读到东西。因此最好加上sleep(),确保这个初始化时间内没有做串口读写的事。同理,当对不同串口进行读写之间,最好加上sleep(),给点延迟,让硬件通信能够建立完成。
  9. 最后想说的是,硬件的问题有时候会比较迷,解决问题需要耐住性子,不断地调试软件程序和检查硬件设备。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章