#include <stdio.h> //provides printf function
#include "pico/stdlib.h" //provides standard library for the pico
#include "hardware/timer.h" //provides timer registers
#include "hardware/irq.h" //provides irq registers
// Simplest form of getting 64 bit time from the timer.
// It isn't safe when called from 2 cores because of the latching
// so isn't implemented this way in the sdk
static uint64_t get_time(void) {
// Reading low latches the high value
uint32_t lo = timer_hw->timelr;
uint32_t hi = timer_hw->timehr;
return ((uint64_t) hi << 32u) | lo;
}
#if PICO_TIME_DEFAULT_ALARM_POOL_DISABLED
#error boom
#endif
// Forward declaration
static void alarm_in_us(uint32_t delay_us);
// Use alarm 0
#define ALARM_NUM 0
#define ALARM_IRQ TIMER_IRQ_0
#define ALARM_SECOND 1000000L
uint64_t randomWait() {
// Wait between 1 and 4 seconds
return ALARM_SECOND + ((rand() * UINT32_MAX) % (ALARM_SECOND*3));
}
// Alarm interrupt handler
static void alarm_irq(void) {
// Clear the alarm irq
hw_clear_bits(&timer_hw->intr, 1u << ALARM_NUM);
uint64_t sleepy=randomWait();
uint64_t now=time_us_64();
// Assume alarm 0 has fired
printf("%9llu ms Timer 0 fired!, will fire again in %0.3f\n", now/1000,sleepy/(float)ALARM_SECOND);
alarm_in_us(sleepy);
}
// Set alarm
static void alarm_in_us(uint32_t delay_us) {
// Enable the interrupt for our alarm (the timer outputs 4 alarm irqs)
hw_set_bits(&timer_hw->inte, 1u << ALARM_NUM);
// Set irq handler for alarm irq
irq_set_exclusive_handler(ALARM_IRQ, alarm_irq);
// Enable the alarm irq
irq_set_enabled(ALARM_IRQ, true);
// Enable interrupt in block and at processor
// Alarm is only 32 bits so if trying to delay more
// than that need to be careful and keep track of the upper
// bits
uint64_t target = timer_hw->timerawl + delay_us;
// Write the lower 32 bits of the target time to the alarm which
// will arm it
timer_hw->alarm[ALARM_NUM] = (uint32_t) target;
}
int main() {
stdio_init_all();
printf("Hello Timer! (Low Level)\n");
alarm_in_us(ALARM_SECOND << 1); //2 second alarm
while (1) {
sleep_ms(1000);
}
}