概述
这是一个使用Linux下的串口编程的示例程序,主要实现了向串口发送数据和接收串口返回数据的功能。
具体来说,程序首先打开串口设备文件,然后配置串口波特率、数据位、停止位等参数,并发送一段字符串到串口。接着程序从串口读取数据并输出到终端上。最后关闭串口设备文件并结束程序。
C代码实现
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
// 定义串口设备文件名和波特率
#define DEVICE_NAME "/dev/ttyS0"
#define BAUD_RATE B9600
int main()
{
int fd;
struct termios options;
// 打开串口设备文件
fd = open(DEVICE_NAME, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("Unable to open device");
exit(EXIT_FAILURE);
}
// 获取现有的串口配置
tcgetattr(fd, &options);
// 设置波特率
cfsetispeed(&options, BAUD_RATE);
cfsetospeed(&options, BAUD_RATE);
// 配置选项:无奇偶校验、8位数据位、1位停止位
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
// 应用修改后的配置
tcsetattr(fd, TCSANOW, &options);
// 写入串口
char message[] = "Hello, world!";
int tx_bytes = write(fd, message, strlen(message));
if (tx_bytes < 0)
{
perror("Error writing to serial port");
exit(EXIT_FAILURE);
}
printf("Sent %d bytes: %s\n", tx_bytes, message);
// 读取串口
char buffer[256];
int rx_bytes = read(fd, buffer, sizeof(buffer));
if (rx_bytes < 0)
{
perror("Error reading from serial port");
exit(EXIT_FAILURE);
}
printf("Received %d bytes: %s\n", rx_bytes, buffer);
// 关闭串口
close(fd);
return 0;
}
总结
需要注意的是,串口编程涉及到硬件底层操作,使用时需要仔细检查代码并确保不会对系统造成损坏。此外,程序中的DEVICE_NAME和BAUD_RATE需要根据实际情况修改,以适配目标设备。