board/main/temperature.c

78 lines
2.7 KiB
C
Raw Normal View History

#include <stdio.h>
#include <stdlib.h>
#include "driver/i2c.h"
#include "embedded_display.c"
#include "esp_log.h"
#include "i2c.c"
#define ACK_CHECK_EN 0x1 /*!< I2C master will check ack from slave*/
#define ACK_CHECK_DIS 0x0 /*!< I2C master will not check ack from slave */
#define ACK_VAL 0x0 /*!< I2C ack value */
#define NACK_VAL 0x1 /*!< I2C nack value */
#define GX21M15_TEMP_POINTER_VALUE 0b00 // 温度寄存器
#define GX21M15_CONF_POINTER_VALUE 0b01 // 配置寄存器
#define GX21M15_THYST_POINTER_VALUE 0b10 // 回滞寄存器
#define GX21M15_TOS_POINTER_VALUE 0b11 // 过温关断寄存器
#define DEFAULT_TEMPERATURE -999 // 过温关断寄存器
#define TEMPERATURE_TAG "temperature"
void fetch_temperature(void* arg) {
esp_err_t error;
float temperature = DEFAULT_TEMPERATURE;
2023-04-24 17:47:37 +08:00
char temperature_str[20];
uint8_t temperature_buffer[] = {0, 0};
display_fill_rect(0, 0, 128, 2, 0x00);
for (;;) {
i2c_cmd_handle_t cmd = i2c_cmd_link_create();
i2c_master_start(cmd);
2023-03-04 16:24:35 +08:00
i2c_master_write_byte(cmd, GX21M15_ADDRESS << 1 | I2C_MASTER_WRITE,
ACK_CHECK_EN);
i2c_master_write_byte(cmd, 0, ACK_CHECK_EN);
i2c_master_start(cmd);
2023-03-04 16:24:35 +08:00
i2c_master_write_byte(cmd, GX21M15_ADDRESS << 1 | I2C_MASTER_READ, ACK_VAL);
i2c_master_read_byte(cmd, &(temperature_buffer[0]), ACK_VAL);
i2c_master_read_byte(cmd, &(temperature_buffer[1]), NACK_VAL);
i2c_master_stop(cmd);
error =
i2c_master_cmd_begin(I2C_MASTER_NUM, cmd, 1000 / portTICK_PERIOD_MS);
i2c_cmd_link_delete(cmd);
if (error != ESP_OK) {
ESP_LOGW(TEMPERATURE_TAG, "read failed. %x", error);
} else {
if (temperature_buffer[0] == 0xff) {
if (temperature == DEFAULT_TEMPERATURE) {
sprintf(temperature_str, "Temp: Loading");
} else {
sprintf(temperature_str, "Temp: %.3f.", temperature);
}
} else {
if (temperature_buffer[0] >> 7) {
temperature = -(((((~temperature_buffer[0]) & 0x7f) << 3) |
((~temperature_buffer[1] >> 5) & 0x07)) +
1) *
0.125;
} else {
temperature =
(temperature_buffer[0] << 3 | temperature_buffer[1] >> 5) * 0.125;
}
sprintf(temperature_str, "Temp: %2.3f", temperature);
}
display_print8_str(8, 0, temperature_str);
}
vTaskDelay(pdMS_TO_TICKS(2000));
}
display_fill_rect(0, 0, 128, 2, 0x00);
}
void auto_fetch_temperature() {
2023-03-04 16:24:35 +08:00
if (is_temperature_online == 0) {
ESP_LOGW(TEMPERATURE_TAG, "temperature is offline");
return;
}
2023-02-24 21:29:15 +08:00
ESP_LOGI(TEMPERATURE_TAG, "auto_fetch_temperature");
xTaskCreate(fetch_temperature, "temperature", 2048, NULL, 10, NULL);
}