C语言串口通信程序示例:基础实现及配置
下面是一个简单的C语言串口通信程序的示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main()
{
int fd;
char buffer[255];
// 打开串口设备文件
fd = open('/dev/ttyUSB0', O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror('无法打开串口设备');
return -1;
}
// 配置串口
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600); // 设置波特率为9600
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD); // 忽略调制解调器控制信息,启用接收器
options.c_cflag &= ~PARENB; // 不使用奇偶校验
options.c_cflag &= ~CSTOPB; // 1位停止位
options.c_cflag &= ~CSIZE; // 8位数据位
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // 非规范模式,禁用回显和信号处理
tcsetattr(fd, TCSANOW, &options);
// 读取串口数据
while (1) {
int num_bytes = read(fd, buffer, sizeof(buffer));
if (num_bytes > 0) {
buffer[num_bytes] = '\0';
printf('接收到的数据:%s\n', buffer);
}
}
// 关闭串口设备文件
close(fd);
return 0;
}
请注意,这只是一个简单的示例,实际的串口通信程序可能需要更复杂的逻辑和错误处理。另外,串口设备文件路径可能因操作系统和硬件而异,需要根据实际情况进行调整。
原文地址: https://www.cveoy.top/t/topic/qi54 著作权归作者所有。请勿转载和采集!