To see if I could go without the complicated hardware timers, I ran a test ramping up a stepper to 100us period step speeds and this worked absolutely fine without using hardware interrupts.
One strange I thing I noticed: if I break the serial USB connection my timing seems to go wrong completely..
Here's a minimal example of the serial issue, tested on Teensy4.0 :
Code:
uint32_t lastTime = micros(); // keep track of time for LED blinking
uint32_t period = 100;
int timingError = 0;
uint32_t serialLastTime = millis(); // keep track of time for serial feedback
uint32_t serialPeriod = 200;
//---------------------------------------------------------------------------------------------------------------------
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
while (!Serial) {
// wait for serial to come up
}
Serial.begin(57600);
Serial.println(
"I am testing if serial connect / disconnect messes up my timing");
serialLastTime = millis();
lastTime = micros();
}
//---------------------------------------------------------------------------------------------------------------------
void loop() {
uint32_t nowUs = micros();
if (nowUs >= lastTime + period) {
timingError += abs((int)(nowUs - lastTime) - (int)period);
lastTime += period;
// briefly flash the LED
digitalWrite(LED_BUILTIN, HIGH);
delayMicroseconds((int)period / 2);
digitalWrite(LED_BUILTIN, LOW);
}
uint32_t now = millis();
if (now >= serialLastTime + serialPeriod && Serial) {
// if (now >= serialLastTime + serialPeriod ) {
// creates visible pulses with LED staying OFF
serialLastTime = now;
Serial.println(timingError);
timingError = 0; // reset timing error
}
}
This will print out zeroes every 100ms, except when I disconnect and reconnect the Serial port..
The version where I keep sending serial messages even when there's no serial port is significantly worse:
Code:
if (now >= serialLastTime + serialPeriod ) {
instead of
Code:
if (now >= serialLastTime + serialPeriod && Serial) {
What could be going on?