SetTimeout()

Hi,
I am unsure of how to use this function, the documentation seems to be almost non existent. I would like to set a timeout when I read one of my sensors that is on an i2c bus incase it gets unplugged so doesn't hang the arduino.

 float hum1 = (SHT2x.GetHumidity());
 float temp1 = (SHT2x.GetTemperature());

If anyone knows how to put that within a setTimeout function I will be very appreciative.

I use this (using the timer 2) to check my serial connection status, but you might need to modify a little bit for your usage. It checks if a condition is met every second, the condition being that the "timeout" variable should be different of zero, otherwise it shows a timeout occurred.

byte timeout = 0;

void setup()
{
  // initialize counter
  TCNT2 = 0;
  // set prescaler to 256
  TCCR2 = 0x06;
  // enable overflow interrupt
  TIMSK |= (1 << TOIE2);
  // enable global interrupts
  asm("SEI");
}

void loop() {
  while(/* blocking function */)
  {
    // prevent timeout
    timeout = 1;
  }
}

ISR(TIMER2_OVF_vect)
{
  // 8e6Hz / 256 / 256 / 122 = 1Hz (check every second)
  if(timerCounter++ < 122)
  {
    return;
  }

  // verify timeout status
  if(timeout == 0)
  {
    // interpret as timeout failure
    /* do something drastic */
  }
  timeout = 0;
  timerCounter = 0;
}

Hi,
Thanks but I don't quite understand how that works, if my device hangs on the reads for the sensors, is there any way I can have it skip over that part of the code?

Many thanks

mrjonny2:
Hi,
Thanks but I don't quite understand how that works, if my device hangs on the reads for the sensors, is there any way I can have it skip over that part of the code?

Many thanks

Yes there is, what you're looking for is named an interrupt, it lets you do pseudo-multitasking, which you're after.

In the code above I use a timer (something that counts up), I enable the overflow interrupt. The timer 2 is an 8-bit timer which means the overflow will happen at 255. This makes the program call the code which is inside the TIMER2_OVF_vect no matter what it was doing before every 8MHz/256 = 31.25kHz. You can further slow down by setting a prescaler, what that does is divide the counting speed of the timer. How to set it and what exactly are all described in the datasheet of your MCU.

TL;DR: search for "avr interrupt" on Google

Hi, thanks.
I will look into integrating that into the library.