Project 04
Potentiometer — LED wave
The code.
void loop() {
int potValue = analogRead(POT_PIN);
// Initialize all LED brightness levels to 0 (off)
int b1 = 0, b2 = 0, b3 = 0, b4 = 0;
// LED 1 Zone: 0 to 255
if (potValue >= 0 && potValue < 256) {
b1 = calculateBrightness(potValue);
}
// LED 2 Zone: 256 to 511
else if (potValue >= 256 && potValue < 512) {
b2 = calculateBrightness(potValue - 256);
}
// LED 3 Zone: 512 to 767
else if (potValue >= 512 && potValue < 768) {
b3 = calculateBrightness(potValue - 512);
}
// LED 4 Zone: 768 to 1023
else if (potValue >= 768 && potValue <= 1023) {
b4 = calculateBrightness(potValue - 768);
}
// Send the calculated fading brightness to the PWM pins
analogWrite(LED_1, b1);
analogWrite(LED_2, b2);
analogWrite(LED_3, b3);
analogWrite(LED_4, b4);
delay(5); // Small delay for stable readings
}
// Helper function to turn a 0-255 position into a fade up/down brightness (0-255)
int calculateBrightness(int localValue) {
if (localValue < 128) {
// First half: Fade UP (0 to 127 steps map to 0 to 254 brightness)
return localValue * 2;
} else {
// Second half: Fade DOWN (128 to 255 steps map back down to 0 brightness)
return (255 - localValue) * 2;
}
}