Using one PIR and one LDR for two boards

Hi

I am working on a project where my house number has a LEDstrip in it with some effects and two other LEDstrips that will illuminate part of the front. The 2 lager strips will have no animation other than color and brightness when motion is detected. The number basically only reacts to the LDR.

I had some problems fully understanding FastLED so I duplicated my code and removed the PIR and LDR stuff and used two buttons to initiate the LDR and PIR pseudo states. I have that code running (alsmost) as I want but when I combine them, the 'LEDeffects' from the number cause delays (and a flickering) in the code that drives the 2 other LEDstrips. I used millis in my own code but replacing the delays in the animation/effects code (not mine) is not really working out so well.

Now I would like to control both items (number and illumination strips) separately to overcome the flicker and delay, but I really would not like to add extra sensors (and wires).

Is it possible, since both are input sensors, to split them to two boards? So that both boards have LDR and PIR input from one set of sensors? If so, are there possible issues?

Thanks in advance!

if You post that combined code we can see what we find.
Reading an LDR and checking a PIR sensor should not be that difficult.

Thanks Railroader,
I will clean my code a bit and remove the (massive amount) of comments and unused code first.

Whats causing my problem is the effectcode. I have a 3 way switch to select out of 3 different effects. If I clear the first effect (no code to execute) it works fine. When I go to effect 3 (fire simulation) it's having a harder time to process it and the flickering is there (every x seconds), which is annoying to say the least.

The more I think about it, the more I would like to split this into two projects. Not because I'm too lazy to learn/adapt but practically it would be better too.

So, I will upload the sketch but my main question is still if I can use one sensor for 2 boards.

Thanks!

ETA: I am using FastLed to control two separate LED strips, one for the number and one for the illumination of the front of the driveway.

Giving up is not what I like. Don't remove relevant comments from code being in use! Check that it's correct!

To connect and read an LDR from 2 different boards is no problem.
If I see Your code I might be able to say something about sharing a PIR.

#define FASTLED_INTERNAL                // irritante waarschuwing uitzetten van fastled
#include "FastLED.h"                    // fastled lib laden

/*
 * BEKNOPTE UITLEG NUMMER ZEVEN EN LEDSTRIPS (LEDS2).
 * Gebruik wordt gemaakt van WS2812 programmeerbare ledstrips. Dit zijn de 5v versies, 3 pins waarvan 1 datapin.
 * De LDR meet constant op intervals 2 waarden en neemt een gemiddelde. Als gemiddelde hoger is dan de LDRtrigger
 * dan wordt een dimStatus op 1 gezet: verlichting mag gedimd aan. Het nummer heeft een eigen gemiddelde en zal
 * daardoor eerder aanspringen. Als dimStatus=1 dan gaan de PIR metingen er ook toe doen.
 * 
 * De PIR zet PIRstatus HIGH of Low. Zodra het HIGH gaat, gaat de PIRval óók HIGH. Vervolgens gaat het licht x-minuten
 * aan. Als de PIRstatus LOW is, dus geen beweging meer, dan verloopt de tijd gewoon en gaat de PIRstatus weer naar LOW, 
 * en dus licht uit. Gaat de PIR wéér HIGH terwijl die tijd nog niet is verlopen, dan reset de tijd dat het aan moet 
 * blijven weer naar maximum, etc.
 * 
 * Als het licht gedimd aan is en de PIR gaat HIGH (dus detectie) dan gaat het licht van de basiskleur naar wit en vol
 * vermogen (fade up) en blijft aan zolang de PIRstatus HIGH is. Wanneer er geen beweging meer is gaat het naar de
 * basiskleur én dimming terug.
 * 
 * Het nummer 7 heeft een eigen strip en controller deel (LEDS1). Deze kunnen eerder aan gaan door de deelwaarde aan te
 * passen in :nummerGemiddeld = (metingA+metingB)/1.25;. Afhankelijk van de status van e 3-weg schakelelaar wordt er 1
 * van de drie effecten gekozen. Grotere switch of array? Meer effecten :)
 */

// +++ Code voor nummer 7 +++
#define LED_PIN_ZEVEN     7             // led pin voor nummer 7 output
#define NUM_LEDS_ZEVEN    30            // aantal leds in keten
CRGB leds1[NUM_LEDS_ZEVEN];             // fastled library aanpreken en aantal LEDs voor calculatie
int nummerGemiddeld = 0;                // is gelijk aan dimStatus maar wordt voor de zeven gebruikt, kan ie eerder aan
int nummerStatus = 1;                   // hebben we de LDR trigger bereikt?
int effect = 2;                         // welk effect moet er draaien
int RPin = 5;                           // rechter pin van on/off/on switch
int LPin = 3;                           // linker pin van on/off/on switch (middelste is GND)

// +++ Code voor andere strips +++
#define LED_PIN_ACHT     8              // led pin voor andere strips output
#define NUM_LEDS_ACHT    30             // aantal leds in keten
CRGB leds2[NUM_LEDS_ACHT];              // fastled library aanpreken en aantal LEDs voor calculatie
int dimMin = 30;                       // hoeveel licht wanneer er geen beweging is
int dimMax = 245;                       // maximale verlichting bij beweging
int dimval;
int dimStatus = 0;                      // Uit = 0, gedimd aan is 1, maximaal aan is 2
int Rgb = 100;
int rGb = 20;
int rgB = 143;

// +++ Maar voor alle strips is geldig:
#define COLOR_ORDER RGB                 // kleurvolgorde GRB
#define CHIPSET     NEOPIXEL            // WS2812
#define FRAMES_PER_SECOND 60            // controleren op flikkeren....
bool gReverseDirection = false;         // looprichting eventueel omdraaien mocht dat nodig zijn...

// +++ sensor +++
int PIRpin = 10;                        // PIR 10
int PIRstatus = 0 ;                    // standaard geen detectie, dus uit
int PIRval = 0;                         // de staat van de pir sensor bewaren
int LDRpin = 11;                        // LDR 11
int LDRtrigger  = 125;                  // wanneer moet LDR iets regelen (is ANDERS dan de dimMin!)
int metingA = 0;                        // eerste meeting LDR, deze lager dan B zetten ivm opstart loop!!
int metingB = 0;                        // tweede meeting LDR
int meting = 1;                         // 1 = A, 2 = B waarde intellen
int gemiddeld = 0;                      // wat is de huidige gemiddelde waarde
const unsigned long LDRinterval = 5000; // tijd tussen de meting van LDR
const unsigned long PIRinterval = 5000; // tijd dat licht aan moet blijven na beweging detectie
unsigned long resetTime = 0;            // interval reset
unsigned long resetPir = 0;             // interval reset


int FadeUp = 0;                         // checken of we een faduup hebben gedaan, doen we maar 1 keer
int Pir = 0;                            // wat is de status van de Pir? 0 is inactief, 1 is actief



void setup() {
  // put your setup code here, to run once:
pinMode(PIRpin, INPUT);                 // PIR input sensor
pinMode(LDRpin, INPUT);                 // LDR input sensor
pinMode(2, INPUT_PULLUP); //***tjdelijk ush button****
pinMode(3, INPUT_PULLUP); //***tjdelijk ush button****
pinMode(RPin, INPUT_PULLUP);            // rechter positie schakelaar
pinMode(LPin, INPUT_PULLUP);            // linker positie schakelaar

FastLED.addLeds<CHIPSET,LED_PIN_ZEVEN>(leds1,NUM_LEDS_ZEVEN);    // fastled laden voor strip zeven
FastLED.addLeds<CHIPSET,LED_PIN_ACHT>(leds2,NUM_LEDS_ACHT);     // fastled laden voor strip acht

Serial.begin(9600);                      // kan uit
}



int buttonState = LOW;

void loop() {

  buttonState = digitalRead(2);
   // check if the pushbutton is pressed. If it is, the buttonState is LOW:
  if (buttonState == LOW) {
        dimStatus=0;
  } 
  if (buttonState == HIGH) {
        dimStatus=1;
  } 


  buttonState = digitalRead(3);
   // check if the pushbutton is pressed. If it is, the buttonState is LOW:
  if (buttonState == LOW) {
        Pir = 0; FadeUp=0;
  } 
  if (buttonState == HIGH) {
        Pir = 1;
          }
 /*  LDR SENSOR
  *  Via millis een interval intellen en wederkerend waardes invullen op metingA en metingB. Het gemiddelde hiervan wordt de trigger
  *  voor de verlichting. Deze doet continue meten (met interval) zodat het licht aan of uit mag). Deinterval staat nu op 5000ms,
  *  dus 5 seconden. Maar misschien moet dat 5 minuten o.i.d. worden zodat een donkere wolk of heldere koplampen geen trigger zijn.
  */
unsigned long currentTime = millis();                                     
if (currentTime - resetTime >= LDRinterval && meting == 1) {                           // 5 intervalseconde meting
      metingA=100;meting=2;                                                            // HIER KOMT INPUT WAARDE VAN LDR
      resetTime = currentTime;                                                         // reset timer
      }
if (currentTime - resetTime >= LDRinterval && meting == 2) {                           // 5 intervalseconde meting
      metingB=222;meting=1;                                                            // HIER KOMT INPUT WAARDE VAN LDR
      resetTime = currentTime;                                                         // reset timer
          }

gemiddeld = (metingA+metingB)/2;                                            // gemiddelde uitrekenen en naar int verplaatsen 

/*
 * We hebben nu een gemiddelde waarde over x tijd. Daardoor mag het licht gedimd aan.
 *

**************
*DIT DEEL ACTIVEREN!
**************
 *
if(gemiddeld >= LDRtrigger){   dimStatus = 1;}else{dimStatus=0;}


/*  PIR SENSOR DIT DEEL ACTIVEREN!
 *  Wanneer de PIR HIGH gaat dan de status naar HIGH. Ook wanneer de PIR weer LOW is kan de status nog een poos HIGH blijven,
 *  soort van grace-time. Wanneer er na ntijd geen HIGH status van de PIR is mag de STATUS naar LOW. Maar dit doen we ALLEEN
 *  wanneer de LDR heeft toegestaan dat het donker genoeg is! Dus dimStatus moet 1 zijn!
 
if(dimStatus > 0){                                    // Mag er gemeten worden, LDR regelt dit
   PIRval = digitalRead(PIRpin);                      // waarde van sensor lezen: HIGH is actief!
  if (PIRval == HIGH) {                               // sensor is HIGH, dus beweging!
      if (PIRstatus == LOW) {                         // er was beweging dus de status naar HIGH zetten!
      Serial.println("ER IS BEWEGING!!"); 
      PIRstatus = HIGH; Pir=1;                        // update pir status naar HIGH
    }
  } 
  else {
      if (PIRstatus == HIGH){                         // status is HIGH maar PIRVal is LOW, dus geen beweging meer!
        Serial.println("Geen beweging meer");Serial.println("Extra tijd actief");
        //millis
        if (currentTime - resetPir >= PIRinterval && PIRstatus == HIGH) {        // wachten tot grace tijd voorbij is
      PIRstatus = LOW; Pir=0;  
      //FadeUp=0;                                         // De status is Low, de PIRval is ook LOW, alles 'uit'
      resetPir = currentTime;}
      }
  }
}
/*    
 *     De aansturing van de langere ledstrips gebeurt hier. De diverse statussen van sensor en modus bepalen wat er gebeurt.
 */

// DimStatus is 0 dus er mag nog niets gedaan worden
if(dimStatus == 0) { AllesUit();}

// nummerStatus is 0 dus ook geen nummer zeven verlichten
if(nummerStatus == 0) { NummerUit();}


// licht mag gedimt aan -> status is dan 1
if(dimStatus == 1 && FadeUp == 0&& Pir == 0){  DimStart();}


// er is beweging, dus fade up
if(dimStatus == 1 && FadeUp == 0 && Pir ==1){
  StartFadeUp();
}


// na de fadeup aanblijven op max vermogen
if(dimStatus == 1 && FadeUp == 1 && Pir ==1){
  MaxLed();
}


/*
 * Code voor het huisnummer 7. Hier diverse effecten specificeren maar kunnen ook het huisnummer eerder aan
 * laten gaan dan de strip... als we daarvoor een andere waarde gebruiken dan dimStatus. Gebruiken we dezelfde
 * dan gaat het nummer gelijktijdig aan met de rest van de strip.
 */
nummerGemiddeld = (metingA+metingB)/1.25;                              // gemiddelde uitrekenen voor de zeven, gaat eerder aan! 

//if(nummerGemiddeld >= LDRtrigger){   nummerStatus = 1;}else{nummerStatus=0;} // ok, hij mag aan



/* De 3-way switch uitlezen. Als links en rechts uit zijn dan moet midden actief worden.
 */
if (!digitalRead(RPin)) //test rechter positie
  {    
//een effect
  }
  else if (!digitalRead(LPin)) //test linker positie
  {    
    //een effect  
    }
  else  {    //een effect
  } 

//if(nummerStatus == 0) { nummerUit();}

if(effect ==1 &&nummerStatus ==1)
  {meteorRain(0xff,0xff,0xff,10, 64, true, 30);}
  else if 
  (effect ==2 &&nummerStatus ==1)
  {RunningLights(0xff,0xff,0xff, 50);}
  else 
  {Fire(20,70,65);} //cooling / sparking en delay




}
/*


 
}//einde loop




/*
 * Onderstaande loops worden aangeroepen bij de diverse lichtstadia van de lange strip
 * 
 */

void AllesUit(){
       fill_solid( leds2, NUM_LEDS_ACHT, CRGB(0,0,0));FastLED.show();
       } // Einde allesuit

void DimStart(){
       for(int i = 0; i < NUM_LEDS_ACHT; i++ ) 
       {leds2[i].setRGB(200,10, 50);} // basiskleur
       FastLED.setBrightness(dimMin);  // dimwaarde
       FastLED.show();
       } // einde dimstart

void StartFadeUp(){
       for( int colorStep=0; colorStep<256; colorStep++ ) {
       int r = colorStep;  // Redness starts at zero and goes up to full
       int b = colorStep;  // Blue starts at full and goes down to zero
       int g = colorStep;  // No green needed to go from blue to red
       for(int x = 0; x < NUM_LEDS_ACHT; x++){leds2[x] = CRGB(r,g,b);}
       for(int z = dimMin; z < dimMax; z++){FastLED.setBrightness(z);}
       FastLED.show();
       FadeUp=1; // fadeup is gedaan dus niet herhalen
       }
       } // einde StartFadeUp

void MaxLed(){
       for(int i = 0; i < NUM_LEDS_ACHT; i++ ) 
       {leds2[i].setRGB(250,250,250);}
       FastLED.setBrightness(250);   
       FastLED.show();
       } // einde maxled

void NummerUit(){
       fill_solid( leds1, NUM_LEDS_ZEVEN, CRGB(0,0,0));FastLED.show();
       } // Einde allesuit
       

/*
 * Extra lib voor LED aansturing: NIET VERWIJDEREN!
 */
 void showStrip() {
 #ifdef ADAFRUIT_NEOPIXEL_H
   // NeoPixel
   strip.show();
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   FastLED.setBrightness(250);
   FastLED.show();
 #endif
}

void setPixel(int Pixel, byte red, byte green, byte blue) {
 #ifdef ADAFRUIT_NEOPIXEL_H
   // NeoPixel
   strip.setPixelColor(Pixel, strip.Color(red, green, blue));
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   leds1[Pixel].r = red;
   leds1[Pixel].g = green;
   leds1[Pixel].b = blue;
 #endif
}

void setAll(byte red, byte green, byte blue) {
  for(int i = 0; i < NUM_LEDS_ZEVEN; i++ ) {
    setPixel(i, red, green, blue);
  }
  showStrip();
}


/*
 * Onderstaande loops zijn voor het lichteffect in de 'zeven'
 * 
 */

/*
 * effect 1
 */
 void meteorRain(byte red, byte green, byte blue, byte meteorSize, byte meteorTrailDecay, boolean meteorRandomDecay, int SpeedDelay) {  
  setAll(0,0,0);
 
  for(int i = 0; i < NUM_LEDS_ZEVEN+NUM_LEDS_ZEVEN; i++) {
   
   
    // fade brightness all LEDs one step
    for(int j=0; j<NUM_LEDS_ZEVEN; j++) {
      if( (!meteorRandomDecay) || (random(10)>5) ) {
        fadeToBlack(j, meteorTrailDecay );        
      }
    }
   
    // draw meteor
    for(int j = 0; j < meteorSize; j++) {
      if( ( i-j <NUM_LEDS_ZEVEN) && (i-j>=0) ) {
        setPixel(i-j, red, green, blue);
      }
    }
   
    showStrip();
    delay(SpeedDelay);
  }
}

void fadeToBlack(int ledNo, byte fadeValue) {
 #ifdef ADAFRUIT_NEOPIXEL_H
    // NeoPixel
    uint32_t oldColor;
    uint8_t r, g, b;
    int value;
   
    oldColor = strip.getPixelColor(ledNo);
    r = (oldColor & 0x00ff0000UL) >> 16;
    g = (oldColor & 0x0000ff00UL) >> 8;
    b = (oldColor & 0x000000ffUL);

    r=(r<=10)? 0 : (int) r-(r*fadeValue/256);
    g=(g<=10)? 0 : (int) g-(g*fadeValue/256);
    b=(b<=10)? 0 : (int) b-(b*fadeValue/256);
   
    strip.setPixelColor(ledNo, r,g,b);
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   leds1[ledNo].fadeToBlackBy( fadeValue );
 #endif  
}








/*
 * effect 2
 */
 void RunningLights(byte red, byte green, byte blue, int WaveDelay)
 {}
/*void RunningLights(byte red, byte green, byte blue, int WaveDelay) {
  int Position=0;
 
  for(int j=0; j<NUM_LEDS_ZEVEN*2; j++)
  {
      Position++; // = 0; //Position + Rate;
      for(int i=0; i<NUM_LEDS_ZEVEN; i++) {
        // sine wave, 3 offset waves make a rainbow!
        //float level = sin(i+Position) * 127 + 128;
        //setPixel(i,level,0,0);
        //float level = sin(i+Position) * 127 + 128;
        setPixel(i,((sin(i+Position) * 127 + 128)/255)*red,
                   ((sin(i+Position) * 127 + 128)/255)*green,
                   ((sin(i+Position) * 127 + 128)/255)*blue);
      }
     
      showStrip();
      delay(WaveDelay);
  }
}
*/





 /*
  * effect 3 vuurrrrrr
  */
  void Fire(int Cooling, int Sparking, int SpeedDelay) {
  static byte heat[NUM_LEDS_ZEVEN];
  int cooldown;
 
  // Step 1.  Cool down every cell a little
  for( int i = 0; i < NUM_LEDS_ZEVEN; i++) {
    cooldown = random(0, ((Cooling * 10) / NUM_LEDS_ZEVEN) + 2);
   
    if(cooldown>heat[i]) {
      heat[i]=0;
    } else {
      heat[i]=heat[i]-cooldown;
    }
  }
 
  // Step 2.  Heat from each cell drifts 'up' and diffuses a little
  for( int k= NUM_LEDS_ZEVEN - 1; k >= 2; k--) {
    heat[k] = (heat[k - 1] + heat[k - 2] + heat[k - 2]) / 3;
  }
   
  // Step 3.  Randomly ignite new 'sparks' near the bottom
  if( random(255) < Sparking ) {
    int y = random(7);
    heat[y] = heat[y] + random(160,255);
    //heat[y] = random(160,255);
  }

  // Step 4.  Convert heat to LED colors
  for( int j = 0; j < NUM_LEDS_ZEVEN; j++) {
    setPixelHeatColor(j, heat[j] );
  }

  showStrip();
  delay(SpeedDelay);
}

void setPixelHeatColor (int Pixel, byte temperature) {
  // Scale 'heat' down from 0-255 to 0-191
  byte t192 = round((temperature/255.0)*191);
 
  // calculate ramp up from
  byte heatramp = t192 & 0x3F; // 0..63
  heatramp <<= 2; // scale up to 0..252
 
  // figure out which third of the spectrum we're in:
  if( t192 > 0x80) {                     // hottest
    setPixel(Pixel, 255, 255, heatramp);
  } else if( t192 > 0x40 ) {             // middle
    setPixel(Pixel, 255, heatramp, 0);
  } else {                               // coolest
    setPixel(Pixel, heatramp, 0, 0);
  }
}

Most is in Dutch... so comments will likely be useless. The effects have English comments since I copied them.

You don't know my way of using a mixture of different languages when reading f ex Dutch....

You have some effect functions containing nested for loops. That can momentarily cause a heavy load on the execution.

Which of the effect functions causes the trouble? Rewriting it using another strategy might help.

haha :+1:

I think that all the effects, I've tested a few more, have similar outcome to my code. It could very well mean that my code is crappy and conflicts with the effect code. I'll test that with another partial sketch that uses a simplified version of my code and check if it still does the flickering and delays. As far as I can tell I'm not using anything complex (not on purpose anyway) code to set values.

That is likely not the answer. One questing is what's going on in those library functions.
I suggest You use serial monitor and Serial.print to time measure strategic library calls and Your own functions. Crank up the baudrate to 115200 in Serial.begin(115200); and in serial monitor.

unsigned long startTime = millis(); function call; Serial.print("Position1: ); Serial.println(millis()-startTime;.

Okay, took me some time to get it figured out but I've found the problem in the flickering.
If the LDR readings are equal to the trigger, it will illuminate the strips to 30% using

FastLED.setBrightness(dimMin) // where dimMin is the value [30]

When the pir is HIGH, it will change color and brightness ramps up to 250 and when the pir is LOW it will drop back to the dimMin.

The flickering only occurred when the strip was in dimmed mode and with a half second or so interval. Which would indicate something is interrupting the LED status.

The problem was this piece of code I copied:

void showStrip() {
 #ifdef ADAFRUIT_NEOPIXEL_H
   // NeoPixel
   strip.show();
 #endif
 #ifndef ADAFRUIT_NEOPIXEL_H
   // FastLED
   **FastLED.setBrightness(250);**
   FastLED.show();
 #endif
}

I thought that that piece of code was specific for the effects, they where running at 250 brightness, so when the Strip LEDS1 are dimmed, code with brightness(250) was send to LEDS2. And every time an effect had a higher brightness - at any given time - than my other dimmed strip my other strip would glitch.

If I remove the 'setbrightness' from that piece of code it works without flickering but the effect strips will only be as bright as dimMin.

I probably could have explained that better...

I think that

FastLED.setBrightness(n);

is global and applied to all strips connected, even if they are specified as separate strips. Not sure I can specify the brightness per strip.

Small update...

Seems like the effects (even the 'simple' ones) are slowing the whole thing down, to the point that I though I had a faulty PIR module. It was lagging and response was irratic. If I turn off the effects it all works fine. I guess the two nano setup is what I'll end up with after all. Bummer.

Not a really proper answer.

If it is slow, it is because the code is wrong.

A "library" is someone else's approach to doing something the way they chose to do something. Whether it does what you want to do is another matter.

However it appears your code still contains "delay()" calls. That is essentially guaranteed to cause problems so I have no sympathy. :roll_eyes:

A "library" is someone else's approach to doing something the way they chose to do something . Whether it does what you want to do is another matter.

Indeed.

However it appears your code still contains "delay()" calls. That is essentially guaranteed to cause problems so I have no sympathy.

Also correct, however that's not my code. I will try to get that sorted too.

Thanks.

I got the code sorted out (mine and the copied effects) and it's all running smooth now. Project is finally coming to an end!

Thanks for your help.