Sony Arouje

a programmer's log

Archive for January 28th, 2016

Arduino Scheduler: sleep x time then run for y time

leave a comment »

Recent days I was playing with my Arduino uno to perform several tasks. One task is something like, say sleep for 10 mins and switch on a pin for 3 mins then sleep for 10 mins, and the cycle continues. I evaluated several libraries but most of them run a task based on an interval. For e.g. toggle pin 13 every 1 minute, it’s more like a delay. But what I wanted was, delay for 2 minutes then give a HIGH voltage to pin 13 for 1 minute then write LOW to pin 13 and again sleep for 10mins.

My search leads nothing, so I decided to write a quick and dirty Scheduler for me. I came up with a library after spending 3 hours yesterday night. I didn’t had much programming experience in C++, so I had to spend some time to understand how things work in C++ world. I also use the Timer library as a reference.

Let’s see the sketch that use my library.

#include "TaskScheduler.h" TaskScheduler t1; TaskScheduler t2; TaskScheduler t3; void setup() { Serial.begin(9600); pinMode(13, OUTPUT); pinMode(12, OUTPUT); t1.sleepThenToggle(4000,1000,13,HIGH); t2.every(2000,readSensor); t3.write(12,HIGH,4000); } void readSensor(){ Serial.println("Reading sensors..."); } void loop() { t1.update(); t2.update(); t3.update(); }

Here I declared three tasks, t1, t2 and t3.

Task t1 is a toggle pin task with sleep, in the sample code above, Arduino sleeps for 4000ms then switch on pin 13 for 1000ms and the cycle continues.

  • sleepThenToggle(<sleep time>,<keep the pin state for x ms>,<pin number>,<starting state of the pin>);

Task t2 is a callback task, in the above case, the function readSensor will get called every 2000ms.

  • every(<sleeptime>,<callback>);

Task t3 is a digitalWrite with timeout. One scenario we can use that functionality is, say the switching on/off of a pin is based on an external command, it might be coming from a Raspberry pi. In a situation if the Pi went down with some reason after issuing a switch on command then Arduino will keep the Pin on till a reset. These scenarios, we can use write, in the above code, the pin 12 will be HIGH for 4000ms, after that it will get switched off automatically.

  • t3.write(<pin number>,<starting state of the pin>,<timeout period>);

Make sure to call the ‘update()’ in the loop, other wise no action will be taken.

For the curious minds visit my Gitrepo to see the code.

 

Happy coding…

Written by Sony Arouje

January 28, 2016 at 1:25 pm

Posted in Arduino

Tagged with ,

%d bloggers like this: