body:
This is my first time asking a question so I will try my best to be precise and detailed.

I had recently started to work on a project that requires me to establish a wireless communication between two XBEE Pro S2C modules for the purpose of sending data of the sensors present on the Arduino Nano BLE 33 Sense.

**What I did so far:**
One of the XBEE (XBEE 1) is connected to my laptop using one of the USB-port, and the other (XBEE 2) to Arduino. The Arduino is also connected to the same laptop using another one of the USB ports. Using the [XBEE][1] and [Arduino][2] pinout diagrams, I connected Vcc, Dout, Din and GND of XBEE 2 to 3.3V, D3, D4 and GND pins of the Arduino respectively. Both the XBEES have been configured using XCTU software and are operating in AT mode. The XBEES are able to talk to each other on the XCTU console if I directly plug both of them into the laptop using the USB ports.

To check and establish a serial communication between the XBEE 2 and Arduino, I wrote the following sketch on Arduino IDE and uploaded it:

    int received = 0;
    #include<HardwareSerial.h>
    UART mySerial(digitalPinToPinName(4), digitalPinToPinName(3), NC, NC);
    void setup() {
      mySerial.begin(9600);
      Serial.begin(9600);
    }

    void loop() {
      while(mySerial.available())
      {
        received =mySerial.read();
        if(received == 'a')
        {
          Serial.println("Character Received");
        }
      }
    }

Now, when I type the character 'a' in the XCTU console of XBEE 1, the XBEE 2 is able to receive it wirelessly and Arduino prints - "Character Received", on the serial monitor as expected. The TX of the adapter for XBEE 1 and the RX of the adapter for XBEE 2 also blinks at the same moment, confirming that the character is being sent by the XBEE 1 and it is being received by XBEE 2 for the Arduino to print.

**The Problem:**
Now, I uploaded the following sketch to do the reverse job, so that XBEE 2 sends the data and it appears on the XCTU console of XBEE 1:

    #include<HardwareSerial.h>
    UART mySerial(digitalPinToPinName(4), digitalPinToPinName(3), NC, NC);

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

    void loop() {
      mySerial.print("a");
      delay(1000);
    }

 This sketch does not print anything on the XCTU console of XBEE 1. I checked the connections and re-uploaded the sketch but it still showed nothing. I included the printing line inside a while-loop,

    while(Serial.available()){
       mySerial.print("a");
    }

so that I can manually type in a character into the serial monitor using Arduino IDE, but that also did not work. I also noticed that the respective TX and RX of the adapters also did not blink, meaning that XBEE 2 is not able to transmit the character only.

I cannot figure out what I am doing wrong and I spent hours to resolve this issue. I also tried changing the Din and Dout pins of XBEE 2 to RX and TX pins of the Arduino but that also did not work, although I think that's because the RX and TX are already being used by the Serial Connection between Arduino and laptop.

Any help to point me into the right direction would be greatly appreciated.

Thanks a lot!

*Some points*:
I came to know that SoftwareSerial library isn't available for the version of Arduino that I am using and for this reason I am using the UART instruction:
`UART mySerial(digitalPinToPinName(4), digitalPinToPinName(3), NC, NC);`
based on the discussion [in this forum][3]. I also use CP2012 XBEE explorer as adapters for XBEES.

  [1]: https://microcontrollerslab.com/wp-content/uploads/2020/01/XBee-S2C-RF-Module-Pin-Configuration-diagram.jpg
  [2]: https://www.researchgate.net/publication/358818914/figure/fig1/AS:1133123140104194@1647169017785/Arduino-33-Nano-BLE-Sense-pinout.ppm
  [3]: https://github.com/arduino/ArduinoCore-nRF528x-mbedos/issues/38

title: Arduino Nano BLE 33 Sense receives but not able to transmit data to XBEE Pro S2C

Answers: 0


body:
I am trying to upload an hex file to my arduino pro micro using Avrdude . The thing is that I cannot upload any code using the Avrdude terminal commands , but when I use arduino IDE to upload any code it perfectly uploads the code to Arduino.

**The command I am using on the terminal:**

    avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -patmega32u4 -cavr109 -PCOM15 -b57600 -D -U flash:w:C:\Users\santi\Documents\keyboard\corne\crkbd_rev1_layout_split_3x6_3_mine.hex:i

I already have avrdude on the environment variables on my windows 10 machine.

**Output**:

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM15
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

    avrdude: butterfly_recv(): programmer is not responding

I keep waiting but it does not upload the code.

I added a push button for RST and GND pins to enter bootloader mode, and I am pressing the reset button. I even tried resetting twice quickly, but I get the same result.

I tried using the Arduino and the code gets uploaded.

I uploaded the following code:

    int RXLED = 17;
    void setup(){
      pinMode(RXLED, OUTPUT);
    }

    void loop() {
      digitalWrite(RXLED, LOW);
      delay(1500);
      digitalWrite(RXLED, HIGH);
      delay(1500);
    }

The command ran in the IDE is:

    "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude" "-CC:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf" -v -V -patmega32u4 -cavr109 -PCOM16 -b57600 -D "-Uflash:w:C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex:i"

Arduino IDE output:

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM16
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .
    Found programmer: Id = "CATERIN"; type = S
        Software Version = 1.0; No Hardware Version given.
    Programmer supports auto addr increment.
    Programmer supports buffered memory access with buffersize=128 bytes.

    Programmer supports the following devices:
        Device code: 0x44

    avrdude: devcode selected: 0x44
    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e9587 (probably m32u4)
    avrdude: reading input file "C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex"
    avrdude: writing flash (3852 bytes):

    Writing | ################################################## | 100% 0.29s

    avrdude: 3852 bytes of flash written

    avrdude done.  Thank you.

I tried using the same Avrdude command in the terminal.

    "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude" "-CC:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf" -v -V -patmega32u4 -cavr109 -PCOM16 -b57600 -D "-Uflash:w:C:\Users\santi\AppData\Local\Temp\arduino-sketch-F0563C64AD4C1F392D3E71AA32E4F874/blink_nano.ino.hex:i"

**Output:**

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM16
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
    avrdude: ser_open(): can't open device "\\.\COM16": El sistema no puede encontrar el archivo especificado.

I don´t know why it uses a different port.
I tried changing the port in that command but I get the same result as before

    avrdude: Version 6.3-20190619
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch

             System wide configuration file is "C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

             Using Port                    : COM15
             Using Programmer              : avr109
             Overriding Baud Rate          : 57600
             AVR Part                      : ATmega32U4
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             RESET disposition             : dedicated
             RETRY pulse                   : SCK
             serial program mode           : yes
             parallel program mode         : yes
             Timeout                       : 200
             StabDelay                     : 100
             CmdexeDelay                   : 25
             SyncLoops                     : 32
             ByteDelay                     : 0
             PollIndex                     : 3
             PollValue                     : 0x53
             Memory Detail                 :

                                      Block Poll               Page                       Polled
               Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
               ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
               eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
               flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
               signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

             Programmer Type : butterfly
             Description     : Atmel AppNote AVR109 Boot Loader

    Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

I could just use the arduino IDE to flash my device but the problem is that I only have the hex file. I am trying to flash my device with a hex file from [QMK Configurator][1]. I am trying to build a custom keyboard.

  [1]: https://config.qmk.fm/

title: Unable to flash arduino pro micro from Terminal

Answers: 1

body:
You have to reset the Arduino using a very special procedure in order
for it to accept being programmed. This involves opening the port at
1200 bps, toggling some control lines, and closing the port again.
You may try using this [ard-reset-arduino][] Python script with the
option `--caterina`.

By the way, this script belongs a project called “Arduino-Makefile”. You
may want to take a look if you want to program your Arduino from the
command line. Alternatively, you can use [arduino-cli][].

[ard-reset-arduino]: https://github.com/sudar/Arduino-Makefile/blob/master/bin/ard-reset-arduino
[arduino-cli]: https://arduino.github.io/arduino-cli/


body:
What is the difference between `:i` and `:a` after my hex file path in avrdude command.

    avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM8 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:i

and

    avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a

title: What is the difference between ":i" and ":a" in avrdude command?

Answers: 1

body:
These are Avrdude file format specifiers.

```
avrdude -C C:\Users\santi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -V -pm32u4 -c avr109 -P COM15 -b 57600 -D -U flash:w:\Users\santi\AppData\Local\Temp\arduino-sketch-35CC2EF472BAA882EB5508D7552111AD/blink_RX_Led_ProMicro.ino.hex:a

```

The final `:a` in this case is a format specifier meaning "auto detect; valid for input only, and only if the input is not provided at stdin."

An `:i` in the same position means "Intel Hex"

A complete list can be found here: https://www.nongnu.org/avrdude/user-manual/avrdude_3.html#Option-Descriptions


body:
EDIT: Things I have tried so far:
1. Increasing the baud rate, but this didn't make any difference as it still continued to stop receiving data after random amount of time.

2. I tried testing one sensor and reducing the sketch to something that only prints in a sketch. I can get the sketch to work up to 2 sensors where it prints the results continuously. 3 or 4 sensors and I get the issue mentioned.

Link to the VL53L4CD library: https://github.com/stm32duino/VL53L4CD

Datasheets:

https://cdn-learn.adafruit.com/downloads/pdf/adafruit-vl53l4cd-time-of-flight-distance-sensor.pdf

https://www.st.com/resource/en/datasheet/vl53l4cd.pdf

----------

I'm currently working on a project where I need to measure distances at two different points using distance sensors (I'm currently using VL53L4CD laser distance sensors). However, this project requires a high sampling rate of 100Hz. To achieve this, I have 4 distance sensors arranged into 2 sensor sets. Each sensor set consists of 2 distance sensors (So for example, sensor set 1 consists of distance sensor 2&3 and sensor set 2 consists of distance sensor 1&4) and I would alternate between reading each sensor set.

This seemed to work at first, I did get a new distance reading every 8ms. However, the serial port stops receiving the distance readings after a very random amount of time. Sometimes the serial port stops receiving new data after 5 seconds, sometimes 30s, sometimes 60 and even 180s.

I'm not sure what's causing this issue what I can do to fix it. Any help is appreciated
(I'm using the Arduino Nano 33 IOT)

Thanks!

Here is my code below:
```
// Included libraries
#include <Arduino.h>
#include <Wire.h>

// Libraries required for VL53L4CD sensors
#include <vl53l4cd_class.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
#include <stdlib.h>

// Definitions
#define DEV_I2C Wire
#define SerialPort Serial

// variables
int alternate = 0; // Variable used to alternate between sensor sets

// Components.
VL53L4CD sensor_vl53l4cd_1(&DEV_I2C, 2); // xshut pin of distance sensor 1 connected to pin 2
VL53L4CD sensor_vl53l4cd_2(&DEV_I2C, 3); // xshut pin of distance sensor 2 connected to pin 3
VL53L4CD sensor_vl53l4cd_3(&DEV_I2C, 5); // xshut pin of distance sensor 3 connected to pin 5
VL53L4CD sensor_vl53l4cd_4(&DEV_I2C, 6); // xshut pin of distance sensor 4 connected to pin 6

/* Setup ---------------------------------------------------------------------*/

void setup()
{
  // DISTANCE SENSOR SETUP
  // Initialize serial for output.
  SerialPort.begin(9600);
  SerialPort.println("Starting...");

  // Initialize I2C bus.
  DEV_I2C.begin();

  // Configure VL53L4CD number 1
  Serial.println("Configuring distance sensor 1");
  sensor_vl53l4cd_1.begin();
  sensor_vl53l4cd_1.VL53L4CD_Off();
  sensor_vl53l4cd_1.InitSensor();
  sensor_vl53l4cd_1.VL53L4CD_SetI2CAddress(0x40);
  sensor_vl53l4cd_1.VL53L4CD_SetRangeTiming(10, 0);

  // Configure VL53L4CD number 2
  Serial.println("Configuring distance sensor 2");
  sensor_vl53l4cd_2.begin();
  sensor_vl53l4cd_2.VL53L4CD_Off();
  sensor_vl53l4cd_2.InitSensor();
  sensor_vl53l4cd_2.VL53L4CD_SetI2CAddress(0x42);
  sensor_vl53l4cd_2.VL53L4CD_SetRangeTiming(10, 0);

  // Configure VL53L4CD number 3
  Serial.println("Configuring distance sensor 3");
  sensor_vl53l4cd_3.begin();
  sensor_vl53l4cd_3.VL53L4CD_Off();
  sensor_vl53l4cd_3.InitSensor();
  sensor_vl53l4cd_3.VL53L4CD_SetI2CAddress(0x44);
  sensor_vl53l4cd_3.VL53L4CD_SetRangeTiming(10, 0);

  // Configure VL53L4CD number 4
  Serial.println("Configuring distance sensor 4");
  sensor_vl53l4cd_4.begin();
  sensor_vl53l4cd_4.VL53L4CD_Off();
  sensor_vl53l4cd_4.InitSensor();
  sensor_vl53l4cd_4.VL53L4CD_SetI2CAddress(0x46);
  sensor_vl53l4cd_4.VL53L4CD_SetRangeTiming(10, 0);

  // Start Measurements
  sensor_vl53l4cd_1.VL53L4CD_StartRanging();
  sensor_vl53l4cd_2.VL53L4CD_StartRanging();
  sensor_vl53l4cd_3.VL53L4CD_StartRanging();
  sensor_vl53l4cd_4.VL53L4CD_StartRanging();
}

void loop()
{
  // Read results from sensor set 1
  if (alternate == 0){
    VL53L4CD_Result_t results2;
    VL53L4CD_Result_t results3;

    // Read results from sensor set 1 (Sensors 2 and 3)
    sensor_vl53l4cd_2.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_2.VL53L4CD_GetResult(&results2);
    sensor_vl53l4cd_3.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_3.VL53L4CD_GetResult(&results3);

    Serial.print("Distance 1-1 = ");
    Serial.print(results2.distance_mm);
    Serial.println(" ");
    Serial.print("Distance 1-2 = ");
    Serial.print(results3.distance_mm);
    Serial.println(" ");

    alternate = 1; // Change value so sensor set 2 is read in the following loop
  }

  // Read results from sensor set 2
  else if (alternate == 1){
    VL53L4CD_Result_t results1;
    VL53L4CD_Result_t results4;

    // Read results from sensor set 1 (Sensors 1 and 4)
    sensor_vl53l4cd_1.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_1.VL53L4CD_GetResult(&results1);
    sensor_vl53l4cd_4.VL53L4CD_ClearInterrupt();
    sensor_vl53l4cd_4.VL53L4CD_GetResult(&results4);

    Serial.print("Distance 2-1 = ");
    Serial.print(results1.distance_mm);
    Serial.println(" ");
    Serial.print("Distance 2-2 = ");
    Serial.print(results4.distance_mm);
    Serial.println(" ");

    alternate = 0; // Change value so sensor set 2 is read in the following loop
   }
   Serial.println(millis());
}
```

title: Serial port stops receiving data after random amount of time

Answers: 1

body: I tried powering all of the sensors with an external power source and this seems to solve the issue, I got consistent readings from all the distance sensors and the serial port did not stop receiving data. It might have been the USB port on my laptop that was causing these issues.


body:
i am newbie to this so i hope i can explain my problem clearly;

Arduino MEGA connected to PC via USB port.

I am using an encoder to trigger function to send data to pc, data is a simple string "A01" or "A02" when i turn encoder to opposite direction, when arduino sends that string to serial port PC answers with another string from serial and its something like "MCPHDGxxx" and arduino does if serial available gets the string and filter it to get and show that number on my 7-segment display.
(xxx is a number between 000 and 359, and that number changes on PC screen when arduino send "A01" or "A02" string to PC)

When i don't send display data from PC to arduino, encoder function works as intended, changes numbers up and down rapidly on PC screen but when i try to send that "number" data to Arduino from serial port number on the PC screen changes so slowly like 1 point up/down per 2 sec even if i turn encoder continuously. Seems like receiving data from PC blocking my send data function until it's done.

Is it possible to make it work asynchronously?

Here is my sketch:

    #include "DigitLedDisplay.h"
     #define outputA 24
     #define outputB 25

     int aState;
     int aLastState;
     unsigned long lastButtonPress = 0;
     long finalMCPHDGLong;
     String ReceivedSerialString;

     DigitLedDisplay ld = DigitLedDisplay(21, 22, 23);

     void setup() {
       pinMode (outputA,INPUT);
       pinMode (outputB,INPUT);

       Serial.begin (115200);
       // Reads the initial state of the outputA
       aLastState = digitalRead(outputA);

         /* Set the brightness min:1, max:15 */
      ld.setBright(10);

      /* Set the digit count */
      ld.setDigitLimit(8);

     }

     void loop() {
       aState = digitalRead(outputA); // Reads the "current" state of the outputA
       // If the previous and the current state of the outputA are different, that means a Pulse has occured
       if (aState != aLastState){
         // If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
         if (digitalRead(outputB) != aState) {
           if (millis() - lastButtonPress > 25) {
             Serial.println("A01");
      }

      // Remember last button press event
      lastButtonPress = millis();

         } else {
           if (millis() - lastButtonPress > 25) {
             Serial.println("A02");
      }

      // Remember last button press event
        lastButtonPress = millis();

         }

       }
       aLastState = aState;

        while (Serial.available() > 0){
          ReceivedSerialString = Serial.readString();
          if (ReceivedSerialString.substring(0,6) == "MCPHDG"){
            String value = ReceivedSerialString.substring(6,9);
              long val = value.toInt();
              finalMCPHDGLong = val;
              if((finalMCPHDGLong <= 99)){
                  ld.printDigit(0,7);
                }if((finalMCPHDGLong <= 9)){
                  ld.printDigit(0,6);
                }
              ld.printDigit(val, 5);
          }
        }
     }

title: Arduino MEGA - How to send and receive data asynchronously?

Answers: 2

body:
Is not easy, but you can implement two modification.

The first one is handling encoder via interrupt, the second one, is change the while to an if, with the while you force the code to loop inside the while serial aviable loosing eventually encoders state change, to avoid this, you shuold take continusly the strings coming from PC and create a command queue and proces it cycle by cicle, unfortunatly arduino mega is single processor, so it can't handle different process at the same time.

You should olso to consider, and run a benckmark to test how much is the refresh rate of your display

body:
> Seems like receiving data from PC blocking my send data function until it's done.

You may be saying the same thing, but I'd put it that it's waiting for more data to arrive that isn't going to.

> Is it possible to make it work asynchronously?

Depending on how you're defining "asynchronously" that may be unnecessary.

```c++
while (Serial.available() > 0){
  if (ReceivedSerialString.substring(0,6) == "MCPHDG"){
    String value = ReceivedSerialString.substring(6,9);
```

There's a lot that could be said about using `String` and conversion to `int` and choosing a simple message format and so forth, but I'll elide most of that. Finding a good approach to what you're doing would require understanding a lot more about what you're doing and why. But, taking your code and question as written, the **main thing is that `readString()` here is terminating based on the value of `Serial.setTimeout()`, which by default is `1000` or 1 second.  So you are spending a lot of time doing nothing following receipt of your command from the PC. So during that 1 second you are not tending to the "encoder".**

You could play with `setTimeout`, but it would be better to avoid a timeout altogether by not attempting to read when there's no more command to be read. If this protocol you're using is line-oriented then you have a terminator you can use in the form of '\r' or '\n'. This can be done with `Serial.readStringUntil(whatever_your_terminator_is);` If you have both '\r' and '\n' you will need to read other part of the termination sequence and then throw it away. Either it will come in as part of the read string or it will not and you will need to do a second read to discard it. There are more sophisticated ways to go about this, but that maybe sufficient for what you're doing.

When it comes to not blocking (or significant blocking) of serial reads, you have to assure that the data is there to be read. Either because you know it's sent (and are willing to trust that it was received okay). Or you use `Serial.setTimeout` with a 0 or sufficiently small number, `.read()` indicates no data with a negative return value, or by checking `.available()`, and it all of these cases deciding what to do when you have not received everything, or everything... yet. Doing it well, manually, is a bit of a pain.

For writing/printing to serial there's a counterpart `.availableForWrite()` which
you can use to determine ahead of time whether or not you're going to be stuck in waiting (in `.print()`/`.println()`/`.write()`) for the serial data to go out, in turn not tending to the encoder. Basically you can choose where and how to throttle your writing to serial so as not overly interfere checking the encoder rather than causing throttle to happen within `Serial.write`. With the way your code is currently written, with events coming in at the rate they apparently are (according to your debouncing code) this is probably not currently a problem for you. But it's worth keeping in mind if you begin handling events at a higher rate. Placing a character in the outbound serial buffer is significantly faster than waiting for space for a character to become available in the serial buffer.


body:
I was hoping someone might be able to help me with a project I'm working on. The general set-up is as follows:

I have an ESP32 hosting a WiFi server and publishing data from a bunch of sensors.

    // Includes
    #include <WiFi.h>
    #include <ESPAsyncWebServer.h>

    /* Global Definitions */

    // DEBUG TOOLS
    #define debug true

    // Define server variables
    const char* _SSID = "**********" ;
    const char* _PASSWORD = "**********" ;

    // Create server instance
    AsyncWebServer server(80) ;

    void setup() {

      Serial.begin(115200) ; // Open Serial comms line at 115200 BAUD
      delay(1000) ; // Delay to ensure serial connection
      Serial.println("\n") ;

      DefineServer() ; // Defines server information

      Serial.println("***** START-UP COMPLETE *****") ;

      RuntimeProcess() ; // Process on request from server

      server.begin() ;
      Serial.println("Server Online.") ;
    }

    void loop() {}

DefineServer function:

    void DefineServer() {
      // Function to create a WiFi server with predefined SSID and Password
      // Setting the ESP as an access point
      Serial.println("Setting AP (Access Point)…") ;
      WiFi.softAP(_SSID, _PASSWORD) ;
      IPAddress IP = WiFi.softAPIP() ;
      Serial.println("AP created successfully.") ;

      if (debug) { // Prints Access Point IP address
        Serial.print("IP address: ") ;
        Serial.println(IP) ;
      }
    }

RuntimeProcess function:

    void RuntimeProcess() {
      // Defines the actions to be taken upon recieving and server  request.
      server.on("/grip" , HTTP_GET , [](AsyncWebServerRequest *request) {
        String grips = GetSensorData() ;
        request -> send_P(200, "text/plain" , grips.c_str()) ;
      } ) ;
    }

Then I have an ESP32 as a client requesting the sensor data every 5ms, and a computer client running a Python script that does the same.

ESP client request function:

    String RequestFrom(const char* serverName) {
      HTTPClient http;
      WiFiClient wifi ;

      // Your IP address with path or Domain name with URL path
      http.begin(wifi, serverName);
      http.setReuse( true ) ;

      // Send HTTP POST request
      int httpResponseCode = http.GET();
      String payload = "--";

      if (httpResponseCode > 0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        payload = http.getString();
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();

      return payload;
    }

It works well enough most of the time but occassionally either one of the clients will hang for a couple of seconds and not update for a while without throwing any errors.

The server is still active as the other client is usually fine and recieving up-to-date data.

I have a couple of theories such as it hangs when both clients attempt to request at the same time (though full disclosure, I'm very new to working with this sort of thing). I've tried changing the request frequency of the two clients to try and avoid simultanious requests but I have no way of fixing the start time for the scripts on both to be the same. I was hoping someone with a bit more knowledge might be able to either tell me I'm being ridiculous, or ideally be able to point me in the right direction for a work around like building a request queue.

Apologies for the codeblock spam,
Cheers!

Alex

title: ESP32 Async Web Server hanging / queue

Answers: 0


body:
#### Error

```txt
Arduino: 1.8.19 (Windows 10), Board: "Arduino Uno"

AnalogInOutSerial:8:56: error: no matching function for call to 'PID::PID(int*, int*, double*, double&, double&, double&, int)'
 PID pid(&Rawval, &Rawval, &setpoint, kp, ki, kd, DIRECT);
                                                        ^
In file included from C:\Users\USER\AppData\Local\Temp\arduino_modified_sketch_407168\AnalogInOutSerial.ino:1:0:
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:24:5: note: candidate: PID::PID(double*, double*, double*, double, double, double, int)
     PID(double*, double*, double*,        // * constructor.  links the PID to the Input, Output, and
     ^~~
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:24:5: note:   no known conversion for argument 1 from 'int*' to 'double*'
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:20:5: note: candidate: PID::PID(double*, double*, double*, double, double, double, int, int)
     PID(double*, double*, double*,        // * constructor.  links the PID to the Input, Output, and
     ^~~
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:20:5: note:   candidate expects 8 arguments, 7 provided
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note: candidate: constexpr PID::PID(const PID&)
 class PID
       ^~~
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note:   candidate expects 1 argument, 7 provided
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note: candidate: constexpr PID::PID(PID&&)
C:\Users\USER\Documents\Arduino\libraries\Arduino-PID-Library-master/PID_v1.h:5:7: note:   candidate expects 1 argument, 7 provided
exit status 1
no matching function for call to 'PID::PID(int*, int*, double*, double&, double&, double&, int)'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
```

#### Actual Code

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

int analogPin = A3;
int Rawval ;  // variable to store the value read
double setpoint = 169; // target value for the system is set to 169
double kp = 1, ki = 0.1, kd = 0.01; // PID constants
int RELAY_pin = 10;    // Relay is connected to pin D10
PID pid(&Rawval, &Rawval, &setpoint, kp, ki, kd, DIRECT);

void setup()
{
  Serial.begin(9600);           //  setup serial
  pinMode(RELAY_pin, OUTPUT);
  pid.SetMode(AUTOMATIC);
}

void loop()
{
  Rawval = analogRead(analogPin);
  Serial.print("Rawvalue from Analog input  =");
  Serial.println(Rawval);
  pid.Compute();
  digitalWrite(RELAY_pin, Rawval < setpoint ? HIGH : LOW);
}
```

title: Error coming from specified code

Answers: 2

body:
The first two parameters need to be of type double.

    PID pid(&Rawval, &Rawval, &setpoint, kp, ki, kd, DIRECT);
            ^^^^^^^  ^^^^^^^

It also makes probably no sense to have input and output both wired to &Rawval.

Take a look [on this example.](https://arduino.stackexchange.com/q/24652/87849)

body:
The error message is quite clear about the problem (extracted and formatted for clarity):

> no matching function for call to
> `PID::PID(int*, int*, double*, double&, double&, double&, int)`
> _[...]_
> candidate:
> `PID::PID(double*, double*, double*, double, double, double, int)`
> _[...]_
> no known conversion for argument 1 from '`int*`' to '`double*`'
> _[other candidates left out due to non-matching number of arguments]_

You need to provide pointers to `double` as the first two arguments, and the candidate will match.

---

**EDIT:**

I hesitated a while to provide your this, because you learn much better by doing it yourself. Anyway, here it is.

Your original variable declaration is:
```c++
int Rawval ;  // variable to store the value read
```

Replace the data type `int` by `double`, as the called constructor expects:
```c++
double Rawval ;  // variable to store the value read
```

Now there is this line, assigning an `int` to a `double`:
```c++
Rawval = analogRead(analogPin);
```
And you might ask yourself, is this OK? Well, try it. You will find that the compiler implicitly converts the value. If you want to make it explicitly, change the line to:
```c++
Rawval = static_cast<double>(analogRead(analogPin));
```

A final point, as datenheim states: Read and learn about the `PID`. It is for sure an error to use the _same variable_ for input and output.


body:
TL;DR : How to prevent step-skipping with a NEMA gearbox motor at low speed.

I am in the process of creating a system in which I want an object to turn on a plate and to show a letter depending on the angle of the rotation. The object is quite heavy hence the rotation should be quite slow, this is why I took a Planetary Gearbox NEMA Stepper.

My system consists in:
- An Arduino Uno
- [A NEMA Stepper Motor][1]
- [A A4988 Driver][2]
- Some wires
- 2 Iron plates
- [A ball bearing element in between the Iron plates][3]
- Screws to fit everything together.

This is the code I ended up with:

    // Define stepper motor connections and steps per revolution:
    #define dirPin 6
    #define stepPin 7
    #define stepsPerRevolution 5373
    int degree_init = 1;

    int mouvement=0;

    // create a mapping between letters and degrees
    int letterToDegree[33] ;
    int degree;
    // function to map letters to degrees
    int mapLetterToDegree(char letter) {
      if (letter=='.'){
        return letterToDegree[27];
      }
      else if (letter==':'){
        return letterToDegree[28];
      }
      else if (letter=="\'"){
        return letterToDegree[29];
      }
      else if (letter==' '){
        return letterToDegree[30];
      }
      else {
      int letterIndex = letter - 'A'; // get the index of the letter in the alphabet
      return letterToDegree[letterIndex]; // return the degree associated with that letter
      }
    }

    void setup() {
      // Declare pins as output:
      pinMode(stepPin, OUTPUT);
      pinMode(dirPin, OUTPUT);
        Serial.begin(9600);
        for (int i = 0; i < 33; i++){
        letterToDegree[i]= degree_init;
        degree_init=degree_init+10;
      }
    }

    void loop() {
      int p= NULL;
      // Set the spinning direction clockwise:
      digitalWrite(dirPin, HIGH);
      String input= "NOW THE NOW THE AAAAA";
      // loop through the letters
      for (int i = 0; i < input.length(); i++) {
        // get the degree for each letter
        degree = mapLetterToDegree(input[i]);
        Serial.print("Letter: ");
        Serial.print(input[i]);
        Serial.print(" Degrees: ");
        Serial.println(degree);
        // wait for the movement to complete
        delay(1000);

      int p_new= map(degree,0,360,0,5373);
      Serial.print(" position: ");
      Serial.println(p_new);
      if (p!=NULL){
        mouvement=p_new-p;
        p=p_new;
      Serial.print(" mouvement: ");
      Serial.println(mouvement);
      }
      else{
        p = p_new;
      }
      if (mouvement<0){
        digitalWrite(dirPin, LOW);
        mouvement=abs(mouvement);
        Serial.println("change de direction");
      }
      Serial.print(" stepper: ");
      Serial.println(mouvement);

      // Spin the stepper motor 1 revolution slowly:
      for (int i = 0; i < mouvement; i++) {
        // These four lines result in 1 step:
        digitalWrite(stepPin, HIGH);
        delay(20);
        digitalWrite(stepPin, LOW);
        delay(20);
      }

      delay(1000);
      digitalWrite(dirPin, HIGH);
    }
    }

I tried following [this tutorial][4] and it works in broad terms **but sometimes the motor skips steps, especially when changing direction.**

I can't seem to understand how torque works within this system and how to minimise the stress I put on the motor.
My hypothesis is that since the system is at equilibrium and the friction is minimised due to the ball bearing, there should be no need for a lot of power from the motor, and that this motor should suffice.

My hypothesis of why steps are skipped:
- Too high a speed for the motor
- Not enough torque power supplied
- Not good enough electricity supply to the motor.

I am not sure how to go about and test these hypothesis and if those are correct.
I am also having a lot of trouble understanding the relationship between the time delay in the code and the movement of the motor.

Especially this bit:

      for (int i = 0; i < mouvement; i++) {
        // These four lines result in 1 step:
        digitalWrite(stepPin, HIGH);
        delay(20);
        digitalWrite(stepPin, LOW);
        delay(20);
      }

Is it ok to change them as I did? do they need to be symetrical (same delay for high and low)?

I am also looking for an explanation of how to apply acceleration and decceleration algorithms for stepper motor, even though I am not sure it makes sense at this speed.

**My questions are:**
- How to calculate the best speed for such a system and how to implement it?
- Is there need for acceleration/ decceleration?
- Does microstepping makes sense when using a gearbox?
- Are there some obvious flaws in my system/ code that I am missing out?

[![Arduino and Driver][5]][5]
[![stepper and ball bearing plate][6]][6]
[![Behaviour description][7]][7]
[![System description][8]][8]

  [1]: https://www.amazon.de/dp/B077YXF759?psc=1&ref=ppx_yo2ov_dt_b_product_details
  [2]: https://www.amazon.de/dp/B083V59HTB?psc=1&ref=ppx_yo2ov_dt_b_product_details
  [3]: https://www.amazon.de/dp/B0B98YSRQS?psc=1&ref=ppx_yo2ov_dt_b_product_details
  [4]: https://www.makerguides.com/a4988-stepper-motor-driver-arduino-tutorial/
  [5]: https://i.stack.imgur.com/gOyRh.jpg
  [6]: https://i.stack.imgur.com/zpbeT.jpg
  [7]: https://i.stack.imgur.com/r9STh.jpg
  [8]: https://i.stack.imgur.com/p4YUy.jpg

title: Need help figuring out how to organise a system to run a stepper motor at low speed without Steps-skipping

Answers: 1

body:
> How to calculate the best speed for such a system and how to implement it?

There is no one best speed. This depends on your requirements, the motor torque with the supplied power and driver and the rotational inertia of the object on the motor axis. You can measure the rotational inertia and set yourself a value for the acceleration (even if you don't write the program for acceleration, it will accelerate on the first steps), that you want to have. Then you can check, if your motor has enough torque for this.

Speaking about the motor: Check the ratings of the motor. A good supplier should also give you information on how much torque your motor has at specific currents. Then check if your driver can handle the current (these small stick drivers often cannot handle much current, like 1 or 2A max). These drivers also have a small potentiometer on board, which controls the motor current. Your supplier should also provide information on how to set it correctly (by checking the voltage on one of the pins). You can even find information about this online, when you search for your type of driver. Setting this wrong can lead to either an underperforming motor or the motor overheating. So when setting the motor current with the potentiometer, check the motor temperature afterwards while it is running. Every motor has its own temperature rating, but I would suggest not letting it get too hot to touch.

Having done all above you can drive a test for checking motor speeds. Forget about your current code for a while. Just drive the motor with specific speeds, starting from only a few steps per second and going up until you notice the motor skipping. Then you know how fast you can drive the motor in your configuration without skipping and acceleration. If that is fast enough for you, you can just stick to that.

> Is there need for acceleration/ decceleration?

That depends on the above. If the non-skip speed is not fast enough, you can accelerate by gradually increasing the steps per second (aka decreasing the delay between step pulses). To halt at a specific position you then need to decelerate, so you need to plan the movement and control the steps per second accordingly. If you don't want to do that yourself I would suggest using the `AccelStepper` library. There you can set the target speed and the maximum acceleration and the library will then handle the motor for you.

You wrote in a comment, that you tried the `AccelStepper` library and that it didn't help. Though you didn't state how exactly it didn't help and what exactly you tried. Maybe you just didn't use the library correctly.

> Does microstepping makes sense when using a gearbox?

With microstepping you can get a smoother movement, though I doubt, that this is the problem here. Activating microstepping will of course mean, that you need to send more pulses to the driver for the same speed. Just keep that in mind.

> Is it ok to change them as I did? do they need to be symetrical (same delay for high and low)?

The first delay establishes the pulse for the driver. It needs to be big enough, that the driver recognizes the pulse. 20ms is very long for that. If you look at the datasheet of the your driver chip, there should be some information on that. I used a delay of about 50us in the past (so `delayMicroseconds(50)`), though you might even get shorter.

The second delay then handles the time between pulses, aka the speed of the motor. Though keep in mind, that the first delay is also still a constant in that equation. The speed in steps per second would then be `1/(delay1+delay2)` (ignoring the time for the execution of the rest of the code, because only relevant at high speeds).


body:
Device: Laptop, HC-05, Resistor 2.2k and 4.7k, Arduino Uno R3

So im trying to rename and change password of my HC-05. for full detail schematic diagram. Here(the difference is, i also used the STATE Pin from HC-05 then connected it to Pin 9
since according to Instructubles it is used for activating AT Mode): [![enter image description here][1]][1]

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

Now for coding, i got it from Instructables.com and here: https://www.instructables.com/Modify-The-HC-05-Bluetooth-Module-Defaults-Using-A/
or

    #include <SoftwareSerial.h>
    SoftwareSerial BTSerial(10, 11);
    #define Key 9
    void setup()
    {
      pinMode(Key, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
      digitalWrite(Key, HIGH);
      Serial.begin(9600);
      Serial.println("Enter AT commands:");
      BTSerial.begin(38400);  // HC-05 default speed in AT command more
    }

    void loop() {
      // put your main code here, to run repeatedly:
      if(BTSerial.available()){
        Serial.write(BTSerial.read());
      }

      if(Serial.available()){
        BTSerial.write(Serial.read());
      }
    }

The problem: i tried to follow the instructuble's instruction. but it didnt work. then i tried doing my own from what several tutorials i have read:
for the details,
1. i set my circuit and do the necessary wiring as shown in the picture + STATE Pin -> Arduino Pin 9.
2. I then connected my Arduino Uno to my Laptop, the HC-05 is blinking per half second, if you need the detail. Then uploaded the code...then finally, I opened the Serial Monitor(note that my HC-05 is not Paired to any devices in the first place. i "Forgot" them just incase).
3. then go to 9600 Monitor and enter simple command like **AT, AT+NAME? or AT+PSWD?** but nothing appeared in my terminal.
4. i also checked the 38400 monitor and did the same things. nothing happened.
5. then just maaaaybe it was just not showing but actually working, I tried AT+NAME=JULIE trying to rename my HC-05 to JULIE for each Terminal, going back and trying at 9600 then 38400. nothing happened at any Terminal. my HC-05 is still HC-05 name and the LED in my HC-05 are still blinking per half sec.

5. Then a bit annoyed, i then do a try-and-error. i tried to upload the code, then Paired it now, this time with my Phone. Then enter AT Commands in my Bluetooth Terminal App(from Playstore) and try to AT Command there. but still, nothing works.

My HC-05 is working as intended when i used it a simple LED on and off, and Servo using my Phone wirelessly few hours ago. But when i tried to do AT Command codes, nothing appears in my Serial Monitor such as the OK() or other AT Command replies.

so i would like to know where i did go wrong and why i cant use AT Command whether 9600, 38400 or even trying to do AT Command in my Phone's BT Terminal App? if you think i have missed an important details that i should mention, feel free to let me know.

title: Arduino + HC-05 Problem: AT Commands are not working

Answers: 1

body:
Ok, MAYBE I solved it^^ so the thing is, i noticed that my LED is still blinking intense instead of 2 sec light off and on. which means that i am still not in AT Mode.

but the thing is if i followed Instructables and other website tutorial. I SHOULD be able to be in AT Mode. im not exactly sure why im still not in AT Mode. So tried something:

the wiring/circuit is still THE SAME. but add something:
I took another wire, connect the **EN Pin of HC-05** **-> 5V of Arduino**.  since days ago i was trying to do tinker my HC-05 here and there and i remember that i tried to put EN in 5V then it start blinking differently. so i tried the same thing today. then i went back and Forget Paired Device, connect my Arduino to my Laptop, then reupload my code, then go to Serial.Monitor 9600 set **No Ending Line -> Both NL & CR**. then i reenter the AT Commands.

**AT+NAME?** then **AT**,then **AT+PSWD?**
all worked. the AT+Name shows the name of my HC-05, and the AT+PSWD shows the password. so then i decided to finally rename my HC-05.
**AT+NAME=USER_FAIZ** and **AT+PSWD=ARDUINO** individually in the Serial Monitor...and now my HC-05 has different name which is ***USER_FAIZ*** and password which is ***ARDUINO***. i then went to my Phone, scan for bluetooth device and there it is. USER_FAIZ and password is ARDUINO.

^^what im not really sure if it is the solution im searching for. i searched some tutorials again but none of them mention of using EN Pin and most of them use STATE Pin of HC-05.So because of that, i wont "Check" this Answer as maybe this is not the best solution out. maybe just not yet. but it did solve MY problem so it may solve other users problem too so ill add it here to inform.


body:
I have project which 3 esp01 controller and 1 nodemcu 12-E receiver which gives scores.
Trying to read all input freely from controllers but when i use 3 at same time or pressing button too quickly nodemcu seems to halts and doesn't react or get messages.

Is my simple if algorithm is flawed or did i hit a hardware barrier.
I used working button library for single click event in ESP-01

For fundamental setup i used tutorial.
Esp01 Sender
```
#include <Button2.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <espnow.h>
#define RED 2
#define BLUE 0

// REPLACE WITH RECEIVER MAC Address
//Esp8266 80:7D:3A:37:C5:66
uint8_t broadcastAddress[] = {0x80, 0x7D, 0x3A, 0x37, 0xC5, 0x66};

// Set your Board ID (ESP32 Sender #1 = BOARD_ID 1, ESP32 Sender #2 = BOARD_ID 2, etc)
#define BOARD_ID  1

// Structure example to send data
// Must match the receiver structure
typedef struct struct_message {
    int id;
    int x;
    int y;
} struct_message;

// Create a struct_message called test to store variables to be sent
struct_message myData;

  // Init ESP-NOW
Button2 buttonA, buttonB;

unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

// Callback when data is sent
void OnDataSent(uint8_t *mac_addr, uint8_t sendStatus) {
  Serial.print("\r\nLast Packet Send Status: ");
  if (sendStatus == 0){
    Serial.println("Delivery success");
  }
  else{
    Serial.println("Delivery fail");
  }
}

//void begin(byte attachTo, byte buttonMode = INPUT_PULLUP, boolean activeLow  = true);

void setup() {
  // Init Serial Monitor
  Serial.begin(115200);
  //pinMode(2,INPUT_PULLUP);
  //pinMode(0,INPUT_PULLUP);

  buttonA.begin(RED);
  buttonA.setClickHandler(click);

  buttonB.begin(BLUE);
  buttonB.setClickHandler(click);
  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();

  // Init ESP-NOW
  if (esp_now_init() != 0) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }
  // Set ESP-NOW role
  esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);

  // Once ESPNow is successfully init, we will register for Send CB to
  // get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);

  // Register peer
  esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_SLAVE, 1, NULL, 0);

}

void loop() {
  buttonA.loop();
  buttonB.loop();
}
void click(Button2& btn) {
    if (btn == buttonA) {
      myData.id = BOARD_ID;
      myData.x = 1;
      myData.y = 0;
      esp_now_send(0, (uint8_t *) &myData, sizeof(myData));
      Serial.println("A clicked");
    } else if (btn == buttonB) {
      myData.id = BOARD_ID;
      myData.x = 0;
      myData.y = 1;
      esp_now_send(0, (uint8_t *) &myData, sizeof(myData));
      Serial.println("B clicked");
    }
}
```

NodeMCU 12-E Receiver

```
#include <ESP8266WiFi.h>
#include <espnow.h>
#include <Arduino.h>

#define  LED0 D0
#define  LED1 D1
#define  LED2 D2
#define  LED3 D3
#define  LED4 D4
#define  LED5 D5
#define  LED6 D6
#define  LED8 D8
#define  LED7 D7

// Structure example to receive data
// Must match the sender structure
typedef struct struct_message {
    int id;
    int x;
    int y;
} struct_message;

// Create a struct_message called myData
struct_message myData;

// Create a structure to hold the readings from each board
struct_message board1;
struct_message board2;
struct_message board3;

// Create an array with all the structures
struct_message boardsStruct[3] = {board1, board2, board3};

// refree
/*
void ref1(int x, int y){

  if (x == 1 ){
      digitalWrite(LED7, HIGH);
      delay(5);
      digitalWrite(LED7, LOW);
    }
  else  if (y == 1 ){

      digitalWrite(LED8, HIGH);
      delay(5);
      digitalWrite(LED8, LOW);
    }

}

void ref2(int x, int y){

  if (x == 1 ){
      digitalWrite(LED6, HIGH);
      delay(5);
      digitalWrite(LED6, LOW);
    }

  else if (y == 1 ){

      digitalWrite(LED2, HIGH);
      delay(5);
      digitalWrite(LED2, LOW);
    }

}

void ref3(int x, int y){

  if (x == 1){
      digitalWrite(LED0, HIGH);
      delay(5);
      digitalWrite(LED0, LOW);
    }

  else if (y == 1){

      digitalWrite(LED1, HIGH);
      delay(5);
      digitalWrite(LED1, LOW);
    }

}
  */

// Callback function that will be executed when data is received
void OnDataRecv(uint8_t * mac_addr, uint8_t *incomingData, uint8_t len) {
  char macStr[18];
  Serial.print("Packet received from: ");
  snprintf(macStr, sizeof(macStr), "x:x:x:x:x:x",
           mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]);
  Serial.println(macStr);
  memcpy(&myData, incomingData, sizeof(myData));
  Serial.printf("Board ID %u: %u bytes\n", myData.id, len);
  Serial.println(myData.id);

  if (myData.id==1 ){
    ref1(myData.x, myData.y);
  }
  if (myData.id==2 ){
    ref2(myData.x, myData.y);
  }
  if (myData.id==3 ){
    ref3(myData.x, myData.y);
  }

  // Update the structures with the new incoming data
  boardsStruct[myData.id-1].x = myData.x;
  boardsStruct[myData.id-1].y = myData.y;
  boardsStruct[myData.id-1].id = myData.id;
  Serial.printf("x value: %d \n", boardsStruct[myData.id-1].x);
  Serial.printf("y value: %d \n", boardsStruct[myData.id-1].y);
  Serial.printf("id value: %d \n", boardsStruct[myData.id-1].id);
  Serial.println();

}

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED0, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  pinMode(LED5, OUTPUT);
  pinMode(LED6, OUTPUT);
  pinMode(LED7, OUTPUT);
  pinMode(LED8, OUTPUT);

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();

  // Init ESP-NOW
  if (esp_now_init() != 0) {
    Serial.println("Error initializing ESP-NOW");
    return;
  }

  // Once ESPNow is successfully Init, we will register for recv CB to
  // get recv packer info
  esp_now_set_self_role(ESP_NOW_ROLE_SLAVE);
  esp_now_register_recv_cb(OnDataRecv);

}

void loop(){

}
```

title: Esp-now reacting like bloating in Many-to-one setup

Answers: 0


body:
I asked same question on another forum, but i need more opinions and advices.

I wrote a simple Python code and Arduino code.

In my code, the Excel matrix data is loaded into Python,
then converted into a numpy form of matrix data in Python,
and then extracted the values of each element of the matrix converted into numpy.
Each extracted element value is a screw lead value.
These screw lead values are calculated and converted to the number of revolutions of each screw.

These converted screw rotational speed values are now transferred to Arduino using pySerial.
Once the values of the screw revolutions are transmitted to Arduino,
rotate the step motor connected to Arduino by the number of revolutions of the screw.

So here's my Python code.:

```
import csv
import pandas as pd
import numpy as np
import os
import serial
import time

py_serial = serial.Serial(
    port="COM5",
    baudrate=9600
)

Location = 'C:/Users/KIMWONKI'
File = 'excel_example.xlsx'

data_pd = pd.read_excel('C:/Users/KIMWONKI/excel_example.xlsx',
                        header=None, index_col=None, names=None)

data_np = pd.DataFrame.to_numpy(data_pd)

start = 2
pitch = 3
lead = 0

for i, row in enumerate(data_np):
    for j, element in enumerate(row):
        lead = data_np[i][j]
        rotation = lead/(start*pitch)
        reverse_rotation = - rotation
        rotation = round(rotation, 6)
        if rotation > 0:
            print(f'motor rotates in the forward direction at {abs(rotation)} times.')
            rotation = str(rotation)
            py_serial.write(rotation.encode())
            time.sleep(8)
```

And next is my Arduino code.:

```
int DIRM=8;
int PULM=9;
int DIRP=10;
int PULP=11;
float rot_number = 0;
float sig;

void setup() {

  Serial.begin(9600);
  pinMode (DIRM, OUTPUT);
  pinMode (PULM, OUTPUT);
  pinMode (DIRP, OUTPUT);
  pinMode (PULP, OUTPUT);
}

void loop() {
  while(Serial.available()){
    sig = Serial.parseFloat(); // sig is rotation number inputted from python
    if(sig > 0){
      rot_number = sig; // rotation number
      rotate_CW(rot_number);
      delay(1000);
      rot_number = 0;
      break;
    }
    else if(sig < 0){
      rot_number = sig;
      rot_number = abs(rot_number);
      rotate_CCW(rot_number);
      delay(1000);
      rot_number=0;
      break;
    }
    else{
      break;
    }
  }
}

void rotate_CW(float rotation_number)
{
  int numberOfRounds = int (rotation_number * 4000);

  for (int i = 0; i < numberOfRounds; i++){
    digitalWrite(DIRM,LOW);
    digitalWrite(DIRP,HIGH);
    digitalWrite(PULP,HIGH);
    digitalWrite(PULM,LOW);
    delayMicroseconds(100);
    digitalWrite(PULP,LOW);
    delayMicroseconds(100);
  }
}

void rotate_CCW(float rotation_number) // reverse rotation function
{
  int numberOfRounds = int (rotation_number * 4000);

  for (int i = 0; i < numberOfRounds; i++){
    digitalWrite(DIRM,HIGH);
    digitalWrite(DIRP,LOW);
    digitalWrite(PULP,HIGH);
    digitalWrite(PULM,LOW);
    delayMicroseconds(100);
    digitalWrite(PULP,LOW);
    delayMicroseconds(100);
  }
}
```

I connected four input/output cables attached to the step motor driver to Arduino. I wrote the code accordingly. DIRM stands for DIR-pin and DIRP stands for DIR+pin PULM means PUL-pin and PULP means PUL+ pin.

I first connected the Arduino Uno board, ran the Arduino code, and then ran the Python code.

Here is the terminal output appears in the Python program.:

```
motor rotates in the forward direction at 0.5 times.
motor rotates in the forward direction at 1.166667 times.
motor rotates in the forward direction at 1.333333 times.
motor rotates in the forward direction at 1.5 times.
motor rotates in the forward direction at 0.833333 times.
motor rotates in the forward direction at 0.666667 times.
motor rotates in the forward direction at 1.333333 times.
motor rotates in the forward direction at 1.333333 times.
motor rotates in the forward direction at 0.666667 times.
motor rotates in the forward direction at 0.333333 times.
motor rotates in the forward direction at 1.666667 times.
```

When using the Arduino Uno board, the motor actually 'rotated' to match the output of this terminal, with 0.5 turns, 1.166667 turns, 1.333333 turns, etc.

But now **I changed the board from Arduino Unoboard to Mega Board, and the motor didn't work.**

It's not like there was an error message in particular, or the code didn't execute at all. Only the output message came from the above terminal output window, and the motor did not rotate.

I checked where the problem occurred. Through the serial monitor of the Arduino IDE, I directly entered the screw revolution value into the Arduino code and found that the motor rotated normally regardless of whether it was using the Arduino Uno board or the Arduino Mega board.

However, the attempt to run Python and transfer the screw revolution value data to Excel->Python->Arduino was only possible on the Arduino Uno board. When the Arduino Mega Board was used, the Python terminal output window still says 'N times' but the motor did not actually rotate.

I checked all the board rates and port names. Board rate settings and port settings were correct, but still motor does not rotate. I don't know where the problem is.

The megaboard I used is 2560 megaboard. My code is a mess, but I'd appreciate it if you could help me.

title: Megaboard Problems about pySerial Communication from Python to Arduino

Answers: 0


body:
I'm having problems using an HC-SR04 ultrasonic sensor in conjunction with an LED display module. The sensor appears to work fine when outputting values to the serial monitor, measuring distances up to the rated maximum of around 3m. However when I connect the display module the maximum distance displayed drops to about 50 or 60cm.

I've tried both a TM1637 four-digit seven-segment display module using the TM1637Display library and a Max7219 eight-digit seven-segment display using the LedControl library. Using the NewPing library's `ping_cm()` function for distance measurement instead of the `pulseIn()` function makes no difference.

I'm tending to think it's either something in the LED module libraries that interferes with the measurement of pulses, or possibly noise and ripple on the power supply.

I tried twisting the longer power and data wires together. I've also added a 0.1uF ceramic capacitor across the power connections to the ultrasonic sensor and a 0.1uF ceramic and 2.2uF electrolytic capacitor across the power rails at the point of connection to the display module. This appeared to improve the reliability of the Max display, which previously showed a garbled display from time to time, but didn't make any difference to the range problem.

I've tried powering the Arduino with a 9V wall adapter and well as the USB supply from my PC. This makes no difference. As far as I can trust my multimeter, the supply voltage to the sensor is adequate; between 5.02V and 4.95V depending on the distance the sensor is measuring (the voltage reduces slightly when sensing longer distance). Unfortunately I don't have access to an oscilloscope so I can't see what's happening at a higher frequency. I had hoped the electrolytic capacitor would help smooth out voltage fluctuations.

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

My current work-around is to disable the display while the sensor measures distance. With the LedControl library, I can do this immediately before reading the pulse duration. With the the TM1637Display library I found I had to clear the display before triggering the sensor. In both cases, the display will then show the correct distance but flickers in proportion to the measurement distance (the longer the distance the longer `pulseIn()` has to wait for the echo).

```
#include <TM1637Display.h>

// Module connection pins (Digital Pins)
#define CLK 7
#define DIO 6
#define ECHO 5
#define TRIG 4

TM1637Display display(CLK, DIO);

void setup(){
  pinMode(TRIG, OUTPUT);
  pinMode (ECHO, INPUT);
  display.setBrightness(7, true);
}

void loop(){
  long duration; // duration in us
  long distance; // distance in cm

  display.clear();
  // This is the workaround described above; without this line
  // the sensor cannot measure any more than about 50 or 60cm.
  // With this line, the sensor measures up to about 3m but
  // obviously the display flickers every time around the loop.

  digitalWrite(TRIG, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG, LOW);

  duration = pulseIn(ECHO, HIGH, 20000);
  // a 20ms (20000us) timeout corresponds to the maximum sensor range (3.4m approx)

  // Since the speed of sound is approx 340m/s, i.e. roughly 29 us/cm
  // we can divide duration (us) by 29 and again by 2 (pulse travels
  // out and back) to obtain a distance from sensor in cm:
  distance = duration / 29 / 2;

  display.showNumberDec(distance, false); // true shows leading zeros
  delay(250);
}
```

Any suggestions?

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

title: Problems using HC-SR04 with LED displays

Answers: 0


body:
I have an MKR WIFI1000 (v2.0 [Arduino:XYZ]) with a "real" analog output pin (DAC0/A0/PIN15). According to the documentation, this is a 10 bit DAC, so I assume I can write `analogWrite(15, 1023)` to have an output of 3.3V on that pin.

However, I don't seem to get it higher than 2.7V, which is already reached well before a value of 256.

This is my code:

    #include <Arduino.h>

    #define AN_OUTPUT 15

    int counter = 0;

    void setup()
    {
      pinMode(AN_OUTPUT, OUTPUT);
    }

    void loop ()
    {
      counter++;
      if (counter > 1023) {
        counter = 0;
      }

      analogWrite(AN_OUTPUT, counter);
      delayMicroseconds(1);
    }

And this is the corresponding signal:

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

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

title: Why is my analog output limited to 2.7V?

Answers: 1

body:
[This link][1] had the answer, you have to **remove** the `pinMode(PIN, OUTPUT)` line.

  [1]: https://learn.adafruit.com/adafruit-feather-m0-basic-proto/adapting-sketches-to-m0


body:
In the Arduino IDE, the Tools menu can be used to make some board-specific settings like this:

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

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

... such as Processor Version = "Atmega168P", Processor Speed = "16MHz Crystal Resonator" and so on. These end up choosing fuses when burning a bootloader.  They may or may not also set constants that influence library behavior, I'm not sure.

What I'd like to know is how such settings stored, as they don't seem to be stored in any file associated with the sketch. And that being the case, they seem to be lost when using different boards or settings for subsequent projects.

So what files store these settings, at least temporarily, and how might one associate those settings more permanently with the project/sketch, so that they are repeatable later?

title: Tools > Board settings: how are they captured?

Answers: 1

body:
The board settings from Tools menu are stored in the IDE preferences file.

You can open the file from the Preference dialog of the Arduino IDE. The path to the file is shown at the bottom of the dialog and it is clickable.


body:
Noob question, I'm sure, but - I have one of these little LILYGO ESP32-S3 1.9" T-Display boards. Linked up with my PC, downloaded my code, runs fine, but I can't get the thing to power up from the 5v rail, or through a 5v supply through the li-po connector on the back, as I have with several other ESP32 boards.

Works fine through the USB-C connector, and I'm measuring 5v on the rail when it's running off the USB.

I assume I'm missing something really obvious to do with either booting without a USB being involved or something, but despite spending half a day hunting t'interwebs, and trying various things, I still can't get it to fire up with anything but a USB-C plugged in. I'm stumped!

(I have read something about attaching a capacitor to the "en" button on a different board in order to pull it to ground on boot, but this board has a reset switch which doesn't seem to reset anything unless attached to a USB supply so not sure if it applies in this case.)

This is the [product](https://www.aliexpress.com/item/1005004496543314.html?spm=a2g0o.productlist.main.5.23f638e32RICMa&algo_pvid=d7e12943-7bce-4ace-9582-581435aa9e06&algo_exp_id=d7e12943-7bce-4ace-9582-581435aa9e06-2&pdp_ext_f={"sku_id":"12000030128898262"}&pdp_npi=3@dis!GBP!17.34!17.34!!!!!@21021d7b16758432423558352d0688!12000030128898262!sea!UK!1871708403&curPageLogUid=vjPPTzDNlj1S) and an image of the pinout is [here](https://ae01.alicdn.com/kf/S49e0b5f973694c679760bff54b3e6ec2U.jpg
) in question.

Can anyone give me a nudge in the right direction please?

title: How to power LILYGO ESP32-S3 1.9" T-Display without USB?

Answers: 1

body:
For anyone that has the same issue, here's what I've found with the kind help of VolosProjects from YouTube:

Pin 15 needs to be set to HIGH (or 1) in order to boot.

    void setup()
    {
    pinMode(15, OUTPUT); // to boot with battery...
    digitalWrite(15,1);  // and/or power from 5v rail instead of USB
    ...
    }

Including the code above allows boot with either battery or power on the 5v pin. LILYGO also advised the same thing (and mentioned that pin 38 can be set to adjust LCD screen brightness).


body:
Can anyone identify this character?
[![enter image description here][1]][1]

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

title: Strange Character In Tempurture Reading

Answers: 1

body:
The degree sign (°) is Unicode character U+00B0 (i.e. code point 0xb0).
In UTF-8, it is encoded as the two-byte sequence 0xc2 0xb0. Your browser
is not aware that the page is encoded as UTF-8, and for some reason it
believed it is ISO-8859-1. This two-byte sequence, interpreted as
ISO-8859-1, represents the two characters “Â” and “°”.

The simplest solution might be to add

```html
<meta charset="utf-8">
```

at the top of the `<head>` element of the Web page.


body:
What is the difference between ESP32 Dev kit & Uno for **analogread() Function?**

As Uno -0 to 1023
As Esp 32 Dev Kit -0 to 4095

**So what will be the raw val & scale val ?**

**For UNO -**

    int Rawval = analogRead(analogPin);
    Serial.print("Rawvalue from Analog input =");
    Serial.print(Rawval);
    Scaleval = map(Rawval, 0, 675, 0, 20);
    Serial.print(" Scaled Value =");

**What will be for ESP32 Dev Kit?**

**Ref UNO-**
// For 3V3 input to read 100%, 3V3 of 5V ref = (3.3 / 5) * 1023 = 675

/// === RELAY code ===

    // raw value 675 correspond to 20%, so for 5% we will get 169
      if ( Rawval < 169) digitalWrite(RELAY_pin, HIGH);
      else  digitalWrite(RELAY_pin, LOW);
    }

**What will be for ESP32 Dev Kit?**

title: What is the raw value & scale value functionality of analog read() of ESP32 ? (Provided for UNO for reference)

Answers: 1

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

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

Confusion! Here also, As you said that code for UNO was provided by someone expert.


body:
**Why?**
In Arduino IDE you can set the core debug level, however, this only sets debug level for files in Arduino-esp32 but the core which is distributed as a precompiled library in .sdk files, located in your Arduinio installation folder, is unaffected - the debug level remains the default “error”.

title: How to compile Arduino-ESP32 core with ESP_LOGx

Answers: 1

body:
**What?**
If you want to change the core code or debug level, you need to clone the repo: [https://github.com/espressif/esp32-arduino-lib-builder](https://github.com/espressif/esp32-arduino-lib-builder), make the modifications there, compile and apply the changes (automatically by the build script).

**How?**
There are 2 basic approaches. Both of them involve editing file `esp32-arduino-lib-builder/configs/defconfig.common`.

The first option is to edit the file directly and then build.
Later you can `git restore configs/defconfig.common` to go back.

The second option is to copy the file `cp configs/defconfig.common configs/defconfig.debug`, edit the debug version and then compile.

Open the defconfig file
`vim configs/defconfig.common` or `vim configs/defconfig.debug`

Edit `line 45` containing by default `CONFIG_LOG_DEFAULT_LEVEL_ERROR=y` to one of the following lines depending on your desired log level:
```
CONFIG_LOG_DEFAULT_LEVEL_NONE=y # No output
CONFIG_LOG_DEFAULT_LEVEL_ERROR=y # Errors - default
CONFIG_LOG_DEFAULT_LEVEL_WARN=y # Warnings
CONFIG_LOG_DEFAULT_LEVEL_INFO=y # Info
CONFIG_LOG_DEFAULT_LEVEL_DEBUG=y # Debug
CONFIG_LOG_DEFAULT_LEVEL_VERBOSE=y # Verbose - All of the above
```
Then simply build the libs for all SoCs or one specific SoC. Note that building for all SoCs takes a lot of time, so if you work only with one specific SoC, build only for that one.
If you have copied the defconfig file and the debug settings are in file `configs/defconfig.debug` add flag `debug`
example : `./build.sh debug`
Build all SoCs: `./build.sh`
Build only selected SoC: `./build.sh -t <soc>`
The exact text to choose the SoC:
- esp32
- esp32s2
- esp32c3
- esp32s3
Example: `./build.sh -t esp32`
A wrong format or non-existing SoC will result in the error `sed: can't read sdkconfig: No such file or directory`


body:
I have a problem with lcd, I have  NUCLEO64 L746RG , I have Lcd Display and I2C connected to it.
When I verify code it gives me and long error and I can not find the solution or cause of this error:

    In file included from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l4xx.h:149,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/stm32/stm32_def.h:48,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/stm32/clock.h:19,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/wiring_time.h:23,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/wiring.h:38,
                     from C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\cores\arduino/Arduino.h:36,
                     from C:\Users\User\AppData\Local\Temp\arduino-sketch-B028C48DF91C28F6EAA5B0CE34D27EE2\sketch\Displaylcd1.ino.cpp:1:
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:29: error: expected identifier before '(' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
      169 | class LCD : public Print
          |       ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                              ~            ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
      169 | class LCD : public Print
          |       ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ~             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
      169 | class LCD : public Print
          |       ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:29: error: expected class-name before '(' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
       38 | class LiquidCrystal_I2C : public LCD
          |                                  ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:29: error: expected '{' before '(' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
       38 | class LiquidCrystal_I2C : public LCD
          |                                  ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                              ~            ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
       38 | class LiquidCrystal_I2C : public LCD
          |                                  ^~~
    C:\Users\User\AppData\Local\Arduino15\packages\STMicroelectronics\hardware\stm32\2.4.0\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l476xx.h:1326:43: error: expected ')' before '*' token
     1326 | #define LCD                 ((LCD_TypeDef *) LCD_BASE)
          |                             ~             ^
    c:\Users\User\Documents\Arduino\libraries\LiquidCrystal/LiquidCrystal_I2C.h:38:34: note: in expansion of macro 'LCD'
       38 | class LiquidCrystal_I2C : public LCD
          |                                  ^~~
    C:\Users\User\Documents\Arduino\Displaylcd1\Displaylcd1.ino:2:22: error: variable 'LiquidCrystal_I2C lcd' has initializer but incomplete type
        2 | LiquidCrystal_I2C lcd(0x27,16,2);  /*I2C scanned address defined + I2C screen size*/
          |                      ^
    Multiple libraries were found for "LiquidCrystal_I2C.h"
      Used: C:\Users\User\Documents\Arduino\libraries\LiquidCrystal
      Not used: C:\Users\User\Documents\Arduino\libraries\LiquidCrystal_I2C
    exit status 1

    Compilation error: variable 'LiquidCrystal_I2C lcd' has initializer but incomplete type

This is my code:

    #include <LiquidCrystal_I2C.h>  /*include LCD I2C Library*/
    LiquidCrystal_I2C lcd(0x27,16,2);  /*I2C scanned address defined + I2C screen size*/
    void setup() {
      lcd.init();  /*LCD display initialized*/
      lcd.clear();     /*Clear LCD Display*/
      lcd.backlight();      /*Turn ON LCD Backlight*/
      lcd.setCursor(2,0);   /*Set cursor to Row 1*/
      lcd.print("I2C LCD Nano"); /*print text on LCD*/
      lcd.setCursor(2,1);   /*set cursor on row 2*/
      lcd.print("Linuxhint.com"); /*print message on LCD*/
    }
    void loop() {
    }

I do not know why, I am not including anything else so why is it giving me this error?

PLEASE HELP, I AM WORKING ON IT for 8 hours AN I STILL COULD NOT FIGURE OUT WHAT IS THE PROBLEM, PLease help

Answers: 1

body:
Normally I wouldn't answer this, but the error is not exactly in your code but (seemingly at least) in two common things in the Arduino ecosystem.

**Roughly speaking, the library you're trying to use is incompatible with the STM32 board support you're using.**

The error message sort of tells this. It may help to read it backwards:

```
<sketchbook>\libraries\LiquidCrystal/LCD.h:169:7: note: in expansion of macro 'LCD'
  169 | class LCD : public Print
      |       ^~~
```

So, it is in your installed LiquidCrystal library trying to process the definition of the LCD class, and having a problem with `LCD`, or rather `in expansion of macro 'LCD'`.  So, there's macro called LCD that it's trying to expand at that point, which should be a red flag.

The top part is where the compiler proper is having issues with the macro expansion where it causes a more fundamental error, `error: expected identifier before '(' token`  This is because it is trying to insert the macro definition directly into where it has found it resulting in this code effective after preprocessing:
```c++
class ((LCD_TypeDef *) LCD_BASE) : public Print
```
which is gibberish. It's pointing to the first open parenthesis there and saying `expected identifier`, the `identifier` being the class name it expected to see, not this cast and other stuff that follows. Whoever wrote your LiquidCrystal library did not expect `LCD` to already be defined as something via macro. This is one of a number of reasons why macros are hated.

The bulk of this is indicating the how the macro got to where it came from to where it wound up. The macro started in `stm32l4xx.h` in CMSIS and wound it's way into the LiquidCrystal header through Arduino.h and everything in between:

```c++
In file included from <Arduino15>\<STM32boardSupport>\system/Drivers/CMSIS/Device/ST/STM32L4xx/Include/stm32l4xx.h:149,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/stm32/stm32_def.h:48,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/stm32/clock.h:19,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/wiring_time.h:23,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/wiring.h:38,
                 from <Arduino15>\<STM32boardSupport>\cores\arduino/Arduino.h:36,
                 from <Temp>\arduino-sketch-B028C48DF91C28F6EAA5B0CE34D27EE2\sketch\Displaylcd1.ino.cpp:1:
```

To oversimply a bit CMSIS is the semi-standard header files that ARM chip makers are supposed to provide that among other things define hardware registers. Although I haven't investigated it, it seems likely that whatever chip you're using has a built in LCD driver, and so there are things, macros namely, that have "LCD" in the name. Unfortunately for you, one just called LCD.

You could try renaming all of the uses all of the uses of `LCD` within the LiquidCrystal library that you have to some other name. Or you could try inserting `#undef LCD` after the include of Arduino.h in the LCD.h header in an attempt to undefined the macro so that the LCD in the class definition is not expanded. But, I would be looking for different versions of the library and making sure the library is even the one you think it is, because everyone and their dog seems to have made some library called LiquidCrystal at some point or another. It would be a pity if you went through all trouble to find out you weren't even looking at the right library.


body: I was trying to send some data to a webpage using an Arduino Uno R3 connected to an ESP01. I simply uploaded the BareMinimum and started sending AT commands through the Serial Monitor. It worked fine for the first time, but now its IPMODE is stuck to 0 (Single IP mode). Everytime I try to set it back to 1 (Multiple IP mode), it throws an error "IPMODE must be 0". I tried resetting the ESP01 but that didn't work.

title: Why won't IP mode change to 1 in ESP01 using the AT commands?

Answers: 0


body:
I am trying to send and receive messages between my mac and esp32 board. I am currently using the Bluetooth classic interface. After a successful connection. I however have observed that there is no data being received on my Macbook.

```
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

void setup()
{
  Serial.begin(9600);
  SerialBT.begin("ESP32test");
  Serial.println("Setup initalised");
  delay(1000);
}

void loop()
{
  String inputFromOtherSide;
  Serial.println("Loop has started");
  if (SerialBT.available())
  {
    Serial.println("SerialBT is available");
    inputFromOtherSide = SerialBT.readString();
    SerialBT.println("You had entered: ");
    SerialBT.println(inputFromOtherSide);
  }
}
```

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

The above-attached images show the output that I currently receive. After some debugging, I noticed that

`SerialBT.available()` returns false. I am not sure how to proceed from here.

I do know that this above code should work as I have tested this on windows and it works.

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

I however need to replicate this on the MacBook any guidance on the reason why this fails here would be appreciated. Or is there a way for me to create a Bluetooth serial link on a mac

  [1]: https://i.stack.imgur.com/vvPFg.png
  [2]: https://i.stack.imgur.com/Gntzp.png
  [3]: https://i.stack.imgur.com/ooZ44.png
  [4]: https://i.stack.imgur.com/OvV1L.jpg

title: Bluetooth Serial is unavailable `SerialBT.available()` returns False on Macbook after a successful bluetoooth connection

Answers: 0