message:
I am attempting to control two stepper motors by using serial input. My code works, however I have to press the new directional command multiple times

I am using two 28BYJ-48 stepper motors with two motor drivers that they come with. (I don't know the name of them.)

Here is my code:

    /*
     * Code to control two stepper motors simultaneously using the stepper library function calls
     * This code has functions which make calls to initiate one step from each of the two motors at a time
     * therefore each motor takes it in turn to step with the end result of them both running together
     * the variable 'lastCall' allows for a continuous input to keep the steppers running if there is no serial input
     * Written by Gabriel Adams  - March 2023 -
     */
    #include <Stepper.h>

    //definitions for each command to be recieved via serial port
    #define COMMAND_LEFT 'a'
    #define COMMAND_RIGHT 'd'
    #define COMMAND_FORWARD 'w'
    #define COMMAND_BACK 's'
    #define COMMAND_STOP ' '

    //Number of steps per internal motor revolution
    const float STEPS_PER_REV = 32;

    //Amount of gear reduction
    const float GEAR_RED = 64;

    //Number of steps per geared output rotation
    const float STEPS_PER_OUT_REV = STEPS_PER_REV * GEAR_RED;

    //enter the steps per rev for your motors here
    int stepsInRev = STEPS_PER_OUT_REV ;

    //this sets the value for the for loops and therefore sets the amount of steps in each call
    int num_of_steps = 1;
    // setup pins for each driver motor1 ~ IN1, IN2, IN3, IN4; motor2 ~ IN1, IN2, IN3, IN4
    Stepper myStepper1(STEPS_PER_OUT_REV, 4, 6, 5, 7);
    Stepper myStepper2(STEPS_PER_OUT_REV, 8, 10, 9, 11);
    // variable to store the last call to the serial port
    char lastCall = ' ';

    //I had prototyped all of the functions here, but for some reason the Arduino IDE didn't like it
    //so they are coded out until I an figure out why
    //void forwardStep();
    //void backwardStep();
    //void leftStep();
    //void rightStep();
    //void allStop();

    //to move the motors forward
    void forwardStep(int steps){
      Serial.println("forward");
      // step one step each forward
      myStepper1.step(1);
      myStepper2.step(1);
      delay(10);
    }

    // to move the motors back
    void backwardStep(int steps){
      Serial.println("backward");
      // step one step each backward
      myStepper1.step(-1);
      myStepper2.step(-1);
      delay(10);
    }

    // to move the motors in opposite directions (left)
    void leftStep(int steps){
      Serial.println("left");
     // step one step each left
      myStepper1.step(1);
      myStepper2.step(-1);
      delay(10);
    }

    // to move the motors in opposite directions (right)
    void rightStep(int steps){
      Serial.println("right");
      // step one step each right
      myStepper1.step(-1);
      myStepper2.step(1);
      delay(10);
    }

    // to power down the motor drivers and stop the motors
    void allStop(){
      Serial.println("stop");
      // steppers stop
      PORTD = B00000000; //sets all of the pins 0 to 7 as LOW to power off stepper1
      PORTB = B00000000; //sets all of the pins 8 to 13 as LOW to power off stepper2
    }
    void setup() {
      Serial.begin(9600);//start the bluetooth serial port - send and recieve at 9600 baud
      // set the speed at 60 rpm:
      myStepper1.setSpeed(700);
      myStepper2.setSpeed(700);
    }

    void loop() {
    //check to see if there is serial communication and if so read the data
    if(Serial.available()) {
    char data = (char)Serial.read();
    // switch to set the char via serial to a command
    switch(data) {
      case COMMAND_FORWARD:
        forwardStep(num_of_steps);
        break;
      case COMMAND_BACK:
        backwardStep(num_of_steps);
        break;
      case COMMAND_LEFT:
        leftStep(num_of_steps);
        break;
      case COMMAND_RIGHT:
        rightStep(num_of_steps);
        break;
      case COMMAND_STOP:
        allStop();
        break;
    }
    // set the 'lastCall' variable to the last call from the serial
    lastCall = data;
    }

    char data = lastCall;

    Loop(lastCall);
    Serial.read();

    }

    void Loop(char x){
    switch(lastCall) {
      case COMMAND_FORWARD:
        forwardStep(num_of_steps);
        break;
      case COMMAND_BACK:
        backwardStep(num_of_steps);
        break;
      case COMMAND_LEFT:
        leftStep(num_of_steps);
        break;
      case COMMAND_RIGHT:
        rightStep(num_of_steps);
        break;
      case COMMAND_STOP:
        allStop();
        break;
    }
    return lastCall;

    (char)Serial.read();
    }

body:
The problem is, that you are reading from the Serial buffer without using the data. There are three places in your code, where you use `Serial.read();`:

1. You use in in the block with your serial code and you set `lastCall` accordingly. This is ok.
2. Then you use it at the end of `void loop()`, but you don't assign the value to anything.
3. And you use it at the end of your own `Loop()` function, again without assigning the value to anything.

Short explanation how `Serial` works: The Uno has hardware to handle Serial communication in the background via interrupts. The data arrives at the Uno and gets automatically (in the background) places in the internal buffer of the `Serial` object. The call to `Serial.read()` removes the oldest byte from the buffer (so that you get the bytes in order of arrival) and returns it. If there is no new data byte available it will return `-1`.

So when you just use `Serial.read()` without assigning the value to anything, you are basically throwing away data bytes from the Serial buffer.

> I was thinking the Serial.read() command would ensure more immediate reads of serial inputs.

Reading the data from the buffer is not enough. You actually have to do something with it. Otherwise you are just reading without reacting. So please remove the two calls to `Serial.read()`, only leaving the the one in your `if(Serial.available())` block.

> how at the moment it won't immediately change direction when I give a new command, how do I utilize the Serial.read() command to quickly move to a new loop?

You should remove all the calls to `delay()`. Currently your code spends the most time in these delays, doing nothing. Instead you can use the non-blocking coding style from the `BlinkWithoutDelay` example, that comes with the Arduino IDE. It uses `millis()` as a time keeper, only executing the code (blinking an LED in the example; doing a step in your code) when it is time to do  so. There are many tutorials about that online.

If you want you can even go further and switch to the `AccelStepper` library, which is more capable than the standard `Stepper` library. It lets you set the speed and acceleration and then you simply run the motor by executing the `run()` method often enough. No need for your own timing of steps then, because the library is handling that. Though this will be a bigger change to your code.


sender: user

message:
IDE will not upload to ATTiny88

I was successfully compiling sketches and uploading to various MCUs, including the ATTiny88.  Suddenly the IDE quit compiling and complained of various missing compilers.  I found and corrected an issue with my anti-virus, which helped some.  Eventually I uninstalled and wiped the entire IDE.  I then reinstalled from scratch, and now everything compiles OK, butt he IDE will not upload the code to the ATTiny88.  This is done a bit differently than other MCUs.  Instead of creating a virtual com port, the driver creates a different virtual USB device, and then searches for the MCU on that USB device.  The driver should cause the "unknown" MCU to become known to the system, but this does not happen, despite having installed the drivers.  The IDE, in turn, does not create a specific error when uploading, but merely times out.  How can I get the virtual driver working again?  I am running IDE 1.8.13 on a Windows 7 PC.
[![Device Manager][1]][1]
[![Digistump Drivers][2]][2]
[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/gi6vZ.png
  [2]: https://i.stack.imgur.com/JbbCc.png
  [3]: https://i.stack.imgur.com/oPWjk.png

sender: assistant

body:
There is an updated driver that fixes the issue. It will still show as unknown, however it will properly connect for programming when you reset or power up the ATTiny. NOTE: One component will say it failed during install, but it doesn't matter, ignore it, it will work.

Driver is here: https://github.com/MHEtLive/MHEtLiveArduino/releases/download/1.0.0/2.0a4.rar


message:
LVGL v8.2 on ESP32-S3 colour issue ILI9341 TFT LCD Arduino IDE

I have [ILI9341 320x240px TFT LCD screen][1] which I am using with ESP32-S3-wroom-1 module.

I have tested with TFT_eSPI and works fine, but when using LVGL, I am seeing weird artefacts on the edges.
[![enter image description here][2]][2]

I am using Arduino IDE

Started off the sketch from

https://github.com/lvgl/lvgl/blob/master/examples/arduino/LVGL_Arduino/LVGL_Arduino.ino

Havent changed sketch file much.

I am using LVGL latest v8.2.0

```c
/*====================
   COLOR SETTINGS
 *====================*/

/*Color depth: 1 (1 byte per pixel), 8 (RGB332), 16 (RGB565), 32 (ARGB8888)*/
#define LV_COLOR_DEPTH 16

/*Swap the 2 bytes of RGB565 color. Useful if the display has an 8-bit interface (e.g. SPI)*/
#define LV_COLOR_16_SWAP 1

/*Enable features to draw on transparent background.
 *It's required if opa, and transform_* style properties are used.
 *Can be also used if the UI is above another layer, e.g. an OSD menu or video player.*/
#define LV_COLOR_SCREEN_TRANSP 1

/* Adjust color mix functions rounding. GPUs might calculate color mix (blending) differently.
 * 0: round down, 64: round up from x.75, 128: round up from half, 192: round up from x.25, 254: round up */
#define LV_COLOR_MIX_ROUND_OFS 0

/*Images pixels with this color will not be drawn if they are chroma keyed)*/
#define LV_COLOR_CHROMA_KEY lv_color_hex(0x00ff00)         /*pure green*/
```
`LV_COLOR_SCREEN_TRANSP 1` was originally 0 changing it did not change anything.

I am following the FAQ which mentions

> 1.6.7 Why I see nonsense colors on the screen?
Probably LVGL's color format is not compatible with your displays color format. Check LV_COLOR_DEPTH in
lv_conf.h.
If you are using 16 bit colors with SPI (or other byte-oriented interface) probably you need to set LV_COLOR_16_SWAP
 1 in lv_conf.h. It swaps the upper and lower bytes of the pixels.

as you can see above in the config, the values are as recommended.

Any help will be greatly appreciated.

  [1]: https://de.aliexpress.com/item/1005003943508410.html?spm=a2g0o.order_list.order_list_main.145.21ef5c5fPSOh1Q&gatewayAdapt=glo2deu
  [2]: https://i.stack.imgur.com/3TBsv.jpg

body:
Turns out, I had to disable `LV_COLOR_16_SWAP`
I had been trying with different colour depths and everything else, I still cannot see gradients drawn properly, but the colours seem to be correct now.[![enter image description here][1]][1]

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


message:
A fatal error occurred: Failed to connect to ESP32: Wrong boot mode detected (0x13)! The chip needs to be in download mode. [upload] Error 2

I have seen so many people complain about this same error and they were given a multitude of answers to help with this error, but nothing so far has worked for me.

Everything was working fine until I upgraded to Win 11 and the latest version of VS Code. I also attempted uploading with the Arduino IDE and no success.
I'm at the point of throwing the ESP32 boards into a box, and moving onto an alternative until someone comes up with a different solution.

This is my failed punch list gathered from the many postings about this error:

1)  Followed these instructions: https://docs.espressif.com/projects/esptool/en/latest/troubleshooting.html  without success.
2)  Removed and Re-installed the CP210x & CH340 (ESP32-CAM Programming Board) Windows Drivers
3)  Tried both VS Code & Arduino IDE with Ubuntu on two different computers.
4)  For Ubuntu, I added "User" to dialout.
5)  Pressed IO0 & RST to force the ESP32 into Boot Mode.
6)  Verified USB cables were data cables.
7)  Tested 6 ESP32 Dev Kit boards to make sure I didn't have a bad one.
8)  Soldered a 10 uF capacitor across the EN pin and GND
9)  Added: monitor_dtr = 0 & monitor_rts = 0 to platformio.ini
10) The two different Boards ESP32 DEV Kit & ESP32-CAM Boards, both appear in Device Manager.
11) Attempted to upload the code in Win 10, and had the same results.

I'm a beginner with this technology, so please keep this in mind when you answer my question.
Thanks,in advance, to anyone who can help me.

body:
I purchased a **NodeMCU** clone **ESP32** board and encountered this error.

>A fatal error occurred: Failed to connect to ESP32: Wrong boot mode detected (0x13)! The chip needs to be in download mode. [upload] Error 2

There were 2 separate problems, and I was stumped by their combined effect:

1. Normally such boards automatically go into program upload mode using the RTS/CTS pins on the USB serial. This self-resetting mechanism did not work on my board. I had to manually press the BOOT button on GPIO0 in order to upload code.

2. I guessed the above problem correctly, but there was an additional quirk: ESPTool sends a RESET command just before uploading the code. So you have to press the BOOT button *when you see the message 'Connecting..' on the Arduino IDE*. Normally we will hold the BOOT button and press reset in order to put the board in boot mode. This did not work with this board. Pressing the button at the time of power up/ connecting the USB cable etc. all failed. You have to press the BOOT button at the right time!

In addition to the Arduino IDE, I observed the same behavior with other tools like Tasmotizer. In all cases, the solution was the same.


message:
Processing doesn't respond to arduino

First of all if I make a wrong sentence this is because my main language isn't english.
I have a homework so i am trying to make a radar with Arduino IDE and Processing. I found and wrote the codes from internet but processing does not respond to ultrasonic sensor and i tought maybe it isn't detecting the serial port.
Code from Processing:
```
import processing.serial.*; // imports library for serial communication
import java.awt.event.KeyEvent; // imports library for reading the data from the serial port
import java.io.IOException;

Serial myPort; // defines Object Serial
// defubes variables
String angle="";
String distance="";
String data="";
String noObject;
float pixsDistance;
int iAngle, iDistance;
int index1=0;
int index2=0;
PFont orcFont;

void setup() {

 size (1600, 900); // ***CHANGE THIS TO YOUR SCREEN RESOLUTION***
 smooth();
 myPort = new Serial(this,"COM3", 9600); // starts the serial communication
 myPort.bufferUntil('.'); // reads the data from the serial port up to the character '.'. So actually it reads this: angle,distance.
 orcFont = loadFont("Calibri-Bold-48.vlw");
}

void draw() {

  fill(98,245,31);
  textFont(orcFont);
  // simulating motion blur and slow fade of the moving line
  noStroke();
  fill(0,4);
  rect(0, 0, width, height-height*0.065);

  fill(98,245,31); // green color
  // calls the functions for drawing the radar
  drawRadar();
  drawLine();
  drawObject();
  drawText();
}

void serialEvent (Serial myPort) { // starts reading data from the Serial Port
  // reads the data from the Serial Port up to the character '.' and puts it into the String variable "data".
  data = myPort.readStringUntil('.');
  data = data.substring(0,data.length()-1);

  index1 = data.indexOf(","); // find the character ',' and puts it into the variable "index1"
  angle= data.substring(0, index1); // read the data from position "0" to position of the variable index1 or thats the value of the angle the Arduino Board sent into the Serial Port
  distance= data.substring(index1+1, data.length()); // read the data from position "index1" to the end of the data pr thats the value of the distance

  // converts the String variables into Integer
  iAngle = parseInt(angle);
  iDistance = parseInt(distance);
}

void drawRadar() {
  pushMatrix();
  translate(width/2,height-height*0.074); // moves the starting coordinats to new location
  noFill();
  strokeWeight(2);
  stroke(98,245,31);
  // draws the arc lines
  arc(0,0,(width-width*0.0625),(width-width*0.0625),PI,TWO_PI);
  arc(0,0,(width-width*0.27),(width-width*0.27),PI,TWO_PI);
  arc(0,0,(width-width*0.479),(width-width*0.479),PI,TWO_PI);
  arc(0,0,(width-width*0.687),(width-width*0.687),PI,TWO_PI);
  // draws the angle lines
  line(-width/2,0,width/2,0);
  line(0,0,(-width/2)*cos(radians(30)),(-width/2)*sin(radians(30)));
  line(0,0,(-width/2)*cos(radians(60)),(-width/2)*sin(radians(60)));
  line(0,0,(-width/2)*cos(radians(90)),(-width/2)*sin(radians(90)));
  line(0,0,(-width/2)*cos(radians(120)),(-width/2)*sin(radians(120)));
  line(0,0,(-width/2)*cos(radians(150)),(-width/2)*sin(radians(150)));
  line((-width/2)*cos(radians(30)),0,width/2,0);
  popMatrix();
}

void drawObject() {
  pushMatrix();
  translate(width/2,height-height*0.074); // moves the starting coordinats to new location
  strokeWeight(9);
  stroke(255,10,10); // red color
  pixsDistance = iDistance*((height-height*0.1666)*0.025); // covers the distance from the sensor from cm to pixels
  // limiting the range to 40 cms
  if(iDistance<40){
    // draws the object according to the angle and the distance
  line(pixsDistance*cos(radians(iAngle)),-pixsDistance*sin(radians(iAngle)),(width-width*0.505)*cos(radians(iAngle)),-(width-width*0.505)*sin(radians(iAngle)));
  }
  popMatrix();
}

void drawLine() {
  pushMatrix();
  strokeWeight(9);
  stroke(30,250,60);
  translate(width/2,height-height*0.074); // moves the starting coordinats to new location
  line(0,0,(height-height*0.12)*cos(radians(iAngle)),-(height-height*0.12)*sin(radians(iAngle))); // draws the line according to the angle
  popMatrix();
}

void drawText() { // draws the texts on the screen

  pushMatrix();
  if(iDistance>40) {
  noObject = "Out of Range";
  }
  else {
  noObject = "In Range";
  }
  fill(0,0,0);
  noStroke();
  rect(0, height-height*0.0648, width, height);
  fill(98,245,31);
  textSize(25);

  text("10cm",width-width*0.3854,height-height*0.0833);
  text("20cm",width-width*0.281,height-height*0.0833);
  text("30cm",width-width*0.177,height-height*0.0833);
  text("40cm",width-width*0.0729,height-height*0.0833);
  textSize(40);
  text("Obje: " + noObject, width-width*0.875, height-height*0.0277);
  text("Açı: " + iAngle +" °", width-width*0.48, height-height*0.0277);
  text("Mesafe: ", width-width*0.26, height-height*0.0277);
  if(iDistance<40) {
  text("        " + iDistance +" cm", width-width*0.225, height-height*0.0277);
  }
  textSize(25);
  fill(98,245,60);
  translate((width-width*0.4994)+width/2*cos(radians(30)),(height-height*0.0907)-width/2*sin(radians(30)));
  rotate(-radians(-60));
  text("30°",0,0);
  resetMatrix();
  translate((width-width*0.503)+width/2*cos(radians(60)),(height-height*0.0888)-width/2*sin(radians(60)));
  rotate(-radians(-30));
  text("60°",0,0);
  resetMatrix();
  translate((width-width*0.507)+width/2*cos(radians(90)),(height-height*0.0833)-width/2*sin(radians(90)));
  rotate(radians(0));
  text("90°",0,0);
  resetMatrix();
  translate(width-width*0.513+width/2*cos(radians(120)),(height-height*0.07129)-width/2*sin(radians(120)));
  rotate(radians(-30));
  text("120°",0,0);
  resetMatrix();
  translate((width-width*0.5104)+width/2*cos(radians(150)),(height-height*0.0574)-width/2*sin(radians(150)));
  rotate(radians(-60));
  text("150°",0,0);
  popMatrix();
}
```
Code from Arduino IDE:
```
#include <Servo.h>   // servo motor kütüphanesi
#define trigPin 4    // ultrasonik sensör trig pini
#define echoPin 3    // ultrasonik sensör echo pini
Servo servoMotor;     // servo motor nesnesi
int angle = 0;        // servo motor açısı
long duration, distance;  // ultrasonik sensör mesafesi

void setup() {
  Serial.begin(9600);  // seri haberleşme hızı
  servoMotor.attach(9); // servo motor pin numarası
}

void loop() {
  for(angle = 0; angle < 180; angle += 10){  // servo motor açıları
    servoMotor.write(angle);  // servo motoru hareket ettir
    delay(200);               // bekleme süresi
    distance = getDistance(); // mesafe ölçümü
    Serial.print(angle);      // açıyı yazdır
    Serial.print(",");
    Serial.println(distance); // mesafeyi yazdır
  }
}

long getDistance(){ // ultrasonik sensör mesafe ölçümü
  pinMode(trigPin, OUTPUT);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);
  distance = duration / 58.2;
  return distance;
}

```
Thank you for the help!

body:
Your processing code is looking for something that ends in a '.'

Your arduino code is sending angle,distnace[new line]

So either change your processing code to look for '\n' (the new line character) rather than '.' or change your arduino code to add a . to the end:

    Serial.print(angle);      // açıyı yazdır
    Serial.print(",");
    Serial.print(distance); // mesafeyi yazdır
    Serial.print(".");


message:
UDP Packet Loss

I have an application on a PC that sends **10 UDP packets** to an Arduino Portenta board.  When sending packets with no delay, half of them are lost.  Wireshark shows the packets are correctly sent by the PC.  If I busy-wait 1ms between each message on the PC, the Arduino receives everything.

I tried to disable the processing done when receiving a message, but it doesn't help.

I know UDP is not a reliable protocol.  Still, having half the packets lost while the PC is directly connected to the Arduino is surprising.  I'm only trying to send 10 packets!

Is there an option to increase the receive buffer?  I would have tried increasing SO_RCVBUF.

Any other idea?

Thank you

body:
UDP does not guarantee delivery.

https://en.wikipedia.org/wiki/User_Datagram_Protocol

>  It has no handshaking dialogues, and thus exposes the user's program to any unreliability of the underlying network; there is no guarantee of delivery, ordering, or duplicate protection.

You have chosen a protocol that is inherently not guaranteed to be delivered, and thus you have to work around it by:

* slowing transmission
* accepting that not all packets will be received
* some other mechanism


message:
Have I ruined my Arduino Nano with my terrible soldering (technique and tools!)

So I bought a Arduino Nano and a *very* cheap soldering iron and solder from Alibaba. I was attempting to solder in some connections and failing pretty hard. A small resister popped off when trying to solder a wire to ground. I was pretty good when soldering in high school...but it's been a while since then.

By just plugging it into my computer, I was able to upload a simple program which switches the LED on and off - and that still works.

I'm not clearly not competent enough and I don't have a good enough soldering iron to do surface mount soldering to repair it. So I'm wondering if it'll still do what I want it to do.

My overall aim is to build a [simple music player][1] for my 3 year old.

My question is, what does that resistor do? Have I ruined the board?

[![Arduino Nano with missing resistor][2]][2]

  [1]: https://blog.arduino.cc/2020/08/01/juuke-is-an-arduino-powered-rfid-music-player-for-the-elderly/
  [2]: https://i.stack.imgur.com/jqjWY.jpg

body:
You haven't answered either of my questions in the comments (where is the component?, what colour is it?) but judging by the position I think it is on the board it is the 0.1 µF capacitor which is part of the reset circuitry. It is designed to briefly pull /RESET low on power-up, or when DTR is asserted.

> If I know what function doesn't work, then I know whether I can still do my project.

Either the board works or it doesn't. There won't be "some function" that won't work. You may have problems resetting it but simply pressing the reset button on the other side (if there is one) should have the same effect.

I suggest you get a better soldering iron with a smaller tip. Also practice soldering a bit. The wire you show in the photo should have a blob of solder around it, not going "raw" into the hole as you have it. I also don't see how you can somehow unsolder a capacitor which is a couple of millimetres away from the pins on the edge of the board. Definitely more practice required.

A common technique with boards like the Nano is to solder a line of pins down each side like this:

[![Nano underneath][1]][1]

Then plug the whole thing into a breadboard and wire up your project on the breadboard. Then you don't need to worry about your soldering technique so much (once you have soldered on the pins, and you can get a friend to help you).

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


message:
An error is shown as sendCommand was not declared in this scope.how to rectify it

#include <LiquidCrystal.h>
    LiquidCrystal lcd(2,8,6,5,4,3);
    #include <SoftwareSerial.h>
    #define RX 9
    #define TX 10
    //ESP8266 CODE
    String AP = "OPPO F11 PRO";       // AP NAME
    String PASS = "bhargav123"; // AP PASSWORD
    String API = "DWX3OYUU26GI5IJ7";   // Write API KEY
    String HOST = "api.thingspeak.com";
    String PORT = "80";
    int countTrueCommand;
    int countTimeCommand;
    boolean found = false;
    int valSensor = 1;

    SoftwareSerial esp8266(RX,TX);

    void setup() {
      // put your setup code here, to run once:
     Serial.begin(9600);
     lcd.begin(16,2);
     lcd.setCursor(0,0);
     lcd.print("Cable");
     delay(1000);
     lcd.setCursor(0,1);
     lcd.print("Fault Detection");
      pinMode(A0,INPUT);
      pinMode(A1,INPUT);
      pinMode(A3,INPUT);
      pinMode(A4,INPUT);
      pinMode(A5,INPUT);

    //ESP8266 CODE

      esp8266.begin(115200);
      sendCommand("AT",5,"OK");
      sendCommand("AT+CWMODE=1",5,"OK");
      sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");

    }

    void loop() {
    //ESP8266 CODE
    String getData = "GET /update?api_key="+ API +"&field1="+Insulation();
     sendCommand("AT+CIPMUX=1",5,"OK");
     sendCommand("AT+CIPSTART=0,\"TCP\",\""+ HOST +"\","+ PORT,15,"OK");
     sendCommand("AT+CIPSEND=0," +String(getData.length()+4),4,">");
     esp8266.println(getData);delay(1500);countTrueCommand++;
     sendCommand("AT+CIPCLOSE=0",5,"OK");

    String Insulation1(){
      if(value>=500 && value1<=700)
      int xoutput=0;
      else
      xoutput=1;
      return String(xoutput);
    }

      int value1=analogRead(A0);
      delay(1000);
      lcd.clear();
      lcd.setCursor(0,0);
      Serial.println("value1");
      Serial.println(value1);
      if(value1>=500 && value1<=700)
      {
        Serial.println("Insulation at 1KM is good");
        lcd.print("Insul good 1KM");
        delay(3000);
        lcd.clear();
      }
    else
       {
         Serial.println("Insulation at 1KM got damaged");
       lcd.print("Insul damage 1KM");
       delay(3000);
       lcd.clear();
       }
      int value2=analogRead(A1);
      Serial.println("value2 ");
      Serial.print(value2);
      delay(1000);
      if(value2>=500 && value2<=700)
      {
        Serial.println("Insulation at 2KM is good");
        lcd.print("Insul good 2KM");
        delay(3000);
        lcd.clear();

      }
    else{
       Serial.println("Insulation at 2KM got damaged");
      lcd.print("Insul damage 2KM");
       delay(3000);
       lcd.clear();
    }
        int value3=analogRead(A2);
        Serial.println("value3 ");
        Serial.print(value3);
        if(value3>=1000)
        {
          Serial.println("short circuit at 1KM ");
          lcd.print("Short at 1KM");
          delay(3000);
          lcd.clear();
        }
        int value4=analogRead(A3);
        Serial.println("value4 ");
        Serial.print(value4);
        if(value4<=1000)
        {
          Serial.println("Open circuit at 1KM");
          lcd.print("open at 1KM");
          delay(3000);
          lcd.clear();

        }
        int value5=analogRead(A4);
        Serial.println("value5 ");
        Serial.print(value5);
        if(value5>=1000)
        {
          Serial.println("short circuit at 2KM");
          lcd.print("short at 2KM");
          delay(3000);
          lcd.clear();

        }
        int value6=analogRead(A5);
        Serial.println("value6 ");
        Serial.print(value6);
        if(value6<=1000)
        {
          Serial.println("open circuit at 2KM");
          lcd.print("Open at 2KM");
          delay(3000);
          lcd.clear();
        }

    //ESP8266 CODE
        void sendCommand(String command, int maxTime, char readReplay[]) {
      Serial.print(countTrueCommand);
      Serial.print(". at command => ");
      Serial.print(command);
      Serial.print(" ");
      while(countTimeCommand < (maxTime*1))
      {
        esp8266.println(command);//at+cipsend
        if(esp8266.find(readReplay))//ok
        {
          found = true;
          break;
        }

        countTimeCommand++;
      }

      if(found == true)
      {
        Serial.println("OYI");
        countTrueCommand++;
        countTimeCommand = 0;
      }

      if(found == false)
      {
        Serial.println("Fail");
        countTrueCommand = 0;
        countTimeCommand = 0;
      }

      found = false;
     }

     }

body:
First thing: format your code properly. Statements that are at the same
nesting level should have the same amount of indenting. If you find this
rule too hard to follow, you can try the auto-format feature of the
Arduino IDE (Ctrl-T).

Once the code is properly indented, its whole structure should become
clear. Here is what it looks like:

```c++
// Preprocessor directives and declarations of variables...

// Definition of the function "setup":
void setup() {
  // Some code...

  sendCommand("AT",5,"OK");
  sendCommand("AT+CWMODE=1",5,"OK");
  sendCommand("AT+CWJAP=\""+ AP +"\",\""+ PASS +"\"",20,"OK");
}

// Definition of the function "loop":
void loop() {
  // Some code...

  // Nested function definition:
  String Insulation1() {
    // ...
  }

  // More code...

  // Nested function definition:
  void sendCommand(String command, int maxTime, char readReplay[]) {
    // ...
  }
}
```

The C++ language does not support nested function definitions. Even if
it did, using in `setup()` a function that is only defined within
`loop()` would not work. The solution is simple: move the definition of
`sendCommand()` out of `loop()`, into the global scope. Oh, and remove
the definition of `Insulation1()`: it is never used.


message:
ESP32 restart each minute with SW_CPU_RESET

running an ESP32 (ttgo), I get strange behavior.  The unit restarts each minute, around 00 seconds.

I get
```12:31:02.861 -> rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)```
as reason.

I checked flash frequency is 40MHz (80 seems to lead to same issues)

Anyway, if I start the device at 10:00:34, it will restart at 10:01:00 and then at 10:02:00 and so on ...

running this code:   https://github.com/xlyric/pv-router-esp32

Powered by a usb-C phone-power, or on computer usb does the same.

The ttgo is plugged on a board connected to a AC/AC transformer and a current mesure device.

using "esp_register_shutdown_handler", I succed to send a mqtt message "gonna die",  it really rise each minute at 00 seconds

body:
The restart reason suggests that the ESP32 restarts upon software restart command. One should go over the code and see where in the code the restart command is sent. For instance starting from line 451 there is following:
```C
if (config.restart) {
    //delay(5000);
    Serial.print(PV_RESTART);
    ESP.restart();
  }
```


message:
Why is sensitivity (threshold) parameter ignored

Analog pontentiometer connected to an Arduino. simplest possible setup.
The goal is to send a message over `Serial` whenever the value changes.

I do not want to spam the Serial connection to much, so the value has to change by at least `20` (sensitivty threshold) before a message Packet is sent.

However, in reality a message Packet is sent even if the value changed only by `1`. **Why is sensitivity parameter ignored?**

**edit:** After debugging I can see that it enters the first IF-statement in `read()`. The IF statement evaluates to `0` which is super weird. It shouldn't have entered that IF statement!

**MagicPot.h:**

    #define MAGIC_POT_MAX_RAW_VALUE_10B     1023
    #define MAGIC_POT_MAX_RAW_VALUE_12B     4095
    #define MAX_RAW_VALUE_DEFAULT           (MAGIC_POT_MAX_RAW_VALUE_10B)

    class MagicPot
    {
     public:
      typedef void (*callback_fn)();
      MagicPot(uint8_t pin, uint16_t minRead = 0, uint16_t maxRead = MAX_RAW_VALUE_DEFAULT, uint16_t maxRawRead = MAX_RAW_VALUE_DEFAULT): pin(pin), minRead(minRead), maxRead(maxRead), maxRawRead(maxRawRead) {};
      void begin();
      bool read(uint8_t sensitivity = 5);
      uint16_t getValue();
      uint16_t getRawValue();
      uint8_t pin;

     private:
      uint16_t minRead;
      uint16_t maxRead;
      uint16_t maxRawRead;
      callback_fn onChangeCallback;
      uint16_t value;
      uint16_t rawValue;
    };

**MagicPot.cpp:**

    void MagicPot::begin()
    {
     this->onChangeCallback = nullptr;
     this->value = 0;
     this->rawValue = 0;
     pinMode(this->pin, INPUT);
     this->read(0);
    }

    bool MagicPot::read(uint8_t sensitivity)
    {
     this->rawValue = analogRead(this->pin);

     uint16_t value = map(this->rawValue, 0, this->maxRawRead, this->minRead, this->maxRead);

     if (abs(value - this->value) > sensitivity)
     {
      this->value = value;
      return true;
     }
     else if (value < sensitivity && this->value != this->minRead)
     {
      this->value = minRead;
      return true;
     }
     else if (value + sensitivity > maxRead && this->value != this->maxRead)
     {
      this->value = this->maxRead;
      return true;
     }
     return false;
    }

**Arduino code:**

    MagicPot analogPots[] =
    {
        MagicPot(A0),
    }

    void setup() {
      for (MagicPot& x : analogPots) //arr only contains 1 element
        x.begin();
    }
    void loop() {
      for (MagicPot& pot : analogPots) //arr only contains 1 element
      {
        if(true == pot.read(20))
          {
            CPPacket* analogPotChangedPacket = new CPPacket(HWEvent::Switch, pot.pin, pot.getValue());
            SendPacket( &myPacketSerial, analogPotChangedPacket);
            delete analogPotChangedPacket;
          }
      }

    }

**Actual Output: (read from computer(conn via Serial))**

| Type | Error | Target | Value |
| ---- | ----- | ------ | ----- |
| Switch | NONE | 54 | 516 |
| Switch | NONE | 54 | 515 |
| Switch | NONE | 54 | 514 |
| Switch | NONE | 54 | 513 |

**Expected Output:**

| Type | Error | Target | Value |
| ---- | ----- | ------ | ----- |
| Switch | NONE | 54 | 516 |
| Switch | NONE | 54 | 496 |
| Switch | NONE | 54 | 456 |
| Switch | NONE | 54 | 436 |

body:
Consider this subtraction:

```c++
value - this->value
```

Like in any arithmetic operation, the operands undergo [integral
promotion][ip], then [usual arithmetic conversions][uac].
Oversimplifying a bit, “integral promotion” means that types smaller
than `int` get promoted to `int`, whereas “usual arithmetic conversions”
mean the smaller operand gets promoted to the type of the bigger one. If
both types have the same size, the unsigned one wins.

On the Arduino Mega, and `int` is 16 bits. Since the operands of the
subtraction are both `uint16_t`, the types are not changed by these
implicit conversions. The subtraction is performed with the `uint16_t`
type and wraps around modulo 216. If you expect −1, you get
65535.

If you cast one of the operands to `int16_t`, then it will be implicitly
converted back to `uint16_t` by the usual arithmetic conversions, and
you get the same result.

On your PC, an `int` is 32 bits, thus both operands get implicitly
converted to `int` by integral promotion, and you get the expected
signed result.

The simple solution to your problem is to turn all your variables to
`int16_t`. I suggest you always use signed types by default, and revert
to unsigned types when you do need the wraparound semantics of the
arithmetic operations ([it is useful][rollover] sometimes).

[ip]: https://en.cppreference.com/w/cpp/language/implicit_conversion#Integral_promotion
[uac]: https://en.cppreference.com/w/cpp/language/usual_arithmetic_conversions
[rollover]: https://arduino.stackexchange.com/a/12588/7508


message:
Arduino | external power supply and USB at the same time

I have got an Arduino Mega 2560 project with many sensor and outputs.
Right now I’m supplying it with an external stabilized 5V over the 5V pin (so that I’m using only one power source for all sensor, outputs and Arduino.)

I also have a Raspberry PI connected to the Arduino via USB for flashing and also logging.
The Raspberry PI has got an external power supply (and also a board with SSD.)

The problem:
If I unplug the RPI external power supply, the Arduino Mega is supplying the RPI with power!!! That’s exactly what I do not want. (Also it’s far too little power for RPI, which isn’t even booting correctly.)
Even when I power the Arduino Mega 2560 over the barrel plug (stable 9V), the RPI will be provided with a 5V over the USB cable.

I’m looking in the electrical wiring diagram: I can see the FDN304V
The comparison circuit (LM358D) controls this p-channel ***mosfet FPN340P***. But why is it ***USBVCC*** connected if the Gate provides 5V over the LM358D?

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

I saw this interesting articles but I'm a bit confused:

[https://arduino.stackexchange.com/questions/893/what-happens-if-i-power-the-arduino-with-both-the-usb-and-external-power-voltage][2]

[https://arduino.stackexchange.com/questions/893/what-happens-if-i-power-the-arduino-with-both-the-usb-and-external-power-voltage][3]

  [1]: https://i.stack.imgur.com/Awyxd.gif
  [2]: https://www.programmingelectronics.com/power-arduino/
  [3]: https://arduino.stackexchange.com/questions/893/what-happens-if-i-power-the-arduino-with-both-the-usb-and-external-power-voltage

body:
Assuming your question is more along the lines of "How to prevent back driving a USB connected RPi through an externally powered Arduino".

Consider cutting the positive power wire in the USB cable connected between the RPi and the Arduino.

As for this specific question:

> But why is it USBVCC connected if the Gate provides 5V over the
> LM358D?

Is it possible you are describing how a N-Channel MOSFET works?  The MOSFET in the schematic is a P-Channel MOSFET. The net USBVCC is connected to the net +5V when the P-Channel MOSFET gate is LOW. And is not connected when the gate is HIGH.


message:
How to use ESP_LOGx?

I can't get the logging to work on the ESP32.
Here is my example:

    #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
    #include <esp_log.h>

    void setup() {
      Serial.begin(115200);
      ESP_LOGE("Test", "This is a test!");
      delay(1000);
    }

    void loop() {
      ESP_LOGE("Test", "This is a repesting test!");
      delay(1000);
      Serial.println("Serial.print");
      delay(1000);
    }

It only prints `Serial.print` every two seconds, but not the log messages.

body: Thanks to hcheung! I had to set the `Core Debug Level` in the `Tools` menu.


message:
How to return a value from a non integer input between 0-5 from an output range of 0-320 in map() method

I am experimenting using the map() method in an ArduinoIDE sketch in an attempt to obtain a pixel position for a horizontal meter in the range 0-320 from an input value in the range 0-5.  However, when I do this I see in the method that the input must be 'long' type.  Here's my example code:

```
  float voltage = 2.5;
  float meterPosition = map(voltage, 0, 5, 0, 320);
  tft.fillRect(0, 0, meterPosition, 10, TFT_GREEN);
  tft.setCursor(10, 70);
  tft.setTextSize(3);
  tft.println(voltage);
  tft.println(meterPosition);
```

But when I run this, despite the input value being 50% of the input range, I expected the meterPosition value to be 160, but it is 128, due I think because the values for this method must be of type 'long' and so the 'float' value is rounded and becomes a 'long' type (I think that's what is happening!!).

I am confused as to the function of the map() method if you are unable to map any range to any other range without using decimals as the input.  I am obviously missing something here, so what do I need to change in my map() method code for it to work in my example please, if I am unable to use floats?

Thanks.
John

body: Apologies for my stupidity folks!  I think I have realised how to do this, it is simply a matter of scaling the input values and input range by 100.


body:
As you already noticed, the `map()` function is meant to work with the
`long` data type. Here is [its implementation][1]:

```c++
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
```

If you want to use floats, you could write a version of this function
that works with floats. Note, however, that since you are using zeros
for both `in_min` and `out_min`, the expression simplifies itself to the
point of becoming trivial:

```c++
float meterPosition = voltage * 320 / 5.0;
```

I would suggest two small changes to this expression though:

 * add parentheses around `(320 / 5.0)`: this ratio will then be
   evaluated at compile-time and you will save an expensive run-time
   floating-point division

 * round to the nearest integer in order to minimize the error: your
   pixel position will have to be an integer anyway.

With these suggestions, we have:

```c++
int meterPosition = round(voltage * (320 / 5.0));
```

Do not forget the `.0` in `5.0`, otherwise you would get an integer
division.

Note that using `map()` with ranges scaled by a factor 100 is not a
terribly good idea: you will waste quite a lot of CPU cycles doing
useless computations, and the result will be polluted by two rounding
errors instead of one.

[1]: https://github.com/arduino/ArduinoCore-API/blob/1.4.0/api/Common.cpp


message:
Arduino uno - 4digit 7seg display via 74HC595 keeps blinking

I am trying to get my 4 digit display (SH5461AS) count from 0 to 9 based on millis() function.

The problem is that it keeps blinking. Even if I display just one number, it shows then it goes black then it shows again, instead of staying on.. Also the upper segment (A) is somewhat delayed. Sometimes it shows, sometimes it does not. I am really not sure what is going on. It is best illustrated in the video: https://youtube.com/shorts/gmbNnvEYq2I

I have arduino UNO R3 hooked up to the 74HC595 8-bit register and from there to the corresponding 'data' pins on the display.
It is a common cathode type so I have all of those connected via resistor to the ground.

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

I appologize for the messy cabeling:

From the display basically all resistors go to ground and all data cables to the register (Q0-DP omitted, segment A-Q7, B-Q6, .., G-Q1 [decimal number 1=A, 2=B, 3=AB,..]).

In the register I got VCC, Ground, data cables, EO grounded, serial data->arduino D4, storage clock -> D5, shift clock -> D6

     #include <LiquidCrystal.h>

    //LCD
    const int rs = 7, en = 8, d4 = 9, d5 = 10, d6 = 11, d7 = 12;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    //7SEG DISPLAY
    int LATCH = 5;
    int CLOCK = 6;
    int SERIALPIN = 4;

    const byte numbers[] = {
      0b111111, 0b0000110, 0b1011011, 0b1001111, 0b1100110, 0b1101101, 0b1111101, 0b0000111, 0b1111111, 0b1101111
    };

    //OTHER

    void setup() {
      //LCD
      lcd.begin(16, 2);
      lcd.print("Test!");

      //7SEG
      pinMode(SERIALPIN, OUTPUT);
      pinMode(CLOCK, OUTPUT);
      pinMode(LATCH, OUTPUT);

      //OTHER
      pinMode(13, OUTPUT); // turn off onboard diode
      Serial.begin(9600);
    }

    void loop() {
      countSeconds();
      delay(1000);
    }

    void countSeconds(){
        digitalWrite(LATCH, LOW);
        // int number = (millis()/1000);
        // Serial.println(number);
        shiftOut(SERIALPIN, CLOCK, LSBFIRST, numbers[0]); //for demonstration purposes display 0
        digitalWrite(LATCH, HIGH);
    }

Any ideas what's wrong?

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

body: As @Mat pointed out, the reset pin on the shift register was not connected. I didn't realize I need to anchor it high. Solved all problems, I guess it was resetting unpredictably..


message:
The Arduino UNO Pin 3V3 have OUTPUT 5V (measured with meter)

I just noticed that my original Arduino UNO on pin 3V3 have 4.98V output. That's odds. That pins should have 3.3V. So I measured the Vout on the voltage regulator LP2985-33DBVR where that pins is connected. And the voltages on Vout are the same of what I have measured on that pin. Does that voltage regulator need to be replaced?

body:
I guess either the regulator has failed creating a short or the 5v rail is shorted to the 3v3 rail elsewhere. Removing the regulator and checking the 3v3 rail is no longer 5v should tell you.

The only time I broke a 3v3 regulator, it failed open, so I don't know how likely it is for a LP2985 to fail short.

You could briefly attach a small load, say a LED and 270 or 330 ohm resistor, to be more certain of the voltage reading.


message:
how to "skip" one parameter of a method with a default value letting it use it's default value, but change parameters after it

**lets say we have a function like this(fictional):**

    function1(int Z, int X, bool Y=true, int Count=10, int ID=1,bool TeaTime=false);

And I want to run this function, but I want to change all parameters, except for "Count", and I want that to keep using it's default value.

**Disclaimer**
in this fictional case and in the real case where I faced it I found the default value in the header file and I manually coded it in. but I do not want that, at least not to rely on it, for example if the default value changes in the library then in my code it would still be forced to use that old value. also for ease of use and reducing the chance at problems/mistakes.

**What I tried:**
I already tried NULL and DEFAULT, both of them actually let my code work perfectly fine, but I made a test function which had such default values and printed the variables to the serial output and I found that using NULL actually overwrites it to 0 and DEFAULT overwrites it to 1.

I also tried some things like keeping one empty and such but those would give compile faults.

**in short:**

**is there a way to let one parameter somewhere in the middle of the parameters of a function use it's default value while still manually setting the later ones?**

body:
Most intuitive would be builder pattern with "chaining" ability (=returning reference to itself)

Something like (computer version, in arduino remove main, iostream and cout):

    #include <iostream>

    struct SomeParams {
        int        X;
        int        Z;
        bool       Y = true;
        int    count = 10;
        int       ID = 1;
        bool teaTime = false;

        SomeParams(int x, int z) : X{x}, Z{z} {};

        SomeParams & noY() { Y=false; return *this; }
        SomeParams & setCount(int c) { count = c; return *this; }
        SomeParams & setId(int i) { ID = i; return *this; }
        SomeParams & yesTeaTime() { teaTime = true; return *this; }
    };

    void function(SomeParams const & p) {
        std::cout << "X: " << p.X
                  << " Y: " << p.Y
                  << " Z: " << p.Z
                  << " ID: " << p.ID
                  << " count: " << p.count
                  << " teaTime: " << p.teaTime
                  << "\n";
    }

    int main() {
        function(SomeParams{45,68}.yesTeaTime().setId(154758).noY());

        // without chaining:
        auto params = SomeParams{4457,5468};
        params.setCount(4515);
        params.setId(15);
        function(params);
    }


message:
How to Protect GPIO when using long wires?

I want to connect a normal toggle switch with one of the gpios pins of a tasmotized esp01 with a wire about 20 feet in length. When I tried this before, I lost the GPIO pin mostly due to the high current drawn from GPIO because of the long wire. How can I limit current and protect the gpio and esp completely?

body: You can use a resistor with a transistor in order to control something that requires more power.  This will protect your io pin. Values depend on what you are specifically connecting to the io pin.


body:
You don't say how your switch is connected.

The standard way to protect a GPIO pin is with a series resistor and ideally a couple of Schottky diodes to clamp it to the supply rails.

Unless you're expecting particularly high voltages or require high speed data then around 100 ohms in series is reasonable.

The diodes go from the input pin to the processors power and ground pins. They are connected so that if the input is between 0 and 3.3 V they are reverse biased and have no effect. But if the input goes above VCC or below GND then the appropriate diode turns on and clamps the voltage. The series resistor limits the current that can flow in this situation and so prevents the diode from getting overloaded. In the image below this means pin 1 of the BAT54-S (the lower right one) goes to GND, pin 2 to 3V3 and pin 3 to your signal. Watch out, different manufacturers sometimes number the pins in different orders.

In theory the diode isn't needed. The chip will include the equivalent diodes internally. However they aren't particularly good ones and will be more susceptible to failure, counting on them is never a good plan. The external ones will clamp sooner and harder and are easier to replace if something does fry.

Just for clarity the resistor is on the outside of the diode. The signal path is: Outside world - resistor - clamping diode - ESP32 pin.

[![Pinout of BAT54 diode][1]][1]

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


body:
Thanks for the tips. I have seen one more solution to protect GPIO pins which was never mentioned here. This uses optocouplers. The anode or the cathode of the optocoupler can be connected through a switch to vcc or ground respectively. With respect to the optocoupler a series resistance will also needed to be used. The GPio and ground are connected to the 3 and 4 pins. when the switch is engaged, the 3 and 4 pins are connected.

The limitation is that not all GPIO can be used as some needs physically pulled to ground like Rx pin of esp8266.
[![Optocoupler Protection For GPIO switch][1]][1]

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


message:
Incorrect data received on serial communication

I have two **Arduino UNO** connected with two wires, and ground, that exchange informations through **serial data.**
The communication is working with INT, but I am having troubles to receive correct characters. Instead of characters I'm only receiving numbers.

I tried every possible combination of `Serial.write()` or `Serial.println()`, with HEX and ascii, but it wouldn't work.

I do not know what I am doing wrong, if anyone could help me, I will appreciate.

**Transmitter :**

    #include <SoftwareSerial.h>
    #define TX 2
    #define RX 3
    #define ask 3
    #define ER_LED 12

    String dataline = "605030";
    const byte code = 60;

    SoftwareSerial syserial(RX, TX); // RX, TX

    void setup() {
      // put your setup code here, to run once:
      syserial.begin(57600);
      Serial.begin(57600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      //syserial.println(dataline); //NO
      //syserial.println(28, DEC); //ok for numbers

      Serial.println(dataline.length());
      for (int i = 0; i < dataline.length(); i++)
      {
        syserial.print((char)dataline[i]);
      }
      syserial.println();
      //syserial.write(234);
      //syserial.print('<');
      delay(4000);
    }

**Receiver :**

    #include <SoftwareSerial.h>
    #define TX 2
    #define RX 3
    const byte ask = 3;
    bool com_end;
    #define ER_LED 7
    #define AC_LED 5

    SoftwareSerial syserial(RX, TX); // RX, TX

    void setup() {
      // put your setup code here, to run once:
      syserial.begin(57600);
      Serial.begin(57600);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      while (syserial.available())
      {
        Serial.println(syserial.read());
      }
      delay(100);
    }

**Serial monitor on whatev b/s:**

    21:19:36.408 -> 253
    21:19:36.408 -> 255
    21:19:40.421 -> 253
    21:19:40.421 -> 255
    21:19:44.495 -> 253
    21:19:44.495 -> 255

**Monitor with *SySerial* on 57600 b/s:**

    21:23:29.317 -> 241
    21:23:33.308 -> 241
    21:23:37.338 -> 241
    21:23:41.328 -> 241

**Monitor with *SySerial* on 300 b/s:**

    21:27:03.444 -> 255
    21:27:07.731 -> 255
    21:27:12.095 -> 255
    21:27:16.335 -> 255
    21:27:20.635 -> 255

**Update :**

I changed the pins on the UNO (TX ->2)(RX -> 3), and now i'm getting different numbers again. I must be doing something bad, but I can't understand what.

body:
*The communication is working with INT, but I am having troubles to receive correct characters. Instead of characters I'm only receiving numbers.*

Suggest you take a step back because you have code that has not been updated with what you have stated in subsequent comments and it is quickly becoming less clear what is going on.

On each UNO Use pins 2,3 and GND. **Don't connect anything else to either UNO.**

UNO ONE pin **2** connects to UNO TWO pin **3**

UNO ONE pin **3** connects to UNO TWO pin **2**

UNO ONE GND to UNO TWO GND

on UNO ONE run this code:

    // RECEIVER
    #include <SoftwareSerial.h>
    SoftwareSerial SSerial(2,3); // RX, TX
    void setup() {
      Serial.begin(9600); // Arduino monitor hardware Serial
      SSerial.begin(9600);
    }
    void loop() {
      // display whatever comes in on the software serial to the Arduino monitor (the hardware serial)
      if (SSerial.available()) {
        Serial.write(SSerial.read());
      }
    }

on UNO TWO run this code

    // SENDER
        #include <SoftwareSerial.h>
        SoftwareSerial SSerial(2, 3); // RX, TX
        void setup() {
          SSerial.begin(9600);
        }
        void loop() {
          SSerial.println("Simple Arduino SoftwareSerial Test");
          delay(1000);
        }

Open the serial monitor on UNO ONE and you will see "Simple Arduino SoftwareSerial Test" printed every second.

If you can't get that far, you have some other problem.

Are you using two UNOs on two different computers?
Are you using two UNOs on one computer, that is; running two instances of the IDE (may depend on OS - I do that all the time on Win 7 but I don't know about other OSs)?

See if you can get this far first and I think it will be easier to get the rest fixed.


message:
Read status of digital pin 11, when it is set as OUTPUT

I have set `pin 11` as output.
`pinMode(11, OUTPUT);`

However, I want to be able to read its state (if it is `HIGH` or `LOW`),  however since it is set as `OUTPUT`, I am not able to use `digitalRead()`.

I found this online though:

    Serial.println(bitRead(PORTD,3));
    //Reads bit 3 of register PORTD which contains the current state (high/low) of pin 3
If I want to read the state of `pin 11` then this:
`Serial.println(bitRead(PORTD,11));` will be enough? Or do I have to change the `PORT` as well?

body:
>  however since it is set as OUTPUT, I am not able to use digitalRead().

Where did you hear that? `digitalRead()` will return the state of a pin set to OUTPUT mode. (In that case, it will be the state you last set it to). As a demonstration, this is a common idiom for inverting the state of an output pin:

```
digitalWrite(LEDPIN, !digitalRead(LEDPIN));
```


message:
ESP32 - BLE does not connect/restart after light sleep

noob in arduino here.

I'm trying to connect via BLE after the ESP32 wakeups from light sleep. I have tried many different things, but none of them work. Everything works fine before the device sleeps the first time. Could you guys please give some ideas of what is wrong? the official docs are terrible.

```

    btStop();
    delay(1000);
    esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
    Serial.println("Going to light sleep now");
    esp_light_sleep_start();
    btStart();

```

body:
I finally found the answer, you just need to advertise again the service after it sleeps. First you need to define this:

    #if CONFIG_PM_ENABLE
    // Configure dynamic frequency scaling:
    // maximum and minimum frequencies are set in sdkconfig,
    // automatic light sleep is enabled if tickless idle support is enabled.
    // esp_pm_config_esp32c3_t pm_config = { // old version
    esp_pm_config_t pm_config = {
            .max_freq_mhz = 160, //  e.g. 80, 160,
            .min_freq_mhz = 80, // 40
    #if CONFIG_FREERTOS_USE_TICKLESS_IDLE
            .light_sleep_enable = true
    #endif
        };
    ESP_ERROR_CHECK( esp_pm_configure(&pm_config) );
    #endif // CONFIG_PM_ENABLE

Then in your loop you could do something like:

    esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
    Serial.println("Going to light sleep now");
    esp_light_sleep_start();
    Serial.println("depois do sleep start");
    BLEDevice::startAdvertising();


message:
How to scroll text on an OLED display using only the SSD1306Wire library?

I'm a 13 years old boy and I am doing a project with esp01 and an OLED screen to display project ideas on the OLED with the ChatGPT API. The answer is displayed on the OLED but I would like it to scroll from bottom to top and so on to the next query so I can see the whole answer.I noted that the only library that worked for me for the esp01 was the SSD1306Wire library .My code is :

 ```
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <Wire.h>
#include <SSD1306Wire.h>
#include <ArduinoJson.h>

const char* ssid = "WIFI_NAME";
const char* password = "WIFI_PASSWORD";

const char* apiEndpoint = "https://api.openai.com/v1/engines/text-davinci-002/completions";
const char* apiToken = "OPENAI_TOKEN";

SSD1306Wire  display(0x3c, 2, 0);
void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }

  Serial.println("Connected to WiFi");

  display.init();
  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
}

void loop() {
  WiFiClientSecure client;
  client.setInsecure();
  HTTPClient http;
  http.begin(client, apiEndpoint);
  http.addHeader("Content-Type", "application/json");
  http.addHeader("Authorization", "Bearer " + String(apiToken));
  String payload = "{\"prompt\": \"TEXT_TO_QUERY\",\"temperature\":0.8,\"max_tokens\":40}";
  int httpResponseCode = http.POST(payload);
  String response = "";

  if (httpResponseCode == 200) {
    response = http.getString();
    int startIndex = response.indexOf("text\":") + 7;
    int endIndex = response.indexOf("\",\"index\"");
    response = response.substring(startIndex, endIndex);
    response.replace("\\n", "\n");
    Serial.println(response);
  } else {
    Serial.print("Error: ");
    Serial.println(httpResponseCode);
  }

  http.end();

  display.clear();
  display.drawStringMaxWidth(0, 0, 128, response);
  display.display();

  delay(18000000);
}

 ```

  Could anyone help me?

body:
 * The SSD1306Wire code, its development history and discussions can be [found here on github.com][1].
 * The Google search pattern "scroll
   site:github.com/ThingPulse/esp8266-oled-ssd1306" can be used to find
   all matches to "scroll" on these web pages. There appears to be
   interest in vertical scrolling by others but no support as of yet.
   There also appears to be some horizontal scrolling support or success as
   discussed [in this github.com issue for this project][2].
 * Also in that thread, there is [a link to another DSS1306 github.com project
   which explicitly states it supports horizontal scrolling][3].

  [1]: https://github.com/ThingPulse/esp8266-oled-ssd1306
  [2]: https://github.com/ThingPulse/esp8266-oled-ssd1306/issues/160
  [3]: https://github.com/androdlang/InfoTicker


message:
How to run avr-gcov on a .ino sketch file

I am new to Arduino and gcov. I have a `.ino` sketch file, `avr-gcov`, and `avr-gcc` from Arduino library in the same directory. Could someone guide me to the steps I should take to run `avr-gcov` on my `.ino` file and get a `.gcov` file?

These are the things I have tried so far. When I run

`./avr-gcov filename.ino`,

it throws the error `filename.gcno: cannot open notes file`. My assumption was that I needed create a `.gcno` file before running gcov. So I tried to create one using the command

`./avr-gcc -c -Wall -pg -fprofile-arcs -ftest-coverage filename.ino`.

But doing so gives a warning: linker input file unused because linking not done and doesn't produce anything.

I tried to create an object code from the sketch file by passing `-o` flag but that throws the error `avr-gcc: fatal error: -fuse-linker-plugin, but liblto_plugin.so not found`.

Any help would be appreciated.

body:
Code coverage by "gcov" has some prerequisites:

1. Instrumented code to count the number the control flow reaches certain points of the program. This is done via the options you tried.
1. Linking with the support library. This is done via the options you tried. The result is a "gcno" file for each translation unit.
1. This support library expects a file system to store the accumulated counter values.
1. Running the application, the support library creates a "gcda" file for each translation unit. This file holds the accumulated counter values.
1. "gcov" expects all these "gcno" and "gcda" files to generate an annotated listing.

Since common Arduinos don't have a file system, the prerequisites cannot be fulfilled. This is the reason why you receive the error messages.

So what can you do now? There are multiple alternatives, but this site is not appropriate to present you ready-made solutions.

1. You can compile the sketch for the PC. For this you need to provide all used Arduino functions, for example as mocks or simulation.
1. You can provide the missing functions on your own, some kind of persistent storage, and finally transfer the data as "gcda" files to your PC. (This sounds complicated and resource expensive, and it is. However, it's doable, I did this years ago with another embedded system and a former version of "gcov".)
1. Refrain from using "gcov" and try other approaches of finding your hot spots. For example, toggle different port pins and/or with different patterns to literally "see" which code is executed. You need a good oscilloscope or logic analyzer for this.


message:
esp based smart light system over alexa malfunctioning

i made a home automation system using esp 32 and 8 channel relay but within 2 or 3 months my relay automatically turns off after sending the signal to it through esp32 but if i connect directly without esp32 it functions absolutely fine. that means that my relay if fine but what must be the possible reason for this malfunctioning.
this is my code

    #include <ESP8266WiFi.h>
    #include <Espalexa.h>
    Espalexa espalexa;

    // define the GPIO connected with Relays and switches
    #define RelayPin1 5  //D23
    #define RelayPin2 4  //D22
    #define RelayPin3 0  //D21
    #define RelayPin4 2  //D19
    #define RelayPin5 14  //D18
    #define RelayPin6 12  //D5
    #define RelayPin7 13  //D25
    #define RelayPin8 15  //D26

    #define SwitchPin1 3  //D13
    #define SwitchPin2 1  //D12
    #define SwitchPin3 10  //D14
    #define SwitchPin4 9  //D27
    #define SwitchPin5 8  //D33
    #define SwitchPin6 11  //D32
    #define SwitchPin7 7  //D15
    #define SwitchPin8 6   //D4

    bool oldStateSwitch_1;
    bool oldStateSwitch_2;
    bool oldStateSwitch_3;
    bool oldStateSwitch_4;
    bool oldStateSwitch_5;
    bool oldStateSwitch_6;
    bool oldStateSwitch_7;
    bool oldStateSwitch_8;

    #define wifiLed    16   //D2

    // WiFi Credentials
    const char* ssid = "akkikisu";
    const char* password = "anirudh@123";

    // device names
    String Device_1_Name = "a1";
    String Device_2_Name = "a2";
    String Device_3_Name = "a3";
    String Device_4_Name = "a4";
    String Device_5_Name = "a5";
    String Device_6_Name = "a6";
    String Device_7_Name = "a7";
    String Device_8_Name = "a8";

    // prototypes
    boolean connectWifi();

    //callback functions
    void firstLightChanged(uint8_t brightness);
    void secondLightChanged(uint8_t brightness);
    void thirdLightChanged(uint8_t brightness);
    void fourthLightChanged(uint8_t brightness);
    void fifthLightChanged(uint8_t brightness);
    void sixthLightChanged(uint8_t brightness);
    void senventhLightChanged(uint8_t brightness);
    void eighthLightChanged(uint8_t brightness);

    boolean wifiConnected = false;

    //our callback functions
    void firstLightChanged(uint8_t brightness)
    {
      //Control the device
      if (brightness == 255)
        {
          digitalWrite(RelayPin1, LOW);
          Serial.println("Device1 ON");
        }
      else
      {
        digitalWrite(RelayPin1, HIGH);
        Serial.println("Device1 OFF");
      }
    }

    void secondLightChanged(uint8_t brightness)
    {
      //Control the device
      if (brightness == 255)
        {
          digitalWrite(RelayPin2, LOW);
          Serial.println("Device2 ON");
        }
      else
      {
        digitalWrite(RelayPin2, HIGH);
        Serial.println("Device2 OFF");
      }
    }

    void thirdLightChanged(uint8_t brightness)
    {
      //Control the device
      if (brightness == 255)
        {
          digitalWrite(RelayPin3, LOW);
          Serial.println("Device3 ON");
        }
      else
      {
        digitalWrite(RelayPin3, HIGH);
        Serial.println("Device3 OFF");
      }
    }

    void fourthLightChanged(uint8_t brightness)
    {
      //Control the device
      if (brightness == 255)
        {
          digitalWrite(RelayPin4, LOW);
          Serial.println("Device4 ON");
        }
      else
      {
        digitalWrite(RelayPin4, HIGH);
        Serial.println("Device4 OFF");
      }
    }

    void fifthLightChanged(uint8_t brightness)
    {
      //Control the device
      if (brightness == 255)
        {
          digitalWrite(RelayPin5, LOW);
          Serial.println("Device5 ON");
        }
      else
      {
        digitalWrite(RelayPin5, HIGH);
        Serial.println("Device1 OFF");
      }
    }

    void sixthLightChanged(uint8_t brightness)
    {
      //Control the device
      if (brightness == 255)
        {
          digitalWrite(RelayPin6, LOW);
          Serial.println("Device6 ON");
        }
      else
      {
        digitalWrite(RelayPin6, HIGH);
        Serial.println("Device6 OFF");
      }
    }

    void seventhLightChanged(uint8_t brightness)
    {
      //Control the device
      if (brightness == 255)
        {
          digitalWrite(RelayPin7, LOW);
          Serial.println("Device7 ON");
        }
      else
      {
        digitalWrite(RelayPin7, HIGH);
        Serial.println("Device7 OFF");
      }
    }

    void eighthLightChanged(uint8_t brightness)
    {
      //Control the device
      if (brightness == 255)
        {
          digitalWrite(RelayPin8, LOW);
          Serial.println("Device8 ON");
        }
      else
      {
        digitalWrite(RelayPin8, HIGH);
        Serial.println("Device8 OFF");
      }
    }

    // connect to wifi – returns true if successful or false if not
    boolean connectWifi()
    {
      boolean state = true;
      int i = 0;

      WiFi.mode(WIFI_STA);
      WiFi.begin(ssid, password);
      Serial.println("");
      Serial.println("Connecting to WiFi");

      // Wait for connection
      Serial.print("Connecting...");
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
        if (i > 20) {
          state = false; break;
        }
        i++;
      }
      Serial.println("");
      if (state) {
        Serial.print("Connected to ");
        Serial.println(ssid);
        Serial.print("IP address: ");
        Serial.println(WiFi.localIP());
      }
      else {
        Serial.println("Connection failed.");
      }
      return state;
    }

    void addDevices(){
      // Define your devices here.
      espalexa.addDevice(Device_1_Name, firstLightChanged); //simplest definition, default state off
      espalexa.addDevice(Device_2_Name, secondLightChanged);
      espalexa.addDevice(Device_3_Name, thirdLightChanged);
      espalexa.addDevice(Device_4_Name, fourthLightChanged);
      espalexa.addDevice(Device_5_Name, fifthLightChanged);
      espalexa.addDevice(Device_6_Name, sixthLightChanged);
      espalexa.addDevice(Device_7_Name, seventhLightChanged);
      espalexa.addDevice(Device_8_Name, eighthLightChanged);

      espalexa.begin();
    }

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

      pinMode(RelayPin1, OUTPUT);
      pinMode(RelayPin2, OUTPUT);
      pinMode(RelayPin3, OUTPUT);
      pinMode(RelayPin4, OUTPUT);
      pinMode(RelayPin5, OUTPUT);
      pinMode(RelayPin6, OUTPUT);
      pinMode(RelayPin7, OUTPUT);
      pinMode(RelayPin8, OUTPUT);

      pinMode(wifiLed, OUTPUT);

      pinMode(SwitchPin1, INPUT_PULLUP);
      pinMode(SwitchPin2, INPUT_PULLUP);
      pinMode(SwitchPin3, INPUT_PULLUP);
      pinMode(SwitchPin4, INPUT_PULLUP);
      pinMode(SwitchPin5, INPUT_PULLUP);
      pinMode(SwitchPin6, INPUT_PULLUP);
      pinMode(SwitchPin7, INPUT_PULLUP);
      pinMode(SwitchPin8, INPUT_PULLUP);

      //During Starting all Relays should TURN OFF
      digitalWrite(RelayPin1, HIGH);
      digitalWrite(RelayPin2, HIGH);
      digitalWrite(RelayPin3, HIGH);
      digitalWrite(RelayPin4, HIGH);
      digitalWrite(RelayPin5, HIGH);
      digitalWrite(RelayPin6, HIGH);
      digitalWrite(RelayPin7, HIGH);
      digitalWrite(RelayPin8, HIGH);

      oldStateSwitch_1 = ! digitalRead( SwitchPin1 ) ;  // note inverted
      oldStateSwitch_2 = ! digitalRead( SwitchPin2 ) ;  // note inverted
      oldStateSwitch_3 = ! digitalRead( SwitchPin3 ) ;  // note inverted
      oldStateSwitch_4 = ! digitalRead( SwitchPin4 ) ;  // note inverted
      oldStateSwitch_5 = ! digitalRead( SwitchPin5 ) ;  // note inverted
      oldStateSwitch_6 = ! digitalRead( SwitchPin6 ) ;  // note inverted
      oldStateSwitch_7 = ! digitalRead( SwitchPin7 ) ;  // note inverted
      oldStateSwitch_8 = ! digitalRead( SwitchPin8 ) ;  // note inverted

        // repeat for seitched 2 to 8

      // Initialise wifi connection
      wifiConnected = connectWifi();

      if (wifiConnected)
      {
        addDevices();
      }
      else
      {
        Serial.println("Cannot connect to WiFi. So in Manual Mode");
        delay(1000);
      }
    }

    void loop()
    {
       if (WiFi.status() != WL_CONNECTED)
      {
        //Serial.print("WiFi Not Connected ");
        digitalWrite(wifiLed, LOW); //Turn off WiFi LED
      }
      else
      {
        //Serial.print("WiFi Connected  ");
        digitalWrite(wifiLed, HIGH);
        //Manual Switch Control
        //WiFi Control
        if (wifiConnected){
          espalexa.loop();
          delay(1);
        }
        else {
          wifiConnected = connectWifi(); // Initialise wifi connection
          if(wifiConnected){
          addDevices();
          }
        }
      }

    //main code

    static uint32_t lastSwitchTest = 0 ;  // static initialised once only

          if ( millis() - lastSwitchTest > 250 ) {  // every 250ms
          lastSwitchTest = millis() ;

          // switch 1

          bool stateSwitch_1 = digitalRead( SwitchPin1 ) ;
          if (  oldStateSwitch_1 != stateSwitch_1 ) {
             oldStateSwitch_1 = stateSwitch_1 ;
             Serial.println("Switch 1 changed");
             EspalexaDevice* d1 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
             if ( stateSwitch_1 == HIGH )  {  // HIGH = off
                Serial.println("Switch 1 off");
                d1->setPercent(0); //set value "brightness" in percent
                digitalWrite(RelayPin1, HIGH);
             }
             else { // switch on
                Serial.println("Switch 1 on");
                d1->setPercent(100); //set value "brightness" in percent
                digitalWrite(RelayPin1, LOW);
             }
          }

          // switch 2

          bool stateSwitch_2 = digitalRead( SwitchPin2 ) ;
          if ( oldStateSwitch_2 != stateSwitch_2 ) {
             oldStateSwitch_2 = stateSwitch_2 ;
             Serial.println("Switch 2 changed");
             EspalexaDevice* d2 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
             if ( stateSwitch_2 == HIGH )  {  // HIGH = off
                Serial.println("Switch 2 off");
                d2->setPercent(0); //set value "brightness" in percent
                digitalWrite(RelayPin2, HIGH);
             }
             else { // switch on
                Serial.println("Switch 2 on");
                d2->setPercent(100); //set value "brightness" in percent
                digitalWrite(RelayPin2, LOW);
             }
          }

          // switch 3

          bool stateSwitch_3 = digitalRead( SwitchPin3 ) ;
          if ( oldStateSwitch_3 != stateSwitch_3 ) {
             oldStateSwitch_3 = stateSwitch_3 ;
             Serial.println("Switch 3 changed");
             EspalexaDevice* d3 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
             if ( stateSwitch_3 == HIGH )  {  // HIGH = off
                Serial.println("Switch 1 off");
                d3->setPercent(0); //set value "brightness" in percent
                digitalWrite(RelayPin3, HIGH);
             }
             else { // switch on
                Serial.println("Switch 3 on");
                d3->setPercent(100); //set value "brightness" in percent
                digitalWrite(RelayPin3, LOW);
             }
          }
          // switch 4

          bool stateSwitch_4 = digitalRead( SwitchPin4 ) ;
          if ( oldStateSwitch_4 != stateSwitch_4 ) {
             oldStateSwitch_4 = stateSwitch_4 ;
             Serial.println("Switch 4 changed");
             EspalexaDevice* d4 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
             if ( stateSwitch_4 == HIGH )  {  // HIGH = off
                Serial.println("Switch 1 off");
                d4->setPercent(0); //set value "brightness" in percent
                digitalWrite(RelayPin4, HIGH);
             }
             else { // switch on
                Serial.println("Switch 4 on");
                d4->setPercent(100); //set value "brightness" in percent
                digitalWrite(RelayPin4, LOW);
             }
          }
          // switch 5

          bool stateSwitch_5 = digitalRead( SwitchPin5 ) ;
          if ( oldStateSwitch_5 != stateSwitch_5 ) {
             oldStateSwitch_5 = stateSwitch_5 ;
             Serial.println("Switch 5 changed");
             EspalexaDevice* d5 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
             if ( stateSwitch_5 == HIGH )  {  // HIGH = off
                Serial.println("Switch 1 off");
                d5->setPercent(0); //set value "brightness" in percent
                digitalWrite(RelayPin5, HIGH);
             }
             else { // switch on
                Serial.println("Switch 5 on");
                d5->setPercent(100); //set value "brightness" in percent
                digitalWrite(RelayPin5, LOW);
             }
          }
          // switch 6

          bool stateSwitch_6 = digitalRead( SwitchPin6 ) ;
          if ( oldStateSwitch_6 != stateSwitch_6 ) {
             oldStateSwitch_6 = stateSwitch_6 ;
             Serial.println("Switch 6 changed");
             EspalexaDevice* d6 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
             if ( stateSwitch_6 == HIGH )  {  // HIGH = off
                Serial.println("Switch 1 off");
                d6->setPercent(0); //set value "brightness" in percent
                digitalWrite(RelayPin6, HIGH);
             }
             else { // switch on
                Serial.println("Switch 6 on");
                d6->setPercent(100); //set value "brightness" in percent
                digitalWrite(RelayPin6, LOW);
             }
          }
          // switch 7

          bool stateSwitch_7 = digitalRead( SwitchPin7 ) ;
          if ( oldStateSwitch_7 != stateSwitch_7 ) {
             oldStateSwitch_7 = stateSwitch_7 ;
             Serial.println("Switch 7 changed");
             EspalexaDevice* d7 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
             if ( stateSwitch_7 == HIGH )  {  // HIGH = off
                Serial.println("Switch 1 off");
                d7->setPercent(0); //set value "brightness" in percent
                digitalWrite(RelayPin7, HIGH);
             }
             else { // switch on
                Serial.println("Switch 7 on");
                d7->setPercent(100); //set value "brightness" in percent
                digitalWrite(RelayPin7, LOW);
             }
          }
          // switch 8

          bool stateSwitch_8 = digitalRead( SwitchPin8 ) ;
          if ( oldStateSwitch_8 != stateSwitch_8 ) {
             oldStateSwitch_8 = stateSwitch_8 ;
             Serial.println("Switch 8 changed");
             EspalexaDevice* d8 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
             if ( stateSwitch_8 == HIGH )  {  // HIGH = off
                Serial.println("Switch 1 off");
                d8->setPercent(0); //set value "brightness" in percent
                digitalWrite(RelayPin8, HIGH);
             }
             else { // switch on
                Serial.println("Switch 8 on");
                d8->setPercent(100); //set value "brightness" in percent
                digitalWrite(RelayPin8, LOW);
             }
          }

          // switch 2 to 8
          // just copy/paste/adjust using switch 1 as a template

        } // if ( millis
    } // loop()

body:
You are using the following project as a code base: https://iotcircuithub.com/esp32-alexa-home-automation-system/

You appear to have confirmed that the same problem symptoms appear when the ESP32 is reset, that is that some lights are in the wrong state at system start. A reset can be caused by such things as a system reset following a power outage, a crash or simply pressing the reset button on the device.

You are using a button handling library AceButton.h in combination with latched switches. The problem here is that the button handling library is intended for momentory push-to-make buttons and assumes that the switch is in the "un-pushed" state at system start. This may not reflect the position of the latched switches where some could be in the on position and others in the off position. This could result in missed events on system start.

Anyway, you do not need a button library. Especially for toggle type switches, like you are using, where it is necessary only to read the switch say every 250ms and test if the state has been changed since the last reading. No other debouncing is required.

In setup() you'd read each switch and store the inverse of its current state in a variable, say oldStateSwitch_1. It is necessary to store the inverse of the state to trigger a first time switch state change action in the loop().

Something like . . .
```
void setup() {
 . . .

 oldStateSwitch_1 = ! digitalRead( switchPin1 ) ;  // note inverted
    // repeat for seitched 2 to 8
 . . .

}
```

In the loop(), you'd do something like . . .

```
void loop() {

. . .
. . .

 static uint32_t lastSwitchTest = 0 ;  // static initialised once only

 if ( millis() - lastSwitchTest > 250 ) {  // every 250ms
   lastSwitchTest = millis() ;

   // switch 1

   bool stateSwitch_1 = digitalRead( switchPin1 ) ;
   if ( oldStateSwitch_1 != stateSwitch_1 ) {
   oldStateSwitch_1 = stateSwitch_1 ;
   Serial.println("Switch 1 changed");
   EspalexaDevice* d1 = espalexa.getDevice(0); //this will get "first device", the index is zero-based
   if ( stateSwitch_1 == HIGH )  {  // HIGH = off
   Serial.println("Switch 1 off");
   d1->setPercent(0); //set value "brightness" in percent
   digitalWrite(RelayPin1, HIGH);
   }
   else { // switch on
   Serial.println("Switch 1 on");
   d1->setPercent(100); //set value "brightness" in percent
   digitalWrite(RelayPin1, LOW);
   }
   }

   // switch 2 to 8
   // just copy/paste/adjust using switch 1 as a template

 } // if ( millis
} // loop()
```

All AceButton code should be deleted.


message:
Lora to Mqtt sensor cannot be read

I'm trying to transfer data from a temperature sensor that is located outside my wifi area. I have chosen the Lora technology between an ESP32 equipped with an SX1278 and a TTGO Lilygo lora.
So far everything works fine. But as soon as I try to publish the data via mosquitto mqtt in order to have access onto home assistant, things are getting worse. I use Mqtt explorer to view the exchanges with mosquitto. I also monitor the data on the serial port.
Everything works correctly as long as I don't publish the temperature data but from the moment I publish it after changing it to string to switch to mqtt, I have some problems:
- the serial port displays wrong values of the string  and scrolls continuously
- the data sent to the mqtt are well displayed in coherence with the serial port but remain incoherent and the number of publications increase quickly
- from a certain moment, things does not moves anymore.

So I have at least two problems and even if I looked at many examples , I have trouble understanding everything...
You will find attached the code loaded into the Lilygo receiver hoping that it will help to solve my problem(s):

    #include <SPI.h>
    #include <LoRa.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    #include <WiFi.h>
    #include <PubSubClient.h>
    #include <Streaming.h>
    #include <Ticker.h>

    #define OLED_SDA 21     // Attention: Les broches SDA et SCL de l'affichage OLED sont inversées sur le dessin de LilyGO et sur GitHub.
    #define OLED_SCL 22
    #define OLED_RST 12     // Note: Le TTGO Lora32 v2 n'utilise pas le signal reset, mais la librairie Adafruit_SSD1306, oui.
    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels

    const int csPin = 18;          // LoRa radio chip select-TTGO
    const int resetPin = 23;       // LoRa radio reset-TTGO
    const int irqPin = 26;         // change for your board; must be a hardware interrupt pin-TTGO
    const int sckPin = 5;          //-TTGO
    const int misosPin = 19;       //-TTGO
    const int mosiPin = 27;        //-TTGO

    const char* ssid = "xxxxxx";      // Nom du wifi
    const char* password = "xxxxxx";    // Mot de passe wifi

    const char* mqtt_server = "xxx.xxx.x.xx";   // Adresse IP du brovker MQTT
    const char* mqtt_username = "xxxxx";     // User MQTT
    const char* mqtt_password = "xxxxxx";    // Password MQTT
    const char* mqtt_topic = "ESP32/DS18B20/temp_piscine";   // Nom du topic MQTT envoyé par home assistant

    char incoming ;
    char msg[4];

    WiFiClient espClient;
    PubSubClient client(espClient);

    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RST);

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

      // setup WiFi
      setup_wifi();
      client.setServer(mqtt_server, 1883);
      client.setCallback(callback);

      //initialize OLED
      Wire.begin(OLED_SDA, OLED_SCL);
      if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3c, false, false))
      { // Address 0x3C for 128x32
        Serial.println(F("SSD1306 allocation failed"));
      }
      display.clearDisplay();
      display.setTextColor(WHITE);
      display.setTextSize(1);
      display.setCursor(0,0);
      display.print("LORA RECEIVER ");
      display.display();

      Serial.println("LoRa Receiver");

      // override the default CS, reset, and IRQ pins (optional)
        SPI.begin(sckPin, misosPin, mosiPin, csPin);
        LoRa.setPins(csPin, resetPin, irqPin); // set CS, reset, IRQ pin

      if (!LoRa.begin(433E6))
      {
        Serial.println("Starting LoRa failed!");
        while (1);
      }
    }
    //Fonction connexion au wifi appelé dans le setup
    void setup_wifi() {
      delay(10);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);
      display.setCursor(0,0);

      WiFi.begin(ssid, password);

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

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
    }

    //Fonction connexion au wifi appelé dans le setup
    void callback(char* topic, byte* message, unsigned int length) {
      Serial.print("Message arrived on topic: ");
      Serial.print(topic);
      Serial.print(". Message: ");
      String messageTemp;

      for (int i = 0; i < length; i++) {
        Serial.print((char)message[i]);
        messageTemp += (char)message[i];
      }
      Serial.println();
    }

    //Fonction connexion au serveur Mqtt  dans le loop
    void reconnect() {
      // Loop until we're reconnected
      while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        // Attempt to connect
        if (client.connect("ESP8266Client", mqtt_username, mqtt_password)) {
          Serial.println("connected");
        } else {
          Serial.print("failed, rc=");
          Serial.print(client.state());
          Serial.println(" try again in 5 seconds");
          // Wait 5 seconds before retrying
          delay(5000);
        }
      }
    }

    void loop()
    {
      client.loop();
      // try to parse packet
      int packetSize = LoRa.parsePacket();
      if (packetSize)
    {
        // received a packet
        Serial.print("Received packet ");
        // read and print packet
        display.clearDisplay();
        display.setCursor(0,0);
        while (LoRa.available())
        {
          incoming = ((char)LoRa.read());
          //Serial.print((char) LoRa.read());
          Serial.print(incoming);
          display.print(incoming);
        }
        // print RSSI of packet
        Serial.print("' with RSSI ");
        Serial.println(LoRa.packetRssi());
        //display.setCursor(0,0);
        display.print("' with RSSI ");
        display.println(LoRa.packetRssi());
        display.display();
          }
      if (!client.connected())
      {
        reconnect();
      }
      dtostrf(incoming, 6, 2, msg);
      Serial.print (msg);
      client.publish(mqtt_topic,msg,false);
      //client.publish(mqtt_topic,dtostrf(LoRa.packetRssi(),6,2,msg),false);

    }

body:
In your `dtostrf(incoming, 6, 2, msg);`, you want to store a float that has a minimum width of 6, with 2-digit precision, you will need an array of at leat 9 bytes(plus NULL terminator) for a value like '12345.78', you only allow 4 bytes for your `msg[4];` which is definitely insufficient.

Even if your temperature is 32.45, it will still need an array of 6 for `msg`.


body:
Hello and thank you for your support, I finally found the pb which was that using incoming need to be stored in a buffer to be used as it was sent char by char. I also found the possibility to use LoRa.readString() who allow a full string storage. I used after the function LoRaData.indexOf... which allow to select specific part of text with specific marks such as #, *, /, ...
Here is an example of the code used for who could be interested.

        void loop()
{
  client.loop();

// try to parse packet
  int packetSize = LoRa.parsePacket();
  if (packetSize)
{
    // received a packet

    Serial.println("Received packet ");
    // read and print packet
    display.clearDisplay();
    display.setCursor(0,0);
    while (LoRa.available()) //>0 retiré
    {
      String LoRaData = LoRa.readString();
      Serial.print(LoRaData);
    // Get Text, temperature and end text : *Temp.piscine #21.56*C*
      int pos1 = LoRaData.indexOf('#');
      int pos2 = LoRaData.indexOf('*');
      Text = LoRaData.substring(0, pos1);
      temperature = LoRaData.substring(pos1 +1, pos2);
      End = LoRaData.substring(pos2+1, LoRaData.length());
    }
    // print RSSI of packet
    Serial.print("' with RSSI ");
    Serial.println(LoRa.packetRssi());

    display.print("temperature Piscine = ");
    display.print(temperature);
    display.print("°C");
    display.print("' with RSSI ");
    display.println(LoRa.packetRssi());
    display.display();

      }

}

I still need to work on it, but it seems to work fine.


message:
Reading/writing Ntag215 with RC522

I ordered Ntag215 from Aliexpress. The tags are identified just fine, yet I have issues writing/reading to them because of failed authentication. I am using Arduino Uno + RFID-RC522 module.
This is my code below:
```
#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN 9  //
#define SS_PIN 10  //

MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance

void setup() {
  Serial.begin(9600);  // Initialize serial communications with the PC
  while (!Serial)
    ;                  // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
  SPI.begin();         // Init SPI bus
  mfrc522.PCD_Init();  // Init MFRC522
  Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}

void loop() {
  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if (!mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if (!mfrc522.PICC_ReadCardSerial()) {
    return;
  }
  Serial.print(F("Card UID:"));
  dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
  Serial.println();
  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
  Serial.println(mfrc522.PICC_GetTypeName(piccType));

  MFRC522::MIFARE_Key key = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
  MFRC522::StatusCode status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid));
  Serial.println(mfrc522.GetStatusCodeName(status));
}

void dump_byte_array(byte *buffer, byte bufferSize) {
    for (byte i = 0; i < bufferSize; i++) {
        Serial.print(buffer[i] < 0x10 ? " 0" : " ");
        Serial.print(buffer[i], HEX);
    }
}
```

And this is the output I get.
```
01:27:26.704 -> Scan PICC to see UID, type, and data blocks...
01:27:30.357 -> Card UID: 04 CB 4A 57 19 61 80
01:27:30.390 -> PICC type: MIFARE Ultralight or Ultralight C
01:27:30.422 -> Timeout in communication.
```

Always get Timeout in communication. With Mifare 1KB tags this is not an issue. Any idea?

body:
Ok after more trial and error and research I have made it possible to Write and Read to Ntag215. Here are code snippets for writing and reading. It was not required to Authenticate to write the data the tag.

Writing: It is actually quite simple. The main rule is that the writing can start from the page 4. And the bufferSize has to be 4. Here is example just writing "A" character to the tag.
```
    char charToProgram = "A";
    byte data = charToProgram;       // Data to write (ASCII character "A")
    byte blockAddr = 4;  // Block address to write to

    // Write the data to the tag
    MFRC522::StatusCode status = reader.MIFARE_Ultralight_Write(4, &data, 4);

    if (status == MFRC522::StatusCode::STATUS_OK) {
      Serial.println("SUCCESS! Wrote to card!");
      reader.PICC_HaltA();
    }
```

Reading:
```
    int blockAddr = 4;  // Block address to read from
    byte data[18];
    byte size = 18;
    // Write the data to the tag
    MFRC522::StatusCode status = reader.MIFARE_Read(blockAddr, data, &size);

    if (status == MFRC522::StatusCode::STATUS_OK) {
      Serial.print("Read character: ");
      Serial.println((char) data[0]);
      reader.PICC_HaltA();
    }
```


message:
Why can't I upload a sketch by connecting directly to the serial pins?

I have an handful of fake arduino nanos.  The work fine, but as an experiment, I tried to program them with a _usb serial adapter_ (a real FTDI one).  It doesn't work, but also, strangely, it seems to stop the bootloader from working properly too, or just puts the arduino in a mode where the `/dev/ttyUSB*` device doesn't appear, and only reappears when I burn the bootloader again

When I try to upload the sketch using the usb serial adapter, I get this:

```
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
Failed uploading: uploading error: exit status 1
```

Then, when I try to upload a sketch over usb again, `/dev/ttyUSB*` no longer appears when I plug in the usb cable to the normal usb jack.

However, when I can still put the sketch on using an in-circuit-programmer, and when I use the in-circuit-programmer to burn the bootloader again, `/dev/ttyUSB*` appears again, and I can upload sketches over usb again.

Is that possible?  What could I be doing wrong

Here is how I connected the usb to serial adapter to the fake arduino:

[![adapter connected to fake arduino][1]][1]

(checkout https://i.stack.imgur.com/nh3d6.jpg for a bigger picture)

So basically I have connected between the arduino (left column) and the usb to serial adapter right column:

```
TX - RX
RX - TX
VIN - VCC
GND - GND
RST - 0.1uF capacitor - DTR
```

I have tried it with and without the reset pin.

The usb to serial adapter is set to 5V.

----

another clue:

If I leave the adapter and arduino connected as in the picture, but plug the usb cable into the arduino instead of the adapter, so the adapter is powered by the arduino - it still gets the error that I have shown, and stops working completely until I reburn the bootloader.

----

Does anybody have any idea why this could be happening?

----

UPDATE:

After it was pointed out, I started using the 5v pin instead of the VCC pin on the fake arduino, but the same thing keeps happening:
 - burn the boot loader
 - normal usb upload works
 - try to upload with the serial adapter
 - doesn't work
 - normal usb upload no longer works until I burn the bootloader again

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

body:
OK this was a combination of at least two things:

----

Main problem:

connecting the fake arduino's RST pin to the FTDI's DTR pin via a 0.1uF capacitor seems to stop it from uploading, when when you manually reset.  Also when I remove it it doesn't seem to fix itself right away if you can believe it.

----

Red Herring

This was not the direct cause of this issue, but is probably a big problem for a lot of other fake arduinos out there:

When I went back to the built-in USB, `brltty`'s udev rules were claiming the CH341 as described here https://askubuntu.com/questions/1403705/dev-ttyusb0-not-present-in-ubuntu-22-04

So if you just have the simpler problem of a fake arduino not appearing, this might solve the problem for you:

```
sudo apt-get remove brltty
```
or if you need `brltty` you can just go into the udev rules that come with it and comment out this one:

```
# Device: 1A86:7523
# Baum [NLS eReader Zoomax (20 cells)]
ENV{PRODUCT}=="1a86/7523/*", ENV{BRLTTY_BRAILLE_DRIVER}="bm", GOTO="brltty_usb_run"
```
(as long as that isn't the screen reader you use - then you might just have to buy a real arduino, or make some better udev rules that recognise your screenreader from the port it's plugged into)

The reason this confused me is that when I tried to plug in to the standard usb port after failing to use the programmer, the above udev rules kicked me out.  But then I think when I burned a new bootloader, because you still have to power the board from usb while the pololu is connected, I managed to have it connected without the above udev rule kicking it - and then when I tried the external FTDI again, and then plugged back in the internal CH341, the brltty udev rule claimed it, and it seemed like trying to upload over FTDI is what broke it.


message:
Potential difference across the same wire

This issue may be weird, and I'm not sure if this is because of my wiring, but it would seem that **I do not have the same voltage** (or approximately the same voltage) between the **VCC(3.3V)** and the **VCC power rail** of my breadboard.

When measuring the voltage, there is **~0.300 mV** difference. And indeed measuring VCC and GND gives me **2.9 V**, instead of **3.3 V**

 - I measured the flat jumper, it **doesn't have any resistance** (~~0)

 - The ESP is consuming **below 100mA**, so no voltage drop

Could anyone explain me that ?
See attached pictures

[![pin layout][1]][1]

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

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

  [1]: https://i.stack.imgur.com/np6J3.jpg
  [2]: https://i.stack.imgur.com/nUu2k.jpg
  [3]: https://i.stack.imgur.com/PfON7.jpg

body:
The only reasonable explanation is that the path between the 3.3V pin and the wire you are measuring does indeed have non-zero resistance. The wires look dirty to me from the photo, plus there would be internal resistance in the breadboard connectors.

You are measuring from the 3.3V pin and not the other end of the wire. I suggest using a different wire, or cleaning that one with sandpaper or by filing it down until you see shiny copper. Also try a different pin on the breadboard.

This is really a hardware or measurement issue. There is no way that a wire with zero resistance from one end to the other is going to have a 0.242V drop across it.