IDD Fall 2015 / Mbed 2 deprecated idd_cpp_rgbled2

Dependencies:   mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "mbed.h"
00002 
00003 /********************
00004  * Interactive Device Design Custom Class Demonstration
00005  * V2 - Improved version without re-creating PwmOut objects at every call
00006  * bjoern@eecs.berkeley.edu, 9/23/2015
00007  ********************/
00008 
00009 
00010 class RGBLed {
00011 public:
00012     
00013     // constructor - same name as class - this one takes pin names
00014     RGBLed (PinName redPN, PinName greenPN, PinName bluePN) {
00015         //create new PwmOut objects
00016         redPin = new PwmOut(redPN);
00017         greenPin = new PwmOut (greenPN);
00018         bluePin = new PwmOut (bluePN);
00019     }
00020      
00021     // set red, green, blue values of on-board LED
00022     // r,g,b range from 0.0(off) to 1.0(full on)
00023     void setColor(float r, float g, float b){    
00024         redPin->write(1.0-r); //invert: PWM 0=on, 1.0=off        
00025         greenPin->write(1.0-g);
00026         bluePin->write(1.0-b);
00027     }
00028 private:
00029     RGBLed() {} // cannot use this from the outside because it is private 
00030 
00031     PwmOut* redPin;   // we don't know which pins these will be connected to yet,
00032     PwmOut* bluePin;  // so only create pointers and allocate the objects later
00033     PwmOut* greenPin; // inside the constructor
00034 };
00035 
00036     
00037 RGBLed myLed(LED_RED,LED_GREEN,LED_BLUE); //declare a variable of our new class type and pass in pin names
00038 
00039 int main() {
00040     while(1) {
00041         myLed.setColor(0.0, 0.0, 1.0); //call the member function setColor() - this is blue
00042         wait(0.2);
00043         myLed.setColor(1.0, 1.0, 1.0); //this is white
00044         wait(0.2);
00045     }
00046 }