// Franzininho WiFi ESP-IDF PWM Example
//
// https://wokwi.com/arduino/projects/324607736698372690
//
// Copyright (C) 2022, Anderson Costa
#include <math.h>
#include <stdio.h>
#include "driver/ledc.h"
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "hal/ledc_types.h"
#define LED_PWM_CHANNEL_1 LEDC_CHANNEL_1
#define LED_PWM_CHANNEL_2 LEDC_CHANNEL_2
#define LED_PWM_TIMER LEDC_TIMER_1
#define LED_PWM_BIT_NUM LEDC_TIMER_8_BIT
#define LED_PWM_PIN 15
void led_pwm_init(void)
{
ledc_channel_config_t ledc_channel1 = {0}, ledc_channel2 = {0};
ledc_channel1.gpio_num = LED_PWM_PIN;
ledc_channel1.speed_mode = LEDC_LOW_SPEED_MODE;
ledc_channel1.channel = LED_PWM_CHANNEL_1;
ledc_channel1.intr_type = LEDC_INTR_DISABLE;
ledc_channel1.timer_sel = LED_PWM_TIMER;
ledc_channel1.duty = 0;
ledc_timer_config_t ledc_timer;
ledc_timer.speed_mode = LEDC_LOW_SPEED_MODE;
ledc_timer.duty_resolution = LED_PWM_BIT_NUM;
ledc_timer.timer_num = LED_PWM_TIMER;
ledc_timer.freq_hz = 25000;
ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel1));
ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel2));
ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
}
void led_pwm_set(float duty_fraction)
{
uint32_t max_duty = (1 << LED_PWM_BIT_NUM) - 1;
uint32_t duty = lroundf(duty_fraction * (float)max_duty);
ESP_ERROR_CHECK(ledc_set_duty(LEDC_LOW_SPEED_MODE, LED_PWM_CHANNEL_1, duty));
ESP_ERROR_CHECK(ledc_update_duty(LEDC_LOW_SPEED_MODE, LED_PWM_CHANNEL_1));
}
extern "C" void app_main()
{
led_pwm_init();
while (1) {
// Increase the LED brightness
for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++) {
// Changing the LED brightness with PWM
led_pwm_set(dutyCycle);
vTaskDelay(3 / portTICK_PERIOD_MS);
}
// Decrease the LED brightness
for(int dutyCycle = 255; dutyCycle >= 0; dutyCycle--) {
// Changing the LED brightness with PWM
led_pwm_set(dutyCycle);
vTaskDelay(3 / portTICK_PERIOD_MS);
}
}
}
Loading
franzininho-wifi
franzininho-wifi