I have simple code that works on a Pro Mini but not on an ATtiny402
I find the timers on the ATtiny402 incredibly complicated and I would be very grateful if someone could help me out before I lose all my hair.
I am receiving a block of 17 pulses of varying lengths (between 500 and 4000 microseconds) and I wish to measure and store the time between falling edges.
The code snippet below works perfectly on the ATmega328p (Pro Mini) without using timers or interrupts. It uses the micros() function to measure the time between falling edges.
It fails on the ATtiny402 (5V, 16MHz, UPDI programming, megaTinyCore 2.0.1, IDE 2.3.6) with default micros() and millis() enabled. The data is almost correct but some pulse lengths are wrong.
My conclusion is that there is something funny with micros() on the ATtiny402.
So, I would like to try using falling edge interrupts and a timer to get the pulse length – but it is doing my head in trying to figure out what to set and use.
Can anyone help?
#define sensor 0 // Sensor on PA6
uint32_t pulselengths [20]; // Array to store pulse lengths
uint32_t pulsestart = 0; // Store time when pulse starts - falling edge
uint8_t pulsecount = 0; // Count of pulses
void setup() {
pinMode(sensor, INPUT);
}
void loop() {
while (digitalRead(sensor) == HIGH) {}; // Wait for sensor data line to go low at start of block
pulsestart = micros(); // Store current time to calculate pulse length
pulsecount = 0; // Count of pulses received
while (pulsecount < 17) {
while (digitalRead(sensor) == LOW) {}; // Wait for it to go high again
while (digitalRead(sensor) == HIGH) {}; // Wait for it to go low again.
pulselengths[pulsecount] = micros() - pulsestart;
pulsestart = micros();
pulsecount = pulsecount + 1;
}
}