body:
I want to know how to connect an lcd i2c, with an led 8x8 matrix at the same time. The problem is, all the analog in pins are used, except A0 and A1. Using this tutorial:

https://www.makerguides.com/character-i2c-lcd-arduino-tutorial/

It says I must have analog pins A0-A2 with nothing connecting, except I have A2 connected, which is why both screens don't work right. So how can I use only pins A0-A1 with an lcd i2c? Thanks.

title: How to connect an lcd i2c using only pins A0 and A1 (SDA, SCL, GND, and VCC are given)

Answers: 1

body:
You may be finding `Connect to LCD via I2C, default address 0x27 (A0-A2 not jumpered)` confusing.  These refer to the I2C address selection lines of the IO expander (the PCF8574T) used on the I2C LCD display and not to the A0-A2 analog pins of the Arduino itself.

[![Location of address selection jumpers on I2C Adapter][1]][1]

The note `// Wiring: SDA pin is connected to A4 and SCL pin to A5.` **is** referring to the analog pins of an UNO (or Nano) because these pins also happen to carry the ATMega328P's I2C ("Wire") signals.

So there's nothing about using the I2C display that prevents you from using the Analog A0-A2 pins of the Arduino for other purposes.  Only the  Arduino's A4 and A5 pins are used to carry I2C/Wire.

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


body:
Folks,

There is a document named "[Complete Guide for RF 433MHz Transmitter.pdf][1]" available in the GitHub.

There is a a connection diagram showing the Data pin of the Transmitter connected to the pin 12 of the Arduino Uno.

The Transmitter sketch given in it is as follows:

```c++
#include <RH_ASK.h>
#include <SPI.h> // Not actually used but needed to compile

RH_ASK driver;

void setup()
{
 Serial.begin(9600); // Debugging only
 if (!driver.init())
 Serial.println("init failed");
}

void loop()
{
 const char *msg = "Hello World!";
 driver.send((uint8_t *)msg, strlen(msg));
 driver.waitPacketSent();
 delay(1000);
}
```

There is no mention of Pin 12 as part of the sketch. I am not sure how the Arduino knows the Transmitter Data input is connected to the Pin 12? Can someone please help?

Ranjith

  [1]: http://www.energiazero.org/arduino_sensori/Complete Guide for RF 433MHz Transmitter.pdf

title: Testing 433MHz Transmitter

Answers: 1

body:
In [RH_ASK.h][1] is:

```c++
RH_ASK(uint16_t speed = 2000, uint8_t rxPin = 11, uint8_t txPin = 12, uint8_t pttPin = 10, bool pttInverted = false);
```

So the argument has a [default value][2] specified here.  If you don't specify it, it assumes that default.

  [1]: http://www.airspayce.com/mikem/arduino/RadioHead/RH__ASK_8h_source.html#l00278
  [2]: https://en.cppreference.com/w/cpp/language/default_arguments


body:
Problem: I've made a circuit consisting of an 8x8 led matrix, which uses all of the digital pins on the Arduino UNO board, and I want to add an LED too it.

I tried looking around the internet but so far, I have not seen any solution on how to use a simple LED with no digital pins to spare.

So I ask, is it possible to connect an LED with no leftover digital pins? I just want to be able to turn the LED on and off.

Thanks.

title: Use a simple LED with no digital pins to spare

Answers: 1

body:
Just found this:

https://forum.arduino.cc/index.php?topic=311099.0

Turns out you can use the analog pins of an Arduino UNO using this:

```
pinMode(A1,OUTPUT);
digitalWrite(A1,HIGH);
```
You just have to list it as an analog pin. Seems to be working, don't think there are any downsides, as far as I see.


body: I am trying to make a social distance detector for a project of mine. There are many projects online about this, but none of them are the right ones. I'm trying to make a thing that attaches to a lanyard. My original plan was when a PIR sensor detected a human, it would trigger the ultrasonic sensor into measuring the distance between the lanyard and the human. The problem is, the PIR sensor was always displaying "high", and after doing some research, a PIR sensor can be only stationary. I am wondering if there are other easy and cheap options other than PIR sensors that can detect humans accurately? Thanks!

title: Arduino Project - Social distance detector

Answers: 0


body:
I tried to send random data to MQTT but it's not working and I get:
<pre>
{
   "m2m:rsp" : {
      "rsc" : 4004,
      "rqi" : "123456",
      "pc" : "Resource not found",
      "to" : "5a185cedc6ad749b:edb0b82be780ba6d",
      "fr" : "/antares-cse"
   }
}
</pre>
This is from mqtt.fx

This is my payload what should I do

```c++
    #include <SoftwareSerial.h> //koneksi ke modem

    #define TINY_GSM_MODEM_SIM7000
    #define TINY_GSM_DEBUG SerialMon
    #define BAUD 9600
    #define SerialMon Serial

    SoftwareSerial SerialAT(10, 8); // RX, TX ke modem

    const char apn[]  = "nb1internet"; //untuk gprs gunakan "internet"
    const char user[] = "";
    const char pass[] = "";
    byte randomValue = random(0, 37);
    const char *mqtt_server = "mqtt.antares.id"; //server antares
    const char *mqtt_user = "";
    const char *mqtt_pass = "";
    const int mqtt_port = 1883;
    const char *mqtt_client_name = "KEKW" + randomValue; // random

    //dibawah ini sesuaikan dengan akun atares kamu
    #define TOPIKPUB "/oneM2M/req/5a185cedc6ad749b:edb0b82be780ba6d/antares-cse/json"
    #define accessKey "5a185cedc6ad749b:edb0b82be780ba6d"
    #define projDev "ECSENSOR/pHnEC"

    // library modem dan mqtt
    #include <TinyGsmClient.h>
    #include <PubSubClient.h>

    #ifdef DUMP_AT_COMMANDS
      #include <StreamDebugger.h>
      StreamDebugger debugger(SerialAT, SerialMon);
      TinyGsm modem(debugger);
    #else

    TinyGsm modem(SerialAT);
    #endif
    TinyGsmClient client(modem);
    PubSubClient mqtt(client);

    long lastReconnectAttempt = 0;
    int val;

    void setup()
    {
      // Set debug console dan modem
      SerialMon.begin(9600);
      delay(10);
      SerialAT.begin(9600);
      delay(3000);

      String modemInfo = modem.getModemInfo();
      SerialMon.print("Modem: ");
      SerialMon.println(modemInfo);

      SerialMon.print("Waiting for network...");
      if (!modem.waitForNetwork(240000L)) {
        SerialMon.println(" fail");
        delay(10000);
        return;
      }
      SerialMon.println(" OK");

      if (modem.isNetworkConnected()) {
        SerialMon.println("Network connected");
      }

      SerialMon.print(F("Connecting to "));
      SerialMon.print(apn);
        if (!modem.gprsConnect(apn, user, pass)) {
        SerialMon.println(" fail");
          delay(10000);
          return;
      }

        SerialMon.println(" OK");

       // MQTT Broker setup
      mqtt.setBufferSize(512);
      mqtt.setServer(mqtt_server, mqtt_port);
    }

    boolean mqttConnect() {
      SerialMon.print("Connecting to ");
      SerialMon.print(mqtt_server);

      // koneksi ke MQTT Broker
      boolean status = mqtt.connect(mqtt_client_name,mqtt_user, mqtt_pass);

      if (status == false) {
        SerialMon.println(" fail");
        return false;
      }
      SerialMon.println(" OK");

      return mqtt.connected();
    }

    void loop()
    {

      //cek jika koneksi mqtt gagal maka ulang lagi
       if (!mqtt.connected()) {
        SerialMon.println("=== MQTT NOT CONNECTED ===");
        // Reconnect every 10 seconds
        unsigned long t = millis();
        if (t - lastReconnectAttempt > 10000L) {
          lastReconnectAttempt = t;
          if (mqttConnect()) {
            lastReconnectAttempt = 0;
          }
        }
        delay(100);
        return;
      }

      int val = random(0-450);  //TEST RANDOM DATA

      String pubString ;
     //JSON yang panjang untuk kirim data ADC ke antares
        pubString +=  F("{");
        pubString += F("\"m2m:rqp\": {");
        pubString += F("\"fr\": \"");
        pubString += String(accessKey) ;
        pubString += F("\",");
        pubString += F("\"to\": \"/antares-cse/antares-id/");
        pubString += String(projDev);
        pubString += F("\",");
        pubString += F("\"op\": 1,");
        pubString += F("\"rqi\": 123456,");
        pubString += F("\"pc\": {");
        pubString += F("\"m2m:cin\": {");
        pubString += F("\"cnf\": \"message\",");
        pubString += F("\"con\": \"{\\\"level\\\":");
        pubString += String(val);
        pubString += F("}\"");
        pubString += F("}");
        pubString += F("},");
        pubString += F("\"ty\": 4");
        pubString += F("}");
        pubString += F("}");

      // kirim atau publish ke antares
      SerialMon.println(pubString);
      char message_buff[pubString.length() + 1];
      pubString.toCharArray(message_buff, pubString.length() + 1);
      mqtt.publish(TOPIKPUB, message_buff);

    delay(5000);
    }
```

title: 4004 (NOT_FOUND) ON MQTT

Answers: 0


body:
I don't understand why the formatted string is displaying ?? instead of float values.
My code:

    #include <Arduino.h>
    #include <Wire.h>
    #include "SparkFunCCS811.h"
    #include <DFRobot_SHT3x.h>

    DFRobot_SHT3x sht3x(&Wire, /*address=*/0x44, /*RST=*/4);

    //* Get SHT31 readings

    void readSHT(float &temp, float &humid)
    {

        DFRobot_SHT3x::sRHAndTemp_t data = sht3x.readTemperatureAndHumidity(sht3x.eRepeatability_High);

        char shtVal[50];

        if (data.ERR == 0)
        {
            temp = data.TemperatureC;
            humid = data.Humidity;

            Serial.println(data.TemperatureC);
            Serial.println(data.Humidity);
        }

        snprintf(shtVal, 50, "Temp = %f  Humidity = %f", temp, humid);
        Serial.println(shtVal);
    }

    void setup()
    {

        Serial.begin(115200);

        //*Initialize the chip
        while (sht3x.begin() != 0)
        {
            Serial.println("SHT31 Initialization Failed");
            delay(1000);

            Serial.print("Chip serial number");
            Serial.println(sht3x.readSerialNumber());

            if (!sht3x.softReset())
            {

                Serial.println("Failed to Initialize the chip....");
            }
        }
    }

    void loop()
    {

        unsigned long newTime = millis();
        static unsigned long oldTime = 0;

        if (newTime - oldTime >= 5000)
        {

            float temp = 0.0;
            float humid = 0.0;

            oldTime = newTime;

            readSHT(temp, humid);
        }
    }

 & here is the output:
Here is what I get as output:

    21.23
    41.06
    Temp = ?  Humidity = ?

The function readSHT()has no problem displaying the actual values but why the formatted string shows ???. Am I doing something wrong?

title: snprintf doesn't display float values

Answers: 1

body:
The standard avr-libc does not have float support enabled in the `printf` family of functions. This is because float support would bloat your code massively, and most people don't need it.

It is possible to enable it through some black magic (I don't know what, but someone else may), but in general you don't want to since there are better ways.

Typically you would use `dtostrf()` to format your float into a `char` array separately. Or if all you are doing is printing to serial then you wouldn't even format it into a string in the first place.

```c++
Serial.print(F("Temp = "));
Serial.print(temp);
Serial.print(F("  Humidity = "));
Serial.println(humid);
```


body:
1. Title question. I do not need any receive communication pins, only transmission.

Actually, I need as many transmission pins as possible on any Arduino besides a Mega2560 (to re/write the EEPROM of slave devices). A Mega2560 has 23 TX/RX pin pairs.

Maybe I'm misunderstanding serial communication. And maybe some sort of multiplexing deal can work like One-Wire temperature sensors...such as `softwareSerials[x].write()`...

---

    SoftwareSerial serialOne(2, 3); // Software Serial ONE
    SoftwareSerial serialTwo(8, 9); // Software Serial TWO
                         // RX, TX

2. Is there a way to make all the pins using SoftwareSerial TX? Or do half need to be RX?

---

"Just take a better microcontroller, and that is all." - [user1829200][1]

3. What off-the-shelf microcontroller is geared for serial communication?

  [1]: https://stackoverflow.com/a/13415523/14327713

title: Can RX pin(s) be used as TX instead?

Answers: 2

body:
You should be (though I haven't tested it) be able to set the RX pin to an unused pin number, such as 255.  Then the RX pin will do nothing.

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

SoftwareSerial s0(255, 2);
SoftwareSerial s1(255, 3);
SoftwareSerial s2(255, 4);
SoftwareSerial s3(255, 5);
SoftwareSerial s4(255, 6);
// ... etc ...
```

The "can't have more than one instance" thing is to do with reception. You can't have more than one SoftwareSerial instance *receiving* at once - but you don't care about that, since reception is not being used.

body:
One way to communicate Arduino to Arduino device is UART (and Software Serial for additional pins). For the ESP32, it seems this allows 28 TX pins using Majenko's method (in their answer). In other words, slave 28 devices.

After further research, isn't I2C the clear route to go?

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

 - With more slave devices the less times per second to talk to them all
 - The application needs to have all the slave devices execute commands synchronously:
    - At least, the slave devices need to start functioning at the same time.

---

 - How many slave Uno's/Nano's can be connected to an ESP32?

> Each device on an i2c network has a 7-bit address, so a single network theoretically supports up to 128 slave devices. In practice though, the limit is much lower. i2c slave chips often support only 8 different bus addresses, no more than 8 of that chip can be attached to the same i2c network.

https://mindbleach.com/words/2012/10/23/i2c-and-device-limits

Unclear answer:

 - https://forum.arduino.cc/index.php?topic=159860.0
 - https://forum.arduino.cc/index.php?topic=367961.0

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


body:
While working with JSON parsing I noticed that the char type data string is written like this:

    char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
Why there are (escapes) \" ---\" used in the code? Why can't we use the string normally?

title: Why use \" in arduino code?

Answers: 1

body:
> Why there are (escapes) " ---" used in the code? Why can't we use the string normally?

Because escapes are required.

In C `"` means 'The start or end of a string', but `\"` means 'A double-quote character'.

There has to be a way to distinguish a double-quote character from a string delimiter so the compiler knows which is which. Without escapes your string would look like:

```c++
char json[] = "{"sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}";
```
and the compiler would find the end of the string at the second `"`, and then a load of junk before it finds the end-of-statement `;` character. It can't work out what `sensor":"gps","time":1351824120,"data":[48.756080,2.302038]}"` is supposed to be, since it isn't in the string, but after it.


body:
When I try to run my code so far with the menu and select buttons, it seems that it works, except that the main menu will not move past "Main Garden" to "Currants". There's also a problem with the submenu where after the first watering warning, pressing the select button makes it simply return to the main menu without lighting the LED on the LEDPower pin or running that watering routing for the whole watering interval.

The one guess I still haven't tried is that maybe I should change void MainMenu() to a Switch Case structure instead of If-Else?

.

edit:
```
.

title: Can someone help me figure out why my menu gets stuck?

Answers: 1

body:
Problem One (Menu not moving past `Main Garden` to `Currants`):

`MainOld` is used to increment `MenuState` but `MainOld` never gets incremented, which means it will never have a value greater than 0. Accordingly `MenuState` can
never be greater than 0 + 1.

Problem Two (Sub Menu looping back to main):

'Checking' the state of `LEDPower` like in `Water1()` is not the best way to accomplish what you want to accomplish. It *may* work but is not technically correct as `LEDPower` is a pin state and you never actually read the state.

The other issue in `Water1` is that `previousWaterMillis` doesn't get updated anywhere in your code, which means that anytime `Water1` is called more than 10 seconds after boot your solenoid will activate and then immediately deactivate. I would recommend a `while` loop inside your `Water1` function. ex.

```
void Water1(){
  digitalWrite(Relay1, HIGH);
  unsigned long currentMillis = millis();
  previousWaterMillis = millis();
  int LEDPowerState = digitalRead(LEDPower);

  while(currentMillis - previousWaterMillis <= WateringInterval){
    digitalWrite(LEDPower, HIGH);
    Serial.println("Watering Garden with LED Lit");
    currentMillis = millis();
  }

  digitalWrite(Relay1, LOW);
  digitalWrite(LEDPower, LOW);
  SubMenuState = 0;
  SubMenuOld = 0;
}

^^ This will illuminate your LED and activate the solenoid for the 10 secs you wish to water.


body:
I was trying to extract data from a multi-function meter with RS485 connectivity and I am using Arduino as master, Arduino Uno and multi-function meter are connected via MAX485 module.

I have tried some code but it returns an E2 error which means communication error.

Kindly explain me the program and help me to solve it.

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

#define MAX485_DE 3
#define MAX485_RE_NEG 2
ModbusMaster node;

void preTransmission()
{
  digitalWrite(MAX485_RE_NEG,1);
  digitalWrite(MAX485_DE,1);
}

void postTransmission()
{
  digitalWrite(MAX485_RE_NEG,0);
  digitalWrite(MAX485_DE,0);
}

void setup()
{
  pinMode(MAX485_RE_NEG,OUTPUT);
  pinMode(MAX485_DE,OUTPUT);
  digitalWrite(MAX485_RE_NEG,0);
  digitalWrite(MAX485_DE,0);

  Serial.begin(9600);

  node.begin(1,Serial);
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
}

void loop()
{
  uint8_t resultMain;

  resultMain = node.readHoldingRegisters(0x0100,6);
  Serial.print(resultMain,HEX);

  if (resultMain == node.ku8MBSuccess)
  {
    Serial.print(resultMain);
    Serial.print(node.getResponseBuffer(0x32));
  }
  delay(1000);
}
```

title: Arduino modbus program error

Answers: 0


body:
I couldn't find any library to use an "old" ESP32 (not the new ESP32-S2) as an HID connected physicaly to the Usb port (not over BLE pairing) to send keystrokes to the PC ...

Is there any solution? Any code example, so far?

Thanks in advance!

title: ESP32 USB HID/MIDI library (not the BLE one)

Answers: 1

body:
The ESP32 doesn't have USB. You can't do USB communication. All it has is (like the UNO) a USB to UART interface chip. Unlike the UNO this is *not* programmable (more like a cheap Chinese knock-off UNO clone in that respect).

You would need to couple it with a microcontroller that *has* USB and program *hat* to be your USB interface and communicate with it over some other communication medium, such as UART or I2C.


body:
I would like to know if it is possible to store a (little, basic) SqlLite DataBase (or of any other type) into the (old) ESP32.

I don't want to use an SD card for that (for which I already know it is possible).

Thanks in advance for any hint on this

title: Can i store a SqlLite DB into an (old) ESP32? (not using SD card)

Answers: 2

body:
I found these two post to be a useful answer to my question:

* [ESP32: Best way to store data frequently?][1]

* [Sqlite3 Library for ESP32 Arduino Core][2]

  [1]: https://stackoverflow.com/questions/63780850/esp32-best-way-to-store-data-frequently
  [2]: https://www.hackster.io/arun/sqlite3-library-for-esp32-arduino-core-a76ad1

body:
Yes you can - or you can certainly store it. ESP32 can use its flash as a filesystem (SPIFFS, LittleFS, FAT, etc) so you can store whatever data you like on there.

Whether the SQLite library can work with that file is another matter though, and is something you would have to explore yourself.

However for your use case using a database file is a bit silly. If all you want is some pre-defined runtime settings then all you really need is a simple text file. Maybe something like an INI file (key=value pairs) would be plenty for your needs, and pretty simple to parse without any libraries.


body:
I am trying to get Arduino nano and SIM800L module working together. I provided the module with the recommended external voltage of 4.0V (documentation states 3.6V - 4.2V) transformed via LM2596. The original source is 5V 3A.

LED on SIM800L blink once a second as stated in documentation when in an unconnected state.

The schema is the following:
```
                  Antena
                   \_/
                    |
Arduino    SIM800L  |  External 4.0V
             NET ---/
             VCC ----- +4.0V
D2 --------- RST
D3 --------- RX
D4 --------- TX
             GND ----- GND
```

I have already tried 3 different libraries for AT communication and also sending raw AT commands using writing to serial manually. I also tried another SIM800L module because I thought the module is faulty.

Here is the dump from serial communication:
```
[551135] ### TinyGSM Version: 0.10.9
[551139] ### TinyGSM Compiled Module:  TinyGsmClientSIM800
AT
��AT
�AT
H�j���[552012] ### Unhandled: Hj
AT
AT-���[552317] ### Unhandled: AT-
AT
��AT
��AT
�Z5
[553228] ### Unhandled: Z5
AT
␚)O���[553532] ### Unhandled: ␚)O
AT
AT���[553836] ### Unhandled: AT
AT
��AT
��AT
�)OK��[554748] ### Unhandled: )OK
AT
���[555053] ### Unhandled: 5
AT
���AT
��AT
��AT
�j�H�[556266] ### Unhandled: jH
AT
CC����[556570] ### Unhandled: CC
AT
AT���[556875] ### Unhandled: AT
AT
��AT
AT
���[557787] ### Unhandled: T
AT
�H����[558091] ### Unhandled: H
AT
AT���[558395] ### Unhandled: AT
AT
��AT
��AT
AT
jRO���[559610] ### Unhandled: jRO
AT
AT���[559915] ### Unhandled: AT
AT
��AT
��AT
AT
�
OK��[561128] ### Unhandled: OK
Failed to initialize SIM800L
```

As you can see the module is trying to negotiate the baudrate. By default, I use speed 9600 as stated in the documentation. When I use a different baudrate the module does not respond at all.

It seems the module replies and sometimes even correctly. Response to `AT` command should be `OK`.

Do you know how do I successfully negotiate the speed and establish reliable serial communication with the module? Do I miss any electrical components in my circuit like a capacitor or resistor? I tried to use capacitor 35V / 3300µF but without any difference. I think my power source is strong enough.

The source code is the following:
```c++
#define PIN_GSM_RST             2
#define PIN_GSM_TX              3
#define PIN_GSM_RX              4
#define GSM_BAUDRATE            9600

#define TINY_GSM_MODEM_SIM800
#define TINY_GSM_DEBUG          Serial
#define TINY_GSM_USE_GPRS       true
#define TINY_GSM_USE_WIFI       false

#include <Arduino.h>
#include <SoftwareSerial.h>
#include <TinyGsmClient.h>
#include <StreamDebugger.h>

SoftwareSerial serial_SIM800L(PIN_GSM_RX, PIN_GSM_TX);
StreamDebugger debugger(serial_SIM800L, Serial);
TinyGsm modem(debugger);
TinyGsmClient client(modem);

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

    Serial.println(F("Serial initialized"));

    serial_SIM800L.begin(GSM_BAUDRATE);
    delay(5000);

    while (!modem.init()) {
        Serial.println("Failed to initialize SIM800L");
    }
}

void loop() {
    //
}
```

title: SIM800L module on Arduino nano

Answers: 1

body:
Thanks to @PeterPaulKiefer here is the answer.

External power for SIM800L module GND pin needs to be connected to both SIM800L module GND pin and Arduino nano GND pin. (e.g between RST and R2 pin on Arduino nano)

In order for the calling function to work, you also need to use a capacitor on SIM800L VCC and GND pins. I used 35V, 3300µF.

Schema:
```
                  Antena
                   \_/
                    |
Arduino    SIM800L  |  External 4.0V
             NET ---/
             VCC ----- +4.0V
 D2 --------- RST   |
 D3 ---------  RX  === Capacitor (35V, 3300µF)
 D4 ---------  TX   |
GND --------- GND ----- GND
```


body: How to use `SoftwareSerial.Write` without blocking if buffer is full? `Serial.write` blocks if the buffer is full. So I need to check `Serial.availableforwrite` before calling write to prevent blocking. But there is no `SoftwareSerial.availableforwrite`. How can I use `SoftwareSerial.Write` without blocking?

title: Non-blocking SoftwareSerial.Write

Answers: 1

body:
In short, you don't.

The SoftwareSerial implementation for AVR [doesn't have an outbound buffer][1] at all.
It just turns the interrupts off during each character outbound and it [sends them all immediately][2].

This means a call to SoftwareSerial's write simply **will** block until all of the data you've tried to send has in fact been sent.  If you can't afford to wait for your data to go out on the TX line *now*, then it's up to you to send it later when you *can* afford to wait.

SoftwareSerial has no [flow control][3].  When you write(), the data is sent out on the TX pin regardless of whether anything is present on the other side of the connection.  And when present, the data is still transmitted regardless of whether other side considers itself "ready" to receive.  There's simply no feedback from the receiver to tell the sender to stop.  So SoftwareSerial itself will never block owing to these things.

  [1]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/libraries/SoftwareSerial/src/SoftwareSerial.cpp#L472
  [2]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/libraries/SoftwareSerial/src/SoftwareSerial.cpp#L436
  [3]: https://en.wikipedia.org/wiki/Flow_control_(data)


body: I have the mini arduino breadboard. The pins go from A to J and 1 to 17. On the larger breadboard, there are symbols + and -. My breadboard doesn't have those two sections to put wires in. Does anyone know what to do?

title: Where is the positive and negative holes on the arduino mini breadboard?

Answers: 1

body:
> Does anyone know what to do?

Do whatever you want to do.

There's nothing special about the +/- rails of a breadboard - they're just chunks of metal that go along instead of across, and are longer, with more holes, and someone has helpfully coloured them red/blue and added some symbols.

If you want a common place for + and - then just choose a common place for + and -.


body:
I am trying to program an adafruit pygamer (which says it's compatible with Arduino). I have added the ZIP folder for the library into the library folder om my PC where all of my folders are supposed to be stored, one thing I managed to find out for a start was that the library folder for the library itself that was installed from GitHub contained a dash in the filename so I replaced that for an underscore. The actual error message that seems to come up now is this:

    'Adafruit_Arcada' does not name a type; did you mean 'Adafruit_SPITFT'?

This error comes up from when I try to use the:

    #include "Adafruit_Arcada.h"

    Adafruit_Arcada arcada;
lines

Within the library folder that I want to try and use there are the code examples within the library folder inside the examples sub-folder

I have tried following a step by step guide into one potential way of trying to solve this problem by looking at a tutorial by adafruit on how to step by step install zip folder libraries. Something tells me though that this error that I am getting is to do with one of the .h or .cpp files within the library itself.

The link for the library itself is here: https://github.com/adafruit/Adafruit_Arcada

In addition, when I look in the `Adafruit_Arcada.h` file I can actually see that there is no `Adafruit_Arcada` class but there is an `Adafruit_SPITFT` one. I know this point might seem like a bit of a no-brainer but I just thought it would be useful to try and find out what could potentially be going on and provide evidence of what I have already tried to do.

When I changed the `Adafruit_Arcada arcada;` to `Adafruit_SPITFT arcada;` (thinking this could potentially resolve the issue because within the `Adafruit_Arcada.h` file there is a class called `Adafruit_SPITFT and not`Adafruit_Arcada`), this brought up another error which was the following:

    simpletest:2:17: error: no matching function for call to 'Adafruit_SPITFT::Adafruit_SPITFT()'

title: Adafruit_Arcada' does not name a type;

Answers: 1

body:
There are some instructions at:

[Pygamer setup][1]

That need to be followed in order to permit the Arduino IDE to work with the Pygamer.  It's not clear that you have followed any or all of these instructions.

I recommend that you carefully follow ALL the steps and then start with the simple example to test that you are building and uploading properly.

Then move on to the Adafruit example that uses the Arcada library.

  [1]: https://learn.adafruit.com/adafruit-pygamer/setup


body: Question is pretty straight forward: How much amps and voltage do I need for 2 SG90 servos? I want to use 4 but you might already know that Arduino Uno only has 2 5V ports.

title: How much voltage and amps for 2 SG90 servos?

Answers: 1

body:
The SG90 servo datasheet is here:

[SG90 Servo Datasheet][1]

As you can see, the voltage specification is 4.8 - 6.0 Volts.  But you do NOT want to power this or any other servo via the Arduino.  Servos are quite "noisy" electrically and this can cause instabilities with your Uno.

You want to supply power to the servo directly from a +5V power supply.

I don't see the current draw for this servo specified so you will need to do your own measurements based on the loading of the output shaft.  Be aware that these draw more current with increased load on the shaft.

As far as the control signal, the Arduino Uno can certainly drive it via its PWM outputs.

  [1]: http://www.ee.ic.ac.uk/pcheung/teaching/DE1_EE/stores/sg90_datasheet.pdf


body:
I'm trying to compare a char array that I'm assembling to a string and I'm having trouble comparing the strings.

I'm getting the data for the char array as a set of bytes and I'm compiling it into a char array like this:

```
void messageHandler(char *topic, byte *payload, unsigned int length)
{
  char buffer[length];
  for (int i = 0; i < length; i++)
  {
    buffer[i] = (char)payload[i];
  }
```

So grabbing each of the ASCII codes and converting it into a character as I add it to the buffer.

After I do that I'm trying to print the buffer to the monitor and then compare it to a string. Though it's not working:

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

I know I'm getting all of those extra characters in the println b/c the buffer doesn't end in `0` so print keeps reading out memory bytes till it hits the zero, but I don't know why `strcmp` isn't showing the buffer matching the string `"ravenclaw"`.

I'm sure it's for the same "missing the null terminator" issue, but I'm not sure how to fix it. Help is appreciated!!

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

title: strcmp doesn't seem to work

Answers: 2

body:
You seem to already understand that it's not null-terminated and that's why it's not working the way you expect.  So, I'll take a different tact for "how to fix it".

You can simply not treat the payload as a string, and instead use `memcmp`, as in:

```c++
if (length == 9 && memcmp(payload, "ravenclaw", 9) == 0) {
```

`memcmp` behaves similarly to `strcmp`, except that it isn't looking for a null terminator. It just compares however many bytes (chars) you specify.  In practice you may want to use a variable to hold "ravenclaw" and to strlen() on it rather than specifying the length separately as I've done above, e.g.:

```c++
static const char ravenclaw[] = "ravenclaw";
static const size_t ravenclaw_len = sizeof ravenclaw - 1;
if (length == ravenclaw_len && memcmp(payload, ravenclaw, ravenclaw_len) == 0) {
```

or any number of variations on that which might use `strlen()`, or a pointer rather than array (if not using `sizeof`) or `PROGMEM` with `strlen_P()` and `memcmp_P()` or... etc, etc, possibly putting this into a function so you can reuse it.

---

As a side note, if you know payload contains non-null-terminated text that you want to print, you can use the overload of `write()` that allows you to specify the length.

```c++
Serial.write(payload, length);
```

body:
The easier way to simply the code is to use `strcpy` to create a buffer that is 1 byte longer than the `length` and then terminate it with `\0`.

    void messageHandler(char *topic, byte *payload, unsigned int length) {
      char buffer[length+1];
      strcpy(buffer, (const char*) payload);
      buffer[length] = '\0';

      Serial.println(buffer);

      int matched = strcmp(buffer, "ravenclaw");
    }


body:
For experimentation I want to import or receive into Arduino the output data from a TMS1000 (1980s) data bus.  For model train controller Hornby Zero1, and the bus sends data to receivers, for loco number, speed, direction etc. I have all the data structure etc) Is it feasible  to import to Arduino, and export from the same Arduino back to the original bus.    Just to see it working, and then later experiment with the data in the Arduino.
What libraries would be best ?
Thanks
Charles Harris

title: Import into Arduino a vintage data bus from TMS1000

Answers: 1

body:
You're not going to find any pre-built libraries for this task which is somewhat unusual but not at all impossible.

Basically all you need to do is to connect the TMS1000 address/data and strobe lines to Arduino inputs and write yourself some relatively simple code to detect the various TMS1000 bus states and capture them when they happen.  In order to detect specific events as you have mentioned you will need to know more about the TMS1000 software that's running and what I/O devices that it's selecting.  But again, that's all pretty straightforward.

Keep in mind, however, that you are going to have to perform level shifting on ALL the inputs from the TMS1000.  This old TI chip was implemented using a PMOS (i.e. a predecessor to both NMOS and CMOS) and uses a NEGATIVE power supply instead of the more common today POSITIVE supply.

So rather than being powered by a +5V supply the way an Arduino is, the TMS1000 is powered by a -15V supply.  In this case ground is still at 0V but Vdd is -15V.  That means the I/O signals adhere to a different scheme as noted in the datasheet:

[![TMS1000 Data][1]][1]

You can view the datasheet yourself at:

[TMS1000 Datasheet][2]

But what this means is that a LOW (i.e. Vil) is at -15V and a HIGH (i.e. Vih) is at 0V.  You will need to translate these voltages so that you don't damage either the TMS1000 or the Arduino and you get the correct levels on the pins that you are watching.

The TMS1000 datasheet has some suggested circuits for interfacing to 74LSxx series parts (i.e. 5V logic) which will probably get you started.  Note that the simplest method involves running the 5V logic with its VDD at 0V and it's "ground" at -5V.  While this might seem odd, the Arduino will not know the difference as voltage is always relative.

  [1]: https://i.stack.imgur.com/QDrpF.png
  [2]: http://www.bitsavers.org/components/ti/TMS1000/TMS_1000_Series_Data_Manual_Dec76.pdf


body:
I am writing a program that echos back the message sent to the web socket server on a host machine. When running the ESP module, the connection is established but immediately disconnects as seen in the first image. I originally thought this maybe a result to the host machines firewall, however, using my laptops connection, I was able to produce the desired echo. Is the constant disconnect a result in different protocols or something I am missing?

WebSocketServer on host machine (modeled off example)
```
import asyncio

from autobahn.asyncio.websocket import WebSocketServerProtocol, \
    WebSocketServerFactory

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {0} bytes".format(len(payload)))
        else:
            print("Text message received: {0}".format(payload.decode('utf8')))

        # echo back message verbatim
        self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))

if __name__ == '__main__':
    factory = WebSocketServerFactory("ws://127.0.0.1:9000")
    factory.protocol = MyServerProtocol

    loop = asyncio.get_event_loop()
    coro = loop.create_server(factory, '0.0.0.0', 9000)
    server = loop.run_until_complete(coro)

    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    finally:
        server.close()
        loop.close()
```

ESP8266 modeled in [arduinoWebSockets](https://github.com/Links2004/arduinoWebSockets/blob/master/examples/esp8266/WebSocketClientSocketIO/WebSocketClientSocketIO.ino)
```
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ArduinoJson.h>

#include <WebSocketsClient.h>
#include <SocketIOclient.h>

#include <Hash.h>

ESP8266WiFiMulti wiFiMulti;
SocketIOclient socketIO;

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case sIOtype_DISCONNECT:
            Serial.printf("[IOc] Disconnected!\n");
            break;
        case sIOtype_CONNECT:
            Serial.printf("[IOc] Connected to url: %s\n", payload);
            socketIO.send(sIOtype_CONNECT, "/");
            break;
        case sIOtype_EVENT:
            Serial.printf("[IOc] get event: %s\n", payload);
            break;
        case sIOtype_ACK:
            Serial.printf("[IOc] get ack: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_ERROR:
            Serial.printf("[IOc] get error: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_EVENT:
            Serial.printf("[IOc] get binary: %u\n", length);
            hexdump(payload, length);
            break;
        case sIOtype_BINARY_ACK:
            Serial.printf("[IOc] get binary ack: %u\n", length);
            hexdump(payload, length);
            break;
    }
}

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

    //Serial.setDebugOutput(true);
    Serial.setDebugOutput(true);
    Serial.printf("[SETUP] starting up");

    Serial.println();
    Serial.println();
    Serial.println();

      for(uint8_t t = 4; t > 0; t--) {
          Serial.printf("[SETUP] BOOT WAIT %d...\n", t);
          Serial.flush();
          delay(1000);
      }

    // disable AP
    if(WiFi.getMode() & WIFI_AP) {
        WiFi.softAPdisconnect(true);
    }

    wiFiMulti.addAP("ssid", "password");

    //WiFi.disconnect();
    while(wiFiMulti.run() != WL_CONNECTED) {
        delay(5000);
        Serial.println("Retrying...");
    }

    String ip = WiFi.localIP().toString();
    Serial.printf("[SETUP] WiFi Connected %s\n", ip.c_str());

    // server address, port and URL
    socketIO.begin("local host address", 9000);
    // event handler
    socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;
//int attempts = 0;
void loop() {
    socketIO.loop();
}
```
[![Serial Monitor Output of the ESP8266 ][1]][1]
[![Connection output from Python WSS][2]][2]

  [1]: https://i.stack.imgur.com/AKIR1.png
  [2]: https://i.stack.imgur.com/O7cR9.png

title: ESP8266 SocketIOclient constant disconnect with Python WebServerSocket

Answers: 1

body:
After testing the server on the host machine using an additional computer, I was able to produce the desired output. I would suspect it is an issue within the library or mis-use/understanding. I found a [post](https://forum.arduino.cc/index.php?topic=522526.0) that suggested the library was the problem and ended up using this [library](https://github.com/gilmaimon/ArduinoWebsockets) instead.

Using the [example implementation](https://github.com/gilmaimon/ArduinoWebsockets/blob/master/examples/Esp8266-Client/Esp8266-Client.ino) , I was able to achieve the desired results.


body: I wanted to do a machine learning project in Arduino UNO R3. But I came to know that the processor(ATMEGA328P) isn't capable of supporting the processing power needed for machine learning. So is there any other processor that is better than ATMEGA328P for machine learning that is supported in UNO? If not any other way that I can do it?

title: What processor can I replace on behalf of ATMEGA328P, to get more processing power for machine learning in UNO

Answers: 2

body:
The Arduino blog recommends this: https://store.arduino.cc/nano-33-ble-sense.

See: https://blog.arduino.cc/2019/10/15/get-started-with-machine-learning-on-arduino/

I know Arduino has been talking about machine learning for about a year or so. Here's the Google search I used to find this: [Arduino machine learning](https://www.google.com/search?q=Arduino+machine+learning&oq=Arduino+machine+learning&aqs=chrome..69i57j69i60.9678j0j7&client=ms-android-google&sourceid=chrome-mobile&ie=UTF-8).

Here's a kit you can buy too: https://store.arduino.cc/usa/tiny-machine-learning-kit.

body:
You can't just replace the processor on the UNO with something better. The 328P is pretty much the best MCU there is in the pinout for that board.

Instead you can replace the whole UNO with something more powerful.

My board of choice for AI work would have to be one based on the Kendryte K210 chip, such as the [Maixduino](https://www.seeedstudio.com/Sipeed-Maixduino-for-RISC-V-AI-IoT-p-4046.html) (which is helpfully in an UNO footprint).  The K210 is a dual-core 64-bit 400MHz RISC-V CPU with embedded neural network co-processor. On the Maixduino it's also coupled with an ESP32 for WiFi/Bluetooth.  That's 2x 400MHz 64-bit cores, 2x 32-bit 240MHz cores, one low-power FSM core, and a neural network core all on one board.


body:
I am making a small project, and for that, I need to measure the time between 2 inputs.
basically, a program to measure the time elapsed from when digital pin 2 is high to when it again becomes high.

title: Measure the time between 2 inputs

Answers: 2

body:
You could do something like this:

    unsigned long startTime;
    unsigned long elapsedTime;

    // Any needed setup stuff
    void setup()
    {
      ...
    }

    void loop()
    {
      // Wait for input to go high
      while(digitalRead(2) == LOW);

      // Start timing
      startTime = millis();

      // Wait for input to go low
      while(digitalRead(2) == HIGH);

      // Now wait for it to go high again
      while(digitalRead(2) == LOW);

      // Now get the time interval
      elapsedTime = millis() - startTime;

      // Do whatever with the result.
      ...
    }

Keep in mind that the millis() value will overflow every 50 days or so.  If you need to run this continuously, you need to check for an overflow and adjust things accordingly.

body:
The way to go depends on the time range, that the event will have. The Arduino framework already includes a function for timekeeping: `millis()`. It returns the number of milliseconds since the startup (much like a clock) and measures the time via the hardware Timer0 and it's interrupts. This function will work good in the 2 digit millisecond range and above. With single digit millisecond or the microsecond domain, you should instead use `micros()` with works similar, but returns the microseconds since startup. For the low microsecond range and below you would need to work directly with a dedicated hardware timer, configuring it via its hardware registers.

Here I would show the principle of `millis()`/`micros()`, since that is most likely what you need. In the following I will only write `millis()`, but all the calculations can also be done with `micros()`. The only difference for the calculations is the factor 1000 between milli- and microseconds.

When you look at your watch and want to measure a time difference, you take note of the start time and the end time. Then you calculate the difference to get the event duration. You can do the same with `millis()`:

    unsigned long starttime = millis(); // take note of start time
    // here the event to measure
    unsigned long endtime = millis(); // take note of end time
    unsigned long duration = endtime - starttime; // duration of the event in ms

So in your code you need to check for a rising edge of your signal. On every rising edge you calculate the time difference between the last timestamp and the current time. Then you reset the timestamp. Something like this:

    int last_input_state = LOW;
    unsigned long timestamp;

    //setup here

    void loop(){
        int current_input_state = digitalRead(2); // get current signal level
        if(current_input_state && !last_input_state){ //check, if signal is now high and was low before
            unsigned long current_time = millis(); // take note of the current time
            unsigned long duration = current_time - timestamp; // calculate the duration and do something with it
            timestamp = current_time; // update the timestamp with the current time
         }
         last_input_state = current_input_state; // update the last input state with the new measured one
    }

Note:

- This code is non-blocking. It needs to run fast and continuously to work correctly. You cannot do long blocking things in the rest of your code, like using high `delay()` calls, but you shouldn't do that either way, since that will block anything from going on.
- You can go even further to lift the weight from your CPU and use an interrupt to sense the rising edge. You could use `attachInterrupt(digitalPinToInterrupt(pin), service_function, RISING);` and provide a `void service_function()`, which does the timestamp measurement and calculation (basically the same code as in the if statement of the code above).


body:
I'm reading from a temperature sensor. I get float values with 2 decimals. I want to round them to nearest 0.1.

This is my sketch:

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

void loop() {
  float temperature = 21.81;
  float rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.81 ->");
  Serial.println(rounded_temperature);
  delay(1000);

  temperature = 21.79;
  rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.79 ->");
  Serial.println(rounded_temperature);
  delay(1000);

  temperature = 21.77;
  rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.77 ->");
  Serial.println(rounded_temperature);
  delay(1000);

  temperature = 21.70;
  rounded_temperature = round(temperature * 10) / 10.0;
  Serial.print("21.70 ->");
  Serial.println(rounded_temperature);
  delay(1000);
}
```

This is the output:

```shell
21.81 ->21.85
21.79 ->21.75
21.77 ->21.75
21.70 ->21.75

```

And this is the output I would... Rounded to "0" and not "5".

```shell
21.81 ->21.80
21.79 ->21.80
21.77 ->21.80
21.70 ->21.70
```

title: Rounding to the next upper (or lower) 0.1

Answers: 3

body:
`float` variables do not have a number of decimal places. They are merely an approximation anyway. Instead it's when you *print* that you decide how many decimals to display.

```c++
Serial.println(temperature, 1); // Print with 1 decimal place
```

Or to put it into a string:

```c++
char buf[8]; // Room for 7 characters plus NULL terminator
float val=23.81;

dtostrf(val, -7, 1, buf); // 7 characters with 1 decimal place and left aligned (negative width)
```

body:
I often store the floating point data that I get from a sensor in integer to preserve the decimal precision that I want by multiple it by 10 before casting it into an integer. It is easier and more efficient (compare to string or float) to send over to another system. This is also how many sensors representing and store the floating data (e.g. TMP275) as well.

To achieve what you want, here is what I would do:

    #include <math.h>

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

      float i=21.81;
      float j=21.79;
      float k=21.77;
      float p=21.70;

      // convert to integers
      int l = (int) round(i*10);  // 218
      int m = (int) round(j*10);  // 218
      int n = (int) round(k*10);  // 218
      int o = (int) round(p*10);  // 217

      // Convert back to actual floating point for display
      Serial.println((float)l/10);  //21.80
      Serial.println((float)m/10);  //21.80
      Serial.println((float)n/10);  //21.80
      Serial.println((float)o/10);  //21.70
    }

body:
Using roundf() function:

float rounded_temperature = roundf(temperature * 10) / 10;


body:
I had problems with connecting my devices via I2C. The "requestfrom" constantly hanged and the endtransmission sometimes gave NACK responses.

After disconnecting the devices from 12V and powering one of them via USB (vin with which it was connected to the other arduino's became 3.8V) they stopped misbehaving and worked together in harmony.

How is this possible? Am I missing something? An Arduino Nano Every should be driven between 6-21V?

All devices are "Arduino Nano Every"'s. They used to get 12V directly on Vin and are connected together in a chain by Vin,GND,A5(SCK),A4(SDA)

The master is in the middle of the chain so that the distance is max 20cm.

I also tried powering them via vin with 9V and 5V. Had the same issue.

Already big thanks for the help.

title: Arduino Nano Every Vin 5V fixes I2c problems

Answers: 1

body:
SO... In the datasheet it says you should use 7-21V on VIN. This gave the problem. I powered the arduinos directly from 5V on the vin. This fixed all I2C problems. Haven't had any problems anymore after changing this.

cheers to all.


body:
i've just got the EthernetShield and watched a tutorial on how to host a html page with it but i can't find my html page on the SD card.

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

    byte mac[] = {0xA8, 0x61,0x0A, 0xAE, 0x3A, 0xC4 };

    EthernetServer server(80);

    File webPage;

    void setup() {
      Ethernet.begin(mac);
      server.begin();
      Serial.begin(9600);

      Serial.println(Ethernet.localIP());

      Serial.println("Initializing SD card...");
      if(!SD.begin(4)){
        Serial.println("ERROR - SD card initialization failed!");
        return;
      }
        Serial.println("SUCCESS - SD card initialized.");
        if(!SD.exists("index.htm")){
          Serial.println("ERROR - Can't find index.htm file!");
        }
          Serial.println("SUCCESS - Found  index.htm file.");
    }

    void loop() {
       EthernetClient client = server.available();
       if(client){
        boolean currentLineIsBlank = true;
        while(client.connected()){
          if(client.available()){
            char c = client.read();
            if(c == '\n' && currentLineIsBlank){
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");
              client.println();

              webPage = SD.open("index.htm");
              if(webPage){
                while(webPage.available()){
                  client.write(webPage.read());
                }
                webPage.close();
              }
              break;
            }
            if(c == '\n'){
              currentLineIsBlank = true;
            }
            else if(c != '\r'){
              currentLineIsBlank = false;
            }
          }
        }
        delay(1);
        client.stop();
       }
    }
[![enter image description here][1]][1]

When i save the HTML file i can't save it with the .htm format

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

  [1]: https://i.stack.imgur.com/KKpuJ.png
  [2]: https://i.stack.imgur.com/CaiR4.png

title: Ethernet Shield web server - Can't find the index.htm file

Answers: 1

body:
Windows is hiding the extension from you.

The file you showed is either `index.htm` or `index.html`. If it's the latter, you could change the windows setting to "show extensions for know filetypes", <strike>or change the sketch so it uses `index.html` instead of `index.htm. I'd go with the latter, as it's the easiest.</strike>

EDIT: the SD library doesn't seem to like file extension that are longer than 3 characters. So changing the code to use "index.html" doesn't work.


body:
Having a skech running on ESP8266 as well as ESP32 with the ability to update via OTA, uploading the wrong binary (upload to ESP8266 compiled for ESP32, and vice versa) leads to crashing the MCU and not being able to do OTA Updates any more.

The Update is done in the simple usual way: Upload binary file and call the methods from the Update Class (begin(), write(), and end()).

Is there any way to check if the uploaded file matches the architecture of the MCU before starting the update?

Edit:

Both the ESP8266 and the ESP32 Updater class check for an "IMAGE_MAGIC" value in the upload header; but that is defined as "ESP_IMAGE_MAGIC = 0xe9" in both cores. So none of them will refuse to update the wrong one.

Edit 2:

Found a simple workaround that satisfies our needs at the moment: As the arduino IDE saves the binaries with a name like <sketch_name>.<board_name>.bin, we just compare the board name as part of the uploaded filename: `if (upload.filename.indexOf(MATCH) > 0) ...`, where `MATCH` is the respective board name. As they are pin compatible, we use "d1_mini.bin" and "d1_mini32.bin".

Edit 3:

When the webserver tries to abort the upload with `403 Forbidden` (because of wrong file), the browser continues to send data until the upload is done. After that, it displays the error message. Thus, even when the filename does not match, it is a waste of time and bandwidth. The only possibility to avoid this is to do a `server.client().stop()`, but then the browser will not display the message sent, just something like "connection broken". This does not confirm with the respective RFCs.

This is not really a final solution, so I'ld appreciate any better idea.

Richard

title: Is it possible to check for correct architecture on OTA update (ESP32 or ESP8266)?

Answers: 1

body: I assume you are the one creating the OTA update.  If so, then why don't you just include a "signature" in the code that is the architecture, i.e. ESP8266 vs. ESP32 and then check for that in your updater code so that it will not install an update for the wrong CPU.


body:
```c++
#include "VernierLib.h"

VernierLib Vernier;

#define led 13

float sensorReading;

void setup() {
  Serial.begin(9600);
  Serial.println(Vernier.sensorName());
  Vernier.autoID();
}

void loop() {
  float base_temp;
  base_temp = Serial.parseFloat();
  sensorReading = Vernier.readSensor();
  Serial.print(sensorReading);
  Serial.print(" ");
  Serial.println(Vernier.sensorUnits());
  Serial.println(base_temp);
  if (base_temp > sensorReading) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
  delay(3000);
}
```

That's the code, I have a question. When I write the temperature to Serial, it lasts only until the end of one loop.

How to keep the same temperature in the next loop?

title: How to transfer constants from one loop to next one

Answers: 2

body:
There are two things here you need to consider.

First is that your variable is a "local" variable. This kind of variable is created at the start of each iteration, then discarded at the end of that iteration.

There's two things you can do to "fix" this:

1. Make the variable "global" - that is, move the definition out of `loop()` to the "global" scope (put it at the top of your program). It is then only created once and never discarded.
2. Make the variable "static" - that is, add the `static` keyword to it. It is then created on the first iteration only, and never discarded.

The second thing to consider is that you have no "There is no value" concept. Every iteration you parse a new float, whether there is one there or not. And if there isn't one then it just gives you `0`. So you need to come up with some way of saying "I have entered a number, so parse it". The simplest thing is just to assume that all values of 0 are "no number entered", but that of course prevents you ever entering 0 as a valid input.

body:
Something like this should work (untested, but you get the idea; the explanation is in the comments):

```c++
void loop() {
  static float base_temp = 21;     // Or whatever default starting value you want
  static float t = 0;              // A temporary store for Serial.parseFloat()

  t = Serial.parseFloat();         // Read t; if Serial.parseFloat() times out, it will return 0.00
  if (t != 0.00) {                 // If something else than 0.00 is in t
    base_temp = t;                 // Update base_temp with t
  }                                // Note: You can't set base_temp to exactly 0.00 with this set-up
  sensorReading = Vernier.readSensor();
  Serial.print(sensorReading);
  Serial.print(" ");
  Serial.println(Vernier.sensorUnits());
  Serial.println(base_temp);
  if (base_temp > sensorReading) {
    digitalWrite(led, HIGH);
  } else {
    digitalWrite(led, LOW);
  }
  delay(3000);
}
```

In this code `0.00` means that "no value was entered", so you can't set the temperature to *exactly* 0.00 with this set-up; 0.01 should work fine, though.


body:
I have an ATmega1284p and I need to have the TXD0 (i.e. pin 9) set to LOW, before going to sleep. After waking up, I want to restore UART0 communication to work as expected. Here is my code:

    Serial.begin(38400,SERIAL_8N1);

    *do Stuff*

    Serial.end();
    //pinMode(9,OUTPUT);
    //digitalWrite(9,LOW);
    //UCSR0B &= ~bit (RXEN0);  // disable receiver
    //UCSR0B &= ~bit (TXEN0);  // disable transmitter
    cli();
    set_sleep_mode (SLEEP_MODE_PWR_DOWN);
    sleep_enable();
    // turn off brown-out enable in software
    //MCUCR = bit (BODS) | bit (BODSE);  // turn on brown-out enable select
    //MCUCR = bit (BODS);        // this must be done within 4 clock cycles of above
    sleep_bod_disable();  //disable brown-out detection
    sei();             // guarantees next instruction executed
    sleep_cpu ();              // sleep within 3 clock cycles of above
    sleep_disable();

    //  UCSR0B |= bit (RXEN0);  // enable receiver
    //  UCSR0B |= bit (TXEN0);  // enable transmitter
    //pinMode(9,OUTPUT);
    //digitalWrite(9,HIGH);
    //delay(100);
    //pinMode(9,INPUT_PULLUP);
    Serial.begin(38400,SERIAL_8N1);
    delay(1000);
    Serial.println("- Good Morning");

    *do Stuff*

You can see in comments all the different things I tried:

 - Using `Serial.end()` and then, after waking up, `Serial.begin()`
 - Using the `UCSR0B` register
 - Using `digitalWrite` to set the pin to `LOW` and then, after waking up, either setting it to `high`, or setting it as `input`

All of the above combinations have the common problem that the cpu hangs after waking up, and the Serial is never restarted to print `good morning` message, neither does the program continue to execute further down.

title: Set TX, RX to LOW before sleeping, re-enable uart after waking up

Answers: 1

body:
After trying many different alternatives, it turns out that my mistake was that, foolishly, **I had included Serial printing inside my ISR routines**, which where accessed when my interrupt fired, in order to wake my uP. As a result, **`Serial.print` was called, with *Serial* being closed** (before issuing the `Serial.begin` command to restart it), thus breaking my uP.

**Extra:** Just wanted to comment about using Serial.print inside ISRs. Although it can lead to unexpected problems like this one, or timing issues (ISR would take too long to execute) and is definitely a bad practice, it can sometimes be useful for debug purposes during development to print some kind of message there.

Printing a message takes long, and the ISR will return before the message is completely transmitted, with the potential to cause a lot of headache. Also, interrupts are disabled inside ISRs, so delay() is not working to do some kind of flow control. The best way to print messages in ISRs that I have come across so far, is by using Serial.flush() before exiting the ISR, making sure the message is completely transmitted.


body:
I was making a project with Arduino Uno ,
It's working is like this it connects to a key pad and a 7segment display ,and when you press a run button connected to Arduino it should run the code written.

I don't want code for display and keypad but for executing a string like we can do in python- **exec("print (8)")**

Please help me and ask any information you need to solve it

title: How can I execute a string in my Arduino Uno board?

Answers: 2

body:
Unless you want to implement some form of scripting engine, you can't.

Arduino code is compiled code, not interpreted code. There is no way of converting text into runnable code, since that is done by your computer at compile time, not by the Arduino at run-time.

The only thing you could possibly do is write some form of scripting engine which reads text and interprets it in some meaningful way to perform operations. That is not a trivial task, so you have to ask yourself: is this *really* what you want to do? Are you going about tackling your problem in the right way?

body:
As stated in Majenko's answer, you would need an interpreter running on
the Arduino. Python is too large to run on an Uno, although [it can run
on some more powerful microcontrollers][uPi].

A Web search for Arduino interpreters yields quite a few promising
options. I have not tested any of them:

* [Firmata][]
* [Forth][]
* another [Forth-ish language][]
* [Lisp][]
* [BASIC][]
* a [C-like language][]

The Forth language is quite popular when you need an interpreter with
minimal footprint.

[uPi]: https://micropython.org/
[Firmata]: https://github.com/firmata/arduino
[Forth]: https://flashforth.com/
[Forth-ish language]: https://github.com/tschaer/tofish
[Lisp]: http://www.ulisp.com/
[BASIC]: https://github.com/robinhedwards/ArduinoBASIC
[C-like language]: https://n.mtng.org/ele/arduino/iarduino.html


body:
any ideas on how could i code this loop so when i press a button everything stops (Vernier stops reading temperature), and then when i press the button again it (Vernier reader) stars working.

       #include "VernierLib.h"
        VernierLib Vernier;
        #define led 13
        #define button 12
        int switchState = 0;
        float sensorReading;
        void setup() {
          Serial.begin(9600);
          Serial.println(Vernier.sensorName());
          Vernier.autoID();
          pinMode(12, INPUT);
        }
        void loop() {
          static float base_temp = 0;
          static float t = 0;
          t = Serial.parseFloat();
          if (t != 0) {
            base_temp = t;
          }
          sensorReading = Vernier.readSensor();
          Serial.print(sensorReading);
          Serial.print(" ");
          Serial.println(Vernier.sensorUnits());
          Serial.print("Željena temperatura: ");
          Serial.println(base_temp);
          if (base_temp > sensorReading) {
            digitalWrite(led, HIGH);
          } else {
            digitalWrite(led, LOW);
          }
          delay(1500);
        }

title: How to pause a loop

Answers: 2

body:
For reading the button I suggest using the [Bounce2 library][1]. Then you can wire your button to a fitting digital pin, the other side to ground. Use

    button.attach( BUTTON_PIN ,  INPUT_PULLUP );

To use the internal pullup of the Arduino. Define a global state variable, that holds, if your code should run or not.

    bool code_running = true;

Then in your main code (additional to calling the update function of the library) use

    if(button.fell()){
        code_running = !code_running;
    }

to toggle the state variable on button presses. Then, still in `void loop()`, use an if statement with the state variable to execute your code:

    if(code_running){
        // put your code here
    }

Note, that your code should not block for long periods for this to work correctly. You should always write your code in a non-blocking way, meaning, that no function call or loop will take longer than a few ms to execute. Otherwise your button action will not be responsive enough.

  [1]: https://github.com/thomasfredericks/Bounce2

body:
Assume you did `#define BUTTON 12` as I suggested.

Somewhere inside your loop you could code:

    if (digitalRead(BUTTON) {        // First button press
      while (digitalRead(BUTTON));   // Wait till button release
      while (!digitalRead(BUTTON));  // Wait till second button press
      while (digitalRead(BUTTON));   // Wait till button release
    }

This "hangs" from the first button press to the second button release. The code assumes your button takes pin 12 HIGH when pressed and LOW otherwise. This is a bit difficult to realize in hardware (well, not really; but you will beed an external Pull-Down resistor). The easier way will be to connect pin 12 to GND when button is pressed, and use the internal PullUp-resistor: `pinMode(BUTTON, INPUT_PULLUP);`. Then the logic of the `while` condition has to be reverted:

    if (!digitalRead(BUTTON) {        // First button press
      while (!digitalRead(BUTTON));   // Wait till button release
      while (digitalRead(BUTTON));    // Wait till second button press
      while (!digitalRead(BUTTON));   // Wait till button release
    }


body:
I'm working on building an LED matrix and I'm using an LED strip to create it. I've worked through a simple wiring setup using my bench top power supply and got a strip test working.

Now that I have the actual fabrication done I want to move the power from my bench top supply to a regular wall adapter supply.

The problem I'm running into is that when I provide power from the wall supply the led strip no longer gets the data from the signal pin.While troubleshooting I connected my multimeter to the signal pin and all of a sudden the strip's first LED got the signals and started lighting up.

I'm assuming I'm running into an impedance issue, but I'm not sure why or how to solve it other than trying different resistor values on the signal pin to overcome the issue.

Here's a rough diagram. there's not a lot to it:

[![diagram][1]][1]

I couldn't find info on the forward voltage of [the strip](https://www.alitove.net/product/50x2811-5v-r/) or a datasheet for it, so I turned all of the LEDs white and looked at the current draw on my bench top supply:

[![max current draw][2]][2]

So the whole matrix is pulling 1.5 amps.

The [trinket M0's GPIO voltage](https://learn.adafruit.com/adafruit-trinket-m0-circuitpython-arduino/pinouts#input-slash-output-pins-2910532-4) is 3.3v, so if I'm thinking about this right to figure out the resistor I need I would use ohms law:

```
r = V/I
```

So in my case:

```
r = 3.3/1.5 = 2.2ohm
```

Is that right? While I know some I still feel like a novice and I'm working alone and teaching myself, so I'm not sure if I'm thinking of everything correctly.

I also shot a video showing what's happening if that helps: https://vimeo.com/496062949

# UPDATE

And actually to simplify things further, I just tried moving the trinket over to the external power supply as well and I get the same issue.

So even with this diagram:

[![simplified circuit][3]][3]

# Update

A closer look at the all-on-the-wall-adapter circuit:

[![enter image description here][4]][4]

  [1]: https://i.stack.imgur.com/FvrR7.png
  [2]: https://i.stack.imgur.com/QVQHg.jpg
  [3]: https://i.stack.imgur.com/WPNho.png
  [4]: https://i.stack.imgur.com/mQzOD.jpg

title: Possible impedance problem when moving to new power supply

Answers: 0


body:
There are two types of tutorials for buttons:
[![no power][1]][1]
[![enter image description here][2]][2]

I don't understand how a button on the first image works. Do we just hope that there is some non zero voltage and hope its enough? I think the first image is really bad, but can't explain why.

  [1]: https://i.stack.imgur.com/FFe8I.png
  [2]: https://i.stack.imgur.com/UCrqw.png

title: button connection without connection to 5V pin

Answers: 2

body:
The digital pins of an Arduino UNO, or rather the AVR microcontroller used in the UNO, have optional internal pull-up resistors that can be enabled with the `INPUT_PULLUP` option to `pinMode`.  When you use `INPUT_PULLUP` (as opposed to `INPUT`) there is a functional resistor somewhere between 20kOhm and 50kOhm connected between VCC ("5V") and the digital pin.  When you account for this internal resistor enabled, the circuits in your two images are structurally mirror images of one another:

[![Images from original post combined and annotated for showing the mirrored circuit structures.][1]][1]
The boxed numbers here are just to clarify what nodes in the wiring diagram correspond to what nodes in the schematic representation.  Don't ask where box number 5 is; it's a mystery.  I chopped part of the original second image so a new GND connection was hand-drawn in.

In your first image (left) the code would have to enable the internal pull-up resistor to establish a default `HIGH` state on the digital pin.    With `INPUT_PULLUP` enabled you can imagine that internal resistor there when comparing with your second image (right).  Here I've drawn a resistor symbol over the board to represent the internal one when enabled.  When the button is pushed some current is drawn through that internal pull-up and the voltage at the pin falls to ground.  Note you could just as easily have an external resistor there and use plain `INPUT` mode.

Your second example image (right) is using an external pull-down resister to establish a default `LOW` state.  So when you push the button, the signal rises toward 5V/VCC or `HIGH`, and some current flows through the pull-down resistor. This would be used with `INPUT` mode rather than `INPUT_PULLUP`; I have not annotated an internal pull-up on the right to indicate that the pull-up is not enabled in this scenario (plain `INPUT` mode).  *Note that if you **were** to enable the internal pull-up in this second configuration it would form a voltage divider with external pull-down; for the 10K external pictured this **could** result default voltage at the pin which is only bordering on being a proper `LOW`*.

Some people find it less confusing to have a `HIGH` state when the button is pushed and also using an external resistor like this helps to explain the concept having a pull resistor altogether, because you can see it.  In practice though, it's nice to able to use the internal resistors even if they pull in a more confusing direction.  Note there do exist microcontrollers have optional internal pull-down resistors as well, but they're not as common; the UNO in particular does not have these.

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

body:
There is a pullup resistor you don't see in the diagram because it is internal to the Arduino. I have added it in red. To make pin 7 an input, you can write:

    digitalWrite(7, INPUT_PULLUP);

, which not only makes the pin an input but also engages the internal ~20K pullup  resistor.

So, you're right about the first diagram - it looks like the pin is left floating. Without the code, or an explanatory note, the pullup resistor isn't documented. In such a diagram, once you are familiar with the processor and know that there are optional pullups on the pin-drivers, you can assume that the optional pullup will be used.

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

  [1]: https://i.stack.imgur.com/wynTU.jpg
Update: I drew in the resistor assuming the red rail was connected to 5v - I should have drawn that in, too.


body:
For this project, I was using an *Elegoo Car V3* and I was trying to add a gyroscope onto it. When I run the code for the car, my loop code iterates once and it is always able to read the sensor data. But after that, the program starts hanging. I traced back the problem to the `Wire.endTransmission(false)` line in my code. For some reason, that line was not completing the second time.

I spent a few hours trying to find a solution online. I triple checked my wiring and still, I could not find a solution to this problem.

Thank you for taking the time to help me!

This is the output of the program
```
RawX= 82
RawY= 241
RawZ= -1
-----------------------------------------
AngleX= 195.41
AngleY= 216.93
AngleZ= 200.14
-----------------------------------------

```

And this is the code
```

#include <Wire.h>

const int MPU_addr = 0x68;
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

int minVal = 265;
int maxVal = 402;

double x;
double y;
double z;
int c = 0;

//www.elegoo.com

//     Right motor truth table
//Here are some handy tables to show the various modes of operation.
//  ENB         IN3             IN4         Description
//  LOW   Not Applicable   Not Applicable   Motor is off
//  HIGH        LOW             LOW         Motor is stopped (brakes)
//  HIGH        LOW             HIGH        Motor is on and turning forwards
//  HIGH        HIGH            LOW         Motor is on and turning backwards
//  HIGH        HIGH            HIGH        Motor is stopped (brakes)

// define IO pin
#define ENA 5
#define ENB 6
#define IN1 7
#define IN2 8
#define IN3 9
#define IN4 11

//set car speed
#define CAR_SPEED 100
typedef unsigned char u8;  //Change the name of unsigned char to u8

void forward(u8 car_speed)
{
  analogWrite(ENA, car_speed);
  analogWrite(ENB, car_speed);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

void back(u8 car_speed)
{
  analogWrite(ENA, car_speed);
  analogWrite(ENB, car_speed);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

void left(u8 car_speed)
{
  analogWrite(ENA, 250);
  analogWrite(ENB, 250);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);

  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
}

void right(u8 car_speed)
{
  analogWrite(ENA, 250);
  analogWrite(ENB, 250);
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
}

void stop()
{
  digitalWrite(ENA, LOW);
  digitalWrite(ENB, LOW);
}

int getGyroData() {
    Wire.beginTransmission(MPU_addr);
    Wire.write(0x3B);
    Wire.endTransmission(false);

    Wire.requestFrom(MPU_addr,6,true);
    AcX = Wire.read()<<8|Wire.read();
    AcY = Wire.read()<<8|Wire.read();
    AcZ = Wire.read()<<8|Wire.read();

    int xAng = map(AcX, minVal, maxVal,-90, 90);
    int yAng = map(AcY, minVal, maxVal,-90, 90);
    int zAng = map(AcZ, minVal, maxVal,-90, 90);

    x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
    y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
    z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

    Serial.print("AngleX= ");
    Serial.println(x);

    Serial.print("AngleY= ");
    Serial.println(y);

    Serial.print("AngleZ= ");
    Serial.println(z);
    Serial.println("-----------------------------------------");

}

void turn(int degrees) {
    int *originalData;
    originalData = getGyroData();
    int originalTurn = originalData[2];

    bool notDone = true;

    while (notDone) {

        int *newVal;
        newVal = getGyroData();
        int newTurn = newVal[2];

        int change = originalTurn - newTurn;
        Serial.println(change);
    }
}

void setup(){
  Wire.begin();
  Wire.beginTransmission(MPU_addr);
  Wire.write(0x6B);
  Wire.write(0);
  Wire.endTransmission(true);
  pinMode(IN1, OUTPUT);//before useing io pin, pin mode must be set first
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);
  pinMode(ENA, OUTPUT);
  pinMode(ENB, OUTPUT);
  Serial.begin(9600);

}

void loop(){
    c++;

    Serial.println(c);
    Wire.beginTransmission(MPU_addr);
    Serial.println(c);
    Wire.write(0x43);
    Serial.println(c);
    Wire.endTransmission(false);

    Serial.println(c);
    Wire.requestFrom(MPU_addr,4,true);
    AcX = Wire.read()<<8|Wire.read();
    AcY = Wire.read()<<8|Wire.read();
    AcZ = Wire.read()<<8|Wire.read();
    Serial.println(c);

    Serial.print("RawX= ");
    Serial.println(AcX);

    Serial.print("RawY= ");
    Serial.println(AcY);

    Serial.print("RawZ= ");
    Serial.println(AcZ);
    Serial.println("-----------------------------------------");

    int xAng = map(AcX, minVal, maxVal,-90, 90);
    int yAng = map(AcY, minVal, maxVal,-90, 90);
    int zAng = map(AcZ, minVal, maxVal,-90, 90);

    x= RAD_TO_DEG * (atan2(-yAng, -zAng)+PI);
    y= RAD_TO_DEG * (atan2(-xAng, -zAng)+PI);
    z= RAD_TO_DEG * (atan2(-yAng, -xAng)+PI);

    Serial.print("AngleX= ");
    Serial.println(x);

    Serial.print("AngleY= ");
    Serial.println(y);

    Serial.print("AngleZ= ");
    Serial.println(z);
    Serial.println("-----------------------------------------");
    delay(500);

}
```

This is a schematic of the car I found

[![This is a schematic of the car I found][1]][1]

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

title: Wire.endTransmission(false) hanging the program after running once when using MPU6050

Answers: 1

body:
In the comments below, [@chrisl][1] makes something explicit that I hadn't in previous edits.  Reading it first may make the below easier to interpret:

> Useful fact about I2C on Arduino: `Wire.endTransmission()` is the
> function, that actually does the I2C communication. Before that (all
> the `Wire.beginTransmission()` and `Wire.write()` calls) no data will run
> over the bus, just placed inside the libraries buffer. Thus a hanging
> `Wire.endTransmission()` equals a blocked I2C bus.

---

On the UNO the A4 and A5 are SDA and SCL, the same signals that are available near AREF and pin 13 on the other side of the board.

So, the ultrasonic range finder in the picture is attached the signals that are needed to operate the I2C ("Wire") bus, and may easily be interfering with `Wire.endTransmission(false)`.  One of the I2C signals is probably causing the range finger to trigger during I2C traffic.  After each trigger, the echo signal from the range finder would then interfere with the connected I2C bus signal.

You could try [bit banging I2C using a library][2] instead of the native I2C that is on A4/A5, and use that to operate your gyroscope.  According to your diagram, A0 through A3 are unused, and seem to be the only signals unused from the UNO.  Despite being "analog" pins they function as digital pins also and should work fine for bit-banging.  Getting to them may be a pain though, since the shield doesn't seem to make them available again as pins.

Or you may be able to route the ultrasonic sensor away from A4/A5 either by not plugging it into the header on the shield and instead route the signals from the plug to where an unused set of pins is available (again A0 though A3) and then updating the code accordingly.  Another possibility might be leave it plugged into the shield but bend the A4 and A5 pins to the side so they don't enter the UNO below, and use jumpers to route them from the bent pins to some other pair of available pins; you won't be able to bend them back and forth more than once or twice, so I would be careful with trying that.

  [1]: https://arduino.stackexchange.com/users/42015/chrisl
  [2]: https://www.arduino.cc/reference/en/libraries/bitbang_i2c/


body:
I want to use hiveMQ public broker in my project that's the same broker as what available in PubSubClient esp8266 examples but when I change WiFi SSID and password in example and upload it I got this output:

```
Connecting to <SSID NAME>
........
WiFi connected
IP address:
192.168.1.14
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...
```

**I tried this with pubsub client v2.8/v2.6/v2.4 and esp32 latest version and esp8266 latest version and 2.3**

in response to the comment as I said my code is esp8266_basic example in the PubSub client examples and here is my code:
```
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "<SSID>";
const char* password = "<PASS>";
const char* mqtt_server = "broker.mqtt-dashboard.com"; //tested with broker.mqttdashboard.com

WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883); //8000 and 1883 tested
  client.setCallback(callback);
}

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();

  // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }

}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("outTopic", "hello world");
      // ... and resubscribe
      client.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long now = millis();
  if (now - lastMsg > 2000) {
    lastMsg = now;
    ++value;
    snprintf (msg, 75, "hello world #%ld", value);
    Serial.print("Publish message: ");
    Serial.println(msg);
    client.publish("outTopic", msg);
  }
}
```

on esp32 I remove `pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output` and
``` // Switch on the LED if an 1 was received as first character
  if ((char)payload[0] == '1') {
    digitalWrite(BUILTIN_LED, LOW);   // Turn the LED on (Note that LOW is the voltage level
    // but actually the LED is on; this is because
    // it is acive low on the ESP-01)
  } else {
    digitalWrite(BUILTIN_LED, HIGH);  // Turn the LED off by making the voltage HIGH
  }
```
sections and includes

and sometimes output is like this:
```
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...connected
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...failed, rc=-4 try again in 5 seconds
Attempting MQTT connection...connected
```

title: couldn't connect to MQTT broker via esp8266/32 and pub/sub client

Answers: 2

body:
all things are OK and the problem is about my network I think there blocked MQTT (cause I couldn't connect any broker and not just hiveMQ) or other related things cause also my notebook doesn't connect I changed my network provider and the problem fixed

if you ran into the same issue, check other stuff and finally check with a computer in your network (don't use things like http://www.hivemq.com/demos/websocket-client/)

body:
I found this video as a problem solver, This may help you.
All MQTT Errors explained very well and Suggester Different troubleshooting techniques
https://youtu.be/CbodTTk-D18


body:
I am using the **Node MCu V3** board ESP8266MOD

Board Manager Version: 2.7.4
Arduino IDE: 1.8.12

My code is stuck in the `while (WiFi.status() != WL_CONNECTED)`

Here is code:
```c++
#include <ESP8266WiFi.h>        // Include the Wi-Fi library

const char* ssid = "ESP8266TestNet";  // The SSID (name) of the Wi-Fi network you want to connect to
const char* password = "ESP8266Test"; // The password of the Wi-Fi network

void setup() {
  Serial.begin(9600); // Start the Serial communication to send messages to the computer
  delay(10);
  Serial.println('\n');

  WiFi.begin(ssid, password); // Connect to the network

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

  int i = 0;
  while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
    delay(1000);
    Serial.print(++i); Serial.print(' ');
  }
  Serial.println('\n');
  Serial.println("Connection established!");
  Serial.print("IP address:\t");
  Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
}

void loop() {
  delay(10000);
  Serial.println(WiFi.status());
}
```

After downloading the code above for setup connection I am using mobile WiFi for connection.

In the mobile settings I can see the WiFi is connected to the ESP Board but when I monitor the Serial it seems that the code is stuck in the `while` loop.

If I comment out the `while` loop the board is giving a WDT reset.

Any ideas? I have been stuck for a long time.

Here I have attached the tools setting of the Arduino IDE:

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

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

title: Node MCU code is stuck in while (WiFi.status() != WL_CONNECTED)

Answers: 0


body:
I have been working on a code for a project of mine. I am making an face tracking Pan and tilt camera using the ESP32, but I am getting some errors that I do not know how to solve.

```
#include <ArduinoWebsockets.h>
#include "esp_http_server.h"
#include <WiFi.h>
#include "camera_index.h"
#include "esp_camera.h"
#include "fb_gfx.h"
#include "fd_forward.h"

const char* ssid = "NSA";
const char* password = "Orange";

// Arduino like analogWrite
// value has to be between 0 and valueMax
void ledcAnalogWrite(uint8_t channel, uint32_t value, uint32_t valueMax = 180)
{
  // calculate duty, 8191 from 2 ^ 13 - 1
  uint32_t duty = (8191 / valueMax) * min(value, valueMax);
  ledcWrite(channel, duty);
}
int pan_center = 90; // center the pan servo
int tilt_center = 90; // center the tilt servo

#define CAMERA_MODEL_AI_THINKER
#include "camera_pins.h"

using namespace websockets;
WebsocketsServer socket_server;

static inline mtmn_config_t app_mtmn_config()
{
  mtmn_config_t mtmn_config = {0};
  mtmn_config.type = FAST;
  mtmn_config.min_face = 80;
  mtmn_config.pyramid = 0.707;
  mtmn_config.pyramid_times = 4;
  mtmn_config.p_threshold.score = 0.6;
  mtmn_config.p_threshold.nms = 0.7;
  mtmn_config.p_threshold.candidate_number = 20;
  mtmn_config.r_threshold.score = 0.7;
  mtmn_config.r_threshold.nms = 0.7;
  mtmn_config.r_threshold.candidate_number = 10;
  mtmn_config.o_threshold.score = 0.7;
  mtmn_config.o_threshold.nms = 0.7;
  mtmn_config.o_threshold.candidate_number = 1;
  return mtmn_config;
}
mtmn_config_t mtmn_config = app_mtmn_config();

httpd_handle_t camera_httpd = NULL;

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

  // Ai-Thinker: pins 2 and 12
  ledcSetup(2, 50, 16); //channel, freq, resolution
  ledcAttachPin(2, 2); // pin, channel

  ledcSetup(4, 50, 16);
  ledcAttachPin(12, 4);

  ledcAnalogWrite(2, 90); // channel, 0-180
  delay(1000);
  ledcAnalogWrite(4, 90);

  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  //init with high specs to pre-allocate larger buffers
  if (psramFound()) {
    config.frame_size = FRAMESIZE_UXGA;
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  }
#if defined(CAMERA_MODEL_ESP_EYE)
  pinMode(13, INPUT_PULLUP);
  pinMode(14, INPUT_PULLUP);
#endif
  // camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  sensor_t * s = esp_camera_sensor_get();
  s->set_framesize(s, FRAMESIZE_QVGA);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  app_httpserver_init();
  socket_server.listen(82);

  Serial.print("Camera Ready! Use 'http://");
  Serial.print(WiFi.localIP());
  Serial.println("' to connect");
}

static esp_err_t index_handler(httpd_req_t *req)
{
  httpd_resp_set_type(req, "text/html");
  httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
  return httpd_resp_send(req, (const char *)index_ov2640_html_gz, index_ov2640_html_gz_len);
}

httpd_uri_t index_uri = {
  .uri       = "/",
  .method    = HTTP_GET,
  .handler   = index_handler,
  .user_ctx  = NULL
};

void app_httpserver_init ()
{
  httpd_config_t config = HTTPD_DEFAULT_CONFIG();
  if (httpd_start(&camera_httpd, &config) == ESP_OK)
    Serial.println("httpd_start");
  {
    httpd_register_uri_handler(camera_httpd, &index_uri);
  }
}

static void draw_face_boxes(dl_matrix3du_t *image_matrix, box_array_t *boxes)
{
  int x, y, w, h, i, half_width, half_height;
  fb_data_t fb;
  fb.width = image_matrix->w;
  fb.height = image_matrix->h;
  fb.data = image_matrix->item;
  fb.bytes_per_pixel = 3;
  fb.format = FB_BGR888;
  for (i = 0; i < boxes->len; i++) {

    // Convoluted way of finding face centre...
    x = ((int)boxes->box[i].box_p[0]);
    w = (int)boxes->box[i].box_p[2] - x + 1;
    half_width = w / 2;
    int face_center_pan = x + half_width; // image frame face centre x co-ordinate

    y = (int)boxes->box[i].box_p[1];
    h = (int)boxes->box[i].box_p[3] - y + 1;
    half_height = h / 2;
    int face_center_tilt = y + half_height;  // image frame face centre y co-ordinate

    //    assume QVGA 320x240
    //    int sensor_width = 320;
    //    int sensor_height = 240;
    //    int lens_fov = 45
    //    float diagonal = sqrt(sq(sensor_width) + sq(sensor_height)); // pixels along the diagonal
    //    float pixels_per_degree = diagonal / lens_fov;
    //    400/45 = 8.89

    float move_to_x = pan_center + ((-160 + face_center_pan) / 8.89) ;
    float move_to_y = tilt_center + ((-120 + face_center_tilt) / 8.89) ;

    pan_center = (pan_center + move_to_x) / 2;
    Serial.println(pan_center);
    ledcAnalogWrite(2, pan_center); // channel, 0-180

    tilt_center = (tilt_center + move_to_y) / 2;
    int reversed_tilt_center = map(tilt_center, 0, 180, 180, 0);
    ledcAnalogWrite(4, reversed_tilt_center); // channel, 0-180

  }
}

void loop()
{
  auto client = socket_server.accept();
  camera_fb_t * fb = NULL;
  dl_matrix3du_t *image_matrix = NULL;

  while (true) {
    client.poll();
    fb = esp_camera_fb_get();
    image_matrix = dl_matrix3du_alloc(1, fb->width, fb->height, 3);

    fmt2rgb888(fb->buf, fb->len, fb->format, image_matrix->item);

    box_array_t *net_boxes = NULL;
    net_boxes = face_detect(image_matrix, &mtmn_config);

    if (net_boxes) {
      draw_face_boxes(image_matrix, net_boxes);
      free(net_boxes->score);
      free(net_boxes->box);
      free(net_boxes->landmark);
      free(net_boxes);
    }

    client.sendBinary((const char *)fb->buf, fb->len);

    esp_camera_fb_return(fb);
    fb = NULL;
    dl_matrix3du_free(image_matrix);
  }
}
```
The error that occured was in this section of code:
```
static esp_err_t index_handler(httpd_req_t *req)
{
  httpd_resp_set_type(req, "text/html");
  httpd_resp_set_hdr(req, "Content-Encoding", "gzip");
  return httpd_resp_send(req, (const char *)index_ov2640_html_gz, index_ov2640_html_gz_len);
}
```
I got this error in the compiler:
```
‘index_ov2640_html_gz’ was not declared in this scope
```

Any ideas on why this happened? Thanks.

title: ESP32 Compile Error - Face tracking Pan and tilt camera Arduino

Answers: 0


body:
Im trying to power a brushless DC Motor (Tamiya 300054358) through the l298n attached to an Arduino.

The l298n is powered by an external 9V source and the logic of the l298n is powered by the Arduinos 5V, wich is also powered by the 9v.

Both components using the same ground.

The code looks good and i can successfully adjust the power-output for the motor between 6-9V.

As soon as is attach the Motor, the volage drops do somewhere around 0-1V and the motor isnt turning.

When i attach the motor directly to the power source, it runs fine, so the power should be enough. (in the original RC car its powered by an 7V battery).

I tried some smaller motors just to be sure and the problem is similar. The motor is turning, but very slowly.

I also tried to connect the batterypack instead of the extern power source just ending up with the same result.

Do you have any ideas, where the problem could be at?

Thanks in advance

title: l298n voltage loss when motor attached

Answers: 2

body: The problem is in the H driver. You lose about 1.4 volts on each leg so your loss from the battery is about 2.8 volts. The internal driver transistors are in a darlington configuration. If the bridge were Power MOS instead of bipolar transistors your voltage would be dependent on the resistance of the MOSFETs. Typically a few tenths of a volt in total. If your 9V source is a battery you probably are not getting the 9V you are expecting.

body:
From an [L298N datasheet][1]:

> TOTAL DC CURRENT UP TO 4 A

From [motor][3]'s ["datasheet":][4]

[![Motor datasheet graph showing current usage up to 150 Amps][2]][2]

I'm no expert in electric motors and driving them, not even sure I'm novice level, but I just don't see you driving a motor anything near this current draw with this part.  If by some miracle you can, it will be horribly inefficient owing to the losses associated with the voltage drops that Gil mentions.

For a motor that operates with this much current I would expect a practical h-bridge setup to have discrete mosfets, perhaps mounted to a heatsink.

  [1]: https://www.st.com/resource/en/datasheet/l298.pdf
  [2]: https://i.stack.imgur.com/WRPfC.jpg
  [3]: https://www.tamiya.de/en/accessories/tamiya-accessories/rc-spare-option-parts/spare-option-parts/e-motor-rs-540-torque-turned-300054358/
  [4]: https://cdn.simba-dickie-group.de/downloads/300054358/300054358_Torque_Tuned.pdf


body:
Can someone help me? I'm using a sim7000e from Waveshare. One week ago it was working normally, but now it doesn't work at all; it even can't read the RX-TX communication.

```c++
#include <SoftwareSerial.h> //koneksi ke modem

#define TINY_GSM_MODEM_SIM7000
#define TINY_GSM_DEBUG SerialMon
#define BAUD 9600
#define SerialMon Serial

const byte rxpin = 2;
const byte txpin = 3;

SoftwareSerial SerialAT(rxpin, txpin); // RX, TX
```

That's  my code for connecting to the Arduino. I believe it from my Arduino, but I don't know if something wrong from Arduino.

My 5V (sim7000E) to 5V (arduino mega2560), GND to GND.

Because I'm using Putty on USB for reading my AT-cmd it doesn't and has some trouble.

title: SIM7000E Waveshare can't do anything

Answers: 1

body:
I'm having similar issues, although it could well be my fault!

I can't see any coding sending AT commands, or waiting for responses in your example.

Try running your TX pin to your RX pin on your Arduino (take the SIM7000e out of the equation completely).  If your code works, then the issue is elsewhere.

I've tried connecting via USB and that seems through a terminal.  I was able to connect to a mobile network using the AT command

AT+CSTT="cmnet"