在Linux环境下使用C语言监听串口主要涉及到对串口设备的操作,包括打开设备、配置串口参数(如波特率、数据位、停止位、校验位等)、读取和写入数据。
一、基础概念
/dev/ttyS0
(对于传统的串口)或者/dev/ttyUSB0
(对于通过USB转串口设备连接的串口)。二、相关优势
三、应用场景
四、示例代码(C语言)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int main()
{
int serial_port = open("/dev/ttyS0", O_RDWR);
if (serial_port < 0) {
printf("Error %i from open: %s\n", errno, strerror(errno));
return 1;
}
struct termios tty;
if (tcgetattr(serial_port, &tty)!= 0) {
printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
return 1;
}
cfsetispeed(&tty, B9600);
cfsetospeed(&tty, B9600);
tty.c_cflag &= ~PARENB; // 无校验
tty.c_cflag &= ~CSTOPB; // 1个停止位
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; // 8位数据位
tty.c_cflag &= ~CRTSCTS; // 无硬件流控
tty.c_cflag |= CREAD | CLOCAL;
tty.c_lflag &= ~ICANON;
tty.c_lflag &= ~ECHO;
tty.c_lflag &= ~ECHOE;
tty.c_lflag &= ~ECHONL;
tty.c_lflag &= ~ISIG;
if (tcsetattr(serial_port, TCSANOW, &tty)!= 0) {
printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
return 1;
}
char read_buf [256];
while (1) {
int n = read(serial_port, &read_buf, sizeof(read_buf));
if (n < 0) {
printf("Error reading: %s", strerror(errno));
break;
}
printf("%.*s", n, read_buf);
}
close(serial_port);
return 0;
}
五、可能遇到的问题及解决方法
sudo
命令运行程序或者修改设备文件的权限(不推荐随意修改权限,可能存在安全风险)。sudo chmod 666 /dev/ttyS0
(仅用于测试目的)。领取专属 10元无门槛券
手把手带您无忧上云