串口:发送0:点亮灯;发送1:关闭灯程序C语言怎么写
时间: 2024-03-07 16:46:42 浏览: 17
如果你想在C语言中编写读取串口数据的程序,你可以使用`termios`和`fcntl`库来控制串口通信。以下是一个示例程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
int main()
{
int fd;
struct termios options;
char buf[255];
// 打开串口
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
printf("Error opening serial port.\n");
return -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_cc[VMIN] = 1;
options.c_cc[VTIME] = 0;
tcsetattr(fd, TCSANOW, &options);
while (1) {
// 读取串口数据
int n = read(fd, buf, sizeof(buf));
if (n > 0) {
buf[n] = '\0';
if (strcmp(buf, "0") == 0) {
// 点亮灯
printf("Turn on the light.\n");
} else if (strcmp(buf, "1") == 0) {
// 关闭灯
printf("Turn off the light.\n");
}
}
}
// 关闭串口
close(fd);
return 0;
}
```
在上面的代码中,我们首先使用`open()`函数打开串口,指定串口的端口号和打开方式。然后使用`fcntl()`函数将串口设置为阻塞模式,使用`tcgetattr()`和`tcsetattr()`函数设置串口的波特率和参数。然后我们进入一个死循环,不断读取串口数据,并使用`strcmp()`函数判断读取到的数据是否为0或1,如果是0则打印“Turn on the light.”,如果是1则打印“Turn off the light.”。
需要注意的是,在你的设备上,串口的端口号和波特率可能会不同,你需要根据你的实际情况进行修改。