在Linux系统中,串口(Serial Port)是一种常用的通信接口,用于与外部设备进行数据传输。Linux内核提供了对串口的支持,允许用户空间程序通过标准的文件I/O操作来访问串口设备。
基础概念:
/dev/ttyS*
(如/dev/ttyS0
)或/dev/ttyUSB*
(如用于USB转串口的设备)。相关优势:
应用场景:
使用串口的一般步骤:
open()
函数以读写模式打开串口设备文件。termios
结构体配置波特率、数据位、停止位和奇偶校验等参数。read()
和write()
函数进行数据的读取和写入。close()
函数关闭串口设备文件。示例代码(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 |= (CLOCAL | CREAD); /* ignore modem controls */
tty.c_cflag &= ~PARENB; /* clear parity bit */
tty.c_cflag &= ~CSTOPB; /* only need 1 stop bit */
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8; /* 8-bit characters */
tty.c_cflag &= ~CRTSCTS; /* no hardware flowcontrol */
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // make raw
tty.c_oflag &= ~OPOST; // make raw
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;
}
常见问题及解决方法:
领取专属 10元无门槛券
手把手带您无忧上云