47 lines
1.3 KiB
C++
47 lines
1.3 KiB
C++
#include <Arduino.h>
|
|
|
|
#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
|
|
}
|