#include <Servo.h>
Servo servo;
byte servoPin = 4;
byte buttonPin[] = { 2, 3, 5, 6, 7 }; // declare button pins in an array
byte rgbled[] = { 8, 9, 11 }; // declare rgbled pins in an array
byte element; // indicates pressed button/pin
byte r, g, b, a; // RGBLED colors and servo angle
byte buttonArray = sizeof(buttonPin) / sizeof(buttonPin[0]); // get number of elements in button array
byte rgbledArray = sizeof(rgbled) / sizeof(rgbled[0]); // get number of elements in rgbled array
unsigned long timer; // timer keeps track of length of button press (or noise/ringing).
unsigned long timeout = 100; // timeout (in milliseconds) is the minimum for "a button is pressed".
void setup() {
Serial.begin(115200); // start serial monitor
for (int i = 0; i < buttonArray; i++) // count to number of elements in button array
pinMode(buttonPin[i], INPUT_PULLUP); // configure button pins for reading (LOW when pressed)
for (int i = 0; i < rgbledArray; i++) // count to number of elements in rgbled array
pinMode(rgbled[i], OUTPUT); // configure RGBLED pins
servo.write(90); // park 360 servo at "STOP" (90 degrees for 180 servo)
servo.attach(servoPin);
}
void loop() {
if (element > buttonArray) // count through array... do not use for() loops. they blocking program flow.
element = 0; // if beyond the array size, start again from the first element
if (!digitalRead(buttonPin[element])) { // button may have been pressed, or just noise/ringing
if (millis() - timer > timeout) { // measure time from last "press" to this "press. replaces delay();
if (digitalRead(buttonPin[element])) { // valid button was released after debounce timeout
timer = millis(); // reset timer after valid button press
switch (element) {
case 0: r = HIGH, g = LOW, b = LOW, a = 180; break; // red, r, fast
case 1: r = LOW, g = HIGH, b = LOW, a = 135; break; // grn, r, slow
case 2: r = HIGH, g = HIGH, b = HIGH, a = 90; break; // wht, stop
case 3: r = LOW, g = LOW, b = HIGH, a = 45; break; // blu, l, slow
case 4: r = HIGH, g = HIGH, b = LOW, a = 0; break; // yel, l, fast
default: break;
}
ledServo(r, g, b, a); // change RGBLED color and servo angle
}
}
}
element++; // next array element
}
void ledServo(byte r, byte g, byte b, int angle) {
digitalWrite(rgbled[2], r);
digitalWrite(rgbled[1], g);
digitalWrite(rgbled[0], b);
servo.write(angle);
}
CCW medium
(135 degrees)
CCW maximum
(180 degrees)
CW medium
(45 degrees)
CW maximum
(0 degrees)
STOP (90)