Provides an extended version of DigitalOut that adds a "toggle()" function, and uses the RTOS Thread API to provide a "flash()" function that toggles the pin in the background at a given interval.

Dependents:   Car_Simulator

Example of use:

#include "mbed.h"
#include "rtos.h"    /* NOTE: Requires the RTOS library or a matching API */
#include "DigitalOutEx.h"

DigitalOutEx led1(LED1);
DigitalOutEx led2(LED2);

int main() {
    
    led1.flash(200);
    led2.flash(500);
    
    Thread::wait(5000);
    
    led1.flash(50);
    
    Thread::wait(5000);
    
    led1 = 0;
    
    Thread::wait(5000);
    
    led1.flash(1000);
    
    while (1) { }    
}
Committer:
Byrn
Date:
Fri Apr 26 10:31:31 2013 +0000
Revision:
0:1798e1bf583a
Child:
1:6f8ca7b70778
Initial commit.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
Byrn 0:1798e1bf583a 1
Byrn 0:1798e1bf583a 2 #include "DigitalOutEx.h"
Byrn 0:1798e1bf583a 3
Byrn 0:1798e1bf583a 4 DigitalOutEx::DigitalOutEx(PinName pin)
Byrn 0:1798e1bf583a 5 : DigitalOut(pin),
Byrn 0:1798e1bf583a 6 _flashThread(NULL),
Byrn 0:1798e1bf583a 7 _flashing(0),
Byrn 0:1798e1bf583a 8 _flashInterval(200) {
Byrn 0:1798e1bf583a 9 }
Byrn 0:1798e1bf583a 10
Byrn 0:1798e1bf583a 11 void DigitalOutEx::write(int value) {
Byrn 0:1798e1bf583a 12 DigitalOut::write(value);
Byrn 0:1798e1bf583a 13 if (_flashing) {
Byrn 0:1798e1bf583a 14 stop_flashing();
Byrn 0:1798e1bf583a 15 }
Byrn 0:1798e1bf583a 16 }
Byrn 0:1798e1bf583a 17
Byrn 0:1798e1bf583a 18 void DigitalOutEx::flash(int intervalMs) {
Byrn 0:1798e1bf583a 19 _flashInterval = intervalMs;
Byrn 0:1798e1bf583a 20 if (_flashing) return;
Byrn 0:1798e1bf583a 21
Byrn 0:1798e1bf583a 22 _flashThread = new Thread(DigitalOutEx::_flash_thread, this);
Byrn 0:1798e1bf583a 23 }
Byrn 0:1798e1bf583a 24
Byrn 0:1798e1bf583a 25 void DigitalOutEx::stop_flashing() {
Byrn 0:1798e1bf583a 26 if (!_flashing) return;
Byrn 0:1798e1bf583a 27
Byrn 0:1798e1bf583a 28 _flashThread->terminate();
Byrn 0:1798e1bf583a 29 _flashThread = NULL;
Byrn 0:1798e1bf583a 30 _flashing = 0;
Byrn 0:1798e1bf583a 31 }
Byrn 0:1798e1bf583a 32
Byrn 0:1798e1bf583a 33 DigitalOutEx &DigitalOutEx::operator=(int value) {
Byrn 0:1798e1bf583a 34 write(value);
Byrn 0:1798e1bf583a 35 return *this;
Byrn 0:1798e1bf583a 36 }
Byrn 0:1798e1bf583a 37
Byrn 0:1798e1bf583a 38 void DigitalOutEx::_flash_thread(const void *argument) {
Byrn 0:1798e1bf583a 39 DigitalOutEx *out = (DigitalOutEx *)argument;
Byrn 0:1798e1bf583a 40 out->_flashing = 1;
Byrn 0:1798e1bf583a 41 while (1) {
Byrn 0:1798e1bf583a 42 // use the base class, as DigitalOutEx's write() stops the flashing for us
Byrn 0:1798e1bf583a 43 ((DigitalOut *)out)->write(!out->read());
Byrn 0:1798e1bf583a 44 Thread::wait(((DigitalOutEx *)argument)->_flashInterval);
Byrn 0:1798e1bf583a 45 }
Byrn 0:1798e1bf583a 46 }