在Linux环境下使用C语言进行串口收发数据,涉及以下基础概念和相关操作:
以下是一个简单的Linux C语言串口收发数据示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
int open_serial_port(const char *port) {
int fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open_serial_port: Unable to open port");
return -1;
}
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600); // 设置波特率
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD); // 启用接收器并忽略本地回环
options.c_cflag &= ~PARENB; // 无校验
options.c_cflag &= ~CSTOPB; // 1个停止位
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8; // 8位数据位
tcsetattr(fd, TCSANOW, &options);
return fd;
}
void close_serial_port(int fd) {
close(fd);
}
int read_serial_port(int fd, char *buffer, int length) {
int n = read(fd, buffer, length);
if (n < 0) {
perror("read_serial_port: Unable to read from port");
return -1;
}
return n;
}
int write_serial_port(int fd, const char *buffer, int length) {
int n = write(fd, buffer, length);
if (n < 0) {
perror("write_serial_port: Unable to write to port");
return -1;
}
return n;
}
int main() {
int fd = open_serial_port("/dev/ttyS0"); // 打开串口设备
if (fd == -1) {
return 1;
}
char write_buffer[] = "Hello, Serial!";
write_serial_port(fd, write_buffer, strlen(write_buffer));
char read_buffer[256];
int n = read_serial_port(fd, read_buffer, sizeof(read_buffer));
if (n > 0) {
read_buffer[n] = '\0';
printf("Received: %s
", read_buffer);
}
close_serial_port(fd);
return 0;
}
/dev/ttyS0
)存在且权限正确。sudo
权限运行程序或修改设备文件权限。通过以上示例代码和常见问题解决方法,可以在Linux环境下使用C语言进行基本的串口收发数据操作。
领取专属 10元无门槛券
手把手带您无忧上云