#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_adc/adc_oneshot.h"
#include <math.h>
#define NUM_SAMPLES 128
float ntc_to_temperature(int adc_raw)
{
const float B = 3950.0;
const float R0 = 10000.0;
const float T0 = 298.15;
float k = (float)adc_raw / 4095.0;
float voltage = k * 3.3;
float r_ntc = R0 * voltage / (3.3 - voltage);
float inverse_temperature = 1.0 / T0 + log(r_ntc / R0) / B;
float temperature = 1.0 / inverse_temperature;
return temperature - 273.15;
}
void app_main(void)
{
printf("Hello, Wokwi!\n");
adc_oneshot_unit_handle_t adc1_handle;
adc_oneshot_unit_init_cfg_t init_config1 = {
.unit_id = ADC_UNIT_1,
.ulp_mode = ADC_ULP_MODE_DISABLE,
};
ESP_ERROR_CHECK(
adc_oneshot_new_unit(&init_config1, &adc1_handle)
);
adc_oneshot_chan_cfg_t config = {
.bitwidth = ADC_BITWIDTH_DEFAULT,
.atten = ADC_ATTEN_DB_12,
};
ESP_ERROR_CHECK(
adc_oneshot_config_channel(
adc1_handle,
ADC_CHANNEL_3,
&config
)
);
while (true) {
int adc_raw;
long sum = 0;
for (int i = 0; i < NUM_SAMPLES; i++) {
ESP_ERROR_CHECK(
adc_oneshot_read(
adc1_handle,
ADC_CHANNEL_3,
&adc_raw
)
);
sum += adc_raw;
}
int adc_avg = sum / NUM_SAMPLES;
float temp = ntc_to_temperature(adc_avg);
printf("ADC avg: %d | Temperature: %.2f C\n", adc_avg, temp);
vTaskDelay(pdMS_TO_TICKS(100));
}
}