stm32单片机将传感器采集到的温度通过NB-IoT模块上报到天翼物联网云平台。
-
硬件连接
将NB-IoT模块的RX,TX分别与单片机的RX,TX相连,GND接GND,保证模块正常连接。 -
串口初始化
该MCU通过串口三给BC28传输数据,从而与云平台通信。这里展示USART3的初始化,使能串口三中断(波特率设置为9600Bits/s):
以下是代码初始化:
点击查看代码
void MX_USART3_UART_Init(void)
{
huart3.Instance = USART3;
huart3.Init.BaudRate = 9600;
huart3.Init.WordLength = UART_WORDLENGTH_8B;
huart3.Init.StopBits = UART_STOPBITS_1;
huart3.Init.Parity = UART_PARITY_NONE;
huart3.Init.Mode = UART_MODE_TX_RX;
huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart3.Init.OverSampling = UART_OVERSAMPLING_16;
huart3.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
huart3.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
if (HAL_UART_Init(&huart3) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART3_Init 2 */
HAL_UART_Receive_IT(&huart3, &s_uart3_rxch, 1);
/* USER CODE END USART3_Init 2 */
}
点击查看代码
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART3)
{
if(g_uart3_bytes < sizeof(g_uart3_rxbuf))
{
g_uart3_rxbuf[g_uart3_bytes++] = s_uart3_rxch;
}
HAL_UART_Receive_IT(&huart3, &s_uart3_rxch, 1); // 启动下一次接收
}
}
- 初始化BC28模块
保证NB-IoT模块正常才能进行通信。
- 下面函数用于解析发送AT命令失败与否。(详细过程不做赘述)
int NBIOT_send_cmd(char* cmd, char *recvbuf, char* response, int timeout)
- 该函数用于发送AT指令,将NB模块注册联网(展示部分代码,其余命令类似)。
点击查看代码
int NBIoT_test(void)
{
int timeout = 500;
if(0 != NBIOT_send_cmd("AT\r\n", g_uart3_rxbuf,"OK\r\n", timeout))
{
printf("AT command test failed,try again...\r\n");
return -1;
}
printf("AT command is normal.\r\n");
}
- 上报数据
确保NB模块已经初始化完毕且连接上网后进行数据的上报。
点击查看代码
int send_data_tocloud(void)
{
char atcmd[256];
int timeout = 1000;
char *response="OK\r\n";
float temperature,humidity;
char hex1[9]={0};
char hex2[9]={0};
if(Dht11_sampledata(&temperature, &humidity)<0)
{
printf("error\n");
return -1;
}
float_to_hex(temperature,hex1);
float_to_hex(humidity,hex2);
printf("temp:%f %s humi:%f %s\r\n",temperature,hex1,humidity,hex2);
snprintf(atcmd, sizeof(atcmd),"AT+QLWULDATAEX=13,0200250008%s%s,0x0100\r\n", hex2, hex1);
if(!NBIOT_send_cmd(atcmd, g_uart3_rxbuf, response, timeout))
{
printf("send data successfully.\r\n");
}
else
{
printf("send data failed\r\n");
return -2;
}
- 登录云平台查看上报的温湿度