Is it bad practice to continually set a pin high in a loop?

Hi guys,

Beginner here. I just wanted to ask the question because i'm driving some relays through my sketch using a mega and i understand the relays have a limited number of switches and i'm not sure if setting an already high pin, high does anything on the hardware level?

something like : //the status is changed via hardware interrupts

while (Status == 1){ digitalWrite (something, HIGH) }

/edit typo

//or would this be better practice

while (Status == 1){ if (!digitalRead(something){ //if pin is not high, make it so, else return. digitalWrite (something, HIGH) }else{ return; }

I would think that setting an already HIGH pin HIGH does nothing but im not sure.

Any help would be appreciated.

Thanks in Advance

i'm not sure if setting an already high pin, high does anything on the hardware level?

It does not.

Neither of your options is best. Best would be:

   digitalWrite (something, HIGH);
   while (Status == 1)
   {
   }

Presumably, after the while loop ends, you want to turn the pin off, but adding that is for you to do.

Adding a return in the while loop is almost certainly NOT going to do what you expect. Reading a pin that you set the state of is pointless. The Arduino can remember how it set the pins.

Hi PaulS,

Thanks for the answer, that does make a lot of sense.

Your sample code is a far more elegant solution.

Appreciate the help

It has its limitations though. You spoke about interrupt service routines. If you have several interrupt service routines say pin change or timers, all pseudo asynchronously setting status variables which you are testing in the loop() and acting on them, then that structure breaks down because you can't be stuck in a while statement waiting for just one of them to change. Look at this example. How would you solve it with a while statement ?

// say ISR1 maintains variable Status1
// say ISR2 maintains variable Status2
// say ISR3 maintains variable Status3

loop(){

  if ( Status1 == 1 ) {
      digitalWrite (something1, HIGH) ;
  } else {
      digitalWrite (something1, LOW) ;
  }

  ( Status2 == 1 ) ? (digitalWrite (something2, HIGH)) : (digitalWrite (something2, LOW)) ;

  digitalWrite (something3, ( Status3 == 1 ))  ;

}