// Test delays with delays being delays or something like that.
// 30 August 2023, by Koepel, Public Domain.
// Forum: https://forum.arduino.cc/t/delaymicroseconds-is-off-by-an-order-of-magnitude/1163575
// This Wokwi sketch: https://wokwi.com/projects/374490739256465409
//
const int pulsePin = 13;
void setup()
{
pinMode(pulsePin, OUTPUT);
}
void loop()
{
// -------------------------------------------------
// Exactly 100 µs by using the clock cycles
// Result: always 100.000000 µs
// -------------------------------------------------
noInterrupts();
bitSet(PORTB, 7);
__builtin_avr_delay_cycles(1600-2); // minus 2 for setting the pin
bitClear(PORTB, 7);
interrupts();
delay(1);
// -------------------------------------------------
// The common AVR delay
// Result: 105.313 µs
// -------------------------------------------------
noInterrupts();
digitalWrite(pulsePin, HIGH);
_delay_us(100);
digitalWrite(pulsePin, LOW);
interrupts();
delay(1);
// -------------------------------------------------
// The Arduino delayMicroseconds
// Result: 104.062 µs
// -------------------------------------------------
noInterrupts();
digitalWrite(pulsePin, HIGH);
delayMicroseconds(100);
digitalWrite(pulsePin, LOW);
interrupts();
delay(1);
delay(10); // extra delay to easily identify the three pulses
}