#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"

const int LED_PIN = 5;
const int BTN_PIN = 28; 

volatile int g_flag_r = 0;

void btn_callback(uint gpio, uint32_t events) {
    if (gpio == BTN_PIN) {     
        g_flag_r = 1;
    }
}

volatile int g_timer_0 = 0;

bool timer_0_callback(repeating_timer_t *rt) {
    g_timer_0 = 1;
    return true; // keep repeating
}


int main() {
    stdio_init_all();

    gpio_init(LED_PIN);
    gpio_set_dir(LED_PIN, GPIO_OUT);

    gpio_init(BTN_PIN);
    gpio_set_dir(BTN_PIN, GPIO_IN);
    gpio_pull_up(BTN_PIN);


    gpio_set_irq_enabled_with_callback(BTN_PIN,
                                     GPIO_IRQ_EDGE_FALL,
                                     true,
                                     &btn_callback);

    int led_state = 0;
    int alarm_state = 0;
    int timer_0_hz = 5;
    repeating_timer_t timer_0;

    while (true) {
      if(g_flag_r) {
        if (alarm_state == 0){
            if (!add_repeating_timer_us(1000000 / timer_0_hz, 
                                        timer_0_callback,
                                        NULL, 
                                        &timer_0)) {
                printf("Failed to add timer\n");
            }
            alarm_state = 1;
        } else {
          gpio_put(LED_PIN, 0);
          cancel_repeating_timer(&timer_0);
          alarm_state = 0;
        }
        g_flag_r = 0;

      }

      if (g_timer_0) {
          led_state = !led_state;
          gpio_put(LED_PIN, led_state);
          g_timer_0 = 0;
      }
    }
}