Fan needs to run every two hours

Hi,

I am working on a greenhouse project. During winter the ventilation louvres will be closed all the time and this wil cause stale air inside the greenhouse.
I want to write a piece of code that operates a ventilation fan every two hours for about 15 seconds to expel stale air.
I have been racking my brain and watched several YouTube clips and tutorials and I came up with the idea to use an interrupt that runs independent of the main program. the interrupt is triggered by one of the internal timers.
My problem is that I don't know how to set up an internal timer and an interrupt that happens every two hours.
Could somebody please help to point into the right direction or provide a bit of basic code that shows how to do this?
In a future stage I will add a RTC (Real time clock) to the board. I know this is complete overkill but I want to use the clock function for other things as well which need to be more precise (Such as draining growbeds).
Many thanks in advance for your input.

Hello and welcome :slight_smile:

I never use interrupts, I prefer polling with millis(), something like this will turn on the onboard led for one second, then off for 3 seconds and repeat:

const uint8_t ledPin = 13;
const uint32_t
  timeON  = 1000ul,
  timeOFF = 3000ul;

bool ledState = false;
uint32_t
  time     = timeOFF,
  curTime  = 0,
  prevTime = 0;


void setup()
{
  pinMode( ledPin, OUTPUT );
}

void loop()
{
  curTime = millis();

  if ( curTime - prevTime >= time )
  {
    prevTime = curTime;
    ledState = !ledState;
    time = ledState ? timeON : timeOFF;
    digitalWrite( ledPin, ledState );
  }
}

Hi Guix,

Thank you very much for this compact and simple sketch.
I never thought about it like that.
Initially I thought using an interrupt wouldn't make a difference on the loop and that's why I was looking into that direction.
Your code is simple and doesn't cause much delay in the program.
I will play around with it.
I think it will exactly do what I wanted to achieve. So, thank you very much for your help!

Luc