Files
JYF_STC15W4K_wireless_charge/Lib/sensor_json.h

101 lines
2.8 KiB
C
Raw Normal View History

2025-03-20 16:36:10 +08:00
/**********************************************
* sensor_json.h
* 5uint16参数封装为紧凑JSON格式
* HEX传输
* C51硬件架构优化
**********************************************/
#ifndef __SENSOR_JSON_H__
#define __SENSOR_JSON_H__
#include <stdint.h>
/* 硬件相关定义 */
#define JSON_BUF_SIZE 57 // 内存预分配避免动态申请
#define HEX_DIGITS "0123456789ABCDEF"
/* 静态缓冲区声明 */
static char json_buf[JSON_BUF_SIZE]
= "{\"vol\":----,\"cur\":----,\"pwr\":----,\"tmp\":----,\"hum\":----}";
/**********************************************
* hex4_encode
* HEX转换
* 164
*
**********************************************/
static void
hex4_encode (uint16_t num, char *out)
{
out[0] = HEX_DIGITS[(num >> 12) & 0x0F];
out[1] = HEX_DIGITS[(num >> 8) & 0x0F];
out[2] = HEX_DIGITS[(num >> 4) & 0x0F];
out[3] = HEX_DIGITS[num & 0x0F];
}
/**********************************************
* make_sensor_json
* 湿
*
*
**********************************************/
char *
make_sensor_json (uint16_t v, uint16_t c, uint16_t p, uint16_t t, uint16_t h)
{
char tmp[4];
/* 定点内存操作(避免字符串拼接) */
hex4_encode (v, tmp);
json_buf[7] = tmp[0];
json_buf[8] = tmp[1]; // vol
json_buf[9] = tmp[2];
json_buf[10] = tmp[3];
hex4_encode (c, tmp);
json_buf[18] = tmp[0];
json_buf[19] = tmp[1]; // cur
json_buf[20] = tmp[2];
json_buf[21] = tmp[3];
hex4_encode (p, tmp);
json_buf[29] = tmp[0];
json_buf[30] = tmp[1]; // pwr
json_buf[31] = tmp[2];
json_buf[32] = tmp[3];
hex4_encode (t, tmp);
json_buf[40] = tmp[0];
json_buf[41] = tmp[1]; // tmp
json_buf[42] = tmp[2];
json_buf[43] = tmp[3];
hex4_encode (h, tmp);
json_buf[51] = tmp[0];
json_buf[52] = tmp[1]; // hum
json_buf[53] = tmp[2];
json_buf[54] = tmp[3];
return json_buf;
}
#endif /* __SENSOR_JSON_H__ */
/**********************************************
* 使
* #include "sensor_json.h"
*
* void main() {
* char* data = make_sensor_json(
* 0x0D0C, // 电压
* 0x047E, // 电流
* 0x1284, // 功率
* 0x0CA2, // 温度
* 0x0BF6 // 湿度
* );
* // 通过P1口输出需按 配置端口模式)
* for(uint8_t i=0; data[i]; i++) {
* P1 = data[i]; // 假设P1接发送模块
* delay_ms(1);
* }
* }
**********************************************/