写一段串口通信的C语言代码
时间: 2023-11-29 21:55:29 浏览: 29
以下是一个简单的串口通信的C语言代码,通过串口发送和接收数据。
```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;
// 打开串口
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open");
return -1;
}
// 设置串口参数
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
tcsetattr(fd, TCSANOW, &options);
// 发送数据
char buffer[256];
strcpy(buffer, "Hello, world!");
write(fd, buffer, strlen(buffer));
// 接收数据
char receive[256];
int n = read(fd, receive, sizeof(receive));
if (n > 0) {
receive[n] = '\0';
printf("Received: %s\n", receive);
}
// 关闭串口
close(fd);
return 0;
}
```
在代码中,首先打开串口 "/dev/ttyS0",然后设置串口参数,包括波特率、数据位、停止位等。接着发送数据和接收数据,最后关闭串口。
注意,在实际使用中,需要根据实际的硬件配置和需求设置串口参数,并处理出现的错误和异常情况。