Example of a custom class for any RGB LED - not just the on-board LED.

Dependencies:   mbed

Revision:
0:0ca7f9aff195
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Wed Sep 23 20:36:10 2015 +0000
@@ -0,0 +1,46 @@
+#include "mbed.h"
+
+/********************
+ * Interactive Device Design Custom Class Demonstration
+ * V2 - Improved version without re-creating PwmOut objects at every call
+ * bjoern@eecs.berkeley.edu, 9/23/2015
+ ********************/
+
+
+class RGBLed {
+public:
+    
+    // constructor - same name as class - this one takes pin names
+    RGBLed (PinName redPN, PinName greenPN, PinName bluePN) {
+        //create new PwmOut objects
+        redPin = new PwmOut(redPN);
+        greenPin = new PwmOut (greenPN);
+        bluePin = new PwmOut (bluePN);
+    }
+     
+    // set red, green, blue values of on-board LED
+    // r,g,b range from 0.0(off) to 1.0(full on)
+    void setColor(float r, float g, float b){    
+        redPin->write(1.0-r); //invert: PWM 0=on, 1.0=off        
+        greenPin->write(1.0-g);
+        bluePin->write(1.0-b);
+    }
+private:
+    RGBLed() {} // cannot use this from the outside because it is private 
+
+    PwmOut* redPin;   // we don't know which pins these will be connected to yet,
+    PwmOut* bluePin;  // so only create pointers and allocate the objects later
+    PwmOut* greenPin; // inside the constructor
+};
+
+    
+RGBLed myLed(LED_RED,LED_GREEN,LED_BLUE); //declare a variable of our new class type and pass in pin names
+
+int main() {
+    while(1) {
+        myLed.setColor(0.0, 0.0, 1.0); //call the member function setColor() - this is blue
+        wait(0.2);
+        myLed.setColor(1.0, 1.0, 1.0); //this is white
+        wait(0.2);
+    }
+}