// Note that pin 7 is not PWM
// See: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/
// Global variables
int green_light_pin = 5; ;// Green pin connected to digital pin 5
int blue_light_pin = 6; // Blue pin connected to digital pin 6
int red_light_pin = 9; // Red pin connected to digital pin 9
int switch_on_pin = 11; // switch on pin connected to digital pin 11
int switch_off_pin = 10; // switch off pin connected to digital pin 10
int previousLEDval = 0;
// Setup
void setup() {
// initialize serial communication:
Serial.begin(9600);
Serial.println( "The sketch has started");
pinMode(green_light_pin, OUTPUT); // sets the greenPin as an output
pinMode(blue_light_pin, OUTPUT); // sets the bluePin as an output
pinMode(red_light_pin, OUTPUT); // sets the redPin as an output
pinMode(switch_on_pin, INPUT_PULLUP); // declare on switch as input + activate internal pull-up resistor
pinMode(switch_off_pin, INPUT_PULLUP); // declare off switch as input + activate internal pull-up resistor
// soft glow after start
RGB_color(15, 15, 15);
} // close setup
// Loop
void loop()
{
// Definition for LEDval
// 0 = centre/idle, 1 = red/up/on, 2 = green/down/off, -1 error
int LEDval;
int switch_on_val = digitalRead(switch_on_pin); // read the state
int switch_off_val = digitalRead(switch_off_pin); // read the state
if (switch_on_val == HIGH and switch_off_val == HIGH)
{
// Neither is pressed, switch in central position
LEDval = 0;
}
else if (switch_on_val == LOW and switch_off_val == HIGH)
{
// Button 'up' or 'on' is pressed, and the other is not.
LEDval = 1;
}
else if (switch_on_val == HIGH and switch_off_val == LOW)
{
// Button 'down' or 'off' is pressed, and the other is not.
LEDval = 2;
}
else
{
// Both are pressed, that is an error
LEDval = -1;
}
if( LEDval != previousLEDval)
{
switch (LEDval) // Select the RGB colour according to switch value
{
case 0: // central position, Blue
RGB_color(0, 0, 255);
Serial.println("Switch in CENTRE BLUE position");
break;
case 1: // Red
RGB_color(255, 0, 0);
Serial.println("Switch in RED position");
break;
case 2: // Green
RGB_color(0, 255, 0);
Serial.println("Switch in GREEN position");
break;
case -1: // both are pressed, not valid
RGB_color(0, 0, 0);
break;
default:
Serial.println( "Error");
break;
}
previousLEDval = LEDval;
}
delay(10); // a small delay for debouncing
}
void RGB_color(int r, int g, int b)
{
analogWrite(red_light_pin, r);
analogWrite(green_light_pin, g);
analogWrite(blue_light_pin, b);
}