body:
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();
    }

title: 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

Answers: 1

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.


body:
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

title: IDE will not upload to ATTiny88

Answers: 1

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


body:
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

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

Answers: 1

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


body:
I am working between an esp8266 and esp32 (I still have some doubt on what to use), and I would like to save sensors data permanently somewhere on my PC. I don't have a SD shield and I am new on this kind of things. There's some simple and easy way to do that? Arduino IOT Cloud actually collect one data per second and seems to be the best solution, but it does not support esp32 Heltec v3. Thingspeak collect data every 15 seconds and I need to collect 4 samples per second.
Is there any alternative to simple send the data to a txt file on my computer?

Edit: I actually found out that the best and Easy way to save data on computer, not considering WiFi, Is the Data Streamer Add-ons of excel, which allows to print data on and excel sheet like It was a serial monitor. It's possibile to plot real time values and save It until million of rows every 100 milliseconds minimum.

title: Save sensors data on PC

Answers: 0


body:
I am working on a project where I am using an HC05 connected to an Arduino to connect to an ELM327 Bluetooth scanner. I am using the SoftwareSerial Arduino library to send and read information from and too the HC05 using the following code. However when I use this code to send PID codes to the HC05 to request data such as 010C I am almost always receiving `010CNODATA>`.

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);

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

void loop(){
  if (mySerial.available()){
    Serial.write(mySerial.read());
  }
  if (Serial.available()){
    mySerial.write(Serial.read());
  }
```
My wiring for the HC05 is:

 - EN: No connection
 - VCC: Arduino 5v
 - GND: Arduino Ground
 - TXD: Digital Pin 9
 - RXD: Digital Pin 10
 - STATE: No connection

I have verified that I am linked to the ELM327 device as I do receive the NODATA from the device. I have ensured that the Arduino Serial monitor is in the 'both NL and CR' mode as that is the data format that the HC05 and the ELM327 take.

When I attempt to send AT commands to the ELM327 device the I get a response like `A?TZ?>`. After much testing I have been able to get all of my commands to work but only if I follow the next steps exactly:

 1. Unplug the Arduino and let it power down.
 2. Plug the Arduino back in and open the Serial monitor and send whatever command I want AT or PID such as `ATZ` or `010C`.
 3. Wait until the HC05 connects to the ELM327 device and the first response that I get back will be correct such as a hex number for RPM.

Any following attempts at sending PID codes will return NODATA.
I have verified that both of the devices work independently of each other using the Bluetooth Serial Monitor app. I can send endless AT or PID codes to the ELM327 from my phone and I get the appropriate response. I have a feeling that it is an issue with either the end characters or with the way the data is being sent across the Serial line.

I would be happy to provide any additional information needed.

Thank you.

title: HC05 and ELM327 NODATA sending PID codes

Answers: 0


body:
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.

title: 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

Answers: 1

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.


body:
I have a project where Arduino Nano 33 BLE (3.3V operating voltage) is powered by a LiPo battery. The battery is charged using [Adafruit's MicroLipo Charger][1] it is then connected to [Adafruit's MiniBoost][2] to boost the voltage to 5V and that powers the Arduino through Vin as well as a logic level converter.

Ideally I'd like to use the device while it's charging. The MicroLipo charger provides a USB C breakout board providing a 5V pin. Is it a bad idea to connect 5V output from the boost converter and from USB C to th same power rail as shown in the frtizing sketch? My gut says try it, my brain says this is a dumb idea.

Is there a way I could use something as a switch which takes in 5V from both the cable and the battery only uses the battery when cable voltage is 0V (not connected)?

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

  [1]: https://www.adafruit.com/product/4410
  [2]: https://www.adafruit.com/product/4654
  [3]: https://i.stack.imgur.com/xKtlg.png

title: How to use LiPo powered Arduino Nano BLE when it's charging (with a charging circuit and a boost converter)?

Answers: 0


body:
I have tried ArduinoOTA and AsyncElegantOTA and they work, but only when you are in the same wi-fi as ESP32.

I need to update ESP32 firmware "remotely" meaning when I'm not in the same local wi-fi network as ESP32.

Has this been done yet for Arduino?

title: Looking for FOTA to update firmware with wi-fi over internet (ESP32)

Answers: 0


body:
I'm working with a 32-Input Modbus RTU module using RS485. I'm trying to read/poll the inputs to check for ON(1) states.  I have tested this module with Arduino UNO, Radzio! Modbus Master simulator, and Modbus Poll -- all worked as expected, (displaying 0=off, 1=on). Using an Arduino Nano with a TTL to RS485 Module like [this.][1]

So using the below code, the output is all 0s regardless of input state.  It compiles and runs without errors.

    #include <ModbusRtu.h>
    #include <SoftwareSerial.h>

    // data array for modbus network sharing
    uint16_t au16data[32];
    uint8_t u8state;

    /**
     *  Modbus object declaration
     *  u8id : node id = 0 for master, = 1..247 for slave
     *  u8serno : serial port (use 0 for Serial)
     *  u8txenpin : 0 for RS-232 and USB-FTDI
     *               or any pin number > 1 for RS-485
     */
    Modbus master(0); // this is master and RS-232 or USB-FTDI via software serial

    /**
     * This is an structe which contains a query to an slave device
     */
    modbus_t telegram;

    unsigned long u32wait;

    SoftwareSerial mySerial(2, 3);//Create a SoftwareSerial object

    void setup() {
      Serial.begin(9600);
      master.begin( &mySerial, 9600 ); // begin ModBus object 9600baud
      master.setTimeOut( 2000 ); // if no answer in 2000 ms, roll over
      u32wait = millis() + 1000;
      u8state = 0;
    }

    void loop() {
      switch( u8state ) {
      case 0:
        if (millis() > u32wait) u8state++; // wait state
        break;
      case 1:
        telegram.u8id = 1; // slave address
        telegram.u8fct = 3; // function code (this one is registers read)
        telegram.u16RegAdd = 128;// start address in slave 0x0080-0x009F(128-159)
        telegram.u16CoilsNo = 32; // number of elements to read  0x00 0x01
        telegram.au16reg = au16data; // pointer memory array in Arduino

        master.query( telegram ); // send query (only once)
        u8state++;
        break;
      case 2:
        master.poll(); // check incoming messages
        if (master.getState() == COM_IDLE) {
          u8state = 0;
          u32wait = millis() + 2000;
            Serial.println(au16data[0]);//Or do something else!
            Serial.println(au16data[1]);//Or do something else!
            Serial.println(au16data[2]);//Or do something else!
            Serial.println(au16data[3]);//Or do something else!
            Serial.println(au16data[4]);//Or do something else!
            Serial.println(au16data[5]);//Or do something else!
            Serial.println(au16data[6]);//Or do something else!
            Serial.println(au16data[7]);//Or do something else!
            Serial.println(au16data[8]);//Or do something else!
            Serial.println(au16data[9]);//Or do something else!
            Serial.println(au16data[10]);//Or do something else!
            Serial.println(au16data[11]);//Or do something else!
            Serial.println(au16data[12]);//Or do something else!
            Serial.println(au16data[13]);//Or do something else!
            Serial.println(au16data[14]);//Or do something else!
            Serial.println(au16data[15]);//Or do something else!
            Serial.println(au16data[16]);//Or do something else!
            Serial.println(au16data[17]);//Or do something else!
            Serial.println(au16data[18]);//Or do something else!
            Serial.println(au16data[19]);//Or do something else!
            Serial.println(au16data[20]);//Or do something else!
            Serial.println(au16data[21]);//Or do something else!
            Serial.println(au16data[22]);//Or do something else!
            Serial.println(au16data[23]);//Or do something else!
            Serial.println(au16data[24]);//Or do something else!
            Serial.println(au16data[25]);//Or do something else!
            Serial.println(au16data[26]);//Or do something else!
            Serial.println(au16data[27]);//Or do something else!
            Serial.println(au16data[28]);//Or do something else!
            Serial.println(au16data[29]);//Or do something else!
            Serial.println(au16data[30]);//Or do something else!
            Serial.println(au16data[31]);//Or do something else!
        }
        break;
      }
    }

Could this be caused by the 'Number of elements" to read?
Any suggestions greatly appreciated.

This is the 32-input module [manual][2]
and [programming guide][3]

Code is based on this [example.][4]

  [1]: https://m.media-amazon.com/images/W/IMAGERENDERING_521856-T2/images/I/61JTdn25ryL._AC_SL1500_.jpg
  [2]: https://hepptech-my.sharepoint.com/:b:/p/sid/EU5R4ozC_x5CmcjbD8TwnzcBJ7FuqtWYBE-dN7v-Gh16UQ?e=c30zLW
  [3]: https://hepptech-my.sharepoint.com/:b:/p/sid/EU5R4ozC_x5CmcjbD8TwnzcBJ7FuqtWYBE-dN7v-Gh16UQ?e=wjcT4V
  [4]: https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino/blob/master/examples/simple_master/simple_master.ino

title: Using ModbusRTU.h, what would cause holding registers all read 0?

Answers: 0


body:
I need help with an Arduino project. I want to read values from a TCS150 scale using the serial port. The hardware I have is an UNO R3 board and a MAX3232 level converter.

I have connected:

MAX3232 power supply - 5V from UNO R3
TX -> D10
When checking the voltage on the TX cable connected to UNO, it varies between 3.5V and 4.2V, so there shouldn't be any connection problem. I tried to upload a simple program as shown in the picture, but I can't receive any values So far, I haven't found a solution. The incoming data when I plugged in scale to computer via Putty is correct. Do you know where I might have made a mistake in connecting or programming the Arduino?

Program:

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(10,-1);  // -1 if not using TX to save a pin

    void setup()
    {
       Serial.begin(9600);
       Serial.println("<Arduino is ready>");
       mySerial.begin(9600);
    }

    void loop()
    {
      if(Serial.available()) {
        Serial.println("serial available");
      } else {
        Serial.println("serial not available");
      }

      if(mySerial.available()) {
        Serial.println("myserial available");
      } else {
        Serial.println("myserial not available");
      }
      string x = mySerial.readString();
      Serial.println(x);
      delay(1000);
    }

    The output is:
    -> serial not available
    -> myserial not available
    -> ? (question mark in rhombus)

title: Communication with scale via rs232

Answers: 0


body:
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!

title: Processing doesn't respond to arduino

Answers: 1

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(".");


body:
I am trying to use following code but its not working. Need a help in this regard.

    #include <SimpleModbusMaster.h>
    #define baudrate 115200
    #define timeout 2000
    #define polling 500
    #define retry_count 5
    #define Txenablepins 2
    #define Led1 12
    #define totalregs 9
    enum{
      PACKET1,
      PACKET2,
      TOTAL_NO_OF_PACKETS
    };
    Packet packets[TOTAL_NO_OF_PACKETS];
    packetPointer packet1 = &packets[PACKET1];
    packetPointer packet2 = &packets[PACKET2];

    unsigned int regs[9];
    unsigned int write_regs[1];

    void setup() {

        packet1->id = 1;
        packet1->function = PRESET_MULTIPLE_REGISTERS;
        packet1->address = 0;
        packet1->no_of_registers = 1;
        packet1->register_array = write_regs;

        packet2->id = 1;
        packet2->function = READ_HOLDING_REGISTERS;
        packet2->address = 0;
        packet2->no_of_registers = 1;
        packet2->register_array = regs;

    modbus_configure(baudrate, timeout, polling, retry_count, Txenablepins, packets, TOTAL_NO_OF_PACKETS);
    pinMode(Led1, OUTPUT);

    }

    void loop() {

    unsigned int connection_status1 = modbus_update(&packets[PACKET1]);
    unsigned int connection_status2 = modbus_update(&packets[PACKET2]);
    if(connection_status1==1 and connection_status2==1){
    digitalWrite(Led1, HIGH);
    }
    else{
    digitalWrite(Led1, LOW);}
    checkResponse();

    }

This is my arduino slave code

    #include <SimpleModbusSlave.h>

    #define  ledPin  11

    enum {
        ADC0,
        ADC1,
        ADC2,
        ADC3,
        ADC4,
        ADC5,
        LED_STATE,
        BUTTON_STATE,
        TOTAL_ERRORS,
        TOTAL_REGS_SIZE
    };

    unsigned int holdingRegs[TOTAL_REGS_SIZE];

    void setup() {
     // put your setup code here, to run once:
       modbus_configure(115200, 1, 2, TOTAL_REGS_SIZE, 0);

       pinMode(ledPin, OUTPUT);
       Serial.flush();
    }

    void loop() {
      // put your main code here, to run repeatedly:

      holdingRegs[TOTAL_ERRORS] = modbus_update(holdingRegs);

      int val = analogRead(ADC0);

      holdingRegs[0] = val;

      delayMicroseconds(50);

    if(holdingRegs[0] == 1){
      digitalWrite(ledPin, HIGH);
    }
    else{
      digitalWrite(ledPin, LOW);
    }

    }

[Using this library for modbus master and slave](https://github.com/angeloc/simplemodbusng)

title: Trying to use an Arduino Uno to control two slaves with one master but its not working

Answers: 0


body:
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

title: UDP Packet Loss

Answers: 1

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


body:
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

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

Answers: 1

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


body:
    #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;
     }

     }

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

Answers: 1

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.


body:
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

title: ESP32 restart each minute with SW_CPU_RESET

Answers: 1

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();
  }
```


body:
I am trying to send information from an **Attiny85 to an ESP32, through RF**.
I am using the most popular 433mhz transmitter on the market.

I know various existing libraries to send and receive data between chip on rf hardware ;

Here are the following ones I tried :

 - Manchester
 - RC Switch
 - Radio Head

All of those seems to be working well enough, but aren't very constant in the range. **I'm having a lot of troubles receiving correct data a few meters away indoors.**

As I am not an expert in radio waves, I would like to have an explanation on what radio protocol can be trusted for simple applications, and what not to use.
I know that a simple encoding like HIGH level for digital 1, and low level for digital 0 can be compromised, and that the manchester encoding is a better idea, but I would like to have a better understanding on how it works.

title: Choosing a good RF library for transmissions

Answers: 0


body:
I have been having trouble with the code below not display and possibly not working and or looping. Before making changes to my code I had a problem where the Serial monitor would print up to "longitude" and occasionally print the first number of this value, however, it would pause stop and the whole code would pause/not continue. I had printed data to the Serial Monitor constantly but was told that the problem could be that the serial monitor is full. With this, I have deleted most of the code for the serial monitor as it is not needed for my project. Now I cant tell at what stage my code is not working. The code for the screen is formatted this way as I have found it is the best way to reduce flickering, however I know there is a fast display library but was unable to implement it.
Could it be battery issue? I am using a 9V battery to power all of the components.
Any help would be much appreciated and the code is provided below.

```
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <DFRobot_SIM808.h>
#include <SPI.h>
#include <Wire.h>

#define TFT_CS        10
#define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
#define TFT_DC         8

#define date_x    20
#define date_y    17
#define time_x    20
#define time_y    35
#define v_x       17
#define v_y       70

float la;
float lo;

char DateGPS[10];
char TimeGPS[5];

String prevDate = "99/99/9999";
String Date = "00/00/0000";
String prevTime = "99:99";
String Time = "00:00";
String prevV = "999:99";
String V = "000:00";

Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

DFRobot_SIM808 sim808(&Serial);

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

  tft.init(240, 280);
  tft.fillScreen(ST77XX_BLACK);

  //******** Initialize sim808 module *************
  while(!sim808.init())
  {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      ;
  else
      ;

}

void loop()
{
   //************** Get GPS data *******************
   if (sim808.getGPS())
   {
    sprintf(DateGPS, "d-d-d", sim808.GPSdata.day, sim808.GPSdata.month, sim808.GPSdata.year);
    Date = String(DateGPS);
    if(prevDate != Date)
    {
      deletePrevDate();
      printDate();
    }
    prevDate = Date;

    sprintf(TimeGPS, "d:d", sim808.GPSdata.hour, sim808.GPSdata.minute);
    Time = String(TimeGPS);
    if(prevTime != Time)
    {
      deletePrevTime();
      printTime();
    }
    prevTime = Time;

    Serial.println(sim808.GPSdata.lat, 6);

    Serial.println(sim808.GPSdata.lon, 6);

    V = String(sim808.GPSdata.speed_kph);
    if(prevV != V)
    {
      deletePrevV();
      printV();
    }
    prevV = V;

    //************* Turn off the GPS power ************
    sim808.detachGPS();
  }

}

void deletePrevDate()
{
  tft.setCursor(date_x, date_y);
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_BLACK);
  tft.println(prevDate);
  return;
}

void printDate()
{
  tft.setCursor(date_x, date_y);
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_WHITE);
  tft.println(Date);
  return;
}

void deletePrevTime()
{
  tft.setCursor(time_x, time_y);
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_BLACK);
  tft.println(prevTime);
  return;
}

void printTime()
{
  tft.setCursor(time_x, time_y);
  tft.setTextSize(2);
  tft.setTextColor(ST77XX_WHITE);
  tft.println(Time);
  return;
}

void deletePrevV()
{
  tft.setCursor(v_x, v_y);
  tft.setTextSize(6);
  tft.setTextColor(ST77XX_BLACK);
  tft.println(prevV);
  return;
}

void printV()
{
  tft.setCursor(v_x, v_y);
  tft.setTextSize(6);
  tft.setTextColor(ST77XX_WHITE);
  tft.println(V);
  return;
}
```

title: Code not displaying/working DFRobot SIM808 shield data on Adafruit 1.69" ST7789 rounded screen

Answers: 0


body:
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 |

title: Why is sensitivity (threshold) parameter ignored

Answers: 1

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


body:
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

Answers: 1

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.


body:
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.

title: How to use ESP_LOGx?

Answers: 1

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


body:
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

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

Answers: 2

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


body:
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

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

Answers: 1

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..


body: 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?

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

Answers: 1

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.


body:
**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?**

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

Answers: 1

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);
    }


body: 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?

title: How to Protect GPIO when using long wires?

Answers: 3

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


body:
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.

title: Incorrect data received on serial communication

Answers: 1

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.


body:
I'm trying to get an ethernet module with the W5500 chipset to connect to my network on an Arduino Uno, but whatever I do, I always get an incorrect IP address.

The module is connected as default SPI, with the CS pin on pin 10.

Initially I was using the wrong libraries (those meant for the ENC28J60), until Juraj pointed out to me that I [had the W5500 chipset][1].

So I loaded the Ethernet WebServer example sketch in my Arduino IDE (1.8.13), changed the IP value, compiled it, and tried to run it. In my code, I set the IP to 192.168.123.225, but the serial monitor showed me IP 192.80.239.132 .

After some Googling I found a post called [Ethernet library not initializing IP correctly][2], as well as several other pages each stating that the Ethernet2 library should be used for the W5500 chipset instead of Ethernet.

I've tried installing the Ethernet2 library from within the Arduino IDE, with the exact same result. I loaded the example sketch of this library, same result. After downloading the library from [GitHub][3] (as found on another page describing the same problem), I got some errors and commented out some sections as seen in my code below, but still with the same result.

In the commented code you can also see that I've added a check to see whether my module is actually recognized as a W5500, and it is...

So my question, while elaborate, is very simple: how can I set the IP correctly on a W5500 chipset module connected to an Arduino Uno?

Here is my code (I've left out the loop, obviously):

    #include <SPI.h>
    #include <Ethernet2.h>

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 123, 225);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);

    void setup()
    {
      // You can use Ethernet.init(pin) to configure the CS pin
      Ethernet.init(10);  // Most Arduino shields

      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial)
      {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      Serial.println("Ethernet WebServer Example");

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);

      // Check for Ethernet hardware present
      /*
      if (Ethernet.hardwareStatus() == EthernetNoHardware)
      {
        Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
        while (true)
        {
          delay(1); // do nothing, no point running without Ethernet hardware
        }
      }
      else
      {
        if (Ethernet.hardwareStatus() == EthernetW5500)
        {
          Serial.println("Ethernet shield is a W5500");
        }
      }

      if (Ethernet.linkStatus() == LinkOFF)
      {
        Serial.println("Ethernet cable is not connected.");
      }
      */

      // start the server
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }

  [1]: https://arduino.stackexchange.com/questions/92678/how-to-connect-and-use-hanrun-hr961160c-ethernet-component?noredirect=1#comment213990_92678
  [2]: https://forum.arduino.cc/t/ethernet-library-not-initializing-ip-correctly/664466
  [3]: https://codeload.github.com/adafruit/Ethernet2/zip/refs/heads/master

title: Incorrect IP address when using Ethernet library with Arduino Uno and WizNet 5500 ethernet module

Answers: 0


body: how do I reinitialize an Arduino kit registration number for a new student using a kit previously registered?  We recently ordered 50 of the IoT Explorer Kits and they will be used in a robotics class that has frequent turnover, and the kits need to be used under different student accounts.

title: IoT Explorer Kit registration process

Answers: 0


body:
According to [this thread][1] the VL6180X after changing the i2c address the new address should persist after a power down. but when i changed mine it came back to its default address at 0x29. Here is the code i used to change the address

    #include <Wire.h>
    #include "Adafruit_VL6180X.h"

    Adafruit_VL6180X vl = Adafruit_VL6180X();

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

      // wait for serial port to open on native usb devices
      while (!Serial) {
        delay(1);
      }

      Wire.setSDA(0);
      Wire.setSCL(1);
      Wire.begin();

      Serial.println("Adafruit VL6180x test!");
      if (! vl.begin()) {
        Serial.println("Failed to find sensor");
        while (1);
      }
      Serial.println("Sensor found!");
      vl.setAddress(0x35);
    }

After running this code i then ran a i2c scanner code which indeed showed the new 0x35 address but when i re-plugged the power it went back to 0x29. Am i doing something wrong here? Or the thread is just wrong ?

  [1]: https://forums.adafruit.com/viewtopic.php?t=123872

title: VL6180X returning to its default i2c address after shutdown

Answers: 0


body:
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?

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

Answers: 1

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));
```


body:
# Issue (short) description
An ESP8266 using PubSubClient fails to establish connection to MQTT broker (mosquitto) if requesting Last Will Testament (LWT) on connection, though it is able to connect without LWT.

# The aim and detailed description of the issue
The aim is actually to make the ESP to receive messages that been published while it was offline. Following [the generic recipe for MQTT][1], I tried to set `cleanSession =false` [which in `PubSubClient` also requires passing LWT arguments][2]. Using code shown bellow (with the arguments passed to the `PubSubClient.connect()` method)  results in that the same ESP board connecting to the same MQTT server could not connect anymore (the code below is stripped to MQTT relevant parts):
```C
WiFiClient wclient;
PubSubClient mqtt_client(wclient);

String DEVICE_NAME = "esp8266_test";
const int DEVICE_ID = 1;
String MQTT_CLIENT_ID = DEVICE_NAME + (String)(DEVICE_ID);

const char * mqtt_client_id = MQTT_CLIENT_ID.c_str();
const char* willTopic = (DEVICE_NAME + "/will").c_str();
uint8_t willQos = 0;
bool willRetain = false;
const char* willMessage = "will";
bool cleanSession = false;
int mqtt_keep_alive = 60;

void connect_mqtt(const char *mqtt_user, const char *mqtt_pass, const int timeout){
  int i = 0;
  logger.info("Connecting to MQTT broker.");
  while ((!mqtt_client.connected()) && (i < timeout) && (WiFi.status() == WL_CONNECTED)) {
    logger.info("Attempt " + (String)(++i));
    mqtt_client.setKeepAlive(mqtt_keep_alive);
    mqtt_client.connect(
      mqtt_client_id,
      mqtt_user,
      mqtt_pass,
      willTopic,
      willQos,
      willRetain,
      willMessage,
      cleanSession);
  }

  if (mqtt_client.connected()) {
        logger.info("MQTT broker connected.");
    } else {
        logger.error("Connection timeout. Failed with state: " + (String)(mqtt_client.state()));
        }
}

void start_mqtt(IPAddress mqtt_server, const int mqtt_port, const char *mqtt_user, const char *mqtt_pass){

  mqtt_client.setServer(mqtt_server, mqtt_port);
  // mqtt_client.setCallback(callback);
  connect_mqtt(mqtt_user, mqtt_pass, timeout);
}

```
In the code above `start_mqtt()` function is called from `setup()`, the output it will result in looks as follows:
```
INFO: Connecting to WIFI SSID: xxxxxxx
INFO: WiFi Connection established
IP address:     192.168.178.55
INFO: Connecting to MQTT broker.
INFO: Attempt 1
INFO: Attempt 2
INFO: Attempt 3
INFO: Attempt 4
INFO: Attempt 5
INFO: Attempt 6
ERROR: Connection timeout. Failed with state: -4
```
If instead one calls `connect()` method with only `mqtt_client_id, mqtt_user, mqtt_pass` arguments, the connection can be established without any issues, e.g.:
```C
mqtt_client.connect(mqtt_client_id, mqtt_user, mqtt_pass)

```
# Attempts to troubleshoot:
* I've tried using `connect()` without `cleanSession` argument, the behaviour is the same: cannot connect with state `-4`. So I've concluded that the issue is in LWT service, which I actually don't need but it [seems one has to use it with `cleanSession`][2]
* According to [PubSubClient documentation][3] the `-4` state is "the server didn't respond within the keepalive time", so I've started looking on the server side (see next items)
* The server log looks like this:
```
2023-04-01 18:37:09 1680367029: Client <unknown> disconnected due to protocol error.
2023-04-01 18:38:36 1680367116: New connection from 172.17.0.1:54174 on port 1883.
```
* If connecting without LWT (using only `mqtt_client_id`, `mqtt_user`, `mqtt_pass` arguments) connection can be established and the log looks like this:
```
2023-04-01 18:38:36 1680367116: New client connected from 172.17.0.1:54174 as esp8266_test1 (p2, c1, k60, u'xxxx').
```
* [Mosquitto documentation][4] doesn't say anything about enabling LWT, which suggests that it should work with the mostly default config which is used here.

* I tried two different Mosquitto servers configured for user/password authentication, results are the same.

# Questions
Based on behaviour above, my conclusion is that using PubSubClient with LWT results in a sort of change of a protocol which is not recognised/supported by Mosquitto. Therefore, the questions are:

1. Is there is a way to fix the issue, or to further troubleshoot it?
1. Is there is a way to use `cleanSession = false` without enabling LWT?
1. Is there other ways of receiving "offline" MQTT messages on ESP8266 (without using `cleanSession = false`)?

  [1]: https://stackoverflow.com/a/34152167/6033228
  [2]: https://pubsubclient.knolleary.net/api#connect
  [3]: https://pubsubclient.knolleary.net/api#state
  [4]: https://mosquitto.org/man/mosquitto-conf-5.html

title: MQTT on ESP8266 cannot connect if using Last Will service

Answers: 0


body:
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();

```

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

Answers: 1

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();


body:
Here is the verbose for the Arduino IDE:

    Flashing with command:/Users/hakan/.arduino-create/arduino/openocd/0.11.0-arduino2/bin/openocd -d2 -s /Users/hakan/.arduino-create/arduino/openocd/0.11.0-arduino2/share/openocd/scripts/ -f interface/cmsis-dap.cfg -c transport select swd; adapter speed 1000 -f target/nrf52.cfg -c telnet_port disabled; init; reset init; halt; adapter speed 10000; program {/var/folders/dy/qqk78q1956s1pb94hc4y_x5m0000gn/T/arduino-create-agent511362936/sketch_mar22a.elf}; reset run; shutdown

    Open On-Chip Debugger 0.11.0+dev-gab95bac57-dirty (2021-05-11-10:57)

    Licensed under GNU GPL v2

    For bug reports, read

    http://openocd.org/doc/doxygen/bugs.html

    debug_level: 2

    adapter speed: 1000 kHz

    Info : CMSIS-DAP: SWD Supported

    Info : CMSIS-DAP: FW Version = v1.0

    Info : CMSIS-DAP: Serial# = AA7EAA93

    Info : CMSIS-DAP: Interface Initialised (SWD)

    Info : SWCLK/TCK = 1 SWDIO/TMS = 1 TDI = 0 TDO = 0 nTRST = 0 nRESET = 1

    Info : CMSIS-DAP: Interface ready

    Info : clock speed 1000 kHz

    Info : SWD DPIDR 0x2ba01477

    Info : nrf52.cpu: hardware has 6 breakpoints, 4 watchpoints

    Info : starting gdb server for nrf52.cpu on 3333

    Info : Listening on port 3333 for gdb connections

    target halted due to debug-request, current mode: Thread

    xPSR: 0x01000000 pc: 0x00006dc4 msp: 0x20010000

    target halted due to debug-request, current mode: Thread

    xPSR: 0x01000000 pc: 0x00006dc4 msp: 0x20010000

    ** Programming Started **

    Info : nRF52832-CIAA(build code: E0) 512kB Flash, 64kB RAM

    Warn : Adding extra erase range, 0x0001d8f8 .. 0x0001dfff

    ** Programming Finished **

    shutdown command invoked

Here is the one for PlatformIO:

    AVAILABLE: blackmagic, cmsis-dap, jlink, nrfjprog, nrfutil, sam-ba
    CURRENT: upload_protocol = cmsis-dap
    openocd -d2 -s /Users/hakan/.platformio/packages/tool-openocd/scripts -f interface/cmsis-dap.cfg -f target/nrf52.cfg -c "transport select swd;" -c "adapter speed 1000" -c "program {.pio/build/nicla_sense_me/firmware.hex}  verify reset; shutdown;"
    xPack OpenOCD x86_64 Open On-Chip Debugger 0.11.0+dev (2021-10-17-00:18)
    Licensed under GNU GPL v2
    For bug reports, read
            http://openocd.org/doc/doxygen/bugs.html
    debug_level: 2

    Info : auto-selecting first available session transport "swd". To override use 'transport select <transport>'.
    Warn : Transport "swd" was already selected
    swd
    adapter speed: 1000 kHz

    Info : CMSIS-DAP: SWD  supported
    Info : CMSIS-DAP: FW Version = v1.0
    Info : CMSIS-DAP: Serial# = AA7EAA93
    Info : CMSIS-DAP: Interface Initialised (SWD)
    Info : SWCLK/TCK = 1 SWDIO/TMS = 1 TDI = 0 TDO = 0 nTRST = 0 nRESET = 1
    Info : CMSIS-DAP: Interface ready
    Info : clock speed 1000 kHz
    Info : SWD DPIDR 0x2ba01477
    Info : nrf52.cpu: Cortex-M4 r0p1 processor detected
    Info : nrf52.cpu: target has 6 breakpoints, 4 watchpoints
    Info : starting gdb server for nrf52.cpu on 3333
    Info : Listening on port 3333 for gdb connections
    target halted due to debug-request, current mode: Thread
    xPSR: 0x01000000 pc: 0x000008e4 msp: 0x20000400
    ** Programming Started **
    Info : nRF52832-CIAA(build code: E0) 512kB Flash, 64kB RAM
    Warn : Adding extra erase range, 0x00052738 .. 0x00052fff
    ** Programming Finished **
    ** Verify Started **
    ** Verified OK **
    ** Resetting Target **
    shutdown command invoked

`Platform.ini` content:

    [env:nicla_sense_me]
    platform = nordicnrf52
    board = nicla_sense_me
    framework = arduino
    monitor_speed = 115200
    debug_speed = 1000
    upload_protocol = cmsis-dap

    lib_deps =
        Wire
        /Users/marcopolo/Documents/PlatformIO/Projects/C1/include/Arduino_BHY2
        /Users/marcopolo/Documents/PlatformIO/Projects/C1/include/ArduinoBLE-master

The code is a very basic `blink` example.

Edit: Here is the error:

    ++ MbedOS Fault Handler ++

    FaultType: HardFault

    Context:
    R   0: 20010000
    R   1: 0001BB1C
    R   2: 00000005
    R   3: 00000000
    R   4: 20010000
    R   5: 20010000
    R   6: 0001BB1C
    R   7: 00000000
    R   8: 00000000
    R   9: 00000000
    R  10: 00000000
    R  11: 00000000
    R  12: FFFFFFFF
    SP   : 20002CA0
    LR   : 00010CB7
    PC   : 00013B3E
    xPSR : A1070000
    PSP  : 20002C80
    MSP  : 2000FFC0
    CPUID: 410FC241
    HFSR : 40000000
    MMFSR: 00000000
    BFSR : 00000082
    UFSR : 00000000
    DFSR : 00000000
    AFSR : 00000000
    BFAR : 20010000
    Mode : Thread
    Priv : Privileged
    Stack: PSP

    -- MbedOS Fault Handler --

    ++ MbedOS Error Info ++
    Error Status: 0x80FF013D Code: 317 Module: 255
    Error Message: Fault exception
    Location: 0x13B3E
    Error Value: 0x2000303C
    Current Thread: main Id: 0x20001A78 Entry: 0x13057 StackSize: 0xC00 StackMem: 0x200020D0 SP: 0x20002CA0
    For more info, visit: https://mbed.com/s/error?error=0x80FF013D&tgt=NICLA
    -- MbedOS Error Info --

Edit: Same board works pretty fine in **Windows OS.**

title: Code works in Arduino Web editor but not in PlatformIO IDE or Arduino IDE with board Nicla Sense ME

Answers: 0


body:
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?

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

Answers: 1

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


body:
I have a code that should pause the script for a specific time (x_time). if x_time is above 30-40 sec the BLE connection to the android phone is lost. Any suggestions on how to avoid the lost connection and creating a pause in the script?

code:
```
#include "LSM6DS3.h"
#include "Wire.h"
#include <ArduinoBLE.h>  // Arduino BLE library

//Create a instance of class LSM6DS3
LSM6DS3 myIMU(I2C_MODE, 0x6A);  //I2C device address 0x6A
const char* UUID_serv = "75681d64-fd7e-40f7-874f-c6f2e7ec996c";

// UUids for accelerometer characteristics
const char* UUID_AccBLE = "75681d64-dd7e-40f7-874f-c6f2e7ec996c";

BLEService myService(UUID_serv);
BLEIntCharacteristic AccBLE(UUID_AccBLE, BLERead | BLENotify);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while (!Serial) {

    pinMode(LEDB, OUTPUT);  // onboard led blue
    //Call .begin() to configure the IMUs
    if (myIMU.begin() != 0) {
      Serial.println("Device error");
    } else {
      Serial.println("Device OK!");
    }
    // init BLE
    if (!BLE.begin()) {
      Serial.println("BLE: failed");
    }
    Serial.println("BLE: ok");

    BLE.setAdvertisedService(myService);
    myService.addCharacteristic(AccBLE);
    BLE.addService(myService);
    AccBLE.writeValue(0);
    // start advertising
    BLE.advertise();
    Serial.println("Advertising started");
    Serial.println("Bluetooth device active, waiting for connections...");
  }
}
float accelerometerX;
unsigned long BreakPreviousMillis;
unsigned long timestamp = micros();

int x_time = 50000;
void loop() {
  BLEDevice central = BLE.central();
  if (central) {
    Serial.print("Connected to central: ");

    while (central.connected()) {
      accelerometerX = myIMU.readFloatAccelX();
      if (accelerometerX > 2) {
        BreakPreviousMillis = millis();
        while (millis() < BreakPreviousMillis + x_time) {
          Serial.println("pause");
        }
      }
      AccBLE.writeValue(accelerometerX);
      Serial.print("*************LOOP TIME[uS] = ");
      Serial.println(micros() - timestamp);  // 13HZ =79000-80000 uS   // used to check framerate
    }

    digitalWrite(LEDB, HIGH);  // High == turning off the Led
    Serial.print("Disconnected from central: ");
    Serial.println(central.address());
  }
}
```

title: BLE disconnect during code "pause"

Answers: 0


body:
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.

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

Answers: 1

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.