The exercice was to to do an intervention using what we’ve learned during last week’s class, aka the use of the push button and the potentiometer with LEDs.
I got in my possession a RGB LED that I’ve really wanted to try out. Basically, I wanted the push button to light on / off the LED, and the potentiometer to change the RGB value of the LED.
The RGB LED got 4 legs, the 2nd leg which is the longest one is (-) while the others legs are (+). I connected the three (+) legs into the digital input, and the (-) into the ground. For each (+) leg, I used a 330Ω resistor.
Then, I connected the push button and the potentiometer, following what I’ve been taught previously. I used a 10KΩ resistor for the push button.
Here is the code ↓↓↓
int redPin = 1; int greenPin = 2; int bluePin = 3; int buttonPin = 7; int potPin = A0; int val = 0; boolean ledState = LOW; boolean prevBtnState = LOW; void setup() { pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); pinMode(buttonPin, INPUT); pinMode(potPin, INPUT); } void setColor (int red, int green, int blue) { analogWrite(redPin, 255 - red); analogWrite(greenPin, 255 - green); analogWrite(bluePin, 255 - blue); } void loop() { boolean btnState = digitalRead(buttonPin); int val = analogRead(potPin); if (btnState == HIGH && prevBtnState == LOW) { if (val < 100) { setColor(255, 0, 0); } if (val >= 100) { setColor(0, 255, 0); } if (val > 400) { setColor(0, 0, 255); } } digitalWrite(redPin, ledState); digitalWrite(greenPin, ledState); digitalWrite(bluePin, ledState); //prevBtnState = btnState; }
I’ve followed last week’s code to write this new one, and I researched tutorials (notably on Adafruit) to implement the RGB LED’s part.
However, it didn’t work out exactly the way I wanted since I can’t seem to work out the part where the switch stays on / off until its next state’s change. I can’t figure it out for now but it still works for the most part. Hopefully, as I get more comfortable with Arduino, I’ll get back to it later and solve it.