uart串口接收json格式的C程序
时间: 2023-10-09 07:11:08 浏览: 37
以下是一个使用UART串口接收JSON格式数据的C程序示例:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/time.h>
#include <json-c/json.h>
#define UART_DEV "/dev/ttyS0" // 串口设备文件路径
#define BAUD_RATE B115200 // 波特率
int uart_fd = -1; // 串口文件描述符
/**
* @brief 打开串口设备
* @param dev 设备文件路径
* @param baud_rate 波特率
* @return 成功返回0,失败返回-1
*/
int open_uart(const char *dev, speed_t baud_rate)
{
int fd;
struct termios options;
// 打开串口设备
fd = open(dev, O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open");
return -1;
}
// 配置串口参数
tcgetattr(fd, &options);
cfmakeraw(&options);
cfsetispeed(&options, baud_rate);
cfsetospeed(&options, baud_rate);
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_cc[VMIN] = 1;
options.c_cc[VTIME] = 0;
tcsetattr(fd, TCSANOW, &options);
return fd;
}
/**
* @brief 读取串口数据
* @param fd 串口文件描述符
* @param buf 缓冲区
* @param len 缓冲区长度
* @return 成功返回读取到的字节数,失败返回-1
*/
int read_uart(int fd, char *buf, int len)
{
fd_set rfds;
struct timeval tv;
int ret;
FD_ZERO(&rfds);
FD_SET(fd, &rfds);
tv.tv_sec = 1;
tv.tv_usec = 0;
ret = select(fd+1, &rfds, NULL, NULL, &tv);
if (ret == -1)
{
perror("select");
return -1;
}
else if (ret == 0)
{
return 0;
}
ret = read(fd, buf, len);
if (ret == -1)
{
perror("read");
return -1;
}
return ret;
}
int main(void)
{
char buf[1024];
int len;
struct json_object *root, *name, *age, *city;
// 打开串口设备
uart_fd = open_uart(UART_DEV, BAUD_RATE);
if (uart_fd == -1)
{
return -1;
}
while (1)
{
// 读取串口数据
len = read_uart(uart_fd, buf, sizeof(buf));
if (len > 0)
{
buf[len] = '\0';
printf("received: %s\n", buf);
// 解析JSON数据
root = json_tokener_parse(buf);
if (root == NULL)
{
printf("failed to parse JSON data\n");
continue;
}
// 获取JSON对象中的字段值
json_object_object_get_ex(root, "name", &name);
json_object_object_get_ex(root, "age", &age);
json_object_object_get_ex(root, "city", &city);
printf("name=%s, age=%d, city=%s\n",
json_object_get_string(name),
json_object_get_int(age),
json_object_get_string(city));
// 释放JSON对象
json_object_put(root);
}
else if (len == -1)
{
break;
}
}
// 关闭串口设备
close(uart_fd);
return 0;
}