#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "math.h"
#include "driver/adc.h" //Required for ADC functions.
float readTemperature(adc1_channel_t channel, float nominalRes, float B); // Function declaration for reading temperature.
void app_main()
{
adc1_config_width(ADC_WIDTH_BIT_12); // Set 12-bit ADC resolution (0–4095), it wasn't working when I tried to set it to 10.
// GPIO4 is ADC1 channel 3, input voltage up to ~3.3V
adc1_config_channel_atten(ADC1_CHANNEL_3, ADC_ATTEN_DB_11);
while (1)
{
float tempC = readTemperature(ADC1_CHANNEL_3, 10000.0f, 3950.0f); // Calling the function to read the temperature from the thermistor in celsius.
printf("Temperature: %.2f°\n", tempC); // Print the value of celsius which is returned from the function.
vTaskDelay(pdMS_TO_TICKS(500));
}
}
/* Function Name - readTemperature
* Description - This function produces a printed output of a temperature reading in celsius of the thermistor.
* Return type - The return type is float, which returns through the "celsius" variable.
* Parameters -
- parameter1 - adc1_channel_t channel: Indicates the channel to read the raw voltage from.
- parameter2 - nominalRes: Nominal resistance of the thermistor R.
- parameter3 - B: Thermal index B of the thermistor.
*/
// Function definition for reading the temperature from the thermistor.
float readTemperature(adc1_channel_t channel, float nominalRes, float B)
{
int adc_value_12bit = adc1_get_raw(channel); // Take the raw voltage and store it as an ADC value in a variable.
int adc_value_10bit = adc_value_12bit >> 2; // Take the 12-bit ADC value and right shift it so it becomes a 10-bit value.
float VRT = adc_value_10bit * 3.3f / 1023.0f; // Vref = 3.3V and 1023 is max ADC value for a 10-bit resolution.
float R = nominalRes;
float R2 = nominalRes;
float RT = R2 * VRT / (3.3f - VRT);
float T1 = 25.0f + 273.15f;
float T2 = 1.0f / ((1.0f / T1) + (logf(RT / R) / B));
float celsius = T2 - 273.15f;
return celsius; // Return the value to tempC.
}