text:
How can I implement double buffering with an Arduino UNO?
I am creating a tiny game on my Arduino UNO with an Adafruit ST7735 1.8" TFT / SD breakout. I am performing screen operations using the built-in TFT-library.
The problem is screen flickering. Even though I take care to prepare data and minimize the time between clearing the screen and writing the new stuff to it, the screen "refresh()" is significant. I heard someone mention something called double buffering, so I read a bit up on it, but I am frankly clueless on how to implement it on an Arduino UNO.
Is it possible to implement double buffering on an Arduino UNO to prevent screen flickering, and if so, how?
Libraries used:
#include <TFT.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>

The screen is "cleared" like this:
screen.background(0,0,0);  // Clear it
screen.text(buf, 10, 25);  // Write new stuff

If you're already preparing the next screen's-worth of data before you clear the screen, then double buffering won't help. In that case, the time taken to re-write the screen data is what causes the flicker, and the only way to improve it is to write the screen faster. If the software is to blame, it will be in screen.text(). If the software is already driving the hardware as fast as the hardware will go, then that's the best you can do.
Double-buffering would let you prepare the next screen while the currently-prepared one is loading (and will require interrupt-driven I/O to do it). The result would be more screen refreshes per unit time, but it doesn't sound like that is your problem.
One easy experiment to try is to not clear the screen before you re-write it, if that is possible to do. Then your next screen will overlay the current screen with (we hope...) no blanking period. That might prevent the blinking.

How can I implement double buffering with an Arduino UNO?

Full screen double buffering (aka off-screen bitmap) for an ST7735 (128 x 160 x 16 bit color) would require 40 Kbyte. With only 2K byte SRAM on the Arduino Uno double buffering is not possible.
Some of the flickering is due to the Arduino core unoptimized SPI protocol and the graphics library. They could be optimized to reduce some of the flickering.
Please see the Cosa ST7735 driver and SPI support for examples of high speed inter-leaving SPI transfer and graphics optimizations.
Smaller mono-chrome screens (such as ST7565) can be supported with double buffering. An example is the Cosa OffScreen Canvas that can be used to create a bitmap that is transfered to the screen in a single operation.
Cheers!

Arduino Due has 40k RAM to spare, but I don't see how that solves the issue of the screen flickering as you will still need to transfer the data to the display controller, meaning you will still have to watch the screen slowly update and for complex contents the screen will spend much more time while updating is in progress than it will be displaying the desired final contents.

@VioletGiraffe Most Arduino graphics libraries use pixel level update and draw directly to the display memory. They do not use a off-screen bitmap and then transfer in a single operation. The transfer can be synchronized with the display to avoid flickers. See chap. 9.11 in the ST7735 datasheet, https://www.displayfuture.com/Display/datasheet/controller/ST7735.pdf

Interesting, thank you very much for responding, I want to investigate the possibilities of of some sort of partial buffering / transfer batching.
It's a shame that none of the popular controllers (ST7735, ILI9341, SSD1963 etc.)  support indexed 8-bit color palettes. 256 colors is more than enough for most embedded applications, and having 8-bit pixel values would mean that each of the controllers I mentioned can already store at least two full sets of image data.

To add to previous answers:
Double-buffering is an approach where you write to the actual device - but in an off-screen area. Then you switch to the new area in a single instruction, indistinguishable to the naked eye, rather than clear the visible area and write while it's still being displayed.
This requires that the device has extra memory to support the two areas: on-screen and off-screen. Absent that extra memory, then the best that you can do is pre-calculate as much as possible, and write to the screen as fast as possible.


text:
Fancy Arduino IDE
Do you know an IDE that is Arduino compatible, with:

Black background; white hurts my eyes.
Some auto completion features maybe?
And also one that lets you minimise brackets. Xcode like.
A better console...
Something to clear the serial console.
A breadboard view.

Something fancy!

You can use any IDE you want; anything fancy as you describe should have a way to define your own build system, so you can just use the makefile or scons or ino or your own shell script. As for the serial console, you will probably just have to deal with it not being built in to a single, monolithic IDE.

Have a look at Fritzing. I don't know how much you can customize there, but it has a whole suite where you can design hardware, write code, and even order PCB if you want to.

I believe Eclipse can do everything you mentioned except for showing hardware layouts. The appearance of editor windows is customizable. If, by minimizing brackets, you mean collapsing them ("just indicate that something is here; I don't want to see the content"), Eclipse does that too. You can clear the console, but I don't know what "better" features you mean so I can't answer that part. It can take some setting up to get it working for you but it's far and away more powerful and feature-filled than the basic Arduino IDE. It is probably the most used IDE by people who look to upgrade from the basic one.
Update:
While it doesn't directly show hardware layouts, it does know about opening files with their default applications. If you put a Fritzing file in your project folder, when you click on it, Eclipse will launch Fritzing. If you put an image file such as a screenshot of the board layout, it will even open that within the IDE.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Using C# Program to Interpret Keystrokes
I am in the process of developing an Arduino application that can read keystrokes from a PS/2 keyboard. I was wondering if it would be possible to upload a C# program onto the Arduino to interpret the keystrokes from the keyboard and write an Arduino program to perform operations based on the keystrokes.

No, the Arduino doesn't run C#

Is there a specific feature of C# you need help working around in C++?

C# is just my go to language. I haven't dabbled in C++ at all, but I guess this would be a good time to pick it up.

The answer is actually, surprisingly, yes! C# requires .NET CLR for execution, I had assumed that .NET exists only in microsoft desktop land, but it has in fact been ported to microcontrollers and released open source as .NET micro, it can even run baremetal with no OS.
However this is not possible on an 8 bit regular arduino, it requires one of the larger 32 bit models. There is a prebuilt clone that has the .NET micro CLR framework ported to it on an STM32F4 cpu called the netduino
Unfortunately the footprint for .Net Micro is too large to run on a regular 8bit arduino and probably hasn't been built for 8bit systems. It is possible with the arduino Due (in theory) and on other micrcontroller platforms that support .NET micro to run C# code outside of the windows platform.

This is interesting... will this work on something like Arduino Due or another 32 bit Arduino board?

@AnnonomusPenguin it requires reasonable resources (256K Flash + 64K ram), but otherwise the devil will be in configuring/building it for the Arduino Due platform, I'm not sure how easy Microsoft makes it on you, I couldn't find anyone working on it after a cursory search for .net micro on arduino due

I hope this answer doesn't get voted down just because it addresses the generic need (do something upon input from a PS/2 keyboard), rather than the (too) specific question that was asked (use c# on Arduino), but here it comes ...
If you use a PS/2 to USB adapter for the keyboard, you can select a much easier solution, based, for example, on raspberry PI (or anything that runs linux and has a USB master port) and use any simple scripting language - even shell. The overall cost would not be much higher and the ease of implementation would be definitely more likely to succeed. And in a short time.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

authors: Иван Кондраль


text:
How do I use 3 Hc-sr04 ultrasonic sensors to control 3 vibration dc motor?
This code we are using only one motor and one hc-sr04 ultrasonic sensor, the code is shown below:
#define trigPin 7
#define echoPin 6
#define motorPin 5

void setup()
{
  Serial.begin(9600);// to use the serial monitor
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(motorPin, OUTPUT);
}

void loop()
{
  int duration,distance;
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2)/29.1;
  Serial.print(distance);//to print the distance on the serial monitor
  Serial.println("cm");

  // to make the motor vibrate depending on the distance
  // if the ultrasonic sensor is too far from the obstacle it will vibrate slowly
  // if the ultrasonic sensor is very close to the obstacle it will vibrate very fast

    if(distance <= 60 && distance >= 45)
    {
      // to make the motor vibrate
    digitalWrite(motorPin, HIGH); // making the motor on

    delay(200);
    digitalWrite(motorPin, LOW);// making the motor off
    delay(200);
    }

    else if(distance < 45 && distance >= 30)
    {
    digitalWrite(motorPin, HIGH);
    delay(100);
    digitalWrite(motorPin, LOW);
    delay(100);
   }
    else if(distance < 30){

    digitalWrite(motorPin, HIGH);
    delay(50);
    digitalWrite(motorPin, LOW);
    delay(50);
  }
  else
  {
    digitalWrite(motorPin, LOW);
  }
}

We want you to tell us your comment about the code.
And we want to add two more motors and two ultrasonic sensors, one of them in the left and the other in the right.
We want you to help us in the code, because we don't know how we can change it for two other motors.

Welcome to the Arduino StackExchange! We hope your stay will be fruitful. To help us view your code you should put it into "code blocks". I have edited your post and done it for you this time. Please read Editing Help to assist you in doing this. What is your question exactly? We want you to help us in the code isn't really a question.

There's a few things you need to consider when making multiple things happen at the same time.
Firstly is timing. You can't make two things happen concurrently with different timings if you have delay() in there, since nothing else can happen while delay() is executing.  So you have to get rid of all delay() calls and replace them with examining the difference between successive calls to millis().
For instance, imagine you're in the kitchen and you want to boil and egg and make a cup of tea at the same time.  You fill the kettle and turn it on.  You put a pan of water on the stove with an egg in it to boil.
Now you could sit and stare at the egg until it's boiled enough for you to eat, but what happens to the kettle while you're doing that?  It's boiled, turned itself off, and started to go cold.
So instead you put the egg in the pan and look at the clock.  Then you think "in 5 minutes I will take the egg out of the boiling water".  You might set an alarm for 5 minutes time if you have one, or you may keep glancing at the clock periodically to see if the 5 minutes have past yet.  Meanwhile the kettle has boiled and you've made your cup of tea.
Then the 5 minutes have passed.  You know that because you remembered what time you put the egg on to boil and you know what the time is now, so you can subtract one from the other to find that 5 minutes have passed.
Now let's make it a little more complex.  Imagine you want two eggs - one soft boiled and one hard boiled.  The hard boiled one may want 8 minutes, the soft boiled one 5 minutes.
So you put one egg on to boil and remember the time.  Roughly three minutes later you put the other egg in and also remember that time.
Once enough time has passed that the first egg has been in 8 minutes you take it out.
Once enough time has passed that the second egg has been in 5 minutes you take it out.
You have had to remember two start times which you then compare separately to decide what to do with each egg when.
To translate that to your program - you have to remember a start time for each action for your motors, along with the state of the motors - and when the right time has elapsed you change the state of the motor (motor on -> motor off - egg in pan -> egg on plate) and remember the time at which you changed the state so you can know when to change the state again.
That's exactly what the BlinkWithoutDelay example does to make an LED change state (on -> off -> on) at certain times by remembering when it last changed state so you know when to change the state next.

Thanks a lot for replying .. the idea of our project is making a hat for blind person, inside the hat we have 3 hc.sr04 ultrasonic sensor and 3 motor  located in : front  , right and left , the motor should vibrate slowly when the obstacle is far and vise versa ... can you help us in code itself ? even if we can communicate to you by your email..

I have rolled the two basic functions (ping and blink) into simple libraries that should get you going.  It should be a very simple matter to put them together. I haven't tested the Pinger library yet since I can't find my ultrasound board off hand, but it's very simple and should work. https://github.com/MajenkoLibraries/Blink https://github.com/MajenkoLibraries/Pinger

Thanks a lot .. plz give me ur email as soon as possible .. I want to ask u about the code :(

If you have a problem with one of the libraries please raise it as an issue on Github. If you have a problem with understanding certain aspects of Arduino programming please ask a fresh question on this site detailing what you have tried and what you are having problems with.  I don't hand my email address out willy-nilly.


text:
digitalWrite queued signals?
I have this simple code who send a signal to a android phone when I press a button:
const int botonPinD = 8;
const int relayPin =  12;
int retardo = 100;
int finBoton=1000;

void setup() {
  pinMode(relayPin, OUTPUT);

  pinMode(botonPinA, INPUT);
  pinMode(botonPinB, INPUT);
  pinMode(botonPinC, INPUT);
  pinMode(botonPinD, INPUT);
}
void loop(){
    botonD = digitalRead(botonPinD);
    if (botonD == HIGH){
   // for simplicity remove botonA, botonB and botonC code, but it's the same with a few digitalWrite
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        digitalWrite(relayPin, HIGH);
        delay(retardo);
        digitalWrite(relayPin, LOW);
        delay(retardo);
        delay(finBoton);
      }
      else{
        digitalWrite(relayPin, LOW);
      }
}

But if I press the button fast (maybe a half a second between clicks) I only receive once the signal.
I'm not very sure about what's happened here (I'm an Arduino newbie). The first signal, has it locked the channel? Can signals be queued? Can I control the way that they are queued?

Hi, and welcome to the Arduno Stack Exchange.  Unfortunately you appear to have only posted a small portion of your code (known as a "snippet") which is lacking the most important portion - the portion that is doing the communication (and thus the "queuing") with the Android device.  Without that information we will not be able to help you.  Please help us to help you by posting your entire program.

The code below is closer to what you seem to be asking about:
// For Mega2560

const int BUTTONS = 4;
const int FIRST_SWITCH = 18;
const int FIRST_RELAY =  41;
const int CLICKS = 5;
const unsigned long DEBOUNCE_TIME = 20;  // ms

int retardo  = 300;
int finBoton = 1000;

volatile byte counts [BUTTONS];
unsigned long lastPress [BUTTONS];

void doInterrupts (const int which)
 {
 // debounce
 if (millis () - lastPress [which] < DEBOUNCE_TIME)
   return;

 lastPress [which] = millis ();
 counts [which]++;
 }  // end of doInterrupts

void pin18Pressed ()
  {
  doInterrupts (0);
  }  // end of pin18Pressed

void pin19Pressed ()
  {
  doInterrupts (1);
  }  // end of pin19Pressed

void pin20Pressed ()
  {
  doInterrupts (2);
  }  // end of pin20Pressed

void pin21Pressed ()
  {
  doInterrupts (3);
  }  // end of pin21Pressed

void setup()
  {
  // configure inputs / outputs
  for (int i = 0; i < BUTTONS; i++)
    {
    pinMode (FIRST_SWITCH + i, INPUT_PULLUP);
    pinMode (FIRST_RELAY + i, OUTPUT);
    }

  attachInterrupt (5, pin18Pressed, FALLING);
  attachInterrupt (4, pin19Pressed, FALLING);
  attachInterrupt (3, pin20Pressed, FALLING);
  attachInterrupt (2, pin21Pressed, FALLING);

  } // end of setup

// turn relay on for a particular switch
void handleSwitchPress (const int which)
  {
  for (int i = 0; i < CLICKS; i++)
  {
    digitalWrite(FIRST_RELAY + which, HIGH);
    delay(retardo);
    digitalWrite(FIRST_RELAY + which, LOW);
    delay(retardo);
  }
  delay(finBoton);
  } // end of handleSwitchPress

// main loop
void loop()
  {
 for (int i = 0; i < BUTTONS; i++)
   if (counts [i] > 0)
     {
     handleSwitchPress (i);
     counts [i]--;
     }
  }  // end of loop

I'll explain parts of it from above:
Interrupts
To queue up switch presses we can use an interrupt. The Mega has quite a few external interrupts (See: attachInterrupt()) so I'll use those. You can read about interrupts on my page about interrupts.
This code attaches four interrupts handlers:
  attachInterrupt (5, pin18Pressed, FALLING);
  attachInterrupt (4, pin19Pressed, FALLING);
  attachInterrupt (3, pin20Pressed, FALLING);
  attachInterrupt (2, pin21Pressed, FALLING);

Because of the way the hardware works we have to use pins 18, 19, 20 and 21 (there are a couple more but these are in sequence).
I set the switches to be INPUT_PULLUP so that they are normally HIGH when not pressed, and go LOW when you press them. Hence the interrupts are looking for a FALLING edge.

Handle one interrupt
An interrupt handler is like this:
void pin18Pressed ()
  {
  doInterrupts (0);
  }  // end of pin18Pressed

Since they all do much the same thing I put all of the switch management into one function and used an array of switches, like this:
volatile byte counts [BUTTONS];
unsigned long lastPress [BUTTONS];

void doInterrupts (const int which)
 {
 // debounce
 if (millis () - lastPress [which] < DEBOUNCE_TIME)
   return;

 lastPress [which] = millis ();
 counts [which]++;
 }  // end of doInterrupts

In order to "queue" presses the interrupt handler adds one to a counter, for that array item. (So, pin 18 is position 0, pin 19 is position 1 and so on).

Debouncing
Debouncing of the switches is done by ignoring multiple presses in quick succession:
 // debounce
 if (millis () - lastPress [which] < DEBOUNCE_TIME)
   return;

 lastPress [which] = millis ();

Handling a queued press
Now in the main loop we just check if the counter has gone up, for each switch:
 for (int i = 0; i < BUTTONS; i++)
   if (counts [i] > 0)
     {
     handleSwitchPress (i);
     counts [i]--;
     }

If so, we call handleSwitchPress which toggles the relay for the desired number of times.

Code for Uno
If you are using a Uno instead of a Mega2560 you don't have four external interrupts. The alternative version below uses pin change interrupts instead of external interrupts.
Pin change interrupts work on all pins of the Uno, however they are in batches of three: Pins A0 to A5, pins D0 to D7 and pins D8 to D13. In the code below I use pins 2, 3, 4 and 5 which are in the batch D0 to D7.
With a pin-change interrupt you only get notification of a change to the pin, so the code has to detect whether the pin changed from high to low or low to high.
// For Atmega328 (eg. Uno)

const int BUTTONS = 4;
const int FIRST_BUTTON = 2;
const int FIRST_RELAY =  8;
const int CLICKS = 5;
const unsigned long DEBOUNCE_TIME = 20;  // ms

int retardo  = 300;
int finBoton = 1000;

volatile bool oldState [BUTTONS];
volatile byte counts [BUTTONS];
unsigned long lastPress;

// handle pin change interrupt for D0 to D7 here
ISR (PCINT2_vect)
 {

 // debounce
 if (millis () - lastPress < DEBOUNCE_TIME)
   return;

 lastPress = millis ();

 // check each switch
 for (int i = 0; i < BUTTONS; i++)
   {
   byte state = digitalRead (FIRST_BUTTON + i);
   if (state != oldState [i])
     {
     oldState [i] = state;  // detect state changes
     if (state == LOW)
       counts [i]++;
     }   // end of state change
   }  // end of for each button

 }  // end of PCINT2_vect

void setup()
  {

  // configure inputs / outputs
  for (int i = 0; i < BUTTONS; i++)
    {
    pinMode (FIRST_BUTTON + i, INPUT_PULLUP);
    oldState [i] = HIGH;
    pinMode (FIRST_RELAY + i, OUTPUT);
    }

  // pin change interrupt (example for D9)
  PCMSK2 |= bit (PCINT18) | bit (PCINT19) | bit (PCINT20) | bit (PCINT21);  // want pins 2, 3, 4, 5
  PCIFR  |= bit (PCIF2);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE2);   // enable pin change interrupts for D0 to D7
  } // end of setup

// turn relay on for a particular switch
void handleSwitchPress (const int which)
  {
  for (int i = 0; i < CLICKS; i++)
  {
    digitalWrite(FIRST_RELAY + which, HIGH);
    delay(retardo);
    digitalWrite(FIRST_RELAY + which, LOW);
    delay(retardo);
  }
  delay(finBoton);
  } // end of handleSwitchPress

// main loop
void loop()
  {
 for (int i = 0; i < BUTTONS; i++)
   if (counts [i] > 0)
     {
     handleSwitchPress (i);
     counts [i]--;
     }
  }  // end of loop

The main problem I guess you are suffering from is the good old delay() blockage.
delay() is a terrible function and should be avoided at all costs.  Nothing at all can happen while you are running delay() - that means you can't be reading the state of your button - until all your delay() calls have finished.
If you want to queue the pressed of the button you will need to do three things:

You will need to recognise when the button changes from LOW to HIGH, not just "when it is HIGH" as you do now.
You will have to queue that button press somewhere. The simplest way is to maintain a count of how many times the button has been pressed.
You will have to process any pending button presses ("while the count > 0") by triggering your output with the right timing without using delay(), which means using millis() and maintaining state information.


text:
Neopixel led strip stops responding after change in brightness
I have an arduino UNO hooked up to a neopixel LED strip with 148 lights.  Most of the time it works fine, but when I upload a program that changes the brightness frequently, particularly when I increase brightness, only the first 8 LEDs continue responding.  The rest get stuck.
Here's an example of the kind of code that sets this issue off.  To fix it, I usually have to restart the lights and the arduino and sometimes upload a blank program to the arduino.
I'm pretty new to arduino programming so and help would be really appreciated.  Thank you.
#include "FastLED.h"

FASTLED_USING_NAMESPACE

// FAST LED definitions
#define DATA_PIN    3
#define LED_TYPE    WS2812B
#define COLOR_ORDER GRB
#define NUM_LEDS    148

CRGB leds[NUM_LEDS];
#define DATA_PIN 3 // Output Pin to Data Line on Strip

int fadeAmount = 5;
int brightness = 0;

void setup()
{
   FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
}

void loop()
{
   for(int i = 0; i < NUM_LEDS; i++ )
   {
   leds[i].setRGB(0,255,0);
   leds[i].fadeLightBy(brightness);
  }
  FastLED.show();
  brightness = brightness + fadeAmount;
  // reverse the direction of the fading at the ends of the fade:
  if(brightness == 0 || brightness == 255)
  {
    fadeAmount = -fadeAmount ;
  }
  delay(20);
}

After doing more research and getting feedback on the Adafruit forum here, it appears that the problem was a cracked solder joint.  I managed to get access to the strip and wiggled it a little and the problem has gone away.  The recommendation is to reflow the joint by adding a little solder over the data connection between where the LEDs stop being responsive.

If it's only the solder, you can indeed resolder/reflow it.
At one of my strips, the solder-joint ripped out some of the strip, then it will be best to cut out the pixel completely. You can easily re-attach them (without the single pixel).

You might indeed also check the heat generation, if it becomes hot enough to reflow the solder, it won't last long.

I replaced the pixel and the set up appears to be working without issue now.

It is almost certainly a power issue. The Adafruit page about one of those types of Neopixels says:

Don't forget, with 256 LEDs, you could use over 15A of current if you turn on all the LEDs on to white (which we really do not recommend because we don't think the flex PCB can handle that much current). Try to keep the current draw at under 5A ...

Increasing the brightness increases the current drawn. Do you have a heavy-duty power supply? Are the connecting leads sufficient for (say) 8 amps of current?

New information based on comments made
Based on comments by Lorenz I now think it is more likely to be that they are overheating.

I have the strip embedded in a picture frame with epoxy resin over it.

That makes it difficult for the ICs to cool down, and LEDs generate heat. If you search for "neopixels heat" you find quite a few matches. Some suggestions made are to use a heat sink or a fan. If this isn't practical for you, then running at a lower PWM rate (ie. not as bright) and not as saturated colour, could help keep the heat down.
You don't want to "cook" one of the early pixels, because each one has to pass the data on to the next one in sequence, so if you lose an early one, you lose everything after it, particularly if you can't get at it to replace one.

Postscript regarding heat
I have been testing a NeoPixel with a temperature sensor. Displaying full white (255/255/255) it has reached about 44°C. So clearly it warms up. However this is in the open air with just some sticky-tape holding the sensor onto the LED. According to the spec the chip can operate at up to 80°C, so this is within range.
However if the whole thing was sealed in epoxy, then the heat being generated would have much less chance of escaping into the ambient air, and thus would be likely to get a lot hotter.

I'm pretty sure I'm good on the power supply side.  I have a 5V 10A supply hooked up (https://www.adafruit.com/products/658).

What do you mean by are the connecting leads sufficient for (say) 8 amps of current?

I'm using basic jumper wires (https://www.adafruit.com/products/1957) connected through a 2.1mm DC barrel jack and a mini breadboard.

I see. From that page Each wire is 28 AWG (7 strands @ 36 AWG) and from  Wire Gauge and Current Limits Including Skin Depth and Strength 28 AWG wire has a maximum of 1.4 amps for chassis wiring. Thus I suspect your wiring cannot carry the load. Try measuring the voltage on the Neopixel end (ie. at the end of the wire). I am guessing that, when the brightness is up, you won't be getting 5V there.

Nick - I've rewired the neopixel wires to go directly to the 5v power supply without any jumper cables in between.  I'm still getting the problem.  I have the strip embedded in a picture frame with epoxy resin over it.  I cannot actually get to the other end of the strip to measure the voltage there.  Is it possible that the epoxy enclosure is causing the LED to overheat.  Usually the strip works fine for a few minutes (if I haven't plugged it in in a while) and then craps out.  Any thoughts on how I might be able to fix this without tearing up the frame?

With a lot of current going through them overheating sounds like a possibility. Do you have a way of measuring the heat of them (eg. a contact thermometer)? You could try setting the code to operate them at a low power level for a while, to see if it is heat, or time, that is causing this. Also, can't you at least measure the power input voltage to the frame?

The input voltage is 5V.  I've measured it and it's pretty constant.  Time definitely seems to be a factor.  When I run the lights at lower power, they last much longer and when I don't run them for a while and then run them, they last longer too.  After they crap out, only the first 8 respond to the pulsing pattern and the rest just stay lit at the color they were the moment it crapped out.  I'm trying to figure out what I can do to remedy this situation.  The LEDs are completely encased in wood and epoxy so there's very little air circulation around the strip.

My understanding of NeoPixels is that the early ones have to take the incoming data, strip out one RGB sequence, and pass the others on. Thus the earlier ones have more to do than the later ones, and if an early one fails, the later ones will do nothing. This would tend to explain what you are seeing.

Can you think of anything I can do to fix the situation?

If you can measure the temperature you could confirm it is indeed getting hot. And to fix it, if it is all encased in epoxy, all I can suggest doing is running at low brightness so it doesn't heat up too much.

Nick - one more question for you.  When I have this issue, the LEDs continue to be fully lit.  It's just the data that doesn't seem to go past the first 8 LEDs.  The remain 140 LEDs stay lit and bright they just stop responding to the pattern.  Would this suggest something other than a power issue?

I presume the LEDs "remember" the last colour latched into them. With power applied they would continue to show that. If data doesn't go past the first 8, it would seem likely that the 8th one has overheated and stopped passing the data on.

See amended post regarding measuring the temperature of the pixel when operating.


text:
Copy content of array
This may be an easy question, and if so im sorry, but i couldn't find out how to do this. I've programmed in python before and hoped that this would work, but it don't.
int myArray1[] = {0, 2, 4, 5, 7, 9, 11};
int myArray2[] = {0, 2, 3, 5, 7, 8, 10};
int myArray3[] = {0, 3, 5, 6, 7, 10};

int newArray[] = myArray2;

I wanted to only have to change one place in my code, which of the first three arrays i want my new array to take values from. Do anyone have any suggestions on how to do this?

memcpy() is the C function for copying blocks of memory. If nobody has answered before I get back to a computer I shall write something up, providing you clarify whether you want to copy the contents or not, and whether the arrays are equal fixed length, different fixed lengths, or truly dynamic lengths.

I suggest you clarify if you want a copy of the contents, or merely make newArray refer to one of the existing arrays. Your wording which of the first three arrays i want my new array to take values from suggests you merely want to change a reference to one of the existing arrays.

Make newArray be a pointer to whichever array you wish to work with.  For example:
int myArray1[] = {0, 2, 4, 5, 7, 9, 11};
int myArray2[] = {0, 2, 3, 5, 7, 8, 10};
int myArray3[] = {0, 3, 5, 6, 7, 10};

int *newArray = myArray2;

// ... work with selected array, via newArray[] subscripting

Note, you may need to set an array-length variable at the same time as choosing the array.
For example:
int *newArray = myArray2;
int newSize = sizeof(myArray2)/sizeof myArray2[0];

// ... work with selected array

newArray = myArray3;
newSize = sizeof(myArray3)/sizeof myArray3[0];
// ... work with selected array

Alternately, add an array-end marker at the end of each array (eg, a negative number), or more elegantly, make all the arrays the same length.
If you want to make a new copy of the original array, such that modifying the new array won't change the old, use (eg) memcpy().  For example:
int newArray[7];
...
memcpy(newArray, myArray2, sizeof(myArray2));

Note that memcpy()'s size argument is given in bytes.  Also, if you need to declare memcpy() [I don't recall whether it's automatically declared in the Arduino environment], add #include <string.h> up front.

But this doesn't copy the contents, it just creates a duplicate reference...

@CharlieHanson, that complies with an interpretation of the question consistent with Python's implementation, which produces a new reference to a list.   Re Python's copy and deep copy see 8.17. copy — Shallow and deep copy operations

Yet it does not comply with the title "Copy content of array".

@CharlieHanson, I'd instead say the title does not comply with the content of the post.  We can hope OP clarifies.  Anyway, will add memcpy note

I'd instead say the content of the post does not comply with the title. Sic vita est.

memcpy(newArray, myArray2, sizeof(myArray2)); - I always like to take the size of the destination, not the source ... just in case.

@NickGammon, If source is myArray3 that will copy an extra word ... typically harmless, technically undefined.  Of course, one could preface the memcpy with an if to test sizeof(source) <= sizeof(dest)

Or something like: memcpy(newArray, myArray2, min (sizeof(myArray2), sizeof (newArray)));

Would there be much overhead in wrapping this in a simple class? I know there are a host of container classes in the C++ STL but they are all overkill, in this case at least. The ability to iterate and reference only within the bounds of the array would be a handy tool, and adding a copy function (a copy constructor, even?) could make using the array painless. Apart from the time taken to actually write the class, are there any drawbacks from an embedded point of view that would make this more harm than good?

Conceivably some sort of wrapper might run more slowly. I don't see any enormous disadvantages, except learning to use the class might take just as long as learning how to do the memcpy. :)


text:
Can I work with larger numbers than an unsigned long long in Arduino?
I would like to use larger numbers than an unsigned long long in Arduino. Is that possible?

You should look up the BigNumber library see if it is suitable for your needs.

But... why do you need them? Usually when someone needs larger numbers then he has probably chosen the wrong algorithm...

I'll check it out.

The entire point of my project is working with large numbers.

There are many ways to use numbers bigger than an unsigned long on Arduino. The right one depends on the application.
Floats and Doubles
floats and doubles types on Arduino can hold exact integers up  2^53. That is a very large number. They are built into the Arduino compiler.
uint64_t
The uint64_t type can hold exact integers up to 2^64. That is a very large number. This type is built into the Arduino compiler, but note that some Arduino library functions do not have versions for this type so may need to down-convert for printing and serializing and stuff like that.
BigNumber (or bc)
The BigNumber type can represent exact numbers (integer or otherwise) limited only by available memory- but certainly hundreds of digits long on Arduino. These are extremely big numbers. This type is not built into the Arduino, but there is a nice Arduino library version available...
https://github.com/nickgammon/BigNumber
Again, this type is not supprted by the Arduino built-in library functions so  you will need to either down-convert or find BigNumber compatible functions for things like printing and serializing.


text:
How do I power my Arduino Micro directly?
I just need some confirmation, before I break something. So far I have been powering my project from USB, no I would like to power it from a battery. The official spec claims I should use a voltage anywhere from 7-12V, so I got myself a 9V block battery and would connect the positive lead to the VIN pin and the negative lead to the ground pin right next to it, based on this schematic: https://40.media.tumblr.com/cdadca4e95808b376de52a88a5468367/tumblr_mi61oww6cu1s5t695o1_1280.png
Do I need a resistor?

According to this schematic, VIN goes to the on arduino-micro's 5 and 3 volt regulators.  So you should not need a resistor.
The 5 volt regulator needs a bit more than 5 volts at it's input to do a good job.  That is why the specification calls for 7 to 12 volts.


text:
Prevent hardware and library examples from showing in the Sketchbook menu
I have various subdirectories in {SKETCHBOOK}/hardware/ and {SKETCHBOOK}/libraries/ that contain an examples/ subdirectory. These examples are showing up in File | Sketchbook | hardware and File | Sketchbook | libraries. Is there any way I can prevent them from showing up in that menu without moving them under the system-level Arduino directory?

Looking at the code it is scanning all folders and there is no option to change that behavior. Also looking at the code, it looks like it dumps them into a sub-menu, hiding them away a little further, if the folder is named anything except "examples", which could be an alternative option for you.
The final option would be to fork your own version and come up with some exclusion logic, maybe with some kind of ".ignore" kind of logic where you can specify folders to exclude form the menu.

Interesting. I think that the proper fix would be to modify Base.addSketches(JMenu, File) to skip "important" directories, since there shouldn't be user sketches in there regardless. But thank you for pointing this out,


text:
Modbus slave data into word

I have simple code. The library downloaded from github:smarmengol/Modbus-Master-Slave-for-Arduino.
I wanted to store floating point. In the code blow, I type casted to integer value. As I know uint16_t au16data[30]; is integer
#include <avr/wdt.h>
#include"glob.h"

#define ID   1
int8_t state = 0;
Modbus slave(ID, 0, 0);
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[30];

void Take_Reading()
{
  for(row=0;row<9;row++)
  {
  int k=(8*array[row][0]+4*array[row][1]+2*array[row][2]+1*array[row][3]);
    digitalWrite(Enablepin,array[row][0]);
    digitalWrite(SO_enable,array[row][1]);
    digitalWrite(S1_enable,array[row][2]);
    digitalWrite(S2_enable,array[row][3]);
   //delay(100);
    Sensor_Value0=analogRead(A0);
    Sensor_Value1=analogRead(A5);
   Mux1_array[row]=(Sensor_Value0 * ARDUINO_ANALOG_SCALING);
   Mux2_array[row]=(Sensor_Value1 * ARDUINO_ANALOG_SCALING);

   Current_Value1[row]=  (Mux1_array[row]*40)-98;
   Current_Value2[row]=  (Mux2_array[row]*40)-98;

  }
}

void setup()
{
     wdt_enable(WDTO_8S);
   slave.begin( 9600 );
  tempus = millis() + 100;
  pinMode(3,OUTPUT);
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  pinMode(Enablepin, OUTPUT) ;// pin can enable/disable using digital IO 4 of arduino
  pinMode(A0, INPUT) ;
  pinMode(A5, INPUT) ;

//  Serial.begin(9600);
}

void loop()
{
  digitalWrite(3,HIGH);
// wdt_reset();
 Take_Reading();
 state = slave.poll( au16data,30 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );

Modbus_call();

}

void Modbus_call()
{

/*reading of coil where i can succefully read value*/
  au16data[0]=(int)Current_Value1[0];
  au16data[1]=(int)Current_Value1[1];
  au16data[2]=(int)Current_Value1[2];
  au16data[3]=(int)Current_Value1[3];
  au16data[4]=(int)Current_Value1[4];
  au16data[5]=(int)Current_Value1[5];
  au16data[6]=(int)Current_Value1[6];
  au16data[7]=(int)Current_Value1[7];
  au16data[8]=(int)Current_Value1[8];
  au16data[9]=(int)Current_Value2[0];
  au16data[10]=(int)Current_Value2[1];
  au16data[11]=(int)Current_Value2[2];
  au16data[12]=(int)Current_Value2[3];
  au16data[16]=(int)Current_Value2[4];
   au16data[17]=(int)Current_Value2[5];
   au16data[18]=(int)Current_Value2[6];
   au16data[19]=(int)Current_Value2[7];
 uint16_t calcCRC( au16data[15]);
     au16data[13] = slave.getInCnt();
  au16data[14] = slave.getOutCnt();
  au16data[15] = slave.getErrCnt();

 }

Conversion method as below.
CS=30.10
Int_CS=int(CS)
FLOAT_CS=(Int_CS-CS)*100

How to store the Int_CS & FLOAT_CS values in au16data[0]??

I have change code accordingly.

But I get zero. After some time its values don't even show
#include <avr/wdt.h>
#include"glob.h"

#define ID   1
int8_t state = 0;
Modbus slave(ID, 0, 0);
unsigned long tempus;
// data array for modbus network sharing
uint16_t au16data[5];
float auFloatData[30];
void Take_Reading()
{
  for(row=0;row<9;row++)
  {
  int k=(8*array[row][0]+4*array[row][1]+2*array[row][2]+1*array[row][3]);
    digitalWrite(Enablepin,array[row][0]);
    digitalWrite(SO_enable,array[row][1]);
    digitalWrite(S1_enable,array[row][2]);
    digitalWrite(S2_enable,array[row][3]);
   //delay(100);
    Sensor_Value0=analogRead(A0);
    Sensor_Value1=analogRead(A5);
   Mux1_array[row]=(Sensor_Value0 * ARDUINO_ANALOG_SCALING);
   Mux2_array[row]=(Sensor_Value1 * ARDUINO_ANALOG_SCALING);

   Current_Value1[row]=  (Mux1_array[row]*40)-98;
   Current_Value2[row]=  (Mux2_array[row]*40)-98;

  }
}

void setup()
{
     wdt_enable(WDTO_8S);
   slave.begin( 9600 );
  tempus = millis() + 100;
  pinMode(3,OUTPUT);
  pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
  pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
  pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
  pinMode(Enablepin, OUTPUT) ;// pin can enable/disable using digital IO 4 of arduino
  pinMode(A0, INPUT) ;
  pinMode(A5, INPUT) ;

//  Serial.begin(9600);
}

void loop()
{
  digitalWrite(3,HIGH);
// wdt_reset();
 Take_Reading();
 state = slave.poll( au16data,5 );
  if (state > 4) {
    tempus = millis() + 50;
    digitalWrite(13, HIGH);
  }
  if (millis() > tempus) digitalWrite(13, LOW );

Modbus_call();

}

void Modbus_call()
{

/*reading of coil where i can succefully read value*/
  auFloatData[20]=Current_Value1[0];
  auFloatData[21]=Current_Value1[1];
  auFloatData[22]=Current_Value1[3];
  auFloatData[4]=Current_Value1[4];
  auFloatData[5]=Current_Value1[5];
  auFloatData[6]=Current_Value1[6];
  auFloatData[7]=Current_Value1[7];
  auFloatData[8]=Current_Value1[8];
  auFloatData[9]=Current_Value2[0];
  auFloatData[10]=Current_Value2[1];
  auFloatData[11]=Current_Value2[2];
  auFloatData[12]=Current_Value2[3];
  auFloatData[16]=Current_Value2[4];
   auFloatData[17]=Current_Value2[5];
   auFloatData[18]=Current_Value2[6];
   auFloatData[19]=Current_Value2[7];
uint16_t calcCRC( au16data[3]);
     au16data[1] = slave.getInCnt();
  au16data[2] = slave.getOutCnt();
  au16data[3] = slave.getErrCnt();

 }

if you need 2 numbers after comma then you can uint16_t x =CS*100 it will store 3010. When extracting from uint to float float y = (float)x/100.

Sizes

Integer Types (int, long and long long)
Size of Boolean type is 1 byte(s)
Number of bits in a character: 8
Size of character types is 1 byte
Signed char min: -128 max: 127
Unsigned char min: 0 max: 255
Default char is unsigned
Size of short int types is 2 bytes
Signed short min: -32768 max: 32767
Unsigned short min: 0 max: 65535
Size of int types is 4 bytes
Signed int min: -2147483648 max: 2147483647
Unsigned int min: 0 max: 4294967295
Size of long int types is 4 bytes
Signed long min: -2147483648 max: 2147483647
Unsigned long min: 0 max: 4294967295
Size of long long types is 8 bytes
Signed long long min: -9223372036854775808 max: 9223372036854775807
Unsigned long long min: 0 max: 18446744073709551615
Note that int and long are the same size and if you want a 64 bit integer then you need to use long long (or unsigned long long).

What do you want to achieve with

.
CS=30.10 // 30.10
Int_CS=int(CS) // 30
FLOAT_CS = (Int_CS-CS)*100 //-10.00 because 30 - 30.10 = -0.1 and -0.1 * 100 = -10.00

CS is already float, why you want to convert it to int and back to float? If value of int is higher than 255 you have to save it in 2 bytes(highByte and lowByte), float is 32bit(4bytes) value.
I think you have to do like this:
float CS = 30.10;
au16data[0]= (int)(CS*100);//3010.00 > 3010

And for better way use :
float auFloatData[30]; //
...
auFloatData[0]=Current_Value1[0];

Minor correction: Default char is signed in gcc (compiler shipped with arduino). You can pass -funsigned-char compiler flag to have unsigned as default.

@Martynas But i have already tried that.when then it zero at end it print only 301 not 3010. SO it will difficult to recognize .when it turns out 3 digit value.

@AMPS What is the range of CS?

it measure 0~25 A , for understanding i given example above.

What accuracy do you need?

0.5% accuracy. I am considering it for testing. Later i go with other model

@AMPS i edited my answer, see if that is ok for you


text:
Timestamp in Arduino
int sensorArray[32] ;
int selectPinZero = 8;
int selectPinOne = 9;
int selectPinTwo = 10;
int selectpinthree=11;
int Enablepin=7;

int inputPinOne = 0;
int inputPinTwo = 1;

int sensor1;
int sensor2;
int voltage1;
int voltage2;
int Current_Sensor1[16];
int Current_Sensor2[16];
int row;
int column;

int array[17][5]={
                    {0,0,0,0,0},
                    {0,0,0,0,1},
                    {0,0,0,1,0},
                    {0,0,0,1,1},
                    {0,0,1,0,0},
                    {0,0,1,0,1},
                    {0,0,1,1,0},
                    {0,0,1,1,1},
                    {0,1,0,0,0},
                    {0,1,0,0,1 },
                    {0,1,0,1,0},
                    {0,1,0,1,1},
                    {0,1,1,0,0 },
                    {0,1,1,0,1},
                    {0,1,1,1,0 },
                    {0,1,1,1,1},
                    {1,0,0,0,0}
                 };

unsigned long StopTime=0;
int Counter=0;

void setup(){

  Serial.begin(9600);
  pinMode(selectPinZero, OUTPUT);
  pinMode(selectPinOne, OUTPUT);
  pinMode(selectPinTwo, OUTPUT);
  pinMode(selectpinthree,OUTPUT);

  pinMode(inputPinOne, INPUT);
  pinMode(inputPinTwo, INPUT);
}

void loop()
{

  for(row=0;row<17;row++)
  {

    digitalWrite(Enablepin,array[row][0]);
    digitalWrite(selectPinZero,array[row][1]);
    digitalWrite(selectPinOne,array[row][2]);
    digitalWrite(selectPinTwo,array[row][3]);
    digitalWrite(selectpinthree,array[row][4]);
    sensor1=analogRead(inputPinOne);
    sensor2=analogRead(inputPinTwo);
    voltage1=sensor1 * ARDUINO_ANALOG_SCALING;
    voltage2=sensor2* ARDUINO_ANALOG_SCALING;
    Current_Sensor1[row]=(10*voltage1)-25;
    Current_Sensor2[row]=(10*voltage2)-25;
    Serial.print("Currentsensor1:");
    Serial.println( Current_Sensor1[row]);
    Serial.print("Currentsensor2:");
    Serial.println( Current_Sensor2[row]);
     Counter=Counter+1;
    Serial.print("Counter:");
    Serial.println(Counter);
    Serial.println(".......................");
        delay(1000);

     }
}

Here is my Arduino code. I wanted to activate Digital pin for every 1000ms delay.
During each delay the analog value should be stored in an array of index.
I don't know how to keep track of analog value read, or from which port I am reading. I could flicker the LED on the hardware side but it doesn't make any sense. Any method you can suggest here?
Application:
I have 32 hall sensors connected via mux circuit. I wanted to know which sensor is reading value. I want any idea to might suggest to me to keep track here.

You should download timer1 library from http://playground.arduino.cc/Code/Timer1
Init timer1 with a value of 1000000 and it will perform an overflow every second. On every overflow it will perform an action, put your code to activate a pin there. And do the serial readings in your loop.


text:
Multiple MFRC522 RFID reader on Uno bugs
I have a problem!
I need to connect 5 MFRC522 readers on an Arduino Uno but it is not working !
With one or two MFRC522 modules it works, when I use three or more nothing works anymore... The serial reading is not working, nothing is read with more than 2 modules. I'm so sad. So tonight I need your help, tell me what is not working in my code or on my setup!
I first thought that it was the Arduino that was not delivering enough current to the modules (on the 3.3v line) but this does not seem to be the case. We added some external ATX PSU power, and connected grounds. Nothing changed.
So we had a look at the code and we believe that it is a library problem. Nobody seems to have successfully connected more than 3 MFRC522 modules. Is there really a problem in the library? How could we achieve success?
#include <SPI.h>
#include <MFRC522.h>
#include <EEPROM.h>

#define SS_PIN_1 10 // PIN SDA pour le module RFID (1)
#define RST_PIN_1 9 // PIN RESET pour le module RFID (1)
#define SS_PIN_2 8 // PIN SDA pour le module RFID (2)
#define RST_PIN_2 7 // PIN RESET pour le module RFID (2)
#define SS_PIN_3 6 // PIN SDA pour le module RFID (3)
#define RST_PIN_3 5 // PIN RESET pour le module RFID (3)
#define SS_PIN_4 4 // PIN SDA pour le module RFID (4)
#define RST_PIN_4 3 // PIN RESET pour le module RFID (4)
#define SS_PIN_5 2 // PIN SDA pour le module RFID (5)
#define RST_PIN_5 A0 // PIN RESET pour le module RFID (5)
#define RELAY_PIN A1 // Pin du signal du Relais
#define RELAY_ON 1024 // Valeur de seuil d'activation du relais
#define RELAY_OFF 0 // Valeur de seuil de désactivation du relais
#define MASTER_BUTTON_PIN A2 // Pin du bouton d'ouverture prioritaire
#define CONFIGURE_BUTTON_PIN A3 // Pin du bouton de reprogrammation des badges
MFRC522 rfid1(SS_PIN_1, RST_PIN_1);
MFRC522 rfid2(SS_PIN_2, RST_PIN_2);
MFRC522 rfid3(SS_PIN_3, RST_PIN_3);
MFRC522 rfid4(SS_PIN_4, RST_PIN_4);
MFRC522 rfid5(SS_PIN_5, RST_PIN_5);
byte tag1[4] = {0xD6, 0x92, 0xBF, 0x93};
byte tag2[4] = {0xC6, 0xA3, 0xC0, 0x93};
byte tag3[4] = {0x96, 0x58, 0x68, 0x8E};
byte tag4[4] = {0x06, 0xFB, 0xC1, 0x93};
byte tag5[4] = {0x66, 0xF3, 0x63, 0x8E};

void setup() {
  Serial.begin(9600);
  SPI.begin();
  rfid1.PCD_Init();
  rfid2.PCD_Init();
  rfid3.PCD_Init();
  rfid4.PCD_Init();
  rfid5.PCD_Init();
  Serial.println("Initialisation du système terminé, en attente de badges...");
}

void activate_relay(){
  analogWrite(RELAY_PIN, RELAY_ON);
  Serial.println("Le relay est activé");
}

void desactivate_relay(){
  analogWrite(RELAY_PIN, RELAY_OFF);
  Serial.println("Le relay est désactivé");
}

void loop() {
  if (! rfid1.PICC_IsNewCardPresent()) {
    return;
  }
  if (! rfid1.PICC_ReadCardSerial()) {
    return;
  }
  if (! rfid2.PICC_IsNewCardPresent()) {
    return;
  }
  if (! rfid2.PICC_ReadCardSerial()) {
    return;
  }
   if (! rfid3.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! rfid3.PICC_ReadCardSerial()) {
    return;
  }
   if (! rfid4.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! rfid4.PICC_ReadCardSerial()) {
    return;
  }
   if (! rfid5.PICC_IsNewCardPresent()) {
    return;
  }
  if ( ! rfid5.PICC_ReadCardSerial()) {
    return;
  }
  if (rfid1.uid.uidByte[0] == tag1[0]  & rfid1.uid.uidByte[1] == tag1[1] & rfid1.uid.uidByte[2] == tag1[2] & rfid1.uid.uidByte[3] == tag1[3]) {
    if (rfid2.uid.uidByte[0] == tag2[0]  & rfid2.uid.uidByte[1] == tag2[1] & rfid2.uid.uidByte[2] == tag2[2] & rfid2.uid.uidByte[3] == tag2[3]) {
      if (rfid3.uid.uidByte[0] == tag3[0]  & rfid3.uid.uidByte[1] == tag3[1] & rfid3.uid.uidByte[2] == tag3[2] & rfid3.uid.uidByte[3] == tag3[3]) {
        if (rfid4.uid.uidByte[0] == tag4[0]  & rfid4.uid.uidByte[1] == tag4[1] & rfid4.uid.uidByte[2] == tag4[2] & rfid4.uid.uidByte[3] == tag4[3]) {
          if (rfid5.uid.uidByte[0] == tag5[0]  & rfid5.uid.uidByte[1] == tag5[1] & rfid5.uid.uidByte[2] == tag5[2] & rfid5.uid.uidByte[3] == tag5[3]) {
          } else {desactivate_relay();}
        } else {desactivate_relay();}
      } else {desactivate_relay();}
    } else {desactivate_relay();}
  } else {desactivate_relay();}
}

I've tried the code above but it didn't work. I also tried the ReadUidMultiReader example code but only one reader is working. Both Readers are working individually but only one when I connect them. I shared the SCK, MISO, MOSI, RST, and have different SS pins.

Thank you in advance.

I don't see the code

@Mazaryk Hello ! I'm glad you'r here to help the comunity ^^.
The code has been added. Enjoy :D

You can use analog pins as digital. You don't need to use analogWrite. Also your code could be a lot shorter with arrays and for loops.

I'm working on a schematic for you, fritzing <3

@gre_gor That's a good idea indeed ! Will try it tomorrow when I go back to my local Fablab.

I have noticed that this problem is very common.
Have a look here :
https://github.com/miguelbalboa/rfid/issues/290

For convenience, here is a comment:  You wrote, “I've tried the code above but it didn't work”.   That is inadequate to convey what happened and what you wanted to happen.    Please edit your question to include a clear statement of symptoms and desired results.
Now on to an answer.
From “I'm only using 2 readers to find the correct and make it work”, I deduce that you have two readers attached.  This by itself is enough to keep the code from producing output.  Assuming those two readers identify as rfid1 and rfid2, when execution gets to if ( ! rfid3.PICC_IsNewCardPresent()), it executes return; which terminates loop() processing.  That is, execution will never get past if ( ! rfid3.PICC_IsNewCardPresent()).  To clear up that problem, remove all the code that references rfid variables other than rfid1 and rfid2 (more properly, other than whichever two you have attached).
That will entail removing 18 lines in the early part of loop(), and three lines in the big nested-if part of loop().
Here is another comment:  When you are debugging code, it makes sense to report lots of intermediate results, and to report them as soon as they are available.  Don't go through a long stack of if statements and get no output and then say it doesn't work; instead, display and check results when you first read them in.

I upvoted this question when it used to help me but now I can not un-vote it ? stange website.
The project still does not work.

“still does not work” doesn't tell what happened and what you want to happen. Please edit your question to include a clear statement of symptoms and desired results.  You edited the question to add a diagram but still just say "didn't work" instead of anything about intermediate results. ¶ The notion that you should unvote this that used to help, but now doesn't because you changed things, is perverted.  It discourages me from replying further:  If I edit my reply, then you can change your vote; so now I won't change it and probably won't reply further.  Oh well.

However, you could write a new question with a clear statement of symptoms, desired results, current code, and intermediate-values printout.

No, don't worry I won't down-vote your question, so I'm going to edit my question and make a better schematic.

Ok, great.  Printing intermediate-values probably would be the most useful item to add.  Also, the sequence of 10 if (...) {  return;  } statements is such that if any one of those tests fail, you return from loop() with no further processing on that pass.  You could instead set status variables (or status bits in a word) so at least something gets reported.

after around million of trying and trying I discovered that the correct way to connect 4 RFID RC522 is to put them in the same line on test board except SS pins and the code as usual is ReadUidMultiReader from RFID library ... like this :

yes that is how SPI works. you can read about it on wikipedia, but the topic of the question above is different. OP does know how to wire the readers. they don't ask about wiring.

This way has solved the same problem because if you don't put them in the same line on test board you don't get enough current to 2 or 3 of them.

authors: هبة الجبه جي

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
lcd.print and 2D arrays
Click here to see my program running
I have created a 2D array (see my full code below), and each row contains one state of a battery here is  a schematic :
row [0] : "▯▢▢▷" // this row represents an empty AAA battery
row [1] : "▮▩▢▷"
row [2] : "▮▩▩▷"
row [3] : "▮▩▩ ▶"  // this row represents a Full AAA battery

Each "▩" character is a custom made character with this function:
lcd.createChar(0, customLcdfont_squareONE);

As you saw in my video it works at the end, but it's absolutely not the way I want it to work. The code that works is a mess!
I think the problem is that the Raw n°1 ([0]) starts with a 0, (try it out it's very strange). If we replace
char batteryFonts [10][5] = {
  { 0, 1, 1, 2 }, // you see { this "0", 1, 1, 2 }, is a problem I think
  { 3, 1, 1, 2 },
  {etc}, }
lcd.print( batteryFonts[0]);  // this sentence does not work

with
"char batteryFonts [10][5]={{ 4, 1, 1, 2 }, // 4 or what ever you want
  {etc},
  {etc}, }
 lcd.print( batteryFonts[0]);  // this sentence behind does work, but only with a row that does not start with a 0. Why?

It works!
Here is my full code. Just connect the pins 12, 13, 7, 4, 3, 2 to the LCD.
//This is a simple program that charges alkaline batteries
//Copyleft
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 13, 7, 4, 3, 2); // why pin 13 and not 12 ? because I love the led attached to it <3

// the empty battery - end
byte customLcdfont_A [8] = { // B stand for "Binary" and then the pixel ...
B01111,
B11000,
B10101,
B10100,
B10100,
B10100,
B11000,
B01111

// the empty battery body with fancy graphics enabled

};
byte customLcdfont_B [8] = { // B stand for "Binary" and then the pixel ...
B11111,
B00000,
B11001,
B00000,
B00000,
B00000,
B00000,
B11111
};

// the empty battery + end

byte customLcdfont_C [8] = { // B stand for "Binary" and then the pixel ...
B11100,
B00100,
B10111,
B00101,
B00111,
B00111,
B00100,
B11100
};

// the full battery - end

byte customLcdfont_D [8] = { // B stand for "Binary" and then the pixel ...
B1111,
B11111,
B10110,
B10111,
B10111,
B10111,
B11111,
B1111
};

// the FULL battery + end
byte customLcdfont_E [8] = { // B stand for "Binary" and then the pixel ...
B11100,
B11100,
B01111,
B11101,
B11111,
B11111,
B11100,
B11100
};

// the full battery  body

byte customLcdfont_F [8] = {
B11111,
B11111,
B00110,
B11111,
B11111,
B11111,
B11111,
B11111
};

// the 1/3 battery body

byte customLcdfont_G [8] = {
B11111,
B11000,
B00001,
B11000,
B11000,
B11000,
B11000,
B11111
};
// the 2/3 battery body

byte customLcdfont_H [8] = {
B11111,
B11110,
B00111,
B11110,
B11110,
B11110,
B11110,
B11111
};

/**************************************************************************/
void setup() {
  int i = 0 ;
  // initialize serial communications at 9600 bps:
  lcd.createChar(0, customLcdfont_A);
  lcd.createChar(1, customLcdfont_B);
  lcd.createChar(2, customLcdfont_C);
  lcd.createChar(3, customLcdfont_D);
  lcd.createChar(4, customLcdfont_E);
  lcd.createChar(5, customLcdfont_F);
  lcd.createChar(6, customLcdfont_G);
  lcd.createChar(7, customLcdfont_H);

  lcd.begin(16, 2);

// WATCH HERE IS THE PROBLEM !!!!

//the char table behind creates my different battery states as shown in the video ;)

 char batteryFonts [10][5]={

 { 0, 1, 1, 2 }, // this is an empty one  f%*# this does not work !!!
 { 3, 1, 1, 2 },
 { 3, 6, 1, 2 },
 { 3, 7, 1, 2 },// this is a 50 % full charged battery !

 { 3, 5, 1, 2 },
 { 3, 5, 6, 2 },
 { 3, 5, 7, 2 },
 { 3, 5, 5, 2 },
 { 3, 5, 5, 4 },// this is nice full one
 };

 // this sentence behind does not work !!! but only with the raw [0]

 lcd.print( batteryFonts[0]);    // I F***ing want this to display the first raw !!!!
 lcd.setCursor(0,1 );

  lcd.print(" not working ");
 lcd.setCursor(0,0 );

        delay(9300); // this make a short pause  for us so that we can see the result
lcd.setCursor(0,1 );

  lcd.print("    working      ");
 lcd.setCursor(0,0 );
      for (i=0; i=10 ; i+=1 ){
       delay(300);

  lcd.setCursor(6,0 );

  lcd.write(byte(0));   lcd.write(byte(1)); lcd.write(byte(1)); lcd.write(byte(2));
    delay(700); //  batterry 0/8 empty aka discharged

  lcd.setCursor(6,0 );
  lcd.write(byte(3));   lcd.write(byte(1)); lcd.write(byte(1)); lcd.write(byte(2));
    delay(1000); //batterry 1 /8

  lcd.setCursor(6,0 );
  lcd.write(byte(3));   lcd.write(byte(6)); lcd.write(byte(1)); lcd.write(byte(2));
   delay(1000);//batterry 2 /8

  lcd.setCursor(6,0 );
   lcd.write(byte(3));   lcd.write(byte(7)); lcd.write(byte(1)); lcd.write(byte(2)); //batery 3 /8

  delay(1000);

  lcd.setCursor(6,0 );
   lcd.write(byte(3));   lcd.write(byte(5)); lcd.write(byte(1)); lcd.write(byte(2));
  delay(1000); //batery 4 /8

  lcd.setCursor(6,0 );
        lcd.write(byte(3));  lcd.write(byte(5));     lcd.write(byte(6));   lcd.write(byte(2));
  delay(1000); //batery 5 /8

  lcd.setCursor(6,0 );
      lcd.write(byte(3));  lcd.write(byte(5));   lcd.write(byte(7));  lcd.write(byte(2));
        delay(1000); //batery 6 /8

  lcd.setCursor(6,0 );
      lcd.write(byte(3));  lcd.write(byte(5));   lcd.write(byte(5));  lcd.write(byte(2));
      delay(1000); //batery 7 /8

  lcd.setCursor(6,0 );
    lcd.write(byte(3));  lcd.write(byte(5));     lcd.write(byte(5));    lcd.write(byte(4)); //batery 8 /8

    delay(1000);

      }

    lcd.setCursor(15, 1);

    delay(115000);

}

/**************************************************************************/
void loop() {

//This is not interesting here
  lcd.print(" ~ The end of the code ... thank you for reading ;) ~ ");

}

You are correct; in C a NUL (0x00) is used to indicate the end of a char*. You will need to use LiquidCrystal::write() in order to send the character data byte by byte instead of depending on LiquidCrystal::print() to handle it.
Also, consider moving all of that static data into flash; you're going to need to handle it manually so you may as well do it right in the first place.

This confirms my doubs ! It's sloppy isn't it  ?
It's the same as in the C89 I studied, but slightly uncomfortable and I think the arduino  compiler should be updated to avoid this "issue"

It has nothing at all to do with the compiler. It is a fundamental tenet of C/C++, and LiquidCrystal::print() adheres to it.

Oh realy ? So I should study more !

I don't say thanks... as the comment box told me to avoid to say thanks (y) But I realy want to !

It's okay, your sentiment has reached me.


text:
How do i fill the second byte?
I am using I2C communications to control a AD5694RBRUZ (http://www.analog.com/media/en/technical-documentation/data-sheets/AD5696R_5695R_5694R.pdf) with my Arduino Nano. If i enter two bytes it wil Wire.write only the first line from top to bottom. In the datasheet it is shown that you muust first fill the command byte, then the high and last the low byte. How can i fill the low byte? I have now scraped the idea to input two bytes separately and decided to input one uint16_t byte. How do i fill the low byte at the same time as the high byte, or if it possible how to input the uint16_t value?
My code is as follows:
#include <Wire.h>

#define Address 0x0D

void setup()
{
Serial.begin(9600);
Wire.begin();
AddressWrite(0x3F,0x05B0);
Serial.print ("Biti = ");
Serial.println (AddressRead(0x01));
}

void loop()
{
}

void AddressWrite (byte Naslov, uint16_t Cifra1)
{
byte Hi, Lo;
Hi = highByte(Cifra1);
Lo = lowByte(Cifra1);
Wire.beginTransmission(Address);
Wire.write(Naslov);
Wire.write(Cifra1);
Wire.endTransmission();
Serial.print ("Biti Hi = ");
Serial.println (Hi);
Serial.print ("Biti Lo = ");
Serial.println (Lo);
Serial.print ("Biti Cifra = ");
Serial.println (Cifra1);
}

byte AddressRead (byte naslov)
{
Wire.beginTransmission(Address);
Wire.write(naslov);

Wire.requestFrom(Address,2);

while(!Wire.available())
  {
  }

return Wire.read();
}

Thank you for your time and help.

You can use a number of Wire.write to write data.
The AD5694R should get three bytes and two bytes can be read from it. There is a "multiple dac readback sequence", but that is an extra.
Your AddressWrite requires an extra Wire.write.
Your AddressRead is missing a Wire.endTransmission and the while(!Wire.available()) should be removed.
void AddressWrite (byte Naslov, uint16_t Cifra1)
{
  byte Hi, Lo;
  Hi = highByte(Cifra1);
  Lo = lowByte(Cifra1);

  Wire.beginTransmission(Address);
  Wire.write(Naslov);       // command byte
  Wire.write(Hi);           // msb first
  Wire.write(Lo);           // lsb second
  Wire.endTransmission();
}

uint16_t AddressRead (byte naslov)
{
  Wire.beginTransmission(Address);
  Wire.write(naslov);       // command byte
  Wire.endTransmission(false);  // repeated start

  uint16_t hi, lo, result;
  Wire.requestFrom(Address,2);
  hi = Wire.read();
  lo = Wire.read();
  result = word(hi,lo);
  return result;
}

I have added a repeated start, because that is according to the datasheet.
Could you make the names more according to the datasheet ? For example 'command' or 'commandByte' instead of 'Naslow'. And perhaps better names for the functions, for example 'writeAD5694R' instead of 'AddressWrite'.

Thank you hor the help may good man. The names have been decided by my boss, but i will inform him of your words of wisdom. Oh and one more thing. MAY YOUR BLOOD LINE LAST A 1000 YEARS. THANK YOU MY HERO!!!


text:
Why use an int variable for a pin when const int, enum or #define makes much more sense
Why do people use a variable to specify a pin number when the pin is unlikely to change throughout the execution of the code?
Many times I see an int being used for a pin definition,
int led = 13;

when the use of a const int
const int led = 13;

or enum, or #define
#define LED 13

makes much more sense.
It is even in tutorials on the Arduino site, for example, the first tutorial that most people run, Blink.
I read somewhere that const int is preferred over #define. Why isn't this encouraged right from the beginning, rather than allowing people to develop bad habits, from the outset? I noticed it a while back, but recently it has started to irritate me, hence the question.
Memory/processing/computing wise is a const int, enum, or for that matter #define, better than a plain int, i.e. occupies less memory, stored in different memory (Flash, EEPROM, SRAM), faster execution, quicker to compile?

This may appear to be a duplicate of Is it better to use #define or const int for constants?, but I am addressing the question of why people use variables, and how does the performance improve when they don't, rather than which type of constant is better.

Because terrible begets terrible. Most hobbyists aren't seasoned programmers and so teach other hobbyists bad habits.

With pins in particular, the simplistic form of the basic arduino API functions like digitalWrite don't encourage proper embedded design, i.e. using masks and a single memory address for the entire port

const int led = 13;

That is the correct method. Or even:
const byte led = 13;

How many pins do you have?
Some of the tutorials did not quite go through as much quality control as they might have.
Performance will be better using const byte, compare to int however the compiler may be smart enough to realize what you are doing.
What you can do is gently encourage people to use more efficient techniques by using them in your own code.

Responses to comments

A commenter has suggested that byte is not standard C. This is correct, however this is an Arduino StackExchange site, and I believe using standard types supplied by the Arduino IDE is acceptable.
In Arduino.h there is this line:
typedef uint8_t byte;

Note that this is not exactly the same as unsigned char. See uint8_t vs unsigned char and When is uint8_t ≠ unsigned char?.
Another commenter has suggested that using byte will not necessarily improve performance, because numbers smaller than int will be promoted to int (see Integer Promotion Rules if you want more on this).
However in the context of a const identifier, the compiler will generate efficient code in any case. For example, disassembling "blink" gives this in the original form:
00000086 <loop>:
  86:   8d e0           ldi r24, 0x0D   ; 13
  88:   61 e0           ldi r22, 0x01   ; 1
  8a:   1b d1           rcall   .+566       ; 0x2c2 <digitalWrite>

In fact it generates the same code whether the 13:

Is a literal
Is a #define
Is a const int
Is a const byte

The compiler know when it can fit a number into one register and when it can't. However it is good practice to use coding that indicates your intent. Making it const makes it clear that the number won't change, and making it byte (or uint8_t) makes it clear that you are expecting a small number.

Confusing error messages
Another major reason to avoid #define is the error messages you get if you make a mistake. Consider this "blink" sketch which has an error:
#define LED = 13;

void setup() {
  pinMode(LED, OUTPUT);      // <---- line with error
}

void loop() {
  digitalWrite(LED, HIGH);   // <---- line with error
  delay(1000);
  digitalWrite(LED, LOW);    // <---- line with error
  delay(1000);
}

On the surface it looks OK, but it generates these error messages:
Blink.ino: In function ‘void setup()’:
Blink:4: error: expected primary-expression before ‘=’ token
Blink:4: error: expected primary-expression before ‘,’ token
Blink:4: error: expected `;' before ‘)’ token
Blink.ino: In function ‘void loop()’:
Blink:8: error: expected primary-expression before ‘=’ token
Blink:8: error: expected primary-expression before ‘,’ token
Blink:8: error: expected `;' before ‘)’ token
Blink:10: error: expected primary-expression before ‘=’ token
Blink:10: error: expected primary-expression before ‘,’ token
Blink:10: error: expected `;' before ‘)’ token

You look at the first highlighted line (line 4) and don't even see a "=" symbol. Plus, the line looks fine. Now it's fairly obvious what the problem is here (= 13 is being substituted for LED), but when the line is 400 lines further down in the code, it isn't obvious the problem is with the way LED is defined.
I've seen people fall for this many times (including myself).

How many pins do you have? is a very good point Nick, as most boards have only in the range of the tens, not hundreds (i.e. greater than 255), so an int is overkill... that is, until Arduino finally come out with the Tera board... :-)

C doesn't have a byte type.  You mean unsigned char.

Performance won't necessarily be better with byte instead of int, since in most contexts, integer value with types smaller than int are promoted to int.

C doesn't have a byte type. You mean unsigned char. - My answer was in the Arduino context, which has this typedef uint8_t byte;. So for an Arduino, using byte is OK.

Performance won't necessarily be better with byte instead of int - see amended post.

As Ignacio has rightly states, it's basically because they don't know better.  And they don't know better because the people who taught them (or the resources they used when learning) didn't know better.
Much of the Arduino code and tutorials are written by people who have never had any training in programming and are very much "self taught" from resources by people who themselves are very much self taught with no proper training in programming.
Many of the snippets of tutorial code I see around the place (and especially those that are only available within YouTube videos --- urgh) would be a fail mark if I were marking them in an exam.
Yes, a const is preferred over a non-const, and even over a #define, because:

A const (like a #define, unlike a non-const) does not allocate any RAM
A const (like a non-const, but unlike a #define) gives the value an explicit type

The second point there is of particular interest.  Unless specifically told otherwise with embedded type-casting ((long)3) or a type suffix (3L) or the presence of a decimal point (3.0), a #define of a number will always be an integer and all mathematics performed on that value will be as if it were an integer.  Most of the time that's not a problem, but you can run into interesting scenarios when you try to #define a value that is larger than an integer can store, such as #define COUNT 70000 and then perform a mathematical operation with other int values on it.  By using a const you get to tell the compiler "This value is to be treated as this variable type" - so you would instead use: const long count = 70000; and all would work as expected.
It also has the knock-on effect that it checks the type when passing the value around the place.  Try passing a const long to a function that expects an int and it would complain about narrowing the variable range (or even completely fail to compile depending on the scenario).  Do that with a #define and it would just silently carry on giving you the wrong results and leave you scratching your head for hours.

It's worth noting that a const variable may require RAM, depending on the context, e.g. if it's initialised using the return value from a non-constexpr function.

Similarly, const int foo = 13; bar(&foo); will definitely require the compiler to allocate actual memory for foo.

If you define a macro that expands to a value that won't fit in an int the compiler treats the value as having the smallest type in which it will fit (modulo rules about signed vs. unsigned). If you're on a system where int is 16 bits, #define count 70000 will result in count looking like a long, just as if it had been defined as const long count = 70000;. Further, if you pass either of those versions of count to a function expecting int, any sane compiler will treat them the same.

I agree with @PeteBecker - a construct like #define COUNT 70000 does not truncate into an int, but the compiler treats it as a type large enough to hold that number. It is true that it might not be obvious when you use COUNT that it isn't an int, but you could say the same thing about a const long anyway.

"a #define will always be an integer" That is not true. You are taking the rules of integer literals and applying them to preprocessor macros. It's like comparing apples and pop music. The expression COUNT in your example is replaced before compilation with the expression 70000, which has a type defined by the rules of literals, just like 2 or 13L or 4.0 are defined by the rules of literals. The fact that you use #define to alias those expressions is irrelevant. You can use #define to alias arbitrary chunks of C code, if you like.

As a consequence your final paragraph is wrong too. It seems like you fundamentally misunderstand the preprocessor. A shame because the rest of the answer was great!

I don't understand what you're on about there. I am not applying anything to macros. I am applying literal rules to the results of the macro expansion - that is why I talk about explicit casting and type suffixes within the macros.

As a 2-week newbie to Arduino I'd pick up on the general idea of Arduino being occupied by non-programmers. Most sketches I have examined, including those on the Arduino site, show a total lack of order,  with sketches that do not work & barely a coherent comment in sight. Flow charts are non-existent, and the "Libraries" are an un-moderated jumble.

My answer is... they do it because it works. I'm having a hard time not asking a question in my answer such as "why does it have to be 'wrong'?"

One hallmark of a good programmer is that the code always reflects their intentions.

We're still talking about Arduinos, right? ;)

Arduino already has a bad rep in the larger EE community because of the mediocre-to-terrible hardware designs put out by the community. Shouldn't we try to give a sh*t about something?

I guess I've come to appreciate the 'just enough' approaches that are common in the Arduino make community. Most projects aren't going to involve risk of life or finances so what difference does it make if Blink.ino uses an int or a const int? Those who stick with it and gain experience will learn when it matters and when it doesn't.

"Most projects aren't going to involve risk of life or finances..." No surprise there. Who would want to involve Arduino where there's any chance of risk after looking at the community at large.

It's 'wrong' not because it doesn't work in one particular situation but because, compared to doing it 'right,' there are more situations in which it doesn't work. This makes the code fragile; changes to the code can cause mysterious failures that eat up debugging time. The compiler's type checking and error messages are there to help you catch those sorts of errors earlier, rather than later.


text:
Delay on multiple NRF24L01+ (RF24.h) and Arduino nodes
I have set up a system using 4 arduino clones, each wired to an NRF24L01+ radio. I am using the RF24 library by maniacbug (https://github.com/maniacbug/RF24) and have set-up the nodes with 1 base node as a receiver and 3 child nodes that transmits continuously to the receiver.
What I want to do is to send the read and analog value wirelessly from the child nodes to the base node as fast as possible. I used the starping example as a guide and it looks almost realtime when only 1 child node is active. When I turn on another child node, most of the time the update stops for a while then continue on, with randomly updating either child 1 or child 2.
I'm guessing there's a collision that's causing the delays. How do I lessen these delays? I'm thinking of having some sort of scheduling system for the children to send their messages (like, child2 will send only after child1, etc.) I also tried radio.setAutoAck(false) in an attempt to lessen the delays but that made all my readings stop altogether.
base node:
    #include "Timer.h"
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"
    #include "printf.h"

    RF24 radio(9,10);
    Timer t;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    unsigned int values[3] = {0,0,0};
    void setup(void)
    {

      Serial.begin(115200);
      printf_begin();
      //printf("Receiver Node Active\n\r");

      radio.begin();

        radio.openReadingPipe(1,pipes[0]);
        radio.openReadingPipe(2,pipes[1]);
        radio.openReadingPipe(3,pipes[2]);
        radio.openReadingPipe(4,pipes[3]);
        radio.openReadingPipe(5,pipes[4]);

      radio.startListening();
      radio.printDetails();
      t.every(1, print_values); //call print_values() every 1ms

    }

    void loop(void)
    {
        int sender_id;
        uint8_t pipe_num;
        if ( radio.available(&pipe_num) )
        {
          unsigned int message;
          bool done = false;
            while (!done)
            {
                done = radio.read( &message, sizeof(message) );
            }
          sender_id = pipe_num - 1;
          values[sender_id-1] = message;
        }
        delay(1);
        t.update();

     }

     void print_values(){
       //formatted for arduinoscope
       printf("%d %d %d 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \n", values[0], values[1], values[2]);
     }
    // vim:ai:ci sts=2 sw=2 ft=cpp

child node:
    #include <SPI.h>
    #include "nRF24L01.h"
    #include "RF24.h"

    RF24 radio(0,1);

    const int SW01 = 18;
    const int SW02 = 19;

    const uint64_t pipes[5] = { 0xF0F0F0F0D2LL, 0xF0F0F0F0C3LL, 0xF0F0F0F0B4LL, 0xF0F0F0F0A5LL, 0xF0F0F0F096LL };
    int node_id;

    void setup(void)
    {
      node_id=3; //hard coded id
      radio.begin();
      radio.openWritingPipe(pipes[node_id]);
    }

    void loop(void)
    {
        unsigned int val = analogRead(A0);
        radio.write( &val, sizeof(val) );
        //delay(1);
    }

You could have the receiver poll the transmitters instead. Maybe using writeAckPayload.

I'd suggest you'd update your library to this.

I am too building a RF24 based network there were two issues I encountered:
1) Update your libraries, use TMRh20 fork of RF24 (to make your life easier, use RF24Mesh too)
2) Add a decoupling cap to the NRF24L01+ power pins.

I can think of 3 ways:

You could have the Base polling for updates to each node
sequentially, or
If all child nodes see each other, node2 can hear when node1
finished transmitting so it can transmit and so on. Or
You can punch through collisions setting random delays between each
retry

1) Since these are all one-way communication, disable AutoAck on all NRFs (setAutoAck(false)). You're not doing Ack anyway which will cause retransmission when not acknowledged.
2) Change the address to something better.
Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate
3) Put a capacitor between ground and Vcc on all NRFs.


text:
How can I read also the temperature with this GSR sensor?
Considering the GSR is the inverse of the Resistance, if I know the resistance and how much it increases for every celsius degree, the game would be done.
Here's how my code looks like at the moment:
const int GSR=A0;
int threshold=0;
int sensorValue;
const long interval = 1000;
unsigned long T = millis();

void setup(){
  long sum=0;
  Serial.begin(115200);
  delay(1000);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
   Serial.print("threshold =");
   Serial.println(threshold);
  }

void loop(){

  if( millis() - T >= 250)  {
   int temp;
  sensorValue=analogRead(GSR);
  Serial.println(sensorValue);
  temp = threshold - sensorValue;
  T = millis();

  }
  }

The page of the sensor:
http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor

The GSR measures resistance. You have temperature. -> What is the formula to transform temp to res in your case? Why don't U use a simple lm35, pt100 or do it digitally with ds18b20? A matter of minutes.

https://upload.wikimedia.org/math/c/8/e/c8e9a28af18315880dd5090267057812.png
Here's the equation to do it
Source: https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance


text:
Why does this code show me a lot of space?
I want to make a 4hz reading of GSR and temperature, in the following format for every second:
697,20.8744
696,20.86521
695,20.8653
699,20.8777

The print, in python, would be print(GSR+","+Temp)
The tries in C are giving problem, here's my actual code:
#include <OneWire.h>

const int GSR=A0;
int threshold=0;
int sensorValue;
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
OneWire  ds(3);

void setup(){
  long sum=0;
  Serial.begin(115200);

  for(int i=0;i<500;i++)
  {
  sensorValue=analogRead(GSR);
  sum += sensorValue;
  delay(5);
  }
  threshold = sum/500;
  }

void loop()
{
  byte i;
  byte present = 0;
  byte type_s;
  byte data[12];
  byte addr[8];
  float celsius;
    if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        // Do your job, such as
        sensorValue=analogRead(GSR);
        Serial.print(sensorValue);
        Serial.print(",");
        if ( !ds.search(addr)) {
    ds.reset_search();
    return;
  }

  if (OneWire::crc8(addr, 7) != addr[7]) {
      return;
  }
  // the first ROM byte indicates which chip

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

   // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();
  }

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  Serial.print(celsius);

    }
    Serial.println("\n");

}

How can I reach the upper format?

From the point of view of what you print, your loop boils down to:
if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.print(celsius);
}
Serial.println("\n");

You are printing two newlines on every loop iteration. One is written
as "\n", the other is the “ln” of Serial.println (“println” means
“print some stuff followed by a new line character sequence”). Instead,
you probably want to print a single newline, and only when there is
actual data being printed:
if (millis() - startTime >= MEASURE_PERIOD) {
    startTime += MEASURE_PERIOD;
    sensorValue = ...;
    celcius = ...;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius);  // notice the ln in println
}

But since you are doing nothing else in loop(), you could simplify a
bit and avoid having everything inside a big if statement:
if (millis() - startTime < MEASURE_PERIOD)
    return;

startTime += MEASURE_PERIOD;
sensorValue = ...;
celcius = ...;
Serial.print(sensorValue);
Serial.print(",");
Serial.println(celsius);

Edit: Here is a simple test demonstrating this logic. In both the
second and the third case, it generates an output in the requested
format.
const uint32_t MEASURE_PERIOD = 250;

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    static uint32_t startTime;
#ifdef SECOND_CASE
    if (millis() - startTime >= MEASURE_PERIOD) {
        startTime += MEASURE_PERIOD;
        int sensorValue = random(695, 699);
        float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
        Serial.print(sensorValue);
        Serial.print(",");
        Serial.println(celsius, 3);  // notice the ln in println
    }
#else  // third case
    if (millis() - startTime < MEASURE_PERIOD)
        return;

    startTime += MEASURE_PERIOD;
    int sensorValue = random(695, 699);
    float celsius = map(sensorValue, 695, 699, 208653, 208777) / 1e4;
    Serial.print(sensorValue);
    Serial.print(",");
    Serial.println(celsius, 3);  // notice the ln in println
#endif
}

Why do you say putting the print outside the if will simplify things?

Maybe “simplify” is not the right word, but it will remove one nesting level to most of your code. I (among others) find this is better for readability.

In the second case I have lines like that:
691,690,20.81
The third case doesn't work

@GabrieleGiordano: Then you have either a communication error, or an error somewhere else in your code. C.f. the test I added as an edit.

I think it's much slower than 250ms. If i put 1000 at the beginning, it gives me a print ever 2 seconds I think

In the third code you wrote, the startTime += MEASURE_PERIOD; is just outside the big if?

I confirm the suspect: it's one reading every sec, I compared with data of another sensor that works at 1hz. I had the same number of elements in the array

Precisely it's 2hz instead of 4

@GabrieleGiordano: Your sensor may be slow to respond, or you may have some other problem elsewhere in your program: different problem → different question. The test code above, on my Arduino Uno, outputs 4 lines per second.

the problems seem to be the sensor, that can't read at 4hz

but with another code seems to work. Anyway, its' a matter of another question


text:
How is it possible that my skin temperature is so constant?

Here's the code
#include <OneWire.h>

int DS18S20_Pin = 3; //DS18S20 Signal pin on digital 3
unsigned long startTime = 0;
#define MEASURE_PERIOD 250
//Temperature chip i/o
OneWire ds(DS18S20_Pin);  // on digital pin 3

void setup() {
  Serial.begin(115200);
}

void loop() {
  if((millis() - startTime) >= MEASURE_PERIOD)
    {
        startTime += MEASURE_PERIOD;
        float temperature = getTemp();
        Serial.println(temperature);
    } //just here to slow down the output so it is easier to read

}

float getTemp(){
  //returns the temperature from one DS18S20 in DEG Celsius

  byte data[12];
  byte addr[8];

  if ( !ds.search(addr)) {
      //no more sensors on chain, reset search
      ds.reset_search();
      return -1000;
  }

  if ( OneWire::crc8( addr, 7) != addr[7]) {
      Serial.println("CRC is not valid!");
      return -1000;
  }

  if ( addr[0] != 0x10 && addr[0] != 0x28) {
      Serial.print("Device is not recognized");
      return -1000;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44,1); // start conversion, with parasite power on at the end

  byte present = ds.reset();
  ds.select(addr);
  ds.write(0xBE); // Read Scratchpad

  for (int i = 0; i < 9; i++) { // we need 9 bytes
    data[i] = ds.read();
  }

  ds.reset_search();

  //byte MSB = data[1];
 // byte LSB = data[0];

  float tempRead = ((((int)data[1]) << 8) | data[0]); //using two's compliment
  float TemperatureSum = tempRead / 16;

  return TemperatureSum;

}

What are X and Y axes on graph?

X time, Y temperature

Y is standardized temperature

Examine your code closely.  It appears that you are partially implementing extended resolution calculations in this line of code:
  float TemperatureSum = tempRead / 16;

In the DS18S20 specifications the extended resolution equation used is:
 TEMPERATURE = TEMP_READ * 0.25 - ((COUNT_PER_C - COUNT_REMAIN) / (COUNT_PER_C))

Where COUNT_PER_C is a DS18S20 register containing a value of up to 16.  Maybe that is where 16 originated?
I believe what you want to do is divide the recovered value by 2.0 base on table 1 from the DS18S20 specifications:
  float TemperatureSum = tempRead / 2.0;

Don't forget the "." in case the compiler you are using decides to do integer math dripping the "float" part before assigning it to TemperatureSum.

I'm not sure I understood what you are suggesting. If i put 2.0 I have values like that:
165
164,5
165

The DS18S20 (https://datasheets.maximintegrated.com/en/ds/DS18S20.pdf) specification says the temperature is returned in degrees centigrade and is in 1/2 degree increments (table 1, page 6).  There might be other important details.  But you said you did not see enough change.  Dividing by 16 instead of 2 would explain that.

Your values do not make sense.  In your graph when you measure your skin temperature you get 0.96 C when you divide by 16.  But in your comment above when you divide by 2 you are getting 165 C  The value 0.96 * 16 is no where near 165 * 2. Carefully consider how you are posting so that we can find the problem faster...  Oh, I get it!  You're using commas as decimal points.  Still, that doesn't explain the 0.96.  But 96 * 16 ~= 165 * 2.

Also, consider the possibility the DS18S20 packaging is slow to respond and the possibility the DS18S20 is internally computing an average in an attempt to reduce noise and increase resolution.  In this (http://electronics.stackexchange.com/questions/186449/what-is-the-fastest-temperature-sensor) stackexchange answer a ti.com TO92 package temperature sensor response is show.  It appears to take 6 to 10 seconds to report the correct oil bath temperature.

0.96 is not the temperature. It's the standardized temperature: value/max(list of values)

Please explain the horizontal axes as well.  Is it time in milliseconds?

it shows seconds

Try using Dallas Temperature Control Library for DS18S20. (Click Here, Download Library). Its simple and easy to use, and it comes with examples.
Here is tutorial.
Hope it helps.

I'm curious why a person found this not useful

I didn't understand how can I put it at 12bits


text:
How to Publish to MQTT with retain option
I don't understand how to publish to mqtt with retain option (The fourth parameters)
I know that I need length in an byte array but I've try allot to determine how to calculate my payload message to an byte var.
here is my code to publish once I am connected.
String str;
char chBright[4];
str = String(ledBrightness); //converting integer into a string
str = str + '%';
str.toCharArray(chBright, 4);
MQTTClient.publish("/maison/GF/Escalier/stairLight/b", chBright);

document ask the third parameter to be an byte

topic – the topic to publish to char*
payload – the message to publish byte array
length – the length of the message byte
retained – whether the message should be retained byte

0 – not retained
1 – retained

mqtt client for Arduino
How in c++ to get bytes from the message I want to publish?
Tank you to clarify my knowledge

Just to clarify: char chBright[2]; and then str.toCharArray(chBright, 4); - you want to put 4 bytes into a 2 byte field, is that it?

ow! you'r right... good mistake sorry.

I think I've found something! https://www.arduino.cc/en/Reference/ByteCast

How to Publish to MQTT with retain option?

The quick answer is add payload length, and retained as true as the last parameters to publish().
const int BUF_MAX = 8;
char buf[BUF_MAX];
itoa(ledBrightness, buf, 10);
strcat(buf, "%");
int len = strlen(buf) + 1;
MQTTClient.publish("/maison/GF/Escalier/stairLight/b", buf, len, true);

Above is a rewrite with the extra parameter for "retained", payload length, and payload as a null-terminated string.
Cheers!

How in c++ to get bytes length from the message I want to publish?

For a String object, the method length() tells you the length.
eg.
int len = str.length ();

For a null-terminated C-type string, you can use strlen, eg.
char foo [20] = "bar";
int len = strlen (foo);


text:
Slow WiFi reconnection after deep sleep (6 to 10 seconds)
With my ESP8266, I need to make a simple GET request to a server, and then go to deep sleep (the goal is 1 year battery powered)... until a signal comes on RST and then it starts again.
The following code works, but it takes 6 to 10 seconds on each RST to get connected to my home WiFi using "WPA2 Personal" (when it stops blinking in my code).
Is this 6 to 10 seconds delay normal, do you have the same order of magnitude? Or can we go down to 1 second, after a wake-up from deep sleep?
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
WiFiClient client;
HTTPClient http;
void setup() {
    pinMode(LED_BUILTIN, OUTPUT);
    if (WiFi.SSID() != WIFI_SSID) {     // don't do begin if not necessary, see tutorial link after
        WiFi.begin("MySSID", "MyPassword");
        WiFi.persistent(true);
        WiFi.setAutoConnect(true);
        WiFi.setAutoReconnect(true);
    }
    while(WiFi.status() != WL_CONNECTED) {
      digitalWrite(LED_BUILTIN, LOW); delay(10); digitalWrite(LED_BUILTIN, HIGH); delay(200);  // blinking
    }
    http.begin(client, "http://example.com/request.php");
    http.GET();
    http.end();
    digitalWrite(LED_BUILTIN, LOW); delay(500); digitalWrite(LED_BUILTIN, HIGH); delay(500);
    ESP.deepSleep(0);
}
void loop() {
}

Note: I have read and carefully respected this useful information about low power / battery-powered ESP8266:
Power Saving tips for the ESP8266  (especially this paragraph):

Do not call WiFi.begin() in setup().
The ESP8266 chip saves the last known wifi settings. Calling WiFi.begin() wipes those out. By calling WiFi.begin() only when it was needed, I shaved more than 2 seconds from the average amount of time it takes to associate with the AP. WiFi.begin() should be called only if the saved SSID does not match the configured SSID. You can check the configured SSID with the WiFi.SSID() call. Also, it is good practice to clear the saved WiFi settings if the timer expires. (See next section "Use watchdog timers")

and does it use now the automatic connection and is it faster?

It is in general take around 6s for the ESP to scan all the 2.4GHz Wi-Fi channels to find the SSID and the associated BSSID (i.e. Mac Address), you can eliminate the scanning time by connecting using BSSID. See one of my project (under the "ESP8266 WiFi - How to speed up connection" section) where I cut the connection time from 6s down to about 2s.

It is in general take around 6s for the ESP to scan all the 2.4GHz Wi-Fi channels to find the SSID and the associated BSSID (i.e. Mac Address), you can eliminate the scanning time by connecting using BSSID.
Using a static IP instead of rely on DHCP server to assign an IP would further reduce the WiFi connecting time by another 500ms.
See one of my project (under the "ESP8266 WiFi - How to speed up connection" section) where I cut the connection time from 6s down to about 2s.
Code signature for WiFi.begin with BSSID here:
    const byte WIFI_BSSID[] = {0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC};
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD, 0, WIFI_BSSID);

For calculating IoT battery consultion, use IoT battery life calculator.

Thank you @hcheung for your answer. Do you know how much power it takes to do wake up + connection to Wifi (2 secondes) + send a single HTTP request (a few bytes to send) + go to deep sleep ? Do you think 200 mA * 3 seconds = 0.17 mAh is the right order of magnitude ? So it could be done ~6000 times on 3 AA batteries ? (I don't have equipment to do more precision measurement)

You need to do some measurement and calculate it yourself. As different boards may use different components, particularly the on-board LDO may not be designed for deep sleep application and has leakage current during deep sleep. If you can't design your own board, then look for those specially designed for battery-operation.

Thanks @hcheung. What is "LDO"? Do you know standard consumer level ESP32 (easy to find on popular shops) that have good battery-operation?

LDO stands for Low Dropout Output, refer to the regulator that convert the input voltage to 3.3v on your board. Typical Chinese made ESP32 boards or ESP8266 boards do not have good LDO, they designed for powering via USB.

Thanks @hcheung. PS: I edited to add the code + link to doc about function signature (not easy to find!)