#include <pico/stdlib.h>
#include <pico/time.h>
// Pin definitions
#define RED_PIN 15
#define YELLOW_PIN 6
#define GREEN_PIN 4
// Timing constants (in milliseconds)
#define RED_DURATION 5000 // 5 seconds
#define YELLOW_DURATION 2000 // 2 seconds
#define GREEN_DURATION 5000 // 5 seconds
// States for the traffic light
enum TrafficState { RED, YELLOW, GREEN };
enum TrafficState currentState = RED;
// Timing variables
uint64_t lastStateChange = 0;
// Function to check if enough time has passed (non-blocking)
bool has_time_passed(uint64_t last_time, uint32_t interval_ms) {
return (time_us_64() / 1000) - last_time >= interval_ms;
}
void setup() {
// Initialize pins
gpio_init(RED_PIN);
gpio_init(YELLOW_PIN);
gpio_init(GREEN_PIN);
gpio_set_dir(RED_PIN, GPIO_OUT);
gpio_set_dir(YELLOW_PIN, GPIO_OUT);
gpio_set_dir(GREEN_PIN, GPIO_OUT);
// Initial state: Red ON, others OFF
gpio_put(RED_PIN, 1);
gpio_put(YELLOW_PIN, 0);
gpio_put(GREEN_PIN, 0);
}
int main() {
setup();
while (true) {
uint64_t currentTime = time_us_64() / 1000; // Convert to milliseconds
// Check if it's time to change state
switch (currentState) {
case RED:
if (has_time_passed(lastStateChange, RED_DURATION)) {
// Switch to Yellow
gpio_put(RED_PIN, 0);
gpio_put(YELLOW_PIN, 1);
gpio_put(GREEN_PIN, 0);
currentState = YELLOW;
lastStateChange = currentTime;
}
break;
case YELLOW:
if (has_time_passed(lastStateChange, YELLOW_DURATION)) {
// Switch to Green
gpio_put(RED_PIN, 0);
gpio_put(YELLOW_PIN, 0);
gpio_put(GREEN_PIN, 1);
currentState = GREEN;
lastStateChange = currentTime;
}
break;
case GREEN:
if (has_time_passed(lastStateChange, GREEN_DURATION)) {
// Switch to Red
gpio_put(RED_PIN, 1);
gpio_put(YELLOW_PIN, 0);
gpio_put(GREEN_PIN, 0);
currentState = RED;
lastStateChange = currentTime;
}
break;
}
}
return 0;
}