Linux下的C串口通信

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>

#define u_char unsigned char
#define u_int unsigned int
#define u_long unsigned long

#define xAppName    "rs232Cli"
#define xAppVer     "v1.0.0"

int main(int argc, char* argv[])
{
    if(argc <= 1)
    {
        printf("%s\n",xAppName);
        printf("%s\n",xAppVer);
        _exit(-1);
    }

    u_char xTTyPath[20] = { 0 };
    strcpy(xTTyPath,"/dev/");
    strcat(xTTyPath,argv[1]);
    int xSerialPort = open(xTTyPath, O_RDWR);

    printf("\033]0;%s %s - %s [115200-E-8-1]\007", xAppName, xAppVer, argv[1]);

    struct termios xTTy;
    if(tcgetattr(xSerialPort, &xTTy) != 0) {
        printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
        return 1;
    }

    //xTTy.c_cflag &= ~PARENB;      //清除奇偶校验位,禁用奇偶校验
    xTTy.c_cflag |= PARENB;         //设置校验位使能
    //xTTy.c_cflag |= PARODD;       //设置为奇检验(1)
    xTTy.c_cflag &= ~PARODD;        //设置为偶校验(0)
    xTTy.c_cflag &= ~CSTOPB;        //清除停止字段,通信中仅使用一个停止位
    xTTy.c_cflag &= ~CSIZE;         //清除所有设置数据大小的位 
    xTTy.c_cflag |= CS8;            //每字节8位
    xTTy.c_cflag &= ~CRTSCTS;       //禁用RTS/CTS硬件流控制
    xTTy.c_cflag |= CREAD | CLOCAL; //打开READ并忽略ctrl行(CLOCAL = 1)

    xTTy.c_lflag &= ~ICANON;
    xTTy.c_lflag &= ~ECHO;
    xTTy.c_lflag &= ~ECHOE;
    xTTy.c_lflag &= ~ECHONL;
    xTTy.c_lflag &= ~ISIG;
    xTTy.c_iflag &= ~(IXON | IXOFF | IXANY); //关闭s/w流量控制
    xTTy.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); //禁用接收字节的任何特殊处理

    xTTy.c_oflag &= ~OPOST;     //防止对输出字节进行特殊解释
    xTTy.c_oflag &= ~ONLCR;     //防止换行转换为回车/换行
    //xTTy.c_oflag &= ~OXTABS;  //防止将制表符转换为空格
    //xTTy.c_oflag &= ~ONOEOT;  //阻止删除输出中的C-d字符(0x004)

    xTTy.c_cc[VTIME] = 10;      //最多等待1秒,收到任何数据后立即返回.
    xTTy.c_cc[VMIN] = 0;

    //将输入/输出波特率设置为115200
    cfsetispeed(&xTTy, B115200);
    cfsetospeed(&xTTy, B115200);

    //保存tty设置,同时检查错误
    if (tcsetattr(xSerialPort, TCSANOW, &xTTy) != 0) {
        printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
        return 1;
    }

    //写入串行端口
    unsigned char msg[] = { 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF };
    write(xSerialPort, msg, sizeof(msg));

    //为读取缓冲区分配内存,根据需要设置大小
    char read_buf [256];

    //通常情况下,您不会执行此memset()调用,但由于本例中我们只接收ASCII数据,因此我们将所有内容都设置为0,以便轻松调用printf().
    memset(&read_buf, '\0', sizeof(read_buf));

    //读取字节,read()的行为(例如,它会阻塞吗?阻塞多长时间?)取决于上面的配置设置,特别是VMIN和VTIME
    int num_bytes = read(xSerialPort, &read_buf, sizeof(read_buf));

    //n是读取的字节数.如果没有接收到字节,n可以是0,也可以是-1以发出错误信号.
    if (num_bytes < 0) {
        printf("Error reading: %s", strerror(errno));
        return 1;
    }

    printf("Read %i bytes. Received message: %s", num_bytes, read_buf);

    close(xSerialPort);
    return 0;
};

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注