First Last
/
Minor_Assignment3_4
Assignment 3 and 4. Both in commits.
Diff: main.cpp
- Revision:
- 2:ae67659d1fca
- Parent:
- 1:958fbf7ad850
- Child:
- 3:b05acad8736e
--- a/main.cpp Wed Sep 02 12:57:47 2015 +0000 +++ b/main.cpp Fri Sep 04 07:26:58 2015 +0000 @@ -21,24 +21,55 @@ 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 {} +//third part is creating a variable of the enum blinkstate type. +enum blinkstates {BLINKRED,BLINKGREEN,BLINKBLUE,BLINKNONE} blink_state; + + + //function to flip one LED void flip1led(DigitalOut& led) { - led = !led; + led.write(!led.read()); } void blink3Leds() { - if(blink_red) + //use the enum value!! This is set from the main loop. + switch(blink_state) { + case BLINKRED: flip1led(r_led); - if(blink_green) + g_led.write(led_off); + b_led.write(led_off); + break; + case BLINKGREEN: flip1led(g_led); - if(blink_blue) - flip1led(b_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; + blink_state = BLINKNONE;//initialize ledtick.attach(blink3Leds, period_led/2); r_led.write(led_off); @@ -46,34 +77,21 @@ 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 - { + if(pc.readable()) { //if character available. If expresseion is non-zero, it's true + switch(pc.getc()) { //read a character case 'r': - blink_red = true; - blink_green = false; - blink_blue = false; - g_led.write(led_off); - b_led.write(led_off); + 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_red = false; - blink_green = true; - blink_blue = false; - r_led.write(led_off); - b_led.write(led_off); + blink_state = BLINKGREEN; break; case 'b': - blink_red = false; - blink_green = false; - blink_blue = true; - g_led.write(led_off); - r_led.write(led_off); + blink_state = BLINKBLUE; break; default: + blink_state = BLINKNONE; pc.printf("only r g b allowed.\n"); } }