陈拓 2021/05/06-2021/05/06
1. 概述
在《ESP8266_RTOS_SDK v3.x 读DS18B20温度数据》
https://zhuanlan.zhihu.com/p/370007889
https://blog.csdn.net/chentuo2000/article/details/116448392
一文中由于ESP8266 RTOS SDK 3.4之前版本的printf函数不支持浮点,输出部分采用了以前单片机的方法。
ESP8266 RTOS SDK 3.4现在支持浮点输出了。
之前的SDK为了节省RAM和Flash占用,采用gcc小型化C库 NewLib nano,不支持浮点数。
2. 更新ESP8266 RTOS SDK
git pull
ESP8266 RTOS SDK已经更新到v3.4。
3. 修改配置
- 项目配置
make menuconfig
make menuconfig > Component config > Newlib > [ ] Enable 'nano' formatting options for printf/scanf family 取消此项选择
保存Save,退出Exit。
4. 修改程序
主程序:
/* user_main.c */
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_spi_flash.h"
#include "driver/gpio.h"
#include "esp_system.h"
#include "ds18b20.h"
#define DQ GPIO_NUM_13 // GPIO13
/* 温度检测任务函数 */
uint8_t temp_s[8] = {' ','9','9','9','9','9','9','\0'};
void temp_task(void *arg)
{
uint8_t msb, lsb;
uint8_t temp0,temp1; // temp0温度的小数位,temp1温度的整数位
uint8_t sign; // sign判断温度符号
int temp, temp_d;
float temperature;
while (1) {
temp = ds18b20_read_temp(DQ);
printf("ds18b20 temp_raw: %d \n", temp);
lsb = (uint8_t)temp;
msb = (uint8_t)(temp >> 8);
// 转换18B20格式到十进制数
temp0 = lsb & 0x0f; // 取4位小数部分存放到temp0
temp1 = ((msb & 0x07)<<4)|((lsb>>4) & 0x0f); // 取7位整数部分存放到存放temp1
sign=(msb>>4==0X0F);
if(sign) { // MS Byte 的前面5位是符号位,同时为 0 或 1,这里只看高4位。如果值为负
temp0 = 16 - temp0; // 求补码(4位 1111=15)
temp1 = 128 - temp1; // 求补码(7位 1111111=127)
}
temp_d = temp1 * 16 + temp0; // 十六进制转换为10进制
temperature = temp_d * 0.0625;
// 添加符号
if(sign) {
temperature = -1 * temperature;
}
printf("ds18b20 temp value -> %.2f°C\r\n", temperature);
vTaskDelay(pdMS_TO_TICKS(5000)); // 调用任务睡眠函数,延时5s
}
}
void app_main()
{
/* 定义gpio配置结构体 */
gpio_config_t io_conf;
/* 初始化gpio配置结构体 */
io_conf.pin_bit_mask = (1ULL << DQ); // 选择gpio
io_conf.intr_type = GPIO_INTR_DISABLE; // 禁用中断
io_conf.mode = GPIO_MODE_OUTPUT; // 设置为输出模式
io_conf.pull_down_en = 0; // 不用下拉模式
io_conf.pull_up_en = 0; // 不用上拉模式
/* 用给定的设置配置GPIO */
gpio_config(&io_conf);
// 启动读温度任务
xTaskCreate(temp_task, "temp task", 2048, NULL, 10, NULL);
}
5. 编译烧写
- 编译
make
和不启用浮点相比较,RAM占用有增加,编译后Bin文件Flash占用有增加。
有兴趣可以比较增加各增加了多少。
- 烧写
make flash
6. 运行测试