Skip to content

Instantly share code, notes, and snippets.

@devyte
Last active September 26, 2018 23:10
Show Gist options
  • Save devyte/d725e283e7eeb87af0ce6b645ad90631 to your computer and use it in GitHub Desktop.
Save devyte/d725e283e7eeb87af0ce6b645ad90631 to your computer and use it in GitHub Desktop.
#include "Arduino.h"
#include "timeout.h"
void runtest1()
{
using namespace esp8266;
polledTimeoutOneShot timeout(3000);
Serial.print("before while 1\n");
while(!timeout.expired())
yield();
Serial.print("after while 1\n");
Serial.print("reset\n");
timeout.reset();
Serial.print("before while 2\n");
while(!timeout)
yield();
Serial.print("after while 2\n");
}
void runtest2()
{
using namespace esp8266;
polledTimeoutPeriodic timeout(3000);
Serial.print("before while 1\n");
while(!timeout.expired())
yield();
Serial.print("after while 1\n");
Serial.print("no reset needed\n");
Serial.print("before while 2\n");
while(!timeout)
yield();
Serial.print("after while 2\n");
}
void runtest3()
{
using namespace esp8266;
polledTimeoutPeriodic timeout(1000);
int counter = 10;
while(1)
{
if(timeout)
{
Serial.print("*");
if(!--counter)
break;
yield();
}
}
Serial.println();
}
polledTimeoutPeriodic loopTimeout(1000);
void setup()
{
Serial.begin(115200);
delay(10);
Serial.println();
Serial.print("runtest1\n");
runtest1();
Serial.print("done\n");
Serial.print("runtest2\n");
runtest2();
Serial.print("done\n");
Serial.print("runtest3\n");
runtest3();
Serial.print("done\n");
loopTimeout.reset();
}
void loop()
{
if(loopTimeout)
Serial.print("#");
}
#ifndef __ESP8266TIMEOUT_H__
#define __ESP8266TIMEOUT_H__
namespace esp8266
{
template<bool PeriodicT>
class polledTimeout
{
public:
using timeType = unsigned int;
polledTimeout(timeType timeout)
: _timeout(timeout), _start(millis())
{}
bool expired()
{
if(PeriodicT)
return expiredRetrigger();
return expiredOneShot();
}
operator bool()
{
return expired();
}
bool reset()
{
_start = millis();
}
protected:
bool checkExpired(timeType t) const
{
return (t - _start) >= _timeout;
}
bool expiredRetrigger()
{
timeType current = millis();
if(checkExpired(current))
{
_start = current;
return true;
}
return false;
}
bool expiredOneShot() const
{
return checkExpired(millis());
}
timeType _timeout;
timeType _start;
};
using polledTimeoutOneShot = polledTimeout<false>;
using polledTimeoutPeriodic = polledTimeout<true>;
}
#endif
@d-a-v
Copy link

d-a-v commented Sep 26, 2018

What about moving yield() in expired() ? (or optimistic_yield())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment