Demo code minor BioRobotics 2016 University of Twente, Enschede, NL Homework set 1, Exercise 9, Example solution

Dependencies:   mbed

Revision:
0:2e3d70904234
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Sep 08 14:20:53 2016 +0000
@@ -0,0 +1,99 @@
+/**
+ * Minor BioRobotics 2016
+ *
+ * Programming Homework Set 1
+ * Exercise 9, example solution
+ *
+ * M.E. Grootens [at] utwente.nl,
+ * v0.1, 08.09.2016
+ */
+
+#include "mbed.h"
+
+#define SERIAL_BAUD 115200  // baud rate for serial communication
+
+// Serial communication with PC
+Serial pc(USBTX,USBRX);
+
+// The LEDs that show the state
+DigitalOut led_red(LED_RED);
+DigitalOut led_green(LED_GREEN);
+DigitalOut led_blue(LED_BLUE);
+
+// Number of states (constant!)
+const int kNumStates = 3;
+// Current state, volatile because modified by interrupt
+volatile int state = 0;
+
+
+/**
+ * Show the state through the LEDs and print to terminal
+ * @ensure red if s==0, green for s==1, blue for s==2
+ */
+void ShowState() {
+    pc.printf("state = %d\r\n",state);   
+    
+    switch (state) {
+        case 0: { 
+            // red on, rest off
+            led_red.write(0);   // on
+            led_green.write(1); // off
+            led_blue.write(1);  // off
+            break;
+        }
+        case 1: { 
+            // green on, rest off
+            led_red.write(1);   // off
+            led_green.write(0); // on
+            led_blue.write(1);  // off
+            break;
+        }
+        case 2: { 
+            // blue on, rest off
+            led_red.write(1);   // off
+            led_green.write(1); // off
+            led_blue.write(0);  // on
+            break;
+        }
+        default: {
+            // this shoud not occur
+            break;
+        }
+    }
+}
+
+/**
+ * Switch the state and display the state by LEDs
+ * @ensure state = ++state % kNumStates
+ */
+void SwitchState() {
+    state++;
+    if (state>=kNumStates) {
+        // could also use modulo ('%') operator
+        state = 0;
+    } 
+    
+    // use the LEDs to show the state
+    ShowState();
+}
+
+/**
+ * Main function.
+ */
+int main()
+{
+    // Serial communication
+    pc.baud(SERIAL_BAUD);
+    pc.printf("\r\n**BOARD RESET**\r\n");
+    
+    // Show the current state through LEDs
+    // state = 0, so red led should be on
+    ShowState();
+    
+    // Interrupt; call SwitchState when button pressed
+    InterruptIn sw2(SW2);
+    sw2.fall(&SwitchState);
+    
+    // Infinite loop; does nothing but needs to prevent termination
+    while (true);
+}
\ No newline at end of file