墨香年少 32 发布于 3月20日 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include <string.h> // 函数声明 int open_serial(const char *device); int setup_serial(int fd, int speed, int parity); int serial_read(int fd, char *buf, int size); int serial_write(int fd, const char *buf, int size); void close_serial(int fd); // 打开串口设备 int open_serial(const char *device) { int fd = open(device, O_RDWR | O_NOCTTY | O_SYNC); if (fd < 0) { perror("open_serial() failed"); return -1; } return fd; } // 配置串口参数 int setup_serial(int fd, int speed, int parity) { struct termios tty; memset(&tty, 0, sizeof tty); if (tcgetattr(fd, &tty) != 0) { perror("setup_serial() failed"); return -1; } cfsetospeed(&tty, speed); cfsetispeed(&tty, speed); tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars tty.c_iflag &= ~IGNBRK; // disable break processing tty.c_lflag = 0; // no signaling chars, no echo, // no canonical processing tty.c_oflag = 0; // no remapping, no delays tty.c_cc[VMIN] = 0; // read doesn't block tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl tty.c_cflag |= (CLOCAL | CREAD); // ignore modem controls, // enable reading tty.c_cflag &= ~(PARENB | PARODD); // shut off parity tty.c_cflag |= parity; tty.c_cflag &= ~CSTOPB; tty.c_cflag &= ~CRTSCTS; if (tcsetattr(fd, TCSANOW, &tty) != 0) { perror("setup_serial() failed"); return -1; } return 0; } // 读取串口数据 int serial_read(int fd, char *buf, int size) { int n = read(fd, buf, size); if (n < 0) { perror("serial_read() failed"); return -1; } return n; } // 向串口写入数据 int serial_write(int fd, const char *buf, int size) { int n = write(fd, buf, size); if (n < 0) { perror("serial_write() failed"); return -1; } return n; } // 关闭串口设备 void close_serial(int fd) { close(fd); } // 主函数示例 int main() { int fd = open_serial("/dev/ttyUSB0"); // 替换为实际的串口设备文件 if (fd < 0) return 1; if (setup_serial(fd, B9600, 0) < 0) { // 设置波特率为 9600 close_serial(fd); return 1; } const char *msg = "Hello, serial port!"; serial_write(fd, msg, strlen(msg)); // 发送数据 char buf[100]; int n = serial_read(fd, buf, sizeof(buf) - 1); // 读取数据 if (n >= 0) { buf[n] = '\0'; printf("Received: %s\n", buf); } close_serial(fd); return 0; } 目之所及,皆是回忆,心之所想,皆是过往 分享这篇帖子 链接帖子 分享到其他站点