message:
Unable to acquire AP network IP and DNS on a ESP32 MCU

I'm getting the following error on serial output (verbose mode) when my smart device , ESP32 S3 tries to connect over WIFI to the Access point (AP). The SSID is `TheScientist`

Below is the serial output:

    Connecting to TheScientist
    [  1064][D][WiFiGeneric.cpp:929] _eventCallback(): Arduino Event: 0 - WIFI_READY
    [  1098][V][WiFiGeneric.cpp:338] _arduino_event_cb(): STA Started
    [  1099][V][WiFiGeneric.cpp:97] set_esp_interface_ip(): Configuring Station static IP: 0.0.0.0, MASK: 0.0.0.0, GW: 0.0.0.0
    [  1099][D][WiFiGeneric.cpp:929] _eventCallback(): Arduino Event: 2 - STA_START
    .......[  4750][V][WiFiGeneric.cpp:360] _arduino_event_cb(): STA Disconnected: SSID: TheScientist, BSSID: 3c:cd:5d:a7:f1:13, Reason: 15
    [  4750][D][WiFiGeneric.cpp:929] _eventCallback(): Arduino Event: 5 - STA_DISCONNECTED
    [  4758][W][WiFiGeneric.cpp:950] _eventCallback(): Reason: 15 - 4WAY_HANDSHAKE_TIMEOUT

body:
Although the verbose debug serial output shows a

 `Reason: 15 - 4WAY_HANDSHAKE_TIMEOUT`

in reality the timeout is due to usage of a password longer than the 32 char allowed on ESP32 MCUs . In summary, any ESP32 MCU to successfully connect to any WIFI Access Point , the Network password must not exceed 32 char long.


sender: user

message:
DS18B20 temperature sensor crashes MbedOS on Arduino Nano RP2040?

I'm trying to use the DS18B20 sensor with Arduino Nano RP2040.
No matter which library I use, it seems to crash MbedOS as soon as the driver is initialized. I get 4 short and 4 long flashes of the orange LED, which as I found somewhere indicates a crash.

I was trying with DS18B20 library (https://github.com/matmunk/DS18B20) as well as the DallasTemperature one (https://github.com/milesburton/Arduino-Temperature-Control-Library).
At first I suspected that the issue is in my code as it interfaces with multiple different devices (EEPROM, SHT30, etc.) and this may interfere with 1-wire interface, but if I upload just the examples from these libraries the effect is the same.

I know that the Arduino is OK, as it can run other code absolutely fine, and the sensor is OK as well since I can read it with RaspberryPi.

Does anyone have similar problems? Is there some workaround?

sender: assistant

body:
#### Test Setup

I have wired an DS18B20+ to an RPI Pico and used a 4.7K pullup. The RPI Pico is a stand-in for your board. It uses the  `arduino:mbed_rp2040:pico` core rather than the `arduino:mbed_nano:nanorp2040connect` that yours does. However, I'm guessing they're similar enough.

#### Test result

When I attempt the to use the [matmonk DS18B20 library][1] you mention, I see similar pattern on the RPI Pico's onboard LED. Just the attempt to [construct the object][2] was sufficient to crash. Construction fairly directly [defers to the OneWire][3] library. So, I tried the OneWire library's own [example for reading the DS18B20][4] (with some appropriate modification) and it crashes in the same manner. This lead to searching for and finding issues for the RP2040 on the OneWire github page resulting in (among others) [this find][5]. The answer mentions [OneWireNG][6].

#### The OneWireNG [DallasTemperature example][7] works

Or rather, it's the library that works. But, this is the relevant example for it that works for me. I made the following modifications.

* All `Serial` usages were replaced with `SerialUSB` because I am using the USB connection for the Serial Monitor (well, a terminal emulator).

* I changed the one wire object to use GPIO28 because it was conveniently close to the pins where I was picking up 3.3V and GND: `OneWire  ds(28);`

<s>It seems plausible **that you could change the `#include <DS18B20.h>` usages** in the two libraries you cited to `#include "OneWireNg_CurrentPlatform.h"` and find that they then work fine. I have not tried this yet. If that's of particular interest to you I will try it and update</s>(**Update below**). However, this stock example from the OneWireNG library is not crashing and is printing temperatures that rise and fall expected when I manipulate the temperature of the sensor.

#### OneWireNg with Matmunk and DallasTemperature libraries

##### In general

It turns out that it is *unnecessary* to modify libraries that were using the original OneWire, not even just changing the `#include`. Despite the OneWireNg example using `"OneWireNg_CurrentPlatform.h"` it also provides a OneWire.h header. It is sufficient to have OneWireNg installed but **the original OneWire library must uninstalled** (or moved out of the libraries directory) so as not to confuse the build process into selecting the original library based on the header name over the OneWireNg library. The OneWireNg authors may have used the OneWireNg specific header in the examples to avoid this problem wit their examples when both libraries were installed. They've gone out of their way to make it compatible with the original, but below are reports of specific tests with the two libraries mentioned anyway.

##### Matmunk library with OneWireNg

With OneWireNg installed and the original OneWire *not* installed, the [Multiple example][8] form the matmunk library worked with the same minor modifications mentioned before (I used pin 28 rather than 2 and `SerialUSB` rather than `Serial`). In case your wondering the only reason why I switched from testing Single to Multiple is the latter didn't require that I first find and enter my part's address. That example is printing temperatures that rise and fall in accordance with manipulation of the sensor.

##### DallasTemperature with OneWireNg

Likewise I tested with the [Multiple example from the DallasTemperature library][8]. Same kind of modifications to the example. I changed `ONE_WIRE_BUS` to `28` for my setup. I changed `Serial` to `SerialUSB`. And runs normally and prints expected temperatures under manipulation of the sensor.

  [1]: https://github.com/matmunk/DS18B20
  [2]: https://github.com/matmunk/DS18B20/blob/1.0.0/examples/Single/Single.ino#L6
  [3]: https://github.com/matmunk/DS18B20/blob/1.0.0/src/DS18B20.cpp#L3-L6
  [4]: https://github.com/PaulStoffregen/OneWire/blob/v2.3.7/examples/DS18x20_Temperature/DS18x20_Temperature.ino
  [5]: https://github.com/PaulStoffregen/OneWire/issues/105
  [6]: https://github.com/pstolarz/OneWireNg/
  [7]: https://github.com/pstolarz/OneWireNg/blob/0.12.2/examples/arduino/DallasTemperature/DallasTemperature.ino
  [8]: https://github.com/matmunk/DS18B20/blob/1.0.0/examples/Multiple/Multiple.ino


message:
how do I wire a 2nd Adafruit TMP117 board to my Adafruit Metro by I2C?

I want to connect two TMP117 boards to one Metro (ie. Arduino).

(the first, addressed at 48 the 2nd at 49.)

Should 2nd board's 4 wires simply attach (ie. solder) in parallel to 1st board's 4 wires?
(ie. 3.3v, gnd, SCL, SDA)

background...
I want to read temperatures from two boards at once, in near real time and write to Windows file.

body: You are correct almost. Connection in parallel is correct however you cannot read both at once, the bus supports talking to only device at a time. You will need to read one then the other. I do not know for sure if it is possible to get them to synchronize conversion but I think not.


message:
Using a limit switch to stop a stepper motor

I am building a machine with a moving bed, the bed moves forward and backward. I need to incorporate a limit switch at the two ends that makes sure the motors stop at the two extremes. I have 2 stepper motors controlled by TB6600 motor drivers, I am trying to start with 1 limit switch (SS-5Gl2) and advance from there.

My 1st question is how I get the code to stop steppers if limit switch is closed?

    // Define stepper motor connections and steps per revolution:
    #define dirPin1 2
    #define stepPin1 3
    #define dirPin2 5
    #define stepPin2 6
    #define stepsPerRevolution 200 // We may need to change 200 to 1600 to get more precise control, i.e. decimals verse integers

    #define Lim1 8

    int direction = 0;
    int remainder = 0;
    long travel = 0;
    long revolutions = 0;

    void setup() {

      // Declare pins as output:
      pinMode(stepPin1, OUTPUT);
      pinMode(dirPin1, OUTPUT);
      pinMode(stepPin2, OUTPUT);
      pinMode(dirPin2, OUTPUT);

      pinMode(Lim1, OUTPUT);

     //Desired travel distance, in mm !!!! set here !!!!
    travel = 1;
    //Desired direction !!!! set here !!!! move die in(ccw) = 1, back out(cw) = 0 !!!!
    //direction = 0; did not work, need boolean?

    // Set the spinning direction counterclockwise (die in) or clockwise (die out):
    //if(direction = 1) digitalWrite(dirPin, HIGH);
    //if(direction = 0) digitalWrite(dirPin, LOW);

    //set direction manually, uncomment HIGH for die in, LOW for die back out
    digitalWrite(dirPin1, LOW);
    digitalWrite(dirPin2, LOW);
    //digitalWrite(dirPin, LOW);

    digitalWrite(Lim1, OFF) //

    //calculating number of revolutions based on mm input. Does not yet account for partial revs - variable is truncated, integers are default. Would need another loop to handle the remainder
    //6.659 (microns) constant is based on 1.25mm acutator screw pitch, and ratio in gearbox
    revolutions = 1000.00*travel/6.659;
    //attempt to output the stored value to PC for debug purposes

    Serial.print("revolutions = ");
    Serial.print(revolutions,4);
    }

    void loop() {

       // Spin the stepper motor X revolutions fast, speed (delay) apparently limited by voltage. 42v should go faster?
       //Required a nested loop because integers on the UNO are limited to ~32k
      for (int i = 0; i < revolutions; i++) {

       if (digitalRead(Lim1 == OFF)){}

       else {
          for (int j = 0; j < stepsPerRevolution; j++) {
           // These four lines result in 1 revolution:
          digitalWrite(stepPin1, HIGH);
          digitalWrite(stepPin2, HIGH);
          delayMicroseconds(250);
          digitalWrite(stepPin1, LOW);
          digitalWrite(stepPin2, LOW);
          delayMicroseconds(250);
          }
      }
      }

       while(1){}

    }

body:
You are doing every step manually directly via `digitalWrite()`, so the principal would be to read the limit switch pin on every iteration of the inner `for` loop in an `if` statement. What to do in that `if` statement depends on what you want to do on hitting the limit switch. Currently you have an infinite empty loop after your motor code. So if you want to stop forever in that case you can create another infinite loop there. So something like this:

    ...
    for (int j = 0; j < stepsPerRevolution; j++) {
       if(!digitalRead(Lim1)){
           while(true);
       }
       // These four lines result in 1 revolution:
       digitalWrite(stepPin1, HIGH);
       digitalWrite(stepPin2, HIGH);
       delayMicroseconds(250);
       digitalWrite(stepPin1, LOW);
       digitalWrite(stepPin2, LOW);
       delayMicroseconds(250);
    }

Note that this assumes that you have connected the limit switch to ground and use the digital pin with a pullup resistor.

---

But you have 2 other problems with your limit switch code:

1. You set your limit switch pin `Lim1` as output, though to read a switch you need to configure it as input. And if you want to use a pullup resistor (in contrast to a pulldown resistor) you can activate the internal pullup in the same step:

        pinMode(Lim1, INPUT_PULLUP);

2. When reading the limit switch inside the outer `for` loop you write

        if (digitalRead(Lim1 == OFF)){}

    You are doing the equality comparison between `OFF` and the pin number and not between `OFF` and the return value of `digitalRead()`. You need to place the parentheses here correctly:

        if(digitalRead(Lim1) == OFF){}

    Above I used the equivalent form

        if(!digitalRead(Lim1)){}

    with the negation operator `!`

Besides that you are missing the `Serial.begin()` with the baudrate, that you want to use, in `setup()`.


message:
Detecting the difference between a deep sleep wake signal and a manual wake button press

When my ESP8266 wakes itself from sleep (i.e. D0 sends wake signal), I want it to do something different to when I manually wake the device with the reset button.

I have the RST and D0 pins connected, so that the device can wake itself from sleep. I also have a button connected to RST which pulls to ground when pressed, so that I can wake the device manually on demand.

How do I differentiate between the device being awoken by itself, or manually by the button press?

I tried using `system_get_rst_info`/`getResetInfoPtr` to determine what action has awoken the device, but it seems that if I reset manually after the device went to sleep, the `REASON_DEEP_SLEEP_AWAKE` reason is returned since that value is based on how the device went to sleep/reset rather than how it woke up.

Disclaimer: I already found a solution (answer below), but it's more complex than I wanted, so I am posting this question to see if anyone else can think of a simpler solution.

body:
I came up with two solutions (3 if you count the combo), both involve connecting the manual reset button to another pin on the MCU (so I can check if it's still pressed when starting).

**Solution 1: Generate a reset pulse**

The problem with the manual reset button is that it's only on release that it resets, since while the RST pin is held low, the MCU won't start.

To solve this, I used a positive edge monostable circuit to pulse the RST pin when the manual reset button is pressed down.

That way, I can hold the button down and the device starts. In the `setup()` function, I can check if the button is still pressed.

**Solution 2: Use an RC delay circuit**

I also considered that I could simply wake the device on button release, and use a debounce cap (very slow discharge) to see if the button was pressed in the last second (by checking the pin on the MCU to which the charged cap is connected).

**Solution 3: A combination of 1 & 2**

Combining 1 and 2, allowed me to wake the device on button down, and use the debounce cap to see if the button was pressed recently (in the last second).

[![Reset button circuit][2]][2]

  [1]: https://i.stack.imgur.com/DwEZU.png
  [2]: https://i.stack.imgur.com/rjXvC.png


message:
Xbox 360 controller commands to Uno-compatible board via USB module

I am trying to receive commands on a third-party **Arduino-Uno-compatible board** from an **Xbox 360 controller** via an **M5Stack USB module** but I am not seeing the behavior I expect (see heading Expected Behavior).

To be clear, I am talking about reading commands from an Xbox controller using an Arduino, *not* emulating an Xbox controller using an Arduino.

# Hardware

![](https://i.stack.imgur.com/nSwRN.jpg)

- A Bluno Nano. (An Arduino-Uno-compatible board in a Nano-like form factor with program uploading and serial communication via a matching Bluetooth USB dongle. However, I am using a wired USB connection to my PC instead.) The board is recognized as an Uno by the Arduino IDE. The same board has worked as expected for other projects.

- An [M5Stack USB module](https://docs.M5Stack.com/en/module/usb) (with a MAX3421E chip), which is  primarily meant to be compatible with an M5Stack microcontroller module. Either way, the USB module communicates using SPI.

- A *wireless* Xbox 360 controller, but I connected it to the USB module using a USB cable that [plugs in to the controller](https://static.bhphoto.com/images/images500x500/1414082712_1071751.jpg) with a seemingly proprietary connector. Should be in working order.

I am not using an [Xbox 360 wireless receiver](https://i.stack.imgur.com/6l1Ys.jpg) to connect to the Xbox controller, nor do I want to connect to it wirelessly.

## Wiring

- I connected the GND (#1/3/5), +5V (#28, VBUS), SCLK (#11, GPIO18), MISO (#9, GPIO19) and MOSI (#7, GPIO23) pins of the USB module to the corresponding pins of the Bluno Nano: GND, +5V, SCK (D13), MISO (D12), and MOSI (D11).

- I tried pulling the USB module's EN pin (#6) up to +5V in attempt to make sure it's enabled.

- I tried pulling the SS pin up/down. I have not tried connecting it to pins D10 or D8, both of which I have seen as SS pins on Arduino Nano pinout diagrams.

- I have not tried connecting the INT pin (#2, GPIO35) to anything.

- I believe these are the only useful pins on the USB module.

### USB module schematic

The useful pinout is in the bottom right corner.

![](https://static-cdn.M5Stack.com/resource/docs/products/module/usb/usb_sch_01.webp)

## Attempts

- Unplugging and re-plugging the Bluno Nano's USB cable with my PC.

- Pressing the Bluno Nano's reset button.

- Unplugging and re-plugging the Xbox controller's USB cable with the USB module, or vice versa (that is, starting with it unplugged).

- Pressing or holding the center "X" button or other buttons on the controller, presumably to turn it on or hopefully enter some kind of connection-setup mode, maybe.

- Using a wired USB mouse instead of the Xbox controller.

- Trying various combinations of the above in different orders.

I have ensured that the USB module is receiving power (even though it seems to have no power indicator LED) by using it's additional 5V and GND pins to successfully drive a digital input pin on the Bluno Nano high or low.

I have ensured that the Xbox controller is receiving power because the center "X" button lights up upon being pressed.

# Software

- Windows 11

- Arduino IDE 2.0

- [USB_Host_Shield_2.0](https://github.com/felis/USB_Host_Shield_2.0) version 1.6.2 (latest) installed through the library manager. Note that this library seems to be primarily designed for a particular USB host shield, but I see it being used with other USB host shields, including in my USB module's documentation. There is a [library for Xbox 360](https://github.com/felis/USB_Host_Shield_2.0#xbox-360-library) therein which works with a USB controller or a wireless controller, with example sketches for each.

Either example sketch uploads successfully without errors (although the programmer sometimes gets stuck not responding, whereupon I disconnect, let it error out, reconnect, and retry uploading).

In the Arduino IDE Serial Monitor, I set the baud rate to 115200 to match that specified in either example sketch.

## Expected behavior

To be printed in the Serial Monitor (`<...>` is how I indicate my comments):

```
XBOX USB Library Started  <instead of "OSC did not start" followed by unresponsiveness to controller button presses, etc.>
<Xbox controller commands upon controls/buttons being pressed, e.g., "LeftHatX: ...">
```

## Attempts

- The USB Host Shield 2.0 documentation says about use with an Xbox 360 controller: "To use it via USB use the XBOXUSB library or to use it wirelessly use the XBOXRECV library. Note that a Wireless controller can NOT be used via USB!". It is unclear to me if my wired USB connection to my wireless controller calls for the XBOXUSB or XBOXRECV library, so I tried both libraries (tried both accompanying example sketches) to no avail.

- I tried removing the following code snippets one-by-one and in some combinations, to no avail. The program uploads successfully in every case.
  ```
  #include <SPI.h>
  ```
  ```
  #if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
  #endif
  ```
  ```
  XBOXUSB Xbox(&Usb);
  <...along with the code in `loop()` that requires it to be defined.>
  ```
  ```
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nXBOX USB Library Started"));
  ```
  **The program failed here because `Usb.Init() == -1`.**

- I tried changing
  ```
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); //halt
  }
  Serial.print(F("\r\nXBOX USB Library Started"));
  ```
  to
  ```
  while (Usb.Init() == -1);
  Serial.print(F("\r\nXBOX USB Library Started"));
  ```
  in attempt to keep trying to enable the connection (while I pressed the controller's "X" and other buttons) to no avail.

- I also tried changing the same snippet to
  ```
  Usb.Init()
  ```
  in attempt to ignore the `-1` return value (which I presume represents an error) and proceed anyway, to no avail.

- Using an older version of the USB Host Shield 2.0 library.

- Setting the following in the library's `settings.h`, with no apparent change in output.
  ```
  /* Set this to 1 to activate serial debugging */
  #define ENABLE_UHS_DEBUGGING 1
  ```

- Setting the following in `XBOXUSB.cpp` and `XBOXRECV.cpp`, with no apparent change in output.
  ```
  #define EXTRADEBUG // Uncomment to get even more debugging data
  #define PRINTREPORT // Uncomment to print the report send by the Xbox 360 Controller
  ```

For trying with a wired USB mouse instead of the Xbox controller, I used `USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino`, attempted additionally with some of the above modifications, to no avail in any case, leading me to believe that the problem is not specific to the Xbox controller or library for it.

I have also tried the [example sketch](https://github.com/m5stack/M5Stack/blob/master/examples/Modules/USB_MAX3421E/usb_mouse/usb_mouse.ino) from the M5Stack USB module documentation after removing parts that would be specific to an M5Stack microcontroller module and unecessary for testing purposes. This was no different.

----

I am completely lost on what else to try hardware- and software-wise. I have tried searching many questions. I suspect that I'm missing something simple and obvious, or that my setup can't work for whatever reason.

Thank you

----

# Update

After getting past the `Usb.Init()` problem by connecting the USB module's SS pin, the connection with the Xbox controller still wasn't being established and commands were not being received.

body:
I discovered that, upon plugging the USB cable into my PC rather than the USB module, the controller appears as "Xbox 360 Wireless Controller via Play & Charge Kit" under "Xbox 360 Peripherals" in the Device Manager.

Turns out, "Play & Charge Kit" refers to the controller's removable rechargeable battery and the USB cable.

According to [this](https://linustechtips.com/topic/658562-solved-xbox-360-controller-via-play-and-charge-kit/), "The play and charge kit only carries power. It does not carry the data required to connect a controller to a PC."


message:
Arduino does not connect to MQTT local broker

I have an Arduino Mega with Ethernet connected to a router by cable. Also I have a PC connected to the router (by Wifi) where also the local MQTT broker is installed (mosquitto). Althought the Arduino Ethernet connection seems ok, the MQTT connection does not: I get the return code -2

This is the full code, there are several functions but the MQTT init is the one that fails:

    #include <SPI.h>
    #include <Ethernet.h>
    #include <PubSubClient.h> // Librería para MQTT

    byte mac[] = { 0xA8, 0x61, 0x0A, 0xAE, 0x3A, 0xC4 };
    byte ip[] = { 192, 168, 1, 100 };
    byte gateway[] = { 192, 168, 1, 2 };
    byte subnet[] = { 255, 255, 255, 0 };

    EthernetClient ethClient;
    PubSubClient mqttClient(ethClient);

    const char *MQTT_BROKER_ADRESS = "192.168.1.101";
    const uint16_t MQTT_PORT = 1883;
    const char *MQTT_CLIENT_NAME = "mqttx_7c0a0ed3";

    void SuscribeMqtt()
    {
        mqttClient.subscribe("hello/world");
    }

    void OnMqttReceived(char *topic, byte *payload, unsigned int length)
    {
        Serial.print("Received on ");
        Serial.print(topic);
        Serial.print(": ");
        String content = "";
        for (size_t i = 0; i < length; i++)
        {
            content.concat((char)payload[i]);
        }
        Serial.print(content);
        Serial.println();
    }

    void InitMqtt()
    {
        mqttClient.setServer(MQTT_BROKER_ADRESS, MQTT_PORT);
        mqttClient.setCallback(OnMqttReceived);
    }

    void ConnectMqtt()
    {
        Serial.print("Starting MQTT connection...");
        if (mqttClient.connect(MQTT_CLIENT_NAME))
        {
            SuscribeMqtt();
            mqttClient.publish("connected","hello/world");
        }
        else
        {
            Serial.print("Failed MQTT connection, rc=");
            Serial.print(mqttClient.state());
            Serial.println(" try again in 5 seconds");
            delay(5000);
        }
    }

    void HandleMqtt()
    {
        if (!mqttClient.connected())
        {
            ConnectMqtt();
        }
        mqttClient.loop();
    }

    void CheckLinkStatus() {

      auto link = Ethernet.linkStatus();

      Serial.print("Link status: ");

      switch (link) {
        case Unknown:
          Serial.println("Unknown");
          break;
        case LinkON:
          Serial.println("ON");
          break;
        case LinkOFF:
          Serial.println("OFF");
          break;
      }
      delay(1000);
    }

    void setup() {

      // You can use Ethernet.init(pin) to configure the CS pin
      //Ethernet.init(10);  // Most Arduino shields

      Serial.begin(9600);

      Ethernet.begin(mac, ip, gateway, subnet);
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());

      delay(1500);

      InitMqtt();

    }

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

      CheckLinkStatus();

      HandleMqtt();

    }

I have done ping from the PC IP (192.168.1.101) to the Arduino IP (192.168.1.100) and it is ok. What could be the issue?.

body:
The issue was coming from mosquitto local broker, which was being blocked by windows 10 firewall. When I executed mosquitto with the correct permissions on its folder (read and write for "all users") and with correct mosquitto configuration file, the following window popped up and I clicked on to allow both private and public connections:

[![n][1]][1]

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

I also use the following batch file to load mosquitto and it works all the time:

    cd "C:\Program Files\mosquitto"
    del mosquitto.log
    mosquitto -v -c mosquitto.conf

This is the content of my mosquitto configuration file:

    listener 1883
    allow_anonymous true
    log_type error
    log_type warning
    log_type notice
    log_type information
    connection_messages true
    log_timestamp true
    log_dest file C:\Program Files\mosquitto\mosquitto.log

Now I am able to use MQTT from Arduino connected to a router.


message:
Best way to get JSON from struct vector class

I have a vector which consist of a struct, see below:

```c++
struct FileInformation
  {
    String name;
    size_t filesize;
  };

std::vector<FileInformation> FileInformations;
```

How do I get JSON out of it the easiest way?

body:
Using [ArduinoJson](https://arduinojson.org):

```c++
DynamicJsonDocument doc(2048);
for (const FileInformation& item : FileInformations) {
  JsonObject& obj = doc.createNestedObject();
  obj["name"] = item.name;
  obj["filesize"] = item.filesize;
}
serializeJson(doc, Serial);
```

This will produce a JSON document that looks like this:

```c++
[
  {"name": "command.com", "filesize": 1234},
  {"name": "config.sys", "filesize": 2345},
  {"name": "autoexec.bat", "filesize": 3456}
]
```

Please read [the tutorial](https://arduinojson.org/v6/doc/serialization/) for more information.


message:
DHT11 temperature and humidity sensor Code

I’ve got a question about this code I’ve attached please- would it be correct to read it like this:

After defining the variable temperature and humidity and assigning measurement_timestamp to millis(), an if loop first checks if millis - measurement_timestamp < 3000 unsigned long (which doesn’t make sense to me) and then if a reading is read, it = true?

Is this correct please?

Code:

    static bool measure_environment( float *temperature, float *humidity )
    {
      static unsigned long measurement_timestamp = millis( );

      /* Measure once every four seconds. */
      if( millis( ) - measurement_timestamp > 3000ul )
      {
        if( dht_sensor.measure( temperature, humidity ) == true )
        {
          measurement_timestamp = millis( );
          return( true );
        }
      }

      return( false );
    }

body:
The code makes sense to me.

The comment, "/* Measure once every four seconds. */" is inaccurate. It will measure when the time since last measurement is greater than 3 seconds.

Because of "static unsigned long measurement_timestamp = millis( );", measurement_timestamp will NOT be initialized to millis() every time the function is called - it will only be initialized once for lifetime of the run. Otherwise, it would never cause a measurement since "if( millis( ) - measurement_timestamp > 3000ul )" would never be true.

The first call sets measurement_timestamp= to millis() [the current timer value] and the function returns "false"

When called 3.001 sec later, "if( millis( ) - measurement_timestamp > 3000ul )" is true - a measurement is taken, "measurement_timestamp" is updated to the current millis() and the function returns "true".

It returns "false" for the next 3 seconds and then "true" and so on.

see https://stackoverflow.com/questions/5033627/static-variable-inside-of-a-function-in-c

and https://arduino.stackexchange.com/questions/12587/how-can-i-handle-the-millis-rollover

Hope it helps.


message:
Detecting an approximate angle/location of a light source using phototransistors

**Note: [I am approximately two weeks into learning Arduino and hence have little experience with utilizing Phototransistors.]**

My plan revolves around placing four identical Phototransisors which are spread approximately 10cm apart on a breadboard in a V configuration. Each Phototransistor is connected to one of the "analog In" pins respectively (I am using the Arduino Uno), with the long leg attached to 5V while the short leg is connected to ground via a 220-ohm resistor. In the center of this setup, I plan to place a servo that will face the direction of the light beam emitted from a flashlight.

(I want this project to be allocated in a dark room with any external lighting calibrated),The idea is to identify the phototransistor which has the highest analog value (closest to the light source). With this information, I want to be able to compute an approximate angle of the light source to then write it on my servo.

You can find the attached datasheets below (All the components are from the Arduino starter kit :) ).

[[Datasheet for the Phototransistor]][1]

[[Datasheet for the Servo motor]][2]

[[Datasheet for the 220 ohm Resistor]][3]

Here is what I have so far for the code:

    #include <Servo.h>
    Servo myServo;
    const int transistorPin1 = A0;
    const int transistorPin2 = A1;
    const int transistorPin3 = A2;
    const int transistorPin4 = A3;
    void setup() {
      myServo.attach (10);
      Serial.begin (9600);
    }
    void loop() {
     int reading1 = analogRead (transistorPin1);
     int reading2 = analogRead (transistorPin2);
     int reading3 = analogRead (transistorPin3);
     int reading4 = analogRead (transistorPin4);
     int reading [] = {reading1, reading2, reading3, reading4}; //This is an array for the values:
     int maxReading = reading [0], maxSensor = 1; // I am setting the maximum reading and the Phototransistor that corresponds to it:
       for (int i = 1; i <= 3; i++){ //Setting this for the other three phototransistors:
         if (reading[i] > maxReading){
         maxReading = reading[i];
         maxSensor = i + 1;
         }
       }
    }

 So my question is: What is the most efficient way to compute the angle of the lighsource? And is my method even relevant for this application?

Thank you for taking you time to read this! Your support will be very much appreciated!

**Edit 1:**

Explanation of my hardware setup:

This project is allocated on two connected breadboards which means that there are no moving parts. The only moving component is the one single servo that is fixed in position.

The phototransistors, (as mentioned above), are placed in a V configuration which too are stationary. The servo is allocated behind the phototransistors and can only rotate 180 degrees. (You can see the attached illustrations below, I apologize in advance for any technical errors or my horrible drawings.)
[![Project Setup Illustration:][4]][4]
[![Connection Diagram:][5]][5]

As you can visualize on the first image, I do not plan on a complete 360 degree rotation which probably complicates the issue further. Any suggestions on how I can code this would be greatly appreciated! Once again thank you for your time.

  [1]: https://www.arduino.cc/documents/datasheets/HW5P-1.pdf
  [2]: https://www.arduino.cc/documents/datasheets/servoMotor.PDF
  [3]: https://www.arduino.cc/documents/datasheets/Resistors.pdf
  [4]: https://i.stack.imgur.com/rzPfH.jpg
  [5]: https://i.stack.imgur.com/Vhxr3.jpg

body:
In principle, you only need two phototransistors, a left and a right one. The quotient of the values from the ad-convertor (Vleft/Vright) will tell you where to find the light source. If the quotient > 1 then the light source is at the left side, if the quotient < 1 then the light source is at the right side. Most likely there is no lineair relationship between the quotient and the angular position of the light source. This relationship depends on the housing and the positioning of the diodes in their housings. One possibility is to do a calibration beforehand and use a lookup table during operation. The calibration could be done by placing the breadboard with photodiodes on a rotating platform with the light source in front and then record Vleft and Vright at various angles (in 1 degree steps?) of the platform in relation to the light source.
If two photoresistors don't give you the required precision and/or range, you can use more photoresistors and use the pair which is best 'looking' in the direction of the light source.


message:
How do I control the rotation of my servo?

```c++
#include <Servo.h> // servo library
Servo servo;
int trigPin = 5;
int echoPin = 6;
int servoPin = 7;
int led= 10;
long duration, dist, average;
long aver[3];   //array for average

void setup() {
  Serial.begin(9600);
  servo.attach(servoPin);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  servo.write(0); // close cap on power on
  delay(100);
  servo.detach();
}

void measure() {
  digitalWrite(10,HIGH);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(15);
  digitalWrite(trigPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  dist = (duration/2) / 29.1; // obtain distance
}

void loop() {
  for (int i=0; i<=2; i++) {
  // average distance
  measure();
  aver[i] = dist;
  delay(10); // delay between measurements
  }

  dist = (aver[0]+aver[1]+aver[2])/3;

  if (dist < 50) { // Change distance as per your need
    servo.attach(servoPin);
    delay(1);
    servo.write(0);
    delay(3000);
    servo.write(150);
    delay(1000);
    servo.detach();
  }

  Serial.print(dist);
}
```

This is my first time in robotics. The servo is a Tower Pro SG90. It rotates over 360° and ony spins in one direction, but I want it to rotate for just about 90° and to rotate back to its original place after. This is the code I used. I'm making a trash bin where the lid automatically opens.

body:
You should buy a normal servo, not a servo with continuous rotation. The Tower Pro SG5010, for example, should basically meet your needs.
But depending on the size of the bin and the mechanical control of the lid, you may want to choose a servo with greater actuating force.


message:
How to read analog sensor data with different timers in arduino

I have three analog sensors like voltage, temperature and pressure. I need to measure the voltage and temperature every 10 ms and I need to measure the pressure alone every 30 ms by using the timers in an Arduino.

How can I do this?

body:
 May this help as starting point! Not tested

```
void setup() {
  Serial.begin(9600);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
  pinMode(A2, INPUT);
}

unsigned long previousMillis1;
unsigned long previousMillis2;

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis1 >= 10) {
    int val1 = analogRead(A0);
    int val2 = analogRead(A1);
    Serial.print("Values from A0 and A1: ");
    Serial.print(val1);
    Serial.print(" ");
    Serial.println(val2);
    previousMillis1 = currentMillis;
  }

  if (currentMillis - previousMillis2 >= 30) {
    int val3 = analogRead(A2);
    Serial.print("Value from A2: ");
    Serial.println(val3);
    previousMillis2 = currentMillis;
  }
}
 ```


message:
Why 5V instead of 3V3?

I'm still quite new to electronics, so please forgive me if the answer is obvious.

I was wondering why virtually all the example circuits I find use the 5V power supply with resistors for all the components instead of the 3V3 power supply directly.

Even for the most simplistic "Blink" example, they use 5V pin and a 220 Ohm resistor to protect the LED instead of using the built-in 3.3V pin.

Yes, I know that in former times "everything" ran on 5V, but since we already have a lower voltage built-in, why not use it and reduce the number of components needed?

TIA for anyone who can solve this puzzle for me.
mav

body:
First, even with 3.3V, an LED needs a resistor to limit the current through it. So, running with 3.3V doesn't solve that particular problem. Try Googling for "LED current limiting resistor".

Second, many Arduinos are designed to run using 5V. In many cases they have an input power jack which can accept a range of voltages and use a voltage regulator to convert it down to 5V,

Why not convert down to 3.3V you might ask? Well, the higher the voltage, the faster the processor can run, within its design limits. For example, the Atmega328P (which is in the Arduino Uno, and others) could only run at 13 MHz at 3.3V rather than 16 MHz.

> ... instead of using the built-in 3.3V pin

But that pin is only provided for convenience. You can't turn it on or off by a program.

The higher voltage (5V vs 3.3V) can be more convenient in some situations, for example switching motors on and off, or with other devices designed to work with 5V.

Motors or other high-power devices are typically turned on with MOSFET transistors. To be efficient, they need to fully turn on (have a low resistance between Source and Drain) and even so-called "logic level" MOSFETs typically require 5V to fully turn them on, rather than 3.3V. If you tried to control a motor with a 3.3V based board you would probably need extra components to turn the MOSFET on properly, so lowering the voltage could potentially add components, not reduce them.

On the other hand, many components these days are designed to work with 3.3V (or lower) so the choice of 5V is a bit of a compromise.


message:
Arduino nano 33 BLE serial port not working with C# app

I use an Arduino Nano with some sensors and send data to a PC using the serial port. I just got a new Arduino Nano 33 BLE and tried the same code but its not working. So for testing I just wrote some simple test code on the Arduino Nano 33 BLE side:
```
void setup()
{
  Serial.begin(57600);
}

void loop()
{
  if (Serial.available())
  {
    char c = Serial.read();
    Serial.write(c);
  }
}
```
This just sends back whatever arrives through the COM port. Using the Arduino IDE Serial Monitor this works very well with the Arduino Nano 33 BLE.
I also made this very simple C# test code (Windows Forms app):
```
SerialPort serialPort = new SerialPort("COM17", 57600);
serialPort.ReadTimeout = 4000;
serialPort.WriteTimeout = 4000;
serialPort.Encoding = Encoding.ASCII;
serialPort.DataReceived += SerialPort_DataReceived;
serialPort.Open();
if (serialPort.IsOpen)
{
 Debug.Print("COM port open");
}
```
This C# code works perfect with my good old Arduino Nano but it doesn't work with the Arduino Nano 33 BLE. I have the **COM port open** message so the port exists and it is open, but then nothing else, no timeout, nothing.
I already lost one day trying out all sorts of combinations but it just doesn't work, my C# app can't communicate with the Arduino Nano 33 BLE. It looks like a serial port issue so I think I'll put it on hold for now...

EDIT:
The rest of my test code, for reference:
```
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
 try
 {
  Debug.Print(serialPort.ReadExisting());
 }
 catch (Exception exception)
 {
  Debug.Print(exception.Message);
 }
}

private void buttonSend_Click(object sender, EventArgs e)
{
 try
 {
  serialPort.WriteLine("HELLO");
 }
 catch (Exception exception)
 {
  Debug.Print(exception.Message);
 }
}
```

body:
I noticed that a lot of line discipline and flow control settings were not made explicit in your C# code, so it made me wonder what they were by default.

In particular `DtrEnable` appears to be [false by default][1] and `Handshake` is None by default (which seems to be irrelevant). The other default amount to 8N1. The first part I found interesting because it seems more typical in serial APIs for DTR to be automatically asserted when a port is opened when you're not explicitly asking it to.  If I'm reading the .NET documentation correctly, it isn't for your application. The original Nano doesn't much care about DTR apart from a falling edge triggering reset. The board is happy to communicate with it solidly either asserted or not. The original Nano's DTR is only capacitively coupled to reset; there's not a way for the code running on the AVR to respond to DTR (unless you count resetting). That lead to a question about to what extent a Nano 33 BLE would care about DTR.

As it turns out the Nano BLE does care. If I deassert DTR in test with pyserial the board stops sending traffic back. I can write while it's deasserted and after asserting again some queued data arrives. *A test environment with pyserial is just more immediately available to me; if needed and I get a chance I'll set up a .net/C# test and confirm with that, but I suspect that won't be necessary.* Seeing that result, I searched and found [this Arduino Forum post][2] with a somewhat similar problem description. The OP replies in answer to their own post saying:

> Problem sorted out. Arduino nano BLE requires DTR and RTS signals to
> be On. Then it works like FDTI.

Disabling RTS had no effect during my tests with pyserial. I'm not sure why it would. Perhaps they just asserted it preemptively. Being entirely a virtual port RTS doesn't really make sense for flow control. DTR might arguably still makes more sense in this context; at the level of serial signals it normally tells you something is paying attention on the other side of the connection. I'm not really surprised, either way, that the BLE sense would react to DTR being disabled by not sending data to the host; there's a lot of latitude in how these signals can be handled. That it's not automatically used when the port is opened (or until specifically requested) seems *mostly* a C# thing. But it looks like the different handling of DTR between the two boards that is making your code work with one but not the other.

So it would seem necessary and sufficient to add
```c++
serialPort.DtrEnable = true;
```
amongst your other settings following the opening of the port.

If there's truth to what the Arduino Forum poster said about RTS, then you would also need
```c++
serialPort.RtsEnable = true;
```

but this is not indicated by the tests I've done (though again with pyserial).

  [1]: https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport.dtrenable?view=dotnet-plat-ext-7.0#system-io-ports-serialport-dtrenable
  [2]: https://forum.arduino.cc/t/cannot-read-write-using-3rd-party-terminal-to-arduino-nano-ble-board/642034


message:
Is there a schematic for the ESP32S Dev Kit C V4 NodeMCU WLAN Development Board?

Recently I bought a ESP32S Dev Kit C V4 NodeMCU WLAN Development Board. I got it from azdelivery.de in Germany.
Now I am interested in the schematic for this board to learn more about it. Not Google, nor the support team at azdelivery.de could help me, but since the board is a Chinese mass product, I hope to find an answer here, where I could get the schematic.
Thank you!

[![Picture][1]][1]

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

body:
Here is a webpage that provides ESP32 Devkit C schematic and pin definition.

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

[ESP32 Devkit C schematic][2]

  [1]: https://i.stack.imgur.com/2C0wr.jpg
  [2]: https://esp32cube.com/esp32/esp32_dev_board.html


body:
Espressif has schematics and more on their website. EZ-Delivery sells two different versions: One has a CP2101 USB-Interface, the other one uses a CH340 instead. If you have the CP2101 variant, this should match the one at Espressif's Website:

https://dl.espressif.com/dl/schematics/esp32_devkitc_v4-sch.pdf

More related docs are linked on their Website (scroll down to "Related Documents" here:

https://docs.espressif.com/projects/esp-idf/en/latest/esp32/hw-reference/esp32/get-started-devkitc.html#get-started-esp32-devkitc-board-front


message:
How to get rid of the second tab in Arduino IDE 2?

For a reason unknown to me, Arduino IDE 2.0.3 opens two tabs with the same name for this sketch. I'm not able to reproduce how to get into this situation.

Changes in one tab immediately changes the other tab as well.

How can I get rid of the second tab?

[![Duplicate tab][1]][1]

Things I tried:

* File / Close (Ctrl+W) closes the whole sketch, i.e. Arduino IDE exists.
* The usual key combination to close tabs (Ctrl+F4) does not work either.
* I deleted all `%AppData%\Local\Temp\.arduinoIDE-unsaved*.gfv2` folders
* I deleted all `%AppData%\Local\Temp\arduino-sketch-*` folders
* I deleted all `%AppData%\Local\Temp\arduino-language-server*` folders
* I deleted all `%AppData%\Local\Temp\arduino-ide2-*` folders
* I used [Streams](https://learn.microsoft.com/en-us/sysinternals/downloads/streams) to check the INO file for alternate data streams
* I deleted the folder `%UserProfile%\.arduinoIDE`

Maybe interesting: when I rename the sketch to HelloWorld2.ino, it opens only one tab. If I rename it back, I have two tabs again.

When I change the preferences to show the files in Sketchbook view, I only see one file:
[![Sketchbook view][2]][2]

The other sketches have been created when trying to reproduce the problem. They are not affected

The tooltip which shows the full file name is identical on both files:

[![Identical tooltips][3]][3]

The Registry does not contain suspicious information. I found only one occurrence of HelloWorld in

```regedit
HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\TypedPaths
```

  [1]: https://i.stack.imgur.com/FqcL3.png
  [2]: https://i.stack.imgur.com/WCJB9.png
  [3]: https://i.stack.imgur.com/f9q3c.png

body:
> How can I get rid of the second tab?

 - Press F1,
 - Type: `View: Reset Workbench Layout` into the _Command Palette_,
 - Press Enter,
 - IDE reloads.

If it does not help, get the [layout data](https://github.com/arduino/arduino-ide/blob/76f9f635d8558f399423f64c0c709e3a53bdcd03/arduino-ide-extension/src/browser/theia/core/shell-layout-restorer.ts#L23-L25) from the logs.
 - Open the DevTools with Ctrl/⌘+Alt+I [built-in](https://github.com/eclipse-theia/theia/blob/7c559c87b3ffb0c7c3845309c20d3bf22529a076/packages/core/src/electron-browser/menu/electron-menu-contribution.ts#L340-L343) command,
 - Open the _Console_ if it's not opened with Esc,
 - Right-click in the console and `Save as...`,
 - Share the data with the devs.

For example:

```json
{"version":5,"mainPanel":{"main":{"type":"tab-area","widgets":[{"constructionOptions":{"factoryId":"code-editor-opener","options":{"counter":0,"kind":"navigatable","uri": ...
```


message:
AD8232 - Measuring heart rate only if USB connector is touched. Grounding issue?

### TL;DR
I can read out my heart rate but I have to physically touch GND of the Arduino or else the signal is just noise.

### Description

So I've started to play around with an Arduino and wanted to try out a heartrate sensor module (AD8232).

The following is the code I am using for this:

```c
const int CONNECTED_LED = 13;

const int LO_MINUS = 10;
const int LO_PLUS = 11;

bool disconnected = true;

enum State {
  CONNECTED,
  DISCONNECTED,
  LO_MINUS_DISCONNECTED,
  LO_PLUS_DISCONNECTED
};

enum State currentState = DISCONNECTED;

void setup() {
  Serial.begin(9600);
  pinMode(LO_MINUS, INPUT); // Setup for leads off detection LO +
  pinMode(LO_PLUS, INPUT); // Setup for leads off detection LO -
}

void loop() {
  State nextState = getState();

  if (nextState != currentState) {
    // Store the current state
    currentState = nextState;
    switch (nextState) {
      case DISCONNECTED:
        break;
      case LO_MINUS_DISCONNECTED:
        break;
      case LO_PLUS_DISCONNECTED:
        break;
    }
  }

  if (currentState == CONNECTED) {
    digitalWrite(CONNECTED_LED, HIGH);
    Serial.println(analogRead(A0));
  } else {
    digitalWrite(CONNECTED_LED, LOW);
    // Serial.println(-1);
  }

  delay(1);
}

State getState() {
  if (digitalRead(LO_MINUS) == 1 && digitalRead(LO_PLUS) == 1) {
    return DISCONNECTED;
  } else if (digitalRead(LO_PLUS) == 1) {
    return LO_PLUS_DISCONNECTED;
  } else if (digitalRead(LO_MINUS) == 1) {
    return LO_MINUS_DISCONNECTED;
  }
  return CONNECTED;
}

```

This is how I am connecting the boards (I double checked already twice)

```
AD8232  | Arduino UNO R3
------------------------
GND     |  GND
3.3v    |  3.3V
OUTPUT  |  A0
LD-     |  ~10
LD+     |  ~11
SDN     |  <not used>
```

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

I've followed this diagram for connecting the electrodes:

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

However, the result is a random signal _unless_ I am touching the USB-connector or GND of the Arduino.

Below you can see the random signal and the moment I touched the connector. I noticed this by accident after hitting the reset button after wondering why on earth I only get this random signal:

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

So.. what's going on here? I have all three electrodes connected.

I've even tried to different modules (I bought the AD8232 two times) but I see the same issues with both modules.

If I touch something else e.g. a radiator (heater) then the signal becomes another kind of random. It only works touching the connector.

Since this appears like a grounding issue I checked for continuity from the GND pin of the AR8232 to the USB connector and continuity is given.

I'm not expert enough (yet) to see the problem. Anybody?

  [1]: https://i.stack.imgur.com/bk6Ho.jpg
  [2]: https://i.stack.imgur.com/vFAEc.png
  [4]: https://i.stack.imgur.com/7ExZS.png

body:
One of your three ECG leads is equivalent to (human)body ground, and it's not making contact. I spent too long making this image to explain it, which should help you a lot more than it will me.  I mean, I don't have the board in my hands, so I cannot see which lead goes to which pin.  You can, easily, with a multimeter testing for continuity between the:
RIGHT ARM,
RIGHT LEG,
LEFT ARM (RA, RL, LA) solder spots, and the tip, ring, barrel of the jack.
Something to keep in mind though is the headphone jack switch.  When the plug is physically inserted, this switch opens.  Again, I'm not there to guide your multimeter, so this image is the best I can do for you.  One of your leads is going to be a grounding lead. It may be the "black" one, it may be the (traditionally) "RL" one, it may be another one, i can't tell.

When you touch USB ground you are effectively replacing the body contact of the missing ground lead. I made these images for you to better understand it.  You should be able to fault find this in a few minutes via you MM and continuity testing.
[![combined image of AD8232 with x-ray vision, and leads][1]][1]

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


message:
How to fix the scambled output of the emojis in Arduino IDE 2?

I have relatively simple code printing some emojis:

```cpp
void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Hello world ❤♀♂✔");
}
```

Just in case it doesn't render very well, here's an image on how it looks like in Arduino IDE 2.0.3:

[![Screenshot of code with emojis rendered][1]][1]

However, the Serial Monitor sometimes displays emojis and sometimes not. It varies from line to line like so:

```none
Hello world �����������������♀�������♂✔����
Hello world ���������������♀♂✔
Hello world ��❤���������������������������������♂���✔
Hello world ❤��������������������
Hello world �������♀��������������✔����
Hello world ��������������♀�������������������
Hello world ��❤���������������������♂�������✔���
```

Again, there's how it looks like on my Windows 10 machine:

[![Screenshot of garbage output][2]][2]

I verified that it's not a mistake in the baud rate. Both, Arduino and PC are set to 9600.

In Arduino IDE 1, the output is not colorful and some emojis are not rendered at all, but the result is much more consistent:

[![Screenshot of output in Arduino IDE 1][3]][3]

How to fix the scrambled output in Arduino IDE 2?

  [1]: https://i.stack.imgur.com/9AvLr.png
  [2]: https://i.stack.imgur.com/qbR5l.png
  [3]: https://i.stack.imgur.com/FYLnF.png

body:
This is an issue of Arduino IDE 2.0.3. It was reported as [issue 589](https://github.com/arduino/arduino-ide/issues/589) and [issue 1405](https://github.com/arduino/arduino-ide/issues/1405).

It was fixed on 9th of December 2022 [[PR]](https://github.com/arduino/arduino-ide/pull/1758) and I can confirm it is fixed in nightly build 2.0.4-221229.


message:
How do I reset the recently used commands in Arduino IDE 2?

I am recording videos on Arduino IDE version 2. In one of the videos I want to explain how to enable a specific setting via the advanced properties. This requires using Ctrl+Shift+P (command palette).

However, my Arduino IDE now shows some commands I have used recently (sorry, screenshot is in German).

[![Arduino IDE 2 Command palette][1]][1]

That's not the default. If someone has just installed Arduino IDE, he would need to scroll until he finds the entry. How do I reset the recently used items, so that I can record a proper video which requires scrolling?

Resetting the workbench layout does not help.

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

body:
1. open the command palette
2. search and choose Preferences: Open Settings (UI)
3. in the preferences window, search for the setting `workbench.commandPalette.history`
4. set that value to 0 and it will not save the recent commands


message:
Can I configure the highlighting for escaped characters in a string?

Given a simple mistake like

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

void loop() {
  Serial.println("\");     // note: " is escaped, so this won't compile
}
```

This is rendered in Arduino IDE 2.0.3 as

[![Syntax highlighting in Arduino IDE 2.0][1]][1]

and the problem is hard to spot.

The Jetbrains IDEs have special highlighting for escaped characters like

[![Special highlighting of escape characters][2]][2]

which makes the problem more obvious because the two quotation marks have different color.

Any chance that this can be configured in the new Arduino IDE 2.0.3 as well?

Because it was asked in the comments: no, the syntax highlighting does not highlight the escaped character when the string is complete. The backslash and quotation mark are both still green.

[![Complete string][3]][3]

  [1]: https://i.stack.imgur.com/bw9mn.png
  [2]: https://i.stack.imgur.com/8V10a.png
  [3]: https://i.stack.imgur.com/Dbb6x.png

body:
> Any chance that this can be configured in the new Arduino IDE 2.0.3 as well?

Yes. You'll need to enable the Arduino language features provided by the [language server](https://github.com/arduino/arduino-language-server). They're disabled by default.

 - Press F1,
 - Type `Preferences: Open Settings (JSON)`,
 - Press Enter,
 - The `settings.json` file opens.

Add the following to the JSON and save it if you do not have auto-save enabled:

```json
{
  "arduino.language.realTimeDiagnostics": true
}
```

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

My `settings.json` with the Arduino language features enabled.

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

Select a board. You can ignore the port selection if you like. The language feature should start, and you will see the error in the editor.

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

More details on the _Advanced Settings_ are [here](https://github.com/arduino/arduino-ide/blob/main/docs/advanced-usage.md).

  [1]: https://i.stack.imgur.com/NS79o.png
  [2]: https://i.stack.imgur.com/qg8Zk.png
  [3]: https://i.stack.imgur.com/FJn8T.png


message:
Why does Serial.write() work but Serial.print() doesn't?

I am testing my GPS module with an ESP32 using the Arduino IDE. I'm asking because I usually don't fully understand the difference between `Serial.write()` and `Serial.print()`.

This code is working perfectly with `Serial.write()` and the output is meaningful:

    void loop() {
      while (Serial2.available() > 0) {
        Serial.write(Serial2.read());
      }

      Serial.println("-------------------------------------");
    }

Output:

    13:28:05.173 -> -------------------------------------
    13:28:05.206 -> $GPRMC,,V,,,,,,,,,,N*53
    13:28:05.238 -> $GPVTG,,,,,,,,,N*30
    13:28:05.238 -> $GPGGA,,,,,,0,00,99.99,,,,,,*48
    13:28:05.270 -> $GPGSA,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30
    13:28:05.334 -> $GPGSV,1,1,00*79
    13:28:05.334 -> $GPGLL,,,,,,V,N*64
    13:28:05.366 -> -------------------------------------

When I convert this code to `Serial.print()` the output looks strange:

    void loop() {
      while (Serial2.available() > 0) {
        Serial.print(String(Serial2.read()));
      }

      Serial.println("-------------------------------------");
    }

Output:

    13:26:43.118 -> -------------------------------------
    13:26:43.150 -> -------------------------------------
    13:26:43.214 -> 367180827767444486444444444444444444447842535113103671808684714444444444444444447842514813103671807171654444444444444844484844575746575744444444444442525613103671807183654465444944444444444444444444444444575746575744575746575744575746575742514813103671807183864449444944484842555713103671807176764444444444448644784254521310-------------------------------------
    13:26:43.566 -> -------------------------------------
    13:26:43.629 -> -------------------------------------

Why does `Serial.write` work, but `Serial.print` doesn't? Or: how to write the same code with `Serial.print()`?

body:
> Why does Serial.write work, but Serial.print doesn't?

`Serial.read()` returns an integer for each byte from the serial port.

`String` converts each integer to its decimal ASCII representation (e.g. $ = "36", G = "71" etc), so `Serial.print()` receives an ASCII string with the decimal values of each input byte, which were already ASCII. This is probably not what you want.


message:
is there Raw RTC output?

I have an I2C Real Time Clock, DS3231 RTC module , and I just want something like Unix Time.
I'm using the uRTCLib, looking at the [class methods][1]
but dont see anything like that. I'm thinking there must be a raw read that would return all the digits. Is there an easy way to do that?

  [1]: https://naguissa.github.io/uRTCLib_doc_and_extras/classuRTCLib.html#af8eea2501d6b82726ce6226529c82a89

body:
The DS3231 doesn't report the Unix time. It reports the current time in
broken-down form (year, month... second). If you need Unix time, you
have to compute it.

I suggest using Adafruit's [RTClib][]. This library implements the
computation of Unix time, e.g.

```c++
uint32_t unix_time = rtc.now().unixtime();
```

[RTClib]: https://github.com/adafruit/RTClib


message:
Temperature is not updated on OLED screen - Grove components

I am using 2 grove components in order to display a temperature. I use an [I2C High Accuracy Temperature Sensor - MCP9808][1] and an [OLED Screen][2] using this script:

    #include <U8g2lib.h>
    #include <SPI.h>
    #include <Wire.h>
    #include "Seeed_MCP9808.h"

    MCP9808 sensor;
    U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/SCL, /* data=*/SDA, /* reset=*/U8X8_PIN_NONE);  //Software I2C

    char strTemp\[16\];
    float temp;

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

      if (sensor.init()) {
        Serial.println("sensor init failed!!");
      }
      sensor.set_config(SET_CONFIG_ADDR, 0x0008);
      Serial.println("sensor init!!");
    }

    void loop() {
      sensor.get_temp(&temp);
      Serial.print("temperature value is: ");
      Serial.println(temp);
      delay(1000);

      dtostrf(temp, 7, 2, strTemp);

      u8g2.clearBuffer();                   // clear the internal memory
      u8g2.setFont(u8g2_font_luBIS08_tf);   // choose a suitable font
      u8g2.drawStr(0, 10, "Hello Seeed!");  // write something to the internal memory
      u8g2.drawStr(0, 30, "Temp. value:");  // write something to the internal memory
      u8g2.drawStr(0, 50, strTemp);         // write something to the internal memory
      u8g2.sendBuffer();                    // transfer internal memory to the display
    }

The temperature output is not updated on the screen and I think it might be related to I2C addresses. Is it possible?

I run an I2C scanner and I think that the OLED address is 0x3C and the temp. sensor is 0x18. How can I assign them correctly. I never done something like that so any help is welcome.

Thanks a lot.

  [1]: https://www.seeedstudio.com/Grove-I2C-High-Accuracy-Temperature-Sensor-MCP9808.html
  [2]: https://www.seeedstudio.com/Grove-OLED-Yellow-Blue-Display-0-96-SSD1315-V1-0-p-5010.html

body:
You mix software I2C with hardware I2C on the hardware I2C pins.

To use hw I2C with the display use the U8G2_SSD1306_128X64_NONAME_F_**HW**_I2C constructor.

```
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/U8X8_PIN_NONE);
```

Or use a different pair of pins for the software I2C display control.


message:
GCRduino shows up briefly in the IDE and then disappears

I have two UNO boards from a few years ago. They look the same as far as chip placement goes.

I can plug both in and get flashing lights on them, and when I hit the reset (2x the on-off) button, they both make the same LED "noises".  Since the LEDs on the non-detected board flash the same start-up sequence as a board that is detected, I assume both boards are working.

One of them has "UNO" printed on the circuit board and the other has "GCRduino Rev 1.0" printed on the circuit board. (edited according the comments for clarification)

I'm using Linux Mint 21 and Arduino IDE 2.0.3.

On hardinfo (the linux program), both of them are listed in Devices->USB Devices as "QinHeng Electronics CH340 serial converter."

The one that has UNO printed on the board is detected and I can load software onto it. The one that say GCRduino is not detected by the IDE and no new entry shows up in /dev.

The GCRduino is detected for a split second and then disappears again.  check this video: http://100wires.com/arduino.mp4

body:
I found the problem with dmesg.  When I insert the card and it shows up very briefly, it gets kicked by another device:

    [  167.032321] input: BRLTTY 6.4 Linux Screen Driver Keyboard as /devices/virtual/input/input25
    [  172.660038] usb 3-3: new full-speed USB device number 9 using xhci_hcd
    [  172.809032] usb 3-3: New USB device found, idVendor=1a86, idProduct=7523, bcdDevice= 2.62
    [  172.809038] usb 3-3: New USB device strings: Mfr=0, Product=2, SerialNumber=0
    [  172.809041] usb 3-3: Product: USB2.0-Serial
    [  172.810938] ch341 3-3:1.0: ch341-uart converter detected
    [  172.811372] usb 3-3: ch341-uart converter now attached to ttyUSB0
    [  173.349731] input: BRLTTY 6.4 Linux Screen Driver Keyboard as /devices/virtual/input/input26
    [  173.655257] usb 3-3: usbfs: interface 0 claimed by ch341 while 'brltty' sets config #1
    [  173.656203] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0
    [  173.656275] ch341 3-3:1.0: device disconnected

I can see the device on lsusb:

Bus 003 Device 008: ID 1a86:7523 QinHeng Electronics CH340 serial converter

That same device serial number is listed in

    grep 1a86 /usr/lib/udev/rules.d/85-brltty.rules
    ENV{PRODUCT}=="1a86/7523/*", ENV{BRLTTY_BRAILLE_DRIVER}="bm", GOTO="brltty_usb_run"

So when it connects, it gets kicked off by it being detected as another device.

So I just comment out that line in /usr/lib/udev/rules.d/85-brltty.rules, restart, and the board can now be detected.


message:
How to abort compilation based on a "wrong" value in a variable

I looking for some code that can generate a compile time error when a variable contains a wrong value.

I once started with this code in a c program:
```
#define FIFO_BUFFER_SIZE 8

#define FIFO_BUFFER_MASK ( FIFO_BUFFER_SIZE - 1 )

#if ( FIFO_BUFFER_SIZE & FIFO_BUFFER_MASK )
#error Fifo buffer size is not a power of 2
#endif
```

Rewrote that in C++ for a PC console application:
```
MovingAVG::MovingAVG( const unsigned long element_count ) {
    ptr = 0;
    siz = element_count;
    buf = new long[siz];
    msk = siz - 1;
    if( siz & msk ) {
        //std::cerr << "Buffer size is not a power of 2" << std::endl;
        //exit( -1 );
    }
}
```

Now I want to use something similar in an Arduino sketch.
Because there is not always a terminal connected to the serial port and exit() is useless in a microcontroller, I am looking for a way to abort compilation based on a value in a variable.
I don't give myself much chance to find anything but to be absolutely sure that there is really no way, I am dropping the question here.

I want to abort compiling (preferably with a message) when the parameter of a class-constructor contains an invalid value. Is that possible at all?

Actually I want to see a message before I start programming the device. I have posted a possible solution below, that will throw a message during linking, but that only works when I declare the class with a constant parameter:
```
class MovingAVG avg( 32 );
```

body:
Because `element_count` is a method's parameter, it is by definition _variable_. Therefore, its value is generally **not known** at compile time.

Since the value of `element_count` is not known at compile time, you cannot get a compile time error for a wrong value.

---

Only if you use the method (here: a constructor) in the _same translation unit_ as its definition, and if the arguments of all calls are known to the compiler (they are _constants_), the compiler will be able to evaluate `siz & msk` as a constant. Please note that some compilers need to receive optimization options for this.

Then you can use any approach that triggers a compiler diagnostic, for example like [this one][1] in C.

  [1]: https://stackoverflow.com/a/59730203/11294831


body:
This will do the trick, a very dirty trick but it will generate an error before I program/test the device.
That might save a few program cycles of the device, but more important it will not waste my time.
```
extern void ElementCountShouldBeAPowerOfTwo(void);

MovingAVG::MovingAVG( const unsigned long element_count ) {
    ptr = 0;
    siz = element_count;
    buf = new long[siz];
    msk = siz - 1;
    if( siz & msk ) {
        // This function will be removed by the optimiser
        // when the buffer size is a power of 2
        ElementCountShouldBeAPowerOfTwo();
    }
}
```

The compiler will not complain about the function "ElementCountShouldBeAPowerOfTwo" because it is marked as external. The linker will throw an error when the optimizer leaves the call in place.

In case the linker throws an error it will show:
```
undefined reference to `ElementCountShouldBeAPowerOfTwo()'
```

@chrisl
I've used both code in C and in C++ and I don't want to rewrite the C++ part.
You and @the_busybee were both right when you wrote that the error will not be shown at compile time.

I should have asked my question differently, I want to see a warning before I program the device :-)

I do not mark an answer because I expect this to fail in the future when the compiler is updated. For the moment, with Arduino 1.8.19, it does what I want.


body:
As suggested by timemage, I think `static_assert()` is the right
solution to your problem: it is the clearest and most semantically
correct. The problem is, you cannot plug `static_assert()` directly into
your code, as the expression you are testing is not a compile-time
constant.

I suggest you turn the argument of the constructor into a template
argument. This will guarantee it is a compile-time constant. As a bonus,
you will be able to use a statically-allocated buffer, which is nicer on
the RAM than dynamic allocation:

```c++
template <int siz> class MovingAVG {
    static const int msk = siz - 1;
    long buf[siz];
    int ptr = 0;
public:
    MovingAVG()
    {
        static_assert((siz & msk) == 0,
                "Element count should be a power of two.");
    }
};
```

This works:

```c++
MovingAVG<32> filter;
```

but this fails with “error: static assertion failed: Element count
should be a power of two.”:

```c++
MovingAVG<33> filter;
```


message:
Curious Collision between OneWire and RadioHead

The code below runs on an Arduino Pro Mini (8MHz 328p) sending temperature readings using an inexpensive ASK transmitter. I use OneWire to read the DS18B20s, and RadioHead to manage the radio.

The original problem was the send() calls at the top of the loop *always* worked, but the send() call in the temperature-reading loop *never* did.

The fix was to insert a call to setModeTx() ahead of the send() call. I'm pleased it works, but it's a hollow victory because I can't figure out *why* it works.

OneWire uses no timers and no interrupts. I wait for the temperature conversion using ```_delay_ms()``` which is a spin delay.

I've read and re-read the OneWire and RH_ASK code and am still puzzled. Can anyone explain?

Many thanks

Here's the gist of the code…
```
RH_ASK radio(1024, 0, 10, 0, false);
OneWire ow(2);

void loop()
{
    radio.send(/* build info */);     // always works
    radio.send(/* battery health */); // always works
    ow.reset_search();
    while (ow.search(addr))
    {
        read_thermometer(addr);

        // the following send() works ONLY
        // when preceded by setModeTx()
        // It *never* works without it
        radio.setModeTx();
        radio.send(/* one temp reading */);
    }
}
```

UPDATE

@timemage was correct in that there are also calls to Serial (which resolve to HardwareSerial) interspersed. I'm no closer to solving it; however, by rearranging calls I can get the failure to happen more- or less often.

In a way this highlights the distinction between diagnosis and repair. I may in the end discover an ordering of the calls that makes the failure exceedingly rare, and in this case the problem will have been *repaired*; though not *diagnosed*.

body:
Finally had time to get back to this. I connected the data-out line from the sender to the data-in line of the receiver, and discovered it always works. So it's **not** any sort of collision between OneWire and RadioHead, curious or otherwise. There's something amiss with the radio link… but what?

Have a look at the following oscilloscope traces. The magenta line is the input to the transmitter. Cyan is the output from the receiver (an SYN480R if you're curious). Yellow is just there to trigger the scope (a digitalWrite() just before sending the problem message).

The packet from the transmitter begins with a series of training pulses for the receiver to establish things like gain and threshold for the demodulator. Thereafter, the data is encoded in a series of long and short pulses.

Note how the receiver (cyan line) syncs up with the training pulses, and is in lock-step with the transmitter... until ... IT GETS LOST and thinks everything is a zero for awhile. It eventually re-syncs with the transmitter, but by this point the packet is corrupt, gets rejected by the decoder, and *that* is why I'm losing the packet at the receiver.

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

But, one wonders, why this particular packet and not any of the others? The answer to that question is pretty much out of band for a software forum, but here goes. Let's add a trace to the scope display.

The following image includes the demodulator threshold in blue. That's an analog value that the demodulator uses to decide if it's looking at a one or a zero. For the SYN480R chip, it's the output of a low pass filter, which produces an *average* over the recent bits.

In this case, notice how the threshold rises during the early part of the packet, then settles down. My conjecture is there are too many ones in the packet encoding thus far (i.e. many more ones than zeroes), and this shifts the threshold high enough that the demodulator thinks everything it sees is a zero. This is confirmed in the previous image. Seeing all zeroes, the threshold settles down and the demodulator can sync up again.

Interestingly, just touching the scope probe to the threshold capacitor (to get the blue trace) disturbs the threshold enough to slow the rise and keep the packets working.

Thus, OneWire is definitely off the hook, as is any interaction with RadioHead. Moving on, I either need to make some tweaks to the RadioHead RH_ASK driver packet encoder, or change out the threshold capacitor in the receiver. That in itself is a balance, because you want it to be able to track changes in the received signal, yet not be so sensitive to packet encoding.

Hope you found this interesting. Many thanks to everyone who took a look and offered your insight.

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

  [1]: https://i.stack.imgur.com/QTDGK.jpg
  [2]: https://i.stack.imgur.com/4JP41.jpg


message:
Arduino code giving error while compiling

I am a beginner, and I'm trying to make code to control a servo using two ultrasonic sensors.
I've tried to make the code, but when I tried to compile it using my simulation app, it gives this error:

```
sketch.ino: In function 'void value2()':
sketch.ino:123:19: error: expected ')' before '!' token
 if((L < R)>=6 & L !> normal){
                   ^
sketch.ino: In function 'void value3()':
sketch.ino:131:19: error: expected ')' before '!' token
 if ((R< L)>=6 & R !> normal){
                   ^

Error during build: exit status 1
```

How do I go about fixing this?
I'm using the Wokwi simulator website, and here is the [link to the simulation][1].

Here is where the problem is in my code:

```c++
void value2() {
  /* I'm using L !> normal to make sure it doesn't run when L is greater than 750, and this is where the problem comes */
  if ((L < R) >= 6 & L !> normal) {
    servo.write(120);
    //goto
    loop();
  }
}

void value3() {
  /* I'm using R !> normal to make sure it doesn't run when R is greater than 750, this is also where the problem comes */
  if ((R < L) >= 6 & R !> normal) {
    servo.write(60);
    //goto
    loop();
  }
}
```

And here is my complete code:

```c++
#include <Servo.h>
#include <Stepper.h>
#define STEPS 100 // stepper steps
#define speed 30 // stepper speed
#define Lechopin 10 // ultrasonic sound sensor left
#define Ltrigpin 11 // ultrasonic sound sensor left
#define Rechopin 12 // ultrasonic sound sensor right
#define Rtrigpin 13 // ultrasonic sound sensor right
long Lduration;
long Ldistance;
long Rduration;
long Rdistance;
int  L;
int  R;
int dt1 = 100; //delay
int dt2 = 1;   //delay
int dt3 = 2;   //delay
int dt4 = 10;  //delay
int serv = 9;  //servo pin
Servo servo;
Stepper stepper(STEPS, 5, 6, 7, 8);
/* Assuming distance of 4 feet measured by sensor is between 100 to 1000, let's set 750 as the normal distance between
sensor and object in which will be anything in 4feet upward far
away from sensor won't be detected by the code. you can edit it with real time measurement, I just assume this */
int normal=750;
int minn=250;

void setup() {
  Serial.begin(9600);
  stepper.setSpeed(speed);
  servo.attach(serv);
  pinMode(Lechopin,INPUT);
  pinMode(Ltrigpin,OUTPUT);
  pinMode(Rechopin,INPUT);
  pinMode(Rtrigpin,OUTPUT);
}

void loop() {
  get_L_dist();
  L = get_L_dist();
  get_R_dist();
  R = get_R_dist();

  normalp();
  value1();
  value2();
  value3();

  //bailout;
}

//print sensors
/*
Serial.print("L is:");
Serial.println(L);
Serial.print("R is:");
Serial.println(R);
*/

/* read left sensor and calculate the distance */
long get_L_dist() {
  digitalWrite(Ltrigpin, LOW);
  delayMicroseconds(dt3);
  digitalWrite(Ltrigpin, HIGH);
  delayMicroseconds(dt4);
  digitalWrite(Ltrigpin, LOW);
  Lduration=pulseIn(Lechopin, HIGH);
  Ldistance=Lduration / 58.2;
  return Ldistance;
}

/* read right sensor and calculate the distance */
long get_R_dist() {
  digitalWrite(Rtrigpin, LOW);
  delayMicroseconds(dt3);
  digitalWrite(Rtrigpin, HIGH);
  delayMicroseconds(dt4);
  digitalWrite(Rtrigpin, LOW);
  Rduration=pulseIn(Rechopin, HIGH);
  Rdistance=Rduration / 58.2;
  return Rdistance;
}

//normal position of servo
void normalp() {
  if (L >= normal & R >= normal) {
    servo.write(90);
    //goto
    loop();
  }
}

void value1() {
  if ((L < minn) >= 2 & (R < minn) >= 2) {
    int ran = random(2);
    if (ran == 0) {
      servo.write(30);
      //goto
      loop();
    }
    if (ran == 1) {
      servo.write(150);
      //goto
      loop();
    }
  }
}

void value2() {
  /* I'm using L !> normal to make sure it doesn't run when L is greater than 750, and this is where the problem comes */
  if ((L < R) >= 6 & L !> normal) {
    servo.write(120);
    //goto
    loop();
  }
}

void value3() {
  /* I'm using R !> normal to make sure it doesn't run when R is greater than 750, this is also where the problem comes */
  if ((R < L) >= 6 & R !> normal) {
    servo.write(60);
    //goto
    loop();
  }
}
```

  [1]: https://wokwi.com/projects/352784217989806081

body:
Use `<=` instead of `!>`; the latter is not proper C++ syntax.

Also, `if (L < R) >= 6` doesn't do what you may think: `(L < R)` evaluates to `true` or `false`, so the whole expression will always evaluate to `false`. Did you mean `if (L - R) >= 6` maybe?

Also, you use `&` as an "and" in your `if` statements, which should be `&&`.


message:
how to transfer json to string?

I am getting a json object from aws iot MQTT. Assuming that json from aws is {status:opened}.
Here is my code.
```
#include <ArduinoJson.h>
void messageHandler(char *topic, byte *payload, unsigned int length)
{
  StaticJsonDocument<32> doc;
  deserializeJson(doc, payload);
  const char *status = doc["status"];
  Serial.println(status);//opened
  if (status == "opened")
  {
    Serial.println("door is opened");//not excute
  }
  else if (status == "closed")
  {
    Serial.println("door is closed");
  }
}
```
Why the if condition is not being excute?

body:
That's one of the peculiarities of the C language: the `==` operator compares the string addresses, not their content. It makes sense when you think of them as pointers, but it can be confusing for beginners.

To fix this, you can use `strcmp()` like so:

`if (strcmp(status,"opened") == 0)`

Alternatively, you can change the type of `status` to `JsonVariant`, like so:

`JsonVariant status = doc["status"]`

It works with `JsonVariant` because I overloaded the `==` operator to support string comparison.


message:
Alternate full speed usb library for ATTINY85?

I'm currently working on a project using the ATTINY85 for USB communication. After some research, it turns out that the V-USB library only supports usb 1.1, which only supports a 125hz polling rate. I would like to be able to have a polling rate of 1000hz, or close to it, which requires usb 2.0 or faster. I was hoping that someone could help point me to a library which supports usb 2.0, or suggest an alternative. Any help would be greatly appreciated, thanks in advance!

body:
Since an ATtiny85 has no built-in USB hardware module, you use a software solution like V-USB. Unfortunately bit-banging software cannot be as fast as hardware, so you are out of luck here. (Reading the documentation of V-USB is enlightened and explains the difficulties and limits of such a solution.)

You cannot have USB 2.0 with an ATtiny85 alone.

Possible solutions:
- an external USB module
- another microcontroller


message:
Rotary encoder weird values

I am trying to understand this rotary encoder I have, but it makes no sense to me.

I am using this rotary encoder:
https://www.amazon.com/gp/product/B07DM2YMT4/

CYT1100 aka CY110 aka EC11

I am using this wiring:
https://i.stack.imgur.com/aMyR5.png

P2 is the "push button" and it gives continuity when pressed.

I am using a knock off arduino nano and this is my simple script:

    #define PIN_CLK 2

    void setup()
    {
     Serial.begin(9600);
     pinMode(PIN_CLK, INPUT);
    }

    void loop()
    {
     auto val = digitalRead(PIN_CLK);

     Serial.println("CLK:" + String(val));
    }

Where PIN_CLK is connected to A (DW) or B (CLK) in the diagram.

My expectation is that A and B should be either a constant HIGH or LOW depending on where the brushes are internally. Not switching to HIGH or LOW for a moment and then returning to what it was before.

When I check them with my multimeter, they are both always 5v (when its not making loose contact on the breadboard).

The serial plotter says its switching between HIGH and LOW repeated:

https://i.stack.imgur.com/6VC3z.png

Same with the Serial monitor:

https://i.stack.imgur.com/wAk0v.png

When I spin the encoder, it gives me gaps of LOW in the output like this:

https://i.stack.imgur.com/lOUmx.png

If I hold my index and thumb against P1 (5v) and A (CLK) while spinning the encoder. I get constant stream of HIGH with a LOW on every notch spin:

https://i.stack.imgur.com/CzUwV.png

Can someone explain this behavior and how this encoder is suppose to work?

Edit: I tried this schematic:

https://i.stack.imgur.com/Mlj1l.png

Whenever I turn the encoder. The LED blinks for a few milliseconds. Then turns off.

Is it suppose to stay solid depending on the 2 bit states?

Edit2: If I turn it extremely slowly. It turns the leds on in the order of left right or right left depending on the direction.

So the led diagram above works, but its weird to me.

body:
There are several problems happening here. Since your code only covers one input pin, I'm going to talk about input A. This pin is left floating! When you turn the dial, the brush connects A and/or B to G in your photo, or in other words, pins A/B to ground. But if A/B is not connected to ground, there is no other voltage state - it's just left floating. You need to have a logic LOW 0V and a logic HIGH (either 3.3V or 5V depending on your Arduino board) for the Arduino to be able to distinguish between the LOW and HIGH states. You can solve this by changing your code to:

    pinMode(PIN_CLK, INPUT_PULLUP);

This way when the pin (A) is not connected to GND via (G), it is held at a logic HIGH state.

P1 & P2 are the for the button, so you can't ignore one of the pins. To wire that correctly using an input pullup, P1 needs to connect to GND. P2 needs to connect to an input pin with another ```input_pullup```. When the button is unpressed, the state will default to HIGH. When it's pressed, it will be connected to GND and show as LOW.

You are most likely following the images online for wiring the encoders that **are already on a PCB**. That PCB has 3 pullup resistors on it. Regardless if you are using code to do it or hardware, the circuit needs to look like this. ```input_pullup``` on the Arduino will act just like resistors shown in the circuit.

Here is a great resource: https://lastminuteengineers.com/rotary-encoder-arduino-tutorial/

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

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


body:
When encountering weird values from a [rotary encoder][1], there are a few possible reasons and troubleshooting steps you can take:

**Mechanical issues:** Check if there is any physical damage or obstruction affecting the rotary encoder's movement. Ensure that it rotates smoothly without any unusual resistance or skips.

**Loose connections:** Verify the wiring connections between the rotary encoder and the device it is connected to. Ensure that the connections are secure and properly seated.

**Electrical noise:** Electrical noise or interference can sometimes cause erratic readings. Try using shielded cables for the connections and consider adding capacitors or ferrite beads to filter out noise.

**Incorrect configuration:** Review the setup and configuration of the rotary encoder in your code or software. Make sure that you have selected the correct type of encoder (incremental or absolute) and that the signal processing is correctly implemented.

**Debouncing:** If you are using an incremental rotary encoder, it may produce multiple pulses or bouncing signals when rotating. Implementing debouncing techniques in your code can help filter out these erroneous readings.

**Resolution and speed settings:** Check if the resolution and speed settings in your code or software match the specifications of your rotary encoder. Incorrect settings can lead to unexpected values.

**Compatibility issues:** Ensure that the rotary encoder you are using is compatible with the device or system you are connecting it to. Check the specifications and requirements of both the encoder and the device to ensure compatibility.

If you have gone through these troubleshooting steps and are still experiencing weird values from your rotary encoder, it might be worth considering a replacement or consulting the manufacturer's support for further assistance.

  [1]: https://indmall.in/rotary-encoders-with-arduino/


message:
Making library for arduino

I'm learning library making on arduino , I want to make a library that works with arrays a user sets, e.g:

User sets array of int,
when  a certain function is been called the library will check if some instance are true or not ann set the return function accordingly as the array.

Code example:

```

    //in project example

#include <Keyss.h>

int rows=4;
int cols=2;
int a=0;
int b=1;
int c=2;
int inp=3;
int keyss[4][2]={
{0,1},,
{2,3},
{4,5},
{6,7}
};

Key key((keyss),rows,cols,inp,a,b,c);

void setup(){
Serial.begin(9600);
int keyprint=key.getkey();
Serial.println(key print);
}
void loop(){
}

```

And this will be the library files
Keys.h

```

#ifndef KEYSS_H
#define KEYSS_H
#include <Arduino.h>

class Key {

public:

Key(int (*keys)[4],int rows,int cols,int inp,int t1,int t2,int t3);
int getkey();
int waitforkey();

private:

int *_keys;
int _rows;
int _cols;
int _inp;
int _t1;
int _t2;
int _t3;

};

#endif

```

And
Keys.CPP

```

#include <Keyss.h>

//initialization

Key::Key(int (*keys)[4],int rows,int cols,int inp,int t1,int t2,int t3){

 _keys=keys[4];
 _rows=rows;
 _cols=cols;
 _inp=inp;
 _t1=t1;
 _t2=t2;
 _t3=t3;

 pinMode(_inp,INPUT);
 pinMode(_t1,OUTPUT);
 pinMode(_t2,OUTPUT);
 pinMode(_t3,OUTPUT);

}

//getkey()

int Key::getkey(){

int _a;
int _b;
int _i=0;
int _keymap=false;
int _val;
int _dt=500;
int _s1;
int _input;

for(_a=0;_a<_rows;_a++){

 for(_b=0;_b<_cols;_b++){

  _s1=_i;
  digitalWrite(_t1,(_s1>>0)&1);
  digitalWrite(_t2,(_s1>>1)&1);
  digitalWrite(_t3,(_s1>>2)&1);
  delayMicroseconds(_dt);

  _input=digitalRead(_inp);

  if(_input==true && _keymap==false){

   _val=_keys[_a*_cols+_b];
   _keymap=true;
}

  _i++;

}
}

if(_keymap==false){
   _val=-1;
}

return _val;

}

//waitforkey()

int Key::waitforkey(){

int _waitfor=getkey();

while(_waitfor<0){

_waitfor=getkey();

}

return _waitfor;

}

```

Where I have problem now is I don't know how to
use or assign an array in a library
I don't know how to use functions to refer to an array a user inputes, like here

```
int keyss[4][2]={
{0,1},
{2,3},
{4,5},
{6,7}
};
```
How do I use a function or inside the library to refer to the array a user sets?

Please how do I achieve that?

Its giving this error
[![error message][1]][1]

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

body:
Your `keys` variable is a 2D array of `int`, i.e. it is an array of
arrays. In C++, when an array is assigned to a variable or passed as an
argument, it implicitly decays to a pointer to its first element.
Note, however, that the decay-to-pointer behavior is not recursive.
In this case you end up with a pointer to an array of three `int`.

Your code should work if you give the proper type to the `_keys` class
member and the `keys` constructor parameter:

```c++
class Key {
public:
    Key(int (*keys)[3], int trig1, int trig2, int trig3, int inpin);
    int getkey();

private:
    int (*_keys)[3];  // pointer to array of 3 int.
    int _trig1;
    int _trig2;
    int _trig3;
    int _inpin;
    int _keye;
};
```

------------------------------------------------------------------------

**Edit**: You have completely changed the question, to the point that my
answer may not be relevant anymore. In the previous version of the
question, it looked like you wanted to use a 3×3 2D array of numbers in
the class. In the current version, you are using an array of arbitrary
sizes represented as a flattened 1D array. These are quite different
approaches.

If you want to use a 2D array, the number of _columns_ has to be a
compile-time constant. You have to declare the member variable as a
pointer-to-array like this:

```c++
int (*_keys)[2];  // there are two columns, not four!
```

assign it like this:

```c++
_keys = keys;  // do NOT subscript keys
```

and use it like this:

```c++
_val = _keys[_a][_b];  // it is a 2D array
```

This approach cannot work if you do not know the number of columns
beforehand.

If you want to use a flattened (1D) array, then the parameter of the
constructor has to be a simple `int*`, and you have to give it the
address of the first element of the original 2D array:

```c++
Key key(&keyss[0][0], rows, cols, inp, a, b, c);
```

The drawback of using a flattened array is that, in order to access the
elements, you have to perform explicit index calculations:

```c++
_val = _keys[_a*_cols + _b];
```


message:
How to trigger a function by detecting voltage change?

```
#define monitor_pin 14

void setup()
{
  pinMode(monitor_pin , INPUT);
}

void loop()
{
    unsigned long d1 = pulseIn(14, HIGH);
    if (d1>0){//trigger function}
}

```
I know there is a function pulseIn(), but it doesnt really solve my problem. I just want to trigger a function when voltage change from LOW to HIGH/HIGH to LOW. pulseIn() need to wait for the voltage to back to original level which in my case will exceed 3 minutes and cause timeout.

How can  I detect a voltage change other than pulseIn()?

body:
You can save the previous state of the pin and then trigger the function when the current state is different from the previous state:

    #define monitor_pin 14
    int previous_state;

    void setup()
    {
      pinMode(monitor_pin , INPUT);
      previous_state = digitalRead(monitor_pin); // Initialize previous state with initial reading of the pin
    }

    void loop()
    {
      int current_state = digitalRead(monitor_pin);
      if(current_state != previous_state){
        // Execute your code here
        previous_state = current_state; // update previous state
      }
    }


message:
Is it possible to program an AVR chip (atmega328p) via i2c?

Currently I am using `avrdude` and I'm programming my `atmega328p` chip via the `spi` pins by pulling the RESET pin low (spidev programmer).

In my project I'm using predominantly `i2c` and this the only place where `spi` is used. I was wondering whether it is possible to program the chip via the `i2c` protocol and remove the `spi` connections altogether?

My searches were unsuccessful.

body:
From section 27.2(*) of the Atmega328xx data sheet (emphasis mine):

> In ATmega88A/88PA/168A/168PA/328/328P the Boot Loader Support provides
> a real Read-While-Write Self- Programming mechanism for downloading
> and uploading program code by the MCU itself. This feature allows
> flexible application software updates controlled by the MCU using a
> Flash-resident Boot Loader program. **The Boot Loader program can use
> any available data interface and associated protocol to read code and
> write (program) that code into the Flash memory,** or read the code from
> the program memory. The program code within the Boot Loader section
> has the capability to write into the entire Flash, including the Boot
> Loader memory. The Boot Loader can thus even modify itself, and it can
> also erase itself from the code if the feature is not needed anymore.
> The size of the Boot Loader memory is configurable with fuses and the
> Boot Loader has two separate sets of Boot Lock bits which can be set
> independently. This gives the user a unique flexibility to select
> different levels of protection.

You may need to re-write the input section of the bootloader, but it sure sounds like Atmel intended it to be doable.

[*] My data-sheet is dated 2018; the relevant section, Section 27, is titled "Boot Loader Support – Read-While-Write Self-Programming", in case a later revision has different section numbers.


body:
Yes, as JRobert pointed out, I have no doubt - it is possible!

You need just 3 things:

 1. a Bootloader that supports uploading the firmware via I2C
 2. an Upload-Software that supports uploading the firmware to the bootloader mentioned in 1.)
 3. an physical connection from the system the upload software is running on to the actual I2C bus of your device

Actually the physical interface is not the problem - there are USB<>I2C interfaces available widely, you can also re-use an arduino itself to be such.

Let's look at the bootloader.

Actually I found a german site that claims having a working [I2C bootloader for Atmega8][1] including an upload tool (use Deepl.com to translate it). It may or may not work for other Atmegas as is.

There is also [another project at github][2].

There will be more if you google for it. Actually I have not investigated any of them.

But chances are good than any of those might work for you.

  [1]: https://old.ethersex.de/index.php/I2C_Bootloader
  [2]: https://github.com/tspspi/ATMega328PBootloaderI2C