#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;
}
串口232接收数据代码,linux
最新推荐文章于 2024-07-06 09:49:08 发布