diff --git a/firmware/src/main.cpp b/firmware/src/main.cpp index 6c6a12d..a5b27fe 100644 --- a/firmware/src/main.cpp +++ b/firmware/src/main.cpp @@ -7,6 +7,7 @@ #include "keyboard.h" #include "encoder.h" #include "debug.h" +#include "timer.h" void setup() { setupDebug(); @@ -27,6 +28,8 @@ void loop() { // debugScanI2C(); // demoScreen(); + demoTimer(); + auto key = handleKeyboard(); if (key != KEY_NONE) { tick(); diff --git a/firmware/src/timer.cpp b/firmware/src/timer.cpp new file mode 100644 index 0000000..e0a2310 --- /dev/null +++ b/firmware/src/timer.cpp @@ -0,0 +1,46 @@ +#include + +#define DEMO_TRIGGER_MS 1500 + +void setupTimer() { + // Set up Timer 0 to trigger interrupt every 1ms + // Timer 0 is already used and configured by Arduino for millis() + // however it uses TOIE0 (overflow interrupt), so we'll use OCIE0A: + // When this bit is written to one, and the I-flag in the Status Register is set + // (interrupts globally enabled), the Timer/Counter0 Output Compare A Match interrupt is enabled + // The corresponding Interrupt Vector is executed when the OCF0A Flag, located in TIFR0, is set. + OCR0A = 0xAF; // any number is OK, it will trigger at some point during the counter + TIMSK0 |= _BV(OCIE0A); +} + +// incremented every DEMO_TRIGGER_MS by interrupt, +// read and decremented by main loop +volatile uint8_t timerEvents = 0; + +void demoTimer() { + bool shouldTrigger = false; + + noInterrupts(); + if (timerEvents > 0) { + timerEvents--; + shouldTrigger = true; + } + interrupts(); + + if (shouldTrigger) { + Serial.println("Timer tick!"); + } +} + +volatile uint16_t timerMillis = 0; + +// triggers every 1ms +ISR(TIMER0_COMPA_vect) { + timerMillis++; + if (timerMillis >= DEMO_TRIGGER_MS) { + timerMillis -= DEMO_TRIGGER_MS; + timerEvents++; + } + + // TODO: Add motor encoder reading, calculate required carriage offset, control stepper +} diff --git a/firmware/src/timer.h b/firmware/src/timer.h new file mode 100644 index 0000000..ba65974 --- /dev/null +++ b/firmware/src/timer.h @@ -0,0 +1,2 @@ +void setupTimer(); +void demoTimer();