message:
Question on pin management using PCA9534PW IO Extender

There is an IO expander [PCA9534PW][1], Arduino UNO. I don’t really understand how I can manage this expander using UNO over I2C.

I found an [example][2], but here is the reading mode.

  [1]: https://datasheet.lcsc.com/szlcsc/NXP-Semicon-PCA9534PW-118_C161197.pdf
  [2]: http://diy-scib.org/content/pca9534-io-expander

What I need:
Set the IO0 pin to exit mode,
set the HIGH / LOW level to IO0.

In the datasheet, I just realized that to enter the settings mode - you need to write Wire.write(0x03).
How can I do it?

body:
You set the pin mode by setting the configuration register.

    Wire.beginTransmission(0x20);
    Wire.write(0x03);                   // Configuration Register
    Wire.write(0xfe);                   // IO7-IO1 Input, IO0 Output
    Wire.endTransmission();

Then write the output port register with HIGH and LOW.

    Wire.beginTransmission(0x20);
    Wire.write(0x01);                   // Output Port Register
    Wire.write(0x01);                   // IO0 HIGH
    Wire.endTransmission();
    delay(500);
    Wire.beginTransmission(0x20);
    Wire.write(0x01);                   // Output Port Register
    Wire.write(0x00);                   // IO0 LOW
    Wire.endTransmission();

But using a library is much easier. See, for instance, https://github.com/alotaiba/PCA9534.


sender: user

message:
Matrix keyboard and 7segment display countdown combination

I'm working on an escape room for my university with an Arduino Mega.
The last part consists of a 7segment display representing a time countdown, and the participants have to introduce the correct number in a matrix keyboard before it reaches zero.

My problem comes when for representing the seconds in the countdown, I have to use a delay, and this stops the matrix keyboard from getting the numbers.

The code I have so far:

    char keys[4][4] =
    {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
    };

    byte rowPins[4] = { 5, 4, 3, 2 };
    byte colPins[4] = { 9, 8, 7, 6 };

    int pinA = 26; //2
    int pinB = 34; //3
    int pinC = 31; //4
    int pinD = 27; //5
    int pinE = 25; //6
    int pinF = 28; //7
    int pinG = 33; //8
    int D1 = 24; //9
    int D2 = 30; //10
    int D3 = 32; //11
    int D4 = 35; //12

    Keypad mykeypad = Keypad( makeKeymap(keys), colPins, rowPins, 4, 4);

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

    pinMode(pinA, OUTPUT);
    pinMode(pinB, OUTPUT);
    pinMode(pinC, OUTPUT);
    pinMode(pinD, OUTPUT);
    pinMode(pinE, OUTPUT);
    pinMode(pinF, OUTPUT);
    pinMode(pinG, OUTPUT);
    pinMode(D1, OUTPUT);  //Turns the first digit on.
    pinMode(D2, OUTPUT);  //Turns the second digit on.
    pinMode(D3, OUTPUT);  //Turns the third digit on.
    pinMode(D4, OUTPUT);  //Turns the forth digit on.
    }

    //
    void showTime(){

      digitalWrite(D1, LOW);
      digitalWrite(D2, LOW);
      digitalWrite(D3, LOW);
      digitalWrite(D4, LOW);

     //3
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, HIGH);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, HIGH);
      delay(1000);

    //2
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, LOW);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, HIGH);
      delay(1000);

      //1
      digitalWrite(pinA, LOW);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, HIGH);
      digitalWrite(pinD, LOW);
      digitalWrite(pinE, LOW);
      digitalWrite(pinF, LOW);
      digitalWrite(pinG, LOW);
      delay(1000);

      //0
      digitalWrite(pinA, HIGH);
      digitalWrite(pinB, HIGH);
      digitalWrite(pinC, HIGH);
      digitalWrite(pinD, HIGH);
      digitalWrite(pinE, HIGH);
      digitalWrite(pinF, HIGH);
      digitalWrite(pinG, LOW);
      delay(1000);

    }

    //Receives the chars from the matrix keyboard.
    void getCode(){
       char key = mykeypad.getKey();
      if(key){
         Serial.print(key);
      }
    }

    void loop()
    {

      showTime();

    }

Any idea on how can I archieve this combination? Have been trying to find something similiar to a Thread, but Arduino doesn't support it.

Thanks in advance.

sender: assistant

body:
Use the "blink without delay" examples in the IDE, whereby you perform an action and then basically watch the clock until and let the rest of the code run until the time elapes.  For example, this blinks the onboard LED on and off, you can add to it for your keypad reading and time outputs.

    unsigned long currentTime;
    unsigned long previousTime;
    unsigned long elapsedTime;
    const byte ledPin = 13;
    byte ledState = 0;

    void setup(){
    pinMode (ledPin, OUTPUT);
    previousTime = millis();
    }
    void loop(){
    currentTime = millis();  // capture the 'time' now
    elapsedTme = currentTime - previousTime; // how much 'time' has passed
    if (elapsedTime >= 1000){  // at least one second?
    ledState = 1 - ledState; // results in 1,0,1,0,1,0 ...
    digitalWrite (ledPin, ledState); // toddle the L led
    previousTime = currentTime;   // set up for the next pass thru loop
    // update the to display, and output it
    }
    // now add keypad reading stuff
    }


body:
Try using `millis()`, it returns the number of milliseconds passed since the Arduino board began running the current program.

When you start the countdown you set a variable for a beginning time

`int millisBegin = millis(); //put this at the end of your setup() {}`.

You will also need a "border" to know when one second is over, so

`int millisBorder = 1000; //one second border`

Every time your the `loop() {}` starts over you can check if one second has passed so far

    int millisNow = millis();
    if(millisNow - millisBegin >= millisBorder){} //if one second over, do {}

Now I would work on the segment showing thingy. In the `{}` I would put a new variable, let's call it `counter = 4; //4 because I found 3 numbers in your sketch`. Every time the `if() {}` is being executed, you go through more `if () {}` statements, checking what number to display next.

    if (counter == 3)
    {
      //show number 3
    }

    if (counter == 2)
    {
      //show number 2
    }

    if (counter == 1)
    {
      //show number 1
    }

    if (counter == 0)
    {
      //show number 0
    }
    counter = counter - 1;

At the end we take one off the counter, so the next time we enter the `if(one second over)` the number displayed will get lower

And well now there are multiple ways of doing the keyboard thingy. You can keep checking if there is a key available, and if so you can safe it as a String (most people hate strings, but I never had a problem with them to be honest).

After you've saved the key as a String you can use the `strcmp();` method to compare the string with the solution/answer `strcmp(key,answer);`. If the key and the answer are the same, it will return 1.

    if(strcmp(key,answer) == 1)
    {
      Serial.println("you made it");
    }


message:
Arduino Mega not receiving data from Neo-6M

I am using the trying to get data from the Neo-6M GPS module with an Arduino mega, but, the condition 'While (gpsSerial.available() > 0' is being met. I believe this means the no bytes are being transferred from the module to the serial port but I'm not sure why.
The light on the Neo-6M was blinking which means it getting a lock but not giving out the data.

    #include <SoftwareSerial.h>

    // Choose two Arduino pins to use for software serial
    int RXPin = 19;
    int TXPin = 18;

    //Default baud of NEO-6M is 9600
    int GPSBaud = 9600;

    // Create a software serial port called "gpsSerial"
    SoftwareSerial gpsSerial(RXPin, TXPin);

    void setup()
    {
      // Start the Arduino hardware serial port at 9600 baud
      Serial.begin(9600);

      // Start the software serial port at the GPS's default baud
      gpsSerial.begin(GPSBaud);
      Serial.write("123");
    }

    void loop()
    {
      // Displays information when new sentence is available.
      while (gpsSerial.available() > 0)
        Serial.write(gpsSerial.read());
    }

I had it working on an Uno by connecting to pins 2,3 rather then 18 and 19. I have also tried swapping the 18 and 19 pins over but still noting.

Thanks for the help

EDIT:
I have the RX and TX plugged into the mega at pins 1 and 2, however, it will only print GPS information when the reset button is pressed or held down

body:
Not all pins on the Mega support software serial, have a read below:

https://www.arduino.cc/en/Reference/SoftwareSerial

Pins 18 / 19 are actually hardware serial pins so should not need the use of software serial.

Edit, should have noted to use hardware pins 18 / 19 you would use the constructor Serial1.begin(9600)


message:
Measure voltage changes with unknown baseline

I would like to monitor an audio stream and detect when it is "active" and music is playing or when it is "inactive" and is silent. What is a good way to measure when an audio stream changes state and continues to be "active?"

Each audio stream is amplified with [this circuit][2].

Each audio stream has a different baseline voltage when it is not playing and "silent", but that voltage tends to drift slightly and change. This may be an artifact of my amp. I don't have an OScope and my multimeter is rubbish for low voltage so I can't quite pin down where the drift is coming from.

Currently, I'm using the method shown below, but that isn't as effectivewhen the audio stream is loud (e.g. has a [compressed dynamic range][2]).

Also, low volume tracks (e.g. classical music) tends have too low of a dynamic range to measure accurately and I get a lot of false "off" states.

```
#include <elapsedMillis.h>    //measure elapsed time

const int analogInPin = A0;   //Analog input pin - reads from amplifyer circuit
const int statusLight = 10;   //Digital output pin for indicator light
int sensorValueA = 0;         //Sensor reading now
int sensorValueB = 0;         //Previous sensor reading
int sensorDeltaA = 0;          //Change in sensor reading
int sensorDeltaB = 0;          //Record the last delta - useful for prefenting accidental triggering on start
int sensorThreshold = 50;      //Threshold in delta to trigger action
elapsedMillis turnOverTime;   //Timer for measuring the turnover between changes in sensor reading

void loop() {
  //measure the analog input
  sensorValueA = analogRead(analogInPin);
  sensorDeltaA = abs(sensorValueA - sensorValueB);

 //check if the data is over the threshold and switch on
  if ((sensorDeltaA >= sensorThreshold) and (sensorDeltaB != 0)) {
    turnOverTime = 0;
    powerStateA = true;
  }

  sensorValueB = sensorValueA;

  //check if no sensor data beyond the threshold has been returned within the delay window, switch off
  if (turnOverTime >= delayTime) {
    turnOverTime = 0;
    powerStateA = false;
  }

  //if the powerstate changes act acordingly
  if (powerStateA != powerStateB) {
    digitalWrite(statusLight, powerStateA);
  }
}
```
  [1]: https://arduino.stackexchange.com/questions/21157/arduino-read-frequency-of-input-from-audio-jack/21165#21165?newreg=853b0d7cc9554d15ad2da1ab8b66d5fe
  [2]: https://en.wikipedia.org/wiki/Dynamic_range_compression

body:
An audio signal consists of two main components:

* An AC signal
* A DC offset

What you are interested in is the AC signal, but not the DC offset.  That DC offset is what is drifting in your current model.

So you need to *AC couple* the signal. That is, couple the signal to your Arduino in such a way that only the AC portion gets through.

The simplest way is with a capacitor.

But the Arduino can't handle negative voltages, and an AC signal has negative voltages. So you need to get rid of them.

The simplest way is to add a DC offset.

But didn't we just get rid of a DC offset that we didn't want? Yep. But that was an *unknown* DC offset. If we then add in a DC offset that we do know, and is stable, then we can work with it.

Here's a very simple circuit:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/OOrii.png)

<!-- End schematic -->

The capacitor C1 removes the existing DC offset.  R1 and R2 then form a voltage divider giving 2.5V (half of 5V), which is then added to the pure AC signal.

That means that the signal now varies around 2.5V.  Silence is 2.5V, and noise is other values above and below that.

Since 2.5V is half of the 5V the Arduino runs on, silence should read at somewhere near half the ADC value. That's about 512.  Sound will be both above and below that value.

So if you subtract 512 from your analog reading you will effectively be subtracting the DC offset you just added, giving you a value that can be either positive or negative.

For simplicity, since you don't care whether it's positive or negative, you can then remove the sign from the number to just give you a magnitude.

    int audio = analogRead(A0); // Get a sample
    audio = audio - 512; // Remove DC offset
    audio = abs(audio); // Remove sign

You can now compare that to a threshold value:

    if (audio > 100) {
        // do something
    }


message:
Why is AREF connected to a capacitor in the Arduino Pro Mini Schematic?

I'm currently looking at the Arduino Pro Mini schematic and have noticed that the pin AREF (analogue reference) is connected to a 0.1uF capacitor as shown below:

[![enter image description here][1]][1]

I have done some research and read [this][2] great explanation into AREF and now understand its purpose as a voltage reference. What I do not understand however is the purpose of the capacitor. Is it as a means of stabilising the pin when an external voltage is applied, or something else?

A full schematic of the Arduino Pro Mini can be sourced from [here][4].

  [1]: https://i.stack.imgur.com/QeQk7.gif
  [2]: https://tronixstuff.com/2013/12/12/arduino-tutorials-chapter-22-aref-pin/
  [3]: https://forum.arduino.cc/index.php?topic=91799.0
  [4]: https://sites.google.com/site/cisc071jc/public/schematics/arduino-pro-mini

body:
On the datasheet for the Atmega328P, in the Analog-to-Digital Converter section, is the sentence:

> The voltage reference may be externally decoupled at the AREF pin by a capacitor for better noise performance.

Also:

> The internal voltage reference may thus be decoupled by an external capacitor at the AREF pin to improve noise immunity.

Thus the capacitor is there to reduce noise on the AREF pin.


body:
An ideal capacitor presents an impedance of wC (radian frequency * capacitance -- ohms).  Of course ideal capacitors do not exist in real component selections or circuits and all include parasitic losses and inductance. The parasitic components depend on the type of the capacitor, lead length, connecting circuits, etc.  Oscilloscopes, network analyzers and spectrum analyzers serve to identify fundamental performance of voltage reference points.

The decoupling capacitor should be connected using short leads to a ground plane layer and the Aref pin.


message:
NodeMCU ESP32s can't get Vin to work?

Trying to power the board with a 9V battery through VIN. As the documentation says, it can take input voltage of 6-12 Volts, but when I connect the 9V battery, all it does is power the board on and nothing else happens.

Anyone know what I am doing wrong?

EDIT: I am stupid had the ground connected to the wrong pin thanks for the help everyone.

body: Assuming you are using a 9V block battery: They don't deliver the current you need for the esp32 to run/create an access point/act as a client. What you can do is connect 6 AA batteries in a row (6*1.5V = 9V) and they will deliver a higher current than the 9V block.


message:
Arduino New Optiboot Bootloader on custom ATMega328p board, ATMEL Studio and AVRdude

I am about to ask a kind of complex question due to the number of system parts involved and the system architecture I am planning to use.

First of all I have a tiny bit of experience with the Arduino Nano and a professional experience with C microcontroller programming.

What I would like is to create a custom ATMega328p board that *does something* and be able to update whatever firmware is running on it using the UART port.

1) Firmware updating
--------------------
Since I am not so familiar with bootloaders, I would skip for now writing my own, so I would like to use the newest Arduino Bootloader for ATMega328p to support the firmware updates.

2) Custom program compilation
-----------------------------
What I definitely do NOT want is use Arduino Sketch IDE to compile whatever application code. I am using Atmel Studio up to now for whatever bootloaderless applications I was doing and I would like to keep using that with my own project and code structure. The question here is, do I need to make any linker modifications or modifications in the code in Atmel Studio projects in order to be able to "transform" my code into application code so that can coexist with the bootloader?

3) Updated firmware programming
-------------------------------

After the board is on the field running with the Optiboot bootloader and an outdated firmware, I would like to use a thirdparty software to communicate with the bootloader and update the application code. Since the optiboot bootloader used by Arduino uses the STK500 communication protocol and functionality, could I use AVRdude to communicate with the bootloader and flash the applications code only through UART?

Do you think this concept could work?

Thank you in advance.
polylogic

body:
> Since I am not so familiar with bootloaders, I would skip for now writing my own, so I would like to use the newest Arduino Bootloader for ATMega328p to support the firmware updates.

Even people who do know about bootloaders rarely bother writing their own when there is a perfectly good one with good support and good cross-platform tools available.  Why would you?

> The question here is, do I need to make any linker modifications or modifications in the code in Atmel Studio projects in order to be able to "transform" my code into application code so that can coexist with the bootloader?

No. The bootloader resides at a high memory address, and your code at address 0x0000 just like normal.  A fuse is set to say "Boot at the bootloader address", and another lets you set the size of the bootloader area (and thus the bootloader address).

> Since the optiboot bootloader used by Arduino uses the STK500 communication protocol and functionality, could I use AVRdude to communicate with the bootloader and flash the applications code only through UART?

Yes. This is what the Arduino IDE does. It just runs `avrdude` to communicate with the bootloader.  If you turn on verbose mode in the preferences you should be able to see what the exact command is that it runs so you can replicate it in your own program or script.


message:
Servo or motor with manual control

I am searching for a servo or motor with the ability to
easy manually controlling (turning) when power off.
What is the mechanism recommend to use?

Thank you for your answer.

body:
Motor that has no gearbox will be easier to manually turn when it is not powered.
Now, I don't know what you categorize as "easy" but this info will give you a starting point.

And I don't get why the use of the "arduino-nano" and "arduino-uno" tag


message:
Will a 12 VDC 1A Power Supply Adapter supply too much power and damage an Arduino Mega 2560?

The specs shown here:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/4FPoA.png

show that it has 54 digital pins with each outputting a DC current of 20mA which makes it 54 * 20 = 1080 mA

Plus the DC current of the 3.3V Pin of 30mA we get a total of 1110mA.

Is this how one should go about doing the computations?

If the adapter is insufficient will a 12 VDC 2A Power Supply Adapter be appropriate or excessive?

Any links to read up on will be greatly appreciated as well.

Links for this question:

https://store.arduino.cc/mega-2560-r3

https://store.nerokas.co.ke/index.php?route=product/product&product_id=567

PS: All I'm planning to connect to the board is: 'a PIR sensor (the first version not Rev B)', a '5V relay' and possibly a 'ESP8266 ESP-01S Relay Module'

body:
No. You have everything wrong there.

First off, a power supply does *not* provide power. It provides voltage. The device attached to it then *draws* current. As much current as it needs at any particular moment in time.  The current rating of a power supply is the *maximum* that the power supply can give.

The same goes for Arduino IO and power pins: The current ratings are the *maximum* current you can draw from the pin.

Exactly what current it will draw from the power supply depends completely on what is connected to what pins, and even what calculations the Arduino is doing at the time.  To get a ball-park figure of current requirements you need to know the current requirements of whatever is attached. If a device has its own power input that is the current you need to worry about. If a device is powered directly from an IO pin (such as an LED) then that forms part of the Arduino's current (which starts at about 40mA or so for the board itself).

There are many other factors to take into consideration:

* The 5V regulator on the Arduino can't give more than 1A maximum, and considerably less than that when powered from a high voltage like 12V.
* The DC jack on the Arduino is limited to 1A due to a polarity protection diode.

It is usually recommended to use a separate 3.3V regulator for an ESP8266 module (or 5V if your module has a built-in 3.3V regulator) due to the lack of power capacity in the Arduino's on-board regulators.

As a rough guestimate:

* Arduino: 40-60mA
* ESP8266: 200mA (when transmitting)
* PIR: Negligible
* Relay: 50mA when active

So you'd be looking at 300mA as a minimum. More is better. 1A should be more than sufficient. 2A would be overkill but give a big margin of error.

For everything you have there, it would be better to use a 5V power supply, not a 12V power supply.


body:
In addition to what Majenko told you, some additional information:

The Arudino uses a linear power supply. That type of power supply works by converting all the excess voltage above the output voltage to heat. So if you feed it 12V, at 1A, it has to convert 1 amp of  12V-5V, or 7 watts of power to heat. The heat sink on the Arduino is not up to dissipating 7 watts of heat.

A linear power supply needs a little more than the output voltage. Feeding it 7.5V would be just about right. You should be able to get a full amp of 5V out of the Arduino’s power supply if you feed it 7.5V at the input, although the output voltage will probably droop some as you approach the max output, and it will get hot. Don’t put it in an airtight container.

As Majenko says, you shouldn’t add up the max current output of every pin on the Arduino to get its power requirements. A digital output line will use almost no current unless it is feeding an output that draws current. Think of the power supply as a spring-fed well, and the output as scoops that scoop water out of the well. As long as you don’t scoop water out of the well faster than it can be replace by the spring, you’re ok. If you only use a couple of small scoops, you’ll hardly take any water out of the well. (If you only have a couple of low power outputs connected, you’ll only draw a small amount of current.)

The Arduino draws a moderate amount of current all by itself. See the specs for details.


message:
Cannot set MOSI pin low even after ending SPI

I'm building a battery operated device and must shutoff MOSI pin during sleep because it leaks current through the SD card if I don't (about 400 µA).

Problem is, it won't stay off.  I've looked at SPI documentation and as far as I know I just need to call `spi.end()` then set pinmode to output and finally digitalWrite LOW.  I observe with an oscilloscope that it does go low upon my asking it to but only for about 1 µs (actually it goes low twice within a 5 µs time period).

I've also tried manually setting the pin low using the PORT registers and the behavior is the same... see relevant code:

    spi.end();

    //pinMode(pin_MOSI, OUTPUT);
    //digitalWrite(pin_MOSI, LOW);

    //Both above (commented out) and below result in the same behavior -- pin does not stay LOW

    DDRB |= B00100000;            //set pin 5 as output
    PORTB &= B11011111;           //set output low for pin 5

    delay(5000);

...As you can see there is a delay to ensure that it isn't being set high by some other code.

Is there some sort of SPI interrupt that automatically sets the pin high again?

Hardware details:
-----------------
**MCU:** ATMEGA1284P;
**Programmer:** Atmel-ICE

----------

**UPDATE (13-Mar-2019):**
-------------------------

I didn't realize that SPI is implemented by Atmel in hardware directly (see datasheet page 105):

> MOSI/PCINT13 – Port B, Bit 5
– MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI0 is enabled
as a slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI
is enabled as a master, the data direction of this pin is controlled by DDB5. When the pin is
forced to be an input, the pull-up can still be controlled by the PORTB5 bit.

I am currently chasing down this latest information and will hopefully come to a resolution soon.  I will post any progress.

body:
Indeed, SPI is hardware implemented.  I was able to get the MOSI pin to operate as intended by clearing the SPI enable bit from the SPCR register as follows:

    SPCR &= 0B10111111;  //disable SPI

To re-enable after sleep, I'm assuming I'll just do `SPCR |= 0B01000000;` ...pretty sure that will work but I'll update here if I have to modify my solution.

.

**Perhaps also pertinant information:**

I was using an object of *SPIClass* in *SPI.h* which is from the Arduino core libraries -- for some reason it wasn't disabling SPI in hardware when calling the `spi.end()` method, maybe because there was some other SPI object initialized by some other library.  Here is the source from SPI.cpp for the *end* method:

    void SPIClass::end() {
      uint8_t sreg = SREG;
      noInterrupts(); // Protect from a scheduler and prevent transactionBegin
      // Decrease the reference counter
      if (initialized)
        initialized--;
      // If there are no more references disable SPI
      if (!initialized) {
        SPCR &= ~_BV(SPE);
        interruptMode = 0;
        #ifdef SPI_TRANSACTION_MISMATCH_LED
        inTransactionFlag = 0;
        #endif
      }
      SREG = sreg;
    }

The line `SPCR &= ~_BV(SPE);` should have done the job for me but I'm guessing it never got there because `initialized` was probably still non-zero.


message:
WS2812B only works while I measure the voltage

I'm going crazy, there is clearly something I'm missing here.
I have a NodeMCU V3.0 and a 5V LED strip WS2812B with 10 diodes.
I tested this first with a 5V 0.3A power supply, only powering 3 diodes, this worked fine.

Than I changed the power supply to a 5V 2A (Measured to 5.2V) and now the colours are way off, they even change everytime its updating, even though nothing is changed. I put my voltmeter across "D3" and "GND" and suddently the LEDs were perfect and stable.

If I remove it again, the LEDs change to random colours again, I tried pulling "D3" to ground with a 10 kOhm resistor, but this doesn't change anything.

What is going on here, why isn't it working, and why does it work with the voltmeter?

[![WS2812B][1]][1]

  [1]: https://i.stack.imgur.com/sX0UN.png

Code:

    #include <ESP8266WiFi.h>
    #include <FastLED.h>

    #define LED_PIN     3
    #define NUM_LEDS    10

    CRGB leds[NUM_LEDS];
    int R = 255;
    int G = 90;
    int B = 10;

    //Set up MQTT and WiFi clients
    WiFiClient client;

    void setup()
    {
      FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
      Serial.begin(9600);

      //Connect to WiFi
      Serial.print("\n\nConnecting Wifi... ");
      WiFi.begin(WIFI_SSID, WIFI_PASS);
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
      }
      Serial.println("OK!");
      pinMode(D4, OUTPUT);
      digitalWrite(D4, HIGH);
    }

    void loop()
    {
     leds[0] = CRGB(255, 0, 0);
        leds[1] = CRGB(0, 255, 0);
        leds[2] = CRGB(0, 0, 255);
     FastLED.show();
     delay(5000);
    }

body:
WS2812B LEDs are 5V devices. The NodeMCU is 3V.  Your first 5V supply will probably have been somewhat under 5V once the NodeMCU had taken a big chunk of the current (see [Voltage Droop](https://en.wikipedia.org/wiki/Voltage_droop)). This would mean that the [Logic High Threshold](https://www.allaboutcircuits.com/textbook/digital/chpt-3/logic-signal-voltage-levels/) would be within the bounds of the 3.3V output by the NodeMCU.

However, with your new high powered power supply that voltage droop will be less prevalent (added to the fact that it's measuring 5.2V), and so the logic high threshold will be higher. At, or very close to, the 3.3V that is output by the NodeMCU. That makes it rather unstable at communicating, since the logic HIGH may not always be above that required HIGH threshold.

Adding your voltmeter obviously changes that logic signal so that it stabilizes above the required threshold (the volt meter input has capacitance. That will help hold the line higher for longer).

To drive 5V devices from a 3.3V MCU you really need to add a logic level shifter, or ensure that the power supply isn't too high.

The WS2812B has a logic HIGH of [0.7 × Vdd](https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf). At 5V that's (0.7*5=) 3.5V. That's close, but not quite there. Your original power supply was probably putting out more like 4.75V under load. That would be 3.325V for a logic high - just about manageable by a NodeMCU.

However at 5.2V the logic HIGH will be 3.675V, which is way above the 3.3V that the NodeMCU outputs.

So you either need to:

* Add a 3.3V to 5V logic level shifter, or
* Reduce your LED power input voltage to below 4.75V.

The latter can be done by adding a single series diode with a suitable current handling capacity to the VDD connection. That will (depending on the diode) drop around 0.7V taking you to about 4.5V (the actual drop usually depends on the current to a certain extent).  The WS2812B will happily run from 3.5V to 5.3V.


message:
RGB not working properly

My RGB led is not working properly. It should light up red when the ultrasonic sensor detects more than 10 cm and green when it detects less than or equal 10 cm. It is just blinking red and green at the same time. How do I fix this?

    #include<Servo.h>
    Servo servo1;
    int Motor = 3;
    int tpin = 7;
    int epin = 6;
    int red1 = 12;
    int green1 = 13;
    int pos = 0;
    long duration, inches, cm;

    void setup() {
     Serial.begin(9600);
     pinMode(tpin, OUTPUT);
     pinMode(epin, INPUT);
     pinMode(red1, OUTPUT);
     pinMode(green1, OUTPUT);
     servo1.attach(Motor);

    }

    void loop() {
     digitalWrite(tpin, LOW);
     delayMicroseconds(5);
     digitalWrite(tpin, HIGH);
     delayMicroseconds(10);
     digitalWrite(tpin, LOW);
     duration = pulseIn(epin, HIGH);
     cm = (duration / 2) / 29.1;
     inches = (duration / 2) / 74;
     Serial.print(inches);
     Serial.print("in, ");
     Serial.print(cm);
     Serial.print("cm");
     Serial.println();
     delay(100);

     if ((cm > 10))
     {
      servo1.write(pos = 0);
      digitalWrite(red1, HIGH);
      delay(100);
      digitalWrite(red1, LOW);
      delay(100);
      Serial.println("\t RED");
     }
     else if ((cm <= 10))
     {
      servo1.write(pos = 90);
      digitalWrite(green1, HIGH);
      delay(100);
      digitalWrite(green1, LOW);
      delay(100);
      Serial.println("\t GREEN");
     }
    }

body:
The ultrasonic sensor scans every 0,1 seconds according to your code. Problem is, sometimes you have "faulty" results. Taking into consideration the frequency of your scans + the "faulty" scans, it could be that your arduino just keeps switching between those two LEDs.

What helped me back then was to make a counter. A variable, that counts how many times in a row the distance to the object is "distance <10cm". If the streak was interrupted, it would reset the variable. This is how a serial output would display it:

    distance: 20cm
    distance: 16cm
    distance: 8cm
    count: 1
    distance: 9cm
    count: 2
    distance: 6cm
    count: 3
    distance: 8cm
    count: 4
    distance: 11cm
    count: 0
    distance: 12cm
    distance: 20cm

And the moment your counter reaches a certain spot, for example the object is closer than 10cm five times in a row, then you will let an led light up

    if(count>=5)
    {
      //turn on green led (color may be wrong)
    }
    else
    {
      //turn on red led (color may be wrong)
    }


message:
Using a water sensor with a NodeMCU make it less sensitive?

I'm trying to `digitalRead` from a water sensor (the one in the picture) using NodeMCU v3,when I try the sensor with an Arduino board it works fine, but when I try it with an ESP8266 NodeMCU v3 it becomes less sensitive to water with some pins or doesn't work at all with the others. My question is: Is that normal or I'm doing something wrong ?
<!-- language-all: lang-cpp -->

     int pin = 14;
     char printBuffer[128];
     int ledPin = 12;
     const int buzzerPin = 13;

      void setup()
      {
        pinMode(pin, INPUT);
        pinMode(buzzerPin, OUTPUT);
        pinMode(ledPin,OUTPUT);
        Serial.begin(115200);
      }

      void loop()
      {
        sprintf(printBuffer,"PIN %d level is %d\n",pin, digitalRead(pin));
        Serial.print(printBuffer);
        if (digitalRead(pin)==HIGH)
        {
          tone(buzzerPin, 100,1000);
          digitalWrite(ledPin, HIGH);
          delay(100);
          noTone(buzzerPin);
          digitalWrite(ledPin, LOW);
          delay(100);
          Serial.println("----------- ALARM ACTIVATED -----------");
        }
        else{
          noTone(buzzerPin);
          digitalWrite(ledPin, LOW);
        }
        delay(500);
       }

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/kjGgC.png

body:
You are using it wrong.

That sensor (crude as it is) is an *analog* sensor. It's not designed to be used connected to a digital pin.

It outputs an analog voltage proportional to the resistance between the tracks in the sensing portion.

By feeding that voltage into a digital pin you are relying on the logic threshold values, plus any other components (pullup resistors, etc), to give you a "wet" or "try" signal.

Since pins differ (some have pullups, some pulldowns, some nothing, etc) and the logic thresholds are only an approximation in any case, it's doomed to failure.

You need to connect the sensor to an analog input and compare the value read to a threshold value of your choosing.  However the ESP8266 is very very poor when it comes to analog - it only has one analog input, and that is only capable of sensing between 0 and 1 volt.


message:
.elf and .hex equivalency? (code, eeprom, fuses, and lock bits all in one)

I have all configurations (eeprom data, fuses, lockbits) of my ATMega168A together with the code in my C files. The compilation creates an elf file that I use as an all-in-one programming file for production.

Just as a tryout, I converted the elf file to hex with avr-objcopy and saw that the code and configurations are still there (why wouldn't they).

My question is, if the two files are equivalent in case of using them for all-in-one programming. Is there any critical data stripping taking place between elf-to-hex conversion that could affect the actual programming?

Also, I tried again to convert the hex file to bin and saw again the same thing but of course with zero-padding. Except for the obvious different of file size, is there any practical difference when using the bin file and the hex file? Does this padding create any problems? (For example trying to write 0 to addresses that do not exist).

Thank you in advance.

body:
> My question is, if the two files are equivalent in case of using them for all-in-one programming. Is there any critical data stripping taking place between elf-to-hex conversion that could affect the actual programming?

Nothing critical, but data stripping does take place. Everything that is in the HEX file is in the ELF file. That is - all the compiled machine code and data.

Basically everything that gets written to the chip is in the HEX file, and the HEX file can be created from what is in the ELF file - ergo the ELF file contains everything that is in the HEX file.

However, not everything that is in the ELF file goes into the HEX file.

The ELF file contains a huge amount more information. Mostly that information is geared towards debugging. There are things like the names and locations of all the *symbols* in the code - that is, the functions and variables, etc. There are breakdowns of all the assembly instructions grouped by source code file and line number.

None of that is relevant for the Arduino environment, but when you're using professional tools to do your development you can use them for realtime debugging and tracing of your program while it's running on the real hardware.

None of that is relevant to putting your program on the chip. It's all used by the PC.


message:
What does "Update of OCR1x at" mean in the WGM table of ATMEGA328?

I just finished a reading a couple of online guides on how to use timer registers with pulse width modulation, so I'm still new to its concept.  When I looked in the ATMEGA328 specification sheet, I see this table:

[![enter image description here][1]][1]

The column that I'm not completely clear on is the "Update of OCR1x at".  I circled row 14 as an example.  If you're operating in mode 14 (ie. setting WGM 13, 12 and 11 to high), then you'll be in Fast PWM.  By setting a value for ICR1, you are effectively setting the TOP value, which will control the period of the pulse waves.  And the overflow flag on the timer will be set when the timer reaches the TOP value.

So does "Update of OCR1x at" mean that only when when the pulse wave form has reached the value of BOTTOM (or the end of a period), that's when the value of OCR1x will be passed on to the OCx pins if COMx bits are set?

  [1]: https://i.stack.imgur.com/fhvEC.png

body:
> So does "Update of OCR1x at" mean that only when when the pulse wave form has reached the value of BOTTOM (or the end of a period), that's when the value of OCR1x will be passed on to the OCx pins...

Yes, that's what it means. To prevent glitches in the PWM output, you frequently do NOT want the PWM waveform to change immediately the instant you update an OCR1A value, for instance, to change the PWM output on output pin A. So, the PWM value you set is double-buffered and only updates the inner buffer used by the output pins once it finishes its current PWM period and reaches the BOTTOM value again, which would be a counter value of 0 in this case. Now, by allowing a previous PWM period to finish before the hardware reads the latest value from the OCR1A/B register (outer buffer) to its inner buffer (which inner buffer actually determines the pin state), you have a nice, clean, glitch-free PWM transition from one value to the next regardless of when you updated the `OCR1A` or `OCR1B` output register.


message:
Unexpected negative values from abs() function inline with analogRead

When sampling from A0 with a 0-5V signal on an arduino micro with the code below I get some negative values.
```
int sensor = 0;
sensor = abs(analogRead(A0) - 512);
```
Values:
```
77
25
-74
-58
46
113
-74
102
-91
-51
-126
47
31
```

When running the (apparently) mathematically equivalent code below I get exclusively positive values.
```
int sensor = 0;
sensor = analogRead(A0);
sensor = sensor - 512;
sensor = abs(sensor);
```

I don't think this is an integer overflow as in this [post][1] because when I switch to `long sensor = 0` I get the same negative results.

What's going on here?

  [1]: https://arduino.stackexchange.com/questions/25989/getting-negative-results-from-calculations

body:
`abs()` is defined in [Arduino.h][1] as a macro:

     #define abs(x) ((x)>0?(x):-(x))

A macro does not evaluate in the same way as a function.

     sensor = abs(analogRead(A0) - 512);

This statement will be expanded at compile-time to:

     sensor = ((analogRead(A0) - 512)>0?(analogRead(A0) - 512):-(analogRead(A0) - 512));

Now the "error" is easy to understand. The analog pin is read twice. The "error" can be avoided by adding the following line first in your sketch:

    #undef abs

This will remove the macro `abs()` and the [standard library function][2] will be used instead.

Cheers!

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Arduino.h#L94
  [2]: http://www.cplusplus.com/reference/cstdlib/abs/


message:
How do I supply either (1) dual voltage or (2) negative voltage?

Sorry in advance if this question already exists--I tried to search but my keyword knowledge is shaky. I have created a Colpitts oscillator on breadboard using AA batteries as the power supplies. I want to implement this oscillator with an Arduino. (Once it's set up, I want to use its voltage to do some things, but that isn't part of this question.)

In the image below, I have two voltages, Vcc (positive voltage) and Vee (negative voltage). My simulations indicate I can run the oscillator either with a dual voltage (+5V and -5V), or with one negative voltage (-5V) and the other set to ground. Either provides a 100 kHz oscillation from about -5 to 2 V. So:

 - Is there a way to provide a dual voltage supply from the Arduino Uno?
 - Is there a way to provide a single negative voltage supply from the Arduino Uno?

Thanks!

[![Colpitts oscillator. According to simulations, I can set Vcc=0 and Vee=-5 and still observe oscillations][1]][1]

  [1]: https://i.stack.imgur.com/9EAde.png

body:
You can make -5 V if you use an external power source, like in the circuit below (untested).

Connect the GND (-) from the Arduino to the +5V from the External (5V) source, than 0V will be the GND (with respect to the Arduino), but the GND of the external source will be -5V with respect to the Arduino.

I only used the resistors to get no short circuits, you can replace it by your own circuit (connecting the 5V arrow to Vcc and the -5V arrow to Vee).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/g7ZOB.png)

<!-- End schematic -->


message:
Component with controllable resistance from Arduino?

I'm new to Arduino and building circuits, and was wondering if there is a type of component, or some other way to do the following task:

I want to control the resistance of a circuit from my computer linked to my Arduino, presumably using an output analog PIN.

Basically what I have is an LED whose brightness I want to control from my computer. I want to be able to control the resistance of the circuit to limit the electricity going to the LED, and I want to be able to do this from my computer (not physically, with a potentiometer) (unless a potentiometer's resistance can also be controlled from a PIN?).

How can I do this?

body:
The easiest way to drive an LED with variable brightness is to use one of the pulse width modulation (PWM) output pins on an Arduino.

A PWM pin takes an input value from 0 to 255 (or is it 0/1023? I don't remember.) and converts it to a ratio of on-time to off-time. At the highest value, the output pin is in the on state, 100% of the time. At the halfway point, the output pin is HIGH 50% of the time, and LOW 50% of the time.

Our eyes average out the flashes and see a variable brightness. It works very well.

If you absolutely must have a variable resistance controlled by a digital value, there are devices known as digital potentiometers. These are variable resistors controlled by digital inputs. For an Arduino, you should think about an I2C or SPI potentiometer, which is controlled by serial port commands. You tell it the resistance you want, and it sets itself to that resistance.

As CrossRoads points out in their comment below, you still need a current limiting resistor to drive an LED from a logic pin, to protect both the LED and the output driver on the Arduino. You want to limit the current to the max current for your LED, and then use PWM to lower the brightness from the absolute max set by the current limiting resistor. CrossRoads explains how to calculate the resistor value.


message:
Using NodeMCU D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) pins

I am using a NodeMCU board and have already used 6 digital pins as output for interfacing with the LCD. I intend to use 2 more digital pins, one as input and other as output for interfacing an ultrasonic sensor.

D8, D4 and D3 are the only digital pins remaining. I understand that D8 (GPIO15), D4 (GPIO2) and D3 (GPIO0) pins of the NodeMCU  have special boot-controlling uses. So how can I use those pins as generic digital pins. Any help is appreciated.

body:
The boot setup pins have pull-up on board (0, 2) and pull-down (15) to ensure the correct boot. io 0 (D3) is additionally wired to the reset circuit controlled over USB to put the esp8266 into bootloader a.k.a. flashing mode.

io 0 must be HIGH for normal boot, io 2 must not be LOW (can float according to spec).

If you attach a device to this pins, the device must respect the boot state. Some devices will pull-down or pull-up a wired pin. Usually it is not documented. You can't use such devices on boot config pin which requires the other state.

The pull-up and pull-down can influence the attached device or readings from the device. For some elements it can be advantageous.

Best is to use this pins for elements which would need pull-up or pull-down anyway. For example buttons/switches or sensors which behave like buttons or switches.

In my project with Wemos D1 R2 I had signal to relay module on io 0, speaker module (with amplifier) for tone() function on io 2. I could not use a relay or mosfet module on io 2. On io 15 I had a reed relay module control signal, which I didn't want to go HIGH at boot as most esp8266 io pins do.


body: Not a direct answer to your question, but some other way that solves your problem, is to use a shift register like 74HC595 and control the 6 pins for the LCD with the 74HC595 which only uses 3 (digital GPIO) pins. That saves you 3 pins for others. Actually you can use 8 pins or even 32 when you daisy chain four 74HC595s.


message:
Reading ADS1232 with Arduino

I'm a newbie and I'm trying to read an ADS1232 with an Arduino for a Weight Scale Project.

I read data through the SPI interface, but i don't receive the result.

<!-- language: c++ -->

    #include <SPI.h>

    #define MISOPIN  50  //DATA
    #define SCLKPIN  52  //SCLK
    #define PDWN     53  // SS
    #define SPEED       5
    #define GAIN0       7
    #define GAIN1       6
    #define CLKIN       10
    #define A0          9
    #define TEMP        8

    uint32_t byte1;
    uint32_t byte2;
    uint32_t byte3;
    uint32_t finaladc = 0;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);

      pinMode(PDWN, OUTPUT);
      pinMode(MISOPIN, INPUT);
      pinMode(SCLKPIN, OUTPUT);
      pinMode(SPEED, OUTPUT);
      pinMode(GAIN0, OUTPUT);
      pinMode(GAIN1, OUTPUT);
      pinMode(A0, OUTPUT);
      pinMode(TEMP, OUTPUT);

      digitalWrite(GAIN0, HIGH);
      digitalWrite(GAIN1, HIGH);
      digitalWrite(SCLKPIN, LOW);
      digitalWrite(A0, LOW);
      digitalWrite(TEMP, LOW);
      digitalWrite(SPEED, HIGH);//0-->  10SPS ,1-->80SPS
      digitalWrite(PDWN, HIGH);  //0-->  POWERDOWN(SLEEPING -NO CONVERSION) ,1-->WORKING MODE

      reset_adc();

      SPI.begin();
      SPI.setBitOrder(MSBFIRST);
      SPI.setDataMode(SPI_MODE1);

      digitalWrite(SCLKPIN,LOW);

    }

    void loop() {
      // put your main code here, to run repeatedly:
      if (digitalRead(MISOPIN)== LOW) read_adc();

      delay(1000);

    }

    void reset_adc()  {
      digitalWrite(SCLKPIN,HIGH);
      delayMicroseconds(1400);

    }

    void read_adc()  {
      drdy_wait();
      uint8_t i;
      finaladc = SPI.transfer(0xff);
      finaladc |= (uint32_t)SPI.transfer(0xff) << 8;
      finaladc |= (uint32_t)SPI.transfer(0xff) << 16;
      Serial.print ("ADC_value:  ");
      Serial.println(finaladc,DEC);
      Serial.println();

    }

    void drdy_wait()
    {
      delayMicroseconds(30);
    }

Has anyone worked with this? Can you help me?  Thank you

body:
I fished out some code I wrote a while back while evaluating the 1232.  SPI is a headache because of the need toggle the clock signal to prevent the last data bit from 'sticking', which will botch repeated reads when the last data bit is high.

If you are absolutely required to use SPI stop reading this answer.

Everything you need to know is on pages 18 and 19 of the [ADS1232 datasheet](http://www.ti.com/lit/ds/symlink/ads1232.pdf).  Note this is strictly demo material, for example it doesn't take into account settle time when switching channels.

    int32_t read_adc(const uint16_t wait_millis) {
       int32_t data = 0;
       // reset ADC
       digitalWrite(ADS1232_PDWN, LOW);
       delayMicroseconds(10);
       digitalWrite(ADS1232_PDWN, HIGH);
       delayMicroseconds(10);

       for (; data < wait_millis && digitalRead(ADS1232_DRDY_DOUT) != LOW;
            delay(1),
            data++);

     if (data == wait_millis) {
      // timeout
      return -1;
     }

       // read in 24 bits, see Page 19 of the datasheet

       data = 0;
       for (uint8_t i = 0; i < 24; i++) {
      digitalWrite(ADS1232_CLK, HIGH); // clock out next data bit
      data <<= 1;
      data |= digitalRead(ADS1232_DRDY_DOUT);
      digitalWrite(ADS1232_CLK, LOW);
     }
     // adjust for sign. See page 18 of datasheet
     if (data & 0x00800000)
      data |= 0xFF000000;
     // avoid having DRDY/DOUT remain in the state of the last bit
     // see page 19 of datasheet
     digitalWrite(ADS1232_CLK, HIGH);
     delayMicroseconds(10);
     digitalWrite(ADS1232_CLK, LOW);

     return data;
    }


message:
Mini ethernet shield pins don't have SI

Please somebody who had the same issue help me.
The question is how to connect this Mini Ethernet shield to an Arduino.
The main problem is the pins that my shield have or haven't; my current connections to the Arduino Mega 2560 are:

1. 5v to 5v
2. GND to GND
3. LNT to NULL
4. CLK to NULL
5. SO  to pin50
6. WOL to NULL
7. SLK to PIN52
8. ST  to ????
9. RST to RST
10. CS to PIN53
11. Q3 to NULL
12. GND to NULL

But in all cases when I search the connection diagram every picture has SI, but I don't have it (I tried to connect ST to PIN51 without luck).

What kind of Ethernet shield is that? Or how to connect those pins?

 I hope someone can help me; thank you in advance.

    /*
      DHCP-based IP printer

      This sketch uses the DHCP extensions to the Ethernet library
      to get an IP address via DHCP and print the address obtained.
      using an Arduino Wiznet Ethernet shield.

      Circuit:
       Ethernet shield attached to pins 10, 11, 12, 13

      created 12 April 2011
      modified 9 Apr 2012
      by Tom Igoe
      modified 02 Sept 2015
      by Arturo Guadalupi

     */

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address for your controller below.
    // Newer Ethernet shields have a MAC address printed on a sticker on the shield
    byte mac[] = {
      0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
    };

    void setup() {
      // You can use Ethernet.init(pin) to configure the CS pin
       // Ethernet.init(53);  // Most Arduino shields
      //Ethernet.init(5);   // MKR ETH shield
      //Ethernet.init(0);   // Teensy 2.0
      //Ethernet.init(20);  // Teensy++ 2.0
      //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
      //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // start the Ethernet connection:
      Serial.println("Initialize Ethernet with DHCP:");
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        if (Ethernet.hardwareStatus() == EthernetNoHardware) {
          Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
        } else if (Ethernet.linkStatus() == LinkOFF) {
          Serial.println("Ethernet cable is not connected.");
        }
        // no point in carrying on, so do nothing forevermore:
        while (true) {
          delay(1);
        }
      }
      // print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      switch (Ethernet.maintain()) {
        case 1:
          //renewed fail
          Serial.println("Error: renewed fail");
          break;

        case 2:
          //renewed success
          Serial.println("Renewed success");
          //print your local IP address:
          Serial.print("My IP address: ");
          Serial.println(Ethernet.localIP());
          break;

        case 3:
          //rebind fail
          Serial.println("Error: rebind fail");
          break;

        case 4:
          //rebind success
          Serial.println("Rebind success");
          //print your local IP address:
          Serial.print("My IP address: ");
          Serial.println(Ethernet.localIP());
          break;

        default:
          //nothing happened
          break;
      }
    }
And result is :

 - 16:41:14.242 -> Initialize Ethernet with DHCP:
 - 16:41:14.804 ->    Failed to configure Ethernet using DHCP
 - 16:41:14.848 -> Ethernet    shield was not found.  Sorry, can't run
   without hardware. :(

body:
The "Mini Ethernet Shield" uses ENC26j60 chip. The Arduino Ethernet library is for Wiznet W5100/W5200/W5500 chips. You can't use it with ENC26j80.

With Arduino Mega I would recommend to use the UIPthernet library for ENC26j80. Other option is the EtherCard library.

The UIPEthernet library has the same API as the the Arduino Ethernet library.


message:
Servo delay problems

So I had a test last week with the Arduino Uno starter kit. We got a task including the servo. I had to get the servo to go from 0 to 90 degrees and it was supposed to use 4 seconds to do so. Than back from 90 degrees to 0 again. My code is like this:

    #include <Servo.h>

    Servo myservo;
    int pos = 0;
    void setup() {
      myservo.attach(9);
    }
    void loop() {
      for (pos = 0; pos <= 90; pos += 1) {
        myservo.write(pos);
        delay(40);
      }
      for (pos = 90; pos >= 0; pos -= 1) {
        delay(13);
      }
    }

As you see the delay should be just 40 and 13 milliseconds, but it used 4 seconds and 1.3 seconds. but since the code was, wrong I didn't pass on this task. So what have I done wrong.

body:
I would use the `millis()` function to set up a timing as accurate as possible.

Before starting your operations store the actual value of the `millis()` timer to a variable `time_passed`. After finishing your operation, in this case a 1° step of the Motor, wait until the 90's part of your desired time (4s) is reached. Then you increase your time_passed with the 90's part of your desired time bevor going on.

    #include <Servo.h>

    unsigned long time_passed;
    unsigned long timestep = 4000 / 90; // necessary period to reach 4s in 90 steps
    Servo myservo;
    int pos = 0;

    void setup() {
      myservo.attach(9);
    }
    void loop() {
      time_passed = millis();
      for (pos = 0; pos <= 90; pos += 1) {
        myservo.write(pos);
        while ( millis() - time_passed < timestep) {
        }
        time_passed = time_passed + timestep; // this was time_passed = millis(); at testing, but this should be even more accurate. Hope I made no mistake, since I tested only the previous Version ;-)

      }

      for (pos = 90; pos >= 0; pos -= 1) {
        myservo.write(pos);
        while ( millis() - time_passed < timestep) {
        }
        time_passed = time_passed + timestep; // this was time_passed = millis(); at testing, but this should be even more accurate. Hope I made no mistake, since I tested only the previous Version ;-)
      }
    }


message:
Why shouldn't you connect more than one motor directly to either the 5V or 3.3V pins/rails of an Arduino?

What would go wrong otherwise?

body:
On an Uno, the barrel jack feeds a reverse polarity diode that can support 1A max, which then feeds a 5V regulator rated for 800mA max (800mA cannot be reached due to lack of cooling - but it does pretty well if barrel jack voltage is kept to 7.5V) which then feeds a 3.3V regulator rated for 150mA.

With too high a voltage or too much current, the 5V regulator either goes into thermal shutdown, or often just severely overheats and fails (sometimes spectacularly).

The 5V can also come from the USB source, which has 500mA PTC resettable fuse, so even less current is available.

So power your motor from another source, and use the Arduino output pins to control a transistor to turn the motor on and off.


message:
How can write a single data into spiffs?

typedef struct book {
    char title[20];
     char author[20];
     int pages[10];

    } Book;

    Book b1 = {"The Zahir","Paulo Coelho",336,0};

while writing this structure into SPIFFS of ESP8266, I am using function

    filename.write( (const uint8_t*)&b1, sizeof(b1));

but how can write a single data like name of book into structure of spiffs?

body:
For this kind of situation it's best to treat your data as records in a database. To change one part of a record you read the entire record, change the value, then write that record back.

    int record = 4; // which record you want to change

    struct book b; // Temporary storage for editing the data

    // Go to the record and read it in
    filename.seek(record * sizeof(struct book));
    filename.read( (const uint8_t*)&b, sizeof(struct book));

    // Change the data
    strcpy(b.title, "Winnie The Pooh");

    // Go to the record again and write it out
    filename.seek(record * sizeof(struct book));
    filename.write( (const uint8_t*)&b, sizeof(struct book));


message:
Wire.h missing - Failing to upload I2C 16x2 LCD sketch

I am total newbie in Arduino and for the last 3 days I am trying to figure this out.

I would like to use an I2C display for a project. I have installed the LiquidCrystal_I2C, but when I try to upload it I get this `wire.h` missing message.

Could anyone please help me to understand and fix this?

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/W64XN.png

body:
That library is special. It expects to be placed in the same location as the Wire library.  You need to find the location of the Wire library and place this library alongside it.  So you have:

    .../Wire/Wire.cpp
    .../Wire/Wire.h
    .../LiquidCrystal_I2C/LiquidCrystal_I2C.cpp
    .../LiquidCrystal_I2C/LiquidCrystal_I2C.h

etc


message:
NodeMCU with HC-SR04 ultrasonic sensor

How can I interface an ultrasonic sensor with a MCU with 3.3 V GPIO like the NodeMCU? I tried powering the sensor with both 5 V and 3.3 V from the MCU. Both failed to show any results as the distance appeared to be 0 V. In both cases the trig pin of the sensor was given 3.3 V input from the GPIO pin. I assume I need to level shift the echo pin output from 5 V to 3.3 V. How can I do that? Or is something else the issue? The code I used is fine as it works with Arduino.

body: The datasheet I found says the logic is TTL, which as far as I know is 2 V - Vcc, so 3.3 V should be fine. Is Trig just constantly given 3.3 V? According to the datasheet, it needs a 10 us pulse. Perhaps that is your issue? Code or schematics could help if that isn't it.


message:
GPS module Ublox Neo 6M issue

I using the above mentioned GPS module with Arduino UNO. I find that I cannot receive the Latitude and Longitude values in the `$GPRMC` string in the NMEA data, as I used the module inside a concrete building. I got the values when I placed the module just outside the window. But I have noticed that the phones we use can get the location data just fine through their in-built GPS after waiting for just some time. How is this possible? Any way I can achieve this using the Ublox Neo 6M module?

body:
Mobile phones use the mechanism of [assisted GPS][1].

In contrast to your Arduino U-Blox module it uses the cell tower data your phone can provide to determine your location. This is especially helpful to get a quicker first fix and to get a fix even when you have poor satellite signal conditions.

That said, this will not be possible using only your GPS module connected to your Arduino.

  [1]: https://en.wikipedia.org/wiki/Assisted_GPS?wprov=sfla1


message:
WiFi connection times out if credentials retrieved via serial terminal

I've implemented a small WiFi connection procedure into my ESP32 project.
The available networks get printed with index, then I'm entering the index and retrieve the network name from it. The password is entered via serial in clear text.

Before connecting, I'm printing the credentials and thus could confirm they are read into `const char *` strings properly.

Unfortunately when using this procedure the connection to my AP times out. I've also tried to override the strings with hardcoded values and then the connection works as expected.

 while (!Serial.available()) {
  // (timeout is implemented here)
 }
 String index_s = Serial.readStringUntil('\n');
 long index = index_s.toInt();

 // { same while as above }
 String passw = Serial.readStringUntil('\n');

 const char *ssid = WiFi.SSID(index).c_str();
 const char *pass = passw.c_str();

 // with this it works:
 // ssid = "my_network";
 // pass = "my_password";

 Serial.printf("connecting to %s using %s", ssid, pass);
 WiFi.begin(ssid, pass);

body:
The answer was quite simple but of the kind you need some time get find out. The issue was a hiding carriage return.

    passw.trim();

Did the trick. `String.trim()` removes the `\r` and thus the password gets accepted.


message:
VNH2SP30 Motor Driver not working in reverse

I bought 2 new VNH2SP30 Motor Drivers because i thought the first one was broken but they are both giving me the same issue, they run in forward direction but not reverse...

When the motor is unplugged the forward led is bright green, when the code executes the reverse direction, the reverse led is lit very dimly and multi meter measures no voltage.

I have tried:

 - changing power source and voltage

 - using different cables and pins

 - using different motors

 - using different code

 - using different VNH2SP30 Motor Driver

 - using different arduino

here is the code:

      #define INA 5 // outputs arduino
     #define INB 7
     #define EN 8
     #define PWM 11

     int motorSpeed = 255 ;  // motor speed

     void setup ( ) {
      pinMode ( INA , OUTPUT ) ;
      pinMode ( INB , OUTPUT ) ;
      pinMode ( EN , OUTPUT ) ;

      digitalWrite ( EN , HIGH ) ;
     }

     void loop ( )
     {
      digitalWrite ( INA , LOW ) ;  // turn the motor in one direction
      digitalWrite ( INB , HIGH ) ;
      analogWrite ( PWM , motorSpeed ) ;
      delay ( 1000 ) ;

      digitalWrite ( INA , HIGH ) ;  // turn the engine in the opposite direction
      digitalWrite ( INB , LOW ) ;
      analogWrite ( PWM , motorSpeed ) ;
      delay ( 1000 ) ;

      digitalWrite ( EN , LOW ) ;  // turn off
      delay ( 1000 ) ;
      digitalWrite ( EN , HIGH ) ;

     }

Heres the wire diagram but my outputs are just on different pins.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/aK4wL.png

body:
There appears to be quite a few faulty drivers such as this one currently on Aliexpress. Of the 4 I have bought, only one works - the other three function exactly as you described.
Same program, same motor, same control wiring as the one which works.
I can only suggest try to buy from a different seller on ebay or ali; or of course pay top dollar for a chip from a reputable source.


message:
Is it possible to connect many (20+) SPI sensors to an Arduino Mega?

I am making a system for measuring whether or not there is vacuum present in big steel containers. They are located up to 100 meters from the control cabinet.

The question is, *how many SPI sensors can I successfully use at the same time with an Arduino Mega?*

I have two main concerns, and there are probably more things I didn't think about.

**Signal strength**
The shared lines for CLK, MOSI and MISO will need to be split up at several junction boxes and led to the different sensors. Since the voltage out from the Arduino is fixed, I'm fearing instability because the signal is weaker for some sensors, has someone done something similar? What is the greatest acceptable voltage loss for these lines to an ordinary sensor?

**Processing**
Will the SPI library be fine coping with this many sensors?

The refresh rate can be set to extremely low, thinking 0.3Hz.

The alternative to all this is to go for 4-20mA sensors and have a 0-5V converter circuit for each sensor, near the controller.

Any inputs would be greatly appreciated!

body:
You can control as many SPI devices as you can set the CS line for. You can even control all the CS lines from a SPI device. A SIPO register will help a lot there.

However you are probably better off using a proxy board to actually connect to the sensors and then connecting the mega to the proxy to communicate the measurements using a connection that is more robust over long distances.


body:
I would recommend using multiplexer(s) for the task.

[![enter image description here][1]][1]
Originally from [this tutorial][2].

[![enter image description here][3]][3]

Or [this tutorial][4] by Sparkfun

  [1]: https://i.stack.imgur.com/e2vPk.png
  [2]: https://bildr.org/2011/02/cd74hc4067-arduino/
  [3]: https://i.stack.imgur.com/PfAS5.png
  [4]: https://learn.sparkfun.com/tutorials/multiplexer-breakout-hookup-guide/all


body:
You need to drive SCK, MOSI, and 20 chip select lines long distance, and then receive MISO back long distance.

The number 20 for slaves is not a problem.
Long distance and maintaining signal integrity will be a problem.

I would suggest a bussed newtwork and send serial data to/from 20 slaves (like ProMini) and let the slaves do the SPI data gathering and then pass that data back to the Master Mega in a polled fashion: #1 send your data, #1 here it is. #2 send your data, #2 here it is. Etc.
Then you just need to connect up a 3 wire bus  (RS485+, RS485-, Gnd) from device to device to device with termination resistors at the end of the run. Power each device seperately vs running power to all of them.
Maxim has some nice tutorials on connecting up RS485.


message:
Where can I find the source codes for the various classes and methods used in Arduino Primo?

I am new to Arduino development. I am trying to connect a BLE device (Arduino Primo) with my iOS app. From the Arduino BLE examples, I understand how to initialize the BLEperipheral class and then call the setValue method to pass value to be transmitted. However I do not want to be dependent on example codes, rather I want read the source code and definitions to know about the available classes and their methods, what argument types passed etc.(not precompiled libraries with .o extension).

For my current issue, I want to know what type of arguments does the `setValue` take in the BLEperipheral class. Can I pass an int value(4 bytes) or it has to be a char only? These questions can be answered by reading the source code of these inbuilt libraries.

Any direction would not only help me with the current project, it would also help to tackle and understand any projects in the future, where I might use inbuilt library calls.

I have searched the internet, however not much information is available for newcomers like me.
Below is a similar question link but outdated and does not solve what I am looking for.

https://arduino.stackexchange.com/questions/860/how-can-i-get-the-source-files-for-arduino-libraries

Thank you for any suggestions.

body:
The Arduino Primo is supported by Arduino nRF52 boards package. The boards packages can contain libraries special for boards handled by the package. The BLE library for Arduino Primo is included in the board package.

The location of boards packages on Windows is in hidden folder AppData in user's home directory. On my Windows computer it is
```
C:\Users\andrassy\AppData\Local\Arduino15\packages\arduino\hardware\nrf52\1.0.2\libraries\BLE
```

On Linux the 'Arduino 1.5' folder is `.arduino15` in users home folder.


message:
Create a device to detect object and voice alert what kind of object it is

Here is what I want to do (since I'm not a embedded guy)

- create a prototype with an Arduino to detect objects using camera(object classification?)
- that prototype will detect objects and alert that object's name

My questions are....

- Is it possible? :)
- What things should I use to create a prototype?
- What camera should I use?
- Is it related to image processing?
- Connection between object detection and voice alert?

body:
The Arduino is not the ideal platform for you since it is more "lightweight" and can't really meet the demand that your application is expecting.

A platform like for example Raspberry Pi that has a full-blown operating system and a lot of tools that fulfils your application needs.


message:
Mapping segments and memory allocation on a segment LCD driver

I've just configured a segment LCD and driver, everything works fine, but because I decided to not use vias on the PCB, the connections between the two are mixed.

To be more precise, in order to display the number 12, both memory addresses should be accessed.

So right now it's impossible to display a single digit without mapping all the segments.

In static mode, this is how RAM memory is allocated to SEG0-SEG7 and SEG8-SEG15 respectively:
[![backplane mapping][1]][1]

  [1]: https://i.stack.imgur.com/aQki5.png

What I've tried was to create two multidimensional arrays and map possible combinations of the two digits, like this:

```
// 01 to 09
const byte map1[10][2] = {
  {B01110111, B111111 },
  {B01110001, B100111},
  {B01111011, B011111},
  {B01111011, B110111},
  {B01111101, B100111},
  {B01111110, B110111},
  {B01111110, B111111},
  {B01110011, B100111},
  {B01111111, B111111},
  {B01111111, B110111}
};

// 10 to 19
const byte map2[10][2] {
  {B00010111, B111100},
  {B00010001, B100100},
  {B00011011, B011100},
  {B00011011, B110100},
  {B00011101, B100100},
  {B00011110, B110100},
  {B00011110, B111100},
  {B00010011, B100100},
  {B00011111, B111100},
  {B00011111, B110100}
};
```

If there is no way to mix or map them in a dynamic way so any possible combination between 00 and 99 can be achieved, the only solution is to add vias on the PCB and rewire everything as explained in the datasheet.

Any ideas?

Thanks

body:
The trick here is to employ both a local memory buffer, and digit masking.

Step one: create a pair of *masks* that define which bits of the memory are associated with which digit.

Imagine you have your digits wired in this order in memory. For simplicity I am working with 16-bit values, but there is no reason why you can't split them into two 8 bit values each if you find that easier (P is the decimal point. Lower case is the left digit, upper case the right digit):

          MSB                         LSB
          a C d g E B p A c D f b e G F P

You would then create a pair of corresponding 16-bit values that represent which bits are associated with each digit.

          MSB                         LSB
          a C d g E B p A c D f b e G F P
    Left  1 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0
    Right 0 1 0 0 1 1 0 1 0 1 0 0 0 1 1 1

The right is just the inverse of the left, so for `right` you can actually use `~left` and save yourself 2 bytes.

So that would end up as:

    uint16_t leftDigit = 0xB2B8;
    uint16_t rightDigit = 0x4D47;

Now you create yourself a table of which segments create which numbers. Now the magic here is that you don't want individual digits. Not yet. What you want is a table of 16-bit values that represent the numbers 00, 11, 22, 33, 44, 55, 66, 77, 88, 99 (and optionally two spaces, but that's just 0x0000, so you may not need to store that explicitly).

You may end up with something like:

    uint16_t digits[] = {
        0b1110110111111010, // 00
        0b0100010010010000, // 11
        0b1011110101011100, // 22
        // ... etc ...
    };

Now the real magic happens.

You need a memory buffer that mirrors the contents of your driver memory.  You don't directly modify the driver memory - you modify your memory buffer, and then send both bytes of it to the display driver at once, updating all the segments together.

    uint16_t buffer = 0;

Now to set a digit you first need to erase whatever is in the bits that correspond to the digit you want.  Let's say we want to display the number 12.  We'll start with the left digit.

    // Step one, erase the left digit
    buffer &= ~leftDigit;
    // Step two, place into it the bits for 1 with the left digit mask imposed:
    buffer |= (digits[1] & leftDigit);

    // Step three, erase the right digit
    buffer &= ~rightDigit;
    // Step four, place into it the bits for 1 with the left digit mask imposed:
    buffer |= (digits[2] & leftDigit);

That is actually quite a long winded way. But it does allow you to just change one digit without affecting the other.  If you want to just replace the entire content of the display (both digits at once) then you don't need as much work:

    buffer = (digits[1] & leftDigit) | (digits[2] & rightDigit);

I'll just dismantle that for you so you can see what it does.

                MSB                         LSB
                a C d g E B p A c D f b e G F P
     digits[1]: 0 1 0 0 0 1 0 0 1 0 0 1 0 0 0 0
     leftDigit: 1 0 1 1 0 0 1 0 1 0 1 1 1 0 0 0
           AND: 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 // b and c enabled

     digits[2]: 1 0 1 1 1 1 0 1 0 1 0 1 1 1 0 0
    rightDigit: 0 1 0 0 1 1 0 1 0 1 0 0 0 1 1 1
           AND: 0 0 0 0 1 1 0 1 0 1 0 0 0 1 0 0 // A B D E and G enabled

    OR of ANDS: 0 0 0 0 1 1 0 1 1 1 0 1 0 1 0 0 // b c A B D E G enabled

And map those segments on to the standard layout of a 7 segment display:

[![enter image description here][1]][1]

And you form the number 12.

Then you take the buffer value and write it out to your display memory.  You can split the 16 bit value into 8 bit values with bit masking (`& 0xFF`) and bit shifting (`>> 8`).

    uint8_t b1 = buffer & 0xFF; // Lower byte of memory
    uint8_t b2 = (buffer >> 8) & 0xFF; // Upper byte of memory

  [1]: https://i.stack.imgur.com/aqWit.png


message:
How to Compile Different Sketches in Different Visual Studio Code Workspaces

I'm using **Visual Studio Code** with the Arduino extension. I have two workspaces each with a different sketch file loaded - Sketch_1 and Sketch_2. Sketch_1 will verify and upload properly. When I click on the Verify to compile or Upload buttons for Sketch_2 in its workspace, VS Code verifies and uploads Sketch_1, not Sketch_2. Am I doing something wrong, or is it not possible to separately Verify and Upload different sketches in different workspaces?

body:
The first time you verify your sketch you are confronted with a list of available sketches (INO's). As soon as you select one of these it gets stored under `"sketch"` in `.vscode/arduino.json`.
If you zero this, `""`, you'll once again be asked which sketch to set as "main sketch".

This "device context" is stored per workspace so you might consider narrowing your scope when opening a folder. I know this is no fun when exploring, and the will to switch and try different examples is big, but currently there are nothing that facilitates a smoother alternative.


message:
L1 is not declared in this scope error

I have a project where I have to control a DC motor.
In this code the purpose is that every time you press a button the direction of the motor changes.

I only get the error that L1 (and L2,R1 and R2) are not declared in this scope. the place in the loop.
How do I define the variables so that the code works?

    int Motorforward = 10;   // MotorDirectionPin set to pin10
    int Motorbackward = 11;   // MotorDirectionPin set to pin11
    const int button1Pin = 2; //button control set to pin 2

    int state = L1;
    int state = L2;
    int state = R1;
    int state = R2;

    int button1State;  // current reading from the input pin
    int previous = LOW; //the previous reading from the input pin

    char input;

    void setup(){
    pinMode(button1Pin, INPUT); //set pin as input
    Serial.begin(9600);

    pinMode(Motorforward, OUTPUT); // sets the pin as output
    pinMode(Motorbackward, OUTPUT);
     }

      void loop(){
    button1State = digitalRead(button1Pin);
    input = button1State;

    switch(state){
      case L1:
        if (state == L1){
        if (button1State == HIGH){
            state == L2;
        }
      }
      break;

    case L2:
      if (state == L2){
        if (button1State == LOW){
          state == R1;
        }
      }
      break;

    case R1:
      if (state == R1){
        if (button1State == HIGH){
          state == R2;
        }
       }
      break;

    case R2:
      if (state == R2){
        if (button1State == LOW){
          state == L1;
        }
      }
      break;
    }

body:
I have the feeling you need only one state which can have 4 values: L1, L2, R1 or R2.

For this, use an enum:

    enum EState { L1, L2, R1, R2 };

Now create one state variable of that type and give it an initial value.

    EState state = L1;

Some other problems I see at first sight:

    case L1:
      if (state == L1){
      if (button1State == HIGH){
          state == L2;
      }
    }
    break;

In this statement, when there is `case L1`, it means the code following ( until the break) is only handled when the state (because of `switch(state)` is L1, so you can remove the check `if (state == L1)`. What is left is:

    case L1:
      if (button1State == HIGH)
      {
        state == L2;
      }
      break;

Than you use `state == L2` to set a new state. However, the `==` only compares two values, if you want to assign it, you have to use a single `=`, thus the code should be:

    case L1:
      if (button1State == HIGH)
      {
        state = L2;
      }
      break;

Of course you have to do this also for the other case statements.

Tip: align your code (make the { and } aligned under each other; this will make your code readability much better.


body:
You have not defined L1, L2, R1, or R2.  You're also redefining the int variable 'state' four times.

Try replacing:

    int state = L1;
    int state = L2;
    int state = R1;
    int state = R2;

With something like:

    #define L1  1
    #define L2  2
    #define R1  3
    #define R2  4
    int state = R2;


message:
NeoICSerial and SPI on the Uno - pin 10

The [NeoICSerial](https://github.com/SlashDevin/NeoICSerial) documentation contains a table that states for the Uno:

* Transmit: 9
* Receive: 8
* PWM Unusable: 10

Pin 8 and 9 are used for the serial connection. Pin 10 is part of the pins for the SPI on the Uno. Does this mean SPI connections can't be used together with NeoICSerial or is this specific for using pin 10 for PWM?

body:
The "Unusable 10" is explained in AltSoftSerial library

> The "Unusable PWM" pins can be used normally, with digitalRead() or
> digitalWrite(), but their PWM function controlled by analogWrite()
> will not work properly, because AltSoftSerial uses the timer which
> controls that pin's PWM feature.

----------

Pin 10 on Uno is SPI slave select if the Uno is SPI slave (then it is an INPUT).

If the Uno is SPI master, this pin must be set as OUTPUT. For this reason it is usual to use pin 10 as slave select for the (first) SPI slave. SPI shields have this pin hardwired as slave select for the (first) SPI device on the shield.


message:
please explain the sketch attached

Sorry about a newbie.
1. what mening of:

        if(Xstr[XstrLength-1] != '|'){
    Xstr[XstrLength] = '|';
    Xstr[XstrLength+1] = '\0';

2. the setup: `char Xstr[60];` what means? and then: `itoa(Yint,Ystr,10);`

Code:

    #include <VirtualWire.h>

    //gamepad setup
    int up_button = 2;
    int down_button = 4;
    int left_button = 5;
    int right_button = 3;
    int start_button = 6;
    int select_button = 7;
    int joystick_button = 8;
    int joystick_axis_x = A0;
    int joystick_axis_y = A1;
    int buttons[] = {up_button, down_button, left_button, right_button, start_button, select_button, joystick_button};

    void setup()
    {

     //gamepad setup
     for (int i; i < 7; i++)
     {
      pinMode(buttons[i], INPUT);
      digitalWrite(buttons[i], HIGH);
     }

     Serial.begin( 9600 );

     //transmitter setup
     vw_set_tx_pin(12);          // Sets pin D12 as the TX pin
     vw_set_ptt_inverted(true);  // Required for DR3100
     vw_setup(2000);             // Bits per sec
    }

    int counter = 0;

    int Xint;
    int Yint;

    char Xstr[60];
    char Ystr[60];

    void loop()
    {
     // Read and store Sensor  data
     Xint = analogRead(joystick_axis_x);
     Yint = analogRead(joystick_axis_y);

     // Convert integer data to Char array directly
     itoa(Yint,Ystr,10);
     itoa(Xint,Xstr,10);

     int XstrLength = String(Xstr).length();

     if(Xstr[XstrLength-1] != '|'){
      Xstr[XstrLength] = '|';
      Xstr[XstrLength+1] = '\0';
     }

     char combinedArray[String(Xstr).length() + String(Ystr).length() + 1];
     sprintf(combinedArray, "%s%s", Xstr, Ystr);

     vw_send((uint8_t *)combinedArray, strlen(combinedArray));
     vw_wait_tx(); // Wait until the whole message is gone

     Serial.println(combinedArray);

    }

body:
1. This adds some end of string characters.

     if(Xstr[XstrLength-1] != '|'){
        Xstr[XstrLength] = '|';
        Xstr[XstrLength+1] = '\0'

First it checks if Xstr last character is a '|', if not:
   Place a | directly after the last character
   And append a '\0', which is a symbol to 'end' a string

A string in C/C++ is normally build up like this, e.g. "Hello" contains of the bytes:

    'H', 'e', 'l', 'l', 'o', \0

Where each of the above are ASCII characters/values and the last \0 a 0 byte.

2. `char Xstr[60];` defines a character array (string) that can contain 60 characters. Note however, that the ending \0 also needs to be in this string, so you can actually only put 59 characters inside.

3. `itoa(Yint,Ystr,10);` converts Yint which is an integer value to a string (where each digit has each own byte), and 10 is the length.


message:
What is the best way to connect multiple Arduinos?

In my situation, I have a map divided into multiple parts, each part could have about 20 to 100 Arduinos that they should send information from time to time to the master. How could I do this?

Second problem. How could I use the other Arduinos to send the info from Arduino that are so far from the Master?

Example in part 1: Arduino X is 500 meters far away from the master. How could use the other to send the information?

Can I do this with NodeMcu or such equipment with built-in WiFi?

body:
You could use low radio frequency modules to get to the 500m. For example there are the so called xbee modules (XBee Pro 60mW PCB Antenna - Series 1). You can find cheaper ones, but from my experience they are a bit harder to understand and not reliable.

You can make a TCP-like connection, where before data is send, the "slave" asks the "master" whether he can catch data or not. If not, he'll just keep asking after a delay has passed till he gets through. Even though TCP is mostly used in WiFi 2.4G, you could still apply it to your project

If you want to use WiFi than you can make a connection between the "slave" and "master" by having some middle man chips in between that pass on the data, but you would need the middle man chips to be constantly powered on (or use a RTC to time the "wake time").


body:
I think you should start with using Wifi modules and you use an esp-01 too instead of NodeMCU. Once you are familiar with esp-01's, you will find them as good as NodeMCU. Esp-01's only lack multiple pins when compared to NodeMCU.

And for communication between arduino and esp-01, use serial ports- 0 and 1.

Here is example code-
For Master Arduino

    int temp;
    int hum;

    void setup(){
     Serial.begin(115200);
     delay(2000);
    }
    void loop() {

     temp = random(0,100);
     hum = random(100,200);
     Serial.print(temp);
     Serial.println('t');
     delay(2000);
     Serial.print(hum);
     Serial.println('h');
     delay(2000);
     Serial.flush();
    }

For Slave Esp or any other slave arduino -

    String inString = "";    // string to hold input

    float temp = 0,hum = 0;

    boolean newtemp=false, newhum=false;

    void setup() {
      Serial.begin(115200);
      Serial.println("ESP 8266 - 01 Module is ready to receive codes from Master Arduino");
     }

    void loop() {
      // Read serial input:
      while (Serial.available() > 0) {
        int inChar = Serial.read();

        if (inChar != '\n') {

          if (inChar == 't')
          newtemp = true;

          if (inChar == 'h')
          newhum = true;

          inString += (char)inChar;
        }
        else {
          Serial.print("Input string: ");
          Serial.println(inString);
          if ( newtemp == true ) {
          temp = inString.toFloat();
          Serial.print("Received Temperature:");
          Serial.println(temp);
          newtemp = false;
          }
          if ( newhum == true ) {
          hum = inString.toFloat();
          Serial.print("Received Humidity:");
          Serial.println(hum);
          newhum = false;
          }
          inString = "";
        }
      }
    }

Pin connections -

Master Arduino TX -- Slave board RX


body:
This is a classical application for `LoRa` technology, not WiFi.  Designing a `LoRa` mesh is no simple task, though.

Check [this post][1], or [this other post][2]

  [1]: https://nootropicdesign.com/projectlab/2018/10/20/lora-mesh-networking/
  [2]: https://forum.arduino.cc/index.php?topic=515565.0


message:
Reading Multiple RFID tags / Reading and ignoring/holding the tag

I'm currently doing a project where ideally I will have multiple objects with RFID tags on them that are placed on top of a Adafruit PN532 RFID Shield connected to a Arduino Uno Wifi Rev 2. The idea is that once a button is pressed the RFID reader will read a Mifare tag then "ignore" it then reads the next tag until all are read. How can I acheive this?

I have read some about Anti-collision protocols and the limitations of RFID but was also wondering if it might be possible to read a tag then hold or ignore that tag until it leaves the range of the RFID shield?

I've also read a user on the Adafruit forums had some luck by altering the library that is used, I'll link it for reference, but I've tried the same method but had no luck myself. [Adafruit-PN532 Library][1]

I'm new to Arduino so I apologise if I've messed anything out.

Thanks for any help!

  [1]: https://github.com/adafruit/Adafruit-PN532/

body: You probably want to use UHF RFID for this.  The Adafruit PN532 is only capable of reading max 2 tags at a time in an alternating fashion.  This is confirmed by the board's designer in the Adafruit forums.


message:
Blinking 2 LED having input from serial monitor

Sir while entering the values on the serial monitor, I ask the user to enter the value for red led voltage(0-255) then again ask for yellow at the red voltage asking it produces the user to  put the value, after that it asks for yellow led input but the time to enter the value for yellow led input is very less and so it does not get entered and the futher program starts. So only red led works where as Yellow does not.

    int REDledpin=9;        //RED led on pin 9 of the uno board.
    int YELledpin=7;        //YELLOW led on pin 8 of the uno board.
    int REDonleddelay=500;  //The red led will be on for 500 ms.
    int REDoffleddelay=500; //The red led will be off for 500 ms.
    int YELonleddelay=600;  //The YELLOW led will be on for 600 ms.
    int YELoffleddelay=600; //The YELLOW led will be off for 600 ms.
    int countredled=5;        //The RED LED count variable
    int countyellowled=5;     //The YELLOW LED count variable
    String red="Red led is blinking";
    String Yellow="Yellow led is blinking";
    int redintensity;
    int yellowintensity;

    void setup() {
      Serial.begin(9600);
      pinMode(REDledpin,OUTPUT);
      pinMode(YELledpin,OUTPUT);

      Serial.println("How much voltage you want to apply to the red LED (0-255)?");
      while(Serial.available()==0){}
      redintensity= Serial.parseInt();

      Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
      while(Serial.available()==0){}
      yellowintensity = Serial.parseInt();

    }

    void loop() {
    Serial.println(red);
    for(int j=1;j<=countredled;j=j+1)
      {
        Serial.print("The red LED blink star: ");
        Serial.println(j);
        analogWrite(REDledpin,redintensity);
        delay(REDonleddelay);
        analogWrite(REDledpin,0);
        delay(REDonleddelay);
      }

    Serial.println(" ");
    Serial.println(Yellow);
      for(int j=1;j<=countyellowled;j=j+1)
      {
       Serial.print("The yellow LED blink stars");
       Serial.println(j);
       digitalWrite(YELledpin,yellowintensity);
       delay(YELonleddelay);
       digitalWrite(YELledpin,0);
       delay(YELoffleddelay);
      }
     Serial.println(" ");
    }

body:
@Juraj was on the right track however the end-of-line characters for example may not be buffered and the problem could continue.

The correct approach is the wait for the end-of-line character specifically.  Let's take the easy way out and use Serial.readStringUntil

    #define EOL_CHAR '\n'

    void setup() {
      Serial.begin(9600);
      pinMode(REDledpin,OUTPUT);
      pinMode(YELledpin,OUTPUT);

      Serial.println("How much voltage you want to apply to the red LED (0-255)?");
      while(Serial.available()==0){}
      redintensity= Serial.parseInt();

      Serial.readStringUntil(EOL_CHAR); // clear serial buffer to end of line character

      Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
      while(Serial.available()==0){}
      yellowintensity = Serial.parseInt();

    }

This all depends on what you're Serial Monitor is sending as a new line; it could be CR (\r), LF (\n) or CRLF (\r\n), so change the EOL_CHAR value accordingly depending on your serial monitor setup.


message:
Attach() resets servo's angle

I'm working on code that will control micro servo. I use generic servo and built-in library for controling servo. Microcontroller is generic STM32.
Controlling servo Works as expected. But I don't want next behavior - `attach()` function sets servo to 180°(maybe 0°, not sure).
In my project I want next:

 - Servo stays at angle before going off/reboot
 - Servo goes to 90° after turning on/reboot

I googled about this problem and tried with `write(90);` before `attach()` in `setup()` function. Servo goes to 90° but after like 50ms `attach()` stops `write(90)` function and it goes back to 180°. So this didn't solve my problem.
Next I've open `Servo.cpp` and found that `attach()` function contains next code:

        bool Servo::attach(uint8 pin,
                       uint16 minPW,
                       uint16 maxPW,
                       int16 minAngle,
                       int16 maxAngle) {
        timer_dev *tdev = PIN_MAP[pin].timer_device;

        if (tdev == NULL) {
            // don't reset any fields or ASSERT(0), to keep driving any
            // previously attach()ed servo.
            return false;
        }

        if (this->attached()) {
            this->detach();
        }

        this->pin = pin;
        this->minPW = minPW;
        this->maxPW = maxPW;
        this->minAngle = minAngle;
        this->maxAngle = maxAngle;

        pinMode(pin, PWM);

        timer_pause(tdev);
        timer_set_prescaler(tdev, SERVO_PRESCALER - 1); // prescaler is 1-based
        timer_set_reload(tdev, SERVO_OVERFLOW);
        timer_generate_update(tdev);
        timer_resume(tdev);

        return true;
    }

What should I do to fix this problem? Servo will adjust angle of PCB which holds LEDs. PCB will be in case and angle of 90° is default angle. 0°/180° will either destory servo or brake case/PCB/something else.

body:
You can avoid using the `attach();` method by programming without the servo library.

      for(x=0; x<150; x=x+1)
      {
        digitalWrite(Servomotor, HIGH);
        delayMicroseconds(2350); //Change the delay here to change the angle it goes to
        digitalWrite(Servomotor, LOW);
        delayMicroseconds(18550);
      }

This is an example code for how it worked for me. It sends a pulse to the servo which makes it turn a bit until it reaches a "barrier".


message:
MIDI keyboard controlled LED strip

My objective is to light a led on a strip corresponding to a keyboard note.
I have Arduino Uno with MIDI in module hooked up to a serial port. Piano is hooked with a standart midi cable, Led Strip is powered using Arduino's 5v (Figured i don't need more because Max 10 leds will be active at a time).

My setup works but not accurately. All is fine when only 1 note at a time is played, but the denser the music becomes (faster or more notes are played simultaniously) more inaccuracies show - more leds don't turn off or on, or the notes I didn't play light up.

At first i used software serial and there were even more mistakes, when i switched to hardware it became better.
Could it be that Arduino UNO is just not powerfull enough and cannot keep up with incoming midi input or is there another problem?

Here is the code:

    #include <MIDI.h>
    #include <Adafruit_NeoPixel.h>

    MIDI_CREATE_DEFAULT_INSTANCE();

    #define STRIP_PIN 11
    #define STRIP_NUM_PIXELS 88

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(STRIP_NUM_PIXELS, STRIP_PIN, NEO_GRB + NEO_KHZ800);

    void handleNoteOn(byte channel, byte pitch, byte velocity)
    {
      strip.setPixelColor(pitch - 21, strip.Color(50, 50, 50));
      strip.show();
    }

    void handleNoteOff(byte channel, byte pitch, byte velocity)
    {
      strip.setPixelColor(pitch - 21, strip.Color(0, 0, 0));
      strip.show();
    }

    // -----------------------------------------------------------------------------

    void setup()
    {
        MIDI.setHandleNoteOn(handleNoteOn);
        MIDI.setHandleNoteOff(handleNoteOff);
        MIDI.begin(MIDI_CHANNEL_OMNI);
        strip.begin();
    }

    void loop()
    {
        MIDI.read();
    }

body:
The biggest problem is that updating the LEDs is an intensive task.

* Hand-crafted assembly is written to get the timing right
* Interrupts are disabled while the update is running
* 88 LEDs take a (relatively) long time to update.

At about 1.2µS per LED plus 50µS for the reset pulse, you're looking at about 155µS that the Arduino can't be doing anything else at all. That includes receiving anything through serial.  And since you update for every note you receive, if there is a second note coming in with 155µS of that one, it will be missed.

You may get better results with the FastLED library instead of the Adafruit Neopixel library, but ideally you want to work with a board that is fast enough to not need to do such tight bit-banging for the protocol, so that interrupts can still be enabled for receiving data.


message:
What data type are the analog pin labels (A0, A1, etc)?

Arduino Mega

I would like to have an array containing analog pin labels something like...

    int analog_pins[] = {A0, A1, A2, A3};
    int num_analog_pins = sizeof(analog_pins) / sizeof(analog_pins[0]);

Is this possible? It has compiled without any warnings or errors but I'm dont have my board with me (yes beginners mistake) so cant really check if it works.

body:
As you can see in [Arduino.h][1], the analogRead() has `uint8_t` as parameter. You can define them as `byte` or `uint8_t` and you don't have to use the sizeof().

The type of A0 is defined in the file [pins_arduino.h][2]:

    #define PIN_A0 (14)
    static const uint8_t A0 = PIN_A0;

Nevertheless, what you have with integers is 100% okay as well.

When you don't have a Arduino board available, you can use the simulation of an Arduino Uno at [Tinkercad][3].

----------
As @DataFiddler writes below this answer, using a 'const' keyword is preferred:

    const uint8_t analog_pins[] = {A0, A1, A2, A3};

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Arduino.h
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/master/variants/standard/pins_arduino.h
  [3]: https://www.tinkercad.com/


body:
Your calculation will be correct for num_analog_pins, however it's convention to use the *type* of the array like so

    int num_analog_pins = sizeof(analog_pins) / sizeof(int);

As @Jot noted, you'd save much space by declaring your array using uint8_t like so

    uint8_t analog_pins[] = {A0, A1, A2, A3};
    uint8_t num_analog_pins = sizeof(analog_pins) / sizeof(uint8_t);


message:
Esp8266 Vin pin

I've read that Vin pin is directly connected to usb cable in esp8266 (which is 5V). I wonder if I can power a relay 5V and a servo motor Sg90  with this pin? And is there any danger of doing that ?

body:
The GPIO pins on the ESP8266 (including the ones with built-in NodeMCU) are 3.3v tolerant.

First, if there is ever any feedback from the 5v+ from the relay coming back down the signal wire, it'll likely cook the ESP.

Also, if it's a 5v relay, 3.3v from the ESP most likely wouldn't be enough to trigger the unit anyhow.

You'll either need to power the relay from an external power supply (or the Vin pin depending on the mA the relay requires), and then use a voltage converter (eg. logic level converter) so you can have 5v on the relay side (I'm speaking of the signal pin here), and 3.3v on the ESP side, or purchase a relay that will operate on 3.3v.