一、基础概念
/dev/ttyS*
(传统的串口设备,如 /dev/ttyS0
)或者 /dev/ttyUSB*
(对于通过USB转串口设备连接的情况)等形式。二、相关优势
minicom
、putty
等串口调试工具)来操作串口设备,开发人员可以快速地进行数据传输的开发。三、类型
四、应用场景
五、常见问题及解决方法
stty
命令来设置串口参数,例如:stty -F /dev/ttyS0 9600 cs8 -cstopb -parenb
(设置波特率为9600,8个数据位,无停止位,无奇偶校验)。dialout
组(在大多数Linux系统中,该组具有访问串口设备的权限),命令为:sudo usermod -aG dialout $USER
,然后重新登录使权限生效。以下是一个简单的在嵌入式Linux下使用C语言进行串口数据发送的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main() {
int serial_port = open("/dev/ttyS0", O_RDWR);
if (serial_port < 0) {
printf("Error opening serial port\n");
return -1;
}
struct termios tty;
if (tcgetattr(serial_port, &tty)!= 0) {
printf("Error from tcgetattr: %s\n", strerror(errno));
return -1;
}
cfsetispeed(&tty, B9600);
cfsetospeed(&tty, B9600);
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~PARENB;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
if (tcsetattr(serial_port, TCSANOW, &tty)!= 0) {
printf("Error from tcsetattr: %s\n", strerror(errno));
return -1;
}
const char *message = "Hello, Serial!";
int n = write(serial_port, message, strlen(message));
if (n < 0) {
printf("Error writing to serial port\n");
}
close(serial_port);
return 0;
}
这个示例代码打开 /dev/ttyS0
串口设备,设置波特率为9600,8个数据位,无奇偶校验,无停止位,然后发送字符串 "Hello, Serial!"到串口。
领取专属 10元无门槛券
手把手带您无忧上云