message:
NodeMCU: Wiegand not working for one device, while working for another

I'm using a NodeMCU, and a working code for reading Wiegand data, with [this library](https://github.com/paulo-raca/YetAnotherArduinoWiegandLibrary).

I managed to successfully read the Wiegand signal from [this device](https://www.aliexpress.com/item/32888710502.html).

However, I also have this [new AR-721H device](http://www.soyal.com/product.php?act=view&id=23), and I can't get the Wiegand to work. This is the [manual for the device](http://www.soyal.com/data/files/download/manual/321H-331H-721H-725H-757H-en.pdf).

There is absolutely nothing coming to the mcu. Everything is wired identically as the working device.

According to the manual, everything should be working, but I am at a loss.

**Can someone please tell me what I might be doing wrong?**

The store clerk told me something about needing a controller that converts RS485 to RS232, but I have no idea what that means. I already made it work with another device...

body:
It's quite cryptic from the little information in that (somewhat chaotic) "manual", but I interpret it that the Wiegand interface is an *input* port, not an *output* port.  It is intended to connect that port to an external card reader or keypad as a remote interface (typically the other side of the door to this unit).

For communication with your Arduino you should use the RS-485 interface. For that you need an MAX485 breakout board.


sender: user

message:
Check if a set of events occur in a limited time period

I am making a project in which I am using 4 Infrared sensors to take an input. The way I want it to work is such that when one of the sensors is triggered, the code listens for input from the other sensors for a fixed amount of time (say 2 seconds). Based on this data, further functions are executed.

I am assigning a number to each of the sensors, and the sequence in which they are triggered is stored in an array like:

    // All relevant pins of the IR sensors are set to input with names ir1,ir2,ir3,ir4
    int sequence[] = {0,0,0,0}
    int s1 = digitalRead(ir1); //and similarly for all other pins
    int counter = 0;

    if(s1==1){
      sequence[counter] = 1; //similarly 2 for s2 and so on
      counter ++;
    }

What I am attempting to do is something like this:

    if(s1 == 1 || s2==1 || s3 == 1 || s4 == 1){
       if(s1 == 1){
          sequence[counter] = 1;
          counter ++;

       //Start listening for other sensors
       } // similarly check which sensor is triggered first

       //Allow 2 seconds for input from all sensors (no input from either one of them is also allowed)
       // After 2 seconds execute some code based on the sequence array which got updated from inputs by different sensors
    }

How do I accomplish this?

sender: assistant

body:
Here's some pseudocode that might help:

       if millis() - start time >= 2000
             time is up, do what you want with the sequence so far
             maybe a boolean flag here so you only do it once
       if any button is pressed
          if counter == 0
              set start time = millis() // start the timer
              set first in sequence
          else
              add the button to the sequence


message:
How do I set up an ATTiny861A-PU for flashing with Arduino Uno?

I have found instructions for 8 pin Tiny but none for my 20 pin. How do I set this chip up on the breadboard for bootloading with Arduino?

body:
The principle is the same, it's all only ISP (In System Programming), and nothing different from any other microcontroller, that uses ISP. Look at the descriptions of the used pins for the 8-pin Attinys, then connect the pins with the same description on your 20-pin chip.

Namely you have to connect the pins MOSI, MISO, SCK, RESET, VCC and GND. MOSI and MISO are the data lines, SCK the clock signal. If you look into a pinout diagram or - even better - at the pin configuration diagram in the chips datasheet, you will see pins, that are marked this way. The rest of the pins is pretty much self explaining.

---

Since you are using an Uno as programmer and didn't have a capacitor between Reset and ground of the programmer, I will explain, why this capacitor is needed here.

The Atmega328p on the Uno doesn't have a native USB interface. So in order to connect it via USB to a PC, there is another microcontroller on the Uno (on original board the Atmega16U2), which has a native USB interface. This microcontroller then is the middleman between Atmega328P and PC. It connects to the Serial (UART) interface of the 328P and translates that to USB communication.

Everytime that the corresponding serial port is opened on the PC, the PC sends a DTR signal, which is connected to the 328P's reset pin. So, when the Arduino IDE tries to connect to the Serial port for flashing the Attiny, the Uno get's resetted and hence cannot flash the Attiny.

The capacitor between Reset and Ground will hold the Reset pin high for long enough, so that this reset does not happen and the Uno can do it's duty.

On Arduino boards with native USB interface this is not necessary, since they don't have this hardwired connection to a reset and they communicate directly over USB.


message:
Trying to light an LED with one Button and have no idea what is wrong

New to Arduino. I am trying to use a single button to light and turn off a single LED. I followed an [online tutorial (youtube video)][1] and changed the code just a bit. I know it is for two LEDs but I tried it for one. I have no idea why it is not working. I don't see why it doesn't make sense but it just does not work.

Here is the code:
<!-- language-all: lang-cpp -->

    float LengthPush = 0; // LengthPush is the amount of time the button has been pressed.

    int ShortPush = 100; // 100 ms push. Supposed to turn on the LED.
    int LPush = 1000; // 1000 ms push. Supposed to turn it off.

    int ButtonPin = 2;
    int RLED = 13;

    void setup() {
      // put your setup code here, to run once:
      pinMode(ButtonPin, INPUT_PULLUP);
      pinMode(RLED, OUTPUT);

      Serial.begin(9600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      while (digitalRead(ButtonPin) == LOW) {
        delay(100);
        LengthPush = LengthPush + 100;

        Serial.print("ms = ");
        Serial.println(LengthPush);
      }

      if (LengthPush >= LPush) {
        digitalWrite(RLED, LOW);
      } else if (ShortPush <= LengthPush < LPush) {
        digitalWrite(RLED, HIGH);
      }
      LengthPush = 0;
    }

  [1]: https://www.youtube.com/watch?time_continue=913&v=IsDzxtaZCoI

body:
I think your problem lies in the else-if-statement, where you try to compare 3 different values. While this doesn't thrown a compiling error in my Arduino IDE, it will probably not do, what you are trying to achieve.

Instead you need to compare `LengthPush` with one value and then with the other. You can even do this inside the same if statement:

    if(ShortPush <= LengthPush && LengthPush < LPush)

The `&&` is the boolean AND operator, which means, that the if statement will be executed, if both statements around it will evaluate as `true`.

---

I'm not sure, what actually happens with your original code, since it doesn't throw a compilation error. It might be (and that's my theory here), that the program will first evaluate `ShortPush <= LengthPush` and then compare the result to `LPush`. Since boolean values evaluate as `0` or `1` in integer calculations, that messes up the whole intent of this. Take the case, that `LengthPush` is really in the required interval. Then the first part will evaluate as `true`, which means `1` as integer. Then this `1` get's compared to `LPush`, which is always higher, so the overall result is true. But the same result comes, when `LengthPush` is smaller than `ShortPush`.


message:
Attempting to monitor serial output for a string to trigger function, apparently matching string is output but the function doesn't trigger

I'm working on my second Arduino project, and am somewhat stuck.

I'm running a PIR module from my Arduino Uno with the following sketch:

    /*
     *  PIR Sensor test
     */

     int pirPin = 6;

     int minSecsBetweenEmails = 60; // 60 seconds

     long lastSend = -minSecsBetweenEmails * 1000l;

     void setup()
     {
      pinMode(pirPin, INPUT);

      Serial.begin(9600);
     }

     void loop() {
      long now = millis();
      if (digitalRead(pirPin) == HIGH)
        {
           if (now > (lastSend + minSecsBetweenEmails * 1000l))
            {
                Serial.println("MOVEMENT");
                lastSend = now;
            }
          else
            {
              Serial.println("Too soon");
            }
        }
            delay(500);
     }

I'm monitoring the COM3 port using the following in JupyterLab with PySerial.

    import time
    import serial
    import smtplib

    to = 'myemail@myemail.com'
    GMAIL_USER = 'myemail@myemail.com'
    GMAIL_PASS = '**********'

    SUBJECT = 'MOTION pir'
    TEXT = 'PIR sensor detected motion'

    ser = serial.Serial('COM3', 9600)

    def send_email():
        print("Sending Email")
        smtpserver = smtplib.smtp("smtp.gmail.com",587)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo
        smtpserver.login(GMAIL_USER, GMAIL_PASS)
        header = str('To:' + TO + '\n' + 'From: ' + GMAIL_USER)
        header = header + '\n' + 'Subject:' + SUBJECT + '\n'
        print (header)
        msg - header + '\n' + TEXT + ' \n\n'
        smtpserver.sendmail(GMAIL_USER, TO, msg)
        smtpserver.close()

    while True:
            message = ser.readline()
            print(message.decode('utf-8'))
            if message[0] == 'MOVEMENT' :
                send_email()
                time.sleep(0.5)

I believe my problem is with the `ser.readline()` function. I've been reading the docs, they seem to say I need to provide some kind of endpoint or timeout for the function to provide for EOF, but my goal was to have the

    if message [0] == 'MOVEMENT' :

continuously evaluate the output lines from COM3...

Any input at all would be very much appreciated.

EDIT: Thanks to all three of you for your help! By changing the Python as shown below I was able to fulfill the `if message[0] == 'MOVEMENT' :`statement

Python should have been:

    import time
    import serial
    import smtplib

    to = 'myemail@myemail.com'
    GMAIL_USER = 'myemail@myemail.com'
    GMAIL_PASS = '**********'

    SUBJECT = 'MOTION pir'
    TEXT = 'PIR sensor detected motion'

    ser = serial.Serial('COM3', 9600)

    def send_email():
        print("Sending Email")
        smtpserver = smtplib.smtp("smtp.gmail.com",587)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.ehlo
        smtpserver.login(GMAIL_USER, GMAIL_PASS)
        header = str('To:' + TO + '\n' + 'From: ' + GMAIL_USER)
        header = header + '\n' + 'Subject:' + SUBJECT + '\n'
        print (header)
        msg - header + '\n' + TEXT + ' \n\n'
        smtpserver.sendmail(GMAIL_USER, TO, msg)
        smtpserver.close()

    while True:
            message = ser.readline()
            print(message)
            if message == b'MOVEMENT\r\n' :
                send_email()
                time.sleep(0.5)

body:
You're confusing `readlines()` with `readline()`.  The former returns an array of lines, the latter a single line.  You need to drop the `[0]` since you're not working with an array of lines, and you need to include the line endings that the Arduino sends:

    while True:
        message = ser.readline()
        print(message.decode('utf-8'))
        if message == 'MOVEMENT\r\n' :
            send_email()
            time.sleep(0.5)


message:
Using the Broadcom AFBR-S50 with Arduino

I'm trying to interface with a Broadcom [AFBR-S50MV85G][1] ToF sensor over SPI using an Arduino, which is complicated by the fact that the provided library and reference application is written for Cortex M0-based NXP microcontrollers. The documentation says that implementing the SPI, IRQ, Debug and Timer interfaces would allow use with other platforms, but it doesn't explicitly state which functions require implementations, or if all of them do, and it's not demarcated within the source code either.

The documentation lists the available command words, but no register addresses, which I believe are used by the platform-independent compiled libraries that come with it. This leaves me with no way to interface manually over SPI, meaning that my only choice appears to be to attempt to implement the platform drivers myself, which will probably take me a significant amount of time.

Is there something else I should try before sinking time into something that may not give me results? Has anyone here used this sensor before, and if so, could you point me in the right direction?

P.S.: The documentation I'm referring to is included in the SDK provided in the downloads section of the product page, and I'm not sure I'd be allowed to rehost it somewhere else in order to link it here.

  [1]: https://www.broadcom.com/products/optical-sensors/time-of-flight-3d-sensors/afbr-s50mv85g

body:
I recently looked into this again, and it turns out that Broadcom had released a [porting guide][1] for this library in August 2020 (nearly a year after I originally posted this question) that should prove useful to anyone trying to make use of this sensor. It's for the STM32 platform, not Arduino, but it's the most detail Broadcom has provided with regards to this product, and should provide a starting point at least.

I happen to have access to the Nucleo board used in the guide, but I had some issues with following it in some cases due to some differences in the SDK file/directory structure. I did eventually get a passing build out of it, but couldn't get anything out of the sensor itself, which means that I either did something wrong, or had damaged the sensor in my earlier attempts to interface with it; at the time of my last attempt, I was leaning towards the latter. I don't think I'll be revisiting this unit any time soon, so hopefully others will have better luck. And if anyone does get it working, please do report back; I'm curious to know if I'd actually be able to use this thing if I were to buy another one.

P.S: I'm not marking this as answered because a) my question was technically for the Arduino, and b) I haven't been able to confirm that this is working.

  [1]: https://docs.broadcom.com/doc/AFBR-S50-PG


body:
I also have been digging for information about the AFBR-S50MV85G and similar sensors for the past week.

Well, I am trying to port it to ATxmegas (ICs that are similar to those ATmegas used in the Arduino Family), but I decided to post my findings here because this is the first forum topic that I have found about this sensor family.

As Joseph mentioned, Broadcom has released a porting guide to Arm devices, but it does not help at all when it comes to porting to other microcontrollers.
Additionally, the minimum requirements of this lib according to Broadcom's [porting guide][1] are:

> Minimum memory requirements:
>    RAM: 8kByte (4kByte Heap + 4kByte Stack)
>    ROM/Flash: 128 kByte

Because of that and other facts, I also conclude that it is not possible to port the available libraries to 8-bit microcontrollers nor develop a new one due to the lack of description about the SPI register structure.

  [1]: https://broadcom.github.io/AFBR-S50-API/porting_guide.html


message:
Arduino UNO and RS485 Communication Problem

I am learning Arduino, a beginner in programming. I want to use Arduino UNO to connect a wind direction sensor RS485. The problem is the output in the serial monitor, the return data from the wind direction sensor is unstable.
[![enter image description here][1]][1]

I need to get the return data from the wind direction sensor to get the wind direction. From the factory manual, they said sent a data to the sensor: 0x01 0x03 0x00 0x00 0x00 0x02 0xC4 0x0B and the sensor will return, like 0x01 0x03 0x04 0x06 0x48 0x00 0xA0 0x7A 0xD5

The wind direction dat at the above 5 and 6 position, the 0x00 0xA0 => 00A0H(HEX)=160 degree.

**Tools:**
Arduino Uno Board

Wind Direction Sensor
http://www.jnrsmcu.com/equipment/299.html

RS485 Board (3.3V)
https://www.waveshare.com/rs485-board-3.3v.htm

**The following is my coding:**

```c++
#include <SoftwareSerial.h>

SoftwareSerial RS485Serial(10, 11); // RX, TX

void setup()
{
    RS485Serial.begin(4800);   // set the data rate
    Serial.begin(4800);
    Serial.println("Start");

    pinMode(12, OUTPUT);
    digitalWrite(12, HIGH);  // Init Transceiver
}

byte buf[8];

int byteReceived;

void loop()
{
    digitalWrite(12, HIGH);

    byte wind[] = {0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0xC4, 0x0B};
    RS485Serial.write(wind, sizeof(wind));
    Serial.flush();
    RS485Serial.flush();
    // Serial.print(wind[0], HEX);
    Serial.println("Send");

    digitalWrite(12, LOW);
    delayMicroseconds(200);

    RS485Serial.readBytes(buf, 8);
    delay(10);
    Serial.println(buf[0], HEX);
    Serial.println(buf[5], HEX);
    Serial.println(buf[6], HEX);
    Serial.flush();
    RS485Serial.flush();
    delay (1000);
}
```

**Connection map:**
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/M6shx.png
  [2]: https://i.stack.imgur.com/8frDw.png

body:
I would suggest you simplify your setup to the point where you have a 'working baseline  configuration', and then start building the system up one step at a time from there.

Start by eliminating the SoftwareSerial interface as a possible contributor to the problem.  Get an Arduino Mega with multiple hardware serial ports.

Next, verify that you can send characters to the selected hardware serial port and receive those same characters back when the Txn and Rxn lines (the 'n' here is the selected hardware serial port number) are connected via a jumper wire. This is called a 'loopback' configuration and is a basic serial comms troubleshooting technique (software serial ports don't support simultaneous transmit and receive, so they don't support loopback testing).  Don't proceed until you have this step completed successfully.

Next, get a second RS-485 module and extend your previous 'loopback' configuration with the hardware serial port on the Mega to include the two RS-485 modules.  Then you should be able to send characters out to one RS-485 module and receive the same characters back from the other, by connecting TXn to DI on one of the two RS-485 modules, and Rxn to DO on the other.

At this point you will have verified all the communications connections, so you can be confident that whatever you send will actually show up at the DO port of the RS-485, and whatever shows up at the DI port of the RS-485 will actually make it back to your serial console.  Now you can connect the sensor and figure out any issues do to data formatting, command sequences, and the like.

This basic 'cut the problem in half' building block technique will work on any system, large or small, simple or complex.

Frank


body:
- I don't see any connection between the sensor's GND and your Arduino's. This is likely the problem if they're not connected, since a common GND is necessary even with RS-485.
- Check the sensor's power supply, make sure it's actually within the advised 10-30 V range. Also check the polarity of the differential lines.
- Have you tried using the provided configuration software?
- `flush()` does nothing for `SoftwareSerial` ports since they have no TX buffer, so you can just get rid of those lines, including the unnecessary `Serial.flush()`
- Finally, your device datasheet says to wait for at least 200 *milliseconds* not microseconds, before checking for a response. Though it really shouldn't matter since you're using `readBytes()` after that, which waits for a second anyways by default, before giving up. Instead, use a bigger buffer, say 20 bytes, then try to read just 8 (the expected length) into it with `readBytes()`:

        byte buf[20];
        int rlen = RS485Serial.readBytes(buf, 8);

Then try to print `rlen` which tells you how many bytes were actually read and also print the whole response to verify the packet format is as it should be. You should get enough info from this to at least eliminate a bunch of possible problems.


message:
Output 3.3V when setting pin to high

I would like to pass 3.3V and Ground to an component. How can I achieve such a thing?

I for example would like to let a wire get 3.3V when I for example do digitalWrite(pin, HIGH). It is hard for me to explain this, so I created an illustration in the hope of better clarifying it.

Edit: I have an product that I have dismantled. On the PCB, there is a push button. I would like to solder some wires to the place where the button is so it can be controlled with an arduino (probably wemos d1). When plugging a cable in the 3.3v of the arduino and a cable from the ground, when connecting it to the push button it will cause a boot of the dismantled product. This explains why I would like to give power to a component ONLY when a pin is set high, so I can for example boot the product via a website / app eventually.

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

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

body:
The normal way is to use a P-channel MOSFET as a "high side" switch.

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

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

<!-- End schematic -->

R1 keeps it switched off under "normal" circumstances.  Driving D4 LOW makes M1 turn on and allow power through to the "component".

Make sure that the MOSFET has a threshold voltage of no more than (less than?) -3V (that is, somewhere between 0V and -3V - note: P-channel MOSFETs have their thresholds quoted as a negative voltage).

You could connect R1 to 3.3V instead of 5V, but since the  GPIO would have 5V on it when HIGH it would be wasting power while idling - so it's better to pull it to 5V instead.


message:
Class member variable would not update

Code would not update variable inside drive method. The variable is updated inside the drive method, but it doesn't change in the rest of the class. I wrote a simple similar method in normal C++ and the variable actually updated in the rest of the class.

engine.hpp
```cpp
#pragma once
#include <Arduino.h>

namespace engine
{
class Engine
{
public:
    Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward);
    void drive(unsigned int t_speed, bool t_isForward = true);
    bool isMovingForward() const;
    void stop();

private:
    const unsigned char m_motor;
    const unsigned char m_forward;
    const unsigned char m_backward;

    // Movements
    bool m_isActive;
    bool m_isForward;
    unsigned int m_speed;
};
} // namespace engine
```

engine.cpp init list
```cpp
Engine::Engine(const unsigned char t_motor, const unsigned char t_forward, const unsigned char t_backward)
    : m_motor(t_motor),
      m_forward(t_forward),
      m_backward(t_backward),
      m_isActive(false),
      m_isForward(true),
      m_speed(0U)
{
}
```

drive method
```cpp
void Engine::drive(unsigned int t_speed, bool t_isForward)
{

    if (!m_isActive || m_isForward != t_isForward)
    {
        stop();

        // Set direction
        if (t_isForward)
        {
            digitalWrite(m_forward, HIGH);
            digitalWrite(m_backward, LOW);
        }
        else
        {
            digitalWrite(m_forward, LOW);
            digitalWrite(m_backward, HIGH);
        }

        m_isActive = true;
        m_isForward = t_isForward;
    }

    if (m_speed != t_speed)
    {
        m_speed = t_speed; // Updated here
        analogWrite(m_motor, t_speed);
    }
}
```

body:
I figured it out.

I was passing the engine objects as references instead of pointers.

main.cpp
```cpp
// Engines
engine::Engine
    engine1(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    engine2(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    engine3(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    engine4(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);
```

engine_controller.cpp init list
```cpp
EngineController::EngineController(engine::Engine &t_e1, engine::Engine &t_e2, engine::Engine &t_e3, engine::Engine &t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}
```

The solution would be to use dynamic memory allocation.

main.cpp
```cpp
// Engines
engine::Engine
    *engine1 = new engine::Engine(motors::Constants::MOTOR_1, motors::Constants::MOTOR_1_FORWARD, motors::Constants::MOTOR_1_BACKWARD),
    *engine2 = new engine::Engine(motors::Constants::MOTOR_2, motors::Constants::MOTOR_2_FORWARD, motors::Constants::MOTOR_2_BACKWARD),
    *engine3 = new engine::Engine(motors::Constants::MOTOR_3, motors::Constants::MOTOR_3_FORWARD, motors::Constants::MOTOR_3_BACKWARD),
    *engine4 = new engine::Engine(motors::Constants::MOTOR_4, motors::Constants::MOTOR_4_FORWARD, motors::Constants::MOTOR_4_BACKWARD);
```

engine_controller.cpp init list
```cpp
EngineController::EngineController(
    engine::Engine *t_e1, engine::Engine *t_e2,
    engine::Engine *t_e3, engine::Engine *t_e4)
    : m_engine1(t_e1),
      m_engine2(t_e2),
      m_engine3(t_e3),
      m_engine4(t_e4),
      m_currentSpeed(EngineControllerConsts::MAX_SPEED),

      // Directions
      m_rights(0),
      m_lefts(0),

      m_rightDistance(-1),
      m_leftDistance(-1),

      m_lastForward(true),
      m_counter(0),

      m_lastForward1(true),
      m_lastForward2(true),
      m_turnsCounter(0)

{
}
```


message:
Cannot convert 'int (*)[size]' to 'int**'

Analyzing [this][1] and [this][2] answers under Arduino, which should be the proper way to pass a 2D array into a function?

The function should be applicable to different sizes of 2D arrays.

    // NOT COMPILING EXAMPLE
    void f(int** x,const int m, const int n){
    // access x as x[0][0], x[0][1], etc...
    }

    void main{}{
        int x1[16][128];
        f(x1,16,128);
        int x2[64][16];
        f(x2,64,16);
    }

  [1]: https://stackoverflow.com/questions/34188355/cannot-convert-int-size-to-int
  [2]: https://stackoverflow.com/questions/5329107/passing-a-pointer-representing-a-2d-array-to-a-function-in-c

body:
According the prototype of `f` and the usage pattern for its `x`
argument, the function expects this argument to be a pointer to the
first element of an array of pointers to the first elements of arrays of
`int`. However, the matrix in `main()` is defined as an array of arrays
of `int`. If you try to pass this to a function, the matrix will decay
into a pointer to an array of `int`. That's not what you want.

If you want both dimensions of the matrix to be variable, the only
simple solution I see is to build an extra array of pointers (pointing
to the matrix rows) and pass _that array_ to the function

```c++
int main() {
    int x[16][128];

    // Build an array of pointers to rows.
    int *px[16];
    for (int i = 0; i < 16; i++)
        px[i] = x[i];

    f(px, 16, 128);
}
```

For more information on this, see the section [Arrays and Pointers][] in
the C FAQ, and more specifically the questions 6.16 (_How can I
dynamically allocate a multidimensional array?_) and 6.19 (_How do I write
functions which accept two-dimensional arrays when the width is not
known at compile time?_).

[Arrays and Pointers]: http://c-faq.com/aryptr/index.html


message:
How to send UDP data packet between two access point?

I am new to arduino programming and nodeMcu boards.I have two ESP8266 bards as access points and one board get some data form WiFi stations and resend that data to other access point. but the problem is second access point didn't receive any data packet from first access point.

This is the code of Access point which collect data and resend it to upper level Access point. This Access point successfully received the data from the WiFi stations.

    const char *ssid1 ="SecondAP";
    const char *pwd1 = "12345678910";

    const char *ssid2 ="FirstAP";
    const char *pwd2 = "123456789101";

    ESP8266WiFiMulti WiFiMulti;

    IPAddress local_IP(192,168,4,10);
    IPAddress gateway(192,168,4,9);
    IPAddress subnet(255,255,255,0);
    IPAddress NextAP(192,168,4,9);
    StaticJsonDocument<200> doc;
    unsigned int locPort1 = 1000;
    unsigned int locPort2 = 2000;
    WiFiUDP udp1;
    WiFiUDP udp2;
    char packetBuffer[100];
    IPAddress addrs;

    void setup() {

      Serial.begin(9600);
      delay(10);
      Serial.println('\n');

      ConnectToAP();
      delay(1000);
      EnableAP();
      delay(1000);

      udp1.begin(locPort1);
      udp2.begin(locPort2);
    }

    void loop() {

    int Icb = 0;

      Icb = udp1.parsePacket();

      if(Icb > 0){
          GetSensorDataPacket();
          Icb = 0;
        }
    }

    void EnableAP(){

      WiFi.softAPConfig(local_IP, gateway, subnet);
      WiFi.softAP(ssid2 , pwd2);
      delay(1000);

      Serial.print("Access Point \"");
      Serial.print(ssid2);
      Serial.println("\" started");
      Serial.print("IP address:\t");
      Serial.println(WiFi.softAPIP());
    }

    void ConnectToAP(){

      WiFi.mode(WIFI_STA);
      WiFiMulti.addAP(ssid1, pwd1);

      Serial.print("Connecting to ...........");
      Serial.print(ssid1); Serial.println("...");

      int i = 0;
      while (WiFiMulti.run() != WL_CONNECTED) {

       delay(1000);
       Serial.print(++i); Serial.print(' ');
      }

      Serial.println('\n');
      Serial.println("Connection established!");
      Serial.print("IP address:\t");
      Serial.println(WiFi.localIP());
    }

    void GetSensorDataPacket(){

      Serial.println("GetSensorDataPacket Function");
      udp1.read(packetBuffer,100);
      DeserializationError error = deserializeJson(doc, packetBuffer);

      IPAddress ClientAddrs = udp1.remoteIP();

      double SensorData = doc["SensorData"];
      int ClientID = doc["ID"];

      delay(1000);
      Serial.println();
      Serial.print("Sensor reading = ");
      Serial.println(SensorData);
      Serial.print("Client ID = ");
      Serial.println(ClientID);

      SendDataToNextAP(SensorData,ClientID);
    }

    void SendDataToNextAP(double Sensor_Data,int Client_ID){

      StaticJsonDocument<500> jsonBuffr;
      Serial.println("I'm in SendDataToNextAP Function");

      udp2.beginPacket(NextAP, locPort1); //gateway
      JsonObject Sob1 = jsonBuffr.to<JsonObject>();
      Sob1["SensorData"] = Sensor_Data;
      Sob1["ID"] = Client_ID;
      serializeJson(jsonBuffr, udp2);

      udp2.println();
      udp2.endPacket();

      delay(1000);
    }

  This is the code of upper Access point which should receive data packet from first access point but didn't receive any data from the first access point.

    const char *ssid = "SecondAP";
    const char *pwd = "12345678910";
    ESP8266WiFiMulti WiFiMulti;

    IPAddress local_IP(192,168,4,9); // Ip address of this node
    IPAddress gateway(192,168,3,1);
    IPAddress subnet(255,255,255,0);

    StaticJsonDocument<200> doc;
    unsigned int locPort1 = 1000;
    WiFiUDP udp1;
    char packetBuffer[100];

    void setup() {

      Serial.begin(9600);
      delay(10);
      Serial.println('\n');

      EnableAP();
      udp1.begin(locPort1);
      delay(1000);
    }

    void loop() {

    int Icb = 0;

      Icb = udp1.parsePacket();
      if(Icb > 0){
          Serial.println("Got a Udp packet");
          GetSensorDataPacket();
        }
    }

    void EnableAP(){

      WiFi.softAPConfig(local_IP, gateway, subnet);
      WiFi.softAP(ssid,pwd);
      delay(1000);

      Serial.print("Access Point \"");
      Serial.print(ssid);
      Serial.println("\" started");
      Serial.print("IP address:\t");
      Serial.println(WiFi.softAPIP());
    }

    void GetSensorDataPacket(){

      Serial.println("GetSensorDataPacket Function");
      udp1.read(packetBuffer,100);
      DeserializationError error = deserializeJson(doc, packetBuffer);

      IPAddress ClientAddrs = udp1.remoteIP();

      double SensorData = doc["SensorData"];
      int ClientID = doc["ID"];

      delay(1000);
      Serial.println();
      Serial.print("Sensor reading = ");
      Serial.println(SensorData);
      Serial.print("Client ID = ");
      Serial.println(ClientID);
    }

I couldn't find the reason for that. If anyone knows the solution for that please help me?

Thanks!

body: The two network interfaces (station and SoftAP) of the middle esp8266 must have different IP address range. If the top AP has 192.168.4.x, set for the AP of the middle IP for example 192.168.5.1. Because with same IP address ranges the esp8266 doesn't know to which network do you want to send the UDP message.


message:
My device doesn't recognize my Arduino

I'm planing to use the ESP8266 to create a web server as a start. My set up is: Arduino nano- Esp8266- Logic level converter  as shown in the diagram.
 [![Diagram of ESP8266 connected to Arduino nano Using Circuito example][1]][1]
After I connected everything my device doesn’t recognize the Arudion’s USB serial port, but when I disconnect everything from the breadboard and connect the Arduino alone it show up as COM3 and when I put the circuit back again and hock up the USB to my device it no longer show up.
I’m having the issue on both win 10 and mac.
Whenever I connected the usb cable to my computer the ESP8266 flashes a light for ones.

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

body:
The Nano cannot power the ESP8266. It has an absolute maximum limit of about 50mA from the 3.3V pin, since it is provided by the USB interface chip. By drawing too much current (the ESP8266 needs hundreds of mA) the USB chip stops functioning.

You need an external 3.3V regulator to power the ESP8266.


message:
Arduino Due Digital Inputs without Response

On two of my Arduino Due, when connecting the pin `3.3V` to any digital inputs (`37`,`36`,`35`,`34`), no serial message nor `LED_BUILTIN` is thrown as output, only the `Test` message.

Digital Pins are set as `INPUT` by default. [`Blink`][1] works.

I have never connected any other thing on those pins, even 5V.

What I am missing?

    void setup() {
        Serial.begin(115200);
        while(!Serial);
        pinMode(LED_BUILTIN,OUTPUT);
        Serial.print("Test");
    }

    void loop() {
        if (digitalRead(37))
            Serial.print("37");
        if (digitalRead(36))
            Serial.print("36");
        if (digitalRead(35))
            Serial.print("35");
        if (digitalRead(34))
            Serial.print("34");
        digitalWrite(LED_BUILTIN,digitalRead(37));
    }

  [1]: https://www.arduino.cc/en/tutorial/blink

body:
A good practice is to set the pin mode for all the pins used by the sketch.

    void setup() {
        Serial.begin(115200);
        while(!Serial);
        pinMode(34, INPUT);
        pinMode(35, INPUT);
        pinMode(36, INPUT);
        pinMode(37, INPUT);
        pinMode(LED_BUILTIN, OUTPUT);
        Serial.print("Test");
    }

The Arduino AVR core does set the pin mode to INPUT by default but the Arduino SAM core does not. The SAM MCU is much more advanced and allows turning on and off the ports, and a lot of other functionality.

Cheers!


message:
How do I properly use the WiFi capabilities of ESP8266?

I am creating a project with an ESP8266 (Arduino IDE) which requires it to serve a webpage to a client. The module will be connected to a WiFi network by default, but when that WiFi network is not available, I need it to turn on its Soft Access Point, so that the user can still access that webpage by connecting to the AP. When the WiFi network becomes available, I want the module to reconnect to the WiFi network and disable the SoftAP.

Here is the chunk of code in my sketch that deals with all the WiFi stuff:

<!-- language: lang-c -->
```
void wifi() {
  if(WiFi.status() != WL_CONNECTED){
    WiFi.mode(WIFI_AP_STA);

    if((unsigned long)(millis() - waitUntil) >= interval){            //this section I used as an alternative to the delay() function, the delay is 3 sec
      WiFi.begin(ssid, password);
      waitUntil = waitUntil + interval;

      if(WiFi.status() == WL_CONNECTED){
        Serial.println("Connection successful! ");
        Serial.print("IP: ");
        Serial.print(WiFi.localIP());
        WiFi.softAPdisconnect(true);
      }
    }
  }

  if(WiFi.status() != WL_CONNECTED && softAPEnabled == false){
    Serial.println("WiFi not connected, enabling SoftAP...");

    WiFi.softAP(softAP_ssid, softAP_password);

    softAPEnabled = true;

    Serial.println("SoftAP ON");
  }
  else if(WiFi.status() == WL_CONNECTED && softAPEnabled == true){
    WiFi.softAPdisconnect(true);
    softAPEnabled = false;
    Serial.println("SoftAP OFF");
  }
}
```

Here are the problems:

1. The webpage works fine when the module is connected to WiFi and I go to the IP address from a browser, but when SoftAP mode is enabled, and I connect to the AP and go to 192.168.1.1, it does not work. The next problem may be related to this.

2. I don't think I'm using WiFi.mode() correctly. I currently have it set to WIFI_AP_STA, but after problem 1 occurred, I tried to change it to WIFI_AP and WIFI_STA individually as I needed each mode, but this still did not work.

body:
The following may not solve of your problems, but just in case it helps...
I was using the ESP8266 both in Station mode and AP. Both worked.
In AP mode, it worked but the ESP8266 ignored my instructions to set name and password for the AP , until I realised the following
. The password must at least be 8 characters long, otherwise the instruction is ignored
. in the IDE, you should erase flash AND WiFI settings, otherwise it will be "lazy" and use previous settings


message:
How to read shiftOut function using arduino

(I'm sorry for my bad English, but I will do my best)

I have a Chinese MUC which already programmed. It communicates with a LED driver chip using three wires (STB,CLK,DIN).
(LED driver controls 16 digit 7 Segment display)

After some research, I found that it can be talk to LED driver using shiftout function.

Now the main coal is to connect these
 3 pins(STB,clk,din) to Arduino and read the incoming data and convert the data to numbers.

To test if this idea is working or not,
I came with two arduino (uno to send shiftout function  and mega to read it) after connect pin 2 of uno to pin 2 of mega and same 3 to 3, 4 to 4 and also Gnd of uno to Gnd of mega.
I wrote these codes:

arduino UNO side (to send shiftOut function)
```

    #define STB  4
#define clockPin  5
#define dataPin  6

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

  pinMode(STB, OUTPUT);
  pinMode(clockPin,  OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
 digitalWrite(STB, LOW);
    shiftOut(dataPin, clockPin, LSBFIRST, 0b10101010 ); // 1st digit
   digitalWrite(STB, HIGH);
}

```
arduino mega side (to read shiftOut function)

```

    #define STB 4
#define clockPin  5
#define dataPin  6

 int R_STB[8];
 int R_clockPin ;
 int R_dataPin ;
void setup() {
   Serial.begin(115200);

  pinMode(STB, INPUT);
  pinMode(clockPin,  INPUT);
  pinMode(dataPin, INPUT);
}

void loop() {

 R_STB = digitalRead(STB);
 R_clockPin = digitalRead(clockPin);
 R_dataPin = digitalRead(dataPin);

   for(int i=0 ; i<8;i++){
  Serial.print(R_STB[i]-2);

  Serial.print(" ");
  Serial.print (R_clockPin[i]);

 Serial.print(" ");
  Serial.print(R_dataPin[i]+2);
Serial.println(" ");
   }
 }

```

But the digital read at arduino mega side can't read all data due to it fast switching between High LOW statement maybe? and I am stuck here.

Please any one has any ideas?

body:
You are right that you can't read the data fast enough with your method there. What you really need is the opposite of "shiftOut" - which happens to be called "shiftIn".  You use it just like shiftOut, but instead of you sending it a value to send it instead returns a value that it reads.

You trigger it using the "STB" pin:

    if (digitalRead(STB) == LOW) {
        uint8_t val = shiftIn(dataPin, clockPin, LSBFIRST);
        Serial.println(val, HEX);
    }

But the protocol you describe is simply SPI.  There is hardware within the Arduino to handle it for you.  A little harder to work with, but it's capable of working at much higher speeds and is more likely to be able to read your incoming data fast enough.

Resources:

* https://www.arduino.cc/en/reference/SPI
* http://www.gammon.com.au/spi

The latter includes how to configure an SPI "Slave" which is used for receiving data that is sent out from elsewhere.


message:
How to connect SPI device on Etherntet shield on Arduino Uno

In my project I need to connect RFID reader (RC522) on top of the Ethernet shield because of it's capability of reading and editing SD card. When I connect only RFID sensor on Arduino, it works. Same goes to Ethernet shield. But when I use both together, It simply doesn't work. I can compile it and upload it, but I don't get anything in the serial monitor. I think it's because both Ethernet shield and RFID reader use the same pins for SPI like MOSI, MISO and SCK. My question is, if that is the problem, how to connect multiple SPI devices on Arduino, or at least on Ethernet shield.

Here is my code, although I think there's nothing wrong with it. I just merged code for RFID and Ethernet shield with copy-pasting. Sorry for bad formatting, I need it just for test, I'll later make the real code.

```arduino
#include <SPI.h>
#include <MFRC522.h>
#include <SD.h>

#define RST_PIN         6          // Configurable, see typical pin layout above
#define SS_PIN          7

MFRC522 mfrc522(SS_PIN, RST_PIN);

// set up variables using the SD utility library functions:
Sd2Card card;
SdVolume volume;
SdFile root;

// change this to match your SD shield or module;
// Arduino Ethernet shield: pin 4
// Adafruit SD shields and modules: pin 10
// Sparkfun SD shield: pin 8
// MKRZero SD: SDCARD_SS_PIN
const int chipSelect = 4;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  while (!Serial);    // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init();   // Init MFRC522
  mfrc522.PCD_DumpVersionToSerial();  // Show details of PCD - MFRC522 Card Reader details
  Serial.println(("Scan PICC to see UID, SAK, type, and data blocks..."));

  Serial.print("\nInitializing SD card...");

  // we'll use the initialization code from the utility libraries
  // since we're just testing if the card is working!
  if (!card.init(SPI_HALF_SPEED, chipSelect)) {
    Serial.println("initialization failed. Things to check:");
    Serial.println("* is a card inserted?");
    Serial.println("* is your wiring correct?");
    Serial.println("* did you change the chipSelect pin to match your shield or module?");
    while (1);
  } else {
    Serial.println("Wiring is correct and a card is present.");
  }

  // print the type of card
  Serial.println();
  Serial.print("Card type:         ");
  switch (card.type()) {
    case SD_CARD_TYPE_SD1:
      Serial.println("SD1");
      break;
    case SD_CARD_TYPE_SD2:
      Serial.println("SD2");
      break;
    case SD_CARD_TYPE_SDHC:
      Serial.println("SDHC");
      break;
    default:
      Serial.println("Unknown");
  }

  // Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
  if (!volume.init(card)) {
    Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
    while (1);
  }

  Serial.print("Clusters:          ");
  Serial.println(volume.clusterCount());
  Serial.print("Blocks x Cluster:  ");
  Serial.println(volume.blocksPerCluster());

  Serial.print("Total Blocks:      ");
  Serial.println(volume.blocksPerCluster() * volume.clusterCount());
  Serial.println();

  // print the type and size of the first FAT-type volume
  uint32_t volumesize;
  Serial.print("Volume type is:    FAT");
  Serial.println(volume.fatType(), DEC);

  volumesize = volume.blocksPerCluster();    // clusters are collections of blocks
  volumesize *= volume.clusterCount();       // we'll have a lot of clusters
  volumesize /= 2;                           // SD card blocks are always 512 bytes (2 blocks are 1KB)
  Serial.print("Volume size (Kb):  ");
  Serial.println(volumesize);
  Serial.print("Volume size (Mb):  ");
  volumesize /= 1024;
  Serial.println(volumesize);
  Serial.print("Volume size (Gb):  ");
  Serial.println((float)volumesize / 1024.0);

  Serial.println("\nFiles found on the card (name, date and size in bytes): ");
  root.openRoot(volume);

  // list all files in the card with date and size
  root.ls(LS_R | LS_DATE | LS_SIZE);
  }
}

void loop() {
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  // Dump debug info about the card; PICC_HaltA() is automatically called
  mfrc522.PICC_DumpToSerial(&(mfrc522.uid));
}
```

body: The two devices should share SCK, MISO, and MOSI, but SS (or CS as it's sometimes called) will have to be different and both shields are probably trying to use pin 10 for SS.  Let the ethernet shield have pin 10 for SS.  On the other shield, take that pin and bend it out so it doens't go down into the header when you stack them and then solder a wire to it and take it to another pin.  Go into the code and modify the code for that shield to use the new pin as SS instead of pin 10.


message:
My 12V DC Vending Machine motor rotates 1 extra 360 degree rotation sometimes. What could be the reasons?

have main board which has motor control circuit and has row and column to control the row and column of the vending machine.

I have made changes in motor in two ways:

A. I have attached an image for circuit diagram
[![enter image description here][1]][1]

In this design I have some pros and cons

PROS: 1. It stops at its home position after one rotation
2. It detects row and column of the machine

CONS: 1. Sometime it does not stop at its home position or take more than 1 rotation

B. I have attached an image of other diagram

[![enter image description here][2]][2]
In this design also I have some pros and cons

PROS: 1. It stops perfectly at its home position after one rotation.

CONS: 1. It does not detect ROW

Please suggest What should I follow and what should I made changes in the circuit.

Here is the video

https://drive.google.com/open?id=1N7ItjeU84JiDAOquAD6SGHkVWufDT40K

https://drive.google.com/open?id=1VX9yncrm6pcr1IBQsNvVZ1yR0UMflJKA

  [1]: https://i.stack.imgur.com/WhUb2.jpg
  [2]: https://i.stack.imgur.com/OuDuu.jpg

body:
> "It rotates little bit forward like 10% extra with 3.1 sec delay,"
>
> "I just want to rotate the motor from the home location to the home location when I give signal one time. But i do not know what time delay should I use?"

More than 2.0 and less than 3.1! If 3.1 sec gives 110% rotation, then you need
(100/110)*3.1 = 2.818sec to get 100%.

I realize that your 10% extra is an estimate and not accurate to 3 decimals, but I'd use 2.82 as a starting point and tweak it up or down until you get the amount of rotation you want.

Remember that timing a motor to get distance will inherently be inaccurate due to inconsistencies in the motor acceleration rate and rotation speeds, due to variations in its temperature and the power supply voltage, and load, but this should get you started. For long term accuracy, i.e., if you need it to always come back to a fixed position, you'll need some position feedback, which may be as simple as flag on the motor shaft interrupting a photocell. And even that will have *some* degree of inconsistency due to coasting speed when you shut the power off, but at least those error won't accumulate.

Update:

>  2.82, My motor rotates 10% less every time and change its location in every rotation

Right - 2.82 was a first approximation. If that is too small, try splitting the difference between 2.81 and 3.1. If that ends up too small, then split the difference between it and 3.1; or if it was too big, try splitting the difference between 2.1 and it. Do that a few more times until you have an acceptably close value.

Then read what I said about accumulating errors. The Arduino doesn't ever know what the motor position is so it can't correct for any overshoot or undershoot. If you need accuracy and repeatability, you'll have to add some kind of position sensing, or switch to using a stepper motor and drive the number of steps that makes one full rotation (and it would still have to be started from a known position).


message:
Why is my Arduino code for running a Bluetooth controlled robot with obstacle sensor not working as it should be?

I have created a Bluetooth based smartphone controlled robot (a 4 wheel car) earlier using Arduino and an obstacle avoidance robot.
Now, I wanted to combine both of them. So, I combined their functions and codes in such a manner that felt right to me. But, it kinda seems wrong to my robot.
My Bluetooth Controlled robot was running smoothly. My obstacle avoiding robot was running flawless. But, when I tried to join them, both of them started crying.

I tried to change orders of the functions, adding some functions twice or thrice removing them from some places that didn't feel right then. Nothing was worthy.

I need to upload whole code because I'm not sure where am I doing it wrong

```#define REMOTEXY_MODE__SOFTSERIAL
#include <SoftwareSerial.h>

#include <RemoteXY.h>

// RemoteXY connection settings
#define REMOTEXY_SERIAL_RX A2
#define REMOTEXY_SERIAL_TX A3
#define REMOTEXY_SERIAL_SPEED 9600

// RemoteXY configurate
#pragma pack(push, 1)
uint8_t RemoteXY_CONF[] =
  { 255,8,0,54,0,176,0,8,228,4,
  5,48,44,26,30,30,0,31,8,1,
  6,0,-84,-142,20,20,0,2,26,129,
  0,6,37,23,8,0,64,78,97,118,
  101,100,0,131,3,51,1,20,5,1,
  2,31,82,111,98,111,116,32,67,97,
  114,0,131,0,62,5,19,5,2,2,
  31,67,111,110,116,114,111,108,108,101,
  114,0,129,0,10,45,13,7,0,16,
  84,72,69,0,129,0,5,52,25,8,
  0,136,83,104,101,105,107,104,0,1,
  0,-34,-111,12,12,1,2,31,88,0,
  1,4,79,44,12,12,0,37,151,240,
  159,147,162,0,65,4,87,9,7,7,
  0,65,1,87,17,7,7,0,65,2,
  87,25,7,7,0,67,5,3,3,25,
  14,0,94,24,51,2,0,86,1,11,
  5,0,135,26,31,31,79,78,0,79,
  70,70,0 };

// this structure defines all the variables of your control interface
struct {

    // input variable
  int8_t joystick_1_x; // =-100..100 x-coordinate joystick position
  int8_t joystick_1_y; // =-100..100 y-coordinate joystick position
  uint8_t rgb_1_r; // =0..255 Red color value
  uint8_t rgb_1_g; // =0..255 Green color value
  uint8_t rgb_1_b; // =0..255 Blue color value
  uint8_t button_1; // =1 if button pressed, else =0
  uint8_t button_2; // =1 if button pressed, else =0
  uint8_t switch_1; // =1 if switch ON and =0 if OFF

    // output variable
  uint8_t red_led_r; // =0..255 LED Red brightness
  uint8_t blue_led_b; // =0..255 LED Blue brightness
  uint8_t green_led_g; // =0..255 LED Green brightness
  char text_indicator[51];  // string UTF8 end zero

    // other variable
  uint8_t connect_flag;  // =1 if wire connected, else =0

} RemoteXY;
#pragma pack(pop)

/////////////////////////////////////////////
//           END RemoteXY include          //
/////////////////////////////////////////////

#define PIN_BUTTON_2 A4
#define PIN_SWITCH_1 A5

#include<AFMotor.h>
#include <NewPing.h>
#include <Servo.h>

#define TRIG_PIN A0
#define ECHO_PIN A1
#define MAX_DISTANCE 250
//#define MAX_SPEED 150 // sets speed of DC  motors
//#define MAX_SPEED_OFFSET 20

NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor left_motor_A(1, MOTOR12_64KHZ);
AF_DCMotor left_motor_B(2, MOTOR12_64KHZ);
AF_DCMotor right_motor_A(3, MOTOR34_64KHZ);
AF_DCMotor right_motor_B(4, MOTOR34_64KHZ);
Servo myservo;

int distance = 100;

int right_motor_speed = 0;
int left_motor_speed = 0;
//define two arrays with a list of pins for each motor
AF_DCMotor RightMotor[2] = {right_motor_A, right_motor_B};
AF_DCMotor LeftMotor[2] = {left_motor_A, left_motor_B};

//speed control of motors
void Wheel (AF_DCMotor * motor, int v) // v = motor speed, motor = pointer to an array of pins
{
  if (v > 100) v=100;
  if (v < -100) v=-100;
  if (v > 0){

    motor[0].run(FORWARD);
    motor[1].run(FORWARD);
    motor[0].setSpeed(v * 1.75);
    motor[1].setSpeed(v * 1.75);
  }
  else if ( v<0 ){

    motor[0].run(BACKWARD);
    motor[1].run(BACKWARD);
    motor[0].setSpeed(v * 1.75);
    motor[1].setSpeed(v * 1.75);
/*    //digitalWrite (motor [1], FORWARD);
    analogWrite (motor [2], (v) * 0.75);
    //analogWrite (motor [2], (-v) * 0.75); */
  }
  else{
    motor[0].run(RELEASE);
    motor[1].run(RELEASE);
    motor[0].setSpeed(0);
    motor[1].setSpeed(0);
  }
}

 int lookRight()
 {
    RemoteXY.blue_led_b = 255;
    RemoteXY.red_led_r = 0;
    RemoteXY.green_led_g = 0;
    sprintf(RemoteXY.text_indicator, "CHECKING THE RIGHT SIDE.");
    myservo.write(50);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
 }

 int lookLeft()
 {
    RemoteXY.blue_led_b = 255;
    RemoteXY.red_led_r = 0;
    RemoteXY.green_led_g = 0;
    sprintf(RemoteXY.text_indicator, "CHECKING THE LEFT SIDE.");
    myservo.write(170);
    delay(500);
    int distance = readPing();
    delay(100);
    myservo.write(115);
    return distance;
    delay(100);
 }

 int readPing()
 {
  delay(100);
  int cm = sonar.ping_cm();
   if(cm==0)
  {
    cm = MAX_DISTANCE ;
  }
  return cm;
 }

 void moveStop()
 {
  left_motor_A.run(RELEASE);
  left_motor_B.run(RELEASE);
  right_motor_A.run(RELEASE);
  right_motor_B.run(RELEASE);

 }

void setup()
{
  RemoteXY_Init ();

  pinMode (PIN_BUTTON_2, OUTPUT);
  pinMode (PIN_SWITCH_1, OUTPUT);

  myservo.attach(10);
  myservo.write(115);
  delay(2000);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);
  distance = readPing();
  delay(100);

}

void loop()
{
  RemoteXY_Handler ();

  digitalWrite(PIN_BUTTON_2, (RemoteXY.button_2==0)?LOW:HIGH);
  digitalWrite(PIN_SWITCH_1, (RemoteXY.switch_1==0)?LOW:HIGH);

    int distanceR = 0;
    int distanceL =  0;
    delay(40);

    if(distance<=27)
    {
      moveStop();
      RemoteXY.blue_led_b = 0;
      RemoteXY.red_led_r = 255;
      RemoteXY.green_led_g = 0;
      sprintf(RemoteXY.text_indicator, "AN OBSTACLE HAS COME IN FRONT OF YOUR ROBOT!!!");
      digitalWrite(PIN_BUTTON_2, HIGH);
      delay(1500);
      distanceR = lookRight();
      delay(250);
      distanceL = lookLeft();
      delay(250);

      if(distanceR>=distanceL)
      {
        RemoteXY.blue_led_b = 255;
        RemoteXY.red_led_r = 0;
        RemoteXY.green_led_g = 0;

        sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE RIGHT SIDE.");
      }

      else
      {
        sprintf(RemoteXY.text_indicator, "IT IS GOOD TO GO ON THE LEFT SIDE.");
      }
    }
    else
    {
      RemoteXY.blue_led_b = 0;
      RemoteXY.red_led_r = 0;
      RemoteXY.green_led_g = 255;
      //manage the right motor
      Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
      Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);

    }
    distance = readPing();

    //manage the right motor
    //Wheel (LeftMotor, RemoteXY.joystick_1_y - RemoteXY.joystick_1_x);
    //Wheel (RightMotor, RemoteXY.joystick_1_y + RemoteXY.joystick_1_x);

  }
```

I want my Robot to work on my directions and when he senses something on its front end then he should stop there and tell me through a RemoteXY.text_string and then check for obstacles at the left and right side and tell me on which side it is available to go. After that, it should again take my orders via my mobile phone.

Firstly, it became impossible to connect the robot to the Smartphone using Bluetooth because the robot was very busy in doing some other stuffs (only he knows what was he doing). Then, I applied a "RemoteXY Button" on my code (that is not in the code that I'm posting here) with an "if" block; such that if this switch is pressed via the Smartphone, only then the robot will start moving. So, doing this thing helped me to connect my robot to my smartphone via Bluetooth but, when I was connection then the Servo Motor was regularly spinning (again, I don't know why) after secure connection, when I turned that switch on, then my robot took only my first order (which is usually moving forward) and it performed on my first order for almost first 3 to 5 seconds and then the Robot got his system hanged and my smartphone was automatically disconnected from the robot.

I am unable to figure out where is the filth in my code or my code is itself fully filthy. This is the matter, where I need you guys' help

Other information that you might need for better Support/help, I am using:
1). RemoteXY app for Android to Robot Communication
2). Arduino UNO as Microcontroller
3). Arduino IDE for Programming Arduino
4). One SG 90 Servo Motor.
5). Four Geared DC- Motors.
6). L293D Motor Driver Shield for driving Dc motors and the Servo
7). HC SR-04 ultrasonic sensor for obstacle sensing
8). A 12V battery
9). HC-05 Module for Bluetooth Communication
10). A buzzer for external indicator/horn. At pin A4
11). A filthy code for Arduino Programming .

Any help with the code will be appreciated.

Thank You So Much in advance. ❤

body:
My guess is, that the function `RemoteXY_Handler()` has to be called very regularly (without long pauses in between) to communicate with the app on your smartphone, or the app will think, that the communication is lost, and disconnect from the robot. This means, that you cannot use long `delay()` calls in your code, since that is just busy waiting. In your code in case of an obstacle in front of the robot, you wait 3.6s in total. That is too much. The robot is doing nothing in this time. Instead you should use a non-blocking coding style. That means, that the code will not block, waiting (and doing nothing) until an event happends (for example a specific amount of time passed), but instead will execute other functions, until the event occurs. That is a generally better way to program a microcontroller, since it enables you to add more functionalities easily without disturbing the program flow.

Here you try to do timed things with `delay()`. Instead you should use a coding style, like the one found in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. It is explained various times throughout the internet and this site. Basically it is like regularily looking at your watch (the `millis()` function here) and only doing things, when the time has come. You should look at the example and maybe go through some of the tutorials about this, so that you really understand, what happens there. Then you can start to rewrite your code and eliminate all `delay()` calls. That will need some restructuring of the code.

---

The `BlinkWithoutDelay` example is an easy structure, since it contains only few logic. Your goal is a bit more complex. So I suggest, that you use a Finite State Machine (FSM). It is rather easy to implement and a powerful tool to structure your code. It's definitely worth learning for every programmer.

A FSM consists of multiple states, that are connected by transitions. In each state there can be code executed. Also there might be code, that is only executed on transitions. First you have to model your project into states. One state here could be `REMOTE_CONTROLLED`, which would just execute the commands coming from the app. Based on input from sensors and the app you can then transition between the states. If you see, that you might need a `delay()` inside a state, that might be a hint, that you can further divide the state into substates. For example I would make an extra state, which gives the servo the time to move. I would suggest, that you really draw a graph for your project with all your states (state name in a bubble). Then draw arrows as state transitions between them. This will give you a good overview of the structure to implement.

In code this is often implemented with a `switch()` `case` structure and a state variable:

    int state=0;
    int distance = 100;

    void loop(){
        RemoteXY_Handler ();
        distance = readPing();

        switch(state){
            case 0:
                // Do whatever the remote demands here
                if(distance <= 27){
                    // Execute code, that should happen once at transition here
                    state = 1; // This makes the transition to the next state
                }
            case 1:
                // Code of the next state
        }
    }

With this structure at every time only the code of the current state will be executed. The transitions are made simply by setting the state variable to the next desired state. To make the states more speaking in the code, you can use an `enum`, so that every state can be referenced with an `enum` name. The remote handler and the reading of the distance is done outside the FSM here, since you always need the input from those. Based on them, you can do state transitions.

To do timed things in an FSM, you can put the `millis()` code (like in the `BlinkWithoutDelay` example) into the corresponding state.

---

Note, that this is only one way to implement a FSM. The video, that you linked, does this a bit different by using functions pointers (the `state()` function pointer is the state variable here). The principle is the same, only the programming structure is different. You can decide yourself, what works better for you, and what you understand better (pointers can be a bit difficult to understand for beginners).


message:
Is this Arduino UNO running at 12 MHz?

I am wondering if this Arduino UNO R3 clone is clocked at 12 MHz instead of the standard 16 MHz? On the board, you can see there is 12.000 written on the crystal oscillator.
[![clone1][1]][1]

But maybe it's not the MCU clock speed? I found this other clone, which has 2 crystal oscillators?! One is 12 MHz and the other one is 16 MHz.
[![clone2][2]][2]

I can't figure out what's happening with these boards... Are these sporting faster or slower speeds? The original Arduino UNO R3 has only one 16 MHz crystal oscillator.

  [1]: https://i.stack.imgur.com/9It2Q.png
  [2]: https://i.stack.imgur.com/awZyF.png

body:
The 12MHz crystal is for the USB interface.

The main MCU uses a very small 16MHz resonator, which you can see between C5 and C6.


body:
The 16 MHz resonator, a 3-pin part, can be seen between C5 and C6 in the first picture.

The 12 MHz is for the CH340 as noted.

So it's not an Uno, but a clone ripoff, as an Uno would have a Atmega16U2 for the USB.


message:
Pro Micro ATMEGA32U4 unable to upload

I have a simple flashing led program that I want to upload on my pro micro (see image) but it doesnt work (see image: no port available, Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.)

I have successfully uploaded this program on my arduino uno.

Ive followed this guide for the drivers and more.
[https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/installing-windows][1]

Thanks for help

[![enter image description here][2]][2]

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

[![o][4]][4]

  [1]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/installing-windows
  [2]: https://i.stack.imgur.com/c3e6g.jpg
  [3]: https://i.stack.imgur.com/2XcV7.jpg
  [4]: https://i.stack.imgur.com/LBzgF.jpg

body:
Your board will only present a serial port if the sketch that is running on it is programmed to present a serial port. The board does not have an actual serial port for communication with the PC - only what the sketch provides.

If the sketch doesn't provide one, or if the sketch isn't running (for example if it was compiled for the wrong board by accident) then you will never see a serial port.

Since the "normal" way of resetting the board to enter the bootloader (which *does* present its own serial port) is to open the serial port at 1200 baud, since you don't have one to open it's kind of hard to get to the bootloader. However, depending on *what* bootloader you have installed there are a number of options that can help you:

1. Briefly connecting RST to GND just before uploading may activate the bootloader for a few seconds.
2. Doing the above *twice* in rapid succession may activate the bootloader for longer (depending on the bootloader version)

Erasing the chip and reinstalling the bootloader is the only real way that is guaranteed to work, though. But that said, I have seen boards come out of China *without any bootloader at all* - so reinstalling the bootloader is always a good first option with cheap boards.  You can use your Arduino UNO as an ISP programmer (using the ArduinoISP sketch and treating it like you're making a breadboard Arduino).


body:
I have also problem with China boards, after 3 days of googling and trying get boards to work, I found out, that chip it self have difference.one chip is for bootloader from arduino micro, and one from lilypad arduino USB, it is about chip ID when arduino IDE is calling for upload sketch, thers are two 4bit id when it cals. And one is chip with cristal 16MHz lilypad arduino USB, and another version 8MHz Arduino micro, but board is it self looks like Arduino pro micro, Chip type have only few letters difference, if I will never find out that solution, if I will not have two chip comparisions .[![enter image description here][1]][1]

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

Last row of numbers makes chip type difference and vendor id depends to what chip type we have. And what clock speed is using. And I see on the veb that many peoples have this problem to not be able to upload simple sketch because of that chip model.


message:
How To Get Data From Arduino Uno Onto My Laptop Through The USB

I want to write a c++ program that does something with the data from one of the input analog pins as the program runs, but I want to know how to get the value from the arduino uno though the USB port (that I am also using to power the uno) and into my laptop for using. IS there any documentation I should read?

My laptop runs Ubuntu 18.04 if that matters.

EDIT: I am not talking about the Serial monitor by the way

body:
The "Serial Monitor" is merely a window to the Arduino's serial port. You don't have to use it to use Serial. It's just a (very simple) built in way of seeing the data.

You can use the Serial interface with your own software, or with third party software. It's not tied to the Serial Monitor in any way at all.

So:

* Use `Serial.print()` etc to send data to the PC
* Write your own PC software in your language of choice to process that data, or
* Use some third party application to read and process the serial data


message:
5V pin output on arduino

Sorry for the newbie question (just started learning electronics).

I just saw a tutorial that says that the 5V output pin on the Arduino delivers more amps (if needed) when connecting more voltage to the board (connecting to the 9 - 12V instead of 5V).
Does that mean that the 5V pin then delivers more than 5V as well?

body:
Time for a crash course in electronics and power:

The 5V pin only ever provides 5V. That's why it's the "5V" pin. (assuming, of course, that you give the board *more* than 5V).

In simple linear electronics you have three values:

* The voltage
* The current
* The load

Generally two of the three are either "fixed" or "known" and the third changes depending on the other two. For simple resistive circuits (where the load is a simple resistor) this relationship is Ohm's Law.

* If the voltage is fixed, and
* If the load changes, then
* The current will also change to keep the relationship stable.

A "power supply" (any device which provides power to some other device) generally has two parameters: Voltage and Current.  One of those is always fixed. The other is always variable, and quoted as a maximum that the supply can give.

For the Arduino's 5V pin the parameters are:

* Voltage: 5V
* Current: 800mA Maximum

That means that the 5V pin has a fixed voltage of 5V, but the current is free to change depending on the load *up to a maximum of 800mA* (or a lower limit if you are providing the input power from a source with a lower current. There is also heat to consider with the Arduino - see below).

The two values, voltage and current, combine together to give the "power" of the power supply, through simple multiplication. So the Arduino's 5V pin is 5V × 0.8A = 4 watts maximum.

When you provide power to the Arduino through the barrel jack it first goes through a *linear voltage regulator*.  This is the device which takes the incoming voltage and reduces it to 5V. Since energy can neither be created nor destroyed it does that reduction in energy by converting some of it to heat.

Say you connect something up that needs 100mA and you plug in a 9V power supply to the board. Let's also assume that the Arduino itself needs 50mA (I like nice round numbers).

* That's 150mA in total for the "load".
* The incoming voltage is 9V
* The outgoing voltage is 5V

The power of the input is thus 9V × 0.15A = 1.35W
The power of the output is then 5V × 0.15A = 0.75W

The power difference is 0.6W

That 0.6W is converted from electrical energy to heat energy by the voltage regulator and "thrown away".

So the "heavier" your load (the more current you demand from the 5V pin) the greater the heat that is generated by the voltage regulator.

When the regulator gets too hot one of two things happen:

1. A good quality regulator will shut down and you will lose power to the board
2. A cheap Chinese regulator will likely "fail short" and feed your 9V direct into the Arduino causing components to release their Magic Smoke™ and stop working


message:
My push button code doesn't work properly

I'm using an OLED display connected to a push button.  I am trying to get my display to show two different values independently  by using the push button to switch between them. Here is a snap of my code from the loop function:

        if (buttonState == HIGH) {
        x=x+1;
      }
      if (x == 1) {
      display.setTextColor(WHITE);
      display.setCursor(0, 0);
      display.setTextSize(2);
      display.print(T);
      display.print(" degree");
      display.display();
      display.print(x);

    }
        else if (x == 2) {
      display.setTextColor(WHITE);
      display.setCursor(0, 0);
      display.setTextSize(2);
      display.print(perventage);
      display.print(" %");
      display.display();
      display.print(x);
    }
        else  {
          x=1;
          }

      delay(10);
    }

 x is defined as 1 initially out side the loop.
What happens is that when the circuit is turned on, the screen displays the value of T then what should happen is when I push the button it switches to the second value which is percentage, and I push again to go back to T. My issue is that the Arduino doesn't response to the push button all of the time sometimes it takes 1 click and other times it takes 6 or 8 fast clicks to switch between them and it doesn't stick to a specific number of pushes to switch.
What would you suggest me to change to fix it.

Edit: here is pic of my wiring diagram
[![Wiring diagram][1]][1]

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

body:
You are reading the raw button state without debouncing it, so you may be getting 2 (or 4, or ...) pulses so quickly - off the same button-push - that the display or your eye can't respond that quickly. Here is [Nick Gammon's tutorial on switches and buttons][1], including debouncing.

Also make sure you use a pull-down resistor on the button input-pin. Floating inputs are noise and will give you a lot of false signals.

  [1]: http://www.gammon.com.au/switches


body:
One core problem is that you have a simple "If the button is HIGH then cycle through the numbers". The longer you hold the button the more times it will cycle through the numbers.  It's pure 50/50 chance that you happen to release the button on a different number to the one it started on.

Instead you need to look for a *change* in the state of the button. Has it changed from LOW to HIGH:

    static uint8_t oldState = LOW;

    uint8_t buttonState = digitalRead(BUTTON_PIN);
    if (buttonState != oldState) {
        oldState = buttonState;

        if (buttonState == HIGH) {
            // This only runs once at the moment of pressing
            // the button - not continuously while you're
            // holding the button in.
            // Cycle through your displays here.
        }
    }


message:
TIMEOUT error when connecting ESP8266 to Arduino Uno

I am trying to set up my Arduino Uno to receive information from the internet, but I am having a very hard time finding proper guides online. I am using an Arduino Uno and ESP8266-01. I am trying to use the "WebClientRepeating" example from this library:
https://github.com/bportaluri/WiFiEsp

Here is the code I am running (updated the SSID and password):

    /*
     WiFiEsp example: WebClientRepeating

     This sketch connects to a web server and makes an HTTP request
     using an Arduino ESP8266 module.
     It repeats the HTTP call each 10 seconds.

     For more details see: http://yaab-arduino.blogspot.com/p/wifiesp.html
    */

    #include "WiFiEsp.h"

    // Emulate Serial1 on pins 6/7 if not present
    #ifndef HAVE_HWSERIAL1
    #include "SoftwareSerial.h"
    SoftwareSerial Serial1(6,7); // RX, TX
    #endif

    char ssid[] = "MY-SSID";            // your network SSID (name)
    char pass[] = "MY-PASSWORD";        // your network password
    int status = WL_IDLE_STATUS;     // the Wifi radio's status

    char server[] = "arduino.cc";

    unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds

    // Initialize the Ethernet client object
    WiFiEspClient client;

    void setup()
    {
      // initialize serial for debugging
      Serial.begin(115200);
      // initialize serial for ESP module
      Serial1.begin(9600);
      // initialize ESP module
      WiFi.init(&Serial1);

      // check for the presence of the shield
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("WiFi shield not present");
        // don't continue
        while (true);
      }

      // attempt to connect to WiFi network
      while ( status != WL_CONNECTED) {
        Serial.print("Attempting to connect to WPA SSID: ");
        Serial.println(ssid);
        // Connect to WPA/WPA2 network
        status = WiFi.begin(ssid, pass);
      }

      Serial.println("You're connected to the network");

      printWifiStatus();
    }

    void loop()
    {
      // if there's incoming data from the net connection send it out the serial port
      // this is for debugging purposes only
      while (client.available()) {
        char c = client.read();
        Serial.write(c);
      }

      // if 10 seconds have passed since your last connection,
      // then connect again and send data
      if (millis() - lastConnectionTime > postingInterval) {
        httpRequest();
      }
    }

    // this method makes a HTTP connection to the server
    void httpRequest()
    {
      Serial.println();

      // close any connection before send a new request
      // this will free the socket on the WiFi shield
      client.stop();

      // if there's a successful connection
      if (client.connect(server, 80)) {
        Serial.println("Connecting...");

        // send the HTTP PUT request
        client.println(F("GET /asciilogo.txt HTTP/1.1"));
        client.println(F("Host: arduino.cc"));
        client.println("Connection: close");
        client.println();

        // note the time that the connection was made
        lastConnectionTime = millis();
      }
      else {
        // if you couldn't make a connection
        Serial.println("Connection failed");
      }
    }

    void printWifiStatus()
    {
      // print the SSID of the network you're attached to
      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());

      // print your WiFi shield's IP address
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);

      // print the received signal strength
      long rssi = WiFi.RSSI();
      Serial.print("Signal strength (RSSI):");
      Serial.print(rssi);
      Serial.println(" dBm");
    }

My wiring is as follows:

 - ESP8266 RX - Uno Pin 7
 - ESP8266 TX - Uno Pin 6
 - ESP8266 VCC - 3.3V power source (not from Uno)
 - ESP8266 GND - Uno GND
 - ESP8266 CH_PD - 3.3V power source (not from Uno)

I also connected the GND of the 3.3V power source to the other GNDs.

When I go to run the WebClientRepeating example, my Serial output says:

    11:05:04.764 -> [WiFiEsp] Initializing ESP module
    11:05:05.760 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:07.785 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:09.758 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:11.780 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:13.803 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:14.794 -> [WiFiEsp] Cannot initialize ESP module
    11:05:20.794 -> [WiFiEsp] >>> TIMEOUT >>>
    11:05:20.794 -> [WiFiEsp] No tag found
    11:05:20.830 -> WiFi shield not present

The tutorial specifies that it uses a "ESP WiFi shield" but I am using a ESP8266 card only - could that be part of the problem? If that is a problem, are there any simple guides out there for how to connect the Arduino Uno to the internet to read information? I am frustrated with the lack of good documentation, and would really appreciate some help.

body:
It means that your ESP8266 is not detected

Because of you connect RX and TX (6 and 7) to secondary pin.
Use your standart RX TX pin to solve the problem


message:
power consumption of esp32

I'm currently working on an IOT project with my esp32, ill need it to run on batteries, I will only be needing "active mode" with wifi once per hour to upload some data to a database and then go back to deep sleep (need to save data cant use hibernation).

[THIS][1] website explain pretty well how much energy the esp needs, but it says e.g. 30mA - 60mA, but on batteries it says mAh, so is the mA just mAh or how do I calculate the power usage?

.

ps.

currently, I'm thinking of using 2 cr2032 batteries, good recommendations on batteries are welcome

  [1]: https://lastminuteengineers.com/esp32-sleep-modes-power-consumption/

body:
There's a number of things to consider when choosing batteries.

First is the capacity. In broad terms, the capacity is, mAh, means "This battery can supply X mA for one hour". So a battery of 1000mAh could supply around 1A (1000mA) for one hour before it goes flat.  Simply divide the mAh by your device's mA and you get the time it will run for before it goes flat. So a 50mA device would run for about (1000 / 50) 20 hours before running flat.  That is only a "ball park" figure though, since the capacity is somewhat dependent on the amount of current you draw.

Then there is the question of the internal resistance of the battery. This determines the maximum current that you can draw from the battery before the voltage drops below a usable level.  Different battery chemistries have different internal resistances.

Small button cells like the CR2032 have a high internal resistance and a low capacity.  A [typical cheap CR2032](http://www.farnell.com/datasheets/1671733.pdf) has around 200mAh capacity. At 50mA that would last 4 hours. But drawing 50mA from a CR2032 is not really on.  Looking at the graphs in the datasheet linked to above you can infer that, with a nominal voltage of 3V, with a 1kΩ load the output drops to 2.6V. That means that 1kΩ is drawing (2.6/1000) 0.0026A (2.6mA).  The internal resistance is dropping (3 - 2.6) 0.4V, therefore the internal resistance must be (0.4 / 0.0026) 154Ω.

Drawing 50mA from the battery would mean the internal resistance would drop (154 * 0.05) 7V. Since you can't get below 3V, that means the battery simply can't support that kind of current drain.  Indeed, in the datasheet I link to the "Standard Current Drain" (the current it's rated for as "normal" usage) is a mere 0.1mA.

So to work out what battery you need, you want:

* The average current draw over the period of an hour
* The peak current draw the device will draw
* The length of time you need the device to run for between battery changes / recharges

For the ESP32 the current can peak at hundreds of mA depending on what you are doing (WiFi uses a lot of power in short bursts). The average will be based on the ratio of the "running" time to the "sleeping" time, and the current draw for both those states.


message:
Soil moisture sensor not working in "pcb"

I have a little and common application in which a sc-28 moisture sensor reads humidity levels and turns a servo (which drives a little faucet) if the soil needs water. Arduino nano is the brain.

All of them is tested and working fine on the proto board. Soil sensor is powered by 5v rail of arduino and everything seems fine even with the servo pulling from 5v rail too.

With all working, I try to translate that to a perfboard. The only difference in circuits are how they are powered.

While the prototype is powered via usb, the definitive one is powered through a 24v psu, leveling the voltage with a lm2596 module down to 5v.

Then this 5v feeds the nano (vin pin) and servo, while the soil sensor still pulls from 5v rail of the arduino to avoid vref problems.

And then, the sensor does not work. No led indicating power or data. This were my steps trying to debug it:

 - **Triple check every connection on the board.** While I am a decent programmer, my solder skills are kind of lacking. But everything looks fine, nothing shorted or loose.

 - **measure voltage**. On the perfboard, voltage between vcc and gnd connector pins spits 4.78v, which is supposed to be in range for the sensor to work.

 - **Power the board through usb** I tried this too, and is not working. Lm module and arduino lights up, code can be executed. I can't explain why the lm2596 module lights up too, and I'm thinking is part of the problem but I do not know. Voltage at soil sensor is still 4.78

And then I'm done. I dont know what could be happening and I only can make wild guesses. It's obviously a board problem, and i am aware I am doing something wrong but I can't see it.

Below, my horror soldering skills and the board. Soil sensor is the 4pin females at the bottom left and servo the 3pin males at the bottom right.

 [![image 1][1]][1]

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/UcjJV.jpg
  [2]: https://i.stack.imgur.com/Mjd3D.jpg

body:
>Then this 5v feeds the nano (vin pin)

Can't feed 5V into Vin and get 5V out. Connect 5V to the 5V pin.


body:
The answer was, in fact, my poor experience with these boards and how they work.

As you can see in the pictures, wire and connectors are on opposite sides of the board. I was assuming that pads were connected on both sides, which is not true. Therefore, connectors were simply dead.

Soldered again at the wire side and it works like a charm. Thank you all for every suggestion, and the learning experience.


message:
Two Arduino Control a LCD Display

I´m building a system that has two arduinos (like the image on the botton) linked via `ICSP`. The "Programer"  programs the second one, called "Worker"( with a .hex file in the SD card of the Programer).

The Worker controls a `LCD 16x4` and displays messages to the user.

What I´m tring to do is when the Programmer is programming the Worker it also displays a message like "Programming, wait" in the Worker LCD. But in code, just telling to the Worker displays a message is not going to happen because when it has been programmed it displays garbage in the LCD.

**Q** So is it possible the the Programmer takes control of the LCD before it begin to program the worker and displays its message?

The LCD works with normal 4-bit mode comunication and I would rather not converte it to I2C if it´s possible.

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

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

body:
There are two solutions that come to my mind, one more HW based and another more SW based.

## Solution 1 ##

The HW way is to let the programmer control the LCD through 2:1 multiplexer(s). You will need to connect the LCD pins to the common pin of the multiplexer, the Programmer's ones to one of the two inputs and the Worker's to the other. Then the programmer can choose who controls the LCD through the additional pin. An example of the multiplexer you can choose is the 74LS157, but there are virtually infinite part numbers. The disadvantage of this approach is that you need to write the whole LCD control stack in the Programmer.

## Solution 2 ##

An alternative, more relying on the SW, is implementing a way to let the slave know that you want to program it. For instance, when a programming is needed the Programmer raises a pin; the Worker writes the string on the LCD, then stops working, raises another pin and waits to be cleared. The programmer then proceeds to flash the Worker, and the message will remain on the LCD. It may happen that garbage exits from the Worker's pins when being programmed. If so, change the enable pin or find a way to temporarily detach it from the Worker to avoid signals reaching the LCD. This schematic illustrates this concept:

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

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

<!-- End schematic -->

When the Programmer wants to program the unit, it sets the DL_Req pin to high. The Worker sees this, and performs accordingly. I think pins are not moved then, but if for instance some noise appears on the signals during programming (and the LCD displays this noise as weird chars), try changing the pin associated to the enable pins (LCD2 in the example above) or put something to prevent noise on that wire only, so that LCD content is not modified.

Personally I'd go with the second solution, but this depends on how much you can change the behavior of the worker and programmer


message:
Control two stepper motors simulatenously?

I'm using Arduino Mega 2560, A4988 motor driver for 5 stepper motors. There are X1, X2, Y, Z, A axis, and if I control Y and Z at once, it works. But when I just change axis from Y&Z to X1&X2, only X1 stepper motor spins. X1&X2 need to move at once(simultaneously) due to they are connected in single bar.

My Arduino IDE code is,

==============================

```
const int X2step = 5;

const int X2dir = 4;

const int X1step = 3;

const int X1dir = 2;

void setup() {

    pinMode(X1step,OUTPUT);

    pinMode(X1dir,OUTPUT);

    pinMode(X2step,OUTPUT);

    pinMode(X2dir,OUTPUT);

}

void loop() {

    digitalWrite(X1dir,HIGH);

    digitalWrite(X2dir,HIGH);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    delay(1000);

    digitalWrite(X1dir,LOW);

    digitalWrite(X2dir,LOW);

    for(int x = 0; x < 4000; x++) {

        digitalWrite(X1step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X1step,LOW);

        delayMicroseconds(2000);

        digitalWrite(X2step,HIGH);

        delayMicroseconds(2000);

        digitalWrite(X2step,LOW);

        delayMicroseconds(2000);
    }

    exit(0);
```
=================================================

Any suggestion would be helpful for me. Thanks.

body:
You likely have other issues to boot based on what you said about only X1 moving, but first I suggest resolving the bug in your code.  It appears to be that you have delays between your digital writes to x1, x2. And set their directions to the same.

At the very least you should be writing to X2 step every time you write to X1 step.  If your wiring is *identical* and the motors are essentially attached *mirrored* on opposite sides of a shaft, don't forget to set the directions opposite before you start sending steps. (If they are on opposite sides of the shaft, one spinning counterclockwise means the other spins clockwise.  You can also play wiring tricks with what coil goes where and how, but identical is simpler.)

    digitalWrite(X1dir,HIGH);
    digitalWrite(X2dir,LOW);

Or

    digitalWrite(X1dir,LOW);
    digitalWrite(X2dir,HIGH);

Then step it like

    digitalWrite(X1step,HIGH);
    digitalWrite(X2step,HIGH);

    delayMicroseconds(2000);

    digitalWrite(X1step,LOW);
    digitalWrite(X2step,LOW);

    delayMicroseconds(2000);
    ...


message:
What Arduino boards would be compatible?

I am considering using an arduino over the raspberry pi for a new project. However, I am not sure what arduino I should buy so that it is compatible with the below add-on.

![add-on board](https://i.stack.imgur.com/DAnCc.jpg)

Are all Arduinos compatible?

TIA.

Edit:

Link to product- https://www.adafruit.com/product/3387

My goal is to use an arduino with the above product to move a 3D model in Unity 3D.

body:
As one can see from the pinout description page (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/pinouts):

[![][1]][1]

So this board is literally designed to be powered by 3.3V and 5V and have compatible logic levels for both these voltage ranges, which is what every Arduino known to me and the Raspberry Pi use.

Furthermore, there is also Arduino Code (https://github.com/adafruit/Adafruit_LSM9DS1)  which is compatible with pretty much every Arduino Core and Raspberry Pi Python code (https://learn.adafruit.com/adafruit-lsm9ds1-accelerometer-plus-gyro-plus-magnetometer-9-dof-breakout/python-circuitpython).

So by means of voltage levels and platforms, this board is highly compatible with everything out there that is either 3.3V or 5V powered and has a SPI or I2C peripheral.

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


message:
Buffer overflow error in ESP8266_SoftwareSerial library

I am running into buffer issues when running the Firmware.ino example [here][1].

The output from my Arduino serial log on baudrate 115200 (I put the ESP on baudrate 9600):

    Begin
    01:17:15.538 -> Baudrate set success
    01:17:15.585 -> Station + softAP - OK
    01:17:18.631 -> Joining AP successful, IP: 192.168 r⸮+@⸮
    01:17:18.991 -> Single Mode OK
    01:17:18.991 -> Sending Request to www.google.com
    01:17:19.084 -> create tcp - OK
    01:17:19.710 -> not sentbuffer is full!
    01:17:20.022 -> HZiw93GUFmVJYFz-yRmahGURP_UBbRb4EF0Ahwzx8MJ1GOyC5Z0dns8UD41G8kUqnL0oxNPxa6xF9nAqNF3X3B_hKW11zoyaBPn8trvUNt-69qbFCNOZwNjgoaloKbOQs7NN-B3tpmwFKpHfKsfKyZfiMdhulN3SgZMhewYBg9c; expires=Wed, 05-Feb-2020 05:17:18 GMT; path=/; domain=.google.com; HttpOnly
    01:17:20.162 -> Accept-Ranges: none
    01:17:20.162 -> Vary: Accept-Encoding
    01:17:20.209 -> ConnecS,
    01:17:24.179 -> Sending Request to www.google.com
    01:17:24.774 -> create tcp - ERROR
    01:17:28.759 -> Sending Request to www.google.com
    01:17:29.432 -> create tcp - ERROR
    01:17:33.402 -> Sending Request to www.google.com
    01:17:34.021 -> create tcp - ERROR
    01:17:38.028 -> Sending Request to www.google.com
    01:17:38.669 -> create tcp - ERROR
    01:17:42.681 -> Sending Request to www.google.com
    01:17:43.294 -> create tcp - ERROR
    01:17:47.298 -> Sending Request to www.google.com
    01:17:47.954 -> create tcp - ERROR
    01:17:51.925 -> Sending Request to www.google.com
    01:17:52.595 -> create tcp - ERROR
    01:17:56.563 -> Sending Request to www.google.com
    01:17:57.204 -> create tcp - ERROR
    01:18:01.222 -> Sending Request to www.google.com
    01:18:01.871 -> create tcp - ERROR
    01:18:05.839 -> Sending Request to www.google.com
    01:18:06.460 -> create tcp - ERROR
    01:18:10.456 -> Sending Request to www.google.com
    01:18:10.596 -> create tcp - OK
    01:18:11.049 -> buffer is full!
    01:18:11.049 ->
    01:18:11.049 ->
    01:18:11.049 -> +IPD,1430:HTTP/1.1 200 OK
    01:18:11.096 -> Date: Tue, 06 Aug 2019 05:18:09 GMT
    01:18:11.096 -> Expires: -1
    01:18:11.096 -> Cache-Control: private, max-age=0
    01:18:11.143 -> Content-Type: text/ht
    l; charset=ISO-8859-1
    01:18:11.143 -> P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
    01:18:11.190 -> Server: gws
    01:18:11.190 -> X-XSS-Protection: 0
    01:18:11.190 -> X-Frame-Options: SAMEORIGIN
    01:18:11.224 -> Set-CooS,
    01:18:15.192 -> Sending Request to www.google.com
    01:18:15.822 -> create tcp - ERROR
    01:18:19.849 -> Sending Request to www.google.com
    01:18:20.473 -> create tcp - ERROR

As you can see, at first it starts ok, gives a buffer error, runs in error for a while, then runs OK again. This happens a couple times, then it runs only in error. I imagine this is some issue with the buffer of the ESP or the Arduino, but I'm not sure how to diagnose it further.

Things I have tried to fix the error:
 - As mentioned in the Firmware.ino example comments, I uncommented #define ESP8266_USE_SOFTWARE_SERIAL
 - Also as mentioned in the comment, I changed line 42 from 64 to 256. It didn't work either time.
 - There is a MAX_BUFFER_SIZE in the included ESP8266.h library that I also changed, from 300 to 256, because I thought that might help, but the error persisted.

  [1]: https://github.com/Circuito-io/ESP8266_SoftwareSerial/blob/master/examples/Firmware/Firmware.ino

body:
There's some heavy `String` usage in that library, would not recommend it for anything you want to be stable, especially with an Uno.

The library seems to create a connection by first clearing the `SoftwareSerial` buffer and then issuing the right AT command. It waits for 500ms for a response before giving up. I suspect the wait interval is sometimes not long enough for the module to receive, parse and handle the command before responding. So you should try increasing it to 2000 ms at line 773.

The `buffer is full` message just refers to the library's own buffer for holding received data, which is 300 bytes by default. The buffer's getting filled so quickly (and the `SoftwareSerial` internal buffer likely overrun too) because you're loading a webpage like Google's which has more than 300 bytes in the response header alone. It's even possible that by the time the next request commences with another AT command, the ESP8266 is still dumping the response from the previous request, and so the command's response is still way down the queue and so doesn't get read before the timeout.

Instead, try loading a simple webpage like `httpbin.org/ip`. That is, at lines 952, 954:

    char* request =  "GET /ip HTTP/1.1\r\nHost: www.httpbin.org\r\nConnection: close\r\n\r\n";

    if (createTCP("www.httpbin.org", 80))


message:
ESP8266 spend 10mA, even though It is in the deep sleep mode

I am using Nodemcu ESP8266. I want to know how much my ESP board consume the battery during sleep mode.
as the Mannual said it spend about micro-ampere, but my multi meter said it spend 10 mili-ampere, I cannot believe the result.

so please see My arrangement is right and give some advice

[arrangement image][1]

[![enter image description here][2]][2]

red line is for vin, black line is for GND.
black pin is COM, red pin is mA.

I set multimeter on 20mA, 200mA, it said it is 10mA.
when I change multimeter to 10mA, 1mA, microAmpere, number was overflowed.

I already connected to RST - D0, so It is properly sleep & wake up automatically. and here is my running code in the board

```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

void setup() {

}

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

ESP.deepSleep(60e6);

}
```

  [1]: https://i.stack.imgur.com/gTVLQ.jpg
  [2]: https://i.stack.imgur.com/mvWGD.jpg

body: `ESP.deepSleep(60e6, WAKE_RF_DEFAULT);` Try this code, it should decrease it a bit.


body: The Board you are using contains an ESP-12F Module, along with other chips that make it easy/possible to connect to UART over USB and thus flash the chip. This USB-to-UART converter chip isn't related to the ESP-12F Module, so is unaffected when the ESP goes to sleep, so the converter continues to draw about 10mA. You can't do anything about this unless you desolder it, or use a pure ESP-12F Module.