body:
I'm trying to connect an Arduino board to IDE on Ubuntu, and I have the following driver log:

    [  543.412356] usb 1-2: USB disconnect, device number 3
    [  549.593729] usb 1-2: new full-speed USB device number 7 using xhci_hcd
    [  549.748438] usb 1-2: New USB device found, idVendor=1a86, idProduct=7523, bcdDevice= 2.54
    [  549.748449] usb 1-2: New USB device strings: Mfr=0, Product=2, SerialNumber=0
    [  549.748454] usb 1-2: Product: USB2.0-Serial
    [  549.750234] ch341 1-2:1.0: ch341-uart converter detected
    [  549.750859] usb 1-2: ch341-uart converter now attached to ttyUSB0
    [  550.347356] input: BRLTTY 6.4 Linux Screen Driver Keyboard as /devices/virtual/input/input20
    [  550.462814] usb 1-2: usbfs: interface 0 claimed by ch341 while 'brltty' sets config #1
    [  550.463418] ch341-uart ttyUSB0: ch341-uart converter now disconnected from ttyUSB0
    [  550.463437] ch341 1-2:1.0: device disconnected
As a result no ports are found, any suggestion?

title: Error while trying to connect CH341 driver

Answers: 1

body:
Solved, thanks to this [article][1]

    sudo apt autoremove brltty

remove the conflict and now the board is visible
  [1]: https://0xsuk.github.io/posts/2022-07-19-how-to-install-ch340-on-ubuntu-22.04/


body:
I'm making a project in which I have to control a mini car and get sensor information via bluetooth. I'd like to be able to control the mini car with the computers keyboard (w,a,s,d), but I was not able to find a library that could help with that, like the "keyboard" library does in python for example

Ex.

```
import keyboard

# when w is pressed, the car goes forward

If (keyboard.is_pressed("w"):

    Forward()
```

The "keyboard" library in arduino does not seem to work the same way. And I didn't find any other libraries nor tutorials about it online.

How to make it work?

title: Control esp32 via keyboard keys

Answers: 1

body:
In case someone is trying to do the same, I came up with a way to make it work. In ArduinoIDE, after the setup, the loop checks if the bluetooth serial is available and has received anything, if it receives the right variables for movement, it passes the instruction to the motors connected to the Arduino through an l298n module.

The code is as follows:
```
// variáveis para conexão bluetooth // variables for bluetooth connection
#include <SoftwareSerial.h>

SoftwareSerial SerialBT(8, 9);
char valorDoBluetooth;

//variáveis para o uso dos motores // variables for the use of motors
// motor 1
const byte in1 = 2;
const byte in2 = 4;
const byte enA = 3;
//motor 2
const byte in3 = 5;
const byte in4 = 7;
const byte enB = 6;

int velocidade = 100; // motor speed (up to 255)

int componentesOut[6] = { in1, in2, enA, in3, in4, enB }; // list created to setup the variables more easily

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

  // loop to set pins to Output
  for (int n = 0; n < 6; n++) {
    pinMode(componentesOut[n], OUTPUT);
  }
}

void loop() {
  // Read data from the Bluetooth module
  if (SerialBT.available()) {
    valorDoBluetooth = SerialBT.read(); // bluetooth Value

    if (valorDoBluetooth == 'F' || valorDoBluetooth == 'T' || valorDoBluetooth == 'D' || valorDoBluetooth == 'E' || valorDoBluetooth == 'P')  // if SerialBt recieved movement value
    {
      movimento(); // movement
    }
  }
}

void movimento() {
  if (valorDoBluetooth == 'F') {
    Serial.println("Frente");  // Forward
    frente();
  } else if (valorDoBluetooth == 'T') {
    Serial.println("Trás");  // Backwards
    tras();
  } else if (valorDoBluetooth == 'D') {
    Serial.println("Direita");  // Right
    direita();
  } else if (valorDoBluetooth == 'E') {
    Serial.println("Esquerda");  // Left
    esquerda();
  } else if (valorDoBluetooth == 'P') {
    Serial.println("Parar");  // Stop
    parar();
  }
  delay(1);
}

void frente() {
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  digitalWrite(enB, velocidade);
}
void tras() {
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  digitalWrite(enB, velocidade);
}
void direita() {
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  digitalWrite(enB, velocidade);
}
void esquerda() {
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  digitalWrite(enB, velocidade);
}
void parar() {
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(enA, velocidade);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
  digitalWrite(enB, velocidade);
}
```

To be able to control it via the PC keyboards, I connected the PC to the device through bluetooth, then see which COM it is connected to in bluetooth configurations of control panel, and use this the COM number on a Python code that's able to communicate with the device.

The Python code is as follows:
```
import serial
import time
import keyboard

# Replace 'COMX' with the actual COM port assigned to the HC-05 module / Esp device on your PC. More info at https://pyserial.readthedocs.io/en/latest/shortintro.html
ser = serial.Serial('COM8', 9600, timeout=1)

flagMovido = True # flag that checks if the motors are finished moving before changing directions

def controle(event):
    global flagMovido

    if event.event_type == keyboard.KEY_DOWN: # if a key is pressed:
        if (event.name == "w" or event.name == "a" or event.name == "s" or event.name == "d") and flagMovido: # if movement keys are pressed and motors are finished moving to any other direction:
            flagMovido = False # motors started moving

            if event.name == "w" and not flagMovido:
                ser.write(b'F')

                print('frente') # Forward

            elif event.name == "a" and not flagMovido:
                ser.write(b'E')

                print('esquerda') # Left

            elif event.name == "s" and not flagMovido:
                ser.write(b'T')

                print('trás') # Backwards

            elif event.name == "d" and not flagMovido:
                ser.write(b'D')

                print('direita') # Right

    elif event.event_type == keyboard.KEY_UP: # if a key is released:
        if (event.name == "w" or event.name == "a" or event.name == "s" or event.name == "d") and not flagMovido: # if movement keys are released and motors are moving to some direction

            flagMovido = True # motors are finished moving

            ser.write(b'P')

            print('parado') # Stop

print('START')

def main():
    while True:
        data = ser.readline().decode().strip()

        keyboard.hook(controle)
        time.sleep(.001)

        if data:
            print(f"Recebido: {data}") # prints data if any received. Used to print the sensor values received.

if __name__ == "__main__":
    main()
```
obs:
* The code runs fine, but may present some problems if you press to many keys at a time, since it was made to handle one direction at a time. But the movement bools will help with that and prevents it from happening to certain extent. Though in specific cases is should be improved.
* I ended up using a HC05 module with Arduino, but the code also woks for Esp. But if connecting to an Esp, the ```ser = serial.Serial('COM8', 9600, timeout=1)``` line should be changed to the way it connects to the Esp. More info at the link provided.


body:
I have an Arduino Lilypad with this simple code where I try to write a simple message to the serial console. The baud rate is set to 9600 both in the code as well as in the serial console and I'm using the [FTDI UART tool](https://www.sparkfun.com/products/10275).
However, the output I'm receiving is corrupted and I'm not sure what could be the cause. Any ideas or suggestions are welcome. Thanks!

```

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

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(3000);
  Serial.write("Hello World");
}

```

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

Arduino is connected to the FTDI tool as shown here [![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/erAtj.png
  [2]: https://i.stack.imgur.com/axOsO.png

title: Lilypad sends corrupted data on Serial

Answers: 1

body:
It looks like the wrong baud rate. That often results in garbage characters. You said in a comment that halving the baud rate on the Arduino end seemed to synchronize the baud rates, and you could see proper characters.

I'm a bit puzzled by that because you were evidently able to upload the sketch in the first place. Therefore the baud rate was correct during the uploading process.

Looking in the file `boards.txt` which you should find somewhere in your Arduino installation, there appear to be a number of Lilypad variants. Perhaps you inadvertently chose the wrong one in the "Board" menu in the IDE?

It looks like the correct baud rate was used for the uploading, but the code generated by the compiler (because of settings passed by the IDE) thought that the board was running at half the speed it actually was (so it set the baud rate clocks to run faster), so by reducing the baud rate in the Serial.begin they became in sync.

You could just live with the difference, or try experimenting with choosing different Lilypad board types.

If the baud rate is wrong, probably the delays will be wrong too, whether or not that matters is up to you.


body:
I have a program that only do get and post to a controller via an ethernet port. My problem is that after a certain amount of loop in the program, i got this error:

    Guru Meditation Error: Core  1 panic'ed (Unhandled debug exception).
    Debug exception reason: Stack canary watchpoint triggered (loopTask)
    Core  1 register dump:
    PC      : 0x4012d2c8  PS      : 0x00060b36  A0      : 0x8012e241  A1      : 0x3ffc9cb0
    A2      : 0x3ffca070  A3      : 0x3ffca1ec  A4      : 0x3ffc9d70  A5      : 0x3ffca4bc
    A6      : 0x00000000  A7      : 0x00000018  A8      : 0x80130298  A9      : 0x3ffc9fd0
    A10     : 0x00000000  A11     : 0x00000000  A12     : 0x00000030  A13     : 0x3ffba06c
    A14     : 0x3ffc49ac  A15     : 0x00000008  SAR     : 0x0000001c  EXCCAUSE: 0x00000001
    EXCVADDR: 0x00000000  LBEG    : 0x40089a78  LEND    : 0x40089a83  LCOUNT  : 0x00000000

    Backtrace: 0x4012d2c5:0x3ffc9cb0 0x4012e23e:0x3ffca010 0x4012e2b3:0x3ffca030 0x4012e2ed:0x3ffca050 0x4012a3d4:0x3ffca070 0x40124912:0x3ffca170 0x40124a0a:0x3ffca1e0 0x40124a56:0x3ffca290 0x40124bd9:0x3ffca310 0x401208d5:0x3ffca330 0x401209b6:0x3ffca4e0 0x40120a95:0x3ffca500 0x40120b69:0x3ffca570 0x4011e28e:0x3ffca590 0x4011f22b:0x3ffca5c0 0x40121c38:0x3ffca610 0x40122911:0x3ffca650 0x401230c7:0x3ffca840 0x401210ef:0x3ffca9a0 0x40121336:0x3ffcaa00 0x4011be1d:0x3ffcaa20 0x40119881:0x3ffcaac0 0x401198bb:0x3ffcaae0 0x400d9af1:0x3ffcab00 0x400d93c9:0x3ffcad80 0x400d943f:0x3ffcadc0 0x400d94ce:0x3ffcae00 0x4016e30d:0x3ffcae20 0x400dab06:0x3ffcae40 0x400dbddb:0x3ffcae70 0x400dbffb:0x3ffcaee0 0x400d5949:0x3ffcaf00 0x400d63e0:0x3ffcb3b0 0x400ddd91:0x3ffcbc10

And here is the Decoded stack:

    0x4012d2c5: mbedtls_sha512_software_process at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/port/sha/parallel_engine/esp_sha512.c line 292
    0x4012e23e: mbedtls_internal_sha512_process at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/port/sha/parallel_engine/esp_sha512.c line 252
    0x4012e2b3: mbedtls_sha512_update_ret at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/port/sha/parallel_engine/esp_sha512.c line 367
    0x4012e2ed: mbedtls_sha512_update_ret at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/port/sha/parallel_engine/esp_sha512.c line 342
    0x4012a3d4: mbedtls_sha512_ret at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/sha512.c line 461
    0x40124912: entropy_update at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/entropy.c line 184
    0x40124a0a: entropy_gather_internal at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/entropy.c line 289
    0x40124a56: mbedtls_entropy_func at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/entropy.c line 369
    0x40124bd9: mbedtls_entropy_func at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/entropy.c line 338
    0x401208d5: mbedtls_ctr_drbg_reseed_internal at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ctr_drbg.c line 380
    0x401209b6: mbedtls_ctr_drbg_reseed at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ctr_drbg.c line 418
    0x40120a95: mbedtls_ctr_drbg_random_with_add at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ctr_drbg.c line 536
    0x40120b69: mbedtls_ctr_drbg_random at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ctr_drbg.c line 603
    0x4011e28e: mpi_fill_random_internal at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/bignum.c line 2501
    0x4011f22b: mbedtls_mpi_random at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/bignum.c line 2594
    0x40121c38: ecp_randomize_jac at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ecp.c line 1719
    0x40122911: ecp_mul_comb at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ecp.c line 2084
    0x401230c7: mbedtls_ecp_mul_restartable at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ecp.c line 2761
    0x401210ef: mbedtls_ecdh_compute_shared at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ecdh.c line 127
    0x40121336: mbedtls_ecdh_calc_secret at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ecdh.c line 685
    0x4011be1d: mbedtls_ssl_handshake_client_step at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ssl_cli.c line 3753
    0x40119881: mbedtls_ssl_handshake_step at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ssl_tls.c line 5770
    0x401198bb: mbedtls_ssl_handshake at /Users/ficeto/Desktop/ESP32/ESP32S2/esp-idf-public/components/mbedtls/mbedtls/library/ssl_tls.c line 5808
    0x400d9af1: start_ssl_client(sslclient_context*, IPAddress const&, unsigned int, char const*, int, char const*, bool, char const*, char const*, char const*, char const*, bool, char const**) at /Users/martin/Library/Arduino15/packages/esp32/hardware/esp32/2.0.11/libraries/WiFiClientSecure/src/ssl_client.cpp line 271
    0x400d93c9: WiFiClientSecure::connect(IPAddress, unsigned short, char const*, char const*, char const*, char const*) at /Users/martin/Library/Arduino15/packages/esp32/hardware/esp32/2.0.11/libraries/WiFiClientSecure/src/WiFiClientSecure.cpp line 140
    0x400d943f: WiFiClientSecure::connect(char const*, unsigned short, char const*, char const*, char const*) at /Users/martin/Library/Arduino15/packages/esp32/hardware/esp32/2.0.11/cores/esp32/Printable.h line 33
    0x400d94ce: WiFiClientSecure::connect(char const*, unsigned short) at /Users/martin/Library/Arduino15/packages/esp32/hardware/esp32/2.0.11/libraries/WiFiClientSecure/src/WiFiClientSecure.cpp line 117
    0x4016e30d: WiFiClientSecure::connect(char const*, unsigned short, int) at /Users/martin/Library/Arduino15/packages/esp32/hardware/esp32/2.0.11/libraries/WiFiClientSecure/src/WiFiClientSecure.cpp line 122
    0x400dab06: HTTPClient::connect() at /Users/martin/Library/Arduino15/packages/esp32/hardware/esp32/2.0.11/cores/esp32/WString.h line 339
    0x400dbddb: HTTPClient::sendRequest(char const*, unsigned char*, unsigned int) at /Users/martin/Library/Arduino15/packages/esp32/hardware/esp32/2.0.11/libraries/HTTPClient/src/HTTPClient.cpp line 601
    0x400dbffb: HTTPClient::GET() at /Users/martin/Library/Arduino15/packages/esp32/hardware/esp32/2.0.11/libraries/HTTPClient/src/HTTPClient.cpp line 518
    0x400d5949: getPumpInfo() at /Users/martin/Library/CloudStorage/Dropbox/ErabliTEK/Martin/Arduino/LILYGO_POE_TEST/LILYGO_POE_TEST.ino line 204
    0x400d63e0: loop() at /Users/martin/Library/CloudStorage/Dropbox/ErabliTEK/Martin/Arduino/LILYGO_POE_TEST/LILYGO_POE_TEST.ino line 307
    0x400ddd91: loopTask(void*) at /Users/martin/Library/Arduino15/packages/esp32/hardware/esp32/2.0.11/cores/esp32/main.cpp line 50

And here is the code:

    #include <Arduino.h>
    // #include <ETH.h>
    #include <ETHClass.h>       //Is to use the modified ETHClass
    #include <SPI.h>
    #include <SD.h>
    #include "utilities.h"          //Board PinMap

    #include <WiFi.h>
    #include <WiFiClientSecure.h>
    #include <HTTPClient.h>
    #include <ArduinoJson.h>

    WiFiClientSecure client;
    HTTPClient https;

    String AIOHTTP_SESSION = "";
    bool loggedIn = false;
    unsigned long lastFetch;

    //Change to IP and DNS corresponding to your network, gateway
    IPAddress staticIP(192, 168, 202, 8);
    IPAddress gateway(192, 168, 202, 1);
    IPAddress subnet(255, 255, 255, 0);
    IPAddress dns(192, 168, 202, 1);

    static bool eth_connected = false;

    #define TXD1 02
    #define RXD1 14

    float atmos = 28.0;
    char pumpInfo[1024];
    char sentPumpInfo[1024];
    char trends[1024];

    void WiFiEvent(WiFiEvent_t event)
    {
        switch (event) {
        case ARDUINO_EVENT_ETH_START:
            Serial.println("ETH Started");
            //set eth hostname here
            ETH.setHostname("esp32-ethernet");
            break;
        case ARDUINO_EVENT_ETH_CONNECTED:
            Serial.println("ETH Connected");
            break;
        case ARDUINO_EVENT_ETH_GOT_IP:
            Serial.print("ETH MAC: ");
            Serial.print(ETH.macAddress());
            Serial.print(", IPv4: ");
            Serial.print(ETH.localIP());
            if (ETH.fullDuplex()) {
                Serial.print(", FULL_DUPLEX");
            }
            Serial.print(", ");
            Serial.print(ETH.linkSpeed());
            Serial.println("Mbps");
            eth_connected = true;
            loggedIn = false;
            break;
        case ARDUINO_EVENT_ETH_DISCONNECTED:
            Serial.println("ETH Disconnected");
            eth_connected = false;
            break;
        case ARDUINO_EVENT_ETH_STOP:
            Serial.println("ETH Stopped");
            eth_connected = false;
            break;
        default:
            break;
        }
    }

    void startPump(){
      https.begin(client, "https://192.168.202.10/api/pump/start");
      https.addHeader("Content-Type", "application/json");
      https.addHeader("Cookie", AIOHTTP_SESSION);
      int httpsResponseCode = https.POST("{}");
      if(httpsResponseCode == 200){
        Serial.println("Succefully started the pump!");
      }else{
        Serial.print("HTTPS Response code: ");
        Serial.println(httpsResponseCode);
        String response = https.getString();
        Serial.print(response);
        Serial.println();
      }
      https.end();
    }

    void stopPump(){
      https.begin(client, "https://192.168.202.10/api/pump/stop");
      https.addHeader("Content-Type", "application/json");
      https.addHeader("Cookie", AIOHTTP_SESSION);
      int httpsResponseCode = https.POST("{}");
      if(httpsResponseCode == 200){
        Serial.println("Succefully stopped the pump!");
      }else{
        Serial.print("HTTPS Response code: ");
        Serial.println(httpsResponseCode);
        String response = https.getString();
        Serial.print(response);
        Serial.println();
      }
      https.end();
    }

    void getPressureSetPoint(){
      https.begin(client, "https://192.168.202.10/api/pressure-setpoint");
      https.addHeader("Cookie", AIOHTTP_SESSION);
      unsigned long _start = millis();
      int httpsResponseCode = https.GET();
      if(httpsResponseCode == 200){
        Serial.print("Succefully fetched Pressure Setpoint in: ");
        Serial.print(millis() - _start);
        Serial.println(" ms");
        String response = https.getString();
        DynamicJsonDocument _doc(2048);
        DeserializationError err = deserializeJson(_doc, response);
        if(err == DeserializationError::Ok){
          DynamicJsonDocument _tmp(sizeof(pumpInfo));
          err = deserializeJson(_tmp, pumpInfo);
          _tmp["pressureSetpoint"] = serialized(String(atmos - (_doc["value"].as<float>() / 33.8639), 1));
          char buf[sizeof(pumpInfo)];
          serializeJson(_tmp, buf);
          strcpy(pumpInfo, buf);
        }
      }else{
        Serial.print("Error fetching Pressure Setpoint: ");
        Serial.print("HTTPS Response code: ");
        Serial.println(httpsResponseCode);
        String response = https.getString();
        Serial.print(response);
        Serial.println();
      }
      https.end();
    }

    void getPumpInfo(){
      https.begin(client, "https://192.168.202.10/api/pump-info");
      https.addHeader("Cookie", AIOHTTP_SESSION);
      unsigned long _start = millis();
      int httpsResponseCode = https.GET();
      if(httpsResponseCode == 200){
        Serial.print("Succefully fetched Pump Info in: ");
        Serial.print(millis() - _start);
        Serial.println(" ms");
        String response = https.getString();
        DynamicJsonDocument _doc(3072);
        DeserializationError err = deserializeJson(_doc, response);
        if(err == DeserializationError::Ok){
          DynamicJsonDocument _tmp(sizeof(pumpInfo));
          err = deserializeJson(_tmp, pumpInfo);
          _tmp["name"] = _doc["name"];
          _tmp["model"] = _doc["model"];
          _tmp["serial"] = _doc["serialNumber"];
          _tmp["status"] = _doc["status"];
          _tmp["runningHours"] = _doc["runningHours"];
          char buf[sizeof(pumpInfo)];
          serializeJson(_tmp, buf);
          strcpy(pumpInfo, buf);
        }else{
          Serial.print("deserializeJson() returned ");
          Serial.println(err.c_str());
        }
      }else if(httpsResponseCode == -11){
        lastFetch = lastFetch - 5000;
      }else{
        Serial.print("Error fetching Pump Info: ");
        Serial.print("HTTPS Response code: ");
        Serial.println(httpsResponseCode);
        String response = https.getString();
        Serial.print(response);
        Serial.println();
      }
      https.end();
    }

    void setAtmos(float value){
      atmos = value;
      https.begin(client, "https://192.168.202.10/api/atmospheric-pressure");
      https.addHeader("Content-Type", "application/json");
      https.addHeader("Cookie", AIOHTTP_SESSION);
      DynamicJsonDocument doc(200);
      doc["unitId"] = 23;
      doc["value"] = atmos;
      char payload[200];
      serializeJson(doc, payload, sizeof(payload));
      int httpsResponseCode = https.POST(payload);
      if(httpsResponseCode == 200){
        Serial.print("setAtmos setted to: ");
        Serial.print(atmos);
        Serial.println(" InHg!");
        //Setting gauge pressure!!
        doc.clear();
        doc["active"] = true;
        serializeJson(doc, payload, sizeof(payload));
        https.setURL("https://192.168.202.10/api/gauge-pressure");
        httpsResponseCode = https.POST(payload);
        if(httpsResponseCode == 200){
          Serial.println("Gauge pressure set succesfully!");
        }else{
          Serial.print("Error setting gauge pressure: ");
          Serial.print(httpsResponseCode);
          Serial.print(" with value: ");
          Serial.println(payload);
        }
      }
      https.end();
    }

    void setup(){
        Serial.begin(115200);
        Serial1.begin(115200, SERIAL_8N1, RXD1, TXD1);
        client.setInsecure();
        WiFi.onEvent(WiFiEvent);

    #ifdef ETH_POWER_PIN
        pinMode(ETH_POWER_PIN, OUTPUT);
        digitalWrite(ETH_POWER_PIN, HIGH);
    #endif

    #if CONFIG_IDF_TARGET_ESP32
        if (!ETH.begin(ETH_ADDR, ETH_RESET_PIN, ETH_MDC_PIN,
                       ETH_MDIO_PIN, ETH_TYPE, ETH_CLK_MODE)) {
            Serial.println("ETH start Failed!");
        }
    #else
        if (!ETH.beginSPI(ETH_MISO_PIN, ETH_MOSI_PIN, ETH_SCLK_PIN, ETH_CS_PIN, ETH_RST_PIN, ETH_INT_PIN)) {
            Serial.println("ETH start Failed!");
        }
    #endif

        if (ETH.config(staticIP, gateway, subnet, dns, dns) == false) {
            Serial.println("Configuration failed.");
        }

    }
    unsigned int functionID = 0;
    void loop(){
      if (eth_connected) {
        if((millis() - lastFetch) >= 500){
          switch(functionID){
            case 0:
              getPumpInfo();
              break;
            case 1:
              getPressureSetPoint();
              break;
          }
          functionID++;
          if(functionID > 1){
            functionID = 0;
          }
          lastFetch = millis();
        }
      }
      if(strcmp(pumpInfo, sentPumpInfo) != 0){
        Serial.println(pumpInfo);
        Serial1.print(pumpInfo);
        strcpy(sentPumpInfo, pumpInfo);
      }
      if(Serial1.available()){
        StaticJsonDocument<2048> doc;
        DeserializationError err = deserializeJson(doc, Serial1);
        if(err == DeserializationError::Ok){
          if(doc.containsKey("command")){
            if(doc["command"] == "startPump"){
              startPump();
            }else if(doc["command"] == "stopPump"){
              stopPump();
            }else if(doc["command"] == "setAtmos"){
              setAtmos(doc["value"]);
            }
          }
          serializeJson(doc, Serial);
          Serial.println();
        }else{
          Serial.print("deserializeJson() returned ");
          Serial.println(err.c_str());
        }
      }
    }

And here is the data i try to retrieve in json:

    {"name": "Shop", "location": null, "notes": null, "serialNumber": "API854338", "controllerSerial": "S5204001517", "model": "GHS350VSD+", "brand": "AtlasCopco", "productName": "HEX@", "status": "Off", "runningHours": 4, "commissioningDate": "2023-01-20T11:35:20.0Z", "datetime": "2023-08-21T15:02:18.860279+00:00", "hlpFeatures": [], "llpFeatures": [], "contactPhone": null, "contactEmail": null, "contactEntity": null, "loadCounters": {"load": 0.0, "time1to20": 6956.10009765625, "time20to40": 6353.2998046875, "time40to60": 703.5999755859375, "time60to80": 330.79998779296875, "time80to100": 2112.60009765625, "ratio1to20": 42.26987838745117, "ratio20to40": 38.60668182373047, "ratio40to60": 4.276423931121826, "ratio60to80": 2.010370969772339, "ratio80to100": 12.842491149902344}, "modelVersion": "v111", "containerVersions": [{"name": "netx90", "version": "0.1.0"}, {"name": "yocto", "version": "0.7.0"}, {"name": "llp", "version": "60793910172e1a27f5a9eb9c-710-001-5fee0bb632c7e68bda513826b3144484bffac665"}, {"name": "v111", "version": "0.12.15"}, {"name": "opcua", "version": "0.3.1"}, {"name": "centralcontroller", "version": "0.3.7"}, {"name": "value-wheel", "version": "0.3.9"}, {"name": "webui-cms-import-v111", "version": "0.2.39-15"}, {"name": "teamviewer", "version": "0.2.1"}, {"name": "iot-client", "version": "0.5.15"}, {"name": "composer", "version": "0.4.3"}, {"name": "webui-scheduler", "version": "0.2.39-15"}, {"name": "webui-front", "version": "0.2.39-15"}, {"name": "webui-api", "version": "0.2.39-15"}, {"name": "llp-interface", "version": "2579fd3d"}, {"name": "proxy-intern", "version": "0.3.2"}, {"name": "proxy", "version": "0.3.4"}, {"name": "database-postgres", "version": "0.2.0"}, {"name": "broker-extern", "version": "0.2.0"}, {"name": "updater", "version": "0.3.24-5"}, {"name": "system-manager", "version": "0.5.8-3"}, {"name": "broker", "version": "0.2.0"}, {"name": "docker-ui", "version": "0.4.0"}], "pressureSetpointPresent": true}

The GET call for this data is very long! It take about 4000ms in average!

Does anyone know what i am doing wrong ??

Thanx a lot!

title: What can be the reason for a Stack canary watchpoint triggered (loopTask) on a https get() command?

Answers: 0


body:
I am using a 74HC595 shift register IC connected to my Arduino board to drive 8 RGB LED modules. The LED modules have built in resistors and require a +5V at anode which I provide from the Arduino. Following is a rough schematic of the circuit, the pins numbers correspond to those on the Arduino UNO microcontroller.
[![Circuit Schematic][1]][1]
Following is a small code for the same:
```c++

const int latchPin = 8;
const int clockPin = 12;
const int dataPin = 13;
const int redValuePin = 9;
const int greenValuePin = 10;
const int blueValuePin = 11;

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(redValuePin, OUTPUT);
  pinMode(greenValuePin, OUTPUT);
  pinMode(blueValuePin, OUTPUT);
  Serial.begin(9600);
  Serial.println("Reset");
}

void loop() {
  analogWrite(redValuePin, 0);
  analogWrite(greenValuePin, 255);
  analogWrite(blueValuePin, 255);
  if (Serial.available() > 0) {
    int bitToSet = Serial.read() - 48;
    registerWrite(bitToSet, HIGH);
  }
}

void registerWrite(int whichPin, int whichState) {
  byte bitsToSend = 0x00;
  digitalWrite(latchPin, LOW);
  bitWrite(bitsToSend, whichPin, whichState);
  Serial.println(bitsToSend);
  shiftOut(dataPin, clockPin, MSBFIRST, bitsToSend);
  digitalWrite(latchPin, HIGH);
}
```

However, the shift register does not seem to be shifting values. This is verified as **only O0 is high in MSBFIRST** and **only O7 is high in LSBFIRST** mode of `shiftOut()`, irrespective of the `bitsToSend` value. That is, only the first line is high. Is there any reason in the hardware/software that caused this, or do I just have a faulty IC?

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

title: Shift register 74595 does not shift values

Answers: 0


body:
I'm using a DF Mini Player with my Arduino Uno project I keep getting stuck on the same point - how to trigger my LED sequence.  I discovered, through some google searching, that utilizing the BUSY pin on the DF Player Mini would return data that I was hoping I could use to trigger the sequence.

My code is as follows:

```c++
// Wed 17 Aug 2023; Modified BUSY_PIN INPUT_PULLUP to INPUT to accomodate for player keeping track of it's own state of HIGH or LOW, fixed BAUD rate mismatch

#include <DFRobotDFPlayerMini.h>
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
#define BUTTON_PIN 4
#define BUSY_PIN 8

bool buttonState = 1; // Normally high, goes low when pressed
bool previousButtonState = 1; // Because we will test when CHANGED

///////////////Create the Player object/////////////////////////////
DFRobotDFPlayerMini player;

static const uint8_t PIN_MP3_TX = 2; // UNO Tx connects module's RX
static const uint8_t PIN_MP3_RX = 3; // UNO Rx connects module's TX
SoftwareSerial softwareSerial(PIN_MP3_RX, PIN_MP3_TX);

//////////////////////////////////////////////////////////////////

/////////////////Create Fairy Light Variables////////////////////

int led = 11;           // the PWM pin the LED is attached to
int brightness = 3;    // how bright the LED is
int fadeAmount = 2;    // how many points to fade the LED by

////////////////////////////////////////////////////////////////

int busyState = 0;
int prevBusyState = 0;

void setup()
{

  ///////////////////////Button Trigger//////////////////////////

  pinMode (BUTTON_PIN, INPUT_PULLUP); // Avoids need for resistor

  ///////////////////////////////////////////////////////////////

  pinMode(BUSY_PIN, INPUT); //check to see if song is still playing

  ///////////////////////Music Functions/////////////////////////

  // Init USB serial port for debugging
  Serial.begin(9600);
  Serial.println();
  // Init serial port for DFPlayer Mini
  softwareSerial.begin(9600);
  delay(1000);

  // Start communication with DFPlayer Mini
  if (!player.begin(softwareSerial, true, false)) {  //Use softwareSerial to communicate with mp3.
    Serial.println(F("Unable to begin:"));
    Serial.println(F("1.Please recheck the connection!"));
    Serial.println(F("2.Please insert the SD card!"));
    while (true) {
      delay(0);
    }
  }

  busyState = digitalRead(BUSY_PIN);
  prevBusyState = busyState;

  ///////////// End Music Functions/////////////////////////////

  ////////////////////Fairy Lights//////////////////////////////

  pinMode(led, OUTPUT); //declare pin 11 to be an output

  //////////////////End Fairy Light/////////////////////////////
}

void loop()
{

  buttonState = digitalRead(BUTTON_PIN);
  busyState = digitalRead(BUSY_PIN);

  if (busyState != prevBusyState) {
    if (busyState == LOW) {
      Serial.print ("song is playing. lights are go");
      Serial.print('\n');
      Serial.print('\r');

      /////////////////Fairy Light Fading Routine////////////////////////
      // set the brightness of pin 10:
      analogWrite(led, brightness);

      // change the brightness for next time through the loop:
      brightness = brightness + fadeAmount;

      // reverse the direction of the fading at the ends of the fade:
      if (brightness <= 1 || brightness >= 240) {
        fadeAmount = -fadeAmount;
      }
      // wait for 30 milliseconds to see the dimming effect
      delay(45);
      /////////////////////////////////////////////////////////////////
    }
    prevBusyState = busyState;
  }

  if (buttonState == LOW && previousButtonState == HIGH)
  {
    /////////////////////Play Song///////////////////////

    // The following NOT inside the previous if()
    // Set volume to maximum (0 to 30).
    player.volume(23);
    // Play the first MP3 file on the SD card
    player.play(1); // i.e. usually file 0001.mp3

    ////////////////////////////////////////////////////

  }
  previousButtonState = buttonState;
}
```

When I check my Serial Monitor, I am getting my print `song is playing. lights are go`. However the LED (which are [Fairy Lights][1]) do not follow the sequence. In fact, they just stay on the entire time. I even added a 10k resistor to Data input 11 - which only dampened the light intensity but otherwise did no other effect.

I'm not sure if I will need to control these lights with another board, code is not sufficient or if I'm missing something in the wiring. I would have thought the power source would be the issue, but if the LED's are getting power through data, I would think the resistor would take care of that issue?

  [1]: https://www.amazon.com/Ariceleo-Operated-Christmas-Centerpiece-Decoration/dp/B09DSSVW8B/ref=sxin_16_pa_sp_search_thematic_sspa?content-id=amzn1.sym.1c86ab1a-a73c-4131-85f1-15bd92ae152d:amzn1.sym.1c86ab1a-a73c-4131-85f1-15bd92ae152d&cv_ct_cx=fairy+lights+battery+operated&keywords=fairy+lights+battery+operated&pd_rd_i=B07S3R6MKJ&pd_rd_r=78d2a0b9-d42a-47a0-96fa-c8e8fd0b9412&pd_rd_w=CD0lO&pd_rd_wg=z4fO9&pf_rd_p=1c86ab1a-a73c-4131-85f1-15bd92ae152d&pf_rd_r=NTFNZG4KPBNGVJXQRTT0&qid=1692734739&sbo=RZvfv//HxDF+O5021pAnSA==&sprefix=fairy+,aps,96&sr=1-4-364cf978-ce2a-480a-9bb0-bdb96faa0f61-spons&sp_csd=d2lkZ2V0TmFtZT1zcF9zZWFyY2hfdGhlbWF0aWM&th=1

title: How to use a DF Mini Player Busy Pin to start an LED Sequence?

Answers: 0


body:
I've been asked to interface with some LED strips that use SM16704 pixel chips.

A site search here doesn't show any mentions of this chip, so I wonder if anyone knows if they're compatible with the more common ones like WS281x and can be addressed using FastLED or other library?

Edit:

**[Here's][1]** the datasheet for the -PB version of the chip. I can't find one for a plain 16704 but I don't think the protocol is any different.

  [1]: http://www.jad-leds.com/web/userfiles/download/SM16704PB-Datasheet.pdf

title: Addressable LEDs using SM16704

Answers: 1

body: The best data I can find says that this chip / protocol is compatible with the WS2813 and should require only a minor tweak, if any.


body:
How to detect, if **Serial** is really connected to listening PC program? (on **atmega32u4**)

I need to connect from PC to **Arduino Micro Pro** over USB `Serial` and disconnect again and not slow down the Arduino with timeouting on all `Serial.print`.

## Difference from other ##
Not same as https://arduino.stackexchange.com/questions/42977/arduino-leonardoatmega32u4-detecting-if-usb-is-connected-to-a-computer
* difference is what should happen after disconnecting PC program
    * "it is still connected to PC" (so it is **OK**, solved there)
    * "it is not listend to" and timeouting (so it is **BAD**, asked **here**)
* I tried the both solutions mentioned there (UDADDR & _BV(ADDEN)) and (USBSTA & _BV(VBUS)) as well as (Serial) - it behave the same from my point of view
    * fast before `screen` connects, fast when `screen` connected, **slow** after `screen` ends, fast when `screen` reconnected

## Details ##
I have **Arduino Micro Pro** managing a lot of things at its own, but I want sometimes connect to it via USB from my computer. I open `screen /dev/ttyACM0 115200` and get a lot of debugging info and so on. Then I close the `screen` and let it work in peace. But there is problem with timeouts - when I stop listening, it waits for me and everything is terribly slow, until I connect there again.

Here is my loop
```c++
 void loop() {
  DoSomethingImportant(); // it works
  StatusOff(); // Green LED off, Yellow On
  if (displayTime()) {  // print debug only on new second
   if (Serial) {   // ######## If there is somebody listening ... #########
    Serial.print(F("Ctrl: "));Serial.print(W00.Used());
    Serial.print(F("); R1/W1: "));Serial.print(R01.Used());Serial.print(F("/"));Serial.print(W01.Used());Serial.print(F(" ("));Serial.print(R01.Total_Count());Serial.print(F("/"));Serial.print(W01.Total_Count());
    Serial.print(F("); R2/W2: "));Serial.print(R02.Used());Serial.print(F("/"));Serial.print(W02.Used());Serial.print(F(" ("));Serial.print(R02.Total_Count());Serial.print(F("/"));Serial.print(W02.Total_Count());
    Serial.print(F("); R3/W3: "));Serial.print(R03.Used());Serial.print(F("/"));Serial.print(W03.Used());Serial.print(F(" ("));Serial.print(R03.Total_Count());Serial.print(F("/"));Serial.print(W03.Total_Count());
    Serial.println(F("); "));
   };
  };
  StatusOn(); // Green LED on, Yellow Off
 }
```
## Problem ##
When I connect the Arduino to PC (so it gets powered, I do not have much of the rest HW completed yet), it starts to do Something Important as fast as it can and every second the yellow LED blinks too fast to see that Green was off. It is OK.

Then I connect with `screen /dev/ttyACM0 115200` and it gets new long line every second. Still the Green looks all time on and Yellow can be seen just blink. Still OK.

Then I end `screen` and it went **slow** - Yellow is on for like 7 second, while Green is on for 1 sec. And it is BAD.

Then I connect with `screen /dev/ttyACM0 115200` and it gets new long line every second. The Green looks all time on and Yellow can be seen just blink. Again OK.

## Question ##
How to detect, if I am connected or not?

Or maybe better, how to prevent the terrible slowdown, when I am not connected?

title: How to detect, if Serial is really connected to listening PC program? (on atmega32u4)

Answers: 2

body:
I can reproduce this on Ubuntu, however it seems to be an anomaly of the screen program. If I use this small Python program to listen to the port, the Micro doesn't seem to slow down.

<!-- language: lang-python -->

    import serial

    ser = serial.Serial('/dev/ttyACM0', 115200)  # Adjust the serial port accordingly

    while True:
        if ser.readable():
            line = ser.readline().decode().strip()
            print (line)

You may need to import pyserial into Python, for example:

<!-- language: lang-bash -->

    python -m pip install pyserial

My Arduino test code was:

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

    const byte LED_PIN = 5;  // some pin for an LED

    void setup() {
      Serial.begin (115200);
      pinMode (LED_PIN, OUTPUT);

    }

    void loop() {
      digitalWrite (LED_PIN, HIGH);
      delay (250);
      digitalWrite (LED_PIN, LOW);
      delay (250);

      Serial.println(F("Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n"
       "Ut molestie quam cursus, feugiat massa eget, lobortis ante.\n"
       "Nulla semper nisi a pretium finibus. Proin rutrum accumsan massa sit amet gravida.\n"
       "Etiam mollis, ipsum ac sagittis aliquam, sem urna euismod ipsum,\n"
       "eget accumsan orci sapien ornare felis. Nulla ex felis, facilisis in tincidunt at,\n"
       "dignissim vitae ligula. Aliquam facilisis tristique velit,\n"
       "a scelerisque turpis mollis quis. Nulla porta, mi vel ornare feugiat,\n"
       "mauris ligula commodo felis, in congue orci neque a est. "));

    }

By looking at the rate of flashes of the LED I can see that it doesn't slow down when running the Python program, or if you Ctrl+C to exit the Python program.

However it does slow down if you attach to the USB using `screen` and then kill it.

---

I don't think the Arduino can per se know whether or not a program on the PC happens to be listening to the USB port or not. That is a function of what is happening in the operating system, not a function of the USB hardware.

---

Another approach which I haven't tested might be to get your Python program to periodically (eg. for each line) send a character, and get the Arduino to check for serial input. If no serial input (ie. not prompting character) then don't echo the debugging data.

---

Another approach (and possibly the simplest) is just to have a switch on the micro on a spare port, and close the switch if you want debugging information, and open it if you don't. Then you have total control over the debugging.

body:
Thanks to Nick Gammon for his answer, the problem is really in the `screen` program.

There is detailed explanation from Majenko in
https://arduino.stackexchange.com/questions/20836/ifserial-not-working-correctly-on-micro-or-pro-micro

The problem is, that some programs (like `screen`) or some systems, or drivers, or so do not pull down `RTS` and `DTR` signals for Micro. (The `DTR` down is supposed to restart Uno and other non-USB arduinos).

It could be solved by running some small program to `close` the USB Serial properly after the `screen` is done with it - here are two which works for me

C program

    #include <unistd.h>
    #include <fcntl.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/ioctl.h>

    int main(int argc, char *argv[]) {
            // Check if the correct number of command-line arguments is provided
            if (argc != 2 ) {
                    fprintf(stderr, "Usage: %s <filename>\n", argv[0]);
                    fprintf(stderr, "  %s /dev/ttyACM0 - close USB Serial for Arduino on the port\n", argv[0]);
                    return 1; // Return an error code
            }
            int fd;
            fd = open(argv[1],O_RDWR | O_NOCTTY );//Open Serial Port

            int RTS_flag;
            RTS_flag = TIOCM_RTS;

            int DTR_flag;
            DTR_flag = TIOCM_DTR;

    //      ioctl(fd,TIOCMBIS,&RTS_flag);//Set RTS pin
    //      ioctl(fd,TIOCMBIS,&DTR_flag);//Set DTR pin

            ioctl(fd,TIOCMBIC,&RTS_flag);//Clear RTS pin
            ioctl(fd,TIOCMBIC,&DTR_flag);//Clear DTR pin
            close(fd);
    }

Python

    #!/usr/bin/python -u

    import serial
    import sys

    # Check if the correct number of command-line arguments is provided
    if not len(sys.argv) in {2,3}:
            print("Usage: {} <filename> [baudrate]".format(sys.argv[0]))
            print(" {} /dev/ttyACM0 - close USB Serial for Arduino on the port".format(sys.argv[0]))
            sys.exit(1)  # Exit with a non-zero error code

    # Get the filename from the command-line argument
    baudrate=115200
    filename = sys.argv[1]
    if len(sys.argv) > 2:
            baudrate=sys.argv[2]

    # Open the serial port
    ser = serial.Serial(filename, baudrate, xonxoff=False , rtscts=True , dsrdtr=True )
    ser.rts=False
    ser.dtr=False


body:
I'm trying to get my ESP32 internet clock to show temperature and humidity data from a dht11 sensor on a MAX7219 display but my code seems to have some issues. After verifying the code there are no errors, however instead of showing time,temperature and humidity my display only reads two letters "rk." What am I doing wrong? Thanks.

```lang-cpp
#include <WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
#include <DHT.h>
#define DHTPIN 1
#define DHTTYPE DHT11   // DHT 11
DHT dht(DHTPIN, DHTTYPE);
float h;
float t;
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW//#define HARDWARE_TYPE MD_MAX72XX::GENERIC_H
#define MAX_DEVICES 4
#define CLK_PIN   18
#define DATA_PIN  23
#define CS_PIN    5
MD_Parola Display = MD_Parola(HARDWARE_TYPE, DATA_PIN, CLK_PIN, CS_PIN, MAX_DEVICES);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
const char* ssid     = "12345";
const char* password = "12345";
String Time, hour, minute;
String Formatted_date;

int interval = 1000;

unsigned long updateTimer;
unsigned long changeDisplayTimer;
unsigned long changeDisplayPeriod = 3000;
boolean printTime = true;

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

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

while (!timeClient.update()) {
  timeClient.forceUpdate();
  }
}

Serial.println("");
Serial.println("WiFi connected.");
timeClient.begin();
timeClient.setTimeOffset(0);

 //Display.begin();
 Display.begin(4);
 Display.setIntensity(0);
 Display.displayClear();
 dht.begin();
}

void loop() {

 // check if more time than stored in variable "changeDisplayPeriod"
 // has passed by since last time this period was over
 if ( TimePeriodIsOver(changeDisplayTimer, changeDisplayPeriod) ) {
   // if more time REALLY has passed by
   printTime = !printTime; // invert the value of flag "printTime"
  }

 if (printTime == true) {
   obtainTime();
  }
 else { // which means printTime == false)
   printHumTEmp();
  }
 }

 void obtainTime() {

 if ( TimePeriodIsOver(updateTimer, 1000) ) {
 Formatted_date = "does not work";//timeClient.getFormattedDate();
   Serial.println(Formatted_date);
   hour = Formatted_date.substring(11, 13);
   minute = Formatted_date.substring(14, 16);

   Time = hour + ":" + minute;
   Serial.println(Time);
   Display.setTextAlignment(PA_CENTER);
   Display.print(Time);
   }
 }

void printHumTEmp() {
 if ( TimePeriodIsOver(updateTimer, 1000) ) {
   // your code reading in
   // and printing humidity and temperature
  }
}

 // easy to use helper-function for non-blocking timing
  boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
   unsigned long currentMillis  = millis();
   if ( currentMillis - startOfPeriod >= TimePeriod ) {
   // more time than TimePeriod has elapsed since last time if-condition was true
   startOfPeriod = currentMillis; // a new period starts right here so set new starttime
   return true;
  }
  else return false;            // actual TimePeriod is NOT yet over
}
```

title: dht11 data on ESP32 NTP clock (updated)

Answers: 0


body:
I am building an airplane. As a controller I am using a Raspberry pi 4. There are 3 sensors (MPU6050, QMC5883L, BME280) and arduino pro mini connected to the raspberry via i2c. When sending requests to the arduino it pulls the bus to 0 and shuts down(?).

- First screenshot. On the first search for all devices on the bus, the arduino responds and shuts down, but does not pull the bus to 0. On the second search It responds and pulls the bus to 0.

- Second screenshot. Rebooting the arduino, the SDA line goes up. Repeated runs of the search leads to what is shown in the first screenshot.

- Third screenshot. The arduino generates a PWM signal that is interrupted after a request to i2c.

As a test request I use the i2cdetect command on the Raspberry.
Raspberry is connected to the sensor bus through a level converter, because the level of signals from Raspberry is 3.3V, and sensors accept 5 volt logic.

There is no bus pull-up to the upper level, it is on the schematic of all sensors used (will it be enough?).

The arduino has a simple slave i2c device code, writing to registers the value arrived and output it to other elements (servo drives, motor controller, stepper motor drivers). The Arduino acts as a port expander because the Raspberry has only 2 buses and too few outputs for all the necessary devices

Why is the bus falling and how can I fix it?

arduino code
```c++
    #include <Wire.h>
    #include <Servo.h>
    #include <Stepper.h>

    uint16_t servoAngle1 = 90;
    uint16_t servoAngle2 = 90;
    uint16_t servoAngle3 = 90;
    uint16_t servoAngle4 = 90;

    bool zoomIn = false;
    bool zoomOut = false;

    bool focusIn = false;
    bool focusOut = false;

    Servo servo1;
    Servo servo2;
    Servo servo3;
    Servo servo4;

    Servo ESC;

    Stepper zoomMotor(100, 2, 4, 7, 8);
    Stepper focusMotor(100, 10, 11, 12, 13);

    void setup() {
      Wire.begin(0x23);
      Wire.onReceive(receiveEvent);

      servo1.attach(3);
      servo2.attach(5);
      servo3.attach(6);
      servo4.attach(9);
      ESC.attach(11, 1000, 2000);
    }

    void loop() {
      servo1.write(servoAngle1);
      servo2.write(servoAngle2);
      servo3.write(servoAngle3);
      servo4.write(servoAngle4);
      ESC.write(0);
      if (zoomIn) {
        zoomMotor.step(100);
        zoomIn = false;
      }
      if (zoomOut) {
        zoomMotor.step(-100);
        zoomOut = false;
      }

      if (focusIn) {
        focusMotor.step(100);
        focusIn = false;
      }
      if (focusOut) {
        focusMotor.step(-100);
        focusOut = false;
      }
    }

    void receiveEvent(int howMany) {
      if (howMany == 2) {
        uint8_t action = Wire.read();
        uint8_t value = Wire.read();

        if (action == 1) { servoAngle1 = value; }
        if (action == 2) { servoAngle2 = value; }
        if (action == 3) { servoAngle3 = value; }
        if (action == 4) { servoAngle4 = value; }

        if (action == 10) {
          if (value == 1) { zoomIn = true; }
          if (value == 2) { zoomOut = true; }
        }

        if (action == 11) {
          if (value == 1) { focusIn = true; }
          if (value == 2) { focusOut = true; }
        }
      } else {
        while (true) {
          Wire.read();
        }
      }
    }
```

**Screenshot 1**
[![screenshot 1][2]][2]

**Screenshot 2**
[![screenshot 2][3]][3]

**Screenshot 3**
[![screenshot 3][4]][4]

**and wiring diagram**
[![wiring diagram][1]][1]

  [1]: https://i.stack.imgur.com/Frk6W.jpg
  [2]: https://i.imgur.com/bqCf4FN.png
  [3]: https://i.imgur.com/n0wGO3m.png
  [4]: https://i.imgur.com/ADLoDgB.png

title: Arduino pulls i2c bus down

Answers: 1

body:
For I2C to work there needs to be pull-ups on SDA and SCL somewhere (not one for each device). Typically 4.7k resistors or thereabouts would be used.

Also you need a bi-directional voltage level translator. An example schematic is:

[![Bi-directional level shifter][1]][1]

Image credit: [Sparkfun: Bi-Directional Logic Level Converter Hookup Guide ](https://learn.sparkfun.com/tutorials/bi-directional-logic-level-converter-hookup-guide/all)

This is because I2C devices actively pull SDA and SCL low, however they rely on the pull-up resistors to pull them high. Also this won't work unless the voltage level shifter is bi-directional.

For more information see the [Philips Application Note AN97055 - Bi-directional level shifter for I²C-bus and other systems.](https://cdn.sparkfun.com/tutorialimages/BD-LogicLevelConverter/an97055.pdf)

If you use the level shifter you need pull-up resistors on both the 3.3V part and the 5V part of the circuit (shown as Rp below).

[![Philips Application Note AN97055][2]][2]

  [1]: https://i.stack.imgur.com/3fEFX.png
  [2]: https://i.stack.imgur.com/EpUxY.png


body:
I'm having issues connecting to my arduino mega via ethernet. Its a very basic start to the code just to get the network side up and running, them im going to add in what I actually want it to do. For some reason, even after changing the cables and ethernet ports used, I still get `linkStatus()` returning LinkOFF? The server starts, and listens for clients, but I can't connect to it from my PC. I'm on the same subnet.

```c++
    #include <SPI.h>
    #include <Ethernet.h>

    IPAddress ip(10,126,132,32);
    int baud = 9600;
    byte mac[] = {
                   0xA8, 0x61, 0x0A, 0xAE, 0x76, 0x17
                 };

    byte subnet[] = {255, 255, 254, 0};
    byte gateway[] = {10, 126, 132, 1};

    EthernetServer server(80);

    void setup(){
      Serial.begin(baud);
      Serial.print("\n-------------------------");
      Serial.print("\nSerial initialised: ");
      Serial.print(baud);
      Ethernet.begin(mac, ip, gateway, gateway, subnet);
      server.begin();
      Serial.print("\nServer initialised... ");
      Serial.print("\nLocal IP: \t");
      Serial.print(Ethernet.localIP());
      Serial.print("\nDNS Server IP: \t");
      Serial.print(Ethernet.dnsServerIP());
      Serial.print("\nGateway IP: \t");
      Serial.print(Ethernet.gatewayIP());
      Serial.print("\nSubnet Mask: \t");
      Serial.print(Ethernet.subnetMask());
      Serial.print("\nHardware status: ");
      if (Ethernet.hardwareStatus() == EthernetNoHardware){Serial.print("No Hardware Detected");}
      else if (Ethernet.hardwareStatus() == EthernetW5500){Serial.print("W5500 Board Detected");}
      else if (Ethernet.hardwareStatus() == EthernetW5200){Serial.print("W5200 Board Detected");}
      else if (Ethernet.hardwareStatus() == EthernetW5100){Serial.print("W5100 Board Detected");}
      Serial.print("\nLink status: \t");
      if (Ethernet.linkStatus() == LinkON){Serial.print("ON");}
      else if (Ethernet.linkStatus() == LinkOFF){Serial.print("OFF");}
      else if (Ethernet.linkStatus() == Unknown){Serial.print("Unknown");}
      Serial.print("\n-------------------------");
      if(server) { Serial.print("\nServer Available\nWaiting for client..."); }
      else {Serial.print("\nServer not available");}
    }

    void loop()
    {
      Ethernet.maintain();
      EthernetClient client = server.available();
      if (client)
        {
          Serial.println("Client found...");
          Serial.println(client.read());
      }
    }
```

When trying to connect via my browser, I get `Error: Connection Refused`.

Any help is appreciated!

title: Arduino (Mega 2560) Ethernet Shield 2 (W5500) - Can't connect

Answers: 0


body:
I have put together the following code to activate a motor using an Arduino Uno via  push buttons.
- Two push buttons should be pressed simultaneously to activate the motor for a specified number of steps,
- then when both buttons are pressed again the motor will spin in reverse, returning the motor to its original position.

The code works, but not every time the button is pressed. I've gone through every line of the code and can't seem to find the issue. I know that the connections are correct since the code executes sometimes, but I don't know if there is an error in the code causing the unreliable response or if I have faulty/cheap push buttons with bad connections.

```c++
    #include <Bounce2.h> // Include the Bounce2 library

    // Define stepper motor connections:
    #define dirPin 3
    #define stepPin 2
    #define motorEnablePin 4 // Motor driver's enable pin
    #define buttonPin 8 // Push button connected to pin 8
    #define buttonPin2 9 // Push button connected to pin 8

    boolean motorRunning = false; // Flag to track motor rotation
    boolean oddRotation = true; // Flag to track odd/even rotations

    // Create a Bounce object for the button
    Bounce debouncer1 = Bounce();
    Bounce debouncer2 = Bounce();

    void setup() {
      // Declare pins as output or input:
      pinMode(stepPin, OUTPUT);
      pinMode(dirPin, OUTPUT);
      pinMode(motorEnablePin, OUTPUT); // Enable pin as output
      pinMode(buttonPin, INPUT_PULLUP); // Use internal pull-up resistor for the button
      pinMode(buttonPin2, INPUT_PULLUP); // Use internal pull-up resistor for the button
      digitalWrite(dirPin, LOW); // Set the spinning direction CW/CCW
      digitalWrite(motorEnablePin, HIGH); // Disable motor driver initially

      // Attach the debouncer to the button pin
      debouncer1.attach(buttonPin);
      debouncer2.attach(buttonPin2);
      debouncer1.interval(50); // Set debounce time
      debouncer2.interval(50);
    }

    void loop() {
      // Update the debouncer
      debouncer1.update();
      debouncer2.update();

      if (debouncer1.fell() && debouncer2.fell()) {
        // Button pressed and motor is not running, initiate motor rotation
        motorRunning = true;
        oddRotation = !oddRotation; // Toggle the rotation direction

        int stepsPerRevolution = 200; // Number of steps for one full revolution
        int desiredRevolutions = 10;  // Number of desired revolutions
        int totalSteps = stepsPerRevolution * desiredRevolutions;
        int stepCount = 0; // Counter for the steps taken

        // Set the motor rotation direction
        digitalWrite(dirPin, oddRotation ? LOW : HIGH);

        // Enable the motor driver
        digitalWrite(motorEnablePin, LOW);

        while (stepCount < totalSteps) {
          // Rotate the motor
          digitalWrite(stepPin, HIGH);
          delayMicroseconds(600);
          digitalWrite(stepPin, LOW);
          delayMicroseconds(600);

          stepCount++;

          // If the desired number of rotations is reached, stop the motor
          if (stepCount >= totalSteps) {
            // Disable the motor driver
            digitalWrite(stepPin, LOW);
            digitalWrite(motorEnablePin, HIGH);

            // Reset the flag to stop motor rotation
            motorRunning = false;
          }
        }

        // Disable the motor driver when idle
        digitalWrite(motorEnablePin, HIGH);
      }
    }
```

title: Code not Executing Reliably on Push Button Activation

Answers: 1

body:
Bounce.fell() returns true only if the input fell since the last update(). So your code will only work if both buttons are pressed at exactly the same time.

I suggest that you record the time at which each button is pressed and execute your code if the press times are less than 100ms apart. That should give reliable operation.

You can test if this is the problem simply by removing the debouncer2.fell() call. The code should then work reliably when only button 1 is pressed.


body:
I'm using Arduino IDE v2.1.1 and Arduino MKR wifi 1010. Everything works fine and at this moment I have a need to protect the wifi connection with ssl certificate. I have generated the ssl certificate using the openssl tool and now I have following files that needs to be set in the controller:

 - ca.crt
 - client.crt
 - client.key

how can I set these three files to the MKR wifi 1010 to enable the SSL certificate protected communication? I couldn't find the tutorial or example on the internet.

let me explain how I do that at the moment. I do have a valid self-signed CA certificate and I'm trying to establish a SSL / TLS connection using the CA sertificate only. This is my code which doesn't work unfortunately:

```c++
#include <WiFiNINA.h>
#include <ArduinoJson.h>
#include <ArduinoMqttClient.h>
#include <ArduinoBearSSL.h>
#include <ArduinoECCX08.h>
#include "secrets.h"

char wifiSsid[] = SECRET_WiFi_SSID;
char wifiPass[] = SECRET_WiFi_PASS;
char mqttUserId[] = MQTT_USERID;
char mqttPass[] = MQTT_PASS;
int status = WL_IDLE_STATUS;
const char* rootCAcertificate  = \
"-----BEGIN CERTIFICATE-----\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" \
"-----END CERTIFICATE-----\n";

bool dev_debug_mode = IS_DEBUG;

WiFiClient    wifiClient;         // Used for the TCP socket connection
BearSSLClient bearSslClient(wifiClient); // Used for SSL/TLS connection, integrates with ECCX08
MqttClient    mqttClient(bearSslClient); // Used for MQTT protocol usage

const char mqttBroker[] = MQTT_BROKER_HOST;
int mqttPort = 8883;

const char deviceRegisterTopic[] = "device/register";

//set interval for sending the Observation (the measurement from the sensor) messages (milliseconds)
const long interval = 3000;

unsigned long previousMillis = 0;

bool deviceIsRegistered = false;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (dev_debug_mode && !Serial) {
    ; // wait for serial port to connect. Needed for native USB port only - development mode. It has to be removed when releasing to live!!!
  }

  // Check the crypto chip module presence (needed for BearSSL)
  if (!ECCX08.begin()) {
    Serial.println("No ECCX08 present!");
    while (1);
  }

  bearSslClient.setEccSlot(0, rootCAcertificate); // inserting a certificate into the slot 0 (zero)

  // ================ SSL SETUP ================
  // Set a callback to get the current time
  // (used to validate the servers certificate)
  ArduinoBearSSL.onGetTime(getTime);

  // attempt to connect to the Wifi network
  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to network: ");
    Serial.println(wifiSsid);
    // Connect to WPA/WPA2 network:
    status = WiFi.begin(wifiSsid, wifiPass);

    Serial.print("Attempt status: ");
    Serial.println(status);

    if(status != WL_CONNECTED) {
      // waiting 10 seconds before trying to connect if it is needed:
      delay(10000);
    }
  }

  // WiFi network connection established! sending some messages to the console
  Serial.println("You're connected to the network");

  Serial.print("Attempting to connect to the MQTT broker: ");
  Serial.println(mqttBroker);
  Serial.println(mqttPort);

  mqttClient.setId(mqttUserId);

  // adding first level of proptection using MQTT broker username and password
  mqttClient.setUsernamePassword(mqttUserId, mqttPass);

  delay(30000);
  while (!mqttClient.connect(mqttBroker, mqttPort)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());
    delay(10000);
  }

  // MQTT broker connection established! sending some messages to the console
  Serial.println("You're connected to the MQTT broker!");
  Serial.println();
}

void loop() {

  // call poll() regularly to allow the library to send MQTT keep alive which
  // avoids being disconnected by the broker
  mqttClient.poll();

  // if this current device is not registered yet, registering the device for the first time
  if(!deviceIsRegistered) {
    Serial.print("Sending Device Register message to topic: ");
    Serial.println(deviceRegisterTopic);
    // DO SOMETHING
  }

  unsigned long currentMillis = millis();

  // sending the actual measurement data to the FHIR Server with some time interval, like few seconds. To be defined later.
  if (currentMillis - previousMillis >= interval) {

    // save the last time a message was sent
    previousMillis = currentMillis;

    Serial.println();
  }
}

// ================================== Auxiliary functions ===================================
unsigned long getTime() {
   Serial.print("Current WiFi time:");
   Serial.println(WiFi.getTime());
  // Get the current time from the WiFi module
  return WiFi.getTime();
}
```

in the code above, I'm using the **BearSSLClient** and the certificate is set manually (I prefer this way as it is more transparent for me) `bearSslClient.setEccSlot(0, certificate);` - this is how the certificate is set. Also I do the following call: ArduinoBearSSL.onGetTime(getTime); - to get the proper time. The CA certificate is validated using the **openssl** tool. It is a valid self-signed root certificate.   Please, any help is much appreciated. I'm really confused as it should work since the certificate is a valid self-signed certificate and it is confirmed and verified using the **openssl** tool. When something should work but it doesnt work and I don't have any details except the **-2** error message it makes me feel completely crazy ((((

@b1n3t thank's dude for your help. I appreaciate that. Let me start with one thing, I do software developent for more than 16 years, but I was working with hardware like microcontrollers and i8086 architecture based hardware more than 10 years ago. I was never investigating the SSL /  TLS issues deeply. Now, I go through your questions one by one: yes, I'm sure that Arduino's internal clock is accurate because I have configured myself a mutual TLS connection to the AWS (Amazon) MQTT broker with this clock engaged and everything works fine. The private key might not be properly stored within the ECC608, this might be the issue because I'm not 100% sure that I've done that right. Yes, I have verified that mosquitto MQTT broker's domain and port are accessible from the device, because it connnects successfully without the mutual TLS. I can send message back anf force from the device to the mosquitto MQTT broker server without mutual TLS and without SSL. Yes, I have configured the linux server to enable the 8883 for external connection. I have used the MQTT Explorer tool to establish a mutual TLS connection using the CA root certificate, client and server certificates from another physical device over my LAN network, everything works smoothly, it connects with the CA and client certificate to the MQTT broker server and I can send and receive messages. All is good here. Let me capture the logs and get back. Broker is configured to trust the CA, however all the certificates are self-signed. I have been struggling with this for about five days now and I figured out few important things: the ECC608 is by default (from the factory) in the unlocked state, it can't be used until it is locked (manually from the code). The certificate sign request should be generated on the MRK WiFi 1010 device and the private key is stored internally within the MKR WiFi 1010 device, tha'ts very important detail. Afte that, the CSR should be passed to the certification provider and the sercret certificate should be generated based on that CSR (certificate sign request). Another very important detail is that the self-signed certificate that I'm using for the development might be an issue as it is marked ALWAYS as invalid just because it is self-signed.

**update 22 September**

I'm still struggling with this problem. At this moment, everything is setup and configured on the microcontroller side. The microcontroller can connect to any online test MQTT broker via ssl/tls protocol. I have checked that and double checked. Everything is good on the microcontroller side. My MQTT broker is configured to use TLS v 1.2 it is deployed live, the cetificate is valid, it is generated by the zerossl trusted authority and it just works. I can connect from the test clients to my Mosquitto MQTT broker. I have tried multiple clients and everythig works fine. At this point, I have verified that client is valid and server is valid, both can connect to another party using TLS secure protocol. But, when I'm trying to pair my microcontroller with my Mosquitto MQTT broker - TLS SSL error is thrown, saying that the handshake failed. ssl tls 1.2 error ACCEPT_SR_KEY_EXCH ssl handshake failure. I have tried to debug it using the Wireshark, but there are no details at all. when I try to debug the SSL/TLS using the Wireshark, I see that there is a Client Hello, after that the Server Hello, then Certificate, Server Key Exchange, Server Hello Done and it repeats in a sequence again:

Client Hello, after that the Server Hello, then Certificate, Server Key Exchange, Server Hello Done

Client Hello, after that the Server Hello, then Certificate, Server Key Exchange, Server Hello Done

Client Hello, after that the Server Hello, then Certificate, Server Key Exchange, Server Hello Done

any help is appreciated.

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

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

title: Arduino MKR wifi 1010 ssl certificate protection

Answers: 1

body:
seems like you have made quite a progress. Frankly, I believe that the problem lies behind not storing your private key in the ECC608.

If the private key is not correctly stored in the ECC608 TLS Handshake will fail. You mentioned the ECC608 is unlocked by default. You're correct that to use the secure functionalities of the chip, it has to be locked. However, as far as I know once it's locked, it can't be unlocked. Make sure you've followed the necessary steps to store your private key in the ECC608 and then locked it to secure the key. I think you can use `ArduinoECCX08` library since it seems to have `ECCX08.begin()`, `ECCX08.lock()`, `ECCX08.generatePrivateKey(slot)` functions. Your approach to generating the CSR directly on the MKR WiFi 1010 device is on point. This method ensures the private key never leaves the device. Consequently, only the public part is sent to the CA, even if it's self-signed. With the CSR, obtain your device certificate. This certificate, coupled with the private key securely housed in the ECC608, should facilitate the TLS handshake.

**TL;DR**: Make sure that you've stored the private key appropriately in the ECC608. Before locking the ECC608, test to ensure that the private key functions as expected. Check your MQTT Broker Logs for further debugging (when provided and when I get time for that I will try my best to pinpoint the error) and try using WireShark to capture SSL traffic.

That is as far as my knowledge goes, all the best luck to you. I hope that I could be of help dude.


body:
I'm facing an issue that I can't seem to resolve due to my limited knowledge in electronics. I'm working with a 4-channel 5V relay module and an ESP32 which operates on 3.3V.
[![enter image description here][1]][1]

The setup seemed to work well initially but I have started experiencing some inconsistencies. One of the four relays is working perfectly fine, but the other three are not triggering as they should.

Here are the symptoms:

The LEDs on the non-working relays do light up when a signal is sent from the ESP32, indicating some form of communication.
There is no audible 'click' sound from these relays when they are supposed to trigger.
I noticed that if I gently tap the relay casing, the relay will sometimes trigger, and I can hear it closing.
I had previously thought that I might have fried my first relay module so I replaced it, but the issue reappeared after a few days.

Any guidance would be greatly appreciated as I'm at a loss here. Thank you!

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

title: ESP32 Struggling to Consistently Trigger 4-Channel 5V Relay Module

Answers: 1

body:
So it turns out that esp32 boards can actually output 5v alongside with 3.3v output pin, You just have to use the VN pin which is used for powering the board when not connected through USB, this is not what the pin is intended for and also might cause some problems and you cannot upload code to the board when VIN pin is connected but so far it works perfectly and outputs consistent 5V that triggers the relays just fine.

Obviously, I was just looking for a solution no matter what risks it imposed, can anyone with a deeper understanding of this topic explain why the power input pin can also work as output and why is this not a feature that comes with esp32 boards


body:
I am trying to upload a library to the Arduino Library Manager. I know the GitHub - arduino/library-registry: Arduino Library Manager list repository, and I have already read the instructions, but I have a question that I hope someone can explain to me.

The project I am working on is multiplatform, and to fulfill all the requirements for multiple platforms, many files are not required for the Arduino compilation process. I work around this because, with the help of GitHub actions, I have automated a workflow that publishes a branch within the project with an adequate file structure that complies with the Arduino library specification.

On the library-registry repo, step 7 says: " This should be the URL of the repository home page. For example: https://github.com/arduino-libraries/Servo" I am wondering if, in this section, I can put the link to the Arduino branch on the project.

This would mean to include :
https://github.com/myProfileName/myProjectName/tree/Arduino

Instead of :
https://github.com/myProfileName/myProjectName

With the reasoning that the second URL would contain many files that are not needed in an Arduino environment

title: Uploading a Library to the library manager from a Github branch

Answers: 1

body:
No. As stated in [the instructions for submitting a library to the Arduino Library Manager registry](https://github.com/arduino/library-registry#instructions), the URL must be to the home page of the repository.

The way [the Library Manager index generation system](https://github.com/arduino/libraries-repository-engine) works:

1. Clone the repository from the URL that was registered URL.
1. Check out each [Git tag](https://git-scm.com/book/en/v2/Git-Basics-Tagging) in the repository.
1. Check to see whether the repository contains an Arduino library at that tag.
1. Check to see whether the library release at that tag is already in the index.
1. If it is a valid new library release, add the release to [the index](http://downloads.arduino.cc/libraries/library_index.json).

So there is no problem with having the Arduino library in a different branches in the repository because the indexer doesn't work from branches. It works from tags, which are independent from branches. You must only make sure to make a Git tag at the commit ref in the Arduino library branch of your repository at the point in the revision history where you make a release of the library.

In case you also want to tag other branches, that is fine. Even though tags are the unit of release for Library Manager, the versioning of the library releases is done exclusively using the value of the `version` field of the [`library.properties` metadata file](https://arduino.github.io/arduino-cli/latest/library-specification/#library-metadata). So you can add something to the tag names to differentiate the Arduino library release tags from tags made in other branches (e.g., `Arduino-1.2.3`, `1.2.3`).

The one consideration with the release strategy I mentioned above is that [the submission validation system](https://github.com/arduino/library-registry-submission-parser) that checks for problems with the library when you [submit](https://github.com/arduino/library-registry#adding-a-library-to-library-manager) it for inclusion in Library Manager checks out [the most recent tag](https://github.com/arduino/library-registry-submission-parser/blob/1.1.1/main.go#L349) in the repository and does that initial validation on the contents of the repository at that specific tag. So you do need to make sure that the Arduino Library release tag is the most recent tag at the time you submit the library.

Once the submission is accepted, all tags in the repository will always be processed (ignoring those that don't pass Arduino Library validation), so it won't matter if tags from branches that don't contain an Arduino library are the most recent tags in the repository after the library has been registered.


body:
I have a project where I need to store data (~16Mo) on a memory and be able to fetch the data fast (<36000bits/s) with DMA because I have other signals to take care of.

Currently I use a SD card with the SD library but it doesn't seems to use DMA because of the delay between to sending.

Many people told me it shouldn't be that hard and I suppose so. My guess is that I can't configure the DMA and/or the SPI correctly.

I tried something a long time ago : https://arduino.stackexchange.com/questions/92888/send-data-through-spi-with-dma

Can someone show me an example of SPI with DMA, or tips on how to configure both.

Thanks again

title: SPI with DMA in a Arduino Due

Answers: 1

body:
```cpp
#include <dmac.h>
#include <SPI.h>
#include <Arduino.h>
#include <sam.h>

uint8_t sourceBuffer[256];

void setup() {
  SPI.begin();
  SPI.setClockDivider(21);  // 4MHz clock (assuming 84MHz system clock)
  setupDMA();
}

void loop() {

  for(int i = 0; i < sizeof(sourceBuffer); i++) {
    sourceBuffer[i] = i;
  }
  startDMATransfer();
  delay(1000);
}

void setupDMA() {
  // Enable the DMA controller
  PMC->PMC_PCER1 |= PMC_PCER1_PID34;  // DMA ID for the Due is 34

  // Disable SPI DMA TX and RX
  SPI0->SPI_PTCR = SPI_PTCR_RXTDIS | SPI_PTCR_TXTDIS;

  // Setup a DMA channel for the transfer (channel 1 for this example)
  DmacChannel* channel = &(DMAC->DMAC_CH_NUM[1]);

  // Disable the DMA channel
  channel->DMAC_CHDR = DMAC_CHDR_DIS;

  // Clear any flags and reset the status
  channel->DMAC_CHDR = DMAC_CHDR_RES;

  // Set up source and destination pointers
  channel->DMAC_SADDR = (uint32_t) sourceBuffer;
  channel->DMAC_DADDR = (uint32_t) &(SPI0->SPI_TDR);

  // Configure source and destination pointers: source increments, destination does not
  channel->DMAC_CTRLA = DMAC_CTRLA_SRC_WIDTH_BYTE | DMAC_CTRLA_DST_WIDTH_BYTE;

  // Set source and destination handshake (related to the SPI0 Tx)
  channel->DMAC_CTRLB = DMAC_CTRLB_SRC_DSCR_FETCH_DISABLE | DMAC_CTRLB_DST_DSCR_FETCH_DISABLE |
                        DMAC_CTRLB_FC_MEM2PER_DMA_FC | DMAC_CTRLB_SRC_INCR_INCREMENTING |
                        DMAC_CTRLB_DST_INCR_FIXED;

  channel->DMAC_CFG = DMAC_CFG_SRC_PER(1) | DMAC_CFG_DST_PER(1) | DMAC_CFG_SOD | DMAC_CFG_FIFOCFG_ALAP_CFG;
}

void startDMATransfer() {
  // Assuming channel 1 is used
  DmacChannel* channel = &(DMAC->DMAC_CH_NUM[1]);

  // Set up the buffer size
  channel->DMAC_CUBC = sizeof(sourceBuffer);

  // Enable SPI DMA for TX
  SPI0->SPI_PTCR = SPI_PTCR_TXTEN;

  // Enable the DMA channel to start the transfer
  channel->DMAC_CHER = DMAC_CHER_ENA;
}
```

When you want to send data via SPI using DMA, you can fill the `sourceBuffer` and call `startDMATransfer()`.

Remember to always refer to the Atmel SAM3X8E datasheet and the Arduino Due's schematic when you are working at this level, as it provides in-depth details on how the hardware functions. I am unable to run the code or test it. But I believe that the code logic is proper. Error handling is up to you.


body:
I'm pretty new to Arduino. I am trying to build a Self-balancing robot. I am using A4988 drivers, ESP32 microcontroller, NEMA 17 motors and a 6050 MPU.

The problem is that, although the speed variable changes according to the position of the MPU. The motors rotate at a slow and constant speed, without varying according to the inclination of the robot.

Here is the code:

```cpp
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include <AccelStepper.h>

#define STEP_IZQ 26
#define DIR_IZQ 27
#define STEP_DER 12
#define DIR_DER 13

AccelStepper stepperizq(AccelStepper::FULL2WIRE,STEP_IZQ,DIR_IZQ);
AccelStepper stepperder(AccelStepper::FULL2WIRE,STEP_DER,DIR_DER);
Adafruit_MPU6050 mpu;

float kp = 20;
float ki = 0.5;
float kd = 30;

float angulo_grad, error,cumError,rateError,output,lastError;
float pid_error_temp, pid_i_mem, pid_setpoint, gyro_input, pid_output, pid_last_d_error;
int speed,outputAbs;

void setup(void) {
  Serial.begin(115200);
  while (!Serial)
    delay(10); // will pause Zero, Leonardo, etc until serial console opens

  Serial.println("Adafruit MPU6050 test!");

  // Try to initialize!
  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    while (1) {
      delay(10);
    }
  }
  Serial.println("MPU6050 Found!");
  mpu.setAccelerometerRange(MPU6050_RANGE_8_G);
  mpu.setGyroRange(MPU6050_RANGE_500_DEG);
  mpu.setFilterBandwidth(MPU6050_BAND_5_HZ);

  pinMode(DIR_IZQ, OUTPUT);
  pinMode(DIR_DER, OUTPUT);

  stepperizq.setMaxSpeed(3000);
  stepperder.setMaxSpeed(3000);
  stepperizq.setAcceleration(1000); //1000
  stepperder.setAcceleration(1000); //1000
}

void loop() {
  /* Get new sensor events with the readings */
  sensors_event_t a, g, temp;
  mpu.getEvent(&a, &g, &temp);

  angulo_grad = atan((a.acceleration.x)/(a.acceleration.z))*(180/3.14);            //0 to 90 degrees
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // pid
  /////////////////////////////////////////////////////////////////////////////////////////////////

  pid_error_temp = angulo_grad;
  if((pid_error_temp > -2.0 )&&( pid_error_temp < 2.0)) pid_error_temp = 0.0;

  pid_i_mem += ki * pid_error_temp;                                 //Calculate the I-controller value and add it to the pid_i_mem variable
  if(pid_i_mem > 800)pid_i_mem = 800;                                       //Limit the I-controller to the maximum controller output
  else if(pid_i_mem < -800)pid_i_mem = -800;
  //Calculate the PID output value
  pid_output = kp * pid_error_temp + pid_i_mem + kd * (pid_error_temp - pid_last_d_error);
  if(pid_output > 5000)pid_output = 5000;                                     //Limit the PI-controller to the maximum controller output
  else if(pid_output < -5000)pid_output = -5000;

  if(output < 50 && output > 50)output = 0;
  pid_last_d_error = pid_error_temp;
  ////////////////////////////////////////////////////////////////////////////////////////////////////
  //motors nema 17
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////
  outputAbs = (int)abs(pid_output);
  speed = map(outputAbs,0,5000,0,3000);

  stepperizq.setSpeed(speed);
  stepperder.setSpeed(speed);

  if(pid_output<0){
    digitalWrite(DIR_IZQ,LOW);
    digitalWrite(DIR_DER,HIGH);
  }
  else if(pid_output>0){
    digitalWrite(DIR_IZQ,HIGH);
    digitalWrite(DIR_DER,LOW);
  }
  stepperizq.runSpeed();
  stepperder.runSpeed();
}
```

title: AccelStepper.h - How can I quickly increase the speed of the NEMA 17 motor?

Answers: 1

body:
To write down my guess from the comments in a proper answer:

When a stepper motor driven with AccelStepper shows a constant speed, though the speed is set to different values, it suggests, that the time interval of the steps is defined by something else.

The `runSpeed()` function works by saving a timestamp of the last step and then checking the elapsed time on the basis of the set speed, to check if the time for another step has come and if yes, then execute exactly one step. For this to work correctly, you need to call this function within intervals smaller than the smallest period between two consecutive steps for your speed.

If for whatever reason you call the function with larger intervals, the `runSpeed()` function will always see, that the time for a new step has come, but it will always only do one step per execution. Thus you overall get one step per `runSpeed()` execution, and this is determined by the rest of your code, not the set speed.

The rest of the code in `loop()` is for getting the measurements of the MPU and calculating the resulting speeds from that. Probably this is taking too long and thus hindering the AccelStepper library from running the motor at the specified speeds. So you need to provide a larger timeslot for the stepper driving on your ESP by cutting down on your MPU sampling rate. This is easiest done by using

    // Running MPU sampling and calculation only every 100ms
    if(millis() - previousMillis >= 100){
      previousMillis += 100;
      // MPU and calculation code here
    }
    // Running the stepper code on every loop iteration
    stepperizq.runSpeed();
    stepperder.runSpeed();

which is the non-blocking coding style used in the `BlinkWithoutDelay` example. If you don't know how to use `millis()`, there are many tutorials online for that.


body:
I am working on IR remote code run on Arduino UNO
I can already get it work. but when I press the button and hold, the output is sent with the same value repeatly. So,the quesion is how can I do to make it send out only one output while I press and hold the button.

this is my code
```
#include <IRremote.h>
int RECV_PIN = 5;
#define PB  3392264773 // button code
#define VUP  3476004267 // button code
#define VDN  2998643817 // button code
#define SRC  387001607 // button code
#define MUTE  305976139 // button code

IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}
void loop() {
  if (irrecv.decode(&results)) {

    if (results.value == PB) {
      Serial.println("Power");
    }
    if (results.value == VUP) {
      Serial.println("Vol UP");
    }
    if (results.value == VDN) {
      Serial.println("Vol Down");
    }
    if (results.value == SRC) {
      Serial.println("Select");
    }
    if (results.value == MUTE) {
      Serial.println("Mute");
    }

    irrecv.resume(); // Receive the next value

  }
}
```
and this is output when I press and hold the button
```
Power
Power
Power
Power
Power
Vol UP
Vol UP
Vol UP
Vol UP
Vol UP
Vol UP
Vol UP
Vol UP
```
Thank you for all answers.
Tanwa

title: IR Remote control on UNO

Answers: 2

body:
As noted in the comments, you cannot change what the remote is sending. Though I guess, that it would be OK for you to just react to the first occurence of a specific value send consecutively. For that you first need to check the time between these consecutive values send, when holding the button down. That (plus a small margin) will be the threshold to recognize multiple distinct button presses. Note: Depending on the rate, that the remote is sending when holding a button, this might mean, that you cannot distinguish between holding a button and pressing it multiple times in a fast pace.

First define a variable to hold the previous decode results and a timestamp for saving when it arrived:

    decode_results previous_results;
    unsigned long previous_timestamp;

On receiving a new value via IR, check if the new value is the same as in `previous_results`. If yes, don't execute the code checking for the actual value. If no, then update `previous_results` with the new value and act upon the actual received value. Then set the timestamp to the current `millis()` value and resume receiving.

    if (irrecv.decode(&results)) {
      if(results != previous_results){
        previous_results = results;
        if (results.value == PB) {
          Serial.println("Power");
        }
        ....
      }
      previous_timestamp = millis();
      irrecv.resume(); // Receive the next value
    }

Now you need to reset the `previous_results` variable after a specific time threshold, so that consecutive presses on the same button can be registered. Add a corresponding `millis()` statement to your `loop()` function:

    if(millis() - previous_timestamp > 500){
      previous_results = 0;
    }

Note: The value of 500ms is just a wild guess. As described at the start, you need to find that value yourself, fitting to your remote. Play a bit with this value until you are satisfied.

All in all something like this:

    #include <IRremote.h>
    int RECV_PIN = 5;
    #define PB  3392264773 // button code
    #define VUP  3476004267 // button code
    #define VDN  2998643817 // button code
    #define SRC  387001607 // button code
    #define MUTE  305976139 // button code

    IRrecv irrecv(RECV_PIN);
    decode_results results;
    decode_results previous_results;
    unsigned long previous_timestamp;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }
    void loop() {
      if (irrecv.decode(&results)) {
        if(results != previous_results){
          previous_results = results;
          if (results.value == PB) {
            Serial.println("Power");
          }
          if (results.value == VUP) {
            Serial.println("Vol UP");
          }
          if (results.value == VDN) {
            Serial.println("Vol Down");
          }
          if (results.value == SRC) {
            Serial.println("Select");
          }
          if (results.value == MUTE) {
            Serial.println("Mute");
          }
        }
        previous_timestamp = millis();
        irrecv.resume(); // Receive the next value
      }

      if(millis() - previous_timestamp > 500){
        previous_results = 0;
      }
    }

Note: I have not tested this code in any way.

body:
by adapting chrisl's idea, I got it done. the code is here.
```
#include <IRremote.h>
int RECV_PIN = 5;
#define PB  3392264773 // button code
#define VUP  3476004267 // button code
#define VDN  2998643817 // button code
#define SRC  387001607 // button code
#define MUTE  305976139 // button code

int pre_p  = 0;
int pre_src  = 0;
int pre_mu  = 0;

//trigger
int p = 0;
int src = 0;
int mu = 0;

int pw = 0;
int s = 0;
int m = 0;

IRrecv irrecv(RECV_PIN);
decode_results results;

unsigned long previous_timestamp;
unsigned long check_timestamp;

void setup()
{
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}
void loop() {
  if (irrecv.decode(&results)) {

        if (results.value == PB){
           p = 1;
          if(p != pre_p){
           pw = !pw;
            //Serial.println(pw);
              Serial.println("pw");
              Serial.println(pw);
          }
        }
      if (results.value == VUP) {
        Serial.println("Vol UP");
      }
      if (results.value == VDN) {
        Serial.println("Vol Down");
      }
      if (results.value == SRC) {
        src = 1;
          if(src != pre_src){
           s = !s;
          Serial.println("s");
          Serial.println(s);
          //Serial.println("Select");
          }
      }
      if (results.value == MUTE) {
        mu = 1;
          if(mu != pre_mu){
           m = !m;
          //Serial.println("Mute");
          Serial.println("mu");
          Serial.println(m);
          }
      }

    irrecv.resume(); // Receive the next value
    pre_p = p;
    pre_src  = src;
    pre_mu  = mu;

    p=0;
    src = 0;
    mu = 0;

    previous_timestamp = millis();

  }
    if(millis() - previous_timestamp > 200){
    pre_p = 0;
    pre_src  = 0;
    pre_mu  = 0;
  }
}
```


body:
I'm trying to use Sparkfun Pro Micro (5v 16MHz) as ISP to program Attiny chips (OS:Windows10Pro). I followed instructions. Installed proper driver and added Sparkfun boards to ArduinoIDE:

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

Using Arduino IDE uploaded ArduinoISP sketch on it. As you can see there are two options available to choose for programmer:

 1. Arduino as ISP
 2. Arduino Leonardo/Pro Micro as ISP

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

Which unfortunately both of them give the same error:

    Sketch uses 28 bytes (2%) of program storage space. Maximum is 1024 bytes.
    Global variables use 0 bytes (0%) of dynamic memory, leaving 64 bytes for local variables. Maximum is 64 bytes.
    C:\Users\K1\AppData\Local\Arduino15\packages\MicroCore\tools\avrdude\7.1-arduino.1/bin/avrdude -CC:\Users\K1\AppData\Local\Arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf -v -pattiny13a -cstk500v1 -PCOM16 -b19200 -Uhfuse:w:0xff:m -Ulfuse:w:0b00111010:m -Uflash:w:C:\Users\K1\AppData\Local\Temp\arduino_build_207900/sketch_aug28a.ino.hex:i

    avrdude: Version 7.2
    Copyright the AVRDUDE authors;
    see https://github.com/avrdudes/avrdude/blob/main/AUTHORS

    System wide configuration file is C:\Users\K1\AppData\Local\Arduino15\packages\MicroCore\hardware\avr\2.3.0\avrdude.conf

    Using Port                    : COM16
    Using Programmer              : stk500v1
    Overriding Baud Rate          : 19200
    avrdude stk500_recv() error: programmer is not responding
    avrdude stk500_getsync() warning: attempt 1 of 10: not in sync: resp=0x00
    avrdude stk500_recv() error: programmer is not responding
    avrdude stk500_getsync() warning: attempt 2 of 10: not in sync: resp=0x00
    ...

    avrdude done.  Thank you.
    the selected serial port
     does not exist or your board is not connected

I tried avrdude in command line with these parameters and got the same results:

    avrdude -p attiny13a -P COM16 -c avrisp -b 19200 -U flash:w:r.hex -v

I also found out that issue most probably has nothing to do with:

 - Target chip that I'm using: because changing it has no effect
 - Wiring: because even when there is no chip connected to SPI pins of ProMicro I get the same error
 - USB cable is good: I can upload sketches successfully to Pro Micro but cannot use it as ISP and replaced cable to rule that probably out.

This is while in this video the guy does what I want easily and has no issues whatsoever:
[https://www.youtube.com/watch?v=7Rz9A9VbDx4][3]

Any ideas appreciated.

  [1]: https://i.stack.imgur.com/1eUd1.png
  [2]: https://i.stack.imgur.com/dIhPo.png
  [3]: https://www.youtube.com/watch?v=7Rz9A9VbDx4

title: Sparkfun Pro Micro (5v) as ISP error

Answers: 1

body:
GOTCHA...
After two days of search and speculation finally found the solution:

**Short answer:**
In avrdude command instead of **-c avrisp** use **-c arduino**:

    avrdude -p attiny13a -P COM16 -c arduino -b 19200 -U flash:w:r.hex -v

**Long answer:**
My target chip was ATtiny13a, so I had to use MicroCore v2.3.0 which is the only core supporting ATtiny13 for Arduino. Contrary to other cores, in this core's programmers.txt list, each entry should have a *upload.protocol* line:

    arduinoasispatmega32u4.upload.protocol=

otherwise it will give this error:

    avrdude programmer_not_found() error: cannot find programmer id {upload.protocol}

I have added this line before to make that error go away but apparently with wrong parameter of **stk500v1** that I have imitated from fabric entries! Converting this parameter to **arduino** solved the problem. This is what that entry should look like for ATtiny13 of MicroCore v2.3.0 (\packages\MicroCore\hardware\avr\2.3.0\programmers.txt):

    arduinoasispatmega32u4.name=Arduino Leo/Micro as ISP
    arduinoasispatmega32u4.communication=serial
    arduinoasispatmega32u4.protocol=arduino
    arduinoasispatmega32u4.upload.protocol=arduino
    arduinoasispatmega32u4.speed=19200
    arduinoasispatmega32u4.program.protocol=arduino
    arduinoasispatmega32u4.program.speed=19200
    arduinoasispatmega32u4.program.tool=avrdude
    arduinoasispatmega32u4.program.extra_params=-P{serial.port} -b{program.speed}

For other cores, like ATTinyCore v1.5.2 (\packages\ATTinyCore\hardware\avr\1.5.2\programmers.txt) no such line is needed hence this entry works fine:

    arduinoasispatmega32u4.name=Arduino Leo/Micro as ISP
    arduinoasispatmega32u4.communication=serial
    arduinoasispatmega32u4.protocol=arduino
    arduinoasispatmega32u4.speed=19200
    arduinoasispatmega32u4.program.protocol=arduino
    arduinoasispatmega32u4.program.speed=19200
    arduinoasispatmega32u4.program.tool=avrdude
    arduinoasispatmega32u4.program.extra_params=-P{serial.port} -b{program.speed}

Also you should update avrdude in the Arduino core manually:
Download latest release from [HERE][1], and replace them IDE's related files. If you can not find them take a look at [HERE][2]. If avrdude is not updated you might get an error like this:

    Error during upload using programmer
    The uploader process failed

    The uploader process failed
    The uploader returned an error
    avrdude: Version 6.3-20201216
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2014 Joerg Wunsch
             System wide configuration file is "C:\Users\K1\AppData\Local\arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf"
    avrdude: error at C:\Users\K1\AppData\Local\arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf:421: syntax error
    avrdude: error reading system wide configuration file "C:\Users\K1\AppData\Local\arduino15\packages\MicroCore\hardware\avr\2.3.0/avrdude.conf"

**Third Solusion:**
Use this App with this configuration:
[![enter image description here][3]][3]

  [1]: https://github.com/avrdudes/avrdude/releases
  [2]: https://forum.arduino.cc/t/avrdude-install-location/532406
  [3]: https://i.stack.imgur.com/9ZyDM.png