#include "pico/stdlib.h"
#include "stdio.h"
#include "hardware/pwm.h"
#define BUTTON_A_PIN 5
#define BUTTON_B_PIN 6
#define LED_RED 11
#define BLINK_DURATION 10000 // Duração total do LED piscando (10 segundos)
volatile uint counter = 0;
volatile bool in_cycle_active = false;
void led_blink(uint hertz)
{
gpio_set_function(LED_RED, GPIO_FUNC_PWM);// Define o GPIO como um PWM
uint wrap = (125000000 / hertz) - 1; // Fórmula para calcular o Wrap
uint slice = pwm_gpio_to_slice_num(LED_RED);
pwm_set_wrap(slice, wrap);
pwm_set_gpio_level(LED_RED, wrap / 2);
pwm_set_clkdiv(slice, 1.0);
pwm_set_enabled(slice, true);
}
void stop_blink()
{
uint slice = pwm_gpio_to_slice_num(LED_RED);
pwm_set_enabled(slice, false); // Desativa o PWM
gpio_set_function(LED_RED, GPIO_FUNC_SIO); // Redefine o GPIO como saída
gpio_put(LED_RED, 0); // Garante que o LED está apagado
}
void init_gpio()
{
// Botão A
gpio_init(BUTTON_A_PIN);
gpio_set_dir(BUTTON_A_PIN, GPIO_IN);
gpio_pull_up(BUTTON_A_PIN);
// Botão B
gpio_init(BUTTON_B_PIN);
gpio_set_dir(BUTTON_B_PIN, GPIO_IN);
gpio_pull_up(BUTTON_B_PIN);
}
void button_callback(uint gpio, uint32_t events)
{
static absolute_time_t last_time = 0;
absolute_time_t now = get_absolute_time();
if (absolute_time_diff_us(last_time, now) > 200000 && events == GPIO_IRQ_EDGE_RISE) // Debouncing
{
if (gpio == BUTTON_A_PIN && !in_cycle_active)
{
last_time = now;
counter++;
}
if (gpio == BUTTON_B_PIN && in_cycle_active)
{
last_time = now;
led_blink(1); // Aplica a nova frequência
printf("Led alterado para 1 Hz\n");
}
}
}
int main()
{
// Entrada e Saida de dados
stdio_init_all();
init_gpio();
// Interruções
gpio_set_irq_enabled_with_callback(BUTTON_A_PIN, GPIO_IRQ_EDGE_RISE, true, &button_callback);
gpio_set_irq_enabled_with_callback(BUTTON_B_PIN, GPIO_IRQ_EDGE_RISE, true, &button_callback);
while (true)
{
if (counter >= 1 && counter < 5)
{
printf("O contador é: %d \n", counter);
sleep_ms(100);
}
else if (counter >= 5) // Quando o botão é pressionado 5 vezes
{
printf("LED piscando por 10 segundos a 10 Hz\n");
led_blink(10); // Inicia o PWM para piscar o LED
in_cycle_active = true;
absolute_time_t start_time = get_absolute_time();
while (absolute_time_diff_us(start_time, get_absolute_time()) < BLINK_DURATION * 1000 && in_cycle_active) // Conta 10 segundos
{
uint seconds = absolute_time_diff_us(start_time, get_absolute_time()) / 1000000.0; // Pega os segundos
printf("Segundos: %d !\n", seconds);
sleep_ms(100);
}
printf("Tempo parou !\n");
stop_blink();
counter = 0;
in_cycle_active = false;
}
sleep_ms(100);
}
return 0;
}