#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/timer.h"
const uint SEGMENTS[8] = {0, 1, 2, 3, 4, 5, 6, 7}; //
const uint DIGITS[4] = {8, 9, 10, 11};
const uint BUTTONS[4] = {12, 13, 14, 15}; // Start/Stop, Set, Increase, Reset
// Button states
volatile bool button_pressed[4] = {false, false, false, false};
volatile bool running = false;
volatile uint digits[4] = {0, 0, 0, 0};
volatile int selected_digit = -1;
volatile bool blink = false;
const uint SEGMENT_MAP[10] = {
0b00111111, // 0
0b00000110, // 1
0b01011011, // 2
0b01001111, // 3
0b01100110, // 4
0b01101101, // 5
0b01111101, // 6
0b00000111, // 7
0b01111111, // 8
0b01101111 // 9
};
void update_display(volatile uint digits[4]);
bool timer_callback(struct repeating_timer *t);
void button_callback(uint gpio, uint32_t events);
void setup_gpio();
void process_buttons();
int main() {
stdio_init_all();
setup_gpio();
struct repeating_timer timer;
add_repeating_timer_ms(100, timer_callback, NULL, &timer);
while (1) {
process_buttons();
update_display(digits);
}
}
void setup_gpio() {
for (int i = 0; i < 8; i++) {
gpio_init(SEGMENTS[i]);
gpio_set_dir(SEGMENTS[i], GPIO_OUT);
}
for (int i = 0; i < 4; i++) {
gpio_init(DIGITS[i]);
gpio_set_dir(DIGITS[i], GPIO_OUT);
gpio_init(BUTTONS[i]);
gpio_set_dir(BUTTONS[i], GPIO_IN);
gpio_pull_up(BUTTONS[i]);
gpio_set_irq_enabled_with_callback(BUTTONS[i], GPIO_IRQ_EDGE_FALL, true, button_callback);
}
}
void button_callback(uint gpio, uint32_t events) {
for (int i = 0; i < 4; i++) {
if (gpio == BUTTONS[i]) {
button_pressed[i] = true;
break;
}
}
}
bool timer_callback(struct repeating_timer *t) {
static uint blink_counter = 0;
if (running) {
digits[0]++;
for (int i = 0; i < 3; i++) {
if (digits[i] >= 10) {
digits[i] = 0;
digits[i + 1]++;
}
}
if (digits[3] >= 10) {
digits[3] = 0;
}
}
blink_counter++;
if (blink_counter >= 5) {
blink = !blink;
blink_counter = 0;
}
return true;
}
void process_buttons() {
if (button_pressed[0]) {
running = !running;
button_pressed[0] = false;
}
if (button_pressed[1]) {
selected_digit = (selected_digit + 1) % 4;
button_pressed[1] = false;
}
if (button_pressed[2] && selected_digit != -1) {
digits[selected_digit] = (digits[selected_digit] + 1) % 10;
button_pressed[2] = false;
}
if (button_pressed[3]) {
running = false;
for (int i = 0; i < 4; i++) {
digits[i] = 0;
}
selected_digit = -1;
button_pressed[3] = false;
}
}
void update_display(volatile uint digits[4]) {
for (int i = 0; i < 4; i++) {
if (i == selected_digit && blink) {
for (int j = 0; j < 7; j++) {
gpio_put(SEGMENTS[j], 0);
}
} else {
uint digit = digits[i];
for (int j = 0; j < 7; j++) {
gpio_put(SEGMENTS[j], (SEGMENT_MAP[digit] >> j) & 1);
}
}
if (i == 1) {
gpio_put(SEGMENTS[7], 1);
} else {
gpio_put(SEGMENTS[7], 0);
}
gpio_put(DIGITS[3 - i], 0);
sleep_ms(5);
gpio_put(DIGITS[3 - i], 1);
}
}
Loading
pi-pico-w
pi-pico-w