前面的文章已经讲解了如果通过MCU连接云平台以及采集温湿度,接下来就是要实现将温湿度上报云平台。首先我们要在云平台上定义上报温度和上报湿度的服务,之前的文章也说过了怎么定义服务,这里就不再讲述。可以发现,在之前的测试数据中,采用的是16进制的形式,上报的是整型数据,这里sht30采集的温湿度是浮点数类型的,由于我现在没有实现将浮点数转16进制如何再通过AT命令上报到云端,所以我采用的是以字符串的形式上报,那么在云平台上定义服务的时候也要将服务的数据类型设置为字符串形式,我设置的是定长字符串,5字节。
确定好上报的数据类型之后,那么我们要怎么实现呢?首先,采集到的温湿度是浮点型数据,那么就要把采集到的数据转化成字符串;转化成字符串之后有要怎么上报到云端呢?要上报到云端,需要把字符串转16进制的ASCII值,以此来上报数据。分析完之后来说说怎么实现。
封装一个字符串转16进制ASCII的函数,写在main.c文件合适的地方即可,同时记得声明函数
/*字符串转16进制ASCII*/
int fstr_to_hex(char *fstr, unsigned int fstrlen, char *out)
{
char str_buf[66] = {0};
char pbuf[65];
int i;
for(i = 0; i<fstrlen; i++)
{
sprintf(pbuf, "%02X", fstr[i]);
strncat(str_buf, pbuf, 2);
}
strncpy(out, str_buf, fstrlen*2);
return fstrlen*2;
}
在采集温湿度的函数里增加将采集到的数据转化成字符串,同时完成上报云端,修改后的函数代码如下
int report_tempRH_json(void)
{
char buf[128];/*声明了一个128字节的缓冲区buf,用于存储JSON数据*/
float temperature,humidity;/*声明了两个变量temperature和humidity,用于存储温度和湿度的值*/
if(SHT30_SampleData(&temperature,&humidity) < 0)
{
printf("ERROR:SHT30 Sample data failure\n");
return -1;
}
memset(buf,0,sizeof(buf));/*使用memset函数将buf缓冲区清0*/
/*使用snprintf函数将温度和湿度的数据格式化为JSON字符串,并存储在buf缓冲区中*/
//snprintf(buf,sizeof(buf),"{\"Temperature\":\"%.2f\",\"Humidity\":\"%.2f\"}",temperature,humidity);
HAL_UART_Transmit(&huart1,(uint8_t *)buf,strlen(buf),0xFFFF);/*使用HAL_UART_Transmit函数将buf缓冲区中的数据发送给UART设备*/
/*将温度和湿度数据转换为字符串形式,并传给fstr_to_hex函数进行处理*/
char str_temperature[10];
char str_humidity[10];
sprintf(str_temperature, "%.2f", temperature);
sprintf(str_humidity, "%.2f", humidity);
char hex_temperature[20];
char hex_humidity[20];
fstr_to_hex(str_temperature, strlen(str_temperature), hex_temperature);
fstr_to_hex(str_humidity, strlen(str_humidity), hex_humidity);
printf("Temperature: %s, ASCII: %s\r\n", str_temperature, hex_temperature);/*在串口调试助手上以字符串的形式打印出温度值,以及转换后的ASCII值*/
printf("Humidity: %s, ASCII: %s\r\n", str_humidity, hex_humidity);/*在串口调试助手上以字符串的形式打印出湿度值,以及转换后的ASCII值*/
//上传云平台
sprintf(str_temperature, "AT+QLWULDATAEX=10,02002D0005%s,0x0100\r\n", hex_temperature);
send_atcmd(str_temperature,EXPECT_OK,500);
HAL_Delay(1000);
sprintf(str_humidity, "AT+QLWULDATAEX=10,02002E0005%s,0x0100\r\n", hex_humidity);
send_atcmd(str_humidity,EXPECT_OK,500);
return 0;
}
最后while里函数调用即可
report_tempRH_json();
HAL_Delay(1000);
编译下载代码,运行。
在串口调试助手上查看打印值
在云端查看上报的数据
这样就完成了将温湿度实时上报到云端的功能