Hello everyone, I'm fairly new to arduino and I'm looking for a little help.
I'm working on a little project where the arduino is supposed to switch between different LEDs when a button is pressed and the brightness of the LEDs is supposed to be controlled by a potentiometer. Fairly simple.
It's working almost as I intended, except for the fact that the brightness of the LEDs changes only when I switch between one another, which is what brings me here, because I can't figure out how to make it work without starting from scratch again. (= I want it so that the brightness changes immediately after adjusting the potentiometer)
Thank you for your time even if you only read about my problem.
Here is my code:
#define LED_1_PIN 6
#define LED_2_PIN 5
#define LED_3_PIN 3
#define BUTTON_PIN 13
#define LED_NUMBER 3
#define analogInPin A0
byte LEDPinArray[LED_NUMBER] = {LED_1_PIN, LED_2_PIN, LED_3_PIN};
unsigned long debounceDuration = 50;
unsigned long lastTimeButtonStateChanged = 0;
byte lastButtonState = HIGH;
int LEDIndex = 0;
int sensorValue = 0;
int outputValue = 0;
void initAllLEDs()
{
for (int i = 0; i < LED_NUMBER; i++) {
pinMode(LEDPinArray[i], OUTPUT);
}
}
void powerOnSelectedLEDOnly(int index, int value)
{
for (int i = 0; i < LED_NUMBER; i++) {
if (i == index) {
analogWrite(LEDPinArray[i], value);
}
else {
analogWrite(LEDPinArray[i], 0);
}
}
}
void setup() {
initAllLEDs();
pinMode(BUTTON_PIN, INPUT_PULLUP);
digitalWrite(LEDPinArray[LEDIndex], HIGH);
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(analogInPin);
outputValue = map(sensorValue, 0, 1023, 0, 255);
unsigned long timeNow = millis();
if (timeNow - lastTimeButtonStateChanged > debounceDuration) {
byte buttonState = digitalRead(BUTTON_PIN);
if (buttonState != lastButtonState) {
lastTimeButtonStateChanged = timeNow;
lastButtonState = buttonState;
if (buttonState == HIGH) { // button has been released
LEDIndex++;
if (LEDIndex >= LED_NUMBER) {
LEDIndex = 0;
}
powerOnSelectedLEDOnly(LEDIndex, outputValue);
}
}
}
Serial.print("sensor = ");
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);
delay(2);
}