Skip to content

Instantly share code, notes, and snippets.

@rlcamp
Created May 30, 2025 18:30
Show Gist options
  • Select an option

  • Save rlcamp/1e49e9326a7854cd79e0e237e9bc8db4 to your computer and use it in GitHub Desktop.

Select an option

Save rlcamp/1e49e9326a7854cd79e0e237e9bc8db4 to your computer and use it in GitHub Desktop.
#include "hardware/sync.h"
#include "hardware/gpio.h"
#include "hardware/irq.h"
#include "hardware/timer.h"
#include "hardware/uart.h"
#include <stdio.h>
#define ALARM0 0
#define DELAY 1000000
int main() {
/* if commented out, and "wakes" is an _Atomic, all subsequent WFEs are inhibited */
// m33_hw->actlr &= ~M33_ACTLR_EXTEXCLALL_BITS;
/* enable sevonpend so that we don't need a nearly empty isr */
scb_hw->scr |= M33_SCR_SEVONPEND_BITS;
/* force clear event register */
__sev();
__wfe();
/* init LED */
gpio_init(PICO_DEFAULT_LED_PIN);
gpio_set_dir(PICO_DEFAULT_LED_PIN, GPIO_OUT);
/* enable uart */
gpio_set_function(0, UART_FUNCSEL_NUM(uart0, 0));
gpio_set_function(1, UART_FUNCSEL_NUM(uart0, 1));
uart_init(uart0, 115200);
uart_puts(uart0, "\r\nhello\r\n");
/* enable interrupt for alarm, but leave it disabled in nvic */
hw_set_bits(&timer_hw->inte, 1u << ALARM0);
irq_set_enabled(hardware_alarm_get_irq_num(ALARM0), false);
/* first tick will be one interval from now */
timer_hw->alarm[ALARM0] = timer_hw->timerawl + DELAY;
while (1) {
/* if this is an _Atomic, and EXTEXCLALL is left enabled, all WFEs are inhibited */
_Atomic unsigned wakes = 0;
/* wait for alarm to fire, with one wfe per condition check */
while (!(timer_hw->intr & (1U << ALARM0))) {
gpio_put(PICO_DEFAULT_LED_PIN, 0);
__wfe();
gpio_put(PICO_DEFAULT_LED_PIN, 1);
wakes++;
}
/* acknowledge and clear the interrupt in both timer and nvic */
hw_clear_bits(&timer_hw->intr, 1U << ALARM0);
irq_clear(hardware_alarm_get_irq_num(ALARM0));
/* increment and rearm */
timer_hw->alarm[ALARM0] += DELAY;
static char buf[64];
snprintf(buf, sizeof(buf), "wakes since last alarm: %u\r\n", wakes);
uart_puts(uart0, buf);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment