main/task_temp.c

Mon, 17 Apr 2023 16:20:58 +0200

author
Michiel Broek <mbroek@mbse.eu>
date
Mon, 17 Apr 2023 16:20:58 +0200
changeset 32
84e54b14e7db
permissions
-rw-r--r--

Version 0.4.1 Measure internal chip temperature, range -10 to 80. Result available in mqtt json payload.

/**
 * @file task_temp.c
 * @brief The FreeRTOS task to query the temperature sensor.
 */


#include "config.h"


static const char		*TAG = "task_temp";

SemaphoreHandle_t		xSemaphoreTEMP = NULL;	///< Semaphore TEMP task
EventGroupHandle_t		xEventGroupTEMP;		///< Events TEMP task
TEMP_State			*temp_state;			///< Public state for other tasks

const int TASK_TEMP_REQUEST_DONE = BIT0;			///< All requests are done.
const int TASK_TEMP_REQUEST_TEMP = BIT1;			///< Request Temperature and Barometer



void request_temp(void)
{
    xEventGroupClearBits(xEventGroupTEMP, TASK_TEMP_REQUEST_DONE);
    xEventGroupSetBits(xEventGroupTEMP, TASK_TEMP_REQUEST_TEMP);
}



bool ready_temp(void)
{
    if (xEventGroupGetBits(xEventGroupTEMP) & TASK_TEMP_REQUEST_DONE)
	return true;
    return false;
}


/*
 * Task to read the chip temperature sensor on request.
 */
void task_temp(void *pvParameter)
{
    float	tsens_value;
    int		error = 0;

    ESP_LOGI(TAG, "Starting task temperature");
    temp_state = malloc(sizeof(TEMP_State));

    temp_state->valid = false;
    temp_state->error = TEMP_ERR_NONE;

    temperature_sensor_handle_t temp_sensor = NULL;
    temperature_sensor_config_t temp_sensor_config = TEMPERATURE_SENSOR_CONFIG_DEFAULT(-10, 80);
    ESP_ERROR_CHECK(temperature_sensor_install(&temp_sensor_config, &temp_sensor));

    /* event handler and event group for this task */
    xEventGroupTEMP = xEventGroupCreate();
    EventBits_t uxBits;

    /*
     * Task loop forever.
     */
    while (1) {

	uxBits = xEventGroupWaitBits(xEventGroupTEMP, TASK_TEMP_REQUEST_TEMP, pdFALSE, pdFALSE, portMAX_DELAY );
	if (uxBits & TASK_TEMP_REQUEST_TEMP) {

	    ESP_ERROR_CHECK(temperature_sensor_enable(temp_sensor));
	    error = temperature_sensor_get_celsius(temp_sensor, &tsens_value);
	    ESP_ERROR_CHECK(temperature_sensor_disable(temp_sensor));

	    if (xSemaphoreTake(xSemaphoreTEMP, 25) == pdTRUE) {
		if (error == ESP_OK) {
		    temp_state->error = TEMP_ERR_NONE;
		    temp_state->valid = true;
		    temp_state->temperature = tsens_value;
		} else {
		    temp_state->error = TEMP_ERR_READ;
		    temp_state->valid = false;
		    temp_state->temperature = 0;
		}
		xSemaphoreGive(xSemaphoreTEMP);
	    }

	    xEventGroupClearBits(xEventGroupTEMP, TASK_TEMP_REQUEST_TEMP);
	    xEventGroupSetBits(xEventGroupTEMP, TASK_TEMP_REQUEST_DONE);
#if 0
	    ESP_LOGI(TAG, "  TEMP: %.3f C, error: %d", temp_state->temperature, temp_state->error);
#endif
	}
    }
}

mercurial