/*
* Projeto: Piscar LED com botão - Raspberry Pi Pico
* Descrição: Este código faz um LED piscar a 10 Hz durante 10 segundos
* após o botão ser pressionado 5 vezes.
* Desenvolvido por: Rafael Sousa
* Data: Janeiro de 2025
*/
#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/cyw43_arch.h"
#include "hardware/timer.h"
#define LED_PIN 13
#define BTN_PIN 5
volatile int btn_press_count = 0;
volatile bool blinking = false; // Variável de controle para o estado de piscar
uint64_t blink_start_time = 0; // Tempo inicial para o ciclo de piscar
const uint PERIOD = 200; // Frequência de 10 Hz (100 ms)
int64_t turn_off_callback(alarm_id_t, void *user_data) {
gpio_put(LED_PIN, false); // Desliga o LED
blinking = false; // Para o ciclo de piscar
printf("\nLED DESLIGADO\n");
return 0;
}
bool manages_led(struct repeating_time *t) {
static absolute_time_t last_press_time = 0;
static bool btn_last_state = false;
bool btn_pressed = !gpio_get(BTN_PIN); // Verifica o estado do botão
// Verifica se o botão foi pressionado
if (btn_pressed && !btn_last_state && absolute_time_diff_us(last_press_time, get_absolute_time()) > 200000) {
last_press_time = get_absolute_time();
btn_last_state = true;
btn_press_count++;
printf("%d\t", btn_press_count);
if (btn_press_count == 5 && !blinking) {
// Quando o botão for pressionado 5 vezes, começa a piscar o LED
blinking = true;
btn_press_count = 0; // Zera a contagem do botão
blink_start_time = to_ms_since_boot(get_absolute_time()); // Inicia o tempo de piscar
printf("\nIniciando o piscar do LED por 10 segundos a 10 Hz\n");
// Define o alarme para desligar o LED após 10 segundos
add_alarm_in_ms(10000, turn_off_callback, NULL, false);
}
}
else if (!btn_pressed) {
btn_last_state = false; // Reseta o estado do botão quando ele não está pressionado
}
// Verifica se o LED deve piscar
if (blinking) {
uint64_t current_time = to_ms_since_boot(get_absolute_time());
if ((current_time - blink_start_time) % PERIOD < (PERIOD / 2)) {
gpio_put(LED_PIN, true); // Liga o LED
} else {
gpio_put(LED_PIN, false); // Desliga o LED
}
}
return true;
}
int main() {
stdio_init_all();
gpio_init(LED_PIN); // Inicializa o pino do LED
gpio_set_dir(LED_PIN, GPIO_OUT); // Configura como saída
gpio_put(LED_PIN, 0); // Desliga o LED inicialmente
gpio_init(BTN_PIN); // Inicializa o pino do botão
gpio_set_dir(BTN_PIN, GPIO_IN); // Configura como entrada
gpio_pull_up(BTN_PIN); // Habilita o resistor pull-up
struct repeating_timer timer;
add_repeating_timer_ms(100, manages_led, NULL, &timer); // Verifica o botão a cada 100 ms
while (true) {
// O loop principal pode ser usado para outras tarefas
tight_loop_contents(); // Mantém a CPU ocupada com outras tarefas
}
}