Welcome to the Bristol Hackspace Wiki

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

waiter_class [2014/04/18 14:17] (current)
patrick created
Line 1: Line 1:
 +====== Waiter class ======
  
 +
 +This class lets you do a non-blocking delay (so the Arduino can continue to execute other code)
 +
 +
 +
 +<code cpp waiter.h>​
 +typedef uint32_t clock_t;
 +const clock_t INFINITE = ( (clock_t)(-1) );
 +const clock_t SEC = 1000;
 +
 +//
 +// waiter: returns true and resets if more than time has passed
 +//
 +class waiter {
 +    clock_t last;
 +public:
 +    waiter() : last(millis()) {}
 +    bool wait( const clock_t time ) {
 +        clock_t now = millis();
 +        if( now - last >= time ) {
 +            last = now;
 +            return true;
 +        }
 +        return false;
 +    };
 +};
 +</​code>​
 +
 +For example, to flash an LED:
 +
 +<code cpp flash.pde>​
 +#include <​waiter.h>​
 +
 +const byte ledPin = 13;
 +const clock_t flashTime = 2 * SEC;
 +
 +waiter ledFlash;
 +bool ledState;
 +
 +void setup() {
 +    pinMode( ledPin, OUTPUT );
 +};
 +
 +void loop() {
 +    if( ledFlash.wait( flashTime ) ) {
 +        ledState = !ledState;
 +        digitalWrite( ledPin, ledState );
 +    }
 +};
 +</​code>​
 +
 +You can reset the timer with:
 +
 +<code cpp>
 +ledFlash.wait( 0 );
 +</​code>​
Print/export
QR Code
QR Code Waiter class (generated for current page)