SSD541_HW12.2

Dependencies:   SLCD TSI mbed

main.cpp

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

File content as of revision 2:f9713d90a13c:

#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);
    pc.printf("Select count->\n\r");
    // set up DAQ timer
    ButtonTimer.start();
    ButtonTimer.reset();
}

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

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

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

int main()
{
    showTitle();
    initialize_global_vars();
    while (true) {
        tsidata = tsi.readPercentage();
        count_num = floor(tsidata*51);
        showData(count_num);
        wait(DATAINTERVAL);
        if (ButtonTimer > BUTTONTIME) {
            if(!buttons[0]){
                stateToggle = 1;
            }
            if(!buttons[1]){
                stateToggle = 0;
                count_num = 0;
                pc.printf("Select count->\n\r");
            }
        }
        ButtonTimer.reset();

        switch (stateToggle) {
            case STOPPEDSTATE:
                if(count_num > 2){
                    pc.printf("Count: %d?\n\r", count_num);
                }
                showData(count_num);
                rled = 1.0;
                gled = 0.0;
                break;
            case COUNTINGSTATE:
                if(stateToggle) {
                    pc.printf("\n Counting down from: %d\n\r", count_num);
                    count_backwards(count_num, count_min);
                    pc.printf("Select count->\n\r");
                }
                stateToggle = 0;
                rled = 0.0;
                gled = !gled;
                break;
        }
    }
}