message:
Powering a water pump with nodemcu

I want to use a nodemcu to water my plants. I connected a pump with a 2N2222 transistor (I know i should add a diode and a pull down on the gate). The pump is DSL370 and when it is off i measure 4.4V on the Vin pin while using a 2A charger connected to the USB port. When the pump is active, the vin voltage drops to 4.1V and the LCD becomes hard to read. I measured the current the pump uses and it is 300mA. What is the reason for the voltage drop? I thought the charger should be able to handle it.

[![A schematic for my plant carrer][1]][1]

  [1]: https://i.stack.imgur.com/sT1uU.jpg

body: Your charger may be able to handle 300mA, but you're pulling that power through your Arduino and that isn't good.  The pump should have a separate power supply, or at least be powered in parallel with the Arduino.  Don't pull power for a motor from the Vin pin unless you just want to destroy the Arduino.


sender: user

message:
Connecting Arduino ethernet shield (ip address - 0.0.0.0)

I need some help to connect my arduino uno R3 and ethernet shield. I don't have a mac address with my shield so I'm using this one: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

The Ethernet controller on the Ethernet shield is W5100 and I don't use SD card.

I have receiver module wich receives data from transmitter and I want to save it in database, but there is issue related to the connection. When I print the Ethernet.localIP i observed only 0.0.0.0.

This is the IP address of my local network - char server[] = "192.168.0.106"

You can find my code below:

      #include <Wire.h> // use Wire library for protocol i2c (A4 = SDA & A5 = SCL)
      #include <VirtualWire.h> // use Virtual library for decode signal from Rx module
      #include <SPI.h>
      #include <Ethernet.h>

      EthernetClient client;
      byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
      char server[] = "192.168.0.106";

      int humidity=0;
      int temp=0;
      int pressure=0;
      char MsgReceived[21];

      void setup()
      {
         Serial.begin(115200);
      Ethernet.begin(mac);

         Serial.println(Ethernet.localIP());

        // Bits per sec
        vw_setup(2000);
        // set pin for connect receiver module
        vw_set_rx_pin(3);
        // Start the receiver PLL running
        vw_rx_start();

      }
      void loop()
      {
      uint8_t buf[VW_MAX_MESSAGE_LEN];
      uint8_t buflen = VW_MAX_MESSAGE_LEN;
      //Taking the data from the control base
      if (vw_get_message(buf, &buflen))
      {
        int i;
        // Message with a good checksum received, dump it.
        for (i = 0; i < buflen; i++)
        {
          // Fill Msg Char array with corresponding
          // chars from buffer.
          MsgReceived[i] = char(buf[i]);
          //Serial.print(MsgReceived[i]);
        }

        sscanf(MsgReceived, "%d,%d,%d",&humidity, &temp,&pressure); // Converts a string to an array
        lcd_display();
        memset( MsgReceived, 0, sizeof(MsgReceived));// This line is for reset the StringReceived

        Serial.print("Temperature = ");
        Serial.print(temp);
        Serial.println(" *C");
        Serial.print("Pressure = ");
        Serial.print(pressure);
        Serial.println(" Pa");
        Serial.print("humidity = ");
        Serial.print(humidity);
        Serial.println(" %");

    if (client.connect(server, 80)) {
       Serial.println("CONNECTED");
       client.print( "GET /diplomna/Arduino/add_data.php?");
       client.print("temperature=");;
       client.print( temp);
       client.print("&&");
       client.print("humidity=");
    // change this to a print rather than println
       client.print( humidity );
    // add a leading space in this println
       client.println( " HTTP/1.1");
    // add a second cr/lf here to denote end of header
       client.println();
       client.println( "Connection: close\r\n" );

       while(client.connected()) {
          while(client.available()) {
            char ch = client.read();
            Serial.write(ch);
          }
        }
       client.stop();
       Serial.println("DISCONNECTED");
       }
     else {
       // you didn't get a connection to the server:
       Serial.println("-> connection failed/n");
     }
       delay(10000);
      }
      }

You can find the serial monitor output below:

0.0.0.0
Temperature = 26 *C
Pressure = 997 Pa
humidity = 57 %
-> connection failed/n

I also tried to execute the following example code (DhcpAddressPrinter)  and the results are the same - 0.0.0.0

    #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
    };

    // Initialize the Ethernet client library
    // with the IP address and port of the server
    // that you want to connect to (port 80 is default for HTTP):
    EthernetClient client;

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      // this check is only needed on the Leonardo:
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // no point in carrying on, so do nothing forevermore:
        for (;;)
          ;
      }
      // print your local IP address:
      printIPAddress();
    }

    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:
          printIPAddress();
          break;

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

        case 4:
          //rebind success
          Serial.println("Rebind success");

          //print your local IP address:
          printIPAddress();
          break;

        default:
          //nothing happened
          break;

      }
    }

    void printIPAddress()
    {
      Serial.print("My IP address: ");
      for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
      }

      Serial.println();
    }

Serial monitor output:
Failed to configure Ethernet using DHCP

I also tried to set the ip address of the shield to be 192.168.137.1 and made the following update:
  Ethernet.begin(mac);  ===>  Ethernet.begin(mac,ip);
The results are the same.

Could you please help me to debug this issue.
Thanks in advance!

Regards,
SK

sender: assistant

body:
The first thing you should do is disconnect or disable all devices from the Arduino except the network card then run your tests again, if they work (which I doubt) then the problem is a hardware resource clash, for which you will need to read the datasheets.

I suspect the problem you have is more fundamental, do you have a DHCP server on your network?

The first example doesn't specifically mention DHCP, but the second example makes the same call top `Ethernet.begin()` and seems to expect the call to have configured the NIC via DHCP.

So my advice would be to look at the API for the NIC and see what you need to do to statically configure you IPv4 settings.  Also you might need to bone up on IPv4 addresses and net masks, because the addresses you mentioned won't be able to communicate unless you have some special routing gear (it could be I read the question wrong).

Hope that helps.


body:
> from comments:
> " I use straight connection cable to connect the ethernet shield to my
> laptop and I use wifi network. "

This is the problem. Connect to router.

The direct Ethernet connection may require the use of a cross-over cable and the PC probably doesn't have a DHCP server for the Ethernet interface, so you should set an IP address for the network interface and in the Arduino sketch.

see [this SO question][1]

  [1]: https://stackoverflow.com/questions/20998745/direct-connection-between-laptop-and-arduino-via-ethernet


message:
Write and read operation via synchronous serial port (Arduino Uno + ADNS2610)

#1.Preliminaries
I have optical sensor ADNS2610 (see datasheet [here][1]) which I plug in to Arduino Uno R3 board.

It is possible either to read from either to write to the sensor. Here is what datasheet says (p. 12):

> **Write Operation**
>
> Write operations, where data is going from the microcontroller to the
> ADNS-2610, is always initiated by the microcontroller and consists of
> two bytes. The first byte contains the address (seven bits) and has a
> “1” as its MSB to indicate data direction. The second byte contains
> the data. The transfer is synchronized by **SCK**. The microcontroller
> changes **SDIO** on falling edges of **SCK**. The ADNS-2610 reads **SDIO** on rising edges of **SCK**.
[![enter image description here][2]][2]
>
> **Read Operation**
>
> A read operation, meaning data that is going from the ADNS-2610 to the
> microcontroller, is always initiated by the microcontroller and
> consists of two bytes. The first byte that contains the address is
> written by the microcontroller and has a “0” as its MSB to indicate
> data direction. The second byte contains the data and is driven by the
> ADNS-2610. The transfer synchronized by **SCK**. **SDIO** is changed
> on falling edges of **SCK** and read on every rising edge of **SCK**. The
> microcontroller must go to a High-Z state after the last address data
> bit. The ADNS-2610 will go to the High-Z state after the last data
> bit. Another thing to note during a read operation;
> **SCK** needs to be delayed after the last address data bit to ensure that the ADNS-2610 has at least 100 μs to prepare the requested data.
> This is shown in the timing diagrams below (See Figures to 23).[![enter image description here][3]][3]
[![enter image description here][4]][4]
[![enter image description here][5]][5]

#2 Arduino program
`WriteRegister` and `ReadRegister` functions are borrowed (though slightly modified) from [OptiMouse][6] project by zapmaker.
##2.1 SetAddress function
This function writes the first byte: data direction (MSB) and address of a register (seven bits) which user intents to read from or to write to.

    void ADNS2610::SetAddress( uint8_t address, DataDirection direction ) const
    {
        pinMode( sdioPin, OUTPUT );

        /*Specify data direction:
         *MSB = 0   ===>   read operation
         *MSB = 1   ===>   write operation*/
        switch( direction )
        {
            case( toSensor ) :
                address |= 0b10000000 ;
                break;
            case( fromSensor ) :
                address &= ~0b10000000 ;
                break;
        }

        for( uint8_t mask = 0b10000000; mask; mask >>= 1 )
        {
            digitalWrite( sckPin, LOW );
            digitalWrite( sdioPin, address & mask );
            digitalWrite( sckPin, HIGH );
        }

        /*Wait for 100 microseconds between address write operation
        *and read data operation (see p.15 of the datasheet)*/
        delayMicroseconds( 100 );
    }

##2.2 ReadRegister function

    uint8_t ADNS2610::ReadRegister( uint8_t address ) const
    {
        SetAddress( address, fromSensor );

        uint8_t data = 0;

        /*Read data from a register*/
        pinMode( sdioPin, INPUT );
        for( int i = 7; i >= 0; i++ )
        {
            digitalWrite( sckPin, LOW );
            digitalWrite( sckPin, HIGH );

            data |= ( digitalRead( sdioPin ) << i );
        }

        /*Wait for 0.25 microseconds between read and either
         *read or write operations (see p.15 of the datasheet)*/
        delayMicroseconds( 1 );

        return data;
    }

##2.3 WriteRegister function

    void ADNS2610::WriteRegister( uint8_t address, uint8_t data ) const
    {
        SetAddress( address, toSensor );

        /*Write data to a register*/
        for( uint8_t mask = 0b10000000; mask; mask >>= 1 )
        {
            digitalWrite( sckPin, LOW );
            digitalWrite( sdioPin, data & mask );
            digitalWrite( sckPin, HIGH );
        }

        /*Wait for 100 microseconds between write and either
        *read or write operations (see p.15 of the datasheet)*/
        delayMicroseconds( 100 );
    }

#3.Discussion
##3.1 Write operation
According to the datasheet

> ... The microcontroller changes **SDIO** on falling edges of **SCK**. The ADNS-2610 reads **SDIO** on rising edges of **SCK**.

And this is how I understand the code (see sec. 2.1):

    digitalWrite( sckPin, LOW );//create a falling edge
    digitalWrite( sdioPin, address & mask );//change SDIO on falling edge
    digitalWrite( sckPin, HIGH );//create a rising edge (ADNS reads here)

Two questions here:

 1. The first line in the above creates a falling edge only if the previous state of **SCK** was `HIGH`, doesn't it? So would it be better to have the following:

        digitalWrite( sckPin, HIGH);
        digitalWrite( sckPin, LOW );//create a falling edge
        digitalWrite( sdioPin, address & mask );//change SDIO on falling edge
        digitalWrite( sckPin, HIGH );//create a rising edge (ADNS reads here)

 2. On figure 20 (see sec. 1, Write operation) you can see that it is required some minimal duration of the clock pulses (250 ns). Does the above code provide such a duration? I know that ATMega328p has frequency 16 MHz, so it seems that time between two operations could be less than 250 ns. Am I right?

##3.2 Read operation

According to the datasheet

>  **SDIO** is changed on falling edges of **SCK** and read on every rising edge of **SCK**. The microcontroller must go to a High-Z state after the last address data bit. The ADNS-2610 will go to the High-Z state after the last data bit

And this is how I understand the code (see sec. 2.2):

    digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
    digitalWrite( sckPin, HIGH );//create a rising edge

    data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

Three questions here:

 1. The first line in the code above creates a falling edge only if the previous state of **SCK** was `HIGH`, doesn't it? Would it be better to have the following:

        digitalWrite( sckPin, HIGH);
        digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
        digitalWrite( sckPin, HIGH );//create a rising edge

        data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

 2. On figure 23 (see sec. 1,Read operation) you can see that it is required some minimal duration of the clock pulses (250 ns). Does the above code provide such a duration?

 3. How do I set the microcontroller into High-Z state after the last address data bit?

  [1]: http://bdml.stanford.edu/twiki/pub/Rise/OpticalDisplacementSensor/ADNS2051.pdf
  [2]: https://i.stack.imgur.com/0wrWi.png
  [3]: https://i.stack.imgur.com/wYdGu.png
  [4]: https://i.stack.imgur.com/cbvrj.png
  [5]: https://i.stack.imgur.com/VkfHq.png
  [6]: https://github.com/zapmaker/OptiMouse

body:
**Question 1**
>   The first line in the code above creates a falling edge only if the
> previous state of SCK was HIGH, doesn't it? Would it be better to have
> the following:
>
>     digitalWrite( sckPin, HIGH);
>     digitalWrite( sckPin, LOW );//create a falling edge (SDIO changes here)
>     digitalWrite( sckPin, HIGH );//create a rising edge
>
>     data |= ( digitalRead( sdioPin ) << i );//read SDIO on rising edge

If you start from Cycle one.. **Yes**. Looking at the read cycle waveform, SCLK should be high before initiating a read or write request and after completing the communication.

**Question 2**

> On figure 23 (see sec. 1,Read operation) you can see that it is
> required some minimal duration of the clock pulses (250 ns). Does the
> above code provide such a duration?

    Here is the code for digital write function
    void digitalWrite(uint8_t pin, uint8_t val)
    {
        uint8_t timer = digitalPinToTimer(pin);
        uint8_t bit = digitalPinToBitMask(pin);
        uint8_t port = digitalPinToPort(pin);
        volatile uint8_t *out;

        if (port == NOT_A_PIN)
            return;

        // If the pin that support PWM output, we need to turn it off
        // before doing a digital write.
        if (timer != NOT_ON_TIMER)
            turnOffPWM(timer);

        out = portOutputRegister(port);

        uint8_t oldSREG = SREG;
        cli();

        if (val == LOW) {
            *out &= ~bit;
        }
        else {
            *out |= bit;
        }

        SREG = oldSREG;
    }

**Please do not give any delay.** the above DigtalWrite function will take 1000's of ns of delay already. it is sufficient.

**Question 3:**

> How do I set the micro controller into High-Z state after the last
> address data bit?

I would do the following. Configure the pin which you want to **set to high impedance** as **input pin**. You can always change it to output mode before you want to use it again.


message:
Does delay() pause the counting of millis()?

If I add a delay for a few seconds, and then will the value given by millis () be equal just before and after delay?

Or to put it in other words, does the internal clock of Arduino stop during delay?

body:
No, I cannot check it (no Arduino at hand), but afaik the clock always keeps counting, so if you perform a delay of 1 second, and diff millis() just before and after, it will be (slightly over) 1,000 (ms).

Note however, that the use of delay is discouraged and it is better to check millis() to perform the next state/command instead of a delay which prevents doing other tasks meanwhile. But the (internal) timer always keeps running.

Only during some deep sleep mode it might stop, but than a delay will not work neither. And when interrupts are disbled (see remark of Chris Stratton below).


body:
Delay uses millis. It just waits examining millis until a certain time has passed.

Millis is driven by an interrupt. The only thing that stops it working is another interrupt (you can only have one interrupt executing at once), which is why you can't use delay in an interrupt.


message:
Detect if Serial1 and Serial2 are defined, at compile time

I have my library that uses `Serial`, `Serial1` and `Serial2` to establish various logging scenarios. Library user would define the config at class constructor, using simple byte constants like 0, 1 and 2.

Problem is, `Serial1` and `Serial2` are not available in all board types. So when I compile my code (that compiles fine on Mega) on Uno, I get error `
'Serial1' was not declared in this scope`.

So I figure I need to adjust my code with preprocessor directive like `#if defined`, in order to include some code only if Serial1 is defined. But it wouldn't work, because Serial1 is defined later, at compile-time. So what is the accepted way to do this?

body:
[HardwareSerial.h][1] in Arduino AVR boards core defines HAVE_HWSERIALX

example

    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(6, 7); // RX, TX
    #endif

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/HardwareSerial.h


body:
Consider the approach used [here in the ArduinoBoardManager project at github][1].  The file [ArduinoBoardManager.h][2] uses conditional compiling to determine the correct code to compile based on processor type.  A similar approach can be used to asses if certain hardware peripherals such as serial ports were available based on processor type.

    #if defined(__AVR_ATmega328P__) // uno, fi
      // Code compatible with an Arduino Uno
    #elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
      // Code compatible with an Arduino Mega
    #endif

  [1]: https://github.com/backupbrain/ArduinoBoardManager
  [2]: https://github.com/backupbrain/ArduinoBoardManager/blob/master/ArduinoBoardManager.h


message:
PWM fans causing temp sensor erroneus values (interference?)

I am learning Arduino programming and my current project for real use is to connect 10-17 PC chassis PWM fans to be temperature controlled by the arduino.

So, I have connected the fans exactly as in the picture.
Taken from https://www.racedepartment.com/threads/easy-diy-wind-simulator-for-assetto-corsa.133999/

[![PWM Fan connection diagram][1]][1]

  [1]: https://i.stack.imgur.com/N1Cau.jpg

The temperature sensor is a TMP36 (included in the official Arduino beginner's kit). It is connected to +5V and GND on the Arduino Uno R3. Middle pin is the output and is connected to A0 on the Uno.

Temperature readings seem to work well up until the point the fans start spinning. When they do, the output pin on the TMP36 sensor outputs junk values. Such as 0V or 700mV and it fluctuates up and down if I try probing it with a multimeter. When fans some to a stop however, the output once again stabilizes to a fairly correct value.

I am no expert in electronics interference, but electric motors I suppose cause some electrical noise? I had hoped that PC Chassis fans would already have electric components inside the hub to prevent such though...
Currently I am trying to run 2 fans at the same time but I wish to use 10-17 later once this works.

The fans I am using are Arctic 92mm PWM Rev 02.

I have checked the datasheet (https://www.arduino.cc/en/uploads/Main/TemperatureSensor.pdf) for TMP36 (TO-92 package type) and tried adding a ceramic 0.1µF capacitor between +5V and GND and also add resistor of varying values to the output pin. I believe I got some stabilization out of it but not  enough. Especially when the fans start spinnig faster than 20% duty cycle on pwm it starts to flip out.

I have tried to disconnect power to fans to check if PWM signal may cause it too, but this is not the case as the TMP36 remain stable with PWM on but fans disconnected.

Can someone please help me with explaining what is probably going on and how I can mitigate the problem in a preferably easy way? Do I need to add diodes, capacitors, resistors? Where? Or should I change to a different temperature sensor (which)?

Thankful for help!

body: In case anyone has the same problem, I solved it. Turns out is was a bad PSU. Buying a new, higher quality one made everything work. So the issue was high ripple I suspect, or at least high enough when applying some load (which is why I noticed that things got worse after the fans started spinning at greater than 20% duty cycle) for the temperature sensor to flip out.


message:
How to determine hardware/software compatibility?

Currently, I'm using [Greiman's SdFat Library](https://github.com/greiman/SdFat) with [Adafruit's Data logging Shield](https://www.adafruit.com/product/1141).

I'm thinking about switching to the [Adafruit micro SD Card Breakout](https://www.adafruit.com/product/254). I imagine that it will work as both products are made by Adafruit, and the board schematics *look* similar. However, I don't know what to look at to be sure they are the same.

Is it enough that they both use the [HC4050M](https://www.mouser.com/ProductDetail/Toshiba/74HC4050DBJ?qs=sGAEpiMZZMuiiWkaIwCK2VGJzXkUQsJSbMju57F4ABI=) chip, or is there something else that I need to be aware of?

Short of buying one and testing it. What do I need to look at to verify that these two boards will work with the library?

body: The HC4050M is just used for logic level translation (SD cards are 3.3V devices). It is "enough" that you are talking to an SD card using an SD card library. The SD card is really all the hardware there is - everything else is just interfacing fluff - completely transparent to the software.


message:
Arduino Nano off 9V : is there any change to output?

I'm building a test circuit on an Arduino Nano that consists of a simple 220 Ohm resistor and an LED on pin D2 which is routed back to GND (ground).

It's as simple as this:
[![Nano circuit][1]][1]

It's running a very simple program to blink the LED on and off.  It all works while connected to the USB port.  I know the USB port provides 5V.

Now I want to run it my Nano and circuit from a 9V battery.  The datasheet says that you can run the Nano on 6V -12V by connecting it to pin 30 (VIN).  Of course, I know I'll have to add a line from GND back to the (common) battery ground also.

When I do that, the voltage on the OUTPUT pin (D2) will never be higher than 5V though, right?
I should not expect any change in output voltage even though I'm changing voltage that is powering the Nano, correct?

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

body:
It looks like VIN connects to a LM2940, 5 volt regulator, so the voltage on the OUTPUT pin (D2) will never be higher than 5V.

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

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


message:
Is there any version of arduino that can do something like serial interruption?

I am using an Arduino to control servo MX18A by serial, and trying to use computer to communicate with the Arduino by another serial to send commands to Arduino and change the servo control mode. Once the computer send a message to Aruduino, I hope it could response in time because may be there is something emergency like the servo being out of control ,under which circumstance I have to change the control strategy in time.

However, it seems like Arduinos like UNO, MEGA does not have serial interruption, so once the message from computer comes, it could not response in time.

I know that judging `serial.available()` in every loop is one solution, but in my different servo control strategy there are many time delays, `for` loops and `while` loops, which means that I have to put `serial.available()` in every time delay or `for` loops, making the code hard to write and maintain.

body:
It is not a case of "An Arduino" that can do serial interupts. *All* Arduino boards have serial interrupts, but they are already used to receive the data and store it in a buffer for you to consume when you have the time.

The Arduino API does not define any serial interrupt handling routines. That kind of thing is designed to be handled internally by the API code, not by the user. That's the whole point of the Arduino API - to abstract away such technicalities from the user.

If you want to use the serial interrupt yourself you will have to write your own serial handling code.

Or write your code in such a way that serial interrupts aren't needed.


message:
TLC5917 Electrical Characteristics

I am using an Arduino Uno to communicate over SPI to 3 cascaded TLC5917 chips corresponding to the Red, Green and Blue rows of an RGB LED Matrix.
I am using direct output IO from the Arduino to power the columns.

Now I intend to use multiplexing to avoid drawing too much current at once, although it could still potentially be quite alot (`3 x 8 x 20ma`).

I have managed to display a full white screen using multiplexing with quite a high brightness, however this should not be possible to my knowledge.

Looking at the data sheet I found that at both at 3V and 5V the Output Voltage is rated at `Vdd - 0.4` for Voh (Voltage High Level Output).
This means that at 5V the minimum output voltage should be 4.6V and at 3V it should be 2.6V.

Disabling multiplexing and simply writing to the registers and columns, and then measuring the voltage shows `2.5V, 2.8V and 1.8V` for different colors.
This contradicts the data sheet.

The circuit contains no resistors except from GND to REXT using a 680Ohm Resistor.
The Arduino is powered over USB.

(http://www.ti.com/lit/ds/symlink/tlc5917.pdf)

Why is the Voltage so low, should it not be higher given the data sheet?
Am i reading the correct attribute?
How can my Arduino manage to drive so many LEDs (albeit through LED Drivers)?

What can I do to make this circuit more electronically safe and stable?

body:
The concepts of HIGH and LOW, and thus the voltages associated with those concepts, apply only to logic signals.

LED drivers are *not* logic signals - they are *constant current sinks*. The voltages you are measuring are the forward voltages of the LEDs.


message:
Need help in connecting 64x32 LED Matrix

I recently got a 64x32 LED Matrix. However, I'm not sure how to connect it to an arduino uno. I tried following the docs here: https://cdn-learn.adafruit.com/downloads/pdf/32x16-32x32-rgb-led-matrix.pdf, but I can't get my OLED matrix to display the example.

This is my current connection so far:
[![enter image description here][1]][1]
(I have the R0 at the top left variant. I tried connecting it to the ESP8266 before and it works well, just that I do not know how to translate the connections to the Arduino UNO) I have a feeling that my connection is wrong since I copied the PI to PO connections from here:
[![enter image description here][2]][2]

and I only changed the PI to ESP8266 connections to the adafruit docs connections.

The code I am running is the example testshapes_32x64 from the RGB matrix panel library: https://github.com/adafruit/RGB-matrix-Panel/blob/master/examples/testshapes_32x64/testshapes_32x64.ino

EDIT: Since my connection for the CLK pin is connected to pin 8, I made changes in the code but it is still not working.

x-post from: https://www.reddit.com/r/arduino/comments/8qgm9x/need_help_in_connecting_a_64x32_oled_matrix_to_an/ and https://forum.arduino.cc/index.php?topic=552832.0

  [1]: https://i.stack.imgur.com/m5kcO.png
  [2]: https://i.stack.imgur.com/eo3RL.jpg

body: If your matrix is the same as mine (32x64) I don't think you can drive it with a UNO. You should use a MEGA. Then follow the wiring supplied by SparkFun and make sure you connect CLK to Pin 11, NOT Pin 8.


message:
WiFi problem on Mega + WiFi R3 ATmega2560 + ESP8266

I've got 2 "Mega + WiFi R3 ATmega2560 + ESP8266" ([link][1]) and both have same issue when trying to use the ESP chip.

Hope someone can point me toward something else to try in order to get them working properly.

**Context**

I'm able to flash the ESP chip using Arduino IDE or PlatformIO.
Dip switch need to be : 5, 6 and 7 ON to flash, and only 5 and 6 to debug through serial.

I've tried using different boards (Generic ESP8266 module, Wemos D1 R2 & mini, Node MCU) as well as different flash mode (DIO, QIO), crystal frequency (26 Mhz, 40 Mhz), CPU frequency (80 Mhz, 160 Mhz)

They all flash correctly without any error and I can get my serial output.

It's written ESP8266EX on the ESP chip. And I've tried with or without an antenna plugged on the board.

**Problem**

The problem I got on both of them is huge instability when using wifi. I cannot connect to them when they are in AP mode, they drop immediately.. And I cannot connect to or see my own wifi network from the Mega's ESP.

The same script and flashing config used on *other ESPs* devices work as expected (see **[output other ESP board]** below). I've tried on WeMos and NodeMCU devices.

But with the mega+wifi, it only see between 0 and 2 access point that are at a greater distance and weaker signal than my own wifi (**[output mega+wifi]** below).

**Question**

I don't have any clue on what can cause such a different result on device from same family (ESP/espressif). As if there was some sort of setting that need to be changed on those ESPs.

Any help or insight would be truly appreciated.

**[code]**

    #include "ESP8266WiFi.h"

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

      // Set WiFi to station mode and disconnect from an AP if it was previously connected
      WiFi.mode(WIFI_STA);
      WiFi.disconnect();
      delay(100);

      Serial.println("Setup done");
    }

    void loop() {
      Serial.println("scan start");

      // WiFi.scanNetworks will return the number of networks found
      int n = WiFi.scanNetworks();
      Serial.println("scan done");
      if (n == 0)
        Serial.println("no networks found");
      else
      {
        Serial.print(n);
        Serial.println(" networks found");
        for (int i = 0; i < n; ++i)
        {
          // Print SSID and RSSI for each network found
          Serial.print(i + 1);
          Serial.print(": ");
          Serial.print(WiFi.SSID(i));
          Serial.print(" (");
          Serial.print(WiFi.RSSI(i));
          Serial.print(")");
          Serial.println((WiFi.encryptionType(i) == ENC_TYPE_NONE)?" ":"*");
          delay(10);
        }
      }
      Serial.println("");

      // Wait a bit before scanning again
      delay(5000);
    }

**[output other ESP board]**

 scandone
 scan done
 8 networks found
 1: 412 Precondition Failed (-67)*
 2: VIDEOTRON1547 (-90)*
 3: BELL275 (-94)*
 4: BELL558 (-72)*
 5: C-PC_Network (-88)*
 6: BELL387 (-90)*
 7: EBOX-4229 (-94)*
 8: VIDEOTRON6825 (-80)*

 scan start
 scandone
 scan done
 11 networks found
 1: 412 Precondition Failed (-63)*
 2: VIDEOTRON1547 (-88)*
 3: BELL681 (-90)*
 4: BELL275 (-90)*
 5: VIDEOTRON0442 (-90)*
 6: BELL558 (-71)*
 7: BELL602 (-90)*
 8: IKA COIFFURE (-90)*
 9: C-PC_Network (-87)*
 10: EBOX-4229 (-87)*
 11: BELL387 (-90)*

 scan start
 scandone
 scan done
 7 networks found
 1: 412 Precondition Failed (-65)*
 2: BELL681 (-88)*
 3: VIDEOTRON1547 (-88)*
 4: EBOX-4229 (-88)*
 5: BELL387 (-87)*
 6: BELL558 (-71)*
 7: dlink-Ares (-75)*

**[output mega+wifi]**

 SDK:2.2.1(cfd48f3)/Core:2.4.1/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1)
 bcn 0
 del if1
 usl
 mode : sta(2c:3a:e8:26:36:13)
 add if0
 wifi evt: 8
 Setup done
 scan start
 scandone
 scan done
 1 networks found
 1: BELL558 (-69)*

 scan start
 scandone
 scan done
 1 networks found
 1: BELL387 (-88)*

 scan start
 scandone
 scan done
 no networks found

 scan start
 scandone
 scan done
 1 networks found
 1: BELL387 (-87)*

**[erasing flash]**

 PS \tool-esptoolpy> python .\esptool.py -p COM10 erase_flash
 esptool.py v2.3.1
 Connecting....
 Detecting chip type... ESP8266
 Chip is ESP8266EX
 Features: WiFi
 Uploading stub...
 Running stub...
 Stub running...
 Erasing flash (this may take a while)...
 Chip erase completed successfully in 14.2s
 Hard resetting via RTS pin...

  [1]: https://robotdyn.com/mega-wifi-r3-atmega2560-esp8266-flash-32mb-usb-ttl-ch340g-micro-usb.html

body:
You state you "cannot connect to them when they are in AP mode" but I do not see AP configured in your code.

    // ESP AP Server
    // password can be blank
    // must be min 8 chars or will not work
    const char *APName = "MYESP8266";
    const char *APPass = "MYPASS123";
    // start the access point server
    WiFi.softAP(APName, APPass);
    // define web link functions
    webServer.on("/", doRoot);
    // start server
    webServer.begin();

    // In LOOP
    // keep checking to see if someone connects to device
    webServer.handleClient();

Regarding the mega-wifi-r3-atmega2560-esp8266
I am unsure how these work, is the code being flashed to the ESP chip or to the Arduino chip and ESP is in AT mode?


body:
I had this problem. On Robotdyn D1 mini the esp8266 flash erase did help. On Robotdyn D1 R2 only the flashing of the AT firmware with Espressif Flash Download Tool restored the esp8266. After then the sketches from IDE had working WiFi.

There are some settings of the Espressif basic esp8266 libraries (SDK) saved on flash and there is some incompatibility between SDK versions. The Flash Download Tool creates right esp settings binary and flashes it to right address on flash.


body:
If you've come upon this page because the ESP8266 on your (WeMos) Mega wifi won't connect to your router (etc), check the age/security of your router:
https://arduino.stackexchange.com/questions/65637/wifi-stopped-connecting-wemos-d1-mini

This line of code that allowed connecting with my old router:
  WiFi.enableInsecureWEP();

which also highlights that I should upgrade it...


message:
How to control a DRV8266 motor controller with an ESP8266?

https://github.com/sparkfun/SparkFun_MiniMoto_Arduino_Library/tree/V_1.1.0

Will this library work on an esp8266?   If not is there any way I can get this driver to work on the ESP?

body: No, since it uses AVR defines. Convert the code that uses these defines to the equivalent ESP8266 code instead.


body:
As Ignacio kindly pointed out (+1), the answer to my original question is no.

---

The following code works to control a Sparkfun Minimoto board, though, or more generally the DRV8830.   Just connect GPIO5 to SCL and GPIO4 to SDA.   On some variants the default SDA/SCL pins are different though -- you can always use any pins (except for GPIO0, GPIO2, and GPIO15 -- see [my recent post][1] on using these pins) for your I2C bus and just call wire.begin(sda,scl) where sda and scl are the pin numbers you want.

    #include <Wire.h>

    #define MOTORA_WRITE 0x64
    #define MOTORA_READ 0x65
    #define CONTROL_addr 0x00
    #define FAULT_addr 0x01

    void setup() {
      Wire.begin();

      drive(20);//enter values from -63 to 63, where negative values are reverse
      delay(100);
      coast();//releases the motor
      delay(100);
      brake();//brakes the motor

    }

    void loop() {
      // put your main code here, to run repeatedly:

    }

    byte tsState = -99;//used so redundant calls of any of these methods don't do anything -- only new calls will trigger communication with the motor controller
    void drive(int speed) {
      if (speed != tsState) {
        tsState = speed;
        // Write to the Fault Register to reset it
        Wire.beginTransmission(MOTORA_WRITE);
        Wire.write(FAULT_addr);
        Wire.write(0x80);
        Wire.endTransmission(true);

        // Write to the Control Register
        Wire.beginTransmission(MOTORA_WRITE);
        Wire.write(CONTROL_addr);
        byte regValue;
        regValue = (byte)abs(speed); // Find the byte-ish abs value of the input
        if (regValue > 63) regValue = 63;
        regValue = regValue << 2; // Left shift to make room for bits 1:0
        if (speed < 0) regValue |= 0x01; // Set bits 1:0 based on sign of input.
        else regValue |= 0x02;
        Wire.write(regValue);
        Wire.endTransmission(true);
      }
    }
    void brake() {
      if (tsState != -98) {
        tsState = -98;
        Wire.beginTransmission(MOTORA_WRITE);
        Wire.write(FAULT_addr);
        Wire.write(0x80);
        Wire.endTransmission(true);
        Wire.beginTransmission(MOTORA_WRITE);
        Wire.write(CONTROL_addr);
        byte regValue = (byte)63;
        regValue = regValue << 2;
        regValue |= 0x03;
        Wire.write(regValue);
        Wire.endTransmission(true);
      }
    }
    void coast() {
      if (tsState != -97) {
        tsState = -97;
        Wire.beginTransmission(MOTORA_WRITE);
        Wire.write(FAULT_addr);
        Wire.write(0x80);
        Wire.endTransmission(true);
        Wire.beginTransmission(MOTORA_WRITE);
        Wire.write(CONTROL_addr);
        byte regValue = (byte)0;
        Wire.write(regValue);
        Wire.endTransmission(true);
      }
    }

  [1]: https://electronics.stackexchange.com/questions/389293/can-i-connect-the-esp8266s-boot-mode-select-pins-directly-to-logic-warning-m/389294#389294


message:
Specified folder/zip file does not contain a valid library

I am trying to use [this](https://github.com/mikedotalmond/arduino-pulseInWithoutDelay) library.
But when I try to import the .zip file (of the directory) downloaded from GitHub, Arduino IDE says "Specified folder/zip file does not contain a valid library"

body:
That's because it contains *two* libraries, and the IDE doesn't know how to handle that.

Because of this repository structure, you will need to do a [manual installation](https://www.arduino.cc/en/guide/libraries#toc5).

Extract the zip file manually and copy the `libraries` folder into your Arduino sketchbook folder. You can find the location of your sketchbook folder in the Arduino IDE at **File > Preferences > Sketchbook location**.


message:
Can I make a 455Khz Sine Wave with the Arduino UNO?

Can any one help me, I need to make a sine-wave of 455Khz for use in aligning a Super 7 - AM Radio.

I looked into buying a function generator but I have an Arduino UNO. Can this do the tasks?

body:
The Arduino does not has a DAC (digital analog converter), so you cannot make an output varying in voltage (except for 0V / 5V) by default.

The PWM outputs use 0V/5V with duty cycle but this is not a sine wave.

So you need additional hardware anyway.

Also, regarding speed if you have a DAC. Assume 16 MHz for the Arduino, having a 455 Khz sinewave, you have about 35 clock cycli per complete sine wave. The sine values you can store in a table, but you need probably at least 3 or 4 clock cycli per sine wave value (to fetch the value from the table and to send it to the DAC), this results in about 8 values which will give a very rough sine wave.

So I would go for a separate sine wave generator.


body: If you don't want to buy a chip, and you do have a few other parts laying around, it would not be hard to do a simple oscillator with Op Amps and get a nearly true sine wave.  Alternatively an inverter (74ls04, or any inverting gate chip cmos or ttl) with an R-C can be made into a square wave generator, and another RC or two could get it to approximate a sine wave.


message:
How to measure room light without LEDs interfering?

I'm trying to measure the light in a room with a simple circuit: a phototransistor connected in series with a resistor. An LED strip changes brightness according to the brightness level in the room.

The problem here is that the phototransistor also picks up the light from the LEDs. It is not an option using an IR phototransistor because I also need to measure the light from the room's light bulbs. Also, because of the device's casing, I need the sensor to be surrounded by the LED strip. Finally, I tried turning off the LEDs before measuring does not seem to work, as either the Arduino or the sensor is too slow, to turn off, perform the measurement, and turning back on the LEDs, without a human eye perceiving it.

Is there any standard or well known solution to this problem?

I will appreciate any help you can provide.

**Additional Information**

The LED strip is the WS2812B.
The phototransistor I'm using operates between 420 nm and 1130 nm, with peak sensitivity around 850 nm.

Furthermore, to specify the functionality I'm trying to achieve: whenever the room is dark, I want the LEDs to be not too bright. If the room is too bright, I want the LEDs to shine brighter as well.

body:
What you can try is to use a color sensor. Since you know the color of the LEDs you control, if the color sensor picks up a different color, you know it is because of other light.

Since this is not full proof (ambient color might be exactly as the LED color), you can check color differences (also with a non color sensor). If it differes without you changing the LED, you know there is ambient light (either increasing/decreasing).

It also will help if you put the sensor in a tube which is in a different direction than the LEDs to prevent as much as possible picking up the light from the sensors if possible.

(if you don't have color sensors you can use a normal sensor with some colored plastic above/around it).


body:
Normally you should be able to switch LEDs off, make a measurement and switch LEDs back on without a noticeable delay. Brightness variation is noticeable below 100Hz, which translates to 10ms period.

What you need is a photodiode with fast response time (under 0,1ms or so, though there are devices responding in nanosecond range). Phototransistors and LDRs are considerably slower.

LEDs response time is in single-digit microseconds even for white LEDs, and RGB LEDs are even faster. Below is a response of typical LEDs to a 200ns pulse:

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

Regular `AnalogRead` takes about 0.1ms (and, again there are faster alternatives), so you can easily achieve kHz measurement frequencies where brightness variation is completely unnoticeable.

  [1]: https://i.stack.imgur.com/Zk13t.jpg


message:
How to improve response time of this sound operated LED?

I have written the following code for lighting an LED on a  clap ( using sound sensor)   that I have connected via a resistance of  330 OHM on pin number 4.

However, when I clap once,  close to the sound sensor,  it does not lights  the LED. But it only lights the LED if  I provide prolong exposure to sound  ( more than 6 seconds) on the sound sensor.

How can I improve this , so that even if I clap once for a seconds duration, the LED glows?

    int soundSensor=10;
    int LED=4;

    void setup()
    {
     Serial.begin(9600);
     pinMode(soundSensor,INPUT);
     pinMode(LED,OUTPUT);
    }

    void loop()
    {
      int SensorData=digitalRead(soundSensor);
      if(SensorData==1)
      {

         digitalWrite(LED,HIGH);
      delay(3000);

         Serial.println("LOUD, LOUD");
         delay(1000);
      }
        else
      {

         digitalWrite(LED,LOW);
         Serial.println("SLOW, SLOW");
         delay(1000);
      }
     }

body:
I think the problem is in the times you check the sensor. If you clap exactly when you check it will glow even if clapped for 1 ms, but if it checks in between two claps it doesn't detect it.

So check more often (reduce the delays) and check for so many sound detections within one second.

Or, as JRE below proposes, use an interrupt, this is even better but needs a bit more programming skills. Still interrupts are used a lot in microcontroller programming so it is worthwhile to check into this.


body: Depending on sensor , simple modification with series diode to detect impulse and hold decaying slow with say 0.01uF to  and 10 MOhm to 0V will detect 1st time and stretch pulse ~ 0.01u*10M =0.1s


body:
Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. Good tasks for using an interrupt may include reading a rotary encoder, or monitoring user input (like clapping).

Using the attachInterrupt() function is the way to go here!

https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/


message:
Analog inputs showing value even there is nothing connected to it

After watching something weird on the serial monitor I wrote a simple code to monitor the analog pin input values. There was nothing connected to the analog pins still they where showing decimal representation of some analog values.

the code is

    float ana [] = {A0,A1,A2,A3,A4,A5};
    float dec [6];

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

    void loop()
    {
      for(int i = 0; i<6 ; i++)
      {
        dec[i] = analogRead(ana[i]);
        Serial.println(dec[i]);
        delay(1000);
      }
    }

How is this even possible?

this is the output result

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

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

body: Your input is floating if nothing is connected.  It is reading whatever random noise it happens to pick up.  That's what it is supposed to do.  For it to read 0 it would need to be connected to ground.  Google "floating input" for more info.


message:
I2c device disappear from bus after writing

I am currently experiencing a really odd I2C problem on a Atmega32u4 based card. I'm trying to use a [TLV493D](https://www.infineon.com/cms/en/product/sensor/magnetic-position-sensor/3d-magnetic-sensor/tlv493d-a1b6/) connected by I2C. I know from this [thread](https://forum.arduino.cc/index.php?topic=419380.0) that before using this device, I have to set the powermode :

    Wire.beginTransmission(HallAddressWrite);       // Address the sensor
    Wire.write(configReg);              // Address the Configuration register
    Wire.write(powerMode);              // Set the Power Mode to Low
    errorCode = Wire.endTransmission();             // Stop transmitting

But each time I'm trying to write on the TLV493D register, the device simply disappear from I2C bus ! I know it sounds strange, but I can demonstrate it with a modified version of [default I2C scanner](https://playground.arduino.cc/Main/I2cScanner)

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      Serial.println("Beginning write test...");
      Wire.beginTransmission(address);
      // no register writing
      errorCode = Wire.endTransmission();
      Serial.print("Test ended with code : ");
      Serial.println(errorCode);

      Serial.println("SECOND Beginning write test...");

      Wire.beginTransmission(address);       // Address the sensor
      Wire.write(0x00);              // Address the Configuration register
      Wire.write(0x05);            // Set the Power Mode to Low
      errorCode = Wire.endTransmission();
      Serial.print("Test ended with code : ");
      Serial.println(errorCode);

      nDevices++;
    }

which gives the output:

    I2C device found at address 0x5E  !
    Beginning write test...
    Test ended with code : 0
    SECOND Beginning write test...
    Test ended with code : 0
And next scan doesn't find anything. As you can see, I don't lost my device when I don't write anything. But it disappears from my bus as soon as I write something (here, it's for setting low power mode, but any value will do the same).

More informations :

 - My code is correct. I know that because I don't have any problem when using an Arduino Uno or Arduino Mega. Unfortunately, I don't have an Arduino Leonardo to see if my problem comes from Atmega32u4.

 - My wiring is correct. I checked the signal on SDA and SCL pin on the TLV493D with an oscilloscope and everything is as expected : 3.3V and 100kHz.

 - I also have a SRF02 on my I2c bus : it is working as expected.

 - I don't think my TLV493D is damaged. In deed, I thought it was because of that. So I changed it for another one but the problem is still here.

 - I noticed than when beginning an I2C transmission at address 0x00, I am able to see my TLV493D again. But it is pointless since I have to set power mode again and thus, it disappears from bus once again.

body:
By default the FAST register is set to 0 at power up.
When the FAST mode is 0 and you set LOW to 0 you are entering Power Down mode.

Looking at your code it looks like you are not altering the FAST register which means I can simplify your question to "Why does my device disappear from the I2C bus every time I turn it off".

Just looking at page 34 of the English User Manual I would say you have to set FAST to 1 before setting LOW to 0.

Also - Do you have pull-up resistors on the I2C bus?  You might encounter problems without them.  They are normally around 4.7K for 5V, but I don't know what they should be for 3.3v systems.


body:
To sum up this problem :
TLV493D configuration work by writing two bytes with I2C. You must begin by writing 0x00, which will be ignored since the first register is reserved. Then, you write a second byte that will actually do the configuration (second register).
The three smalest bits enable or disable INT, FAST and LOW mode.

I still don't understand why I am not able to enable INT mode on my Atmega32u4 while it doesn't seem to be a problem on Uno or Mega (on LOW mode). Anyway, two configurations work for me :

0x07 --> INT, FAST and LOW are all enabled

0x01 --> only LOW is enabled

I don't think it's a issue to disable INT. If I understood correctly, it will make the device send an interrupt pulse to request microcontroller reading. If you manage readings by yourself, I don't think you need INT to be enabled.

Many thanks to CodeGorilla for his support.

**UPDATE:**

I managed to get an Arduino Leonardo. Indeed, all my obsevations on my Atmega32u4 based card are still corrects (writing 0x05 second register make the device disappear from bus, but not with 0x01 or 0x07). But again, it works normally on Uno or Mega... Really odd ! If anyone has an explanation to offer, it would be greatly appreciated.


message:
Print with round towards zero instead of round to nearest

When printing with one decimal place, Arduino's `Serial.println()` rounds numbers like `123.89` to “123.9”. Is there any way to change the rounding mode? For some reasons I want the value to be rounded towards zero (i.e., truncated) to one decimal place, like `123.89` → “123.8”.

here is the code

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

    }

    void loop()
    {
    float A = analogRead(A0);
    A = (A/1023)*5.0;
    Serial.print("A = ");
    Serial.println(A,3);
    float B = A*10;
    Serial.print("A * 10 = ");
    Serial.println(B,1);
    delay(1000);
    }

the output is

    A = 2.473
    A * 10 = 24.7
    A = 2.488
    A * 10 = 24.9
    A = 2.517
    A * 10 = 25.2
    A = 2.527
    A * 10 = 25.3
    A = 2.507
    A * 10 = 25.1

instead I want the output to be like this

    A = 2.473
    A * 10 = 24.7
    A = 2.488
    A * 10 = 24.8
    A = 2.517
    A * 10 = 25.1
    A = 2.527
    A * 10 = 25.2
    A = 2.507
    A * 10 = 25.0

is it possible ?

body:
A cheap trick to round a number to one decimal place (in "chop-off mode") is to multiply it by 10, convert it to an integer, and divide by `10.0f` again:

<!--language:lang-cpp-->

    float myVal = 123.89f;
    myVal = (long)(myVal * 10) / 10.0f;
    // = ((long)1238.9) / 10.0f
    // = 1238 / 10.0f
    // = 123.8

You can then print this modified number to the serial monitor.

This method can also be generalized to other precisions. For 2 decimal places, we just have to multiply by 10^2 (100) and divide by 10^2. A macro would be:

    #define TRUNCATE(val, numDecimalPlaces) \
     (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

Note: You don't have to actually dynamically compute `pow(10, numDecimalPlaces)`, you can also create macros for each decimal precision from 1 to `x` and simply precompute that value (100, 1000, 10000, ..).

The same can also be achieved by using the standard library function `trunc` from `math.h`:

    #define TRUNCATE_TO_ONE(val) \
     (trunc((val) * 10.0f) / 10.0f)

See http://www.cplusplus.com/reference/cmath/trunc/.

Here's a small sketch in which it is demonstrated:

    #include <Arduino.h>

    #define TRUNCATE(val, numDecimalPlaces) \
     (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

    #define TRUNCATE_TO_ONE(val) \
     (trunc((val) * 10.0f) / 10.0f)

    void printValueFormatted(float value, int numDecimalPlaces) {
        //format correctly
        char buf[20];
        char* res = dtostrf(value, sizeof(buf)-1, numDecimalPlaces, buf);

        //skip over empty chars
        while(*res == ' ')
         res++;

        //print buffer
        Serial.println(res);
    }

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

    void loop(void)
    {
     float myVal = 123.8978f;
     printValueFormatted(myVal, 4);
     printValueFormatted(TRUNCATE(myVal, 1), 1);
     printValueFormatted(TRUNCATE(myVal, 2), 2);
     printValueFormatted(TRUNCATE(myVal, 3), 3);
     printValueFormatted(TRUNCATE(myVal, 1), 4);
     printValueFormatted(TRUNCATE(myVal, 2), 4);
     printValueFormatted(TRUNCATE(myVal, 3), 4);
     delay(1000);
    }

Prints

    123.8978
    123.8
    123.89
    123.897
    123.8000
    123.8900
    123.8970


body:
Use the given [function] for your problem. This function works on a pre-defined [algorithm].

    int roundTowardZero(float number, int decimal_place) {
        float round_number = round(number);
        if(round_number > number) round_number = round_number - 1;
        float deci = (number - round_number) * pow(10, decimal_place);
        float round_decimal = round(deci);
        if(round_decimal > deci) round_decimal = round_decimal - 1;
        round_decimal = round_decimal / pow(10, decimal_place);
        total_number = round_number + round_decimal;
        return total_number;
    }
Place this function above `int setup()`

like:

    int roundTowardZero( ... ) {
        ...
    }
    void setup() {
        ...
    }
    void loop() {
        ...
    }
Function syntex is like this : `roundTowardZero([Enter a Decimal Value], [Enter Round Place Value])`
Example :` roundTowardZero(123.89, 1) //Output : 123.8`

Please comment below is you find any problem or face any error.


message:
I get a redefinition of "..." on every single line, of every variable, class, function, etc

When I compile my program I get an error message saying redefinition of "..." on every single line, of every variable, class, function, etc.

What am I doing wrong?

    int incomingByte = 0;   // for incoming serial data

    int byteCount = 0;

    bool decision = false;

    bool last_debounce = false;

    bool test_running = false;

    bool ready_freq_enable = false;

    int cur_cavity_address = 0;

    char serBuffer[256] = {0};

    unsigned long previousMillis_enable = 0;
    const long interval_online = 1000 / 100;

    unsigned long previousMillis_debounce = 0;
    const long interval_debounce = 50;

    void setup() {
      // put your setup code here, to run once:
     /* pinMode(22, OUTPUT);//address bit 1
      pinMode(24, OUTPUT);//address bit 2
      pinMode(26, OUTPUT);//address bit 3

      pinMode(36, INPUT);

      pinMode(40, OUTPUT);
      pinMode(48, OUTPUT);
      pinMode(52, OUTPUT);*/

      pinMode(2, OUTPUT);//address bit 1
      pinMode(3, OUTPUT);//address bit 2
      pinMode(4, OUTPUT);//address bit 3

      pinMode(5, OUTPUT);
      pinMode(6, OUTPUT);
      pinMode(7, OUTPUT);

      pinMode(10, INPUT);

      Serial.begin(9600);
    }

    int seekChar(char c){
      for (int x = 0; x < 256; x++) {
        if (serBuffer[x] == c){
          return x;
        }
      }
      return -1;
    }

    void return_error(){
      Serial.println("ERROR!");
    }

    void loop() {
      if (Serial.available() > 0) {
              // read the incoming byte:
             int incomingByte = Serial.read();
              serBuffer[byteCount] = incomingByte;
              byteCount++;

              if (serBuffer[strlen(serBuffer)-1] == '\r'){
                serBuffer[strlen(serBuffer)-1] = 0; //remove the last carriage return

                int charIdx = seekChar(' ');
                char value[32] = {0};
                byteCount = 0;
                Serial.flush();

                if (charIdx != -1){
                  memcpy(value, serBuffer + charIdx + 1, sizeof(value));
                  memset(serBuffer + charIdx, 0, sizeof(serBuffer) - charIdx);
                }

                if (strcmp(serBuffer, "run") == 0){
                  if (ready_freq_enable == true){
                    test_running = strcmp(value, "true") == 0;
                    if (test_running){
                      decision = 0;
                    }
                  } else {
                    return_error();
                  }

                } else if (strcmp(serBuffer, "reset") == 0){
                  cur_cavity_address = 0;
                  decision = false;
                } else if (strcmp(serBuffer, "decision") == 0){
                  decision = strcmp(value, "true") == 0;
                } else if (strcmp(serBuffer, "enable") == 0){
                  ready_freq_enable = strcmp(value, "true") == 0;

                } else if (strcmp(serBuffer, "address") == 0){
                  if (abs(atoi(value)) > 8){
                    return_error();
                  }
                  cur_cavity_address = abs(atoi(value));
                }

                memset(serBuffer, 0, sizeof(serBuffer));
                memset(value, 0, sizeof(value));

              }
      }

      test_running &= ready_freq_enable;
      update_io();
      check_status();
    }

    void check_status(){
      unsigned long currentMillis = millis();
      bool new_debounce =  digitalRead(10);
      if (new_debounce != last_debounce){

        if (currentMillis - previousMillis_debounce >= interval_debounce) {

        // save the last time you blinked the LED
          previousMillis_debounce = currentMillis;

          Serial.print( new_debounce );
          last_debounce = new_debounce;
        }

      } else {
        previousMillis_debounce = currentMillis;
      }
    }

    void update_io(){
      //digitalWrite(48, !digitalRead(48) );

      digitalWrite(7, test_running);

      digitalWrite(3, (cur_cavity_address & 0b001) != 0);
      digitalWrite(2, (cur_cavity_address & 0b010) != 0);
      digitalWrite(4, (cur_cavity_address & 0b100) != 0);

      unsigned long currentMillis = millis();
      //Serial.println(ready_freq_enable);
      if (currentMillis - previousMillis_enable >= interval_online) {
        // save the last time you blinked the LED
        previousMillis_enable = currentMillis;
        digitalWrite(5, !digitalRead(5) & ready_freq_enable);
        if (ready_freq_enable == false){
          cur_cavity_address = 0;
        }
      }

      digitalWrite(6, decision & ready_freq_enable);
    }

body: Apparently I had a duplicate ino file on my same folder. Must of happened accidentally when I was creating a copy as backup. Thanks Chris!


message:
Serial.parseFloat() reads 0 despite me entering different value

I'm trying to make a robot that asks the user for the longitude and the altitude form the user and then using the data the GPS collects to go to the wanted location, however when I use Serial.parseFloat() to get the location from the user, i get the right value for the latitude and the longitude returns zero for some reason
here's the code i wrote

    #include "Adafruit_FONA.h"

    // standard pins for the shield, adjust as necessary
    #define FONA_RX 2
    #define FONA_TX 3
    #define FONA_RST 4
    #define PIN13 13
    #define IN1 6      //IN1
    #define IN2 7        //IN2
    #define ENA 5          //ENA
    #define ENB 10        //ENB
    #define IN3 8          //IN3
    #define IN4 9          //IN4
    #define trigger1 A3      //Trigger
    #define echo1 A2        //Echo
    #define trigger2 A4
    #define echo2 A5
    #define trigger3 A0
    #define echo3 A1

    // We default to using software serial. If you want to use hardware serial
    // (because softserial isnt supported) comment out the following three lines
    // and uncomment the HardwareSerial line
    #include <SoftwareSerial.h>
    SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
    SoftwareSerial *fonaSerial = &fonaSS;
    int counter;
    char serialData;
    int duration;
    float distance1, distance2, distance3;
    float latitudeDestination, longitudeDestination;

    // Hardware serial is also possible!
    //  HardwareSerial *fonaSerial = &Serial1;
    Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
    // Have a FONA 3G? use this object type instead
    //Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST);

    void getLatitude(){
        Serial.println("Enter the latitude destination :");
        while (Serial.available() == 0){}
        latitudeDestination = Serial.parseFloat();
    }

    void getLongitude()
    {
        Serial.println("Enter the longitude destination :");
        while (Serial.available() == 0){}
        longitudeDestination = Serial.parseFloat();
    }

    void securityPassed()
    {
        Serial.println("You need to pass security first");
        while (Serial.available() ==0){}
        serialData = Serial.read();
        if (serialData == '1')
        {
            Serial.println("Passed") ;
        }
        else {}
    }

    void setup() {
        pinMode(PIN13, INPUT);
        pinMode(trigger1, OUTPUT);
        pinMode(echo1, INPUT);
        pinMode(trigger2, OUTPUT);
        pinMode(echo2, INPUT);
        pinMode(trigger3, OUTPUT);
        pinMode(echo3, INPUT);
        pinMode(IN1 , OUTPUT);
        pinMode(IN2, OUTPUT);
        pinMode(IN3, OUTPUT);
        pinMode(IN4, OUTPUT);
        pinMode(ENA, OUTPUT);
        pinMode(ENB, OUTPUT);

        digitalWrite(ENA , HIGH);
        digitalWrite(ENB, HIGH);

        Serial.begin(9600);

        getLatitude();
        getLongitude();
        securityPassed();

        Serial.println(F("Adafruit FONA 808 & 3G GPS demo"));
        Serial.println(F("Initializing FONA... (May take a few seconds)"));
        fonaSerial->begin(4800);
        if (! fona.begin(*fonaSerial)) {
            Serial.println(F("Couldn't find FONA"));
            while (1);
        }
        Serial.println(F("FONA is OK"));
        // Try to enable GPRS
        Serial.println(F("Enabling GPS..."));
        fona.enableGPS(true);
    }

    void loop() {
        delay(2000);

        float latitude, longitude, speed_kph, heading, speed_mph, altitude;
        float latitudeDistance = latitudeDestination - latitude ;
        float longitudeDistance = longitudeDestination - longitude;

        // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix
        boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude);
        if (gps_success) {
          Serial.print("GPS lat:");
          Serial.println(latitude, 6);
          Serial.print("GPS long:");
          Serial.println(longitude, 6);
          Serial.print("GPS speed KPH:");
          Serial.println(speed_kph);
          Serial.print("GPS speed MPH:");
          speed_mph = speed_kph * 0.621371192;
          Serial.println(speed_mph);
          Serial.print("GPS heading:");
          Serial.println(heading);
          Serial.print("GPS altitude:");
          Serial.println(altitude);
          Serial.print("Latitude Distance: ");
          Serial.println(latitudeDistance);
          Serial.print("Longitude Distance: ");
          Serial.println(longitudeDistance);

          if ( latitudeDistance < 0.00001 && latitudeDistance > -0.00001)
          {

            if ( longitudeDistance < 0.00001 && longitudeDistance > -0.00001)
            {
              Serial.print("Arrived");
              stopm();
            }
            else
            {
              if (!counter == 1 && longitudeDistance > 0 )
              {
                moveRight();
                Serial.println("Turning Right");
                counter =1;
              }
              else if ( !counter == 1 && longitudeDistance < 0 )
              {
                moveLeft();
                Serial.println("Turning Left");
                counter=1;

              }
              moveForward();
            }
          }
          else
          {
            moveForward();
            Serial.print("Going To Destination");
          }
        }
        else {
          Serial.println("Waiting for FONA GPS 3D fix...");
        }
    }

body:
It is certainly possible that a person typing (or an automated system feeding data in packets over a spotty link) might fail to provide a valid number in the (default 1 second) time before `parseFloat()` times out.

However, given this is the *second* value to be read, there's a more complex possibility.

It's likely that the sequence actually sent might be something like

`123.45\r\n`

In this case `123.45` and the first non-value character `\r` will be consumed by the first `parseFloat()`.

But that leaves a remaining `\n` in the serial buffer, so the `serialAvailable()` check is satisfied *immediately* and the next `parseFloat()` begins before the user has even *started* typing.  Unless they're very quick to respond, it may time out before they even begin.

If the user is supposed to use a terminal program that sends a carriage return and/or newline, you should probably change input processing to either consume until the end of the line before processing.

Or you can make your code flexible by being sure to consume any trailing line end characters (after checking for them with `Serial.peek()`) before you decide that the user has begun entering a new value and starting your next `parseFloat()` call.

You could also make your own more sophisticated `parseFloat()` using a different algorithm.


message:
USB Mouse Passthrough

I am currently doing research for a project of mine. My goal is simple: I want to pass input from a physical mouse, to a microcomputer to process the input and modify, and send the input in the form of USB HID to a PC.

> Mouse ---> Microcomputer (input modified) ---> PC

 The Microcomputer preferably should be able to both send data to the PC (in the form of USB HID inputs as a mouse) and receive data from the PC.

I found the arduino Leonardo can act as a USB slave and emulate mouse movement, half of what I want. I need some microcomputer with capabilities to act both as a USB host and as a USB slave. I don't have experience with microcomputers, and I don't know how to find something with this feature.

body:
Plug a USB Host Shield into the Leonardo.

    USB mouse --- USB Host Shield --- Leonardo --- PC

[USB Host Shield Library][1]

[Circuits@Home Project][2]

    /*
     * USB Mouse pass through. Works at HID report level. HID report is not decoded.
     * Tested on Leonardo with Arduino USB host shield, IDE 1.8.5, and Logitech Marble
     * trackball/mouse. This is a proof of concept so is not guaranteed to work with
     * all USB mice/trackballs.
     */
    // USB host mouse from USB Host Shield Library. Install using Library Manager
    #include <hidboot.h>

    // USB device mouse library included with Arduino IDE 1.8.5
    #include <Mouse.h>

    // Satisfy the IDE, which needs to see the include statment in the ino too.
    #ifdef dobogusinclude
    #include <spi4teensy3.h>
    #endif
    #include <SPI.h>

    class MouseRptParser : public MouseReportParser
    {
    protected:
        void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
    };

    void MouseRptParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
    {
      Serial.print("MouseRptParser::Parse");
      // Show USB HID mouse report
      for (uint8_t i = 0; i < len ; i++) {
        Serial.print(' '); Serial.print(buf[i], HEX);
      }
      Serial.println();

      // On error - return
      if (buf[2] == 1)
        return;

      if (len > 2) {
        uint8_t mouseRpt[4];
        mouseRpt[0] = buf[0];
        mouseRpt[1] = buf[1];
        mouseRpt[2] = buf[2];
        mouseRpt[3] = 0;
        HID().SendReport(1,mouseRpt,sizeof(mouseRpt));
      }
    }

    USB     Usb;
    HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

    MouseRptParser Prs;

    void setup()
    {
      Serial.begin( 115200 );
    #if !defined(__MIPSEL__)
      while (!Serial) delay(1); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
    #endif
      Serial.println("Start");

      if (Usb.Init() == -1) {
        Serial.println("USB host shield did not start.");
      }
      delay( 200 );

      HidMouse.SetReportParser(0, &Prs);

      Mouse.begin();
    }

    void loop()
    {
      Usb.Task();
    }

  [1]: https://github.com/felis/USB_Host_Shield_2.0
  [2]: https://www.circuitsathome.com/arduino_usb_host_shield_projects/


message:
Schematic for the adafruit motor shield v2.3

I am trying to locate a schematic for the Adafruit motor shield v2.3. It has many ports and currently I have found little to no explanation of what is on the board. I located this picture which highlights the motor ports, servo ports, and Arduino Pins. But what about everything else?

What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins? What is the PWMs 0,1,14,15? How is the big empty board in the center setup?

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

  [1]: https://i.stack.imgur.com/darsZ.jpg

body:
Everything can be found out by reading the schematic which, incidentally, is the first hit on Google when you search for "Adafruit motor shield 2.3 schematic":

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

> What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins?

Yes. They're just there to make it easy to solder wires and jumpers to.

> What is the PWMs 0,1,14,15?

They are connected to PWM pins 0, 1, 14 and 15 of the PCA9685.

> How is the big empty board in the center setup?

It's just holes. Known as a "matrix prototyping board" for you to solder your own components and things into. Nothing there is connected to anything at all, it's up to you to make the connections with solder and wires.

As you can see from the schematic the only Arduino pins used are SDA/SCL (A4 and A5) and two PWM pins D9 and D10. Everything else comes from the on-board I2C PWM chip.

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


message:
Arduino RFID with motor and limit switches

Thanks for looking into my Arduino code.
I'm building an automated sliding draw, and I'm trying to activate the motor with a RFID scanner. The scanner waits for the token, and once it detects a token the motor turns and waits for a limit switch to be detected and stops the motor, then it does the same thing when it detects another RFID token but instead the motor travels in the opposite direction and waits for the opposite limit switch to be hit.
I have 2 sets of code. One is just the RFID scanner code which works fine, but it only switches a relay on and off. The other code is for the motor with 2 limit switches with a activation button. That code works too, and the draw opens and closes when you press a button, but it doesn't work with a RFID scanner. So my goal is to implement the RFID scanner code into the automated draw code in order to have a motor that turns and reverses with a RFID token and stops with a limit switch. I'm using an Arduino UNO board, 2 limit switches, a L298N H Bridge motor driver, and a MFRC522 RFID scanner.

Here is a schematic picture:
[![Schematic view of arduino board][1]][1]

Here is the code for the automated draw using 3 buttons (2 limit switch, 1 activation button) and the DC motor:

    // constants won't change. They're used here to set pin numbers:
    const int buttonPin = 4;     // the number of the pushbutton pin
    const int buttonPin3 = 1;     // the number of the pushbutton pin
    const int buttonPin2 = 2;     // the number of the pushbutton pin
    const int motorPin =  5;      // the number of the LED pin
    const int motorPin2 =  6;      // the number of the LED pin

    // variables will change:
    boolean buttonState = 0;         // variable for reading the pushbutton status
    boolean buttonState2 = 0;         // variable for reading the pushbutton status
    boolean buttonState3 = 0;   // variable for reading the pushbutton status

    int drawPosition = 2;  // Tells progam what position the draw is in

    /**
     *  setup inputs for switches and outs for motor pins
     *  serial begin to read the switches to test for errors
     */
    void setup() {
        // initialize the pin as an inputs:
        pinMode(motorPin, OUTPUT);
        pinMode(motorPin2, OUTPUT);
        // initialize the pushbutton pin as an input:
        pinMode(buttonPin, INPUT);
        pinMode(buttonPin2, INPUT);
        pinMode(buttonPin3, INPUT);
        Serial.begin(9600);
    }

    /**
     * this function turns motor foward
     */
    void drawForward() {
         // turn motor foward:
         digitalWrite(motorPin, LOW);
         digitalWrite(motorPin2, HIGH);
    }

    /**
     * this function turns motor backwards
     */
    void drawBackward() {
         // turn motor in other direction:
         digitalWrite(motorPin, HIGH);
         digitalWrite(motorPin2, LOW);
    }

    /**
     * Stop the motor form moving
     */
    void stopDrawFromMoving() {
      digitalWrite(motorPin, LOW);
      digitalWrite(motorPin2, LOW);

    }

    /**
     *
     */
    void loop() {
       // read the state of the pushbutton value:
         buttonState = digitalRead(buttonPin);
         buttonState2 = digitalRead(buttonPin2);
       buttonState3 = digitalRead(buttonPin3);

       // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
       if (buttonState == HIGH) {
          drawPosition = 2;
          Serial.println(F("Front button state is high draw is open"));
          stopDrawFromMoving();
       }else if (buttonState2 == HIGH) {
          drawPosition = 1;
          stopDrawFromMoving();
      }

      if (buttonState3 == HIGH) {
        if( drawPosition  == 1 ){
          drawBackward();
          delay(100);
          drawPosition = 2;
          delay(100);
        }else if (drawPosition == 2 ) {
          delay(100);
          drawForward();
          delay(100);
          drawPosition = 1;
        }

      }
    }

And that code you just read works fine, but it only activates the motor with a push button, but I'm trying to use RFID scanners.

Here is the code where I attempted to put the RFID code and the automated draw code together:

    #include <EEPROM.h>     // We are going to read and write PICC's UIDs from/to EEPROM
    #include <SPI.h>        // RC522 Module uses SPI protocol
    #include <MFRC522.h>  // Library for Mifare RC522 Devices

    //setting up inputs for limit switches and outputs for H Bridge motor driver
    const int buttonPin = 4;     // the number of the pushbutton pin
    const int buttonPin2 = 2;     // the number of the pushbutton pin
    const int motorPin =  6;      // the number of the motors H Bridge (L298N) pin
    const int motorPin2 =  5;      // the number of the motors H Bridge (L298N) pin

    // variables for the state of the limit switches
    boolean buttonState = 0;
    boolean buttonState2 = 0;
    int drawPosition = 2;  // Tells progam what position the draw is in

    //this is the function to be called inside the loop. it makes the motor turn foward
    void drawForward() {
      // turn H Bridge motor driver on in the foward polarity
      digitalWrite(motorPin, LOW);
      digitalWrite(motorPin2, HIGH);
    }
    // and this function turns the motor backwards
    void drawBackward() {
      // turn H Bridge on with the REVERSED polarity
      digitalWrite(motorPin, HIGH);
      digitalWrite(motorPin2, LOW);
    }
    //This function is called when the motor needs to STOP moving
    void stopDrawFromMoving() {
      //turn H Bridge motor driver OFF by turning both pins to LOW
      digitalWrite(motorPin, LOW);
      digitalWrite(motorPin2, LOW);
    }

    // Just stuff for the RFID to work
    boolean match = false;          // initialize card match to false
    boolean programMode = false;  // initialize programming mode to false
    int successRead;    // Variable integer to keep if we have Successful Read from Reader
    byte storedCard[4];   // Stores an ID read from EEPROM
    byte readCard[4];   // Stores scanned ID read from RFID Module
    byte masterCard[4];   // Stores master card's ID read from EEPROM
    #define SS_PIN 10
    #define RST_PIN 9
    MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.

    ///////////////////////////////////////// Setup ///////////////////////////////////
    void setup() {
      // Setting up the digital read for limit switches
      buttonState = digitalRead(buttonPin);
      buttonState2 = digitalRead(buttonPin2);

      //Protocol Configuration for RIFD scanner
      Serial.begin(9600);  // Initialize serial communications with PC
      SPI.begin();           // MFRC522 Hardware uses SPI protocol
      mfrc522.PCD_Init();    // Initialize MFRC522 Hardware
      // This sets the RFID range to Maximum
      mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
      Serial.println(F("BlueCore Tech Acces Control"));   // For debugging purposes

      // Check if master card defined, if not let user choose a master card
      if (EEPROM.read(1) != 143) {
        Serial.println(F("No Master Card Set"));
        Serial.println(F("Scan A RFID Card to Set as Master Card"));
        do {
          successRead = getID();            // sets successRead to 1 when we get read from reader otherwise 0
        }
        while (!successRead);                  // Program will not go further while you not get a successful read
        for ( int j = 0; j < 4; j++ ) {        // Loop 4 times
          EEPROM.write( 2 + j, readCard[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
        }
        EEPROM.write(1, 143);                  // Write to EEPROM we defined Master Card.
        Serial.println(F("Master Card Set"));
      }
      Serial.println(F("-------------------"));
      Serial.println(F("Master Card's UID = "));
      for ( int i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
        masterCard[i] = EEPROM.read(2 + i);    // Write it to masterCard
        Serial.print(masterCard[i], HEX);
      }
      Serial.println("");
      Serial.println(F("-------------------"));
      Serial.println(F("Everything Ready"));
      Serial.println(F("Waiting for Keys or cards to be scanned"));
      cycleLeds();    // Everything ready lets give user some feedback by cycling leds
    }
    ///////////////////////////////////////// Main Loop ///////////////////////////////////
    void loop () {

    //this first chunk of "if" is always setting the variable from iether "1" or "2" depending on what limit switch is closed, this allows the program to REMEMBER what the position of the draw is.
      if (buttonState == HIGH) {   //if the back limit switch is closed, the draw is in the closed (or backward) position
        drawPosition = 2;    //sets the variable to "2" meaning the draw is in the closed position
        Serial.println(F("Front button state is high so draw is open"));
        stopDrawFromMoving();  //this also stopes the motor form moving foward any further
      } else if (buttonState2 == HIGH) { // same principle applies here but its just reversed:
        drawPosition = 1;
        Serial.println(F("Back button state is high draw is open"));
        stopDrawFromMoving();
      }

    // THERE IS A ERROR HERE I CANNOT FIX ////////////////////////////////////////////////////////////////////////////THERE IS A ERROR HERE I CANNOT FIX/////////////////////////////////////////THERE IS A ERROR HERE I CANNOT FIX///////////////////////////////////////
    //   'getID' was not declared in this scope exit status 1      this happens anywhere inside the loop where there is a mention of the 'getID' function. I though this only happens if you calling a function but it doesnt exist, but it clearly does exist becuase its at the bottom
      do {
        successRead = getID();  // sets successRead to 1 when we get read from reader otherwise 0
        if (programMode) {
        }
        else {
          normalModeOn();     // Normal mode, blue Power LED is on, all others are off
        }
      }
      while (!successRead);   //the program will not go further while you not get a successful read
      if (programMode) {
        if ( isMaster(readCard) ) { //If master card scanned again exit program mode
          Serial.println(F("Master Card Scanned"));
          Serial.println(F("Exiting Programming Mode"));
          Serial.println(F("-----------------------------"));
          programMode = false;
          return;
        }
        else {
          if ( findID(readCard) ) { // If scanned card is known delete it
            Serial.println(F("I know this key, removing..."));
            deleteID(readCard);
            Serial.println("-----------------------------");
          }
          else {                    // If scanned card is not known add it
            Serial.println(F("I do not know this key, adding..."));
            writeID(readCard);
            Serial.println(F("-----------------------------"));
          }
        }
      }
      else {
        if ( isMaster(readCard) ) {   // If scanned card's ID matches Master Card's ID enter program mode
          programMode = true;
          Serial.println(F("Hello Master - Entered Programming Mode"));
          int count = EEPROM.read(0);   // Read the first Byte of EEPROM that
          Serial.print(F("I have "));     // stores the number of ID's in EEPROM
          Serial.print(count);
          Serial.print(F(" record(s) in DATABASE"));
          Serial.println("");
          Serial.println(F("Scan a Card or key to ADD or REMOVE"));
          Serial.println(F("-----------------------------"));
        }
        else {
          if ( findID(readCard) ) {  // If not, see if the card is in the EEPROM
            Serial.println(F("Welcome, Acces Granted"));
            //this is another part from the other code that im trying to implement into the RFID code
            if ( drawPosition  == 1 ) { //if the variale is saying the draw is currently in the FOWARD position
              drawBackward();  //then return it to the BACKWARD position
              delay(100);
              drawPosition = 2;  //then make the variable a "2" so the code remembers what the position of the draw is for next time the RFID scanner is activated
              delay(100);
            } else if (drawPosition == 2 ) {  //same principle under here but its just reversed for when the draw is found in the opposite position and needs to return to the opposite position
              delay(100);
              drawForward();
              delay(100);
              drawPosition = 1;
            }
          }
          else {   // If the token is unknown, show that the ID was not valid and dont do anything else
            Serial.println(F("Acces Denied!"));
          }
        }

      }
      ///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
      int getID() {
        // Getting ready for Reading PICCs
        if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue
          return 0;
        }
        if ( ! mfrc522.PICC_ReadCardSerial()) {   //Since a PICC placed get Serial and continue
          return 0;
        }
        // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
        // I think we should assume every PICC as they have 4 byte UID
        // Until we support 7 byte PICCs
        Serial.println(F("Scanned KEY's UID:"));
        for (int i = 0; i < 4; i++) {  //
          readCard[i] = mfrc522.uid.uidByte[i];
          Serial.print(readCard[i], HEX);
        }
        Serial.println("");
        mfrc522.PICC_HaltA(); // Stop reading
        return 1;
      }
      ///////////////////////////////////////// Show reader details ///////////////////////////////////
      void ShowReaderDetails() {
        // Get the MFRC522 software version
        byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
        Serial.print(F("MFRC522 Version: 0x"));
        Serial.print(v, HEX);
        if (v == 0x91)
          Serial.print(F(" = v1.0"));
        else if (v == 0x11)
          Serial.print(F(" = BlueCore Tech. RFID Acces v2.0"));
        else
          Serial.print(F(" (unknown)"));
        Serial.println("");
        // When 0x00 or 0xFF is returned, communication probably failed
        if ((v == 0x00) || (v == 0xFF)) {
          Serial.println(F("WARNING: Communication failure, is the RFID-MFRC522 properly connected?"));
          while (true); // do not go further
        }
      }
      //////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
      void readID( int number ) {
        int start = (number * 4 ) + 2;    // Figure out starting position
        for ( int i = 0; i < 4; i++ ) {     // Loop 4 times to get the 4 Bytes
          storedCard[i] = EEPROM.read(start + i);   // Assign values read from EEPROM to array
        }
      }
      ///////////////////////////////////////// Add ID to EEPROM   ///////////////////////////////////
      void writeID( byte a[] ) {
        if ( !findID( a ) ) {     // Before we write to the EEPROM, check to see if we have seen this card before!
          int num = EEPROM.read(0);     // Get the numer of used spaces, position 0 stores the number of ID cards
          int start = ( num * 4 ) + 6;  // Figure out where the next slot starts
          num++;                // Increment the counter by one
          EEPROM.write( 0, num );     // Write the new count to the counter
          for ( int j = 0; j < 4; j++ ) {   // Loop 4 times
            EEPROM.write( start + j, a[j] );  // Write the array values to EEPROM in the right position
          }
          successWrite();
          Serial.println(F("Succesfully added ID record to DATABASE"));
        }
        else {
          failedWrite();
          Serial.println(F("Failed! There is something wrong with ID or bad DATABASE"));
        }
      }
      ///////////////////////////////////////// Remove ID from EEPROM   ///////////////////////////////////
      void deleteID( byte a[] ) {
        if ( !findID( a ) ) {     // Before we delete from the EEPROM, check to see if we have this card!
          failedWrite();      // If not
          Serial.println(F("Failed! There is something wrong with ID or bad DATABASE"));
        }
        else {
          int num = EEPROM.read(0);   // Get the numer of used spaces, position 0 stores the number of ID cards
          int slot;       // Figure out the slot number of the card
          int start;      // = ( num * 4 ) + 6; // Figure out where the next slot starts
          int looping;    // The number of times the loop repeats
          int j;
          int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
          slot = findIDSLOT( a );   // Figure out the slot number of the card to delete
          start = (slot * 4) + 2;
          looping = ((num - slot) * 4);
          num--;      // Decrement the counter by one
          EEPROM.write( 0, num );   // Write the new count to the counter
          for ( j = 0; j < looping; j++ ) {         // Loop the card shift times
            EEPROM.write( start + j, EEPROM.read(start + 4 + j));   // Shift the array values to 4 places earlier in the EEPROM
          }
          for ( int k = 0; k < 4; k++ ) {         // Shifting loop
            EEPROM.write( start + j + k, 0);
          }
          successDelete();
          Serial.println(F("Succesfully removed ID record from DATABASE"));
        }
      }
      ///////////////////////////////////////// Check Bytes   ///////////////////////////////////
      boolean checkTwo ( byte a[], byte b[] ) {
        if ( a[0] != NULL )       // Make sure there is something in the array first
          match = true;       // Assume they match at first
        for ( int k = 0; k < 4; k++ ) {   // Loop 4 times
          if ( a[k] != b[k] )     // IF a != b then set match = false, one fails, all fail
            match = false;
        }
        if ( match ) {      // Check to see if if match is still true
          return true;      // Return true
        }
        else  {
          return false;       // Return false
        }
      }
      ///////////////////////////////////////// Find Slot   ///////////////////////////////////
      int findIDSLOT( byte find[] ) {
        int count = EEPROM.read(0);       // Read the first Byte of EEPROM that
        for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
          readID(i);                // Read an ID from EEPROM, it is stored in storedCard[4]
          if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
            // is the same as the find[] ID card passed
            return i;         // The slot number of the card
            break;          // Stop looking we found it
          }
        }
      }
      ///////////////////////////////////////// Find ID From EEPROM   ///////////////////////////////////
      boolean findID( byte find[] ) {
        int count = EEPROM.read(0);     // Read the first Byte of EEPROM that
        for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
          readID(i);          // Read an ID from EEPROM, it is stored in storedCard[4]
          if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
            return true;
            break;  // Stop looking we found it
          }
          else {    // If not, return false
          }
        }
        return false;
      }
      ///////////////////////////////////////// Write Success to EEPROM   ///////////////////////////////////
      void successWrite() {
        Serial.println(F("Write to EEPROM is Succsusful"));
      }
      ///////////////////////////////////////// Write Failed to EEPROM   ///////////////////////////////////
      void failedWrite() {
        Serial.println(F("Failed to write to EEPROM"));
      }
      ///////////////////////////////////////// Success Remove UID From EEPROM  ///////////////////////////////////
      void successDelete() {
        Serial.println(F("Removed from EEPROM"));
      }
      ////////////////////// Check readCard IF it is masterCard   ///////////////////////////////////
      // Check to see if the ID passed is the master programing card
      boolean isMaster( byte test[] ) {
        if ( checkTwo( test, masterCard ) )
          return true;
        else
          return false;
      }

So there's 2 main errors in the second code (the code implementing RFID with my limit switch logic and motor functions.)
The first one was quite obvious in the code when I said "ERROR HERE" and the error is a "exit status 1 getID was not declared in this scope." Not sure why this happens, I cant make sense of it.
Once that's fixed I can look at the main issue, and that's actually making it work. I have tested the code before I was getting that exit status error and the logic wasn't working. There is probably a better way of putting these to bits of code together but I'm fairly new to programing and I cant figure it out.

Thanks so much for your help  ( :

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

body:
C++ and C only reads function declarations and globals from top to bottom, it will not look ahead to see if any others were defined.

You can put a declaration of the functions you want to use above where you want to use it.

    //...
    int getID();
    ///////////////////////////////////////// Main Loop ///////////////////////////////////
    void loop () {
    //...


message:
How do I get LEDs to turn on according to a continuous Python input?

I'm trying to make a tuner. 3 LEDs are connected to the Arduino board, each one corresponding to one situation (too high, low or correct).

Python handles the detecting of a note according to the mic input, and determines which led should be turned on, but as it's a live tuner, Python sends the information pretty fast.

I've figured out how to turn a led on one at a time and keep it on as long as the input doesn't change, but it only works at a low speed when I do it manually, with a Python program like this :

    code=1
    while code!=0:
        code=input("Code?")
        ser.write(code.encode('utf-8'))

If I try it with a Python code such as :

    code= '5'
    while 1:
    ser.write(code.encode('utf-8'))

then the LEDs just stay off.

Here is my Arduino Code :

    int hauteur = 0;

    void setup() {
        pinMode (2, OUTPUT); //red pin
        pinMode (6, OUTPUT); //green pin
        pinMode (5, OUTPUT); //yellow pin
        Serial.begin(9600);
    }

    void loop() {
        if(Serial.available ()) {
            hauteur = Serial.parseInt();

            while (hauteur==2) {
                (digitalWrite(2,HIGH));
                if (Serial.available ()) { hauteur=Serial.parseInt(); }
            }
            digitalWrite(2,LOW);

            while (hauteur==5){
                (digitalWrite(5,HIGH));
                if (Serial.available ()) { hauteur=Serial.parseInt(); }
            }
            digitalWrite(5,LOW);

            while (hauteur==6){
                (digitalWrite(6,HIGH));
                if (Serial.available ()) { hauteur=Serial.parseInt(); }
            }
            digitalWrite(6,LOW);

            Serial.flush();
        }
    }

If 2, 5 or 6 are received with enough time in between them, then the board does what it's supposed to do and turns on the according LED. How can I reduce that necessary lapse of time to get a real time change of lights like a live tuner?

body:
You don't need to parseInt for one digit. Use Serial.read().

      hauteur = Serial.read() - 48; // 48 is ascii code of '0'

or better send bytes from python, not digit characters