So, I have a phone app which sends me commands relating to a function involving using timers. I store the time value in the EEPROM and pass it to the timer function (using the TimerOne library). This function I have is in a different tab. I want the function to return a value so that the main program can continue receiving data from thee app AND also return a value when the timer function is done (much like an interrupt). A function can only return a value once, right? Is there some way I can get something like this working? I hope I have been able to convey the query properly!
Please post your code.
Please remember to use code tags so it looks
like this.
/*
switch a led on for 5 seconds
returns:
false while led is on (timing not finished), else true (5 seconds passed)
*/
bool ledFiveseconds()
{
static unsigned long startTime = 0;
unsigned long currentTime = millis()
if(startTime == 0)
{
startTime = currentTime;
digitalWrite(yourLed, HIGH);
return false;
}
if(currentTime - millis() >= 5000)
{
startTime = 0;
digitalWrite(yourLed, LOW);
return true;
}
return false;
}
And you call it from loop
void loop()
{
static bool fCompleted = false;
if(fCompleted == false)
{
fCompleted = ledFiveseconds();
}
...
...
}
loop() will call ledFiveseconds() as long as fCompleted is false. So after 5 seconds ledFiveseconds() will return true and fCompleted will be true. As a result loop() will no longer call it (till somewhere else in the code you set fCompleted to false again).
PS
Just to give you the idea how it can be done in general.
sterretje:
Just to give you the idea how it can be done in general.
Thank you sterretje for the code!
odometer:
Please post your code.
I used the timerOne.h libraray to get my function working.
the code looks like this -
#include <EEPROM.h>
#include <TimerOne.h>
const int timerInterruptLed = 13;
unsigned int val = 2; //Minutes delay
int x = 1;
volatile unsigned long functionCounter = 0; //Count how many times the ISR is called
void timer(); void function();
void setup()
{
Serial.begin(9600);
Serial.println("Hi! Timer program is running!");
pinMode(timerInterruptLed, OUTPUT);
Timer1.initialize(2000000); //2 million microseconds is 2 seconds
}
void loop()
{
if(Serial.available() > 0)
{
if(x > 0)
{
Serial.println("2 minutes starts now");
timer();
x = 0;
}
}
if(functionCounter == val*30)
{
digitalWrite(timerInterruptLed, HIGH);
Serial.println("Finished 2 minutes");
Timer1.detachInterrupt();
}
}
void timer()
{
Timer1.attachInterrupt(function);
}
//interrupt service routine function
void function()
{
functionCounter++;
}