Giter VIP home page Giter VIP logo

Comments (27)

zombiehunter1 avatar zombiehunter1 commented on May 27, 2024 1

You need to provide 5V power feeds to both ends, you are getting voltage drop across the string
if you have already done this try the following
add #define FASTLED_ALLOW_INTERRUPTS 0 just before #include <FastLED.h>

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

No, I haven't tried injecting power to the other side yet (no pun intended).

I have uploaded two videos of the flickering.

https://youtu.be/1ME0uWs6-eA
https://youtu.be/9XuRzFD0oO4

Is this flickering caused by low voltage on the far end? Solid colors work flawless. I would like to know the physics behind the flickering, if anyone can explain that.

from esp-mqtt-json-digital-leds.

encor50 avatar encor50 commented on May 27, 2024

Try my code
https://pastebin.com/RMPasRAU
https://pastebin.com/ZLmpYK87
There is more effects and i think i know why its flickering i had the same problem with my ws2813

from esp-mqtt-json-digital-leds.

encor50 avatar encor50 commented on May 27, 2024

Because he deleted these lines form his code
#define FASTLED_INTERRUPT_RETRY_COUNT 0
#define FASTLED_ALLOW_INTERRUPTS 0
I re added them in mine plus i have some more effects or just add these 2 lines to the top of his code and it will be good

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

Thank you @zombiehunter1 and @encor50 . I will try the ``FASTLED_ALLOW_INTERRUPTS 0` thingy tonight. From what I read at the official FastLED documentation this could indeed solve my issues. Also I will checkout the added effects. Since I'm going to mount my strip behind my flatscreen tv I'm looking for more effects anyway. Running lights (light sinelon, police, etc.) are cool if the strip is visible, but probably not behind a TV.

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

Okay, I tried the two paramaters @encor50 suggested. Unfortunately no success. 😞

I did try another thing: I manually set the number of LEDs to 200 (instead of 300 which are acutally in/on the strip). Sure enough the solid effect only lights up about two thirds of the strip. Sometimes when I change color or brightness the remaining 100 LEDs change color as well. It seems to be completely random, I could not make out a pattern or reproduce at will. Just clicking around in the HA light widget atm.

Effects light sinelon or police also travel only up to the set amount of LEDs, but the LEDS at the end randomly flicker in the same colors as the effect has.

[EDIT]
Not sure if noteworthy, but when I turn the switch off, the LEDs after the set number of LEDs remain switched on and in the colors they were last in.
[/EDIT]

from esp-mqtt-json-digital-leds.

encor50 avatar encor50 commented on May 27, 2024

Check your cables ? If all good connected
And change the chipset to WS2812B

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

Since I don't have much time to spent on my hobby (wife + two kids, one only seven month old) I was hoping that this has happened to somebody in the past already. I did change the chipset to WS2812B right before uploading the sketch for the first time (like this:)

#define CHIPSET WS2812B

The last thing that remains which I didn't try yet is injecting more power on the other end. Given that my power supply can deliver enough Amps can I just wire the end of the strip to the beginning? This would look like a loop then:

Power Supply                       LED strip
  |                                    |
  V                                    V
------+                 +----------------------------+      +--------+
     +|----o------------|(+) - - - - - - - - - - - -/      / - - - - |------------+
      |    |            |(D) - - - - - - - - - - - /      /- - - - - |            |
     -|-----------o-----|(G) - - - - - - - - - - -/      / - - - - - |------+     |
------+    |      |     +------------------------+      +------------+      |     |
           |      |                                                         |     |
           |      |                                                         |     |
           |      +---------------------------------------------------------+     |
           |                                                                      |
           +----------------------------------------------------------------------+

I'm not very good with electricity... This won't fry my circuits, right? 😅

from esp-mqtt-json-digital-leds.

zombiehunter1 avatar zombiehunter1 commented on May 27, 2024

This is the correct wiring, remember it's not a current problem it's a voltage problem. the first led will receive 5v but as we get further down the string the voltage will be less due to resistance in the wire e.t.c. . the ws28xx chips need a stable 5 volts to work correctly.

My first experience with this was with a string 50 10mm ws2812's . I had the same problem powering both ends fixed it.

if you are going to use the full 5 meters you may also need to inject power in multiple locations

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

Well, this sounds promising. Going to try that tonight. Will report back here.

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

I hooked up power to the other end of the strip, but unfortunately this didn't change anything. The sinelon effect for instance seems even worse than before. A lot of the LEDs don't light up when they should and some show the wront color (colors and affected LEDs change randomly on each loop).

[EDIT]
Well, one thing has changed for sure. The effects all run faster than before (with only power to one end).
[/EDIT]

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

I've decided to attach the strip to my TV regardless of the current issues. I was hoping that the flickering would go away when the strip length reduces. Unfortunately, no. 😞

Now I have one more issue. The LEDs at the top are noticably dimmer when the brightness is set to max.

Full brightness:

img_20171031_205306_304

Brightness set to 50%:

img_20171031_205328_812

What's weird about this: I inject power to both ends of the strip and the strip is not 5m anymore but only about 3m, which is 179 LEDs in total. When I touch the upper corner joints the brightness changes, so naturally I assumed that the connection is too "flaky" (excuse my choice of words, I'm not an english native). But what I mean is that the resistance at the joints is too high and I'm dealing with some sort of voltage drop(?). So I used some wire to bridge over the joints in parallel, but the brightness didn't change at all. This occures more visibly when the color is set to white, but it is still noticable when using other colors like green or purple (of course, only when brightness is set to max).

I'm not planning to illuminate the whole room with my moodlight, so for the time I'll guess I just leave it as it is and don't set the strip to full brightness. And I wanted to share (intermediate) result with you guys, since it already looks amazing:

effect
police

(Unfortunately you cannot really see the flickering when converting the videos I shot on my phone to GIF.)

from esp-mqtt-json-digital-leds.

jainsarthak avatar jainsarthak commented on May 27, 2024

I have the same problem. Powering at both ends made colors better but did not fix this.

I tried some test code from Adafruit_NeoPixel.h, that works without any issues. So I believe either it is something to do with Fastled, probably.

@riker09 Did you try changing the Fastled option NEO_KHZ800 to NEO_KHZ400? I'll play with options tonight and report if I get anything.

If nothing works, I''ll try to reimplement it using Adafruit_NeoPixel instead of FastLED

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

@jainsarthak I was just messing around with my moodlight tonight and bought a voltage meter to see if I'm dealing with voltage drop. Matter of fact, I do. Running a second power line to one of the upper cornes significantly improves brightness of the top led strip. Not to full brightness though, but it was just an experiment to see where my brightness issues were coming from. I'm going to order some more wires and will inject power on both top corners, that should take care of that.

The flickering is still another mystery to me. I did try to use Adafruit_NeoPixel.h, but my strip would not light up at all. I tried to keep the OTA and WiFi part from Bruhs original implementation intact, since the NodeMCU is mounted behind my wall-mounted TV and thus difficult to reach via USB cable. I was able to flash it a couple of times but then it seemed I broke something. Had to unmount my TV today, commented out NeoPixel stuff and got it back to status quo.

Here's the code that I tried which didn't work out:

#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include "FastLED.h"
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <Adafruit_NeoPixel.h>



/************ WIFI and MQTT Information (CHANGE THESE FOR YOUR SETUP) ******************/
const char* ssid = "My WiFi"; //type your WIFI information inside the quotes
const char* password = "My super secret wifi pasword";
const char* mqtt_server = "192.168.178.99";
const char* mqtt_username = "mqtt";
const char* mqtt_password = "hahahaha";
const int mqtt_port = 1883;



/**************************** FOR OTA **************************************************/
#define SENSORNAME "tv_moodlight" //change this to whatever you want to call your device
#define OTApassword "hahahaha" //the password you will need to enter to upload remotely via the ArduinoIDE
int OTAport = 8266;



/************* MQTT TOPICS (change these topics as you wish)  **************************/
const char* light_state_topic = "home/tv_moodlight";
const char* light_set_topic = "home/tv_moodlight/set";

const char* on_cmd = "ON";
const char* off_cmd = "OFF";
const char* effect = "solid";
String effectString = "solid";
String oldeffectString = "solid";



/****************************************FOR JSON***************************************/
const int BUFFER_SIZE = JSON_OBJECT_SIZE(10);
#define MQTT_MAX_PACKET_SIZE 512



/*********************************** FastLED Defintions ********************************/
#define NUM_LEDS    179
#define DATA_PIN    5
//#define CLOCK_PIN 5
#define CHIPSET     WS2812B
#define COLOR_ORDER GRB
#define MILLION 1000000

byte realRed = 0;
byte realGreen = 0;
byte realBlue = 0;

byte red = 255;
byte green = 255;
byte blue = 255;
byte brightness = 255;



/******************************** GLOBALS for NeoPixel *******************************/
#ifdef __AVR__
  #include <avr/power.h>
#endif

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800);




/******************************** GLOBALS for fade/flash *******************************/
bool stateOn = false;
bool startFade = false;
bool onbeforeflash = false;
unsigned long lastLoop = 0;
int transitionTime = 0;
int effectSpeed = 0;
bool inFade = false;
int loopCount = 0;
int stepR, stepG, stepB;
int redVal, grnVal, bluVal;

bool flash = false;
bool startFlash = false;
int flashLength = 0;
unsigned long flashStartTime = 0;
byte flashRed = red;
byte flashGreen = green;
byte flashBlue = blue;
byte flashBrightness = brightness;



/********************************** GLOBALS for EFFECTS ******************************/
//RAINBOW
uint8_t thishue = 0;                                          // Starting hue value.
uint8_t deltahue = 10;

//CANDYCANE
CRGBPalette16 currentPalettestriped; //for Candy Cane
CRGBPalette16 gPal; //for fire

//NOISE
static uint16_t dist;         // A random number for our noise generator.
uint16_t scale = 30;          // Wouldn't recommend changing this on the fly, or the animation will be really blocky.
uint8_t maxChanges = 48;      // Value for blending between palettes.
CRGBPalette16 targetPalette(OceanColors_p);
CRGBPalette16 currentPalette(CRGB::Black);

//TWINKLE
#define DENSITY     80
int twinklecounter = 0;

//RIPPLE
uint8_t colour;                                               // Ripple colour is randomized.
int center = 0;                                               // Center of the current ripple.
int step = -1;                                                // -1 is the initializing step.
uint8_t myfade = 255;                                         // Starting brightness.
#define maxsteps 16                                           // Case statement wouldn't allow a variable.
uint8_t bgcol = 0;                                            // Background colour rotates.
int thisdelay = 20;                                           // Standard delay value.

//DOTS
uint8_t   count =   0;                                        // Count up to 255 and then reverts to 0
uint8_t fadeval = 224;                                        // Trail behind the LED's. Lower => faster fade.
uint8_t bpm = 30;

//LIGHTNING
uint8_t frequency = 50;                                       // controls the interval between strikes
uint8_t flashes = 8;                                          //the upper limit of flashes per strike
unsigned int dimmer = 1;
uint8_t ledstart;                                             // Starting location of a flash
uint8_t ledlen;
int lightningcounter = 0;

//FUNKBOX
int idex = 0;                //-LED INDEX (0 to NUM_LEDS-1
int TOP_INDEX = int(NUM_LEDS / 2);
int thissat = 255;           //-FX LOOPS DELAY VAR
uint8_t thishuepolice = 0;
int antipodal_index(int i) {
  int iN = i + TOP_INDEX;
  if (i >= TOP_INDEX) {
    iN = ( i + TOP_INDEX ) % NUM_LEDS;
  }
  return iN;
}

//FIRE
#define COOLING  55
#define SPARKING 120
bool gReverseDirection = false;

//BPM
uint8_t gHue = 0;


WiFiClient espClient;
PubSubClient client(espClient);
struct CRGB leds[NUM_LEDS];



/********************************** START SETUP*****************************************/
void setup() {
  Serial.begin(115200);
  FastLED.addLeds<CHIPSET, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS);

  setupStripedPalette( CRGB::Red, CRGB::Red, CRGB::White, CRGB::White); //for CANDY CANE
  gPal = HeatColors_p; //for FIRE

  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);

  //OTA SETUP
  ArduinoOTA.setPort(OTAport);
  // Hostname defaults to esp8266-[ChipID]
  ArduinoOTA.setHostname(SENSORNAME);

  // No authentication by default
  ArduinoOTA.setPassword((const char *)OTApassword);

  ArduinoOTA.onStart([]() {
    Serial.println("Starting");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();

  Serial.println("Ready");
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  strip.begin();
  strip.show(); 
}



/********************************** NEOPIXEL SAMPLES*****************************************/

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}



/********************************** START SETUP WIFI*****************************************/
void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

/*
  SAMPLE PAYLOAD:
  {
    "brightness": 120,
    "color": {
      "r": 255,
      "g": 100,
      "b": 100
    },
    "flash": 2,
    "transition": 5,
    "state": "ON"
  }
*/



/********************************** START CALLBACK*****************************************/
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");

  char message[length + 1];
  for (int i = 0; i < length; i++) {
    message[i] = (char)payload[i];
  }
  message[length] = '\0';
  Serial.println(message);

  if (!processJson(message)) {
    return;
  }

  if (stateOn) {

    realRed = map(red, 0, 255, 0, brightness);
    realGreen = map(green, 0, 255, 0, brightness);
    realBlue = map(blue, 0, 255, 0, brightness);
  }
  else {

    realRed = 0;
    realGreen = 0;
    realBlue = 0;
  }

  Serial.println(effect);

  startFade = true;
  inFade = false; // Kill the current fade

  sendState();
}



/********************************** START PROCESS JSON*****************************************/
bool processJson(char* message) {
  StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;

  JsonObject& root = jsonBuffer.parseObject(message);

  if (!root.success()) {
    Serial.println("parseObject() failed");
    return false;
  }

  if (root.containsKey("state")) {
    if (strcmp(root["state"], on_cmd) == 0) {
      stateOn = true;
    }
    else if (strcmp(root["state"], off_cmd) == 0) {
      stateOn = false;
      onbeforeflash = false;
    }
  }

  // If "flash" is included, treat RGB and brightness differently
  if (root.containsKey("flash")) {
    flashLength = (int)root["flash"] * 1000;

    oldeffectString = effectString;

    if (root.containsKey("brightness")) {
      flashBrightness = root["brightness"];
    }
    else {
      flashBrightness = brightness;
    }

    if (root.containsKey("color")) {
      flashRed = root["color"]["r"];
      flashGreen = root["color"]["g"];
      flashBlue = root["color"]["b"];
    }
    else {
      flashRed = red;
      flashGreen = green;
      flashBlue = blue;
    }

    if (root.containsKey("effect")) {
      effect = root["effect"];
      effectString = effect;
      twinklecounter = 0; //manage twinklecounter
    }

    if (root.containsKey("transition")) {
      transitionTime = root["transition"];
    }
    else if ( effectString == "solid") {
      transitionTime = 0;
    }

    flashRed = map(flashRed, 0, 255, 0, flashBrightness);
    flashGreen = map(flashGreen, 0, 255, 0, flashBrightness);
    flashBlue = map(flashBlue, 0, 255, 0, flashBrightness);

    flash = true;
    startFlash = true;
  }
  else { // Not flashing
    flash = false;

    if (stateOn) {   //if the light is turned on and the light isn't flashing
      onbeforeflash = true;
    }

    if (root.containsKey("color")) {
      red = root["color"]["r"];
      green = root["color"]["g"];
      blue = root["color"]["b"];
    }
    
    if (root.containsKey("color_temp")) {
      //temp comes in as mireds, need to convert to kelvin then to RGB
      int color_temp = root["color_temp"];
      unsigned int kelvin  = MILLION / color_temp;
      
      temp2rgb(kelvin);
      
    }

    if (root.containsKey("brightness")) {
      brightness = root["brightness"];
    }

    if (root.containsKey("effect")) {
      effect = root["effect"];
      effectString = effect;
      twinklecounter = 0; //manage twinklecounter
    }

    if (root.containsKey("transition")) {
      transitionTime = root["transition"];
    }
    else if ( effectString == "solid") {
      transitionTime = 0;
    }

  }

  return true;
}



/********************************** START SEND STATE*****************************************/
void sendState() {
  StaticJsonBuffer<BUFFER_SIZE> jsonBuffer;

  JsonObject& root = jsonBuffer.createObject();

  root["state"] = (stateOn) ? on_cmd : off_cmd;
  JsonObject& color = root.createNestedObject("color");
  color["r"] = red;
  color["g"] = green;
  color["b"] = blue;

  root["brightness"] = brightness;
  root["effect"] = effectString.c_str();


  char buffer[root.measureLength() + 1];
  root.printTo(buffer, sizeof(buffer));

  client.publish(light_state_topic, buffer, true);
}



/********************************** START RECONNECT*****************************************/
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect(SENSORNAME, mqtt_username, mqtt_password)) {
      Serial.println("connected");
      client.subscribe(light_set_topic);
      setColor(0, 0, 0);
      sendState();
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}



/********************************** START Set Color*****************************************/
void setColor(int inR, int inG, int inB) {
  for (int i = 0; i < NUM_LEDS; i++) {
    leds[i].red   = inR;
    leds[i].green = inG;
    leds[i].blue  = inB;
  }

  FastLED.show();

  Serial.println("Setting LEDs:");
  Serial.print("r: ");
  Serial.print(inR);
  Serial.print(", g: ");
  Serial.print(inG);
  Serial.print(", b: ");
  Serial.println(inB);
}



/********************************** START MAIN LOOP*****************************************/
void loop() {

  if (!client.connected()) {
    reconnect();
  }

  if (WiFi.status() != WL_CONNECTED) {
    delay(1);
    Serial.print("WIFI Disconnected. Attempting reconnection.");
    setup_wifi();
    return;
  }

  client.loop();

  ArduinoOTA.handle();

  // Some example procedures showing how to display to the pixels:
  colorWipe(strip.Color(255, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 255, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 255), 50); // Blue
  // Send a theater pixel chase in...
  theaterChase(strip.Color(127, 127, 127), 50); // White
  theaterChase(strip.Color(127, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 127), 50); // Blue
  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);

}


/**************************** START TRANSITION FADER *****************************************/
// From https://www.arduino.cc/en/Tutorial/ColorCrossfader
/* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS
  The program works like this:
  Imagine a crossfade that moves the red LED from 0-10,
    the green from 0-5, and the blue from 10 to 7, in
    ten steps.
    We'd want to count the 10 steps and increase or
    decrease color values in evenly stepped increments.
    Imagine a + indicates raising a value by 1, and a -
    equals lowering it. Our 10 step fade would look like:
    1 2 3 4 5 6 7 8 9 10
  R + + + + + + + + + +
  G   +   +   +   +   +
  B     -     -     -
  The red rises from 0 to 10 in ten steps, the green from
  0-5 in 5 steps, and the blue falls from 10 to 7 in three steps.
  In the real program, the color percentages are converted to
  0-255 values, and there are 1020 steps (255*4).
  To figure out how big a step there should be between one up- or
  down-tick of one of the LED values, we call calculateStep(),
  which calculates the absolute gap between the start and end values,
  and then divides that gap by 1020 to determine the size of the step
  between adjustments in the value.
*/
int calculateStep(int prevValue, int endValue) {
  int step = endValue - prevValue; // What's the overall gap?
  if (step) {                      // If its non-zero,
    step = 1020 / step;          //   divide by 1020
  }

  return step;
}
/* The next function is calculateVal. When the loop value, i,
   reaches the step size appropriate for one of the
   colors, it increases or decreases the value of that color by 1.
   (R, G, and B are each calculated separately.)
*/
int calculateVal(int step, int val, int i) {
  if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
    if (step > 0) {              //   increment the value if step is positive...
      val += 1;
    }
    else if (step < 0) {         //   ...or decrement it if step is negative
      val -= 1;
    }
  }

  // Defensive driving: make sure val stays in the range 0-255
  if (val > 255) {
    val = 255;
  }
  else if (val < 0) {
    val = 0;
  }

  return val;
}



/**************************** START STRIPLED PALETTE *****************************************/
void setupStripedPalette( CRGB A, CRGB AB, CRGB B, CRGB BA) {
  currentPalettestriped = CRGBPalette16(
                            A, A, A, A, A, A, A, A, B, B, B, B, B, B, B, B
                            //    A, A, A, A, A, A, A, A, B, B, B, B, B, B, B, B
                          );
}



/********************************** START FADE************************************************/
void fadeall() {
  for (int i = 0; i < NUM_LEDS; i++) {
    leds[i].nscale8(250);  //for CYCLon
  }
}



/********************************** START FIRE **********************************************/
void Fire2012WithPalette()
{
  // Array of temperature readings at each simulation cell
  static byte heat[NUM_LEDS];

  // Step 1.  Cool down every cell a little
  for ( int i = 0; i < NUM_LEDS; i++) {
    heat[i] = qsub8( heat[i],  random8(0, ((COOLING * 10) / NUM_LEDS) + 2));
  }

  // Step 2.  Heat from each cell drifts 'up' and diffuses a little
  for ( int k = NUM_LEDS - 1; k >= 2; k--) {
    heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2] ) / 3;
  }

  // Step 3.  Randomly ignite new 'sparks' of heat near the bottom
  if ( random8() < SPARKING ) {
    int y = random8(7);
    heat[y] = qadd8( heat[y], random8(160, 255) );
  }

  // Step 4.  Map from heat cells to LED colors
  for ( int j = 0; j < NUM_LEDS; j++) {
    // Scale the heat value from 0-255 down to 0-240
    // for best results with color palettes.
    byte colorindex = scale8( heat[j], 240);
    CRGB color = ColorFromPalette( gPal, colorindex);
    int pixelnumber;
    if ( gReverseDirection ) {
      pixelnumber = (NUM_LEDS - 1) - j;
    } else {
      pixelnumber = j;
    }
    leds[pixelnumber] = color;
  }
}



/********************************** START ADD GLITTER *********************************************/
void addGlitter( fract8 chanceOfGlitter)
{
  if ( random8() < chanceOfGlitter) {
    leds[ random16(NUM_LEDS) ] += CRGB::White;
  }
}



/********************************** START ADD GLITTER COLOR ****************************************/
void addGlitterColor( fract8 chanceOfGlitter, int red, int green, int blue)
{
  if ( random8() < chanceOfGlitter) {
    leds[ random16(NUM_LEDS) ] += CRGB(red, green, blue);
  }
}



/********************************** START SHOW LEDS ***********************************************/
void showleds() {

  delay(1);

  if (stateOn) {
    FastLED.setBrightness(brightness);  //EXECUTE EFFECT COLOR
    FastLED.show();
    if (transitionTime > 0 && transitionTime < 130) {  //Sets animation speed based on receieved value
      FastLED.delay(1000 / transitionTime);
      //delay(10*transitionTime);
    }
  }
  else if (startFade) {
    setColor(0, 0, 0);
    startFade = false;
  }
}
void temp2rgb(unsigned int kelvin) {
    int tmp_internal = kelvin / 100.0;
    
    // red 
    if (tmp_internal <= 66) {
        red = 255;
    } else {
        float tmp_red = 329.698727446 * pow(tmp_internal - 60, -0.1332047592);
        if (tmp_red < 0) {
            red = 0;
        } else if (tmp_red > 255) {
            red = 255;
        } else {
            red = tmp_red;
        }
    }
    
    // green
    if (tmp_internal <=66){
        float tmp_green = 99.4708025861 * log(tmp_internal) - 161.1195681661;
        if (tmp_green < 0) {
            green = 0;
        } else if (tmp_green > 255) {
            green = 255;
        } else {
            green = tmp_green;
        }
    } else {
        float tmp_green = 288.1221695283 * pow(tmp_internal - 60, -0.0755148492);
        if (tmp_green < 0) {
            green = 0;
        } else if (tmp_green > 255) {
            green = 255;
        } else {
            green = tmp_green;
        }
    }
    
    // blue
    if (tmp_internal >=66) {
        blue = 255;
    } else if (tmp_internal <= 19) {
        blue = 0;
    } else {
        float tmp_blue = 138.5177312231 * log(tmp_internal - 10) - 305.0447927307;
        if (tmp_blue < 0) {
            blue = 0;
        } else if (tmp_blue > 255) {
            blue = 255;
        } else {
            blue = tmp_blue;
        }
    }
}

Note: I did remove the effects from the original code since the fastLED is disabled anyw. Im guessing the FastLED include interfers with NeoPixel somehow=

from esp-mqtt-json-digital-leds.

jainsarthak avatar jainsarthak commented on May 27, 2024

@riker09 your strip is not lighting up with Adafruit_NeoPixel because NeoPixel does not translate your GPIO pin to DPIN. for example I use Nodemcu and for me DATA_PIN 1 in FastLED is same as pin 5 in Adafruit_NeoPixel. Both of these send data to pin labeled "D1" on my microcontroller.

You are using pin 5, that I believe will become 14 as per this:
https://github.com/FastLED/FastLED/blob/master/platforms/esp/8266/fastpin_esp8266.h#L87

Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, DATA_PIN, NEO_GRB + NEO_KHZ800);

from esp-mqtt-json-digital-leds.

jainsarthak avatar jainsarthak commented on May 27, 2024

OMG this fixed the flickering

#define FASTLED_ALLOW_INTERRUPTS 0

got from krzychb/EspFire2012@524b8ba

cc @bruhautomation please add it

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

I did have the #define FASTLED_ALLOW_INTERRUPTS 0 thing in my configuration before, but that didn't change anything so I threw it away again. But according to issue #60 I have to define this before including the FastLED library. So this needs to go in line 4.

I will try that as soon as I find some time and will report my findings back here.

from esp-mqtt-json-digital-leds.

Diaoul avatar Diaoul commented on May 27, 2024

I'd live to know if that actually works or not. I have some WS2811 lying around and I know I could not use them with ESP8266 directly due to timing issues with more than approx 60 LEDs some time ago.
Also, do you use 3.3V-5V level shifters? I've had some success driving them directly from 3.3V.

from esp-mqtt-json-digital-leds.

Philje123 avatar Philje123 commented on May 27, 2024

I was having terrible flickering issues/wrong colours/leds remaining on etc. I am using WS2811 12v strip with 69 LEDs. And using an ESP-01.

I found that I needed to have 12v ground attached to the 3.3v ground of the ESP. This completely fixed my issues. There is no reference to this in the Bruh instructions but found reference to it elsewhere online.

I am now just having a couple of small issues where with an effect running certain sections of the strip will flicker slightly. Will try the #define FASTLED_ALLOW_INTERRUPTS 0 suggested above and report back. Good job for Arduino OTA!

from esp-mqtt-json-digital-leds.

craig3050 avatar craig3050 commented on May 27, 2024

Similar problem, using #define FASTLED_ALLOW_INTERRUPTS 0 just before declaring the FastLED library sorted my problem too. Thanks!

from esp-mqtt-json-digital-leds.

Philje123 avatar Philje123 commented on May 27, 2024

Compiled and uploaded with #define FASTLED_ALLOW_INTERRUPTS 0. Perfect now!

Thanks guys.

Just waiting for a couple of Wemos D1s to arrive and I can sort my LED strip round the TV.

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

My additional wire arrived today, so I'll probably do some soldering tonight. The OTA broke for some reason, otherwise I would've tried the #define FASTLED_ALLOW_INTERRUPTS 0 already. But now I have to dismount my TV anyway... :)

I do not use a 3.3V -> 5V level shifter. My WS2812B is directly hooked up to PIN 5 of my NodeMCU.

@Philje123 When I initially wired everything together I also had some terrible flickering because the NodeMCU and the strip were not sharing a common ground. I found a hint about this somewhere on the internet. Good to see that I'm not the only one who ran into this issue. Maybe the documentation could use some improvements?

from esp-mqtt-json-digital-leds.

Philje123 avatar Philje123 commented on May 27, 2024

It should still work without the level shifter depending on the length of cable from your NodeMCU to the strip. Since the signal only has to get to the first LED and is then repeated along the chain.

I tried without the level shifter and the common ground and it seemed to work ok. But kept the shifter in the circuit since I already had it and to make sure it worked.

As for OTA I found you have to have all the upload settings matching the device you are trying to update.

And yes I think the documentation needs to mention the common ground. I wonder why this problem is not always encountered.

from esp-mqtt-json-digital-leds.

Diaoul avatar Diaoul commented on May 27, 2024

And yes I think the documentation needs to mention the common ground. I wonder why this problem is not always encountered.

Because it's common knowledge. And that's also the reason why it's not explained, maybe it was obvious for the writer and he didn't think writing that down.

As for level shifting, the datasheet says it requires 5V signal, it may work at 3.3V depending on how strong the voltage is. YMMV though and if you experience problems this is the first thing I'd investigate.

For those who tried #define FASTLED_ALLOW_INTERRUPTS 0: do you experience that your WiFi is flaky or sometimes doesn't respond to commands?

from esp-mqtt-json-digital-leds.

Philje123 avatar Philje123 commented on May 27, 2024

Well I wouldn't say it's common knowledge. All the wiring diagrams I've seen (including this one) does not show a common ground connection.

It also seemed strange to me to have the 12v ground tied to the 3.3v ground.

I'll keep an eye on it over the next few days but so far it hasn't affected the wifi.

from esp-mqtt-json-digital-leds.

craig3050 avatar craig3050 commented on May 27, 2024

The Wifi was fine. I have made a reasonably long strip (about 280) of WS2811 for round the edge of the house at Christmas. For that I needed to inject power at least 3 points, as I was dropping to about 2.8V in the middle.
Without using the #define FASTLED_ALLOW_INTERRUPTS 0 , I found that the lights in the middle of the chain were flickering when using some of the effects. - most noticeably with the Rainbow effect.

from esp-mqtt-json-digital-leds.

riker09 avatar riker09 commented on May 27, 2024

I did it. The top strip is as bright as the rest of the strip thanks to some injected power. The flickering is gone thanks to the define bugfix. Thanks to all the little hints I got from this thread. You guys are amazing. And since this looks like a valid workaround I will go ahead and close this issue.

from esp-mqtt-json-digital-leds.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.