lab 5 part 2

Dependencies:   TSI

main.cpp

Committer:
WilliamMarshQMUL
Date:
2020-02-20
Revision:
6:71ef35e456ab
Parent:
5:2a9a3d74a1d8
Child:
7:a910936bf4f8

File content as of revision 6:71ef35e456ab:

#include "mbed.h"
#include "TSISensor.h"

// Example program for lab 5
// -------------------------
//  A value is read from the touch sensor and use
//    to control two LEDs
//  The value is also output to the serial interface

Serial pc(USBTX, USBRX); // tx, rx
DigitalOut redLED(LED_RED);
DigitalOut greenLED(LED_GREEN);
TSISensor tsi;

Thread redThread ; // thread for red LED
Thread greenThread ; // thread for green LED

# define REDFLAG 0x01   
# define GREENFLAG 0x02
EventFlags signals;  // event flags for signalling; 2 used
 
void red_thread() {  // method to run in thread
    while (true) {
        signals.wait_any(REDFLAG);
        redLED = false ; // turn on
        ThisThread::sleep_for(5000) ; // wait(5.0);
        redLED = true ; // turn off 
        signals.clear(REDFLAG) ;
          // Signal are automatically cleared by wait_any but
          // the signal might have been set again while LED on 
    }
}

void green_thread() {  // method to run in thread
    while (true) {
        signals.wait_any(GREENFLAG);
        greenLED = false ; // turn on 
        ThisThread::sleep_for(5000) ; // wait(5.0);
        greenLED = true ; // turn off 
        signals.clear(GREENFLAG) ;
          // Signal are automatically cleared by wait_any but
          // the signal might have been set again while LED on 
    }
}

int main(void) {
    redLED = true ; // turn off 
    greenLED = true ; // turn off 
    redThread.start(red_thread) ; // start the red thread
    greenThread.start(green_thread) ; // start the green thread
    
    while (true) {
        uint8_t d = tsi.readDistance() ;  // Distance is between 0 and 39
                                          // When no touch --> 0
                                          // Left --> low value  Right --> high value
        pc.printf("%d", d) ;  
        pc.putc(' ') ;
        if (d == 10) signals.set(REDFLAG) ;
        if (d == 20) signals.set(GREENFLAG) ;
        ThisThread::sleep_for(500) ; // This polling rate is too slow - increase it
                    // The slower rate maks it easier to output on the terminal
    }
}