Linux通用串口数据接收代码

Linux通用串口数据接收代码

247
247
2024-09-11 / 0 评论 / 19 阅读 / 正在检测是否收录...
#include <iostream>
#include <thread>
#include <mutex>
#include <termios.h>
#include <string.h>
#include <poll.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <pthread.h>

using namespace std;

int fd;

void serial_read()
{
    int nread;
    int BUFSIZE = 1024;
    unsigned char buff[BUFSIZE];
    unsigned char *pbuff = NULL;
    struct timeval tv;
    fd_set rfds;
    tv.tv_sec = 2;
    tv.tv_usec = 0;

    while (true)
    {
        FD_ZERO(&rfds);
        FD_SET(fd, &rfds);
        if (select(1 + fd, &rfds, NULL, NULL, &tv) > 0)
        {
            if (FD_ISSET(fd, &rfds))
            {
                pbuff = buff;
                nread = read(fd, buff, BUFSIZE);
                printf("Recv Len = %d\n", nread);
                for (int i = 0; i < nread; i++)
                {
                    printf("0x%x ", buff[i]);
                }
                printf("\n");
                memset(buff, 0, sizeof(buff));
            }
        }
    }
}
int main()
{
    if ((fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK)) < 0)
    {
        printf("err: can't open serial port!\n");
        return -1;
    }

    struct termios options;
    tcgetattr(fd, &options);
    bzero(&options, sizeof(options));
    options.c_cflag |= B115200 | CLOCAL | CREAD;
    options.c_cflag &= ~CSIZE;
    options.c_cflag |= CS8;
    options.c_cflag &= ~CSTOPB;
    options.c_cflag &= ~PARENB;
    tcflush(fd, TCIOFLUSH);
    if (tcsetattr(fd, TCSANOW, &options) != 0)
        return -1;
    thread th(serial_read);
    th.join();
    return 0;
}
0

评论 (0)

取消