Created
December 10, 2017 06:32
-
-
Save YushengLi/02f33801f06d37c4f3635079ec3c39aa to your computer and use it in GitHub Desktop.
An Example to switch color of a RGB LED with a button
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const byte redPin = 3; | |
const byte greenPin = 5; | |
const byte bluePin = 6; | |
const byte interruptPin = 2; | |
volatile byte mode = 0; | |
volatile byte modeChanged = 0; | |
unsigned long lastInterrupt; | |
void setup() { | |
setColourRgb(0,0,0); | |
pinMode(redPin, OUTPUT); | |
pinMode(greenPin, OUTPUT); | |
pinMode(bluePin, OUTPUT); | |
pinMode(interruptPin, OUTPUT); | |
attachInterrupt(digitalPinToInterrupt(interruptPin), changeMode, RISING); | |
} | |
void loop() { | |
modeChanged = 0; | |
switch (mode) { | |
case 0: | |
breathingLight(); | |
break; | |
case 1: | |
setColourRgb(255, 0, 0); | |
break; | |
case 2: | |
setColourRgb(255, 20, 0); | |
break; | |
case 3: | |
setColourRgb(255, 80, 0); | |
break; | |
case 4: | |
setColourRgb(0, 255, 0); | |
break; | |
case 5: | |
setColourRgb(0, 0, 255); | |
break; | |
case 6: | |
setColourRgb(0, 80, 150); | |
break; | |
case 7: | |
setColourRgb(255, 0, 255); | |
break; | |
default: | |
breathingLight(); | |
break; | |
} | |
} | |
void breathingLight() { | |
unsigned int rgbColour[3]; | |
// Start off with red. | |
rgbColour[0] = 255; | |
rgbColour[1] = 0; | |
rgbColour[2] = 0; | |
// Choose the colours to increment and decrement. | |
for (int decColour = 0; decColour < 3; decColour += 1) { | |
int incColour = decColour == 2 ? 0 : decColour + 1; | |
// cross-fade the two colours. | |
for(int i = 0; i < 255; i += 1) { | |
if(modeChanged == 1) { | |
return; | |
} | |
rgbColour[decColour] -= 1; | |
rgbColour[incColour] += 1; | |
setColourRgb(rgbColour[0], rgbColour[1], rgbColour[2]); | |
delay(50); | |
} | |
} | |
} | |
void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) { | |
analogWrite(redPin, red); | |
analogWrite(greenPin, green); | |
analogWrite(bluePin, blue); | |
} | |
void changeMode() { | |
noInterrupts(); | |
if(millis() - lastInterrupt > 300) { | |
mode = (mode + 1) % 8; | |
modeChanged = 1; | |
lastInterrupt = millis(); | |
} | |
interrupts(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment