串口232接收数据代码,linux

本文详细介绍了如何使用C++编程语言打开并配置/dev/ttyS0串口,设置波特率为9600,进行无校验、非停等模式的通信,并持续从串口读取数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
    int serial_port = open("/dev/ttyS0", O_RDONLY);

    if (serial_port < 0) {
        std::cerr << "Failed to open serial port" << std::endl;
        return -1;
    }

    struct termios tty;
    struct termios tty_old;
    memset(&tty, 0, sizeof(tty));

    if (tcgetattr(serial_port, &tty) != 0) {
        std::cerr << "Failed to get serial port attributes" << std::endl;
        return -1;
    }

    tty_old = tty;
//波特率设置为9600,可以根据具体需求更改
    cfsetospeed(&tty, (speed_t)B9600);
    cfsetispeed(&tty, (speed_t)B9600);

    tty.c_cflag |= (CLOCAL | CREAD);
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;
    tty.c_cflag &= ~PARENB;
    tty.c_cflag &= ~CSTOPB;
    tty.c_cflag &= ~CRTSCTS;

    tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
    tty.c_iflag &= ~(IXON | IXOFF | IXANY);
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL);

    tty.c_oflag &= ~OPOST;

    tty.c_cc[VTIME] = 10;
    tty.c_cc[VMIN] = 0;

    tcsetattr(serial_port, TCSANOW, &tty);

    while (true) {
        char buffer[256];
        int n = read(serial_port, buffer, sizeof(buffer));
        if (n > 0) {
            buffer[n] = '\0';
            std::cout << buffer << std::endl;
        }
    }

    tcsetattr(serial_port, TCSANOW, &tty_old);
    close(serial_port);

    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值