#include <stdio.h>
#include <math.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/adc.h"
// INÍCIO DA BIBLIOTECA DO LDR -------------------------------------------
#define ADC_1 1
#define ADC_2 2
typedef struct {
uint8_t adc_device;
uint8_t adc_channel;
float k1;
float k2;
} ldr_handle_t;
float ldr_get_illuminance(ldr_handle_t * ldr) {
if (ldr->adc_device == ADC_2) {
int buffer;
adc2_get_raw(ldr->adc_channel, ADC_WIDTH_BIT_12, &buffer);
return ldr->k1 + ldr->k2 * log((4096.0 / buffer) - 1);
}
else {
return ldr->k1 + ldr->k2 * log((4096.0 / adc1_get_raw(ldr->adc_channel)) - 1);
}
}
// FIM DA BIBLIOTECA DO LDR ----------------------------------------------
void app_main() {
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(ADC1_CHANNEL_7, ADC_ATTEN_DB_11);
ldr_handle_t ldr = {
.adc_device = ADC_1,
.adc_channel = ADC1_CHANNEL_7,
.k1 = 49.95095,
.k2 = 10.34034
};
while (true) {
printf("Iluminância: %.1f%%\n", ldr_get_illuminance(&ldr));
printf("--------------------\n");
vTaskDelay(2000 / portTICK_PERIOD_MS);
}
}