Hej,
a NeoPixel ring with 24 LEDs is illuminated with a fading trail clockwise and a button press makes it reverse direction any time it is pressed.
This works, but there’s a glitch - when I serial print ledPos, I get 1-24 going forward, but 23-0 going backward, so the 1st LED never lights up when going backward. What am I doing wrong?
Thanks!
#include "FastLED.h"
#define NUM_LEDS 24
#define DATA_PIN 4
const byte pinSensor = A0;
const byte pinPotentiometer = A1;
const byte pinSwitch = A2; // Pin to which the momentary switch is connected
byte lastSwitchState = HIGH; // Switch is open at start
int ambientLightLevel, lightLevelMax = 1023, lightLevelMin = 0;
byte ledPos = 0; // Position in LED array at start
int counter = 1; // Increment at start
struct CRGB leds[NUM_LEDS];
void setup() {
FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
pinMode (pinSwitch, INPUT_PULLUP);
}
void loop() {
int changeHue = map(analogRead(pinPotentiometer), 0, 1024, 0, 256);
ambientLightLevel = analogRead(pinSensor);
autoDim();
byte switchState = digitalRead (pinSwitch); // Switch is hardware debounced
if (switchState != lastSwitchState)
{
lastSwitchState = switchState;
if (switchState == LOW)
{
counter = -counter;
}
}
EVERY_N_MILLISECONDS(20)
{
fadeToBlackBy(leds, NUM_LEDS, 128);
leds[ledPos] = CHSV(changeHue, 255, 255);
ledPos = ledPos + counter;
Serial.println(ledPos);
if (ledPos == NUM_LEDS)
{
ledPos = 0;
}
else if (ledPos == 0)
{
ledPos = NUM_LEDS;
}
FastLED.show();
}
}
void autoDim()
{
FastLED.setBrightness(128); // Later ambient light level calculated here
}