linux串口编程实例
时间: 2023-08-10 07:37:12 浏览: 49
好的,下面是一个简单的Linux串口编程实例:
```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 tty;
// 打开串口设备
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY);
if (fd < 0) {
printf("无法打开串口设备!\n");
return -1;
}
// 配置串口参数
memset(&tty, 0, sizeof(tty));
tty.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
tty.c_iflag = IGNPAR;
tty.c_oflag = 0;
tty.c_lflag = 0;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &tty);
// 写入数据
char *msg = "Hello, world!\n";
write(fd, msg, strlen(msg));
// 读取数据
char buf[1024];
int n = read(fd, buf, sizeof(buf));
buf[n] = '\0';
printf("收到数据:%s", buf);
// 关闭串口设备
close(fd);
return 0;
}
```
这个程序会打开 `/dev/ttyS0` 串口设备,配置波特率为 9600,然后向串口设备写入一条消息,最后读取从串口设备返回的数据。注意,串口设备的名称可能会因系统而异,需要根据实际情况进行调整。