uart串口发送json格式的C程序
时间: 2023-09-16 21:12:12 浏览: 358
uart发送程序
5星 · 资源好评率100%
这是一个简单的示例程序,演示如何使用UART串口发送JSON格式的数据:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <errno.h>
#include <json-c/json.h>
#define UART_DEVICE "/dev/ttyS0"
#define BAUDRATE B9600
int uart_fd;
int uart_init()
{
struct termios tty;
uart_fd = open(UART_DEVICE, O_RDWR | O_NOCTTY);
if (uart_fd < 0) {
perror("open");
return -1;
}
memset(&tty, 0, sizeof(tty));
if (tcgetattr(uart_fd, &tty) != 0) {
perror("tcgetattr");
return -1;
}
cfsetospeed(&tty, BAUDRATE);
cfsetispeed(&tty, BAUDRATE);
tty.c_cflag |= (CLOCAL | CREAD);
tty.c_cflag &= ~CSIZE;
tty.c_cflag |= CS8;
tty.c_cflag &= ~PARENB;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
tty.c_iflag &= ~(IXON | IXOFF | IXANY);
tty.c_iflag &= ~INPCK;
tty.c_iflag &= ~(ICRNL | IGNCR | INLCR);
tty.c_oflag &= ~OPOST;
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 0;
if (tcsetattr(uart_fd, TCSANOW, &tty) != 0) {
perror("tcsetattr");
return -1;
}
return 0;
}
int uart_send_json(json_object *jobj)
{
const char *json_str = json_object_to_json_string(jobj);
int len = strlen(json_str);
if (write(uart_fd, json_str, len) != len) {
perror("write");
return -1;
}
return 0;
}
int main()
{
if (uart_init() != 0) {
exit(EXIT_FAILURE);
}
json_object *jobj = json_object_new_object();
json_object_object_add(jobj, "name", json_object_new_string("John"));
json_object_object_add(jobj, "age", json_object_new_int(30));
json_object_object_add(jobj, "height", json_object_new_double(1.75));
json_object_object_add(jobj, "married", json_object_new_boolean(0));
if (uart_send_json(jobj) != 0) {
exit(EXIT_FAILURE);
}
json_object_put(jobj);
close(uart_fd);
exit(EXIT_SUCCESS);
}
```
这个程序首先使用`uart_init()`函数初始化UART串口,然后创建一个JSON对象`jobj`,将数据添加到其中,最后调用`uart_send_json()`函数将JSON字符串发送到串口。`uart_send_json()`函数将JSON对象转换为字符串,并使用`write()`函数将其发送到串口。发送完成后,程序释放JSON对象并关闭串口。
阅读全文