I'm working on controlling an Adafruit NeoPixel strip with an Arduino and a potentiometer. Specifically, I'm trying to use the potentiometer to control how many pixels are lit up on the strip. As I turn the potentiometer "up" (i.e., increasing the value), the number of lit-up pixels increases.
However, if I try to turn the potentiometer the other way and decrease the number of lit-up pixels, then the strip will stay at whatever the last value was.
I have a method below that's called during the 'void loop()' method that read in the potentiometer data:
void readAndSendPotentiometerDataIfChanged(void) {
//Read data from analog pin 2, and scale it
int newPotentiometerValue = analogRead(A2) / 5.68;
if (newPotentiometerValue != lastPotentiometerValue) {
Serial.print("POT. value");
Serial.print(newPotentiometerValue);
lastPotentiometerValue = newPotentiometerValue;
/* The value of "colorVal" is determined by a switch, and seems to be
working properly */
if (colorVal == "RED") {
//If the value is 0, we want to clear the pixel values to white
if (lastPotentiometerValue == 0) {
clearPixels();
} else {
colorWipe(strip.Color(255, 0, 0)); // Red
}
} else if (colorVal == "BLUE") {
if (lastPotentiometerValue == 0) {
clearPixels();
} else {
colorWipe(strip.Color(0, 0, 255)); // Blue
}
}
}
}
The method below will clear out all 180 pixels on my strip to no color (clear).
void clearPixels() {
uint16_t clearColor = (127, 127, 127);
strip.setPixelColor(180, clearColor);
strip.show();
}
Here's where the pixels on the strip get set...I'm sure the problem is in the for loop below, but I haven't been able to come up with a better way to set the pixels on the strip and then turn them on:
void colorWipe(uint32_t c) {
/* Use the value of 'lastPotentiometerValue' to determine how many pixels
on the strip should be lit up */
for(uint16_t i=0; i<lastPotentiometerValue; i++) {
strip.setPixelColor(i, c);
delay(0.5);
}
strip.show();
}
Anyone have a pointer to how I could refactor my code so that the potentiometer works in both directions, and will light up or turn off the pixels on the strip as appropriate? Thank you!
EDIT Based on Ignacio's answer, I changed my colorWipe
method to this:
void colorWipe(uint32_t c) {
for (uint16_t i = lastPotentiometerValue; lastPotentiometerValue<180; i++){
uint16_t clearColor = (127, 127, 127);
strip.setPixelColor(i, clearColor);
}
for(uint16_t i=0; i<lastPotentiometerValue; i++) {
strip.setPixelColor(i, c);
delay(0.5);
}
strip.show();
}
However, now no strips are lit up.
EDIT 2
The condition was wrong; below is the code that works:
void colorWipe(uint32_t c) {
for(uint16_t i = lastPotentiometerValue; i<180; i++){
uint16_t clearColor = (0, 0, 0);
strip.setPixelColor(i, clearColor);
}
for(uint16_t i=0; i<lastPotentiometerValue; i++) {
strip.setPixelColor(i, c);
delay(0.5);
}
strip.show();
}