在 Linux 中进行串口操作通常需要使用 termios
结构来配置串口的参数,包括波特率、校验位、数据位长度和停止位长度。以下是一个简单的示例,展示如何打开串口并按照要求配置这些参数。
示例代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <termios.h>
int configure_serial_port(int fd, int baud_rate, int data_bits, char parity, int stop_bits) {
struct termios tty;
// 获取当前的串口设置
if (tcgetattr(fd, &tty) != 0) {
perror("tcgetattr");
return -1;
}
// 设置波特率
switch (baud_rate) {
case 9600:
cfsetispeed(&tty, B9600);
cfsetospeed(&tty, B9600);
break;
case 115200:
cfsetispeed(&tty, B115200);
cfsetospeed(&tty, B115200);
break;
// 添加其他波特率...
default:
fprintf(stderr, "Unsupported baud rate\n");
return -1;
}
// 数据位
tty.c_cflag &= ~CSIZE; // 清除数据位掩码
switch (data_bits) {
case 5:
tty.c_cflag |= CS5;
break;
case 6:
tty.c_cflag |= CS6;
break;
case 7:
tty.c_cflag |= CS7;
break;
case 8:
tty.c_cflag |= CS8;
break;
default:
fprintf(stderr, "Unsupported data bits\n");
return -1;
}
// 校验位
if (parity == 'N' || parity == 'n') {
tty.c_cflag &= ~PARENB; // 无校验
} else if (parity == 'E' || parity == 'e') {
tty.c_cflag |= PARENB; // 开启校验
tty.c_cflag &= ~PARODD; // 偶数校验
} else if (parity == 'O' || parity == 'o') {
tty.c_cflag |= PARENB | PARODD; // 奇数校验
} else {
fprintf(stderr, "Unsupported parity\n");
return -1;
}
// 停止位
if (stop_bits == 1) {
tty.c_cflag &= ~CSTOPB; // 一个停止位
} else if (stop_bits == 2) {
tty.c_cflag |= CSTOPB; // 两个停止位
} else {
fprintf(stderr, "Unsupported stop bits\n");
return -1;
}
// 应用设置并使其生效
tty.c_cc[VMIN] = 0; // 不等待字符到达(非阻塞)
tty.c_cc[VTIME] = 10; // 超时10*100ms
// 启动原始模式并不启用流控制等额外功能。
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
if(tcflush(fd,TCOFLUSH)<0)
{
perror("tcflush TCOFLUSH");
}
if(tcflush(fd,TCIFLUSH)<0)
{
perror("tcflush TCIFLUSH");
}
if(tcsetattr(fd,TCSANOW,&tty)!=0)
{
perror("tcsetattr");
return -1;
}
return 0;
}
int main() {
const char *portname = "/dev/ttyS0"; // 根据实际情况更改端口名,例如 /dev/ttyUSB0 等
int fd = open(portname, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open_port: Unable to open port ");
return EXIT_FAILURE;
}
if(configure_serial_port(fd, 9600, 8, 'N', 1) != 0) {
close(fd);
return EXIT_FAILURE;
}
printf("Serial port configured successfully.\n");
close(fd);
return EXIT_SUCCESS;
}
编译和运行
将上述代码保存为 serial_configure.c
,然后在终端中编译:
gcc serial_configure.c -o serial_configure
确保你有足够的权限访问所选的串口设备,然后运行程序:
sudo ./serial_configure
注意事项
- 修改
/dev/ttyS0
为实际要使用的串口设备名称。 - 确保程序有权限访问串口,可以通过
chmod
或者sudo
来运行程序。 - 根据具体需求调整波特率、数据位、校验及停止位参数。
该代码可以作为基础框架,根据你的需要进行进一步扩展,比如增加错误处理或发送接收数据的功能。
内容由零声教学AI助手提供,问题来源于学员提问