首先确认系统识别到的串口设备:
ls /dev/ttyS* # 查看传统串口(COM)
ls /dev/ttyUSB* # 查看USB转串口设备
ls /dev/ttyACM* # 查看某些USB设备(如Arduino)
dmesg | grep tty # 查看内核识别的串口设备信息
默认情况下普通用户可能没有串口访问权限:
# 临时解决方案 - 更改设备权限
sudo chmod 666 /dev/ttyS0
# 永久解决方案 - 将用户加入dialout组
sudo usermod -a -G dialout $USER
# 然后重新登录使更改生效
# 安装串口通信工具
sudo apt-get install minicom screen picocom putty
# 安装开发库(根据编程语言选择)
sudo apt-get install libserial-dev # C++
sudo apt-get install python-serial # Python
使用stty
命令配置串口参数:
stty -F /dev/ttyS0 115200 cs8 -parenb -cstopb
常用参数说明: - 115200: 波特率 - cs8: 8位数据位 - -parenb: 无奇偶校验 - -cstopb: 1位停止位(使用cstopb表示2位)
minicom -D /dev/ttyS0 -b 115200
screen /dev/ttyS0 115200
(退出screen: Ctrl+A, 然后按k, 再按y确认)
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main() {
int serial_port = open("/dev/ttyS0", O_RDWR);
struct termios tty;
memset(&tty, 0, sizeof tty);
if(tcgetattr(serial_port, &tty) != 0) {
printf("Error %i from tcgetattr: %s\n", errno, strerror(errno));
return 1;
}
cfsetospeed(&tty, B115200);
cfsetispeed(&tty, B115200);
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; // 禁用信号字符
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // 禁用软件流控
tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL);
tty.c_oflag &= ~OPOST; // 原始输出
tty.c_oflag &= ~ONLCR;
tty.c_cc[VMIN] = 1; // 读取至少1个字符
tty.c_cc[VTIME] = 10; // 等待时间(十分之一秒)
if (tcsetattr(serial_port, TCSANOW, &tty) != 0) {
printf("Error %i from tcsetattr: %s\n", errno, strerror(errno));
return 1;
}
// 写入数据
unsigned char msg[] = "Hello Serial!\n";
write(serial_port, msg, sizeof(msg));
// 读取数据
char buf[256];
int n = read(serial_port, &buf, sizeof(buf));
close(serial_port);
return 0;
}
import serial
ser = serial.Serial(
port='/dev/ttyS0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
ser.write(b'Hello Serial!\n')
response = ser.readline()
print(response.decode('utf-8'))
ser.close()
ls /dev/tty*
ls -l /dev/ttyS0
stty -F /dev/ttyS0
查看当前设置创建/etc/rc.local
文件添加:
stty -F /dev/ttyS0 115200 cs8 -parenb -cstopb
编辑/boot/cmdline.txt
(树莓派)或/etc/default/grub
(其他Linux):
console=tty1
然后运行sudo update-grub
并重启。
通过以上配置,您的Linux系统应该能够支持串口通信编程了。根据您的具体应用需求,可以选择合适的编程语言和库进行开发。