Bug in digitalReadFast()

yoonghm

Active member
If you make the built-in LED to blink 5 times, it will blink 3 instead, then blink the external LED, followed by another 2 blinks on the built-in LED.

If you make the built-in LED to blink 6 times, it will blink 3 instead, then blink the external LED, followed by another 3 blinks on the built-in LED.

The console shows the right sequence.

Teensy 3.2 and 3.6 show the same symptom.

Something interrupts digitalWriteFast().

Code:
void toggle(uint8_t pin, uint32_t count) {
  // volatile uint32_t index;

  for (; count; --count) {
    digitalWriteFast(pin, !digitalRead(pin));
    Serial.print("+");
    // for (index = 0; index < 80000; ++index) {}
    delay(500);
  }
  Serial.println();
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(0,           OUTPUT);
}

void loop() {
  toggle(LED_BUILTIN, 5);
  toggle(0,           1);
}
 
Last edited:
When you call your function with 5, it does not blink 5 times, but changes state 5 times
So on, off on, off, on
The you call for pin 0,
Then next time you cal with 5, you get off,on,off,on,off
So first time 3on states, next time 2.
 
Update:

Code:
void toggle(uint8_t pin, uint32_t count) {
  // volatile uint32_t index;

  for (; count; --count) {
    digitalWriteFast(pin, !digitalRead(pin));
    Serial.print("+");
    // for (index = 0; index < 80000; ++index) {}
    delay(200);
  }
  Serial.println();
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(0,           OUTPUT);
}

void loop() {
  toggle(LED_BUILTIN,  7);
  toggle(0,           10);
}

The sequence is now (i.e., they alternatively blink the LED partially, until make up the values)


Built-in LED: 3x -- 4x -- 3x -- 4x
External LED: -- 5x -- 5x -- 5x -- 5x
 
Update:

Code:
void blink(uint8_t pin, uint32_t count) {
  // volatile uint32_t index;

  for (; count; --count) {
    digitalWriteFast(pin, !digitalRead(pin));
    delay(100);
    digitalWriteFast(pin, !digitalRead(pin));
    delay(100);
    // for (index = 0; index < 80000; ++index) {}
  }
  Serial.println();
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(0,           OUTPUT);
}

void loop() {
  blink(LED_BUILTIN,  7);
  blink(0,           10);
}
 
your using digitalWriteFast, why not also use digitalReadFast while your at it? :)

Did try both, forgotten to update

Code:
void blink(uint8_t pin, uint32_t count) {
  volatile uint32_t index;

  for (; count; --count) {
    digitalWriteFast(pin, !digitalReadFast(pin));
    for (index = 0; index < 80000; ++index) {}    
    digitalWriteFast(pin, !digitalReadFast(pin));
    for (index = 0; index < 80000; ++index) {}
  }
  Serial.println();
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(0,           OUTPUT);
}

void loop() {
  blink(LED_BUILTIN,  7);
  blink(0,           10);
}
 
Back
Top