For use and an example of states and mod operator with KL46Z somewhat abusive use of c++

Dependencies:   SLCD mbed

Fork of blink_kl46z by Stanley Cohen

main.cpp

Committer:
scohennm
Date:
2014-09-11
Revision:
4:bd42ab18979b
Parent:
3:64e28ee5719b

File content as of revision 4:bd42ab18979b:

#include "mbed.h"
#include "SLCD.h"


// An example of C++ abuse 140904 sc
//#define PRINTDEBUG
#define PROGNAME "blink_kl46z_states v1\n\r"
#define LEDON false
#define LEDOFF true
#define PWMDWELL 50 // milliseconds
#define DFDELTA 0.01
#define PWMTIME 1 // ms (kHz
#define LCDLEN 10
#define RMPUP true
#define RMPDWN false
#define NUMSTATES 2
#define NEWDUTYFACTOR 1
#define IDLESTATE 0


SLCD slcd; //define LCD display globally define
Serial pc(USBTX, USBRX);

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

int main() {
    PwmOut greenColor(LED_GREEN);
    PwmOut redColor(LED_RED);
    char lcdData[LCDLEN];
    Timer LEDTimer;  // time till next PWM values is to change.
    int dfState = IDLESTATE; // work till timer transitions
    float dutyFactor = 0.0;  
    float workingDelta; // hold value of direction of duty factor
   
    int timeToChangeDF = PWMDWELL;
    // set up timer for next step of Duty Factor timing
    LEDTimer.start();
    LEDTimer.reset();
    pc.printf(PROGNAME);
    
    greenColor.period_ms(PWMTIME); // set the frequency of the pulse train
    redColor.period_ms(PWMTIME);   // so there is no flickering
    
    workingDelta = DFDELTA;

    while(true) {
        switch (dfState){ 
            case IDLESTATE: {
                if (LEDTimer.read_ms() > timeToChangeDF){ // check for timer time out transtion
                    dfState = NEWDUTYFACTOR;
                    LEDTimer.reset();
                    }
                break;
              }
             case  NEWDUTYFACTOR: {              
                dutyFactor += workingDelta;           
                if(dutyFactor >= 1.0) workingDelta = -workingDelta; // change direction if needed
                if(dutyFactor < DFDELTA) workingDelta = DFDELTA; 
                redColor.write(dutyFactor);
                greenColor.write(1.0 - dutyFactor);
                // print to LCD screen
                sprintf (lcdData,"%4.3f",dutyFactor);  
                LCDMess(lcdData);
                
                LEDTimer.reset();  // reset the timer
                dfState = IDLESTATE;  // go idle state
                break;
              }
        } // end state machine
        
#ifdef PRINTDEBUG
        pc.printf("i= %d dutyfactor = %5.4f workingDelta %5.4f \n\r",  i, dutyFactor, workingDelta); 
#endif
    }// emd while
}