text:
I am attempting to control two stepper motors by using serial input. My code works, however I have to press the new directional command multiple times
I am using two 28BYJ-48 stepper motors with two motor drivers that they come with. (I don't know the name of them.)
Here is my code:
/*
 * Code to control two stepper motors simultaneously using the stepper library function calls
 * This code has functions which make calls to initiate one step from each of the two motors at a time
 * therefore each motor takes it in turn to step with the end result of them both running together
 * the variable 'lastCall' allows for a continuous input to keep the steppers running if there is no serial input
 * Written by Gabriel Adams  - March 2023 -
 */
#include <Stepper.h>

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

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

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

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

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

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

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

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

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

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

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

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

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

char data = lastCall;

Loop(lastCall);
Serial.read();

}

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

(char)Serial.read();
}

Why are you doing these two Serial.read()s without using the result outside of your serial code? If your data arrives right before that, it will just be discarded.

I am still in the learning process of object-oriented coding. I was thinking the Serial.read() command would ensure more immediate reads of serial inputs. How would I better assess this? As in, instead of how at the moment it won't immediately change direction when I give a new command, how do I ulitize the Serial.read() command to quickly move to a new loop.

Seems you have a strange understanding of function parameters, which are not used by the functions. BTW: function prototyping is done by the IDE for you, but if you do it yourself, do it right: parameters should fit.

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

You use in in the block with your serial code and you set lastCall accordingly. This is ok.
Then you use it at the end of void loop(), but you don't assign the value to anything.
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.


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

Go into Properties on your "Unknown Device", go to Details tab, show the Hardware Ids property values.

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

source: Stack Exchange

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

sort: votes


text:
LVGL v8.2 on ESP32-S3 colour issue ILI9341 TFT LCD Arduino IDE
I have ILI9341 320x240px TFT LCD screen 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.

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
/*====================
   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.

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.

I am encountering the exact same problem, using the same ESP32-S3, but using ESP-IDF framework; not Arduino. My solution was exactly the same as yours; comment out the LV_COLOR_16_SWAP in the generated ui.c. BTW, the project I am working on is here: https://github.com/smeisner/smart-thermostat I am hoping this gets fixed sometime soon!

BTW, I found this on the SquareLine Studio forum: http://forum.squareline.io/t/when-exporting-let-us-choose-if-we-want-lv-color-16-swap-or-not/1750?u=meisner

Thanks @SteveMeisner for sharing the link

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


text:
Save sensors data on PC
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.

How is your ESP connected to your PC? If there is a USB link, something like stty -F /dev/ttyUSB0 raw -echo && cat /dev/ttyUSB0 > sensor-data.txt should do it (the details are OS-dependent). If using WiFi, I would try netcat.


text:
HC05 and ELM327 NODATA sending PID codes
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:

Unplug the Arduino and let it power down.
Plug the Arduino back in and open the Serial monitor and send whatever command I want AT or PID such as ATZ or 010C.
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.

which part of your post is about arduino? ... the sensor is responding with a message

I am wondering if there is something going on with the way I am using Arduino's Software Serial that is making my inputs unable to be read properly by the ELM327 device when passed through the HC05. Apologies for not clarifying on what the problem is.

if the HC05 is sending you clear, readable messages, then the problem is not the arduino


text:
A fatal error occurred: Failed to connect to ESP32: Wrong boot mode detected (0x13)! The chip needs to be in download mode. [upload] Error 2
I have seen so many people complain about this same error and they were given a multitude of answers to help with this error, but nothing so far has worked for me.
Everything was working fine until I upgraded to Win 11 and the latest version of VS Code. I also attempted uploading with the Arduino IDE and no success.
I'm at the point of throwing the ESP32 boards into a box, and moving onto an alternative until someone comes up with a different solution.
This is my failed punch list gathered from the many postings about this error:

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

I would start over and bring up the simplest software development kit possible.  That means to layoff VSCode and just start with a fresh install of the Arduino software development kit.  I might even start with a real Uno (not a knock off, and not something as complex as an ESP processor).  Just to make sure everything is functioning as expected.  BTW, I recently updated many tools on one of my windows PCs and noticed that VSCode posted a note indicating a paradigm switch WRT it's Arduino software was taking place as part of the VSCode upgrade.

Thanks, I will try your suggestion.  If it doesn't work, then I'll add it to the my list of attempts.  I'm not familiar with "paradigm switch WRT".  What does that mean?

When I updated my copy of VSCode there was a message (a popup) that the Arduino feature was being changed.  I don't recall the particulars.  I use VSCode extensively for something other than Arduino development and popups usually never happen during an upgrade.  That is what I meant by a "paradigm switch WRT ... (With Respect To)".

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:

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.

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.


text:
How to use LiPo powered Arduino Nano BLE when it's charging (with a charging circuit and a boost converter)?
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 it is then connected to Adafruit's MiniBoost 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)?

I would definitely not do that. You try to short the USB 5 V with the 3.7 V of the LiPo battery. If VBat on the charger is not protected, 5V will produce a loading current that might destroy the battery. I also have to tell you, the resistor for the LED on your schematics has no meaning. Both legs of the resistor and one leg of the LED are on the same rail of breadboard. For a power selector the following link might help https://arduino.stackexchange.com/questions/39805/can-you-charge-and-use-a-lipo-battery-at-the-same-time

For example Seeed studio Xiao BLE has the same MCU and also battery "pads" + charging circuit
And of course then you can't use constructs like while (!Serial); in setup

"Ideally I'd like to use the device while it's charging", this is not an Arduino question, it is an electronic question. In order to use the device while charging, you need a "load sharing" circuit, otherwise your battery might not get fully charged. Read this Microchip App Note. The load sharing circuitry disconnect the battery from the  load (i.e. your device) while charging and directly supply the 5V from USB to the load, and when the USB/5V is not present, the battery will supply the power to the load.


text:
Looking for FOTA to update firmware with wi-fi over internet (ESP32)
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?

the HTTPUpdate library bundled with the esp32 Arduino core


text:
Using ModbusRTU.h, what would cause holding registers all read 0?
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.
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
and programming guide
Code is based on this example.

Your code would be more readable with proper indentation. Can you clarify what you mean with "never displayed"? What is actually displayed? Is the actual amount of received bytes correct?

What is actually displayed is a 0, not a 1 when the input is ON.

If you change your code completely, you should added it as an UPDATE than total replace your original code.

What RS485/Modbus interface board you have? other than the Pin2 for RX, and P3 for TX, How do you wire the RE(Receiver Enable) and DE(Driver Enable) pins?

"Code courtesy of: [He who shall not be named]"  No, what that guy does is leech off these sites with an automatic video generation system. Real credit goes to (or more to) one of the authors here of an ESE Q&A.

I am using this RS485 interface board: https://m.media-amazon.com/images/W/IMAGERENDERING_521856-T2/images/I/61JTdn25ryL.AC_SL1500.jpg
I apologize for the code replace and didn't know about an Update.  I've been fussed at before for posting a second too similar of a question.

I think the library somehow changed the API for creating an instance of master and deprecated the master.begin() in favour of master.start().

I found a working solution here: https://www.youtube.com/watch?v=zTanigwP5ow (see link to his blog-bottom) that was very simple using the same two libraries.


text:
Communication with scale via rs232
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)

Quick comment:  It looks like you are trying  to open a hardware serial port and a software serial port.  Two serial ports!  Is that what you really wanted to do?

@st2000 I think Konrad wants to read from a scale TCS150 and forward the reading to the Arduino Terminal. So both channel are required. The Serial.available if statement is not needed, there is no writing from the terminal to the Arduino. I would do it like if (myserial.available()){ Serial.write(myserial.read()); }.  And delete the rest of the code in the loop() routine.


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

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

void setup() {

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

void draw() {

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

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

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

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

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

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

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

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

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

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

  text("10cm",width-width*0.3854,height-height*0.0833);
  text("20cm",width-width*0.281,height-height*0.0833);
  text("30cm",width-width*0.177,height-height*0.0833);
  text("40cm",width-width*0.0729,height-height*0.0833);
  textSize(40);
  text("Obje: " + noObject, width-width*0.875, height-height*0.0277);
  text("Açı: " + iAngle +" °", width-width*0.48, height-height*0.0277);
  text("Mesafe: ", width-width*0.26, height-height*0.0277);
  if(iDistance<40) {
  text("        " + iDistance +" cm", width-width*0.225, height-height*0.0277);
  }
  textSize(25);
  fill(98,245,60);
  translate((width-width*0.4994)+width/2*cos(radians(30)),(height-height*0.0907)-width/2*sin(radians(30)));
  rotate(-radians(-60));
  text("30°",0,0);
  resetMatrix();
  translate((width-width*0.503)+width/2*cos(radians(60)),(height-height*0.0888)-width/2*sin(radians(60)));
  rotate(-radians(-30));
  text("60°",0,0);
  resetMatrix();
  translate((width-width*0.507)+width/2*cos(radians(90)),(height-height*0.0833)-width/2*sin(radians(90)));
  rotate(radians(0));
  text("90°",0,0);
  resetMatrix();
  translate(width-width*0.513+width/2*cos(radians(120)),(height-height*0.07129)-width/2*sin(radians(120)));
  rotate(radians(-30));
  text("120°",0,0);
  resetMatrix();
  translate((width-width*0.5104)+width/2*cos(radians(150)),(height-height*0.0574)-width/2*sin(radians(150)));
  rotate(radians(-60));
  text("150°",0,0);
  popMatrix();
}

Code from Arduino IDE:
#include <Servo.h>   // servo motor kütüphanesi
#define trigPin 4    // ultrasonik sensör trig pini
#define echoPin 3    // ultrasonik sensör echo pini
Servo servoMotor;     // servo motor nesnesi
int angle = 0;        // servo motor açısı
long duration, distance;  // ultrasonik sensör mesafesi

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

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

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

Thank you for the help!

the processing sketch is irrelevant here ... open the Arduino IDE serial monitor to determine if the correct data is being sent by the Arduino

can you give me more details. Like i said i don't know english too much and i am new to arduino ide. And there is only the angle in the serial monitor

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


text:
Trying to use an Arduino Uno to control two slaves with one master but its not working
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

what does not working mean? ... what actually happens? ... please update your post with a clear description

add some debugging code ... right now, you have no way of knowing what the programs are doing

"control two slaves with one master but its not working" You were able to get it to control one?

The library you are using uses Serial port for modbus communication, that means that you can't open the Serial Monitor and the only way to know whether it is working or not is by observing the LED. You should either take a look at the library SoftwareSerail examples or find a better Modbus library.


text:
UDP Packet Loss
I have an application on a PC that sends 10 UDP packets to an Arduino Portenta board.  When sending packets with no delay, half of them are lost.  Wireshark shows the packets are correctly sent by the PC.  If I busy-wait 1ms between each message on the PC, the Arduino receives everything.
I tried to disable the processing done when receiving a message, but it doesn't help.
I know UDP is not a reliable protocol.  Still, having half the packets lost while the PC is directly connected to the Arduino is surprising.  I'm only trying to send 10 packets!
Is there an option to increase the receive buffer?  I would have tried increasing SO_RCVBUF.
Any other idea?
Thank you

Obvious "other idea": TCP - nothing is lost and if the network doesn't have capacity, you can't flood it like with UDP. Another one: bigger packets, less often. But nothing useful

The use case is not appropriate for TCP.

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

The PC is directly connected to the Arduino, and I only send 10 packets.  Would that mean only 5 packets are buffered by the Arduino?

@Simon It could indicate that the rate at which the Arduino can remove packets from the buffer is such that it can only keep up with a slower rate. Possibly only one packet is buffered, but by the time you have processed that you have lost the next one but the third can be received OK. And so on.


text:
Have I ruined my Arduino Nano with my terrible soldering (technique and tools!)
So I bought a Arduino Nano and a very cheap soldering iron and solder from Alibaba. I was attempting to solder in some connections and failing pretty hard. A small resister popped off when trying to solder a wire to ground. I was pretty good when soldering in high school...but it's been a while since then.
By just plugging it into my computer, I was able to upload a simple program which switches the LED on and off - and that still works.
I'm not clearly not competent enough and I don't have a good enough soldering iron to do surface mount soldering to repair it. So I'm wondering if it'll still do what I want it to do.
My overall aim is to build a simple music player for my 3 year old.
My question is, what does that resistor do? Have I ruined the board?

Is that the spot up near the top-right? What colour was the "resistor"? Brown? Judging by an image I found on the Internets it is actually the DTR reset capacitor, probably 0.1 µF.

You obviously solder without any solder flux. Learn for example from https://www.youtube.com/watch?v=oqV2xU1fee8

@KIIV I can attest I soldered with solder. Lots of solder.
What I did not do, was clean the board of residue and check for the correct technique for soldering wires to pinholes. I also used incredibly cheap soldering iron and solder from Alibaba. I've now rectified all those elements and am wondering whether I should just chuck the board or its still usable.

I was able to upload a simple program which switches the LED on and off - and that still works - sounds usable to me.

From what I can work out, the two reset pins are now dead. It looks like the other resister (capacitor?) was connected in series to the capacitor that was lost. I can't work out what else was connected to that...

@NickGammon I know it kinda works but with one tiny component missing, something is definitely broken. If I know what function doesn't work, then I know whether I can still do my project.

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:

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

Thanks Nick for the comment. After a bit of practice and borrowing a different soldering iron, it turns out the issue was largely my cheap soldering iron. It was not getting up to temperature properly, so I was leaving it heating the joint for way too long before being able to melt the solder. I appreciate the help.


text:
An error is shown as sendCommand was not declared in this scope.how to rectify it
#include <LiquidCrystal.h>
LiquidCrystal lcd(2,8,6,5,4,3);
#include <SoftwareSerial.h>
#define RX 9
#define TX 10
//ESP8266 CODE
String AP = "OPPO F11 PRO";       // AP NAME
String PASS = "bhargav123"; // AP PASSWORD
String API = "DWX3OYUU26GI5IJ7";   // Write API KEY
String HOST = "api.thingspeak.com";
String PORT = "80";
int countTrueCommand;
int countTimeCommand;
boolean found = false;
int valSensor = 1;

SoftwareSerial esp8266(RX,TX);

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

//ESP8266 CODE

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

}

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

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

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

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

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

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

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

    countTimeCommand++;
  }

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

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

  found = false;
 }

 }

I am sure there are more error messages. read them

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


text:
ESP32 restart each minute with SW_CPU_RESET
running an ESP32 (ttgo), I get strange behavior.  The unit restarts each minute, around 00 seconds.
I get
12:31:02.861 -> rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
as reason.
I checked flash frequency is 40MHz (80 seems to lead to same issues)
Anyway, if I start the device at 10:00:34, it will restart at 10:01:00 and then at 10:02:00 and so on ...
running this code:   https://github.com/xlyric/pv-router-esp32
Powered by a usb-C phone-power, or on computer usb does the same.
The ttgo is plugged on a board connected to a AC/AC transformer and a current mesure device.
using "esp_register_shutdown_handler", I succed to send a mqtt message "gonna die",  it really rise each minute at 00 seconds

Your question does not contain enough information to anwer it. Describe your setup. What code is your ESP32 running? What power supply is it connected to? What other hardware is connected to it?

Thanks all, bug was between chair and keyboard :-) I was getting http calls on "/reset" from a crazy domoticz instance

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:
if (config.restart) {
    //delay(5000);
    Serial.print(PV_RESTART);
    ESP.restart();
  }


text:
Choosing a good RF library for transmissions
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.

what leads you to believe that the library is the cause of the problem?

I don't believe any library might be the problem, but that differents protocol will offer different speed. For example I would like to send the received data to another chip, and the receiving speed matters. But I don't really know what protocols they use, and what is the difference between them. In my application the code seems to slow down reception, as I'm not sure how it works, I think the way reception is handled might change things, but I'm not sure... I also didn't really know how to put the question...


text:
Code not displaying/working DFRobot SIM808 shield data on Adafruit 1.69" ST7789 rounded screen
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, "%02d-%02d-%04d", sim808.GPSdata.day, sim808.GPSdata.month, sim808.GPSdata.year);
    Date = String(DateGPS);
    if(prevDate != Date)
    {
      deletePrevDate();
      printDate();
    }
    prevDate = Date;

    sprintf(TimeGPS, "%02d:%02d", 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;
}

serial monitor is full is nonsense ... you can test that with a sketch that sends a lot of data

please roll back your code to the previous version with lots of serial.print ... copy the content of the serial monitor and paste it into your question ... format it as code for readability ... please, no screenshots of text


text:
Why is sensitivity (threshold) parameter ignored
Analog pontentiometer connected to an Arduino. simplest possible setup.
The goal is to send a message over Serial whenever the value changes.
I do not want to spam the Serial connection to much, so the value has to change by at least 20 (sensitivty threshold) before a message Packet is sent.
However, in reality a message Packet is sent even if the value changed only by 1. Why is sensitivity parameter ignored?
edit: After debugging I can see that it enters the first IF-statement in read(). The IF statement evaluates to 0 which is super weird. It shouldn't have entered that IF statement!
MagicPot.h:
#define MAGIC_POT_MAX_RAW_VALUE_10B     1023
#define MAGIC_POT_MAX_RAW_VALUE_12B     4095
#define MAX_RAW_VALUE_DEFAULT           (MAGIC_POT_MAX_RAW_VALUE_10B)

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

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

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

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

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

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

Arduino code:
MagicPot analogPots[] =
{
    MagicPot(A0),
}

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

}

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

Type
Error
Target
Value

Switch
NONE
54
516

Switch
NONE
54
515

Switch
NONE
54
514

Switch
NONE
54
513

Expected Output:

Type
Error
Target
Value

Switch
NONE
54
516

Switch
NONE
54
496

Switch
NONE
54
456

Switch
NONE
54
436

you subtract two unsigned types so the result is stored in an unsigned temporary too. try abs((int16_t) value - this->value)

@Juraj: It should be either abs((int16_t) (value - this->value)) or abs((int16_t) value - (int16_t) this->value). Or, better yet, make everything signed. Otherwise, if only one term of the subtraction is signed, the unsigned type wins the “usual arithmetic conversions” game.

@EdgarBonet  Thank you, the weird behaviour was caused by uint16. I tested running the code (with uint) in VisualStudio and there it worked. Do you know why it worked in VS/Win11 but not in Arduino?  Is the c++ version different? Compiler?  And why didn't the compiler warn me? Ps, I am a complete beginner in c++

Consider this subtraction:
value - this->value

Like in any arithmetic operation, the operands undergo integral
promotion, then usual arithmetic conversions.
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 sometimes).


text:
Arduino | external power supply and USB at the same time
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?

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
What happens if I power the Arduino with both the USB and external power voltage simultaneously?

In previous work coworkers solved this by adding Schottky diode to the cable usb cable. But it's also possible to change 3V3 reg to 1.8 and connect VIN with 5V (It's turning off the mosfet if VIN is 2 times 3V3)

get a short USB type A extender and cut the 5 V wire inside the extender cable

@jsotola
Yes, that was exactly my idea. Actually is very simple in my situation: My RPI is connected with a cable soldered to the usb plug of the Arduino (just because of space problems) -> so I just have to disconnect the 5V pin
But I'm more interested in an "professional" solution also I'm very curious why the this circuit with the FDN340P is not working as I thought!

-KIIV A schottky diode sounds actually nice, but there will be a voltage drop (even when its much less than a normal diode). Probably about 0.2-0.3V which result in a power loss of 90mW @300mA current consumption.

@stevo the question about the circuit is not about arduino ... it belongs at https://electronics.stackexchange.com/questions ... anyway, look closely at the MOSFET symbol ... MOSFETs contain a body diode

@jsotola
ah ok thanks. I did not really realize this body diode inside the MOSFET. now it makes sense.
Do you have any idea, why Arduino uses this type of circuit: Where current can flow to the usb device?

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.

Yes correct, I'm asking exactly this: Why is this circuit powering ("back driving") the USB device.
Well I think @jsotola answered already my question: There is a small body diode within this p-channel mosfet which allows current to flow into the USBVCC direction.
Yes, I'm disconnecting the 5V pin, that was also my workaround idea. (Actually is very simple in my situation: My RPI is connected with a cable soldered to the usb plug of the Arduino.)


text:
How to use ESP_LOGx?
I can't get the logging to work on the ESP32.
Here is my example:
#define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE
#include <esp_log.h>

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

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

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

Without any experience but after rushing through the documentation: Don't you need to call esp_log_level_set()?

You can set the log level from the Arduino IDE via Tools -> Core Debug Level. By default it is set to NONE.

I just had to add my thanks to hcheung! Changing the #defines and using esp_log_level_set() made no apparent difference. Setting Core Level Debug made all the difference, seeming to override the #defines mentioned above. -- John B

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


text:
How to return a value from a non integer input between 0-5 from an output range of 0-320 in map() method
I am experimenting using the map() method in an ArduinoIDE sketch in an attempt to obtain a pixel position for a horizontal meter in the range 0-320 from an input value in the range 0-5.  However, when I do this I see in the method that the input must be 'long' type.  Here's my example code:
  float voltage = 2.5;
  float meterPosition = map(voltage, 0, 5, 0, 320);
  tft.fillRect(0, 0, meterPosition, 10, TFT_GREEN);
  tft.setCursor(10, 70);
  tft.setTextSize(3);
  tft.println(voltage);
  tft.println(meterPosition);

But when I run this, despite the input value being 50% of the input range, I expected the meterPosition value to be 160, but it is 128, due I think because the values for this method must be of type 'long' and so the 'float' value is rounded and becomes a 'long' type (I think that's what is happening!!).
I am confused as to the function of the map() method if you are unable to map any range to any other range without using decimals as the input.  I am obviously missing something here, so what do I need to change in my map() method code for it to work in my example please, if I am unable to use floats?
Thanks.
John

What about just saying float meterPosition = voltage * 64.0 ; ?

As you already noticed, the map() function is meant to work with the
long data type. Here is its implementation:
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:
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:
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.

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.


text:
Arduino uno - 4digit 7seg display via 74HC595 keeps blinking
I am trying to get my 4 digit display (SH5461AS) count from 0 to 9 based on millis() function.
The problem is that it keeps blinking. Even if I display just one number, it shows then it goes black then it shows again, instead of staying on.. Also the upper segment (A) is somewhat delayed. Sometimes it shows, sometimes it does not. I am really not sure what is going on. It is best illustrated in the video: https://youtube.com/shorts/gmbNnvEYq2I
I have arduino UNO R3 hooked up to the 74HC595 8-bit register and from there to the corresponding 'data' pins on the display.
It is a common cathode type so I have all of those connected via resistor to the ground.

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%10);
    // Serial.println(number);
    shiftOut(SERIALPIN, CLOCK, LSBFIRST, numbers[0]); //for demonstration purposes display 0
    digitalWrite(LATCH, HIGH);
}

Any ideas what's wrong?

what happens if you exchange the two digitalWrite() program lines?

Hard to tell but it looks like the reset pin is floating. Make sure it is tied high (or controlled by your MCU).

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


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

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.

I tested pin 3v3 and pin 5v5, but there is no continuity between them. they seems not shorted together

I removed the regulator and the 3v3 pin it's around 1,5-2v

A Uno with no shields and no connections to offboard components should have nothing connected to the output 3v3 regulator.  See updated answer - though I wrote that before seeing your comment and 1.5v won't be enough to light most LEDs. I suspect your voltmeter is now seeing a meaningless floating value.

I agree about testing it with a small load since sometimes a regulator can actually show a higer voltage(typically input of the regulator(so around 5v in this case)) when no load it attached to it. essentially the voltage won't drop, and so the small spikes keep it high.

also try testing it with the arduino uno's analog ports, so get 2 resistors of the same value(for example both 1k resistors, 1 in 3.3v, 1 in gnd, and the middle in a analog port. if you read a value of around 500(half of analog range then you get a reading which keeps fluctuating, or is close to 0 then it is broken most likely, if you get a value of around 350(actually 341)(340(+-30) of 1024 range) then it should still work.

Sorry, how I have to connect resistor? I didn't understood, one resistor 1k between 3v3 and GND and one around 500ohm between GND and A0?

With a LED Red and a 330ohm resistor connected to 3.3V pin, I have 2.35V


text:
how to "skip" one parameter of a method with a default value letting it use it's default value, but change parameters after it
lets say we have a function like this(fictional):
function1(int Z, int X, bool Y=true, int Count=10, int ID=1,bool TeaTime=false);

And I want to run this function, but I want to change all parameters, except for "Count", and I want that to keep using it's default value.
Disclaimer
in this fictional case and in the real case where I faced it I found the default value in the header file and I manually coded it in. but I do not want that, at least not to rely on it, for example if the default value changes in the library then in my code it would still be forced to use that old value. also for ease of use and reducing the chance at problems/mistakes.
What I tried:
I already tried NULL and DEFAULT, both of them actually let my code work perfectly fine, but I made a test function which had such default values and printed the variables to the serial output and I found that using NULL actually overwrites it to 0 and DEFAULT overwrites it to 1.
I also tried some things like keeping one empty and such but those would give compile faults.
in short:
is there a way to let one parameter somewhere in the middle of the parameters of a function use it's default value while still manually setting the later ones?

No, you have to define everything until the last non default value you are passing. Everything after gets default values. You can make overloaded functions or you can pass the structure..

your question belongs at https://stackoverflow.com/questions ... it is a general programming question

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

Ah, I see what you mean, that would indeed work well.
took a while to look how it works since I didn't code that much lately and then indexes tend to blend between languages in memory.
but this seems very usefull and fun for making more dynamic things.
however in my case the problem faced mostly was that in some normal libraries they had noting like this(just checked if there was), so instead of making better functions, I originally was looking for using existing ones better.

still I am happy, since I came to learn/get inspire with something new, and got that now, by learning something nice and interesting(I think I even sought for something like this some years ago)

Added other way without chaining (if you have those setters without returning reference to itself eg like: void noY() { Y=false; })


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

There are reasons why technology such as rS232, RS485 or 4-20 mA DC loop exist, not just for providing isolation, but for ability to send data over twist pair for distance, with noise immunity and without signal degradation.

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.

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.

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

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.


text:
Incorrect data received on serial communication
I have two Arduino UNO connected with two wires, and ground, that exchange informations through serial data.
The communication is working with INT, but I am having troubles to receive correct characters. Instead of characters I'm only receiving numbers.
I tried every possible combination of Serial.write() or Serial.println(), with HEX and ascii, but it wouldn't work.
I do not know what I am doing wrong, if anyone could help me, I will appreciate.
Transmitter :
#include <SoftwareSerial.h>
#define TX 2
#define RX 3
#define ask 3
#define ER_LED 12

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

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

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

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

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

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

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

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

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

Serial monitor on whatev b/s:
21:19:36.408 -> 253
21:19:36.408 -> 255
21:19:40.421 -> 253
21:19:40.421 -> 255
21:19:44.495 -> 253
21:19:44.495 -> 255

Monitor with SySerial on 57600 b/s:
21:23:29.317 -> 241
21:23:33.308 -> 241
21:23:37.338 -> 241
21:23:41.328 -> 241

Monitor with SySerial on 300 b/s:
21:27:03.444 -> 255
21:27:07.731 -> 255
21:27:12.095 -> 255
21:27:16.335 -> 255
21:27:20.635 -> 255

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

I get different numbers, instead of characters

please  open the content of the serial monitor window and paste it into your post ... format as code ... please no pictures

Yes, but they do not appear as characters

What numbers do you get at 9600 b/s?

Updated code with monitor output

Pins 0 and 1 on the Uno are for the HW serial. Perhaps if you used pins 3 and 4 for the SW serial, it may work as intended.

Changed it, doesn't work. I used to have pins 2 and 3

Are you swapping the wires? ie. RX on one Uno to TX on the other. Try using a lower baud rate for the software serial, 57600 is probably pushing it.

Hi, thanks for your reply. Swapping the wires gives nothing on the monitor, so I think that the wires are in the right positions. I tried using both 300 b/s, and 9600 b/s for syserial, but it only changes a few numbers (52 on 300 b/s, gives 53 on 9600 b/s). The numbers seems to change when I use different baud rates

Don't you have an oscilloscope or logic analyzer at hand to measure instead of guessing?

@the busybee I do not have any oscilloscopes, or logic analyzers. I would have tried with those if I could.

Well, then, double-check each SW/HW component and do baby-steps: for example, check by local loop-back that you have the right pins and software, transmit single bytes of clear patterns (0x01 to 0x80) with enough interval, and so on. It is always quite hard to do development without appropriate tools.

What do you mean each ""SW/HW"" component ? At the moment I checked pins correspondence, I tried using different pins, and tried standard codes I could find online, but no luck so far...

Correct, the pins you use, the functions you call, the parameters of these functions. Did you try the suggestions? Please add new information to your question by [edit]ing it.

I would try using the hardware serial ports instead. And yes: the receiver can use the hardware port both for receiving from the other Arduino and for sending to the serial monitor.

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.

Thanks for answering, the setup you gave seems to be working, I will try to understand what was wrong in my previous code...


text:
Incorrect IP address when using Ethernet library with Arduino Uno and WizNet 5500 ethernet module
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.
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, 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 (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());
}

Is your network using DHCP? Perhaps the network is trying to assign the IP address "it wants" to your device. Is there a test sketch with the W5500 library that uses DHCP to connect to the network? Maybe this sketch could help to narrow down the issue... https://github.com/RoboCore/Ethernet_W5500/blob/master/examples/DhcpAddressPrinter/DhcpAddressPrinter.ino

try the WebClient example of the Ethernet library version 2.0.0+. it has enhanced diagnostics (don't comment it out)

@VE7JRO Yes, my network is using DHCP, but if the address was a DHCP address, it would be in the range 192.168.123.x . I'll give the sketch you mentioned a try to find out what IP I get when using DHCP, I'm curious to find out if DHCP does work.

@Juraj Thanks for the pointer, I'll give it a go and update accordingly. And no, I won't comment out the diagnostics ;)

@VE7JRO Well, I downloaded the Ethernet_W5500 library from your link, replaced all files under "Ethernet" with those files and tried the WebServer example client again after verifying in the source code that the W5500 was active, but unfortunately I still get the wrong IP address (192.80.239.132).

@Juraj I've checked and (prior to testing VE7JRO's answer) I had the 2.0.2 version of the Ethernet library. I loaded the WebClient example, but as it was, I never got a DHCP address (I changed the MAC address in the code to one which is allowed on my network). I gave up on DHCP and set a static IP (same as above), but just like the code VE7JRO pointed to, I ended up with the same erroneous IP address...

check the wiring

@Juraj The wiring is correct as far as I can tell. Vcc to 3.3V (from a separate supply), gnd combined with the Arduino, SCK to pin 13 of the Arduino, Mi (miso) to 12, Mo (mosi) to 11, SC (ss) to 10 (as stated in the code, the only variable pin). Int pin is not connected, Reset pin is not connected (these are never mentioned in the articles I found).

should the module be powered with 3.3 V? some Ethernet modules have a converter from 5 V to 3.3 V for the W5500, because some Arduinos can't provide enough current on the 3.3 V pin

@Juraj Yes, this particular module should be powered by 3.3V. Also, I'm not powering the module from the Arduino but from a separate (lab) power supply, and yes, both grounds (Arduino and lab power supply) are connected.

if begin hangs it is a problem with communication with the module

@Juraj Begin doesn't hang, the entire setup gets executed, and the final Serial.println prints an incorrect IP address.

I meant begin using DHCP. begin with static IP never fails but if it didn't work, reading the IP address back gives you a random value.

@Juraj I'm afraid I'm a bit confused now, I'm not using DHCP. Or are you telling me to begin by using DHCP as a test? Because I already tested using DHCP and I never get an IP address, whether or not the MAC address I assign is explicitly allowed in my network.

I am still at the WebClient example of the Ethernet library as a basic troubleshooting tool

@Juraj That's the sketch I was trying on March 29, but I never got a DHCP address. That's why I switched to using a static IP address. Any idea on how to figure out why the DHCP begin hangs?

W5500 works fine with IP ranges upto xxx.127.xxx.xxx But with the second octect 128 or higher, the IP becomes some random numbers ie gets corrupt . Unable to resolve the problem. For other IP ranges, there no issue

I had the same issue: a strange IP was shown. Also the LEDs of the Lan connection had a rather strange blinking: green went on for a second then off and then orange did the same. The solution for me: an external power supply with 7 V at the Vin. Apparently the Lan shield is drawing too much power for the usb power supply...
Also it is working with the standard ethernet library

something is wrong with your hardware if USB doesn't provide enough power for Uno with Ethernet shield


text:
IoT Explorer Kit registration process
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.

please ask the place where you register the kits ... make up names, something like kit001 ... as it stands, the question is about the usage of an internet service, not about Arduino


text:
VL6180X returning to its default i2c address after shutdown
According to this thread 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 ?

The data sheet and the thread agree with what you are seeing...the device will always power up at the default address, but you can change the address while it is powered up.  The Pololu link is explicit about this: "It can be changed to any other value by writing one of the device configuration registers, but the new address only applies until the sensor is reset or powered off." I don't see anything in the thread that says that you can change the default value when first powered up.


text:
Read status of digital pin 11, when it is set as OUTPUT
I have set pin 11 as output.
pinMode(11, OUTPUT);
However, I want to be able to read its state (if it is HIGH or LOW),  however since it is set as OUTPUT, I am not able to use digitalRead().
I found this online though:
Serial.println(bitRead(PORTD,3));
//Reads bit 3 of register PORTD which contains the current state (high/low) of pin 3

If I want to read the state of pin 11 then this:
Serial.println(bitRead(PORTD,11)); will be enough? Or do I have to change the PORT as well?

Why not try it?

please don't ask what will happen if I do this? ... do it first, then ask, if you do not understand something

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