#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/pwm.h"
// Pin definitions and configurations
const uint LED_PIN = 13; // LED pin
const uint BTN_A_PIN = 5; // Button A pin
const uint BTN_B_PIN = 6; // Button B pin
const uint16_t PERIOD = 1000; // Period for 10 Hz
const float DIVIDER_PWM = 16.0; // PWM clock divider
volatile uint click_count = 0; // Click counter
volatile absolute_time_t last_press_time_a; // Stores the last press time of Button A
volatile absolute_time_t last_press_time_b; // Stores the last press time of Button B
volatile int led_frequency = 50; // Initial LED frequency (10 Hz)
// PWM setup function
void setup_pwm() {
uint slice = pwm_gpio_to_slice_num(LED_PIN);
gpio_set_function(LED_PIN, GPIO_FUNC_PWM);
pwm_set_clkdiv(slice, DIVIDER_PWM);
pwm_set_wrap(slice, PERIOD);
pwm_set_gpio_level(LED_PIN, 0); // LED initially off
pwm_set_enabled(slice, true); // Enable PWM
}
// Interrupt callback function for button press
void gpio_callback(uint gpio, uint32_t events) {
if (gpio == BTN_A_PIN && (events & GPIO_IRQ_EDGE_RISE)) {
absolute_time_t now = get_absolute_time();
if (absolute_time_diff_us(last_press_time_a, now) > 200000) { // Debounce: 200ms
last_press_time_a = now; // Update last press time
click_count++; // Increment click counter
}
} else if (gpio == BTN_B_PIN && (events & GPIO_IRQ_EDGE_RISE)) {
absolute_time_t now = get_absolute_time();
if (absolute_time_diff_us(last_press_time_b, now) > 200000) { // Debounce: 200ms
last_press_time_b = now; // Update last press time for Button B
led_frequency = (led_frequency == 50) ? 500 : 50;
if (led_frequency == 500) printf("Frequência alterada para 1Hz\n");
else printf("Frequência alterada para 10Hz\n");
}
}
}
// Function to blink the LED for 10 seconds at the set frequency
void blink_led_for_frequency() {
uint slice = pwm_gpio_to_slice_num(LED_PIN); // Get PWM slice
uint64_t start_time = to_ms_since_boot(get_absolute_time()); // Start time
while (to_ms_since_boot(get_absolute_time()) - start_time < 10000) { // Loop for 10 seconds
pwm_set_gpio_level(LED_PIN, PERIOD / 2); // 50% duty cycle (LED on)
sleep_ms(led_frequency); // Half period (50 ms on)
pwm_set_gpio_level(LED_PIN, 0); // 0% duty cycle (LED off)
sleep_ms(led_frequency); // Half period (50 ms off)
}
}
int main() {
stdio_init_all();
// Button configuration
gpio_init(BTN_A_PIN);
gpio_set_dir(BTN_A_PIN, GPIO_IN);
gpio_pull_down(BTN_A_PIN);
gpio_set_irq_enabled_with_callback(BTN_A_PIN, GPIO_IRQ_EDGE_RISE, true, &gpio_callback);
gpio_init(BTN_B_PIN);
gpio_set_dir(BTN_B_PIN, GPIO_IN);
gpio_pull_down(BTN_B_PIN);
gpio_set_irq_enabled_with_callback(BTN_B_PIN, GPIO_IRQ_EDGE_RISE, true, &gpio_callback);
// PWM setup
setup_pwm();
// Main loop
while (true) {
if (click_count == 5) {
printf("Botão pressionado 5 vezes\n");
click_count = 0; // Reset counter
blink_led_for_frequency(); // Blink the LED
}
sleep_ms(10); // Small delay to avoid loop overload
}
}
Loading
pi-pico-w
pi-pico-w