SSD541_HW12.2

Dependencies:   SLCD TSI mbed

main.cpp

Committer:
eseifert
Date:
2016-11-06
Revision:
1:d82569d51964
Parent:
0:fb6ea61c315b
Child:
2:f9713d90a13c

File content as of revision 1:d82569d51964:

#include "mbed.h"
#include "TSISensor.h"
#include "SLCD.h"
#define TSILIMIT     0.99
#define LCDCHARLEN   10
#define DATAINTERVAL 0.5
#define PROGNAME     "kl46z_recursive_count\n\r"
#define BUTTONTIME 0.2
#define LCDTITLE "rCNT"
#define TITLEWAIT 2.0
#define NUMBUTS 2
#define LBUT PTC12  // port addresses for buttons
#define RBUT PTC3
#define STOPPEDSTATE 0
#define COUNTINGSTATE  1

DigitalOut gpo(D0);
DigitalOut led0(LED_RED);
SLCD slcd;
Serial pc(USBTX, USBRX);
PwmOut gled(LED_GREEN);
PwmOut rled(LED_RED);
TSISensor tsi;
Timer ButtonTimer;
DigitalIn buttons[NUMBUTS] = {LBUT, RBUT};

char lcdData[LCDCHARLEN];
float tsidata   = 0.0;
int count_num   = 0;
int count_min   = 0;
bool stateToggle = 0;

void LCDMess(char *lMess){
        slcd.Home();
        slcd.clear();
        slcd.printf(lMess);
}

void initialize_global_vars()
{
    pc.printf(PROGNAME);
    // set up DAQ timer
    // set up DAQ timers
    ButtonTimer.start();
    ButtonTimer.reset();
}

void showTitle()
{
    LCDMess(LCDTITLE);
    wait(TITLEWAIT);
    return;
}

void count_backwards(int cnt, int min){
    if(!buttons[1]){
        stateToggle = 0;
        cnt = 0;
        showTitle();
    }
    gled = !gled;
    pc.printf("\tT-%d\n\r", cnt);
    sprintf (lcdData,"tz%d",cnt);  
    LCDMess(lcdData);  
    wait(DATAINTERVAL);
    // tail recursion to correct the direction of counting
    if(cnt > min){ 
        count_backwards(cnt-1,min);
    }
}

void showData(int cnt){
    sprintf (lcdData,"%d",cnt);  
    LCDMess(lcdData);  
}

int main()
{
    initialize_global_vars();
    showTitle();
    pc.printf(PROGNAME);
    while (true) {
        rled = !rled;
        tsidata = tsi.readPercentage();
        count_num = floor(tsidata*51);
        if(count_num > 2){
            pc.printf("\n Count down from: %d\n\r", count_num);
            showData(count_num);
        }
        wait(DATAINTERVAL);
        if (ButtonTimer > BUTTONTIME) {
            if(!buttons[0]){
                stateToggle = 1;
            }
        if(!buttons[1]){
            stateToggle = 0;
            count_num = 0;
            showTitle();
        }
        }
        ButtonTimer.reset();

        switch (stateToggle) {
            case STOPPEDSTATE:
                showData(count_num);
                rled = 1.0;
                gled = 0.0;
                break;
            case COUNTINGSTATE:
                if(stateToggle) {
                    count_backwards(count_num, count_min);
                }
                rled = 0.0;
                gled = !gled;
                break;
        }
    }
}