text:
Why are the UART ports not working on my Portenta breakout board?
I am using a Portenta Arduino Breakout Board that is connected to the Portenta H7 for a project I am working on. The project requires me to use three Adafruit Ultimate GPS sensors and connect each to its own UART ports on the Portenta breakout board. I am only using UART0, UART1, and UART2 (which are respectively Serial, Serial1, and Serial2).
To be able to get data, I've been using this example code from the Arduino IDE:
// Test code for Ultimate GPS Using Hardware Serial
// (e.g. GPS for Leonardo, Flora or FeatherWing)
//
// This code shows how to test a passthru between USB and hardware serial
//
// Tested and works great with the Adafruit GPS FeatherWing
// ------> https://www.adafruit.com/products/3133
// or Flora GPS
// ------> https://www.adafruit.com/products/1059
// but also works with the shield, breakout
// ------> https://www.adafruit.com/products/1272
// ------> https://www.adafruit.com/products/746
//
// Pick one up today at the Adafruit electronics shop
// and help support open source hardware & software! -ada

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

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

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

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

void loop() {
  if (Serial.available()) {
    char c = Serial.read();
    GPSSerial.write(c);
  }
  if (GPSSerial.available()) {
    char c = GPSSerial.read();
    Serial.write(c);
  }
}

This code works for Serial1, and I get data when I connect a GPS to the UART1 port of breakout board. When I call for Serial, or Serial2, changing #define GPSSerial Serial1 to #define GPSSerial Serial or #define GPSSerial Serial2 the code will upload with no errors, but I am not receiving any data from the GPS when it is connected to the respective UART port (UART0 and UART2).
I checked to see if the data is automatically only coming from UART1 port but it will not show anything when I am calling for Serial or Serial2, which should be expected.
Does anyone know how to deal with this issue? Could UART0 and UART2 ports not be transferring data to the Portenta H7 board which could be why I am not seeing any data?
Please let me know if I should clarify anything.

I just spent a day tracking down this same issue. The cause is that Arduino made an absolute mess of the naming conventions for these UART ports. Please see the table below. I created this table from the Portenta Schematic and the Breakout board Schematic.

Breakout Schematic
P. Schematic @ J1,J2
P. Schematic @ Micro
Micro Pin (tx,rx)
pins_arduino.h

UART0
Serial2
UART4
(PA0,PI9)
not defined

UART1
Serial1
LPUart
(PA9,PA10)
Maybe Serial 1?

UART2
Serial3
UART6
(PG14,PG9)
not defined

UART3
Serial4
UART8
(PJ8,PJ9)
Serial 3

Unfortunately as you can see, the built in serial definitions in pins_arduino.h are not going to work for the breakout board. (unless you use Serial 1 or Serial 3)
If you want to use these other serial ports, you need to define your own serial ports which actually isn't that hard. You just have to manually specify the pins and you're off.
#include "Serial.h"
UART UART0Breakout = UART(PA_0, PI_9);
UART UART2Breakout = UART(PG_14, PG_9);
void setup()
{
    UART0Breakout.begin(115200);
    UART2Breakout.begin(115200);
}

Hope this helps you! It certainly drove me mad for a while. Unfortunately the schematic I used for the breakout board was not nearly as nicely annotated as the one I linked here (I found it while writing this answer).


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

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

boolean newData = false;

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

void loop() {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    newData = false;
    }
}

The data will be sent from ESP32 to change the values of controlCondition, droneCondition, gasValue, pitchValue, rollValue, and yawValue.
I have tried it and the Interrupt cannot be triggered. The Interrupt should be triggered whenever the controlCondition, droneCondition, gasValue, pitchValue, rollValue, or yawValue change its value. Any idea what should I do? or is there something wrong with my code?
Note that the code that i showed in the void loop() is just an example code. The real code is more complex with so many calculations involved. The variables that I mentioned are the important variables for the calculations.

attachInterrupt(digitalPinToInterrupt(1), handleInterrupt, RISING) : which Arduino because pin 1 on say a Uno is not set up for edge triggered external interrupts.
The usual method for handling serial is in the loop() using Serial.available() to check if there is any data to process. Why are you attempting to do this in an interrupt service routine? Are you planning blocking code in the loop() or what?

https://stackoverflow.com/questions/53104440/how-can-i-implement-interrupt-for-serial-usart-communication-for-atmega328p-ardu#53105966

while (Serial.available()) ... if the arduino speed was scaled to human speed, then a serial character would arrive once a week

@jsotola I'm not sure what you are getting at, to be honest.

@NickGammon I don't either ... I was probably thinking that the ISR is waiting for multiple bytes

It should be nice having the possibility to get Serial Rx interrupt to call a function that listen Serial Port only when we receive data. The current method that consist to check in an infinite loop if data are available in the "software Rx Buffer" is not very  usable. In case, we have a feature that takes several seconds in the main loop, we could miss or delay an important message from the Serial port. HardwareSerial  library catches the Rx Interrupt but it also should allow to call a function we could override with our own code. We currently loose all the benefit of IRQ usage.

Why do you want to use an interrupt anyway? The serial hardware already generates an interrupt, and inside that ISR the incoming byte is placed into a buffer.
I presume you have a main loop where you are doing other stuff, and you want to react when some interesting serial data arrives.
I have an example of processing serial data without blocking on my page about serial processing which I reproduce below:
/*
Example of processing incoming serial data without blocking.

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

Released for public use.
*/

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

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

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

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

  switch (inByte)
    {

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

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

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

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

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

    }  // end of switch

  } // end of processIncomingByte

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

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

  }  // end of loop

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

The problems with an interrupt like you are doing are:

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

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

Your ISR is doing too much.

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

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

Actually my project is building a Drone that can be controlled with an Android App, so the variables that I mentioned are very important for calculating the PID for the Drone. And the calculations are very large, so it can take a long time for the loop to read the values of the variables. I have tried the way that you showed before and it did not work. You can see my code here. Any idea?

Well, saying it "did not work" is not very helpful. Your code has many many serial prints in it. What are you seeing on the terminal? You seem to be calling showParsedData in the main loop. Wouldn't it be better to call it directly after parsing the data?

You left in the test for \n as the end of the data, but I thought you had ">" as the data delimiter. Is there also a newline?

Don't do anything in your loop() function except calling other functions, each of which decides - for one part of your process - whether or not it is time to do that part. If so, do that part; if not, return immediately to the loop function.
Read my answer to a similar question that talks more about how to do this. This technique is called non-blocking programming. Your code should poll rapidly for whatever it might need to respond to, but should not wait for any of those things to occur. If you do that, you will likely not need the kind of response that would require interrupts.
Also, the print statements in your loop() will slow down (block) execution and may keep your PID from responding adequately. If you need them for debugging your calculations, you can wrap them in #if DEBUG ... #endif statements so one #define DEBUG can easily include them them when you need to (knowing that your device control will be affected) and remove them for operational tests. If you must keep some print statements live, make only as few as necessary live at one time, make sure to use the highest baud-rate possible, and keep them as brief as possible.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


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

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

Troubleshooting Steps Taken:

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

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

does the program upload correctly?

Were there any error messages during upload? Have you tried programming another Arduino using the same cables & IDE (even an Uno, in case you don't have another Nano)? Can you tell whether the Nano got programmed? If you have an Arduino that is already programmed, and talks to the serial port, have you tested whether you can read or write to that one from your IDE's serial terminal?

There are many varieties of "Nanos" with different processor types which may require a special configuration of the IDE, selection of a bootloader type etc. Here, for example, is one using a "near" clone of the ATmega328P chip: https://robot-r-us.com.sg/p/lgt8f328p-more-capable-than-arduino-nano-v3-0. Can you provide a link to the one you have purchased?

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

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
DS18B20 Error in Proteus 8.13
I am using the below code to check temperatures from 36 DS18B20 sensors using Arduino Mega 2560.  If any one of them go above 50 deg. celsius, then it sets the output pin to HIGH.
I am trying to run the code on Proteus 8.13, but during the same run, sometimes the virtual terminal prints -127 deg. celsius for all, sometimes right for some sensors and wrong for the other ones (usually the wrong value is also 85 deg. celsius). Is it something wrong with the simulator, or my code?
    #include <OneWire.h>
    #include <DallasTemperature.h>

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

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

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

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

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

    void loop() {
      float celsius[NUM_SENSORS];

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

      bool aboveThreshold = false;

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

      digitalWrite(OUTPUT_PIN, aboveThreshold);

      printSensorData(celsius);

      delay(1000);
    }

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

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

DS18B20 is using one-wire protocol, no SDA, nor SCL.

It appears that each sensor is on a separate pin - 36 1-Wire busses, as it were. If that is correct, is there a reason you haven't put the sensors on just a few 1-Wire busses? It would require many fewer pullup resistors and there will be many fewer mechanical connections to fail. There is an helpful application-note, "Guidelines for Reliable 1-Wire Networks" that discusses how to make reliable large networks and what the limits are.


text:
Make my Arduino (Mega or whatever is better for the task) to be able to read and write `Serial` data to a **rj45** port
I have a Chinese hybrid solar inverter that exposes an rj45 input which talks the serial protocol (Baud rate 2400, no parity, 8 bits, 1 stop bit). I need my Arduino (say, Mega or whatever, does not really matter) to talk to it. What would be the best option to connect an Arduino board to the rj45 input such that it would be available as Serial in the code?
Basically, I'd like the following piece to code to "just work":
    uint8_t query[] = {81, 80, 73, 71, 83, 183, 169, 13};
    Serial.write(query, sizeof(query)); // Write some bytes to a device, i.e. send a request.
    Serial.flush();

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

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

the rj45 is irrelevant here because it is just an 8 pin connector ... the electronics behind the connector are the important part

@jsotola I know for sure it talks Serial with the params I specified. That is the only fact I know. I belive the protocol is r232 or something alike, I am far from being proficient in the hardware part of the things. Yet the bytes I am sending over the serial are correct.

You need to know the signal voltage level (Arduinos use 5V or 3.3V depending on model), whether control signals (DTR, DCD, DSR...) are used or needed (Arduinos do not use them), whether flow control is needed (Arduinos do not do flow control natively), and the pinout of the RJ45 connector. If all the stars align, it's just a matter of connecting the device's RX, TX, and GND to the appropriate Arduino pins. Otherwise you may need a level shifter.

@EdgarBonet I don't have necessary tools to get that data. Shall I hope it does align as expected and simply connect the named RX, TX and GND to a converter. The question is - how that conver is suppose to look like? I guess a would need a converter to be installed on the Arduino board AND I would also need a data cable that would carry the signal to the rj45 input. Where do I get these and how to choose them corretly? I don't really see another options except "give it a try" and pray.

You might consider having a few spare Arduinos, connecting them to the wrong voltage can fry them. There are interface ICs that to the translation from the micro to the serial cable. I am assuming that is a commercial inverter and it would surprise me if it were just a logic output.

Your best bet is most probably to get someone with a minimum of knowledge with serial communication and hardware to help you physically at your place. Or prepare for a steep learning curve, including purchasing some tools like an oscilloscope. You need to research the technical information for your inverter. Please [edit] your question to add all new information, at least brand and model of the inverter, optimally links to relevant documentation.

use a serial dongle on a computer to figure out the connections ... get one of these https://duckduckgo.com/?q=serial+dongle&iax=images&ia=images ... and maybe one of these https://duckduckgo.com/?q=serial+dongle&iax=images&ia=images ... cut length of lan cable end for the RJ45 connection ... make sure that the USB dongle can plug into the DB9 breakout ... buy one with female connector and the other with male connector

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


text:
Error while trying to connect CH341 driver
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?

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/


text:
Control esp32 via keyboard keys
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?

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.

it is good to see that you were able to figure this out yourself ... the test of all values in loop()  is somewhat redundant, just call movimento() without an if statement

Thanks, and good point. I narrowed down the code to explain the logic here, but in the project I'm making this 'if' statement is actually necessary. That's true nonetheless, as it is, that's just a unnecessary 'if' statement.


text:
Lilypad sends corrupted data on Serial
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.
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");
}

Arduino is connected to the FTDI tool as shown here

@jsotola I have it connected as shown on the picture here https://i.stack.imgur.com/axOsO.png

@jsotola updated, but that doesn't really answer my question

Just as an experiment, try changing the code to make the serial port 4800 and if that doesn't work, try 119200. Alternatively, change the speed in the Terminal Monitor window to double or halve the speed.

I say that because it looks like the baud rate is wrong. Don't change both settings at once.

Does the LED blink with the 3-second delay?

@NickGammon changing the baud rate to 4800 while keeping 9600 in the terminal solved this. Now I can see properly written "Hello World" in the console. Can you post it as an answer here and I'll mark it as solved? Also, could you please explain why is that? Thanks a lot

He shouldn't. The answer should follow from the question. What he offered you was perfectly good diagnostic advice. At least he realized that and put it in a comment this time. What you've put in your comment is information that can be integrated into the question. A real answer as to why (or "what" following from what you asked) is still unknown.

What we have now is just an unexplained work-around. We still need to find out the underling reason, why you need different baudrates for your Lilypad and the PC. Is it possible that the IDE thinks that the Lilypad has a 16 MHz clock?

@timemage My answer (now posted) did follow from the question. What else would it follow from?

All three Lilypad boards are 8 Mhz. Of the two non-USB versions that take an FTDI style header, only the matching board definition will upload successfully because they have different bootloader baud rates. As the busybee said, what you have is a workaround. The actual cause and potential problem is still there. Incorrect fuses, wrong bootloader, boards.txt has been altered, core altered to set CLKPR, who knows? And we and future readers not going to know as things stand. I appreciate that you're happy to see your message printing though.

@timemage I agree we haven't solved the underlying problem, but without knowing exactly what board they selected, whether or not boards.txt was altered, the fuses on the Lilypad, etc. then the solution remains as a work-around. However quite possibly no-one else will have this exact problem. Even if they did, how would we know for sure it was the same problem?

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.


text:
What can be the reason for a Stack canary watchpoint triggered (loopTask) on a https get() command?
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!

Don't you have to explicitly free the storage assigned to a DynamicJsonDocument as used say in getPumpInfo(). See  https://arduinojson.org/v6/how-to/reuse-a-json-document/

I don't reuse the json document i recreate it each time! And the error happend before i create the json document!! The error happen on a GET call!

Ok, so, this is likely due to your stack not being big enough. Every time a function call is made, information needs to be pushed onto the stack. It'll be popped off when that function call returns. When you call into a library - you're calling a function. When that library function calls a function, it uses the same exact stack. Most likely, your stack is not big enough. Increase your stack size.

Also, make sure you're not making a recursive call ;)

This could also happen if you have a stray pointer and happen to modify the canary value stored in the stack. This value is periodically checked to see if it changes - IT SHOULD NEVER CHANGE - but it did. You could have your own bug that's causing this to happen, even though the stack may be the proper size. What I described above is what happens when you push something onto a full stack - it must overwrite that value, which will trigger what you're seeing.

Could this be done directly without using buf and save 1k stack space char buf[sizeof(pumpInfo)]; serializeJson(_tmp, buf); strcpy(pumpInfo, buf); ?
This also has what appears to be an unnecessary intermediate variable String response = https.getString(); Serial.print(response); possibly fragmenting heap storage. Maybe also look here because the data sizes in your program are huge: https://arduinojson.org/v6/how-to/reduce-memory-usage/. Some systems also impose a limit on the maximum URL size for HTTP GET. The stack size of the ESP32 is also limited and further reduced by heap growth.

The json object you shown has nothing related to the data you are trying to desrialize in the getPumpInfo(), so what exactly is the json object (before you are trying to deserialize it) that you received? how long is it? Also if you want others to help, trim down your code to the minimum reproducible code, and only show that code...


text:
Shift register 74595 does not shift values
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.

Following is a small code for the same:

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?

where are the current limiting resistors?

Try printing this value out int bitToSet = Serial.read() - 48; Depending on how you have configured the serial monitor you may have terminating characters in there.

The comment about the current limiting resistors is a very important one, especially because you haven't mentioned what those are actually doing. My guess is they are not lit, because they were over-currented and are now open.

Sorry I haven't shown this in the schematic above but I am sort of using an LED module that has the resistors with it.

Hint: A Power Supply the Arduino is NOT! You are probably having the arduino's regulator overheating and shutting down. This is a SWAG as the schematic does not show power sources other then the Arduino.

Yes it is true that I am using the Arduino as a power supply. I will try using an external power supply. Hopefully that solves it.

This problem has been resolved. As it turns out, the error was with the serial monitor, as it sent more than one value to the variable (the second one causing the bitToSet to be negative). This is most likely due to terminating characters as pointed out by @6v6gt. I guess it is much better to use standard functions like atoi() to convert serial monitor data to integers.

In relation to my previous comment, the problem was due to my Serial monitor adding a NL (new line) character to my inputs, once configured to not do this, the program works fine.

I guess that qualifies as an answer which you can add yourself and maybe you get a few brownie points. Thanks anyway for reporting back.

Yeah actually I tried doing that but cannot since the question was closed. I have edited it and submitted for reopening though.


text:
How to use a DF Mini Player Busy Pin to start an LED Sequence?
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:
// 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) 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?

your problem has nothing to do with the DF player, in fact it is just clutter in the question ..... forget about the DF player for now, that part works ... write simple code that turns the lights on for one second, turns lights off for one second and repeats

so the fade code that im using in my sketch is actually part of the arduino built in examples (01. basics > fade). Which works when its not nested inside the if statement - but the tradeoff is that it "works" at all times with no trigger.

then there is something wrong with the if statements ... add debugging code to your program

well thats actually the thing, I put in a Serial.print ("song is playing. lights are go"); to run if/when BUSY state is picked up by my code in the serial monitor. That does actually come through. But the Light sequence does not. Thats the thing that keeps confusing me. I thought for sure once I got my Serial Monitor to read that, I would have success, but that was not the case :(

like I said before ... write a new program that only turns the lights on and off ... no DF player code


text:
Addressable LEDs using SM16704
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 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.

the timing is quite different ... you could rewrite the library

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.


text:
How to detect, if Serial is really connected to listening PC program? (on atmega32u4)
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 Arduino Leonardo(Atmega32u4) - 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
    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?

This is weird. Sending data to a disconnected serial port shouldn't slow things down, the data just gets sent to nowhere. I'm not sure what if (Serial) exactly does on that board, but have you tried just removing that test?

You have something weird going on with the }; before StatusOn(); and the lack of { after if (displayTime()). I'm guessing it's just from editing, but it's something you may want to fix in the question.

@timemage I fixed the formating for better readability, but the code was correct. The syntax is if (condition) command; where command may be compound command, like { ... } or simple command, or another if (condition) command; block as it was here. You are right, that the formating was remainder from earlier changes.

@PMF I had it first totally without the if (Serial), in hope that the output will just 'go nowhere' eventually and all will work the same. But I had seen the ?timeouts?, which behaved the same as is described in Problem section, so I tried the if (Serial) construction recomended somewhere, but it did not work. I also tried other conditions as in Difference from other section, but the problem remains.

@gilhad it's mostly the semicolon that throws things. You can put a semicolon after code block like that, but it's not terminating it. it's actually it's own statement called a "null statement". you use them in places to fulfill a syntax requirement. but, when you put it there, without a requirement, it just makes it look like you intended to do something else. if you really want to throw people put a number in front of it like if (condition) {} 7; it'll still be "correct", but it will look even less so than what you have. =)

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.
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:
python -m pip install pyserial

My Arduino test code was:
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.

Thank you very much, the screen was culprit after all. But it is too convenient for me and I call it from Makefiles all the time, so I found fix for it, which close the Serial anyway :)

Thanks to Nick Gammon for his answer, the problem is really in the screen program.
There is detailed explanation from Majenko in
if(Serial) 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

Re “the problem is really in the screen program”: I suggest you ditch screen and try picocom. This is a small program (tiny compared to screen) for accessing devices that provide serial consoles. It does only one thing but does it well; it does not try to emulate or multiplex terminals. I do not know whether picocom defaults to the correct behavior, but it keeps you in control: see the options --noreset, --hangup, --lower-rts, --raise-rts, --lower-dtr and --raise-dtr.

@EdgarBonet can I somehow "type in" file to picocom? As if I open picocom /dev/ttyACM0 communicate with Arduino over its Serial.read and then "type-in file lorem.txt" and Arduino will get impression, that I am typing really fast really long texts. (the Serial.read will just receive lots of chars - the content of the file)

I am using Gentoo Linux and I also use serial communication with other 8-bit computers, where I need sometimes send few kilobytes of hexa code (Intel Hex) so it will be more convenient, then simply copy-paste text to terminal window

picocom -b 115200 -s cat /dev/ttyUSB0 works (-s cat) and then C-a C-s ./test_serial.002.0200.s.x.hex


text:
dht11 data on ESP32 NTP clock (updated)
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.
#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
}

why do you think that there are issues? ... nobody will waste time trying to figure out what problems you are seeing ... please describe what you expect to happens, what actually happens and what errors you get ... add all of that to the question ... do not write a comment

my code seems to have some issues could mean anything. Describe the issues. We are not mind-readers.

To try to reproduce whatever these issues are we would have to download all those libraries you used, for which you have not provided links. It is not uncommon for libraries to be supplied on different sites, and be of different versions. If there is an error message please copy and paste it.

Move unsigned long currentMillis  = millis(); to the end of the setup() function, and move the rest of TimePeriodIsOver() (actually only two lines of codes needed) to the loop(), and reset the changeDisplayTimer if time is over (you never did that in your code). Write simple straightforward code, and only when it is work, then try to re-factor into function if necessary.

The 'rk' which you mentioned in the title comes from the end of the string "does not work". This statement extracts it: hour = Formatted_date.substring(11, 13);. The following statement reads past the end of the string so will return invalid data: minute = Formatted_date.substring(14, 16);. This comment in the program: // your code reading in and printing humidity and temperature is to inform you where you should write your code to complete this assignment.


text:
Arduino pulls i2c bus down
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
    #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 2

Screenshot 3

and wiring diagram

please add a clear, answerable question to your post ... also add the code listing

The bus needs a pull-up.

That logic level shifter must be bidirectional. If it has markings on it like TX/RX then it is unlikely to be bidirectional. There should be pullup resistors (say 4.7k) on the low and high voltage sides of the I2C bus. If at least one module on each side of the level shifter has these then that should be enough. The module mpu6050 (and maybe others also) has 3.3 volt logic and should be on the Raspberry Pi side of the level shifter.

added code listing.

The BME280 is apparently a 3.3V device, so I don't know why you have it on the 5V part of the circuit.

The Pro Mini can also run at 3.3V - you are making it hard for yourself with the logic level converter.

From your newly posted code. How is it going to break out of this infinite loop ?  else { while (true) { Wire.read(); } }

@NickGammon How do I power it from 3.3V? Does it have no 3.3V pin or can 3.3V be supplied to the VCC pin too?

You have got to find and understand the schematics of the those modules you are using. Here https://www.waveshare.com/w/upload/4/42/BME280-Environmental-Sensor-Schematic.pdf for example is a BME280 module. The chip itself is 3.3v but the module has been designed for 5v operation with a built in level shifter. If this is the one you are using then, in this case, it is correct to connect it to the 5v side. What about the coding error that has been pointed out in my previous comment. Would that not cause the symptoms you have reported ?

You show the Raspberry Pi as having 3.3V on SDA and SCL - where does that come from? You show your devices like the BME280 with a 3.3V supply. Why are you asking where 3.3V comes from? If you don't want to do that then look at 6v6gt's comment. You need a bidirectional level shifter, otherwise I2C won't work.

The global variables which are used in the loop and updated in receiveEvent() should be declared as volatile because the call to this routine is via an interrupt. You should show also the code used on the I2C master.

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:

Image credit: Sparkfun: Bi-Directional Logic Level Converter Hookup Guide
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.
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).


text:
Arduino (Mega 2560) Ethernet Shield 2 (W5500) - Can't connect
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.
    #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!

the WebClient example works? does it work with DHCP assigned IP address? try to wait half a second and then again test the link status.


text:
Code not Executing Reliably on Push Button Activation
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.
    #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);
      }
    }

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.