Require components:
1x Arduino Uno
1x Traffic Light
4x red/black/yellow/green wires
Video:
Code:
const byte PIN_GREEN = 11;
const byte PIN_YELLOW = 10;
const byte PIN_RED = 9;
void setup() {
pinMode(PIN_GREEN, OUTPUT);
pinMode(PIN_YELLOW, OUTPUT);
pinMode(PIN_RED, OUTPUT);
Serial.begin(9600);
}
void setColor(byte red, byte yellow, byte green) {
Serial.print("setColor(");
Serial.print(red);
Serial.print(", ");
Serial.print(yellow);
Serial.print(", ");
Serial.print(green);
Serial.println(") ");
analogWrite(PIN_RED, red);
analogWrite(PIN_YELLOW, yellow);
analogWrite(PIN_GREEN, green);
}
void show1LED() {
Serial.println("show1LED()");
setColor(255, 0, 0); delay(1000); // red
setColor(0, 255, 0); delay(1000); // yellow
setColor(0, 0, 255); delay(1000); // green
}
void show2LEDs() {
Serial.println("show2LEDs()");
setColor(255, 255, 0); delay(1000); // red & yellow
setColor(0, 255, 255); delay(1000); // yellow & green
setColor(255, 0, 255); delay(1000); // red & green
}
void show3LEDs() {
Serial.println("show3LEDs()");
setColor(0, 0, 0); delay(1000); // turn off
setColor(255, 255, 255); delay(1000); // turn on all colors
setColor(0, 0, 0); delay(1000); // turn off
}
void fadeColor(byte red, byte yellow, byte green) {
Serial.print("fadeColor(");
Serial.print(red);
Serial.print(", ");
Serial.print(yellow);
Serial.print(", ");
Serial.println(green);
byte total = 8; // should mod for 256 = 0;
for(byte current = 0; current <= total; current++) { // fade in
byte r = red / total * current ;
byte y = yellow / total * current;
byte g = green / total * current;
setColor(r, y, g);
delay(100);
}
for(byte current = total - 1; current > 0; current--) { // fade out
red = red / total * current;
yellow = yellow / total * current;
green = green / total * current;
setColor(red, yellow, green);
delay(100);
}
setColor(0, 0, 0);
delay(100);
}
void fade1LED() {
Serial.println("fade1LED()");
fadeColor(255, 0, 0); delay(1000); // red
fadeColor(0, 255, 0); delay(1000); // yellow
fadeColor(0, 0, 255); delay(1000); // green
}
void fade2LEDs() {
Serial.println("fade2LEDs()");
fadeColor(255, 255, 0); delay(1000); // red & yellow
fadeColor(0, 255, 255); delay(1000); // yellow & green
fadeColor(255, 0, 255); delay(1000); // red & green
}
void fade3LEDs() {
Serial.println("fade3LEDs()");
fadeColor(0, 0, 0); delay(1000); // turn off
fadeColor(255, 255, 255); delay(1000); // turn on all colors
fadeColor(0, 0, 0); delay(1000); // turn off
}
void showAllColors() {
Serial.println("showAllColors()");
byte increasement = 32; // should mod for 256 = 0, ex: 1, 2, 4, 6, 8, 16, 32, 64, 128, 256
for(short red = 0; red <= 256; red += increasement) {
for(short yellow = 0; yellow <= 256; yellow += increasement) {
for(short green = 0; green <= 256; green += increasement) {
setColor(min(255, red), min(255, yellow), min(255, green));
delay(100);
}
}
}
}
void loop() {
show1LED();
show2LEDs();
show3LEDs();
fade1LED();
fade2LEDs();
fade3LEDs();
showAllColors();
}
No comments:
Post a Comment