#include <stdio.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/adc.h"
#include "driver/ledc.h"
#include "esp_adc_cal.h"
#include "esp_log.h"
#define POTENTIOMETER_ADC_CHANNEL ADC_CHANNEL_4 // GPIO4
#define LEDC_OUTPUT_IO 5 // GPIO5
#define LEDC_TIMER LEDC_TIMER_0
#define LEDC_MODE LEDC_HIGH_SPEED_MODE
#define LEDC_CHANNEL LEDC_CHANNEL_0
#define LEDC_DUTY_RES LEDC_TIMER_10_BIT // Resolução de 10 bits (0-1023)
#define LEDC_FREQUENCY 5000 // 5 kHz
void app_main(void)
{
// 1. Configurar o ADC
adc_unit_t adc_unit = ADC_UNIT_1;
adc_oneshot_unit_handle_t adc_handle;
adc_oneshot_unit_init_cfg_t init_config = {
.unit_id = adc_unit,
};
adc_oneshot_new_unit(&init_config, &adc_handle);
adc_oneshot_chan_cfg_t channel_config = {
.atten = ADC_ATTEN_DB_11, // Para leitura até ~3.3V
.bitwidth = ADC_BITWIDTH_12
};
adc_oneshot_config_channel(adc_handle, POTENTIOMETER_ADC_CHANNEL, &channel_config);
// 2. Configurar PWM (LEDC)
ledc_timer_config_t ledc_timer = {
.speed_mode = LEDC_MODE,
.duty_resolution = LEDC_DUTY_RES,
.timer_num = LEDC_TIMER,
.freq_hz = LEDC_FREQUENCY,
.clk_cfg = LEDC_AUTO_CLK
};
ledc_timer_config(&ledc_timer);
ledc_channel_config_t ledc_channel = {
.speed_mode = LEDC_MODE,
.channel = LEDC_CHANNEL,
.timer_sel = LEDC_TIMER,
.intr_type = LEDC_INTR_DISABLE,
.gpio_num = LEDC_OUTPUT_IO,
.duty = 0,
.hpoint = 0
};
ledc_channel_config(&ledc_channel);
while (1) {
// 3. Ler valor do potenciômetro
int adc_reading = 0;
adc_oneshot_read(adc_handle, POTENTIOMETER_ADC_CHANNEL, &adc_reading);
// 4. Converter leitura para PWM duty
uint32_t duty = (adc_reading * 1023) / 4095;
// 5. Atualizar PWM
ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, duty);
ledc_update_duty(LEDC_MODE, LEDC_CHANNEL);
printf("ADC: %d -> Duty: %d\n", adc_reading, duty);
vTaskDelay(pdMS_TO_TICKS(100));
}
}