在Linux环境下使用C语言打开串口主要涉及到对/dev/ttyS*
(对于传统的串口,如COM1对应/dev/ttyS0
)或者/dev/ttyUSB*
(对于USB转串口设备)设备的操作。以下是相关的基础概念、步骤以及示例代码:
<fcntl.h>
用于文件操作,<termios.h>
用于串口配置,<unistd.h>
用于一些系统调用函数(如close
)。open
函数以合适的模式(读、写或者读写)打开串口设备文件。termios
结构体来设置波特率、数据位、停止位、奇偶校验等参数。read
和write
函数对串口进行数据的读取和发送。close
函数关闭串口设备文件。以下是一个简单的打开串口并设置基本参数的示例:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int main() {
int serial_port;
struct termios tty;
// 打开串口设备(这里以/dev/ttyS0为例)
serial_port = open("/dev/ttyS0", O_RDWR);
if (serial_port < 0) {
printf("Error %i from open: %s\n", errno, strerror(errno));
return 1;
}
// 获取当前串口配置
tcgetattr(serial_port, &tty);
// 设置波特率为9600
cfsetispeed(&tty, B9600);
cfsetospeed(&tty, B9600);
// 设置数据位为8位,停止位为1位,无奇偶校验
tty.c_cflag &= ~PARENB;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
// 使能接收和发送数据
tty.c_cflag |= (CLOCAL | CREAD);
// 设置本地模式,忽略硬件流控制
tty.c_cflag &= ~CRTSCTS;
// 设置新的串口配置
tcsetattr(serial_port, TCSANOW, &tty);
// 这里可以进行读写操作,例如:
// write(serial_port, "Hello Serial", 11);
// char buffer[256];
// read(serial_port, &buffer, sizeof(buffer));
close(serial_port);
return 0;
}
sudo
运行程序或者将当前用户添加到dialout
组(sudo usermod -a -G dialout $USER
,然后重新登录)。/dev
目录下的设备文件或者使用dmesg
命令结合插入串口设备的情况来确定正确的设备文件。termios
结构体后,一定要调用tcsetattr
函数来应用新的配置,并且要注意TCSANOW
标志表示立即应用配置。没有搜到相关的文章