linux打开串口代码
时间: 2023-05-21 16:03:14 浏览: 76
以下是一个简单的 Linux 打开串口的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int main()
{
int fd;
struct termios options;
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open");
exit(1);
}
fcntl(fd, F_SETFL, 0);
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
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] = 0;
tcsetattr(fd, TCSANOW, &options);
char buffer[255];
int n = read(fd, buffer, sizeof(buffer));
if (n > 0)
{
printf("Received: %s\n", buffer);
}
close(fd);
return 0;
}
```
这个代码示例打开了串口 `/dev/ttyS0`,设置了波特率为 9600,然后读取了从串口接收到的数据并打印出来。