用C语言写一个串口测试程序
时间: 2023-03-24 22:02:53 浏览: 53
你好,以下是用 C 语言编写串口测试程序的示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
int main()
{
int fd;
struct termios options;
char buffer[256];
// 打开串口设备
fd = open("/dev/ttyS", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open");
exit(EXIT_FAILURE);
}
// 配置串口参数
tcgetattr(fd, &options);
cfsetispeed(&options, B960);
cfsetospeed(&options, B960);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~CRTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_iflag &= ~(IXON | IXOFF | IXANY);
options.c_oflag &= ~OPOST;
options.c_cc[VMIN] = 1;
options.c_cc[VTIME] = ;
tcsetattr(fd, TCSANOW, &options);
// 发送测试数据
strcpy(buffer, "Hello, world!\n");
write(fd, buffer, strlen(buffer));
// 接收测试数据
memset(buffer, , sizeof(buffer));
read(fd, buffer, sizeof(buffer));
printf("Received: %s", buffer);
// 关闭串口设备
close(fd);
return ;
}