Constant digitalWrite?

Hi,
I'm controlling a relay based on data from a CO2 sensor. The Arduino is looking for a range of CO2 values and don't need to write to the relay constantly.

My question is do I need to digitalWrite to my relay every 1.5 seconds? Is that a good thing?

thanks

here's my code

void loop()
{
  double co2 = K_30.getCO2('p'); //returns co2 value in ppm ('p') or percent ('%')
  co2 = co2 * 44.01 / 10000;
  //quicker than co2/1000000 * 44.01 / 1000000
  if ( co2 >= 40 ) {
      digitalWrite(pin, LOW);
  } else if ( co2 <= 35 ) {
      digitalWrite(pin, HIGH);
  } else {
      digitalWrite(pin, HIGH);
  }

  Serial.println(co2);	//print value 
  delay(1500);	//wait 1.5 seconds

}

In an embedded system, it is better to assume nothing, so I would vote for writing to the relay.

My question is do I need to digitalWrite to my relay every 1.5 seconds? Is that a good thing?

Do you need to? No, of course not, you only HAVE to write to it if you need to change it's state, output bits latch. On the other hand writing to the relay every 1.5 seconds is such a low cost, why not. I would think it would matter more depending on your code structure and if it's clear to any reader (including you a year from now) of your source code, what happens when and where as far as the relay is concerned.

Lefty

The Arduino is not going to spontaneously change the output state so duplicate writes are pointless. However, in this case it would simplify the code to do the output unconditionally rather than add logic to detect changes.

On the issue of simplicity/clarity: Given that you only have two output actions (set HIGH/set LOW) it's hard to see why there are three conditions being detected:

  if ( co2 >= 40 ) {
      digitalWrite(pin, LOW);
  } else if ( co2 <= 35 ) {
      digitalWrite(pin, HIGH);
  } else {
      digitalWrite(pin, HIGH);
  }

This does the same thing and is simpler, and hence better:

  if ( co2 >= 40 )
  {
      digitalWrite(pin, LOW);
  }
  else
  {
      digitalWrite(pin, HIGH);
  }

(I'd also suggest using a more meaningful name than 'pin'.)