Demonstration of EventQueues

Dependencies:   ELEC350-Practicals-FZ429

Fork of Task622Solution-mbedos54 by Nicholas Outram

main.cpp

Committer:
noutram
Date:
2017-11-21
Revision:
12:01c7edd1dd19
Parent:
11:67cb33bc247e

File content as of revision 12:01c7edd1dd19:

#include "mbed.h"
#include <iostream>
#include "sample_hardware.hpp"
#include "mbed_events.h"
void buttonPressedISR();
void buttonReleasedISR();
void addSample(float t);
void heartBeat();
 
InterruptIn btn(USER_BUTTON);

//Creates a queue with the default size
EventQueue mainQueue;

Timer tmr1;
Thread t1;

//Buffer
float arrayOfTimes[10];

//Set up rising edge detection
void rising() {
    btn.rise(buttonPressedISR);
}
//Set up falling edge detection
void falling() {
    btn.fall(buttonReleasedISR);
}

int main() {
    //Power on self test
    post();
    
    puts("Press the BLUE button as close to once a second as you can");
    
    //Set up ISR
    btn.rise(buttonPressedISR);
    
    //Start timer
    tmr1.start();
    
    //Background flash (backed by a Ticker)
    mainQueue.call_every(500, heartBeat);
    
    // events are executed by the dispatch method
    mainQueue.dispatch();
    
    //Unreachable code
    printf("This should never appear!\n");
}

void buttonPressedISR() { 
    float t = tmr1.read();  //Immediately read time in seconds
    btn.rise(NULL);         //Turn off interrupt
    mainQueue.call(addSample, t);           //Add sample to buffer and print
    mainQueue.call_in(200, falling);        //After 200ms, look for falling edge
}

void buttonReleasedISR() { 
    btn.fall(NULL);                     //Turn off interrupt
    mainQueue.call_in(200, rising);     //After 200ms, look for rising edge again
}

// Add sample to buffer
// Single parameter t, copy of latest switch time
void addSample(float t) {
    
    //Manually shuffle the buffer
    for (unsigned int n=9; n>0; n--) {
        arrayOfTimes[n] = arrayOfTimes[n-1];
    }
    
    //Add new sample
    arrayOfTimes[0] = t;
    
    //Display deltas
    for (unsigned int n=9; n>0; n--) {
        float delta = (arrayOfTimes[n-1] - arrayOfTimes[n]);
        printf("%5.1f ", delta);
    }
    printf("\n");
    
}

//Flashing LED 
void heartBeat() {
    redLED = !redLED;
}