body:
**Disclaimer**: I have [asked][1] [questions][2] about this project before but this is yet another issue I'm facing.

**What I really want to do**: Build a battery powered device with 6 colored buttons. When you press one of the buttons the gadget should play a sound saying the name of the color.

It should not need an ON/OFF toggle to save battery capacity but rather have a very low idle current draw so that the battery will lasts for weeks (or even months) when it's not used.

Something like this
[![enter image description here][3]][3]

**Hardware**: ATtiny85 (low draw in general, very low draw in sleep), DfPlayer, 3.7v Battery (probably 18650)

The 6 buttons are attached to a single input pin. The microcontroller can distinguish them by reading the ADC value. The buttons have [different resistors attached][1] to them

**How I wanted to do it**: My initial plan was to press a button that wakes the microcontroller up. The mcu then wakes the dfplayer, plays a sound and goes back to sleep. If that would not be responsive enough add a delay to the sleep like: if no button was pressed within the last 30s go to sleep. That worked [after some initial problems][2] but it turned out that the DfPlayer "sleep mode" doesn't mean it goes to sleep as in it draws less current but much rather that it's just idling, not playing any sound.

**How I want to do it now**: Pretty much the same as above but instead of sending the DfPlayer to sleep just turn it on and off:
Press a button that wakes the microcontroller up. The mcu then turns the DfPlayer on by setting the gate of an n-channel mosfet ([IRF3708][4]) HIGH, waits a short period of time, plays a sound, turns the dfplayer off and goes back to sleep. If that's not responsive enough add a sleep delay like explained above.

**What I'm already able to do**:

- make the DfPlayer play a specific sound over serial communication
- distinguish between the 6 input buttons
- wake the microcontroller up with any of these buttons
- turn the DfPlayer on/off by using an n-channel mosfet

**The problem that I have**: The microcontroller *freezes* when I set the output pin attached to the mosfet gate to HIGH. Freeze means it just won't execute any code after the `digitalWrite(PIN_MOS, HIGH);` call. I tested it by turning an LED on a different pin on and off like so

    digitalWrite(PIN_LED, HIGH);
    digitalWrite(PIN_MOS, HIGH);
    digitalWrite(PIN_LED, LOW);

The LED turns on but won't ever turn off. When I use the external reset of the attiny the mosfet will turn off and code will execute again just fine. Until I try to set the mosfet pin to HIGH again.
The DfPlayer will turn on though, I can play sounds on it by shorting 2 pins on it. It doesn't seem to be unstable either. It's just that the attiny hangs up.
I use a cheap lab psu but it should be good enough to be not the problem. I've also tried a fully charged 18650 battery and a CR2032 battery. The 18650 worked the same as the psu and the CR2032 just couldn't handle the draw and the DfPlayer wouldn't properly turn on.
I tried it different voltages between 3.3v and 5v. In theory everything should work and in reality it didn't change anything either.

Here is the breadboard layout I use.
I also added an electrolytic and ceramic cap between Vcc/GND on the DfPlayer but that didn't help either

[![enter image description here][5]][5]

Here is the code I use
```c
    #include <Arduino.h>
    #include <avr/sleep.h>
    #include <DFMiniMp3.h>
    #include <avr/interrupt.h>
    #include <avr/power.h>
    #include "LemonSerial.h"
    #include "mp3notify.h"

    #define PIN_TX PB0
    #define PIN_RX PB1
    #define PIN_MOS PB2
    #define PIN_LED PB3
    #define PIN_A PB4

    LemonSerial secondarySerial(PIN_RX, PIN_TX);
    DfMp3 dfmp3(secondarySerial);

    void sleep();

    void initADC()
    {
      ADMUX =
          (1 << ADLAR) | // left shift result
          (0 << REFS1) | // Sets ref. voltage to VCC, bit 1
          (0 << REFS0) | // Sets ref. voltage to VCC, bit 0
          (0 << MUX3) |  // use ADC2 for input (PB4), MUX bit 3
          (0 << MUX2) |  // use ADC2 for input (PB4), MUX bit 2
          (1 << MUX1) |  // use ADC2 for input (PB4), MUX bit 1
          (0 << MUX0);   // use ADC2 for input (PB4), MUX bit 0

      ADCSRA =
          (1 << ADEN) |  // Enable ADC
          (1 << ADPS2) | // set prescaler to 128, bit 2
          (1 << ADPS1) | // set prescaler to 128, bit 1
          (1 << ADPS0);  // set prescaler to 128, bit 0
    }

    void setup()
    {
      initADC();

      pinMode(PB5, INPUT_PULLUP);
      pinMode(PIN_A, INPUT);
      pinMode(PIN_LED, OUTPUT);
      digitalWrite(PIN_LED, LOW);
      pinMode(PIN_MOS, OUTPUT);
      digitalWrite(PIN_MOS, LOW);
    }

    void play(uint16_t track)
    {
      if (digitalRead(PIN_MOS) == LOW)
      {
        digitalWrite(PIN_LED, HIGH);
        delay(500);
        digitalWrite(PIN_MOS, HIGH);
        digitalWrite(PIN_LED, LOW);

        delay(500); // wait for DfPlayer to turn on

        dfmp3.begin();
        dfmp3.reset();
        dfmp3.disableDac();
        dfmp3.setVolume(30);
        dfmp3.setPlaybackSource(DfMp3_PlaySource_Sd);
      }

      dfmp3.playGlobalTrack(track);
    }

    void loop()
    {
      ADCSRA |= (1 << ADSC); // start ADC measurement
      while (ADCSRA & (1 << ADSC))
      {
          // wait till conversion complete
      }

      uint8_t adcValue = ADCH;
      // actually calculate the parameter based off adcValue here. omitted for readability
      play(1);
    }

    // Interrupt Serviceroutine (Pin-Change-Interrupt)
    ISR(PCINT0_vect)
    {
      LemonSerial::handle_interrupt();
    }

    // ADC interrupt service routine
    ISR(ADC_vect)
    {
      ; // noop
    }
```

  [1]: https://arduino.stackexchange.com/questions/93980/how-to-properly-read-adc-on-an-attiny85
  [2]: https://arduino.stackexchange.com/questions/93902/attiny85-with-sleep-and-serial
  [3]: https://i.stack.imgur.com/l5xY8.png
  [4]: https://www.infineon.com/dgdl/Infineon-IRF3708-DataSheet-v01_01-EN.pdf?fileId=5546d462533600a4015355df7cf5193c
  [5]: https://i.stack.imgur.com/yaxSn.png

title: Microcontroller freezes when triggering the gate of an N-channel MOSFET

Answers: 1

body:
[@6v6gt][1] was the one who figured out what was missing.

I had to increase the 1Ω resistor between the output pin and gate to 1kΩ and add a 100nF ceramic capacitor between GND and gate. Eventually it worked just as expected.

This is the full code I ended up using. I tried to add enough comments to make it clear what happens.

    #include <Arduino.h>
    #include <avr/sleep.h>
    #include <DFMiniMp3.h>
    #include <avr/interrupt.h>
    #include <avr/power.h>
    // this is just "SoftwareSerial" without blocking interrupts
    // thus you have to call handle_interrupt() from here
    #include "LemonSerial.h"
    #include "mp3notify.h"

    #define PIN_TX PB0
    #define PIN_RX PB1
    #define PIN_MOS PB2
    #define PIN_LED PB3
    #define PIN_A PB4
    // turning the player on and initializing it takes quite a while
    // thus do not go back to sleep immediately after each button press
    uint32_t timeoutMs = 30000;
    uint64_t started = 0;

    // dfplayer api
    LemonSerial secondarySerial(PIN_RX, PIN_TX);
    DfMp3 dfmp3(secondarySerial);

    void sleep();

    uint8_t readADC()
    {
      ADCSRA |= (1 << ADSC); // start ADC measurement
      while (ADCSRA & (1 << ADSC))
        ; // wait till conversion complete

      uint8_t adcValue = ADCH;
    }

    void initADC()
    {
      ADMUX =
          (1 << ADLAR) | // left shift result
          (0 << REFS1) | // Sets ref. voltage to VCC, bit 1
          (0 << REFS0) | // Sets ref. voltage to VCC, bit 0
          (0 << MUX3) |  // use ADC2 for input (PB4), MUX bit 3
          (0 << MUX2) |  // use ADC2 for input (PB4), MUX bit 2
          (1 << MUX1) |  // use ADC2 for input (PB4), MUX bit 1
          (0 << MUX0);   // use ADC2 for input (PB4), MUX bit 0

      ADCSRA =
          (1 << ADEN) |  // Enable ADC
          (1 << ADPS2) | // set prescaler to 128, bit 2
          (1 << ADPS1) | // set prescaler to 128, bit 1
          (1 << ADPS0);  // set prescaler to 128, bit 0
    }

    void setup()
    {
      initADC();

      // set INPUT_PULLUP to reduce current draw
      pinMode(PB5, INPUT_PULLUP); // PB5 is not assigned to any constant
      pinMode(PIN_LED, INPUT_PULLUP);

      pinMode(PIN_A, INPUT); // ADC pin is physically pulled low
      pinMode(PIN_MOS, OUTPUT);
      digitalWrite(PIN_MOS, LOW);

      started = millis();
    }

    /// @brief plays a track on the dfplayer. turns the player on if neccessary
    /// @param track track number to play
    void playTrack(uint16_t track)
    {
      started = millis();

      if (digitalRead(PIN_MOS) == LOW)
      {
        digitalWrite(PIN_MOS, HIGH);
        delay(50); // wait 50ms for DfPlayer to turn on

        // baud 4800 because the attiny runs at 16mhz (8mhz -> 9600)
        dfmp3.begin(4800);
        dfmp3.setVolume(30);
      }

      dfmp3.playGlobalTrack(track);
    }

    void loop()
    {
      uint8_t adcValue = readADC();

      if (adcValue >= 227 && adcValue <= 237)
      {
        // 10k ohm (3.0V -> adc 232)
        playTrack(1);
      }
      else if (adcValue >= 212 && adcValue <= 223)
      {
        // 18k ohm (2.8V -> adc 217)
        playTrack(2);
      }
      else if (adcValue >= 196 && adcValue <= 206)
      {
        // 27k ohm (2.6V -> adc 201)
        playTrack(3);
      }
      else if (adcValue >= 181 && adcValue <= 191)
      {
        // 38k ohm (2.4V -> adc 186)
        playTrack(4);
      }
      else if (adcValue >= 165 && adcValue <= 175)
      {
        // 50k ohm (2.2V -> adc 170)
        playTrack(5);
      }
      else if (adcValue >= 150 && adcValue <= 160)
      {
        // 65k ohm (2.0V -> adc 155)
        playTrack(6);
      }
      // ending up here every loop where no button was pressed. so basically 99.99% of the time
      else
      {
        // started gets set to millis() everytime a track is played
        if (millis() - started > timeoutMs)
        {
          // sleep if some time has passed without input (see timeoutMs)
          sleep();
        }
      }
    }

    // sets the device into POWER DOWN mode.you can probably tune it to be more efficient
    void sleep()
    {
      digitalWrite(PIN_MOS, LOW);

      // pin change interrupt
      PCMSK |= bit(PIN_A);
      GIFR |= bit(PCIF);  // clear any outstanding interrupts
      GIMSK |= bit(PCIE); // enable pin change interrupts

      set_sleep_mode(SLEEP_MODE_PWR_DOWN);
      power_all_disable(); // power off ADC, Timer 0 and 1, serial interface
      sleep_enable();
      sleep_cpu();
      sleep_disable();
      power_all_enable(); // power everything back on
    }

    // Interrupt Serviceroutine (Pin-Change-Interrupt)
    ISR(PCINT0_vect)
    {
      // the SoftwareSerial does not block any interrupt pins anymore and thats why we have to call it from here
      LemonSerial::handle_interrupt();
    }

    // ADC interrupt service routine
    ISR(ADC_vect)
    {
      ; // noop
    }

This is a schematic from how everything is set up now. This is the first time I drew a _real_ schematic so I hope it's clear whats going on

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

  [1]: https://arduino.stackexchange.com/users/31043
  [2]: https://i.stack.imgur.com/NMhOf.png


body:
I have bought my brand new Arduino MKRZero to emulate a keyboard. When I plug it in, I get the following on COM6, which is listed as "Arduino MKRZero".

"This device cannot start" (Code 10)

[![!\[image|402x450\](upload://2ys9cT0qBD8jgMtzldUfvHLboId.png)][1]][1]

I also get a new COM port connection, COM3, listed as a generic USB Serial Device.

[![!\[image|389x137\](upload://iZGu03re8ovSh80b2EhwCuqzNLE.png)][2]][2]

In my IDE (2.1.0) I am given the following:

[![!\[image|419x478\](upload://qpDwaiL6GOMFx2Bonl6pgFVCp4Z.png)][3]][3]

COM 3 opens on the Serial Monitor, while COM 6 gives a port monitor error:

[![!\[image|690x149\](upload://rRsTPxCwVEv3BINi2234Dpn4wAf.png)][4]][4]

## Attempts ##

I have tried a few things based on the following:
https://forum.arduino.cc/t/solved-arduino-uno-this-device-cannot-start-code-10-at-hardware-manager/298777
https://forum.arduino.cc/t/this-device-cannot-start-code-10-arduino-leonardo/897137
https://www.lifewire.com/how-to-fix-code-10-errors-2623181

* Updating drivers
* Rolling back drivers
* Using a different USB connector
* Restarting laptop

## Context ##

The reason why I ask is because I am attempting to use the following code in an Arduino, which, per my understanding, should print the letter "F" every second with my keyboard.

```
#include <Keyboard.h>

void setup() {
  // open the serial port:
  Serial.begin(9600);
  // initialize control over the keyboard:
  Keyboard.begin();
}

void loop() {
    Keyboard.write('F');
    delay(1000);
}
```

However, no response is received.

Please let me know if more information is required, or if this is a code issue. I am on Win 10.0.19045, and attempted both the latest version and an alleged, more stable version of the MKRZero driver (Arduino SAMD Boards [32-bits ARM Cortex-M0+] version 1.8.13 and 1.8.9).

  [1]: https://i.stack.imgur.com/YQ8CF.png
  [2]: https://i.stack.imgur.com/zm4wp.png
  [3]: https://i.stack.imgur.com/KpLCj.png
  [4]: https://i.stack.imgur.com/2R81Z.png

title: Arduino MKRZero "This device cannot start" (Code 10), and Keyboard.h

Answers: 0


body:
I am using an ESP32 a TB6600 micro stepper, and a Nema 23 stepper motor, I am trying to control the motor with the esp32 but the TB6600 requires a 5v signal, I tried to fix this by using a logic level converter (specifically [this](https://www.amazon.com/dp/B07LG646VS?psc=1&ref=ppx_yo2ov_dt_b_product_details)) but when I attempt to control the motor I get a very slight hum out of the motor and no movement.

The motor controller and motor both work as I tested it with an Arduino Uno.

```
void setup() {
  pinMode(15, OUTPUT);
  pinMode(16, OUTPUT);
  pinMode(17, OUTPUT);
  digitalWrite(16, HIGH);
}

void loop() {

  digitalWrite(15,LOW);
  digitalWrite(15,HIGH);
  digitalWrite(17, HIGH);
   delay(200);
}
```

Picture of Circuit
[![Arduino circuit][1]][1]

Circuit Diagram
[![Circuit Diagram ][2]][2]

  [1]: https://i.stack.imgur.com/3W6yZ.jpg
  [2]: https://i.stack.imgur.com/huZA4.jpg

title: Unable to control motor with ESP32 using logic level shifter

Answers: 2

body:
I haven't used this kind of system, so I'm just guessing. But in the Manual it says:

> When“EN”is in the valid state, the motor is in a free states (Off-line
  mode). In this mode, you can adjust the motor shaft position manually. When“EN”is
  in the invalid state, the motor will be in an automatic control mode.
([Source][1]).

It is not entirely clear what they mean by "manually". But you set pin 17 to HIGH and the result would fit the description. Maybe set 17 to LOW?

On another note: there is no delay/time between `digitalWrite(15,LOW);` and `digitalWrite(15,HIGH);`. This will create a very short pulse, which might be too short for the level shifting electronics to translate. Some delay() or equivalent non-blocking code between the two writes could help.

  [1]: https://www.makerguides.com/wp-content/uploads/2019/10/TB6600-Manual.pdf

body:
I figured out the problem, the logic level switcher I was using is meant for I2C  sensors, and thus was only capable of converting open-drain signals and cannot perform push/pull level translation meaning it was not able to provide a data signal to the micro stepper. I replaced the shifter with a shifter capable of push/pull translation specifically [This][1]

  [1]: https://www.sparkfun.com/products/12009


body:
I have cash counter with RS232 in the back of it. I want to read the data that supposed displayed on the projector with RS232 to TTL convertor and arduino.

Here is all my setup

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

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

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

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

  [1]: https://i.stack.imgur.com/38Gwe.jpg
  [2]: https://i.stack.imgur.com/432NF.jpg
  [3]: https://i.stack.imgur.com/p4nZo.jpg
  [4]: https://i.stack.imgur.com/zDk0z.jpg

Now I
- Connect the MAX3232 TX pin to the RX Arduino pin
- and Connect the MAX3232 RX pin to the TX Arduino pin
- and the Vcc to 5V
- and MAX3232  GND to arduino  GND
- and plug the MAX3232  to the cash counter and the arduino to the pc
- and flash

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

void loop() {
  int data = Serial.read();
  if (data != -1) {
    Serial.println(data);
  }
}
```

And the output comes like this

```
50
56
48
67
49
52
48
8
10
106
13
51
56
56
76
147
48
51
12
13
83
106
51
1
13
64
10
1
49
254
254
254
254
252
254
255
```

How can I read the data from this device?

title: I have a cash counter with RS232 in the back of it, I want to read the data that supposed displayed on the projector

Answers: 0


body:
I've looked around for solutions and tried but can't get this to work. I'm trying to send a  POST request to a localapi. My code:
```
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include "ArduinoJson.h"
#include <WiFiClient.h>

const char* ssid = "VIOT";
const char* password = "********";
const char* sensor_0 = "1234";
const char* sensor_1 = "5678";
const char* sensor_2 = "3678";
String postMessage;

void setup()

 {
Serial.begin(115200);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.println(WiFi.localIP());
}

void loop()
{
  WiFiClient client;
  HTTPClient http;
  StaticJsonDocument<256> doc;
  doc["batteryCharge"] = sensor_0;
  doc["powerUsage"] = sensor_1;
  doc["powerProduced"] = sensor_2;

  serializeJson(doc, postMessage);

  Serial.print("[HTTP] begin...\n");
  http.begin(client,"http://192.168.1.190/",3000);
  http.addHeader("Content-Type", "application/json");
  Serial.print("[HTTP] POST...\n");
  int httpCode = http.POST(postMessage);
  Serial.print(httpCode);
  if (httpCode > 0) {
    if (httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      Serial.println("HTTP POST request successful");
      Serial.println("Response: " + payload);
}
}

else {

 Serial.println("HTTP POST request failed");

 }

http.end(); delay(10000); // Wait for 10 seconds before sending the next request

 }
```
Both devices are connected to the same network and my computer ip is 192.168.1.190.
Tested my api on postman and it ran successfully.
Here is the error:
```
15:45:26.469 -> Connecting to WiFi...
15:45:27.469 -> Connecting to WiFi...
15:45:29.207 -> Connecting to WiFi...
15:45:30.208 -> Connecting to WiFi...
15:45:30.208 -> Connected to WiFi
15:45:30.208 -> 192.168.1.180
15:45:30.208 -> [HTTP] begin...
15:45:30.208 -> [HTTP] POST...
15:45:30.208 -> -1HTTP POST request failed
```

title: HTTP POST request error on esp8266 to my localhost (error:-1)

Answers: 1

body:
I found the problem. I changed
```
http.begin(client,"http://192.168.1.190/",3000);
```
to
```
http.begin(client,"http://192.168.1.190:3000");
```


body:
I'm using the code below, but I had no success.

I'm using this connection wire:
The photo of the Arduino doesn't show the SCL and SDA pins, but please consider that it has 2 SCL pins and 2 SDA pins in the places where I marked them in the image.

Both sensors are working, however they are mirroring each other's measurements.

That link is from the datasheet:
https://static.garmin.com/pumac/LIDAR_Lite_v3_Operation_Manual_and_Technical_Specifications.pdf

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

    #include <Wire.h>
    #include <LIDARLite.h>

    #define LIDAR1_ADDRESS 0x62 // Endereço I2C do LIDAR Lite 1
    #define LIDAR2_ADDRESS 0x63 // Endereço I2C do LIDAR Lite 2

    LIDARLite lidar1; // Objeto para o LIDAR Lite 1
    LIDARLite lidar2; // Objeto para o LIDAR Lite 2

    void setup() {
      Wire.begin();        // Inicializa a biblioteca Wire (I2C)
      Serial.begin(115200);  // Inicializa a comunicação serial

      // Inicializa os objetos dos LIDARs
      lidar1.begin(LIDAR1_ADDRESS); // Inicialização do LIDAR Lite 1
      lidar2.begin(LIDAR2_ADDRESS); // Inicialização do LIDAR Lite 2
    }

    void loop() {
      int distance1 = lidar1.distance();
      int distance2 = lidar2.distance();

      // Exibe as medições dos LIDARs no Monitor Serial
      Serial.print("LIDAR 1: ");
      Serial.print(distance1);
      Serial.print(" cm | LIDAR 2: ");
      Serial.print(distance2);
      Serial.println(" cm");

      delay(500); // Intervalo entre as leituras
    }

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

title: How to make 2 lidar lite v3 work with 1 Arduino?

Answers: 1

body:
If these are the Garmin Lidar Lite V3, here is a [link to their data sheet.][1] On page 5 of the datasheet you'll find instructions for configuring their I2C addresses. If you haven't already done that, it's quite likely that both devices are replying at once to the same query.

If you have done that already, please update your question with that and any other relevant data - such as the manufacturer, if I got that wrong, add any configuration changes you've made.

  [1]: https://static.garmin.com/pumac/LIDAR_Lite_v3_Operation_Manual_and_Technical_Specifications.pdf


body:
im trying to upload my code to my esp32 through OTA iam able to discover the network port but my code is always failing to upload i donno the reason behind it

```
#include <WiFi.h>
#include <ArduinoOTA.h>

const char* ssid = "Redmi";
const char* password = "12345678s";
const char* OTA_password = "1234"; // set your own OTA password

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

  // Connect to Wi-Fi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Print IP address
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  // Start OTA update server with authentication
  ArduinoOTA.setHostname("my-esp32");
  ArduinoOTA.setPassword(OTA_password); // set OTA password
  ArduinoOTA.onStart([]() {
    // Disable other tasks that may interfere with OTA update
    Serial.println("OTA update started");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nOTA update finished");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("OTA update progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("OTA update error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) {
      Serial.println("OTA authentication failed");
    } else if (error == OTA_BEGIN_ERROR) {
      Serial.println("OTA begin failed");
    } else if (error == OTA_CONNECT_ERROR) {
      Serial.println("OTA connect failed");
    } else if (error == OTA_RECEIVE_ERROR) {
      Serial.println("OTA receive failed");
    } else if (error == OTA_END_ERROR) {
      Serial.println("OTA end failed");
    }
  });
  ArduinoOTA.begin();
}

void loop() {
  ArduinoOTA.handle();
  // Your other code here
}

```
above is the code i uploaded to create OTA server
```
#include <WiFi.h>
#include <ArduinoOTA.h>

const char* ssid = "Redmi";
const char* password = "12345678s";

#define LEDPIN 4

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

  // Connect to Wi-Fi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("");

  // Start OTA update server
  ArduinoOTA.begin();
  Serial.println("OTA server started");

  // Initialize LED pin as output
  pinMode(LEDPIN, OUTPUT);
}

void loop() {
  ArduinoOTA.handle();

  // Blink LED every second
  digitalWrite(LEDPIN, HIGH);
  delay(1000);
  digitalWrite(LEDPIN, LOW);
  delay(1000);
}
```
and im trying to upload above blink program through OTA
[![getting stucked and i have to restart the software everytime to test it][1]][1]
and above is the error im getting it getting stucked and i have to restart the software everytime to test it. I appreciate if anybody care to explain and help me

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

title: Uploading code to ESP32 using Arduino OTA

Answers: 0


body:
Why I can't read the last byte in the file when I use the Arduino ide code?
The code in cpp is work without any mistakes.
This is my code on Arduino ide:

      vector<unsigned char> text;
      unsigned char textseg;
      in_file.read(&textseg,1);
      while (in_file.available()){
          text.push_back(textseg);
          in_file.read(&textseg,1);
      }

And this is cpp code:

    vector<unsigned char> text;
    unsigned char textseg;
    in_file.read(reinterpret_cast<char*>(&textseg), 1);
    while (!in_file.eof())
    { text.push_back(textseg);
     in_file.read(reinterpret_cast<char*>(&textseg), 1);
    }

title: Read binary file on SD card

Answers: 1

body:
Your loop seems to be out-by-one. I would prefer:

<!-- language: lang-c++ -->

      vector<unsigned char> text;
      unsigned char textseg;
      while (in_file.available()){
          in_file.read(&textseg,1);
          text.push_back(textseg);
      }

Why read a byte, as you did, before you know if it is available?

In the Standard C++ library, `eof()` is true if a read fails, however in the Arduino `available()` means a byte is available to be read. They are not directly swappable.


body:
I made a spider robot using arduino and from esp. I made an audio output device which is linked to python program which writes a particular data (when we speak a command) to esp board and accordingly the voice would be activated. Now I want to link them together.

If the esp32 sends a particular data the function in arduino is executed.  Therefore I want to connect esp32 to arduino uno though Serial monitor and send data from esp 32 to arduino. I have only analog pins vacant as all digital pins are used for the servos. how can I achieve this?.

In the main arduino file there are 2 more flexitimer and flexitimer2.cpp files but there is no need of editing them and hence I am giving the code of main file.

```c++
    #include <Servo.h>    //to define and control servos
    #include "FlexiTimer2.h"//to set a timer to manage all servos
    /* Servos --------------------------------------------------------------------*/
    //define 12 servos for 4 legs
    char data = 0;
    Servo servo[4][3];
    //define servos' ports
    const int servo_pin[4][3] = { {2, 3, 4}, {5, 6, 7}, {8, 9, 10}, {11, 12, 13} };
    /* Size of the robot ---------------------------------------------------------*/
    const float length_a = 55;
    const float length_b = 77.5;
    const float length_c = 27.5;
    const float length_side = 71;
    const float z_absolute = -28;
    /* Constants for movement ----------------------------------------------------*/
    const float z_default = -50, z_up = -30, z_boot = z_absolute;
    const float x_default = 62, x_offset = 0;
    const float y_start = 0, y_step = 40;
    const float y_default = x_default;
    /* variables for movement ----------------------------------------------------*/
    volatile float site_now[4][3];    //real-time coordinates of the end of each leg
    volatile float site_expect[4][3]; //expected coordinates of the end of each leg
    float temp_speed[4][3];   //each axis' speed, needs to be recalculated before each movement
    float move_speed;     //movement speed
    float speed_multiple = 1; //movement speed multiple
    const float spot_turn_speed = 4;
    const float leg_move_speed = 8;
    const float body_move_speed = 3;
    const float stand_seat_speed = 1;
    volatile int rest_counter;      //+1/0.02s, for automatic rest
    //functions' parameter
    const float KEEP = 255;
    //define PI for calculation
    const float pi = 3.1415926;
    /* Constants for turn --------------------------------------------------------*/
    //temp length
    const float temp_a = sqrt(pow(2 * x_default + length_side, 2) + pow(y_step, 2));
    const float temp_b = 2 * (y_start + y_step) + length_side;
    const float temp_c = sqrt(pow(2 * x_default + length_side, 2) + pow(2 * y_start + y_step + length_side, 2));
    const float temp_alpha = acos((pow(temp_a, 2) + pow(temp_b, 2) - pow(temp_c, 2)) / 2 / temp_a / temp_b);
    //site for turn
    const float turn_x1 = (temp_a - length_side) / 2;
    const float turn_y1 = y_start + y_step / 2;
    const float turn_x0 = turn_x1 - temp_b * cos(temp_alpha);
    const float turn_y0 = temp_b * sin(temp_alpha) - turn_y1 - length_side;
    /* ---------------------------------------------------------------------------*/

      - setup function
       ---------------------------------------------------------------------------*/
    void setup()
    {
      //start serial for debug
      Serial.begin(9600);
      Serial.println("Robot starts initialization");

      //initialize default parameter
      pinMode(14, OUTPUT);
      set_site(0, x_default - x_offset, y_start + y_step, z_boot);
      set_site(1, x_default - x_offset, y_start + y_step, z_boot);
      set_site(2, x_default + x_offset, y_start, z_boot);
      set_site(3, x_default + x_offset, y_start, z_boot);
      for (int i = 0; i < 4; i++)
      {
        for (int j = 0; j < 3; j++)
        {
          site_now[i][j] = site_expect[i][j];
        }
      }
      //start servo service
      FlexiTimer2::set(20, servo_service);
      FlexiTimer2::start();
      Serial.println("Servo service started");
      //initialize servos
      servo_attach();
      Serial.println("Servos initialized");
      Serial.println("Robot initialization Complete");
    //   stand();
    //   delay(1000);
    //   hand_shake(2);
    //   Serial.println("hihihihihi");
    //   delay(1000);
    //   step_forward();
    //   step_forward();
    //   step_forward();
    //   step_forward();
    //   step_forward();
    //   step_forward();
    //   delay(1000);
    //   step_back();
    //   step_back();
    //   step_back();
    //   step_back();
    //   step_back();
    //   step_back();
    //   delay(1000);

    //   turn_left();
    //   turn_left();
    //   turn_left();
    //   turn_left();
    //   delay(1000);
    //   turn_right();
    //   turn_right();
    //   turn_right();
    //   turn_right();
    //   delay(1000);
    //   hand_wave(4);
    //   delay(1000);
    //   hand_shake(4);
    //   delay(1000);
    //   sit();
    //   delay(1000);
    }

    void servo_attach(void)
    {
      for (int i = 0; i < 4; i++)
      {
        for (int j = 0; j < 3; j++)
        {
          servo[i][j].attach(servo_pin[i][j]);
          delay(100);
        }
      }
    }

    void servo_detach(void)
    {
      for (int i = 0; i < 4; i++)
      {
        for (int j = 0; j < 3; j++)
        {
          servo[i][j].detach();
          delay(100);
        }
      }
    }

    /*
      - loop function
       ---------------------------------------------------------------------------*/
    void loop()
    {

      if(Serial.available() > 0)
       {
          data = Serial.read();
          Serial.print(data);
          Serial.print("\n");

          if(data == 'F')
            {
             Serial.println("Step forward");
             step_forward();
            }
          else if(data == 'B')
             {
              Serial.println("Step back");
              step_back();
            }
          else if(data == 'L')
             {
             Serial.println("Turn left");
             turn_left();

            }
          else if(data == 'R')
            {
              Serial.println("Turn right");
              turn_right();

            }
            else if(data == 'X')
            {
             Serial.println("Stand");
             stand();
            }
             else if(data == 'x')
            {
              Serial.println("Sit");
              sit();
            }
           else if(data == 'S' ||data == 'D' )

            {

            }

             else if(data == 'W')
            {
              digitalWrite(14, HIGH);
            }
              else if(data == 'w')
            {
             digitalWrite(14, LOW);
            }
            else if(data == 'V')
            {
              Serial.println("Hand wave");
              hand_wave(3);
            }
              else if(data == 'v')
            {
             Serial.println("Hand wave");
             hand_shake(3);
            }
             else if(data == 'U')
            {
              Serial.println("Body dance");
              body_dance(10);
            }
              else if(data == 'u')
            {
              Serial.println("Body dance");
              body_dance(10);
            }
            while(Serial.available()) {Serial.read();}
       }

    }

    /*
      - sit
      - blocking function
       ---------------------------------------------------------------------------*/
    /*
      - spot turn to right
      - blocking function
      - parameter step steps wanted to turn
       ---------------------------------------------------------------------------*/
    void turn_right()
    {
        move_speed = spot_turn_speed;

        if (site_now[2][1] == y_start)
        {
          //leg 2&0 move
          set_site(2, x_default + x_offset, y_start, z_up);
          wait_all_reach();

          set_site(0, turn_x0 - x_offset, turn_y0, z_default);
          set_site(1, turn_x1 - x_offset, turn_y1, z_default);
          set_site(2, turn_x0 + x_offset, turn_y0, z_up);
          set_site(3, turn_x1 + x_offset, turn_y1, z_default);
          wait_all_reach();

          set_site(2, turn_x0 + x_offset, turn_y0, z_default);
          wait_all_reach();

          set_site(0, turn_x0 + x_offset, turn_y0, z_default);
          set_site(1, turn_x1 + x_offset, turn_y1, z_default);
          set_site(2, turn_x0 - x_offset, turn_y0, z_default);
          set_site(3, turn_x1 - x_offset, turn_y1, z_default);
          wait_all_reach();

          set_site(0, turn_x0 + x_offset, turn_y0, z_up);
          wait_all_reach();

          set_site(0, x_default + x_offset, y_start, z_up);
          set_site(1, x_default + x_offset, y_start, z_default);
          set_site(2, x_default - x_offset, y_start + y_step, z_default);
          set_site(3, x_default - x_offset, y_start + y_step, z_default);
          wait_all_reach();

          set_site(0, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
        else
        {
          //leg 1&3 move
          set_site(1, x_default + x_offset, y_start, z_up);
          wait_all_reach();

          set_site(0, turn_x1 + x_offset, turn_y1, z_default);
          set_site(1, turn_x0 + x_offset, turn_y0, z_up);
          set_site(2, turn_x1 - x_offset, turn_y1, z_default);
          set_site(3, turn_x0 - x_offset, turn_y0, z_default);
          wait_all_reach();

          set_site(1, turn_x0 + x_offset, turn_y0, z_default);
          wait_all_reach();

          set_site(0, turn_x1 - x_offset, turn_y1, z_default);
          set_site(1, turn_x0 - x_offset, turn_y0, z_default);
          set_site(2, turn_x1 + x_offset, turn_y1, z_default);
          set_site(3, turn_x0 + x_offset, turn_y0, z_default);
          wait_all_reach();

          set_site(3, turn_x0 + x_offset, turn_y0, z_up);
          wait_all_reach();

          set_site(0, x_default - x_offset, y_start + y_step, z_default);
          set_site(1, x_default - x_offset, y_start + y_step, z_default);
          set_site(2, x_default + x_offset, y_start, z_default);
          set_site(3, x_default + x_offset, y_start, z_up);
          wait_all_reach();

          set_site(3, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
    }

    /*
      - go forward
      - blocking function
      - parameter step steps wanted to go
       ---------------------------------------------------------------------------*/
    void step_forward()
    {
        move_speed = leg_move_speed;

        if (site_now[2][1] == y_start)
        {
          //leg 2&1 move
          set_site(2, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(2, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(2, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = body_move_speed;

          set_site(0, x_default + x_offset, y_start, z_default);
          set_site(1, x_default + x_offset, y_start + 2 * y_step, z_default);
          set_site(2, x_default - x_offset, y_start + y_step, z_default);
          set_site(3, x_default - x_offset, y_start + y_step, z_default);
          wait_all_reach();

          move_speed = leg_move_speed;

          set_site(1, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(1, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(1, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
        else
        {
          //leg 0&3 move
          set_site(0, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(0, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(0, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = body_move_speed;

          set_site(0, x_default - x_offset, y_start + y_step, z_default);
          set_site(1, x_default - x_offset, y_start + y_step, z_default);
          set_site(2, x_default + x_offset, y_start, z_default);
          set_site(3, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = leg_move_speed;

          set_site(3, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(3, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(3, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
    }

    /*
      - go back
      - blocking function
      - parameter step steps wanted to go
       ---------------------------------------------------------------------------*/
    void step_back()
    {
        move_speed = leg_move_speed;
        if (site_now[3][1] == y_start)
        {
          //leg 3&0 move
          set_site(3, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(3, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(3, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = body_move_speed;

          set_site(0, x_default + x_offset, y_start + 2 * y_step, z_default);
          set_site(1, x_default + x_offset, y_start, z_default);
          set_site(2, x_default - x_offset, y_start + y_step, z_default);
          set_site(3, x_default - x_offset, y_start + y_step, z_default);
          wait_all_reach();

          move_speed = leg_move_speed;

          set_site(0, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(0, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(0, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
        else
        {
          //leg 1&2 move
          set_site(1, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(1, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(1, x_default + x_offset, y_start + 2 * y_step, z_default);
          wait_all_reach();

          move_speed = body_move_speed;

          set_site(0, x_default - x_offset, y_start + y_step, z_default);
          set_site(1, x_default - x_offset, y_start + y_step, z_default);
          set_site(2, x_default + x_offset, y_start + 2 * y_step, z_default);
          set_site(3, x_default + x_offset, y_start, z_default);
          wait_all_reach();

          move_speed = leg_move_speed;

          set_site(2, x_default + x_offset, y_start + 2 * y_step, z_up);
          wait_all_reach();
          set_site(2, x_default + x_offset, y_start, z_up);
          wait_all_reach();
          set_site(2, x_default + x_offset, y_start, z_default);
          wait_all_reach();
        }
    }

    // add by RegisHsu

    void body_left(int i)
    {
      set_site(0, site_now[0][0] + i, KEEP, KEEP);
      set_site(1, site_now[1][0] + i, KEEP, KEEP);
      set_site(2, site_now[2][0] - i, KEEP, KEEP);
      set_site(3, site_now[3][0] - i, KEEP, KEEP);
      wait_all_reach();
    }

    void body_right(int i)
    {
      set_site(0, site_now[0][0] - i, KEEP, KEEP);
      set_site(1, site_now[1][0] - i, KEEP, KEEP);
      set_site(2, site_now[2][0] + i, KEEP, KEEP);
      set_site(3, site_now[3][0] + i, KEEP, KEEP);
      wait_all_reach();
    }

    void hand_wave(int i)
    {
      float x_tmp;
      float y_tmp;
      float z_tmp;
      move_speed = 1;
      if (site_now[3][1] == y_start)
      {
        body_right(15);
        x_tmp = site_now[2][0];
        y_tmp = site_now[2][1];
        z_tmp = site_now[2][2];
        move_speed = body_move_speed;
        for (int j = 0; j < i; j++)
        {
          set_site(2, turn_x1, turn_y1, 50);
          wait_all_reach();
          set_site(2, turn_x0, turn_y0, 50);
          wait_all_reach();
        }
        set_site(2, x_tmp, y_tmp, z_tmp);
        wait_all_reach();
        move_speed = 1;
        body_left(15);
      }
      else
      {
        body_left(15);
        x_tmp = site_now[0][0];
        y_tmp = site_now[0][1];
        z_tmp = site_now[0][2];
        move_speed = body_move_speed;
        for (int j = 0; j < i; j++)
        {
          set_site(0, turn_x1, turn_y1, 50);
          wait_all_reach();
          set_site(0, turn_x0, turn_y0, 50);
          wait_all_reach();
        }
        set_site(0, x_tmp, y_tmp, z_tmp);
        wait_all_reach();
        move_speed = 1;
        body_right(15);
      }
    }

    void hand_shake(int i)
    {
      float x_tmp;
      float y_tmp;
      float z_tmp;
      move_speed = 1;
      if (site_now[3][1] == y_start)
      {
        body_right(15);
        x_tmp = site_now[2][0];
        y_tmp = site_now[2][1];
        z_tmp = site_now[2][2];
        move_speed = body_move_speed;
        for (int j = 0; j < i; j++)
        {
          set_site(2, x_default - 30, y_start + 2 * y_step, 55);
          wait_all_reach();
          set_site(2, x_default - 30, y_start + 2 * y_step, 10);
          wait_all_reach();
        }
        set_site(2, x_tmp, y_tmp, z_tmp);
        wait_all_reach();
        move_speed = 1;
        body_left(15);
      }
      else
      {
        body_left(15);
        x_tmp = site_now[0][0];
        y_tmp = site_now[0][1];
        z_tmp = site_now[0][2];
        move_speed = body_move_speed;
        for (int j = 0; j < i; j++)
        {
          set_site(0, x_default - 30, y_start + 2 * y_step, 55);
          wait_all_reach();
          set_site(0, x_default - 30, y_start + 2 * y_step, 10);
          wait_all_reach();
        }
        set_site(0, x_tmp, y_tmp, z_tmp);
        wait_all_reach();
        move_speed = 1;
        body_right(15);
      }
    }

    void head_up(int i)
    {
      set_site(0, KEEP, KEEP, site_now[0][2] - i);
      set_site(1, KEEP, KEEP, site_now[1][2] + i);
      set_site(2, KEEP, KEEP, site_now[2][2] - i);
      set_site(3, KEEP, KEEP, site_now[3][2] + i);
      wait_all_reach();
    }

    void head_down(int i)
    {
      set_site(0, KEEP, KEEP, site_now[0][2] + i);
      set_site(1, KEEP, KEEP, site_now[1][2] - i);
      set_site(2, KEEP, KEEP, site_now[2][2] + i);
      set_site(3, KEEP, KEEP, site_now[3][2] - i);
      wait_all_reach();
    }

    void body_dance(int i)
    {
      float x_tmp;
      float y_tmp;
      float z_tmp;
      float body_dance_speed = 2;
      sit();
      move_speed = 1;
      set_site(0, x_default, y_default, KEEP);
      set_site(1, x_default, y_default, KEEP);
      set_site(2, x_default, y_default, KEEP);
      set_site(3, x_default, y_default, KEEP);
      wait_all_reach();
      //stand();
      set_site(0, x_default, y_default, z_default - 20);
      set_site(1, x_default, y_default, z_default - 20);
      set_site(2, x_default, y_default, z_default - 20);
      set_site(3, x_default, y_default, z_default - 20);
      wait_all_reach();
      move_speed = body_dance_speed;
      head_up(30);
      for (int j = 0; j < i; j++)
      {
        if (j > i / 4)
          move_speed = body_dance_speed * 2;
        if (j > i / 2)
          move_speed = body_dance_speed * 3;
        set_site(0, KEEP, y_default - 20, KEEP);
        set_site(1, KEEP, y_default + 20, KEEP);
        set_site(2, KEEP, y_default - 20, KEEP);
        set_site(3, KEEP, y_default + 20, KEEP);
        wait_all_reach();
        set_site(0, KEEP, y_default + 20, KEEP);
        set_site(1, KEEP, y_default - 20, KEEP);
        set_site(2, KEEP, y_default + 20, KEEP);
        set_site(3, KEEP, y_default - 20, KEEP);
        wait_all_reach();
      }
      move_speed = body_dance_speed;
      head_down(30);
    }

    /*
      - microservos service /timer interrupt function/50Hz
      - when set site expected,this function move the end point to it in a straight line
      - temp_speed[4][3] should be set before set expect site,it make sure the end point
       move in a straight line,and decide move speed.
       ---------------------------------------------------------------------------*/
    void servo_service(void)
    {
      sei();
      static float alpha, beta, gamma;

      for (int i = 0; i < 4; i++)
      {
        for (int j = 0; j < 3; j++)
        {
          if (abs(site_now[i][j] - site_expect[i][j]) >= abs(temp_speed[i][j]))
            site_now[i][j] += temp_speed[i][j];
          else
            site_now[i][j] = site_expect[i][j];
        }

        cartesian_to_polar(alpha, beta, gamma, site_now[i][0], site_now[i][1], site_now[i][2]);
        polar_to_servo(i, alpha, beta, gamma);
      }

      rest_counter++;
    }

    /*
      - set one of end points' expect site
      - this founction will set temp_speed[4][3] at same time
      - non - blocking function
       ---------------------------------------------------------------------------*/
    void set_site(int leg, float x, float y, float z)
    {
      float length_x = 0, length_y = 0, length_z = 0;

      if (x != KEEP)
        length_x = x - site_now[leg][0];
      if (y != KEEP)
        length_y = y - site_now[leg][1];
      if (z != KEEP)
        length_z = z - site_now[leg][2];

      float length = sqrt(pow(length_x, 2) + pow(length_y, 2) + pow(length_z, 2));

      temp_speed[leg][0] = length_x / length * move_speed * speed_multiple;
      temp_speed[leg][1] = length_y / length * move_speed * speed_multiple;
      temp_speed[leg][2] = length_z / length * move_speed * speed_multiple;

      if (x != KEEP)
        site_expect[leg][0] = x;
      if (y != KEEP)
        site_expect[leg][1] = y;
      if (z != KEEP)
        site_expect[leg][2] = z;
    }

    /*
      - wait one of end points move to expect site
      - blocking function
       ---------------------------------------------------------------------------*/
    void wait_reach(int leg)
    {
      while (1)
        if (site_now[leg][0] == site_expect[leg][0])
          if (site_now[leg][1] == site_expect[leg][1])
            if (site_now[leg][2] == site_expect[leg][2])
              break;
    }

    /*
      - wait all of end points move to expect site
      - blocking function
       ---------------------------------------------------------------------------*/
    void wait_all_reach(void)
    {
      for (int i = 0; i < 4; i++)
        wait_reach(i);
    }

    /*
      - trans site from cartesian to polar
      - mathematical model 2/2
       ---------------------------------------------------------------------------*/
    void cartesian_to_polar(volatile float &alpha, volatile float &beta, volatile float &gamma, volatile float x, volatile float y, volatile float z)
    {
      //calculate w-z degree
      float v, w;
      w = (x >= 0 ? 1 : -1) * (sqrt(pow(x, 2) + pow(y, 2)));
      v = w - length_c;
      alpha = atan2(z, v) + acos((pow(length_a, 2) - pow(length_b, 2) + pow(v, 2) + pow(z, 2)) / 2 / length_a / sqrt(pow(v, 2) + pow(z, 2)));
      beta = acos((pow(length_a, 2) + pow(length_b, 2) - pow(v, 2) - pow(z, 2)) / 2 / length_a / length_b);
      //calculate x-y-z degree
      gamma = (w >= 0) ? atan2(y, x) : atan2(-y, -x);
      //trans degree pi->180
      alpha = alpha / pi * 180;
      beta = beta / pi * 180;
      gamma = gamma / pi * 180;
    }

    /*
      - trans site from polar to microservos
      - mathematical model map to fact
      - the errors saved in eeprom will be add
       ---------------------------------------------------------------------------*/
    void polar_to_servo(int leg, float alpha, float beta, float gamma)
    {
      if (leg == 0)
      {
        alpha = 90 - alpha;
        beta = beta;
        gamma += 90;
      }
      else if (leg == 1)
      {
        alpha += 90;
        beta = 180 - beta;
        gamma = 90 - gamma;
      }
      else if (leg == 2)
      {
        alpha += 90;
        beta = 180 - beta;
        gamma = 90 - gamma;
      }
      else if (leg == 3)
      {
        alpha = 90 - alpha;
        beta = beta;
        gamma += 90;
      }

      servo[leg][0].write(alpha);
      servo[leg][1].write(beta);
      servo[leg][2].write(gamma);
    }
```

NOTE: I am deleting some functions like `void sit(void)` stand as the maximum limit of characters was reached.

This is my esp32 code

```c++
    #include "Arduino.h"
    #include "WiFi.h"
    #include "Audio.h"

    #define I2S_DOUT      25
    #define I2S_BCLK      27
    #define I2S_LRC       26

    Audio audio;

    char data = 0;
    void setup()
    {

      Serial.begin(115200);

      WiFi.disconnect();
      WiFi.mode(WIFI_STA);
      WiFi.begin( "Physics", "299792458");

      while (WiFi.status() != WL_CONNECTED)
        delay(1500);

      audio.setPinout(I2S_BCLK, I2S_LRC, I2S_DOUT);
      audio.setVolume(100);
      audio.connecttospeech("Hello From akshit singh,,welcome to tapovan international school's project day ,,i am a smart walking robot ,you can also call me astra bot ", "en");

    }

    void loop(){
    if(Serial.available() > 0)
       {
          data = Serial.read();
          Serial.print(data);
          if(data == 'A')
            {
             audio.connecttospeech("hello everyone ,welcome to tapovan international school's project day ", "en");
             Serial.println("done");
            }

          else if(data == 'B')
            {
             audio.connecttospeech("BYE Bye everyone", "hi");
             Serial.println("done 2");
            }
          else if(data == 'C')
            {
             audio.connecttospeech("i am a smart walking robot ,you can also call me astra bot ", "hi");
             Serial.println("done 2");
            }

          else if(data == 'F')
            {
             audio.connecttospeech("going forward ,sir", "hi");
             Serial.println("done 2");
            }

          else if(data == 'b')
            {
             audio.connecttospeech("going backward ,sir", "hi");
             Serial.println("done 2");

            }
          else if(data == 'L')
            {
             audio.connecttospeech("moving left, sir", "hi");
             Serial.println("done 2");

            }
          else if(data == 'R')
            {
             audio.connecttospeech("moving right ,sir", "hi");
             Serial.println("done 2");

            }

       }

    {
      audio.loop();
    }

      }

    void audio_info(const char *info) {
      Serial.print("audio_info: "); Serial.println(info);
    }

```

title: communicating esp 32 with arduino uno

Answers: 1

body:
Well first of all you need to be aware that the UNO runs at 5V, and the ESP32 at 3V3, so you will need a level shifter in between the UNO and ESP32 unless you want to possibly damage your ESP32.

You can [create a bidirectional level shifter with an N-Channel mosfet and 2 resistors,][1]
or [buy a breakout board,][2] or use a chip like the GTL2010. Just note that not all bidirectional level shifters are the same, some require changing the direction with a pin(usually DIR), the GTL2010 is not one of those.

#### [Bitbanged UART][3]

Can be done on any pin.

Either a uni or bi directional level shifter will work just fine.

#### [SPI][4]
 Since your servos aren't being run by PWM/Timer hardware you could use the analog pins for a couple of your servos, and use the SPI peripheral which uses pins 10, 11, 12, and 13.

Your ESP32 is sending the commands, so you'd want to set up the ESP32 as the master, and the UNO as the slave.

Just like the BBUART option, either a uni or bi directional level shifter will work.

#### [I2C][5]

This uses the SDA and SCL pins next to VREF, which are really just A4 and A5. And again, you'd set the ESP32 to be the master, and the UNO to be the slave.

Be aware that you will need a **bidirectional** level shifter, a unidirectional will not work.

Although I don't recommend, there is a chance you may be able to get away without using a level shifter by attaching your pull-up resistors to 3V3. Just note, [for the atmega328P to register a high logic level, the input voltage needs to be 60% of VCC.][6] So if its running at 5V, it will take 3V to read high, which does have a chance at working. But if its running at 5V5, it will require 3V3 to register high and probably wont function properly if at all.

Another reason to use a level shifter is apparently the Arduino I2C library uses the internal pull-up resistors, so you would have to modify the library to disable them, so your ESP32 pins aren't pulled to 5V.

*BBUART is probably your best bet, it uses the least pins, and easiest to work with in code. All you need is a level shifter and you're good to go. But if you feel confident enough coding wise, you could try I2C without a level shifter, and if it doesn't work then purchase one.*

  [1]: https://cdn.sparkfun.com/r/400-400/assets/f/3/3/4/4/526842ae757b7f1b128b456f.png
  [2]: https://www.sparkfun.com/products/12009
  [3]: https://docs.arduino.cc/learn/built-in-libraries/software-serial
  [4]: https://www.arduino.cc/reference/en/language/functions/communication/spi/
  [5]: https://docs.arduino.cc/learn/communication/wire
  [6]: https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf#nameddest=28.2 DC Characteristics


body:
I have a project where I want to control a pump, I use an Arduino, connected to a driver L298N and I will connect the pin 5, 6, 7 of the arduino to the pin IN2, IN1, ENA of the driver respectively and the motor will be connected to the output

My materiel :
- Arduino Uno R3
- Multimeter
- Arduino IDE 2.1.1

The issue :
When I use the function analogWrite the voltage vary only between two value (0v or 5.5v).
The pin used was the Digital pin n°7, noted in the code 7.

The code :

```c++
#define PUMP_DIR_1 5
#define PUMP_DIR_2 6
#define PUMP_PWM 7
#define INVERTED 0

void setup() {
  Serial.begin(9600);
  pinMode(PUMP_PWM, OUTPUT);
}

void set_pump_speed(int speed){
  Serial.print("Set speed ");
  Serial.print(speed);
  Serial.print("\r\n");
  analogWrite(PUMP_PWM, speed);
}

void loop() {
  set_pump_speed(255);
  delay(3000);
  set_pump_speed(0);
  delay(3000);
  set_pump_speed(125);
  delay(3000);
}

```

As output I obtained :

>00:32:17.184 -> Set speed 0\
00:32:20.175 -> Set speed 125\
00:32:23.178 -> Set speed 255\
00:32:26.182 -> Set speed 0\
00:32:29.197 -> Set speed 125\
00:32:32.201 -> Set speed 255

From the mutlimeter I obtained :
>0v when speed = 0\
0v when speed = 125\
5.5v when speed = 255

The arduino is not wired to anything

title: When I use AnalogueWrite the voltage doesn't vary properly

Answers: 1

body: Pin 7 isn't a PWM pin. Use, say, pin 6 and you will get correct results. The PWM pins are marked with a "~" on the board.


body:
I'm using Arduino IDE 2.1.1 on a Mac M2 and it's failing to upload, No drive to deploy, I have tried 3 different Mac's, and multiple Picos & USB cables.

Summary of what I've done:

 - Loaded Example Blink application
 - Selected board Raspberry Pico W from Raspberry Pi Pico Arduino core 3.3.2
 - Port selection initially UF2 which shows connected and successfully uploads, then shows as /dev/cu.usbmodem1101

The first time I do the above the blink application works but any further uploads to /dev/cu.usbmodem1101 fail, with the following output:

    Resetting /dev/cu.usbmodem1101
    Converting to uf2, output size: 660992, start address: 0x2000
    Scanning for RP2040 devices
    No drive to deploy.
    Failed uploading: uploading error: exit status 1

I have only two ports available for upload

 - /dev/cu.Bluetooth-Incoming-Port
 - /dev/cu.usbmodem1101

It feels as if I'm either consistently missing some key configuration details or there's technical issues with Arduino IDE or the Pico's

title: Arduino IDE 2.1.1 Mac M2 - Fails to upload, No drive to deploy, Raspberry Pico

Answers: 0


body:
I wanted to connect my Arduino board to MATLAB although it recognized the Arduino board, I kept receiving the error that said:

"Internal error: The initialization of the server code is incorrect."

I got the recommendation of updating my Arduino board's firmware;
So I connected my board to my pc and opened Arduino IDE; It said that the Arduino Mega or Mega 2560 on com6 is connected.

I even uploaded the blink example to my board to make sure that it was connected and fully functioning. Which it was.

But in the above bar in Arduino IDE, "Tools" menu, when I select the "WIFI101/ Firmware Updater" It says that no supported board connected.
What should I do now?

*P.S:
I'm currently using Arduino IDE version 2.1.1 and MATLAB 2023a on Windows 11.*

I'm sorry, I'm really new to this and would appreciate your help.

title: Updating the firmware of Arduino Mega2560

Answers: 1

body:
https://www.mathworks.com/help/supportpkg/arduinoio/ug/configure-setup-for-arduino-hardware.html

This link has the instructions for connecting the Arduino board.  Look right at the first where it talks about the USB connection. Step 2 where you click program is the step where you are loading the server firmware onto the Mega.  That's the bit it sounds like you're missing.


body:
I'm developing an industrial project and my programming knowledge is limited to arduino.

I'm planning to use either Atmega328 or STM32F103C8T6 chip in my pcb and to program it using arduino IDE. My plan is just to use Arduino IDE to create sketches and programming the chip after burning arduino bootloader.

Is this concept viable for industrial environments? Are there any problems/challenges using this method?

title: Can arduino be used in industrial projects?

Answers: 4

body:
The chips should work fine, however it depends on how things are assembled, what parts are used, ambient temperature, cooling and electronic protection. For reference here is what I use:
Hobby: 0°C to 50°C
Commercial: 0 ° to 70 °C.
Industrial: −40 ° to 85 °C.
Military: −55 ° to 125 °C.
Automotive: -40°C to 175°C, location dependent.
Without a complete set of specifications, schematic, and component information I cannot give you a yes or no answer.

At this point you should realize it will not be a slam dunk simple project.

body:
Industrial environments can be hostile to electronics that aren't "hardened" against the potential hazards. There is no one answer to this without knowing the specific environment. Will it be controlling heavy electrical machinery (even if not switching the power). You'll need to know more about the intended environment to know whether and how you can harden your electronics to it.

But if nothing else, Arduino is terrific for prototyping things that, once the concept is proven, might then have to be re-built to a higher standard for production use.

body:
You don't talk about Arduino hardware. Your concern is the Arduino IDE.

Which is a lawyer's licensing topic. Might depend on the libraries you plan to use. And whether you want to hide the fact you're using (selling ?) open source software.

body:
I don't think there are any major problems with your proposal. The chips themselves will have documented limitations (specifications) that you would need to be aware of. I think you would find that most manufacturers of washing machines, toasters, TVs etc. do not also manufacture processor chips, so they too would be relying on commercially-available chips such as the ones you mentioned.

This brings us to the IDE. It is basically a "wrapper" around a C++ compiler which is available for anyone to use in any project. The Arduino libraries themselves may have licensing you would need to be aware of, the same as if you used a library not associated with the Arduino.

See this page: [Licensing for products based on Arduino](https://support.arduino.cc/hc/en-us/articles/4415094490770-Licensing-for-products-based-on-Arduino):

> ## Note:
>
> * You can freely use Arduino hardware and software for your personal purposes, or within your company or organization, with no restrictions. The rules described in this document apply only when you distribute products based on Arduino to third parties or you make them public in any form.
> * If you comply with the open-source licenses of Arduino, you can distribute your software/hardware products for free or commercially. This document provides a summary of such rules for your convenience and does not waive the need to get professional legal advice.

---

I am not a  lawyer, and if you are worried about the legal aspects I suggest you get legal advice. However I doubt that a small-scale project would warrant anyone getting their lawyers involved. For one thing, it would be hard to prove that the 0s and 1s on your chip were produced using the Arduino IDE, or any of its libraries.


body:
I trying to learn how to write arduino code for an ESP32 WROOM 32.  I want my esp32 to make an http request to a RESTFUL API i've set up. Thus, my esp32 will need wifi access. I was planning to use Bluetooth to tell my esp32 what wifi connection details to use and the specific address of the RESTFUL API end point.  I read some documenation online and people suggested that I would need `BluetoothSerial.h` for bluetooth connection, `<WiFi.h>` for wifi connection and `<HTTPClient.h>` for make HTTP requests.

But the moment I include all 3 packages and initialize a few variables and try to compile, my Arduino IDE gives me the following error:

```
text section exceeds available space in boardSketch uses 1428393 bytes (108%) of program storage space. Maximum is 1310720 bytes.

Global variables use 55740 bytes (17%) of dynamic memory, leaving 271940 bytes for local variables. Maximum is 327680 bytes.
Sketch too big; see https://support.arduino.cc/hc/en-us/articles/360013825179 for tips on reducing it.
Error compiling for board ESP32-WROOM-DA Module.
```

This is the code that caused the error:
```c++
#include "BluetoothSerial.h"
#include <WiFi.h>
#include <HTTPClient.h>

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
const char* ssid = "";
const char* pass = "";
String apiUrl = "";

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA); //Optional
  WiFi.begin(ssid, pass);

  while(WiFi.status() != WL_CONNECTED){
      delay(100);
  }
  SerialBT.begin("ESP32test"); //Bluetooth device name
}

void loop() {
  delay(20);
}
```

As you can see, I haven't even begun any real coding and I already get an error that suggest my ESP32 doesn't have necessary resources.

Did I do something wrong?  What else should I consider?

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

UPDATES

@jsotola

When I comment out the lines `BluetoothSerial SerialBT;` and `SerialBT.begin("ESP32test");`, then the program compiles and I see this message:

```
Wrote 726112 bytes (464336 compressed) at 0x00010000 in 7.0 seconds (effective 828.6 kbit/s)...
Hash of data verified.
```

So does that mean just those two lines of bluetooth related code takes up about 700kb?

@hcheung - If I change the `Tools > Partition Scheme` from `Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)` to `8MB with spiffs (3MB APP/1.5MB SPIFFS)`, then Arduino IDE compiles and writes the code to my ESP32.  However, when I try to use my Android phones Serial Bluetooth app to try to connect to the ESP32, I get the error `Connection failed: read failed, socket might closed or timeout, read ret:-1`.  So it seems the partition scheme affects bluetooth functionality.

I also tried changing the `Tools > Flash Size` from 4MB to 8MB.  And I get the same behaviour - 4MB doesn't compile.  But 8MB does compile.  But after it compiles my phone can't connect via bluetooth.

And just to be sure, the following code below from `File > Examples > BluetoothSerial > SerialtoSerialBT` only works with Flash Size 4MB and Default Partition Scheme of `Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)`

```
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;

void setup() {
  Serial.begin(115200);
  SerialBT.begin("ESP32test"); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");
}

void loop() {
  if (Serial.available()) {
    SerialBT.write(Serial.read());
  }
  if (SerialBT.available()) {
    Serial.write(SerialBT.read());
  }
  delay(20);
}
```

title: text section exceeds available space in board for esp32 + bluetooth + wifi + httpclient

Answers: 0


body:
I want to use the soft serial communication example.

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

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

But when I compile it, it sais:

    /home/xxx/Arduino/SoftwareSerialExample/aa/aa.ino:28:28: schwerwiegender Fehler: SoftwareSerial.h: Datei oder Verzeichnis nicht gefunden
    Kompilierung beendet.
    exit status 1
    Fehler beim Kompilieren für das Board Arduino Uno.

What is going there?
I  have a directory also with AFSoftSerial.h at /Arduino/libraries/AFSoftSerial/AFSoftSerial

title: Using Soft UART - how include library

Answers: 3

body:
Check to make sure you have the line:

    #include <SoftwareSerial.h>

... at the top of your Sketch.

Also, compare your code with that found on the [Arduino Software Serial Library web page here][1].

Finally, make sure your Arduino Application and all your Arduino Libraries are up to date.

  [1]: https://docs.arduino.cc/learn/built-in-libraries/software-serial

body:
> I have a directory also with AFSoftSerial.h at /Arduino/libraries/AFSoftSerial/AFSoftSerial

The code is looking for the "SoftwareSerial" library and that is the library you need include and call, not "AFSoftSerial". Or, if you intend to use AFSoftSerial, then change your code to say that instead.

body:
Download [Arduino SoftwareSerial library][1], extract it and put it into your libraries folder. Libraries folder is in your project folder. If you haven't changed project folder in Preferences, it will be in C:\Users\your_username\Documents\Arduino. Be careful that there are not two SoftwareSerial folders.
Then try to upload your code again.

  [1]: https://github.com/arduino/ArduinoCore-avr/tree/master/libraries/SoftwareSerial


body:
I'm trying to read the UID of MIFARE 13.5Mhz cards with MFRC522 lib and I have defined the following function for it.
```
void getUID() {
if (mfrc522.PICC_IsNewCardPresent() && mfrc522.PICC_ReadCardSerial()) {
  Serial.println("Scanned PICC's UID:");
  tag = "";
  for (byte i = 0; i < mfrc522.uid.size; i++)
   {
    tag.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    tag.concat(String(mfrc522.uid.uidByte[i], HEX));
   }
  tag.toUpperCase();
  Serial.println(tag);
  mfrc522.PICC_HaltA(); // Stop reading
}
}

```
this function works perfectly fine in void loop() but when I call it in the following web request my esp8266 crashes.

```
controlserver.on("/searchuid", HTTP_POST, [](AsyncWebServerRequest *request){

    transmit = request->arg("idcode");
    if (request->hasArg("configmodule")) {
    File file = SPIFFS.open("/inputString.txt", "r");
    if (!file) {
    Serial.println("Failed to open file");
    return;
    }
    getID();
    delay(500);
    Serial.println(tag);
    String content = file.readString();
    if (content.indexOf(tag) >= 0) {
    Serial.println("Found search string");
  } else {
    Serial.println("Did not find search string");
  }

    }
  });
```
and I cannot understand why, any help will be appreciated.

title: Problem with reading MIFARE 13.5Mhz with MFRC522 lib

Answers: 1

body:
Under ["Important Things To Remember"][1] in the ESPAsyncWebServer README:

> You can not use yield or delay or any function that uses them inside
> the callbacks

Your code calls `delay()` in the callback, and calls functions that you cannot know do not call `delay()` or `yield()`.

You need to rewrite your code to follow the instructions in the web server's documentation.

  [1]: https://github.com/me-no-dev/ESPAsyncWebServer#important-things-to-remember


body:
I'm looking to drive a high side driver at PWM frequency of 200Hz on a Teensy 4.1 with variable duty. The high side driver current sense pin is connected to an analogue pin on the Teensy. I want to sample an analogue reading only when the PWM output is low (HSD is on). I'll also likely need to read the analogue input with some delay after the PWM output has gone low (approximately 200uS).

How can I achieve this and guarantee synchronisation?

title: Teensy 4.1 Synchronized PWM - ADC sampling

Answers: 0


body:
Beginner with the Pi Pico here, but I studied electronics engineering and am reasonably hardware literate. I've used mbed online for a project prior to covid.

I want to use SPI to connect to a display using the ILI9488, (480 x 320 TFT panel), however, I cannot see how or where I would define SPI pins, and my understanding is that using SPI.h would default to Arduino pinouts - the uno etc being pin incompatible with the pi pico.

Do I need to trudge through the SPI.h file to try to work out how I set the pins manually? Or am I barking up the wrong tree?

I am using macOS, Arduino IDE 2.1.1 and have no issues connecting to the pico W. Please ask for any other clarification, I can provide a schematic of my design if it makes things easier. Love the pico but am finding it hard to use with C/C++.

Thanks,
KL

title: Using SPI on Pi Pico, Arduino IDE

Answers: 1

body:
You can read the actual SPI pins with the following sketch

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

    void loop() {
      Serial.print("MOSI: ");
      Serial.println(MOSI);
      Serial.print("MISO: ");
      Serial.println(MISO);
      Serial.print(" SCK: ");
      Serial.println(SCK);
      Serial.print("  SS: ");
      Serial.println(SS);
      Serial.println();
      delay(5000);
    }
```
As Juraj wrote, they are defined in the board files.

I have no experience with your ILI9488 display and the corresponding library. Many libraries allow you to use software defined pins. I would not recommend that, especially for a display with 480 x 320 pixels. You really need the speed of the hardware SPI.


body:
I am using the fantastic `ArduinoJson` library for working with JSON data on my ESP8266. I have been facing issues with **random software wdt resets** and have been investigating memory leaks wherever I can. I want to trim down my use of `Strings` and `DynamicJsonDocument`s as much as possible. So I thought of using automatic variables: char buffers: `char[N]` and `StatitcJsonDocument`s instead.

I am using the ArduinoJson assitant service to help me figure out how many bytes I should reserve. The following is one response payload, I am expecting to receive:

```
// char input[MAX_INPUT_LENGTH];

StaticJsonDocument<128> doc;

DeserializationError error = deserializeJson(doc, input, MAX_INPUT_LENGTH);

if (error) {
  Serial.print(F("deserializeJson() failed: "));
  Serial.println(error.f_str());
  return;
}

int statusCode = doc["statusCode"]; // 200
bool needUpdate = doc["needUpdate"]; // true
const char* message = doc["message"]; // "update required"

JsonObject data = doc["data"];
const char* data_deviceId = data["deviceId"]; // "DLD00005"
const char* data_user_fw_version = data["user_fw_version"]; // "0.0.0"
const char* data_new_fw_version = data["new_fw_version"]; // "0.0.5"

```

As you can see I am using a `char [N]` type as the input, which is in fact being copied using `strncpy()` from the `https.getString().c_str()` from the response of a previous `https.POST()` request. My issue is that **I do not know how much memory I should reserve for the `char[N]` array**, ie what should be the value of `N`? The reasons I ask is that I am getting a `deserialization() failed: IncompleteInput` error, which I'm pretty sure is because the `char[N]` buffer is not large enough. So my question is if the StaticJsonDocument object is `128` bytes, then how big should I make the `char[N]` buffer (is there any relation between the sizes)? Or should I just go with an arbitrarily large value like `char[512]` which I want to avoid to avoid stack overflows?
```
StaticJsonDocument<128> payload;
char payloadSerial[???];
...
int status = https.POST(payloadSerial);
strncpy(payloadSerial, https.getString().c_str(), sizeof(payloadSerial));
DeserializationError error = deserializeJson(payload, payloadSerial, sizeof(payloadSerial));
if (error) {
    Monitor.print(F("DeserializeJson() failed: "));
    Monitor.println(error.f_str());
}
```

title: ArduinoJson library: how much space to allocate for serialized buffer?

Answers: 1

body:
You're asking about code that looks like this:
```
StaticJsonDocument<128> payload;
char payloadSerial[???];
...
int status = https.POST(payloadSerial);
strncpy(payloadSerial, https.getString().c_str(), sizeof(payloadSerial));
DeserializationError error = deserializeJson(payload, payloadSerial, sizeof(payloadSerial));
```

The documentation for [`deserializeJson()`](https://arduinojson.org/v6/api/json/deserializejson/?cmdf=deserializeJson) shows that it can accept a `String` directly:
```
DeserializationError deserializeJson(JsonDocument& doc, const String& input);
```

So there's no need to copy `https.getString().c_str()` into `payloadSerial`. You can just pass the `String` that `https.getString()` returns:

```
StaticJsonDocument<128> payload;

int status = https.POST(request_body);

DeserializationError error = deserializeJson(payload, https.getString());
```

You were using the same character array here for both the body of the request that you passed to `POST()` and for deserializing the JSON response. While this is okay, for clarity I changed the `POST` call to use something else as the character array is completely unnecessary for processing the response.

Even if `deserializeJson()` didn't accept a `String` type as an argument, you still wouldn't need to copy the response into a buffer. You could just pass `https.getString().c_str()`:
```
StaticJsonDocument<128> payload;

int status = https.POST(request_body);

DeserializationError error = deserializeJson(payload, https.getString().c_str());
```

You **really** should check the value of `status`. It indicates whether the POST succeeded or not. If it failed, you should report that and the reason for the failure, and not attempt to process the returned payload as there is no returned payload.


body:
I am looking for help with ATtiny85 coding. The project I am working on is using an Arduino Nano and I want to switch to an ATtiny85.

The code below works with the Nano but not with the ATtiny85. I am relatively new to Arduinos and have done a few projects with success but this is my first time using an ATtiny.

I will try to explain. When the code is running on a Nano
- It is checking for a number between 1 and 32 in the EEPROM at address 0.
- If the number is outside either value it will generate a random number between 18 and 32.
- I then check to see if the value at address 0 in the EEPROM is less than or equal to 0, if not it will decrement that value and store the new value in address 0.
- Once the value is at 0 or less a separate value is generated for a time delay.
- Once that time delay has occurred pin 7 outputs power for 1 second and stops.
- Once that has occurred a new random number is generated and stored in address 0.
- To decrement the value the Nano is powered off and on again and the check is made.

I have tested this code with a Nano multiple times and with pin 7 connected to an led it turns on and off, resets and begins again. When I load this code onto an ATtiny85 and run the same test the led will not turn on, also I get an error with the `Serial.begin(9600)` and anything else starting with Serial, so I comment them out and it compiles and uploads just fine. I have the Spark Fun AVR programmer and was able to get the ATtiny to blink an led using a simple led blink sketch but that's as far as I got. I need some help.
```c++
    #include <EEPROM.h>  // Include the EEPROM library

    void setup() {
      Serial.begin(9600);          // Initialize the serial communication
      pinMode(7, OUTPUT);          // Use digital pin 7 as output
      randomSeed(analogRead(0));   // Seed the random number generator with a random value
      int value = EEPROM.read(0);  // Read the value stored in EEPROM address 0

      if (value <= -1 || value > 32) {  // If the value is not between 1 and 32
        int new_Value = random(18, 32);  // Generate a new random number between 18 and 32
        EEPROM.write(0, new_Value);    // Store the new value in EEPROM address 0
        Serial.println("Generated a new random number: " + String(new_Value));
      }

      else if (value <= 0) {     // Check if the random value is less than or equal to 0
        value--;                 // If no then decrement the value
        EEPROM.write(0, value);  // Write the new value to EEPROM address 0
        Serial.println("Random number from EEPROM: " + String(value));
      }

      else {
        int time_delay = random(1, 25);  // Generate random number for time delay
        Serial.println("Generated Time Delay: " + String(time_delay));

        delay(1000 * time_delay);

        digitalWrite(7, HIGH);
        delay(1000);
        digitalWrite(7, LOW);

        int new_Value = random(18, 32);  // Generate new random day value
        EEPROM.write(0, new_Value);    // Write new value to EEPROM address 0
        Serial.println("Generated a new random number: " + String(new_Value));
      }
    }
    void loop() {
    }
```

Sketch used for LED blink
```c++
    void setup() {
      pinMode(0, OUTPUT);
    }

    void loop() {
      digitalWrite(0, HIGH);
      delay(5000);
      digitalWrite(0, LOW);
      delay(5000);
```

title: Need help with ATtiny85 code

Answers: 0


body:
I am trying to use the timer interrupt on an Arduion Uno.

Here is a imple example code for displaying a progressive digit on a lcd display, which is updated with timer interupt every second:

```
#include <LCD_I2C.h>

LCD_I2C lcd(0x27);
volatile bool timerFlag = false; // Timer-Flag (timer-Interrupt)
int displayWidth = 16; // display width
int digit = 0; // current digit

void setup() {
  lcd.begin();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Initializing...");

  noInterrupts();
  TCCR1A = 0;
  TCCR1B = (1 << CS12) | (1 << CS10); // set Prescaler to 1024
  TCNT1 = 0;
  OCR1A = 15624; // should be 1 second with a prescaler of 102
  TIMSK1 |= (1 << OCIE1A); // Enable timer interrupt
  interrupts();
}

ISR(TIMER1_COMPA_vect) {
  timerFlag = true;
}

void loop() {
  static int position = 0;
  char displayString[17]; // +1 null termination

  if (timerFlag) {
    lcd.clear(); // clear display

    // update digit and progress
    digit = (digit + 1) % 10;
    position = (position + 1) % (displayWidth + 1);
    memset(displayString, ' ', displayWidth);
    displayString[displayWidth] = '\0'; add null termination
    displayString[position] = '0' + digit; // Character for the current digit

    // Show updated progress on the display
    lcd.setCursor(0, 1);
    lcd.print(displayString);

    timerFlag = false;
  }
}
```
The values for setting up he inteupt timer 1 for 1 second is arround everywhere.
BUt the updates generated by this code is clearly much slower than 1 second, it's more about 4 seconds.
So i did a comparison with a delay based version of the same example:
```
#include <LCD_I2C.h>

LCD_I2C lcd(0x27);
int displayWidth = 16; // display width

void setup() {
  lcd.begin();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("Initializing...");
}

void loop() {
  for (int digit = 0; digit < 10; digit++) {
    char displayString[17]; // +1 null termination
    int position = digit % (displayWidth + 1);

    // Update progression
    memset(displayString, ' ', displayWidth);
    displayString[displayWidth] = '\0'; // add null termination
    displayString[position] = '0' + digit; // Character for the current digit

    // Show updated progress on the display
    lcd.clear(); // Clear display
    lcd.setCursor(0, 1);
    lcd.print(displayString);

    delay(1000);
  }
}
```
This one works as expected and updates every second.

So what is wrong with my interrupt settings?

title: Timer interrupt setup for one second is too slow (~ 4 seconds)

Answers: 2

body: It is ignoring this `OCR1A = 15624;` and simply rolling over at 65535 instead., hence the error factor of 4. You have to set the wave generation mode as CTC in registers TCCR1A/B.

body:
There is a flag in `TCCR1A/B` called `WGM12` which sets the `wave generation mode (WGM)` to `Clear Timer on Compare Match (CTC)`.
This causes the timer to count up to the value in OCR1A and then automatically reset to 0.

This flag was forgotten, so the interrupt simply ignores the setting `OCR1A = 15624;` and counts through to 65535, which corresponds to the observed factor of about 4.
Therefore the setting line for TCCR1B must be changed to
```
TCCR1B = (1 << WGM12) | (1 << CS12) | (1 << CS10);
// Set CTC mode and set Prescaler to 1024
```
Now the interrupt is triggered correctly every second.


body:
I am using a Portenta Arduino Breakout Board (<https://store.arduino.cc/products/arduino-portenta-breakout>) that is connected to the Portenta H7 (<https://store.arduino.cc/products/portenta-h7>) for a project I am working on. The project requires me to use three GPS sensors (Adafruit Ultimate GPS sensors, <https://learn.adafruit.com/adafruit-ultimate-gps/overview>) and connect each to its own UART ports on the Portenta Breakout Board. I am only using UART0, UART1, and UART2 (which are respectively Serial, Serial1, and Serial2).

To be able to get data, I've been using this example code from the Arduino IDE:

```c++
// Test code for Ultimate GPS Using Hardware Serial
// (e.g. GPS for Leonardo, Flora or FeatherWing)
//
// This code shows how to test a passthru between USB and hardware serial
//
// Tested and works great with the Adafruit GPS FeatherWing
// ------> https://www.adafruit.com/products/3133
// or Flora GPS
// ------> https://www.adafruit.com/products/1059
// but also works with the shield, breakout
// ------> https://www.adafruit.com/products/1272
// ------> https://www.adafruit.com/products/746
//
// Pick one up today at the Adafruit electronics shop
// and help support open source hardware & software! -ada

// what's the name of the hardware serial port?
#define GPSSerial Serial1

void setup() {
  // make this baud rate fast enough to we aren't waiting on it
  Serial.begin(115200);

  // wait for hardware serial to appear
  while (!Serial) delay(10);

  // 9600 baud is the default rate for the Ultimate GPS
  GPSSerial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    char c = Serial.read();
    GPSSerial.write(c);
  }
  if (GPSSerial.available()) {
    char c = GPSSerial.read();
    Serial.write(c);
  }
}
```
This code works for Serial1, and I get data when I connect a GPS to the UART1 port of breakout board. When I call for Serial, or Serial2, changing
`#define GPSSerial Serial1` to `#define GPSSerial Serial` or `#define GPSSerial Serial2` the code will upload with no errors, but I am not receiving any data from the GPS when it is connected to the respective UART port (UART0 and UART2).

I checked to see if the data is automatically only coming from UART1 port but it will not show anything when I am calling for Serial or Serial2, which should be expected.

Does anyone know how to deal with this issue? Could UART0 and UART2 ports not be transferring data to the Portenta H7 board which could be why I am not seeing any data?

Please let me know if I should clarify anything.

title: Why are the UART ports not working on my Portenta breakout Board?

Answers: 0


body:
Currently i have a project that forced me to make a program that receives several data from Serial Input using Interrupt in Arduino. I use Arduino as the receiver and ESP32 as the sender through Hardware Serial. The program i have written for Arduino is as posted at [Serial Input Basics][1] with a few changes as written below :
```
const byte numChars = 32;
char receivedChars[numChars];
char tempChars[numChars];        // temporary array for use when parsing

// variables to hold the parsed data
char messageFromPC[numChars] = {0};
unsigned long sendDataPrevMillis = 0;
int controlCondition = 0;
int droneCondition = 0;
int gasValue = 0;
int pitchValue = 0;
int rollValue = 0;
int yawValue = 0;

boolean newData = false;

void setup() {
  attachInterrupt(digitalPinToInterrupt(1), handleInterrupt, RISING);
  Serial.begin(57600);
}

void loop() {

  Serial.print("Control Condition :");
  Serial.print(controlCondition);
  Serial.print(" Drone Condition :");
  Serial.print(droneCondition);
  Serial.print(" Roll:");
  if(rollValue < 1500)Serial.print("<<<");
  else if(rollValue > 1500)Serial.print(">>>");
  else Serial.print("-+-");
  Serial.print(rollValue);
  Serial.print("  Pitch:");
  if(pitchValue > 1500)Serial.print("^^^");
  else if(pitchValue < 1500)Serial.print("vvv");
  else Serial.print("-+-");
  Serial.print(pitchValue);

  Serial.print("  Gas:");
  if(gasValue < 1500)Serial.print("vvv");
  else if(gasValue > 1500)Serial.print("^^^");
  else Serial.print("-+-");
  Serial.print(gasValue);

  Serial.print("  Yaw:");
  if(yawValue < 1500)Serial.print("<<<");
  else if(yawValue > 1500)Serial.print(">>>");
  else Serial.print("-+-");
  Serial.println(yawValue);
}

void handleInterrupt(){
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (Serial.available() && newData == false) {
        rc = Serial.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }

        else if (rc == startMarker) {
            recvInProgress = true;
        }
    }
    if (newData == true) {

    strcpy(tempChars, receivedChars);
    char * strtokIndx; // this is used by strtok() as an index

    strtokIndx = strtok(tempChars, ",");
    controlCondition = atoi(strtokIndx);

    strtokIndx = strtok(NULL, ",");
    droneCondition = atoi(strtokIndx);

    strtokIndx = strtok(NULL, ",");
    gasValue = atoi(strtokIndx);

    strtokIndx = strtok(NULL, ",");
    pitchValue = atoi(strtokIndx);

    strtokIndx = strtok(NULL, ",");
    rollValue = atoi(strtokIndx);

    strtokIndx = strtok(NULL, ",");
    yawValue = atoi(strtokIndx);

    newData = false;
    }
}
```
The data will be sent from ESP32 to change the values of `controlCondition`, `droneCondition`, `gasValue`, `pitchValue`, `rollValue`, and `yawValue`.

I have tried it and the Interrupt cannot be triggered. The Interrupt should be triggered whenever the `controlCondition`, `droneCondition`, `gasValue`, `pitchValue`, `rollValue`, or `yawValue` change its value. Any idea what should I do? or is there something wrong with my code?

Note that the code that i showed in the `void loop()` is just an example code. The real code is more complex with so many calculations involved. The variables that I mentioned are the important variables for the calculations.

 [1]: https://forum.arduino.cc/t/serial-input-basics-updated/382007

title: How to use Interrupt in Arduino to receive the data from Serial Input

Answers: 2

body:
Why do you want to use an interrupt anyway? The serial hardware already generates an interrupt, and inside that ISR the incoming byte is placed into a buffer.

I presume you have a main loop where you are doing other stuff, and you want to react when some interesting serial data arrives.

I have an example of processing serial data without blocking on [my page about serial processing](http://www.gammon.com.au/serial) which I reproduce below:

<!-- language: c++ -->

    /*
    Example of processing incoming serial data without blocking.

    Author:   Nick Gammon
    Date:     13 November 2011.
    Modified: 31 August 2013.

    Released for public use.
    */

    // how much serial data we expect before a newline
    const unsigned int MAX_INPUT = 50;

    void setup ()
      {
      Serial.begin (115200);
      } // end of setup

    // here to process incoming serial data after a terminator received
    void process_data (const char * data)
      {
      // for now just display it
      // (but you could compare it to some value, convert to an integer, etc.)
      Serial.println (data);
      }  // end of process_data

    void processIncomingByte (const byte inByte)
      {
      static char input_line [MAX_INPUT];
      static unsigned int input_pos = 0;

      switch (inByte)
        {

        case '\n':   // end of text
          input_line [input_pos] = 0;  // terminating null byte

          // terminator reached! process input_line here ...
          process_data (input_line);

          // reset buffer for next time
          input_pos = 0;
          break;

        case '\r':   // discard carriage return
          break;

        default:
          // keep adding if not full ... allow for terminating null byte
          if (input_pos < (MAX_INPUT - 1))
            input_line [input_pos++] = inByte;
          break;

        }  // end of switch

      } // end of processIncomingByte

    void loop()
      {
      // if serial data available, process it
      while (Serial.available () > 0)
        processIncomingByte (Serial.read ());

      // do other stuff here like testing digital input (button presses) ...

      }  // end of loop

It looks to me like you are looking for an "end marker" which is when you want to react to what you have received earlier. Like in my example above, you could just pick up individual bytes in the main loop, and when the end marker arrives the whole line can be processed. I used a newline for and end marker, but you could change that to '>'.

---

The problems with an interrupt like you are doing are:

* The interrupt will fire on the first bit (out of 10) and so there won't be any serial data yet, and your program will uselessly look for serial data which won't be there.

* You are calling Serial.read() which won't return anything because while you are in **your** ISR the main serial ISR won't be able to fire.

* Your ISR is doing too much.

* Serial line is normally HIGH, and transitions to LOW (the start bit) when the byte starts, so you should be looking for FALLING and not RISING.

---

I strongly suggest you rework to just check for serial available in the main loop, as I have done, and process it when the end delimiter arrives.

body:
Don't do anything in your `loop()` function *except* calling other functions, each of which decides - for one part of your process - whether or not it is time to do that part. If so, do that part; if not, return immediately to the loop function.

Read [my answer to a similar question][1] that talks more about how to do this. This technique is called non-blocking programming. Your code should poll rapidly for whatever it might need to respond to, but should not wait for any of those things to occur. If you do that, you will likely not need the kind of response that would require interrupts.

Also, the print statements in your `loop()` will slow down (block) execution and may keep your PID from responding adequately. If you need them for debugging your calculations, you can wrap them in `#if DEBUG` ... `#endif` statements so one `#define DEBUG` can easily include them them when you need to (knowing that your device control will be affected) and remove them for operational tests. If you must keep some print statements live, make only as few as necessary live at one time, make sure to use the highest baud-rate possible, and keep them as brief as possible.

  [1]: https://arduino.stackexchange.com/questions/60759/how-to-rotate-two-or-more-steppers-simultaneously-by-giving-array-of-angles/66380#66380


body:
I'm encountering a problem with my Arduino Nano board. When I attempt to upload sketches to the board using the Arduino IDE, only the Power LED lights up, and the TX and RX LEDs remain inactive. I've tried several troubleshooting steps, including reinstalling drivers, using different USB cables, and trying different USB ports on my computer. Despite these efforts, I haven't been able to resolve the issue.

Board Details:
- Arduino Nano with ATmega microcontroller
- Power LED is lit when the board is connected
- "L" LED blinks rapidly during upload
- TX and RX LEDs are not lighting up during upload

Troubleshooting Steps Taken:
- Reinstalled Arduino IDE and drivers
- Tried multiple USB cables and ports
- Verified COM port selection in Arduino IDE
- Checked USB-Serial converter chip for damage

I'm reaching out to the community for help and guidance. Has anyone else encountered this issue? What further steps should I take to diagnose and resolve this problem? Any insights or suggestions would be greatly appreciated.

title: Arduino Nano TX and RX LEDs Not Lighting Up During Upload

Answers: 1

body: They many times will not light because of the bit pattern being sent and the short time the bit is active to light the LED. If it is uploading code without errors you are good to go.  Quick test, If not try another Arduino and see if it uploads or not. If not it is your computer or a bad cable otherwise it is a bad Arduino.


body:
I am using the below code to check temperatures from 36 DS18B20 sensors using Arduino Mega 2560.  If any one of them go above 50 deg. celsius, then it sets the output pin to HIGH.

I am trying to run the code on Proteus 8.13, but during the same run, sometimes the virtual terminal prints -127 deg. celsius for all, sometimes right for some sensors and wrong for the other ones (usually the wrong value is also 85 deg. celsius). Is it something wrong with the simulator, or my code?

```c++
    #include <OneWire.h>
    #include <DallasTemperature.h>

    #define NUM_SENSORS 36
    #define START_PIN 14
    #define OUTPUT_PIN 2

    OneWire oneWire[NUM_SENSORS];
    DallasTemperature sensors[NUM_SENSORS];

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

      for (int i = 0; i < NUM_SENSORS; i++) {
        oneWire[i] = OneWire(START_PIN + i);
        sensors[i] = DallasTemperature(&oneWire[i]);
        sensors[i].begin();
      }

      pinMode(OUTPUT_PIN, OUTPUT);
      digitalWrite(OUTPUT_PIN, LOW);
    }

    void loop() {
      float celsius[NUM_SENSORS];

      for (int i = 0; i < NUM_SENSORS; i++) {
        sensors[i].requestTemperatures();
        celsius[i] = sensors[i].getTempCByIndex(0);
      }

      bool aboveThreshold = false;

      for (int i = 0; i < NUM_SENSORS; i++) {
        if (celsius[i] > 50.0) {
          aboveThreshold = true;
          break;
        }
      }

      digitalWrite(OUTPUT_PIN, aboveThreshold);

      printSensorData(celsius);

      delay(1000);
    }

    void printSensorData(float celsius[]) {
      for (int i = 0; i < NUM_SENSORS; i++) {
        Serial.print("Sensor ");
        Serial.print(i + 1);
        Serial.print(": ");
        Serial.print(celsius[i]);
        Serial.print(" C  ");
        Serial.print(sensors[i].toFahrenheit(celsius[i]));
        Serial.println(" F");
      }
    }
```

title: DS18B20 Error in Proteus 8.13

Answers: 1

body: The -127 indicates a fault on the hardware side, generally an open circuit. Also it sounds like your pull up resistor is not installed or way out of range.For the Mega. UNO and other 5V units 4.7K is a good size and 3.3K for the 3V3 systems. Note the resistor goes from VCC to the sensor output.


body:
I have a Chinese hybrid solar inverter that exposes an **rj45 input** which talks the serial protocol (Baud rate 2400, no parity, 8 bits, 1 stop bit). I need my Arduino (say, Mega or whatever, does not really matter) to talk to it. What would be the best option to connect an Arduino board to the rj45 input such that it would be available as `Serial` in the code?

Basically, I'd like the following piece to code to "just work":

```
 uint8_t query[] = {81, 80, 73, 71, 83, 183, 169, 13};
 Serial.write(query, sizeof(query)); // Write some bytes to a device, i.e. send a request.
 Serial.flush();

 while (!Serial.available()); // Wait for device to reply.
 String str = Serial.readString();
    // do someting with `str`...
```

In other words, I am looking for a hardware solution to connect my Arduino board to the rj45 input without introducing an unnecessary complication (if any).

title: Make my Arduino (Mega or whatever is better for the task) to be able to read and write `Serial` data to a **rj45** port

Answers: 1

body: Look up the data sheet for the max232. It is an old chip that does what you need.  ARDUINOs serial work at 0 to 5v and the old fashioned standard for serial data works at +-12v.  Also, there will be a high low inversion.