Performance digitalRead(), digitalWrite()

Hi all,

which is the best option?

void loop()
{
float temp = ReadTemp();
if (temp > 30)
{
//check pin state
if (digitalRead(43) == LOW)
{
digitalWrite(43, HIGH);
}
//or simply always set pin to HIGH
digitalWrite(43, HIGH);
}
}

Thanks
Zdenal

if (temp > 30)
   {
      //check pin state
      if (digitalRead(43) == LOW)
      {
         digitalWrite(43, HIGH);
      }
      else
      {
      digitalWrite(43, LOW);
      }
   }

Otherwise, how will it go low?

// ... simply always set pin to HIGH
digitalWrite(43, HIGH);

CrossRoads:

if (temp > 30)

{
      //check pin state
      if (digitalRead(43) == LOW)
      {
        digitalWrite(43, HIGH);
      }
      else
      {
      digitalWrite(43, LOW);
      }
  }



Otherwise, how will it go low?

It is only example / snippet :slight_smile:

Simply inverting a pin?

digitalWrite (43, ! digitalRead (43)) ;

Though one would normally store the pin state in a variable:

  pin_state = !pin_state ; // invert
  digitalWrite (43, pin_state) ; // output

If you call digitalRead it takes more time and you are sensitive to the pin being shorted out
causing different behaviour.

Why don't you write a small test code that e.g. loops thousand times and measure the durations for the different approaches?

void loop()
{
	float temp = ReadTemp();
	if ( temp > 30 )
	{
#f 0
		// variable time to set as we first check it's value and only set it if
		// it's not high, but why bother as if it is LOW then set it to HIGH and
		// if it's already HIGH what difference would it make to set it HIGH
		// regardless ...

		if ( digitalRead(43) == LOW )
		{
			digitalWrite(43, HIGH);
		}
#else
		// ... const time to set ...
		
		digitalWrite(43, HIGH);
#endif
	}
}