Assignment 3 and 4. Both in commits.

Dependencies:   MODSERIAL mbed

main.cpp

Committer:
vsluiter
Date:
2015-09-04
Revision:
3:b05acad8736e
Parent:
2:ae67659d1fca

File content as of revision 3:b05acad8736e:

#include "mbed.h"
#include "MODSERIAL.h"

DigitalOut r_led(LED_RED);
DigitalOut g_led(LED_GREEN);
DigitalOut b_led(LED_BLUE);

DigitalIn button(PTA4);
MODSERIAL pc(USBTX, USBRX);

const int baudrate = 115200;
//const int ms_wait = 100;

const float period_led = 0.2;

const int led_on = 0;
const int led_off = 1;


bool blink_red = false;
bool blink_green = false;
bool blink_blue  = false;

//with an enum, you can assign integer values to a name. You don't have to 
//remember the numbers, just remember the names.
//This is very handy if you want to use this with switch statements.
//If you compare this to the previous version you'll see 
//that this code is much more readable.

//first part is creating a new datatype, enum blinkstate
//second part is defining the names between {}
enum BlinkState {BLINKRED,BLINKGREEN,BLINKBLUE,BLINKNONE};

//we now have a new datatype BlinkState. Just as with
//floats and ints, we can create a new variable and initialize it:
BlinkState blink_state = BLINKNONE;

 
 //function to flip one LED
void flip1led(DigitalOut& led)
{
    led.write(!led.read());
}

void blink3Leds()
{
    //use the enum value!! This is set from the main loop.
    switch(blink_state) {
        case BLINKRED:
            flip1led(r_led);
            g_led.write(led_off);
            b_led.write(led_off);
            break;
        case BLINKGREEN:
            flip1led(g_led);
            r_led.write(led_off);
            b_led.write(led_off);
            break;
        case BLINKBLUE:
            flip1led(b_led);
            g_led.write(led_off);
            r_led.write(led_off);
            break;
        case BLINKNONE:
            r_led.write(led_off);
            g_led.write(led_off);
            b_led.write(led_off);
            break;
    }
}

int main()
{
    Ticker ledtick;
    ledtick.attach(blink3Leds, period_led/2);

    r_led.write(led_off);
    g_led.write(led_off);
    b_led.write(led_off);
    pc.baud(baudrate);
    pc.printf("Hello World!\n");

    while (true) {
        if(pc.readable()) { //if character available. If expresseion is non-zero, it's true
            switch(pc.getc()) {  //read a character
                case 'r':
                    blink_state = BLINKRED;//using the enum, we can just use the names defined above. This also makes it easier to extend functionality
                    break;
                case 'g':
                    blink_state = BLINKGREEN;
                    break;
                case 'b':
                    blink_state = BLINKBLUE;
                    break;
                default:
                    blink_state = BLINKNONE;
                    pc.printf("only r g b allowed.\n");
            }
        }
    }
}