Skip to Content
This is the Beta version of our new Learning Paths approach. Please email feedback.

RGB LED

rgb_led.ino
/* Project: Smart Home Component: RGB LED Sketch Description: This sketch has functions to light up an RGB LED in any supported color. Author: STEMVentor Educonsulting This code is copyrighted. Please do not reuse or share for any purpose other than for learning with subscribed STEMVentor programs. This code is for educational purposes only and is not for production use. */ // LIBRARIES // PIN DEFINITIONS // See board_parameters.h // If we add a potentiometer to manually control the brightness. // #define potRed A0; // Potentiometer controls Red pin -> A0 // #define potGreen A1; // Potentiometer controls Green pin -> A1 // #define potBlue A2; // Potentiometer controls Blue pin -> A2 // GLOBAL CONSTANTS // GLOBAL VARIABLES // INITIALIZE OBJECTS // LOCAL FUNCTIONS void RGBLEDSetup() { pinMode(RED_LED_PIN,OUTPUT); pinMode(GREEN_LED_PIN, OUTPUT); pinMode(BLUE_LED_PIN,OUTPUT); // Test cycle through the three primary colors. powerRGBLED(255, 0, 0); // Red delay(2000); powerRGBLED(0, 255, 0); // Green delay(2000); powerRGBLED(0, 0, 255); // Blue delay(2000); powerRGBLED(0, 0, 0); // Off // If we add a potentiometer to manually control the brightness. // pinMode(potRed, INPUT); // pinMode(potGreen, INPUT); // pinMode(potBlue, INPUT); } // This can be called in the main function as a visual indicator wherever required. void powerRGBLED(uint8_t red, uint8_t green, uint8_t blue) { // This is for a RGB LED DIP module with a common GND. analogWrite(RED_LED_PIN, red); analogWrite(GREEN_LED_PIN, green); analogWrite(BLUE_LED_PIN, blue); // Reads the current position of the potentiometer and converts // to a value between 0 and 255 to control the according RGB pin with PWM // RGB LEDs come with two pin types: Commmon Anode and Common Cathode // The signal to the pins is provided accordingly with the code snippets below. // RGB LED COMMON ANODE /* analogWrite(redPin, 255-(255./1023.)*analogRead(potRed)); analogWrite(greenPin, 255-(255./1023.)*analogRead(potGreen)); analogWrite(bluePin, 255-(255./1023.)*analogRead(potBlue)); */ // Uncomment for RGB LED COMMON CATHODE /* analogWrite(redPin, (255./1023.)*analogRead(potRed)); analogWrite(greenPin, (255./1023.)*analogRead(potGreen)); analogWrite(bluePin, (255./1023.)*analogRead(potBlue)); */ } void switchRGBLEDOff(){ powerRGBLED(0, 0, 0); }