Go Down

Topic: SetTimeout() (Read 798 times) previous topic - next topic

mrjonny2

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.

Code: [Select]
float hum1 = (SHT2x.GetHumidity());
float temp1 = (SHT2x.GetTemperature());


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

Solenoid

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.

Code: [Select]

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;
}

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

Solenoid


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

mrjonny2

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

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy