So I have been beating my head against a wall for week now trying to figure a workaround for this. Nothing I have tried has worked reliably. I have tried validating the pulse length but as the falling edge interrupt can happen at any time, my validation routine doesn’t always catch it. I have also tried using the pulseIn() function but as it is a blocking function, it messes up some other timing in my program.
I have found that yes, there is (or was) a bug in the micros() function and has been for some time although for most it seems to have been fixed. The consensus is, it is or was in the wiring.c file. Why my code works fine on a Pro Micro but not the SAMD21 is puzzling though.
I am more of a hack at this time and getting down to that level is way beyond my skillset at the moment.
I am using the latest IDE (2.3.2) on a Macbook. I did find another simpler code example that duplicates what I am trying to do but alas, it does the same thing.
https://roboticsbackend.com/arduino-pulsein-with-interrupts/
#define BUTTON_PIN 4
volatile unsigned long pulseInTimeBegin = micros();
volatile unsigned long pulseInTimeEnd = micros();
volatile bool newPulseDurationAvailable = false;
void buttonPinInterrupt() {
if (digitalRead(BUTTON_PIN) == HIGH) {
// start measuring
pulseInTimeBegin = micros();
} else {
// stop measuring
pulseInTimeEnd = micros();
newPulseDurationAvailable = true;
}
}
void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(BUTTON_PIN),
buttonPinInterrupt,
CHANGE);
}
void loop() {
if (newPulseDurationAvailable) {
newPulseDurationAvailable = false;
unsigned long pulseDuration = pulseInTimeEnd - pulseInTimeBegin;
if (pulseDuration > 1000) Serial.println(pulseDuration);
}
// do your other stuff here
}
I really would like to get this to work on the XIAO due to its smaller size.