Code efficiency / Performance / Energy saving question around digitalWrite / digitalRead

Hello,
I am currently very interested in optimising code for energy consumption and performance.
One thing that intrigued me is if I should store the state of a pin from digitalRead in a variable or read it every time in a loop.
For example:
If I want to switch on an external LED when a certain value is too low there are two options:

either:
if ( value_is_smaller_than_minimum ){
if (digitalRead(my_pin) == LOW){
digitalWrite(my_pin,HIGH);
};
}else{
if (digitalRead(my_pin) == HIGH){
digitalWrite(my_pin,LOW);
};
};

or:

bool led_is_on = false;
if ( value_is_smaller_than_minimum ){
if(!led_is_on){
digitalWrite(my_pin,HIGH);
led_is_on = true;
};
}else{
if(led_is_on){
digitalWrite(my_pin,LOW);
led_is_on = false;
};
};

The latter would omit reading the pin state on each loop iteration but instead read the boolean.
Does this in fact make any difference?
Maybe the first way is even faster?

Thanks a lot

The question you need you ask yourself is how fast does it need to run.

Using PORTs will be much faster than using digitalXXX but do you need it ?

Consider that the actual pin status may change, randomly, at any time an not under your direct control, your code will be much more responsive if you check the actual, current, value at the time you need to know the value.

It does not need to run fast.
I am more concerned about efficiency and energy consumption.
And generally about understanding the cost of certain procedures.
Sometimes code can be more complicated but also more efficient in terms of energy.

Generally, I think trying to out think an optimizing compiler isn't a productive exercise.

But one time obscure code incoming.

const uint8_t my_pin = 13;

volatile uint8_t *port;
uint8_t mask;

const uint16_t minimum = 32767;
uint16_t value = 0;

void setup() {
   port = portOutputRegister(digitalPinToPort(my_pin));
   mask = digitalPinToBitMask(my_pin);
   *portModeRegister(digitalPinToPort(my_pin)) |= mask;
}

void loop() {
   ++value;
   if( value < minimum ) {
      *port |= mask;
   } else {
      *port &= !mask;
   }
}

You would have to compare the compiler's machine code output to the source code (C++) in.

I hope not. It looks like @brainino is using my_pin in OUTPUT mode, so its state should be what it was last written.

There is an argument for reading the pin! I haven't run into any of them, yet. And outside of clever one-line toggling, I don't see it very often in code I read here. This is chatGPT helping me:

Situation Best approach
Simple LED, private pin Keep a boolean
Shared or bus pin Read the pin
Fault detection Read the pin
High performance Track state or use toggle register
AVR toggle Write to PINx

To me it mostly says use the tracking variable. YMMV.

I don't think it could possibly make a significant difference.

a7

Energy saving?
The microcontroller will draw the same current whether it is looping around in loop(), waiting in delay() or calculating the hell out of floats.
The only way to decrease the energy used is to lower the clock rate, the supply voltage, or both.
If you're looking for saving time, please say so.

Why? BTW, probably the only reasonable answer is that you want the project to be battery-powered. In that case processor clock rate (already mentioned) and sleep modes will have orders of magnitude greater effect than trying to fine tune the code's instruction sequence or variable use for power dissipation.

The energy consumed by MCUs is very nearly constant while running and does not depend on the instructions being executed. The only significant savings come when idle or sleep modes are implemented.

If the program is waiting for input on a pin, an option is to have the processor sleep until awakened by a pin change interrupt.

Hey all.
Thanks for all the great responses.
I now have a better idea.
But just to clarify:
setting an output pin to HIGH on each loop iteration does not make a difference to setting it once and have an otherwise idle main loop?

Good to know that sleep, idle and cpu throttle are more effective.
I usually do these on battery powered projects.

I doubt that machine code generated by this:

void setup()
{
    DDRB = 0x20; // pin 13 is OUTPUT
}

void loop()
{
  bool state = analogRead(A0) < 512;
  bitWrite(PORTB,5, state ? HIGH : LOW);
}

Would be much different than that generated by your code.

Setting it HIGH again is useless but won’t draw more energy than having the loop spin empty.

Would save the time of 2 "if"s.

Would save time, not energy.

Not using sleep a common structure is:

void loop() {
  if(button) {
    function();
  }
}
  • If you're waiting 10 minutes before someone pushes the button, 0.5µs or 100µs execution time of the function() is not important.
  • Looping the loop() costs the same current as executing the function().

Using sleep a common structure is:

void loop() {
  gotoSleep();
}

ISR(vector) {
  function();
}
  • The current used in sleep is significantly lower than normal.
  • If you're using half the clock speed, the current used during executing the function() is also half what's normal, but the execution time is doubled. No saving on battery life.
  • 0.5µs instead of 100µs execution time of the function() does save energy, but if you're waiting 10 minutes before someone pushes the button, the difference in battery life may not be all that much.

We're talking about the power consumption of the microcontroller, the power consumed by the LED comes on top of that.

Choosing a different board might help, a UNO R3 draws about 50mA, a Nano (also ATmega328P) only 30mA.

This would make quite a difference. When calling digitalWrite(..) the microcontroller will:

  • Lookup which timer the pin is on, if any, and kill PWM.
  • Lookup which port the pin is on.
  • Lookup the bitmask for the pin.
  • Then set the appropriate bit.

Using bitWrite(...) YOU need to keep track of everything.

Instead of analogRead, I started to:

bool state = bitRead(PIND,2); // is pin 2 HIGH or LOW?

But was looking at the OP's
if ( value_is_smaller_than_minimum )

The same goes for digitalRead(.) vs bitRead(..).

And that's the beauty of the Arduino system, allow beginners to use an MCU without first having to learn low level digital logic, binary math and microprocessor operation. But the tools are still there to be able to "throw away the training wheels".

Is OP ready to "throw away the training wheels"?