#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/timer.h"
// GPIOs
#define RED_LED 13
#define GREEN_LED 11
#define BUTTON_PIN 15
// Estados do semáforo
enum State { RED, GREEN, YELLOW };
volatile enum State state = RED;
volatile int timer_counter = 0;
volatile bool pedestrian_request = false;
repeating_timer_t timer;
// Função para atualizar os LEDs conforme o estado
void update_lights() {
if (state == RED) {
gpio_put(RED_LED, 1);
gpio_put(GREEN_LED, 0);
} else if (state == GREEN) {
gpio_put(RED_LED, 0);
gpio_put(GREEN_LED, 1);
} else if (state == YELLOW) {
gpio_put(RED_LED, 1);
gpio_put(GREEN_LED, 1); // Amarelo = Vermelho + Verde
}
}
// Callback do temporizador, chamado a cada 1 segundo
bool timer_callback(repeating_timer_t *rt) {
timer_counter++;
if (pedestrian_request && state != RED) {
// Se botão foi pressionado, interrompe ciclo e vai pro amarelo
printf("Botão de Pedestres acionado\n");
state = YELLOW;
timer_counter = 0;
update_lights();
pedestrian_request = false;
return true;
}
switch (state) {
case RED:
if (timer_counter == 1) {
printf("Sinal: Vermelho\n");
}
if (timer_counter >= 10) {
state = GREEN;
timer_counter = 0;
printf("Sinal: Verde\n");
update_lights();
}
break;
case GREEN:
if (timer_counter >= 10) {
state = YELLOW;
timer_counter = 0;
printf("Sinal: Amarelo\n");
update_lights();
}
break;
case YELLOW:
if (timer_counter >= 3) {
state = RED;
timer_counter = 0;
printf("Sinal: Vermelho\n");
update_lights();
}
break;
}
return true; // continua rodando o timer
}
// Interrupção do botão de pedestre
void button_isr(uint gpio, uint32_t events) {
pedestrian_request = true;
}
int main() {
stdio_init_all();
gpio_init(RED_LED);
gpio_set_dir(RED_LED, GPIO_OUT);
gpio_put(RED_LED, 0);
gpio_init(GREEN_LED);
gpio_set_dir(GREEN_LED, GPIO_OUT);
gpio_put(GREEN_LED, 0);
gpio_init(BUTTON_PIN);
gpio_set_dir(BUTTON_PIN, GPIO_IN);
gpio_pull_up(BUTTON_PIN);
gpio_set_irq_enabled_with_callback(BUTTON_PIN, GPIO_IRQ_EDGE_FALL, true, &button_isr);
update_lights(); // inicia com vermelho
printf("Sinal: Vermelho\n");
// Temporizador chama callback a cada 1000ms (1s)
add_repeating_timer_ms(1000, timer_callback, NULL, &timer);
while (1) {
tight_loop_contents(); // Aguarda interrupções
}
}