text:
Arduino uno RF transmitter and receiver, MYSQL
i tried to connect my arduino uno and ethernet shield with Mysql and everything works fine. Then I tried to connect the RF transmitter and receiver. I use a similar code, but i have problem with connection with database.
For the project i use:2xArduino Uno,Rf transmitter and receiver ,DHT11 and BMP080,and Ethernet shield. This is my Code:
transmitter:
#include <VirtualWire.h>
  #include "LowPower.h"
  #include "DHT.h"
  #include "Adafruit_BMP085.h"
  #include "Wire.h"

  #define DHTPIN 8     // what pin we're connected to
  #define DHTTYPE DHT11   // DHT 11
  DHT dht(DHTPIN, DHTTYPE);
  Adafruit_BMP085 bmp;
  int ledPin = 13;
  char Msg[30];// The string that we are going to send trought rf transmitter
  void setup()
  {
    Serial.begin(115200);
    dht.begin();  // initialing the DHT sensor
    bmp.begin();
    pinMode(ledPin,OUTPUT);
    // VirtualWire setup
    vw_setup(2000); // Bits per sec
    vw_set_tx_pin(12);// Set the Tx pin. Default is 12
  }
  void loop()
  {
     Serial.print("Pressure = ");
     Serial.println(bmp.readPressure());
     Serial.print("Temperature = ");
     Serial.println(bmp.readTemperature());
     Serial.print("Humidity = ");
     Serial.println(dht.readHumidity());

    // Read and store Sensor Data
    int humidity = dht.readHumidity();
    int temp = bmp.readTemperature();
    unsigned long pressure = bmp.readPressure()/100;
     Serial.print("Pressure = ");
     Serial.println(pressure );

    sprintf(Msg, "%d,%d,%d", humidity,temp ,pressure);
   // Turn on a light to show transmitting
    digitalWrite(ledPin, HIGH);
   //LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
    delay(100);
    vw_send((uint8_t *)Msg, strlen(Msg));
    vw_wait_tx(); // Wait until the whole message is gone
   // Turn off a light after transmission
    digitalWrite(ledPin, LOW);
    // put 5 mins sleep mode
    // As lowpower library support maximam 8s ,we use for loop to take longer (5mins) sleep
    // 5x60=300
    //300/4=75
    for(int i=0;i<75;i++)
    {
    LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF);    // Instead of delay(4000);
   //delay(4000);
    }
  }

reciever:
#include <SPI.h>
#include <Ethernet.h>
#include "Wire.h"
#include <VirtualWire.h> // use Virtual library for decode signal from Rx module

 EthernetClient client;
  byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
  char server[] = "192.168.0.101";

  int humidity=0;
  int temp=0;
  unsigned long pressure=0;
  char MsgReceived[21];

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

    // VirtualWire
    // Bits per sec
    vw_setup(2000);
    // set pin for connect receiver module
    vw_set_rx_pin(5);
    // Start the receiver PLL running
    vw_rx_start();

  }

  void loop()
  {
    uint8_t buf[VW_MAX_MESSAGE_LEN];
    uint8_t buflen = VW_MAX_MESSAGE_LEN;
    //Taking the data from the control base
    if (vw_get_message(buf, &buflen))
    {

      delay(100);
      int i;
      // Message with a good checksum received, dump it.
      for (i = 0; i < buflen; i++)
      {
        // Fill Msg Char array with corresponding
        // chars from buffer.
        MsgReceived[i] = char(buf[i]);
        Serial.print(MsgReceived[i]);
      }
  connection();

    sscanf(MsgReceived, "%d,%d,%d",&humidity, &temp, &pressure); // Converts a string to an array

    memset( MsgReceived, 0, sizeof(MsgReceived));// This line is for reset the StringReceived

    Serial.print("Temperature = ");
    Serial.print(temp);
    Serial.println(" *C");

    Serial.print("Pressure = ");
    Serial.print(pressure);
    Serial.println(" hPa");

    Serial.print("humidity = ");
    Serial.print(humidity);
    Serial.println(" %");

    delay(10000);
    }
}

  void connection()
  {
    if(client.connect(server, 80)) {

      client.print( "GET /diplomna/Arduino/add_data.php?");
      client.print("temperature=");
      client.print( temp );
      client.print("&&");
      client.print("humidity=");
      client.print( humidity );
      client.print("&&");
      client.print("pressure=");
      client.println( pressure );
      client.println( "HTTP/1.1");
      client.println( "Connection: close" );
      client.stop();
      Serial.println("CONNECTED");
    }
    else {
      // you didn’t get a connection to the server:
      Serial.println("-> connection failed");
    }

  }

Output receiver:
70,23,100-> connection failed
Temperature = 23 *C
Pressure = 1001 hPa
Pahumidity = 70 %

without : #include <VirtualWire.h> and rf function I connect with the database and make a record :(

Do you really want a 10 second delay in there?

it is not necessary, but without it does not work too :)

I found where is the problem. It is function of virtualwire.h - rx_setup. It use a timer and there is  conflict with any of the libraries. Can anybody tell me how то change the timer, that is used by the function.


text:
Rf receiver, change timer
I need some help. I use function rx_setup()  оf library VirtualWire.h which is used to transmit information wirelessly. The function use timer аnd there is  conflict with any of the other libraries. Does anyone know how I can change the timer, which uses function?
This is the function:
void vw_setup(uint16_t speed)
{
    uint16_t nticks; // number of prescaled ticks needed
    uint8_t prescaler; // Bit values for CS0[2:0]

#ifdef __AVR_ATtiny85__
    // figure out prescaler value and counter match value
    prescaler = _timer_calc(speed, (uint8_t)-1, &nticks);
    if (!prescaler)
    {
        return; // fault
    }

    TCCR0A = 0;
    TCCR0A = _BV(WGM01); // Turn on CTC mode / Output Compare pins disconnected

    // convert prescaler index to TCCRnB prescaler bits CS00, CS01, CS02
    TCCR0B = 0;
    TCCR0B = prescaler; // set CS00, CS01, CS02 (other bits not needed)

    // Number of ticks to count before firing interrupt
    OCR0A = uint8_t(nticks);

    // Set mask to fire interrupt when OCF0A bit is set in TIFR0
    TIMSK |= _BV(OCIE0A);

#elif defined(__arm__) && defined(CORE_TEENSY)
    // on Teensy 3.0 (32 bit ARM), use an interval timer
    IntervalTimer *t = new IntervalTimer();
    t->begin(TIMER1_COMPA_vect, 125000.0 / (float)(speed));

#else // ARDUINO
    // This is the path for most Arduinos
    // figure out prescaler value and counter match value
    prescaler = _timer_calc(speed, (uint16_t)-1, &nticks);
    if (!prescaler)
    {
        return; // fault
    }

    TCCR1A = 0; // Output Compare pins disconnected
    TCCR1B = _BV(WGM12); // Turn on CTC mode

    // convert prescaler index to TCCRnB prescaler bits CS10, CS11, CS12
    TCCR1B |= prescaler;

    // Caution: special procedures for setting 16 bit regs
    // is handled by the compiler
    OCR1A = nticks;
    // Enable interrupt
#ifdef TIMSK1
    // atmega168
    TIMSK1 |= _BV(OCIE1A);
#else
    // others
    TIMSK |= _BV(OCIE1A);
#endif // TIMSK1

#endif // __AVR_ATtiny85__

    // Set up digital IO pins
    pinMode(vw_tx_pin, OUTPUT);
    pinMode(vw_rx_pin, INPUT);
    pinMode(vw_ptt_pin, OUTPUT);
    digitalWrite(vw_ptt_pin, vw_ptt_inverted);
}

#endif // ARDUINO

// Start the transmitter, call when the tx buffer is ready to go and vw_tx_len is
// set to the total number of symbols to send

source: Stack Exchange

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

sort: votes


text:
How to power 2 MG996R towerpro servo
I am a beginner and tried powering MG996R Tower Pro (180 deg Metal Gear) Servo from Arduino UNO and ended up hibernating the host PC.
I want to power 2 such motors (in parallel configuration) for lets say 10 minutes a day at a time. What is the best solution to power it. I have learned the hard way that Arduino UNO's 5 V pin is not enough and it may have damaged my board too.
Should I use a 6 V charging adapter and cut off its end connect it to the motor? Should I use a capacitor? What am I supposed to do to power 2 such motors simultaneously? Also if possible provide a schematic of how to connect my motors (series or parallel) with the power supply. Datasheet : https://www.towerpro.com.tw/product/mg996r/
Side-question: How to check if my Arduino board is damaged after drawing too much current from servo because right now it works fine and is not heating and nothing seems charred.

These servos can draw a good deal of current when moving quickly or drawing high loads.
You can find that value under "Stall current" on the datasheet. That's the highest one of these motors will draw if stalled. In the case of these servos it's 1.4A -- For two servos that's almost 3A
A generic USB port can supply ~500mA (0.5A) of current. A USB 3 port might get you 3A though your Arduino isn't built to handle more than 1A trough the USB port.
For your case I'd suggest getting a good 5V power brick with about 3A or more. That way you can be sure that your servos won't kill the power brick if they ever stall. I suggest using 5V instead of 6V as that supply can also power the Arduino.
As for the wiring, the best option for flexibility and power is to attach the power supply to the 5V and GND of your Arduino as well as Red and Brown servo wire. That way the power brick can run both the arduino and servo together and you don't need a seperate supply for the Arduino.
You will need to figure out which of the power brick's leads are positive (5V) and negative (GND).

Side answer: If your Arduino board was damaged due to a high current load it would likely not run at all.

Could you please share a link of a suggested power supply which i should buy?

@AdityaJain We don't do product recommendations here. They are very volatile and region specific. But you can just go to the website of your favorite retail store and search for "5V 3A power supply". Every power supply, which is rated with 5V and 3A (or higher ampere) will fit, preferably one, that you can directly plug into a wall outlet.

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


text:
ESP32-S3 pericodically connect wifi
In my application it's necessary to send some data to a web server at regular intervals (~5min). The rest of the time the wifi should be dormant and only some sensor measurements have to be executed. Since the sensors are temperature dependent, the wifi can't just be left on, because the board and enclosure will heat up due to the high heat of the esp32. Also, the corresponding sensor libraries (MOX/VOC) must be continuously fed with sensor values. Therefore sleep modes are not an option. The general idea is to raise CPU frequency and connect wifi only when needed, and disconnect and lower the frequency the rest of the time just to perform sensor tasks.
I found code on how to re-initialize the wifi library after usage of light sleep and tried to use it just in a loop.
Here is the code snipped. The setup() contains only initialization of the serial line
void loop() {
  int state = 0;
  WiFi.disconnect(false);
  WiFi.mode(WIFI_STA);
  delay (200);
  Serial.print("Begin: ");
  Serial.println(WiFi.begin(ssid, pass));

  uint32_t last = millis();

  while(state != WL_CONNECTED && ((millis()-last)<20000)){
    state = WiFi.status();
    Serial.print(state);
    delay (100);
  }
  Serial.println();
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
  delay(10000); // For testing, in real-world it will be 5min

}
First after boot, the state will change from 6 (Disconnected) to 0 (IDLE) and 3 (Connected) within 2 seconds and a valid IP is printed out
The second and all following times, the state will remain at 6 (Disconnected) for multiple seconds, and then switch to 1 (NO SSID AVAILABLE) where it remains until 20s timeout.
If the esp is reset, the connection will work again. Also when i implement deep sleep, it will always work
What could be the issue?

try putting WiFi.mode(WIFI_OFF) before WiFi.disconnect(true)

i tried but no change

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


text:
How execution time of code instructions influences signal between Arduino and DHT11?
I am exemining code for DHT11 from CircuitGeeks, variant without using lib. The problem is a mismatch between DHT11/DHT22 protocol and signals, which are read from sensor in scetch. Despite this, sketch is working and I would like to find out how.
#define DHT11_PIN   12

unsigned long TON_TIME = 0;
unsigned long TOFF_TIME = 0;

unsigned char data_byte[5];
unsigned int data_packet[40];
unsigned char bit_data = 0;
unsigned char checksum_byte = 0;
int bit_counter = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("DHT11 Humidity & Temperature Sensor\n");
  delay(1000);//Wait before accessing Sensor
}

void loop() {
  pinMode(DHT11_PIN, OUTPUT);
  digitalWrite(DHT11_PIN, LOW);
  delay(18);
  digitalWrite(DHT11_PIN, HIGH);
  pinMode(DHT11_PIN, INPUT_PULLUP);

  TOFF_TIME = pulseIn(DHT11_PIN, LOW);
  if (TOFF_TIME <= 84 && TOFF_TIME >= 76) {
    while (1) {
      TON_TIME = pulseIn(DHT11_PIN, HIGH);
      if (TON_TIME <= 28 && TON_TIME >= 20) {
        bit_data = 0;
      }
      else if (TON_TIME <= 74 && TON_TIME >= 65) {
        bit_data = 1;
      }
      else if (bit_counter == 40) {
        break;
      }
      data_byte[bit_counter / 8] |= bit_data << (7 - (bit_counter % 8));
      data_packet[bit_counter] = bit_data;
      bit_counter++;
    }
  }
  checksum_byte = data_byte[0] + data_byte[1] + data_byte[2] + data_byte[3];

  if (checksum_byte == data_byte[4] && checksum_byte != 0) {
    Serial.println("Humidity: ");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c]);
    }
    Serial.print("\t");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c + 8]);
    }
    Serial.print("\t");
    Serial.print(data_byte[0]);
    Serial.print("%");
    Serial.println(" ");

    Serial.println("Temperature: ");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c + 16]);
    }
    Serial.print("\t");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c + 24]);
    }
    Serial.print("\t");
    Serial.print(data_byte[2]);
    Serial.print("C");
    Serial.println(" ");

    Serial.println("Checksum Byte: ");
    for (int c = 0; c <= 7; c++) {
      Serial.print(data_packet[c + 32]);
    }
    Serial.println(" ");
    Serial.print("CHECKSUM_OK");
    Serial.println("");
    Serial.println("");
  }

  bit_counter = 0;
  data_byte[0] = data_byte[1] = data_byte[2] = data_byte[3] = data_byte[4] = 0;
  delay(1000);
}

Looking into the code there is 18 ms of LOW level for initialization. Then about 40 us of HIGH level, it can be considered as time between digitalWrite(DHT11_PIN, HIGH); and TOFF_TIME = pulseIn(DHT11_PIN, LOW); instructions. But then after 80 us of LOW level TOFF_TIME = pulseIn(DHT11_PIN, LOW); it should be 80 us HIGH level. Instead of this, the code is being continued by conditions for checking pulses length, which are responsable for data bits. If pulse length is 26-28 us it's 0, if 70 us - it's 1. I understand that with TON_TIME = pulseIn(DHT11_PIN, HIGH); instruction we will find length of HIGH pulses of data bits only.

Why 80 us HIGH level is passed, however this doesn't impact on interaction with sensor? Does it pass in time of executing instructions from  if (TOFF_TIME <= 84 && TOFF_TIME >= 76) to TON_TIME = pulseIn(DHT11_PIN, HIGH); ?

At the end of the 80 µs LOW from the HDT11, pulseIn(DHT11_PIN, LOW)
returns. At this point in time, the data line is HIGH, somewhere near
the beginning of the positive 80 µs pulse. Now, the code executes the
first pulseIn(DHT11_PIN, HIGH).
You cannot measure the length of a positive pulse if you missed the
rising edge. Thus, as pulseIn() finds the line HIGH, it will first
wait until it transition to LOW, then wait until in transitions back to
HIGH, and only then starting timing.
See for example the implementation of the counting loop in the AVR
core, or rather the C code that served to generate the assembly
implementation. It has three waiting loops:

wait for any previous pulse to end
wait for the pulse to start
wait for the pulse to stop


text:
Install Bluetooth inside a home theater, How?
I have a 5.1 home theater(old one), I would like to transform it into a audio streaming system. I have a Arduino UNO and HC-05 Bluetooth Module, and I don't know how to install it in my home theater(if it does). solution please...

Can you be more specific please? What are you wanting the Arduino to do?

I don't know, just mentioned that I have..

You want to use the arduino to override the buttons of your home theather?
Or do you want your arduino to send IR commands (same as a remote) to your home theather?

I just want to make my home theater into an A2DP bluetooth audio reciever..thats all..please give me solution regarding that..

@Harish Were you able to do it? Could you please share the details?

I don't think this will be feasible. There are two main issues:
1. I don't think there's a sensible way to get the HC-05 module to work with A2DP. It's great for a simple serial connection, but Bluetooth-enabled media devices generally won't connect to it if they're looking for audio streaming systems (as far as I know).
2. The Uno probably isn't powerful enough. Even if you could get the audio data into it, I don't think it will be able to decode the information to an analog audio signal in real-time.
Something like a Raspberry Pi with a suitable Bluetooth module might be a better choice for this.

So could you suggest me any Bluetooth module that works like A2DP, so that I can install in my home theater.

I would suggest something like this, if you want your stereo to be able to receive music over bluetooth:
http://www.tinydeal.com/en/Bluetooth-Music-Receiver-A2DP-Wireless-HiFi-3-5mm-Stereo-Audio-Dongle-Adapter-p-70931.html?currency=EUR&ship_to=NL&gclid=Cj0KEQjwgI6pBRDak6aRovWNqLsBEiQA8zZSLttsqa4WBkkKJSjTnlIndXji0IkOhH4QXCRPJiaEqyEaAly68P8HAQ
Cheaper as an arduino, way easier and actually possible.

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


text:
how to turn yun to ad hoc mode?
Can I turn Yun to ad hoc mode?
How to?

As the image above I can see the Ad-Hoc model in that drop down list. But only WEP for its security.


text:
yun manage bridge manually
in "Disabling the Bridge Script" of http://cylonjs.com/documentation/platforms/yun/
I did:

Edit the /etc/inittab file to comment out the ttyATH0 line (put a # before it)

::sysinit:/etc/init.d/rcS S boot
::shutdown:/etc/init.d/rcS K shutdown
#ttyATH0::askfirst:/bin/ash --login

But I want to turn it on or off manually. Then I can program through WiFi if I want.
How to do that?


text:
GPS module GY-GPS6MV2 only returns numbers
I have a GY-GPS6MV2 connected to a nano. (Also tried UNO same result). RX on GPS goes to TX of Nano PIN 3 and TX on GPS to PIN 4 on Nano.
When I run the code below all I get is a set of numbers. They do not appear to be hex numbers.
367180827767444486444444444444444444447842535113103671808684714444444444444444447842514813103671807171654444444444444844484844
The code I am using is
#include <SoftwareSerial.h>

String data = "";

// Define the Arduino pins for software serial communication
const int RXPin = 4;
const int TXPin = 3;

// Set the default baud rate for the NEO-6M GPS module
const int GPSBaud = 9600;

// Create a software serial object for GPS communication
SoftwareSerial gpsSerial(RXPin, TXPin);

void setup() {
  // Start the hardware serial port for communication with the computer
  Serial.begin(9600);

  // Start the software serial port for GPS communication
  gpsSerial.begin(GPSBaud);
}

void loop() {
  data = "";
  // Check if there is data available from the GPS module
  while (gpsSerial.available()>0) {
    // Read the incoming data and send it to the computer
      data += gpsSerial.read();
  }

    // Read the incoming data and send it to the computer
  Serial.println(data);
  delay(30000);
}

I tried 2 different GPS modules and the result is the same. Seems that the GPS sends me data via the Arduino but not the correct data. I read about cold starts so I left the module running more than 30 hours but the result is the same. I know it may not see satellite and was expecting to see some NMEA from it even if gibberish NMEA.
What have I missed in making this work please?

use a separator when printing values. such as a ,

research ASCII values

Sorry, how does that help turn and ASCII string into NMEA?

it's not an ASCII string ... it is a set of numeric values ... display them as ASCII text, instead of numbers

3671808277674444... is the ASCII code for "$GPRMC,,..., so you are receiving data correctly but doing the wrong data cancatenation. When programming in C/C++, always need to aware what kind of data type you are dealing with. gpsSerial.read() return an int, so you need to cast it to a char before you can concatenate with a String with data += (char) gpsSerial.read();.

@hcheung - Thanks for the help that is exactly what I needed to know. C/C++ is all new to me so I did not know I had to cast the values. Now it is giving characters just got to get the GPS module to see the satellites. I will run it outside today.

When you write gpsSerial.read(), you are calling the method
int SoftwareSerial::read();

Notice it returns an int, not a char. Why, you may ask. The reason
is that a char can only hold 256 different values, whereas this
method can return 257 different values:

values from 0 through 255 represent actual bytes read from the port
the value −1 represents an error condition.

In your case, you don't have to worry about errors, as you are only
calling the method when you know for sure it has data to deliver (i.e.
when gpsSerial.available()>0).
When you write data += gpsSerial.read();, you are calling the method
String & String::operator += (int num);

which appends a number to a string. In the face of it, this seems
meaningless. What could it even mean to “append a number to a string”?
The Arduino library interprets it as meaning “write down the number in
decimal, using ASCII digits, and append that to the string”. Thus, if
you
data += 36;

this will append the string "36" to data.
Now, if you instead do
data += (char) 36,

this will add to data the character number 36, i.e. '$'. And this is
what you actually want. Thus:
data += (char) gpsSerial.read();


text:
WiFi credentials pulled from an SD card fail, but work hard-coded?
I'm trying to move my hard-coded wifi SSID/password credentials to an SD card so they can be more easily changed, but when passing the SSID to the WiFi.begin() function, I'm getting a status code 1 - "WL_NO_SSID_AVAIL" error.  I'm even double-checking to make sure there are no additional characters at the end of the SSID when I read it from the text file on the SD Card.  The values appear to be exactly right, but I'm still getting the error.  Can anyone see what I'm missing?  The code I'm trying is here:
#include <SPI.h>
#include <SD.h>
#include <WiFi.h>
#include <esp_now.h>
#include <vector>  // Include vector library

// Define the pin for the SD card reader
#define SD_CS_PIN 5

// Variables to store network credentials and MAC addresses
String ssid;
String password;
std::vector<uint8_t*> macAddresses;  // Dynamic array to store MAC addresses

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

  // Initialize SD card
  if (!SD.begin(SD_CS_PIN)) {
    Serial.println("Card failed, or not present");
    return;
  }
  Serial.println("Card initialized.");

  // Open the config file
  File configFile = SD.open("/network.txt");

  if (!configFile) {
    Serial.println("Failed to open config file");
    return;
  }

  // Read the file line by line and parse the values
  while (configFile.available()) {
    String line = configFile.readStringUntil('\n');

    if (line.startsWith("SSID=")) {
      ssid = line.substring(5);
    } else if (line.startsWith("PASS=")) {
      password = line.substring(5);
    }
  }

  configFile.close();
  delay(500); // Making sure the execution is complete before continuing

  // Debug: Print the SSID and Password to the Serial Monitor -- checking for trailing chars
  Serial.print("Connecting to SSID: '");
  Serial.print(ssid);
  Serial.println("'");

  Serial.print("Using Password: '");
  Serial.print(password);
  Serial.println("'");

  // Connect to Wi-Fi
  WiFi.disconnect(true); // Making sure no connections are currently established
  delay(1000);
  WiFi.begin(ssid.c_str(), password.c_str());

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print("Current WiFi Status Code: ");
    Serial.println(WiFi.status());
    Serial.println("Connecting to WiFi...");
  }

  Serial.println("Connected to WiFi");

void loop() {

}

I've tried making sure the I/O function with the SD Card was complete by adding a delay after the close() command, but that didn't help.  I also tried adding a WiFi.disconnect() before the WiFi.begin() with a delay just to make sure there weren't any other connections being made.  Finally, I'm verifying the SSID and PASS are correct in the serial monitor, and don't have any whitespace characters at the end that I wasn't seeing in the text file.  The values are correct as I see them, but I'm still getting the 1 error code, or "WL_NO_SSID_AVAIL" after each connection attempt.  When I hardcode the values into the code directly, the I'm connecting without issue.

try trim() on ssid and password. I am not sure if you would see a solo \r in Serial Monitor

That....worked.  I can't believe the debug line to print the string followed immediately by a single quote didn't catch that.  I thought for sure I'd at least see a space or something before the quote.  Thank you very much!

Dangers of using plain text file. Invisible characters can sneak in. Use JSON, for instance, to store settings.

Even though you're printing the SSID and password to the Serial Monitor, it's possible that hidden characters (such as a carriage return \r or extra whitespace) are being appended to the SSID or password when reading from the SD card. You can manually trim the hidden characters by using trim() function.

Thanks to Juraj, this is solved. The method I was using allowed for a non-printable character at the end to sneak in.  Adding 'ssid.trim();' after getting the SSID value, and adding 'password.trim();' after getting the password value fixed the issue.

Interesting. WiFi.begin(ssid.c_str(), password.c_str()); You [and @Juraj] are also assuming (possibly correctly in this case) that the begin method stores the character arrays and not just a pointer to them so that say subsequent calls, if necessary, of .begin() (without parameters) will work. Some of the ESP functions, for example configTime( , , char* NtpServerName ) require the user to provide static storage for the character array and this is not always obvious without drilling through the library. The character array provided by .c_str() doesn't last very long.

@6v6gt I am not assuming. I know


text:
How to run G code with SoftwareSerial?
I'm trying to build my own CNC machine. Since I need to control a large number of motors at the same time, I want to control it via an Arduino master and several slaves with CNC shields. Now I'm trying to set up one motor by sending G-code via SoftwareSerial on the slave. I'm not getting any response from mySerial.
Can you please tell me if I need to integrate my code into the Grbl library?
Here's an example of a slave code:
#include <SoftwareSerial.h>

#define SLAVE_ADDR 9
#define ANSWERESIZE 5

SoftwareSerial mySerial(10, 11); // RX, TX для GRBL

String answer = "Hello";
String command = "";

void setup() {
  // Инициализация Wire для I2C
  Wire.begin(SLAVE_ADDR);
  Wire.onRequest(requestEvent);  // Функция для отправки данных
  Wire.onReceive(receiveEvent);  // Функция для получения данных

  mySerial.begin(115200);  // GRBL работает на 115200 бод по умолчанию
  Serial.begin(9600);  // Для отладки

  Serial.println("Initializing GRBL...");
  delay(1000);  // Ждем загрузки GRBL

  // Включаем шаговые двигатели (посылаем команду на активацию)
  mySerial.println("$X");  // Разблокировка GRBL
}

void loop() {
  // Проверяем, есть ли команда для выполнения
  if (command.length() > 0) {
    Serial.println("command: " + command);  // Выводим команду для отладки
    executeCommand(command);  // Передаем команду GRBL для выполнения
    command = "";  // Очищаем команду после выполнения
  }
}

// Функция для обработки полученных данных через I²C
void receiveEvent(int howMany) {
  command = "";  // Очищаем строку перед началом чтения
  while (Wire.available()) {
    char c = Wire.read();  // Читаем байт и конвертируем в символ
    command += c;  // Добавляем символ к строке команды
  }

  Serial.println("Received I²C Data!");  // Уведомляем о получении данных
}

// Функция отправки ответа обратно на мастер
void requestEvent() {
  byte response[ANSWERESIZE];

  for (byte i = 0; i < ANSWERESIZE; i++) {
    response[i] = (byte)answer.charAt(i);
  }

  Wire.write(response, sizeof(response));  // Отправляем ответ
  Serial.println("Sent response to master!");  // Уведомляем о отправке
}

// Функция для передачи команды GRBL
void executeCommand(String command) {
  // Отправляем команду G-кода через Serial (на GRBL)
  Serial.print("Sending to GRBL: ");
  Serial.println(command);

  // Отправляем команду на GRBL через SoftwareSerial
  mySerial.println(command);

  // Ждем выполнения команды
  delay(100);  // Настройте задержку в зависимости от сложности движения
}

17:52:18.951 -> Received I²C Data!

17:52:18.951 -> cSent response to master!

17:52:19.000 -> ommand: G91 G1 X1600 F1000

17:52:19.018 -> Sending to GRBL: G91 G1 X1600 F1000

receiveEvent and requestEvent works fine, but there are some problem in executeCommand or mb in SoftwareSerial settings.

Welcome to SE/Arduino! Please take the [tour] to learn how this site works, and read some of the pages of the [help]. Then come back and [edit] your question to clarify and extend. -- Are you aware that SoftwareSerial is sensitive to other interrupts and that it cannot work fullduplex? You might want to try an other library. -- Are you aware that serial transmission takes time on UART and I²C? Your receiving loop might miss later bytes/characters. -- Please translate your comments to English.

SoftwareSerial is disabling the interrupts for a long time and might interfere with Wire interrupts and hardware serial interrupts.
You can try using AltsoftSerial which adds less latency to other interrupts.
If still not working you might want to change to an Arduino with at least two hardware serial ports or find another way to debug your code and use hardware serial for sending G-codes.


text:
Translating analogWrite() into PWM duty cycle formula
We can use the function analogWrite(int x) for digital pins which support PWM because any microcontroller has a built in PWM generator.For given x and for Arduino Uno which is the formula to calculate the duty cycle of the generated PWM signal?Thanks

x/255 (Now padding up to 30 characters....)

On pins 5 and 6 (those controlled by Timer 0):

duty cycle = (x+1)/256,
except for x = 0, which gives a duty cycle of 0.

On the other PWM pins:

duty cycle = x/255

The difference comes from the fact that Timer 0, which provides the
timing for millis(), micros() and delay(), is configured in “fast
PWM” mode, while the other timers are in “phase correct PWM”

Duty Cycle= (x/255)×100%
x is the value passed to the analogWrite() function, ranging from 0 to 255.
Duty Cycle is expressed as a percentage, representing the fraction of time the signal is on compared to the total period of the PWM signal.

Not on all pins. Try analogWrite(5, 1) on an Uno and see what comes out.


text:
Arduino Uno/Nano + ML
I couldn't find any clear answers elsewhere, hence I'm asking here.
I have a TensorFlow/TensorFlow Lite model which I have already trained on some sensor data.
Now, how can I utilize this model on my Arduino Nano/Uno to perform some other functions like moving a motor?
Any help would be appreciated!
Thanks

The documentation of Tensorflow lite states:

The core runtime just fits in 16 KB on an Arm Cortex M3 and can run many basic models.

So the Tensorflow lite runtime itself needs 16kB of - I guess - RAM. That would be 8 times of what the Uno/Nano actually has. If they mean program memory, then it would fit, since Uno/Nano has 32kB of flash.
Though it would still not work:

TensorFlow Lite for Microcontrollers is written in C++ 17 and requires a 32-bit platform.

The Uno/Nano uses the Atmega328p, which is an 8-bit microcontroller.
So all in all: No, you cannot use Tensorflow lite on an Uno/Nano. You should look at the "Supported Platforms" section of the linked Tensorflow Lite documentation to choose a board, that fits your needs.

FYI: https://docs.arduino.cc/tutorials/nano-33-ble-sense/get-started-with-machine-learning/  (it's board with Nano "form factor" - 3.3V only + Cortex M4 with FPU)


text:
Control external device using Java Web Servlet -> Pi -> Arduino -> Device
I'm new to the world of Arduino & PI, so far it's been a fantastic experience but I'm now looking to build something a bit more practical.
My plan is for the PI to host a JSP Servlet website.  I'd like to go to a certain page of this site: 'powerCycleDevice' for example where it would pass a parameter in '?=on' or something similar.  This would then be picked up by the Arduino which in turn would then power said device.
It's also be nice to just use it as a monitoring station.  If I have several Arduinos hooked up (and I plan to - think Wallace & Gromit :)) then it'd be nice to view the statistics of each of the sensors.
My problem is not knowing if a: it's possible (I'm certain it is) and b: where to start.
If anyone can lend any advice, hints or tips on where to get started it would be fantastic.  A noob guide or tutorial would be great as I'd then use the info and expand upon it.
Thanks in advance.

You can use Ardulink. It's a java open source project of mine. It can control an Arduino boad. So you have just to write a servlet that call my library. That's it.
See this post to understand how install ardulink in a PI: http://www.ardulink.org/how-to-install-arduino-pc-link-on-raspberry-pi/
You can read a sample code that sends some messages to Arduino you can read this post:
http://www.ardulink.org/how-to-blink-a-led/
The most important statement is Link link = Link.getDefaultInstance();
Link is the Ardulink class you need to send (and receive) messages.

That's fantastic, thank you. I'll have a look as soon as I'm able to


text:
General Question about fast Serial Communication and Arduino
I'm looking for a fast (and safe, in terms of stability) way to send sensor data from an Arduino UnoR3 in real time to a Computer (in my case a MacBook Pro) with a sample rate of at least 1kHz.
I tried following:

Sending sensor values with the related timestamp (in microseconds):
I use 7 bytes for each sample [1 Header byte, 2 bytes for the sensor value (10/(16)bit-Int), and 4 bytes for a 32-bit unsigned long (time in microseconds)] and send them right away.
On the receiving end i mainly use Processing (Im relatively new to Processing though): Reading the bytes in, converting them in integers and safe them in a file or plot them.

For sampling rates of 1sample/10ms my code runs smooth and i even can plot the data in "real-time".
For higher frequencies i ran into following problems:

If i want to plot things, my peripherals freeze and program stops after some time. I have no clue why... maybe serial buffer overflow??
If i just save the data in a text file (without plotting) it works but with a delay of around 20-30seconds on total sampling times of 10seconds (10000 samples).
Meaning that somewhere seems to be a bottleneck and i cant keep up with the sent samples from the Arduino.
Is it possible that the serial bus is the bottleneck here? How can i speed things up? (I'm working with a baudrate 115200bits/s and also 230400bits/s)

How can i improve this while still be able to process data in almost real-time (e.g plotting). Is this even possible or do you recommend logging the data in a text file first and then plot?
Will it helps to send the data in packages (10samles = 70bytes)?
I added a timestamp on each sample, since i observed some delay between the actual sensor measurement and the input on the receiving end. I thought that would allow me to plot and postprocess accurately in "real"-time (with a little delay). Any other ideas?
I would appreciate some input and advice!
Thanks in advance!

You might be interested in the Telemetry library in combination with the command line interface for plotting the data (among other things). It is exactly designed for this sort of things ; also, it is well tested and reliable (I can send without issues data at maximum serial port rate). Arduino library is here Full disclaimer: I am the author of both

You are sending data at ~70kbps. Provided you use serial rate greater than this (115.2 kbps or faster on the Arduino) there should be no problem, assuming you samples are processed quickly enough. This seems to be the case.
Your problem seems to be on the Mac. With a quad core CPU on a fast multitasking machine this should not be an issue. If you are having problems this would be in how you are processing the data. I am not familiar with Processing but you could do this in any language. You need to separate the data logging from the processing and display task. This could be as simple as running a logger and piping the data into a display program.
This is not an Arduino issue (or even a Mac issue), you should ask on https://stackoverflow.com/. NOTE if you want help there you will need to give more detail of the code you are running in the Mac.

So i guess i'm more or less on the right track. Thanks for clearing things up a bit!


text:
How initialise and uninitialise serial based on the user's input?
In Summary. If the argument is true, I want to create a function that prints the necessary stuff into the serial. However, if its false serial is uninitialised and does not print anything, it only executes the code.
The code below does not work, but it's an example code to show what I mean.
bool status;
void setDebug(bool x){
 if (x){
  Serial.begin(115200);
  status = true;
 }
else {
 status = false;}
}
void setup(){
 setDebug(true);
}
void loop(){
Serial.println("Hello World");
}

I have found a few solutions that might be beneficial

If Statement - This overall code works; however, I am looking for a better and more efficient way to do this

void loop(){
 if (status){
  Serial.println("Hello World");
 }
}

Preprocessor directive - I have seen many libraries use #ifdef DEBUG, which works. However, I want to be able to  change it through a function, and the preprocessor directives won't allow me to do that

void loop(){
 #ifdef DEBUG
  Serial.println("Hello World");
 #endif
}

How else can I achieve this?


text:
ArduinoMega2560 throws avrdude: com-state error after pressing the reset button a few times
I have recently switched to an ArduinoMega2560 (authentic) from the Arduino Uno and have been having a bit of trouble with uploading sketches after the reset button has been pressed a few times. This is the sketch I am using to test:
void setup() {
  Serial.begin(115200);
  Serial.println("hello world");
}

void loop() {
  Serial.println("testing");
  delay(1000);
}

When I was using the Uno, the sketch would automatically run when the sketch is uploaded. When the reset button is pressed the sketch restarts ("hello world" is printed followed by "testing" every second). I can press the reset button any number of times and the sketch restarts with no issue. This is what I believe to be the expected behavior.
With the Mega however things have been unpredictable. When the sketch is uploaded it sometimes runs but other times not (haven't figured out the pattern if there is one) and after pressing the reset button it sometimes works, sometimes not. I have noticed that after the reset button a few times (3-5 times on average) then the following com-state error occurs:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\Crustus\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : wiring
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't set com-state for "\\.\COM3"
avrdude: ser_drain(): read error: The handle is invalid.

avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: ser_send(): write error: sorry no info avail
avrdude: stk500_send(): failed to send command to serial port
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_getsync(): timeout communicating with programmer

avrdude done.  Thank you.

Failed uploading: uploading error: exit status 1

If I try upload a sketch again after this it just times out.
Any idea what the issue could be? I have changed COM ports and tried but don't think it is a  COM port issue as the Uno works but perhaps that assumption is wrong.
Does the reset button work differently on the Uno and Mega perhaps?
I am using the ArduinoIDE (2.0.0-rc9.3).I have found a few instances of variations of this issue across the forums but have not found one resolved or relating to the reset button and it working intermittently.

try it with IDE 1. IDE 2 has still many problems. if it has the problem with IDE 1, return the Mega

@Juraj Thanks, I have tried IDE 1 and it has produced the same result

Are you testing this with nothing connected to the Mega board except the computer?

@timemage yes, nothing else connected

I am unable to replicate your problem using your code on an Arduino MEGA ADK, which is essentially the same board except having integrated USB host shield. Tested under Windows 10, IDE v1.8.9 as distributed from the Windows Store (v1.8.57.0), AVR boards package v1.8.5. You are resetting with just the reset button, right? Your board is not laying on top of a conductive surface would short when downward pressure was applied? Otherwise provide any other detail you can think might allow recreating the problem.

@timemage Thanks, appreciate the effort. I am resetting with the reset button and the board was not on a conductive surface - but good thing to note for future. Ended up reinstalling the IDE again and it seemed to fix it for now. IDE 2 still produces the same error (AVR v1.8.5) but IDE 1 (also AVR v1.8.5) works so guess I'll be going back to that. I am on Windows 11 so maybe something funky going on there. Thanks again.


text:
ESP32 how to preserve RTC time during brownout
I want to use the ESP32 built-in RTC clock.
In my situation, my ESP32 will not have access to an NTP server
I do not want to use external RTC modules
ESP32 provides a pin VDD_RTC will powers the RTC domain exclusively
My problem would be solved if I attach a coin cell to this pin.
In this case, in the event of a brownout, the VDD_RTC will be powered and RTC clock preserved.
But, all dev kits I have seen seem to have VDD_CPU, VDD_DSIO and VDD_RTC connected together
So, if I would use a battery or some sort of small ups to power my ESP32 during brownout, it will be depleted by the use of GPIOs and CPU and other functions.
Solution would be here to detect brownout and force ESP32 to go to deep sleep, and then wake it up after brownout. But this would require an external source attached to a ESP32 pin to trigger deep sleep, and I don't see any pin to trigger it
Maybe I could have a circuit that would give me a signal when there is a brownout. I could attach this signal to a GPIO pin and trigger an interrupt that makes ESP32 go into deep sleep
But it seems too much for something that I am sure is super basic and should be implemented already somehow in a more convenient way
Could anyone share with me any experiences of how to preserve RTC using minimum external circuitry?

have you looked at the ESP32 datasheet? ... or ESP32 application note ... one of then may have a recommended circuit schematic

I did and I couldn't find anything interesting

You don't need to do anything special to detect Brownouts. ESP32 itself detects them, and would reset the chip automatically. The reset reason would then indicate a brownout (don't remember the exact name). So you only need to check for the reset reason at the start of your code, whether it is normal powerup, or brownout. The esp won't boot up until the brownout is over, so you don't even need to check when the brownout condition starts nor when it stops.
Moreover, in general (irrespective of brownouts) you don't need any external pins to set the esp32 to sleep, nor do you need them to wake it up. You simply call:
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
esp_deep_sleep_start();

The first line tells the esp how long to sleep. The second one initiates deep sleep. The esp32 (unlike the esp8266), will automatically wake itself back up. If a brownout happens while it is asleep, it will boot up again once the brownout is over, but the wake-up reason would be different depending on the case.
The default voltage that triggers the brownout condition is I think 2.8V. This is only configurable in esp-idf, not Arduino. But you don't have to worry about it. Above 2.8V the esp32 continues to keep time correctly. Below 2.8V, it halts, then wakes up once it rises above 2.8V. However, if you don't use an external RTC, and don't use a stable power source, there is no way to keep track of time after the brownout. You can't know how long the brownout was. There is no way to do this. The only option is then to find the pin that supplies the RTC alone, sever it, and wire it to a separate battery. This requires alot of SMD skills.

I think built-in brownout detector is not good for me because it resets the chip. I need it to go to sleep in order to keep the internal RTC running.

there was a discussion on this blog a while ago -- https://esp32.com/viewtopic.php?t=1558


text:
Can I configure an Arduino via NFC using PN532 with an iPhone as the source?
It seems clear that Apple has intentionally limited the possibilities with NFC, so I understand that I'm going against the grain here. However, I need to support Android and Apple for my device setup, so I'm hoping to work around the Apple restrictions by making my Arduino receive data from an iPhone by posing as an RFID card and accepting a write from my Adafruit PN532 breakout board. I've got my Arduino Uno connected to the board and successfully reading from RFID cards. So the question is can I do a read from an iPhone? I've been experimenting with NFCTools on my iPhone to see if I can stimulate any behavior on my Arduino by running the Adafruit example programs and putting my phone near the reader while activating a write. I haven't had any success yet.
My idea is to avoid requiring Bluetooth for Arduino setup. My configuration is very simple so I don't need anything with high bandwidth. The configuration is done rarely and always by a person who is nearby. It seems like leaving out Bluetooth capability out of my device will save on cost and power consumption (though I don't know how much). It would be really slick too since my customer wouldn't need to go into settings to connect with Bluetooth. Instead they just put their phone near the device and it gets configured!

so, you are asking if your iPhone is able to pose as an RFID card ... wouldn't that be a question for the iPhone crowd?

I'm asking in two directions-- can the iPhone be a Card for read purposes, or can the PN532 be a card for Write purposes. Anyway, I did some more research and it looks like BLE is a better connectivity solution for my needs and still has the magic feel of appearing in an app without going into Settings and explicitly connecting.

can the iPhone be a Card for read purposes? is not about arduino, so it is off topic here ... can the PN532 be a card for Write purpose is also not about arduino ... you may have a better chance of a good answer at a Adafruit forum

My understanding is that the PN532 is a reader/writer and will only want to communicate with passive nfc devices (an RFID card). Therefore, with a phone you cannot really communicate between the two in the way you want. Basically both your phone and the PN532 are going to only look for a passive device.


text:
Arduino IDE EEPROM put() then read() returns different data on ESP32
I'm trying to understand how to read/write a UID struct from miguelbalboa to EEPROM to persist a card ID across system restarts on my ESP32-S3 through the Arduino IDE. I expected Put/Get/Read to be symmetrical but can't seem to prove that. Here's my test program:
/**
 * This is a simple script to experiment with reading and writing MFRC522::Uid
 * structures to eeprom.
 */

#include <MFRC522.h>
#include <EEPROM.h>

#define UID_EEPROM_LOCATION 0
#define EEPROM_SIZE 256

void setup() {

  Serial.begin(115200);   // Initialize serial communications with the PC
  Serial.println("Serial started.");
  EEPROM.begin(EEPROM_SIZE);
  Serial.print("EEPROM started ");
  Serial.println(EEPROM_SIZE);
  printBytesFromEeprom();
  MFRC522::Uid uidToWrite = {
    0x04,
    {B00000000, B10000000, B11100000, B01100000},
    0
  };
  Serial.print("UID Before Write: ");
  printUid(&(uidToWrite));
  storeUidInEeprom(&(uidToWrite));
  printBytesFromEeprom();
  Serial.println("UID was put.");
  MFRC522::Uid uidFromRead;
  readUidFromEeprom(&(uidFromRead));
  printBytesFromEeprom();
  Serial.print("UID from Read: ");
  printUid(&(uidFromRead));
}

void loop() {
}

void printUid(MFRC522::Uid *uid) {
  Serial.print(uid->size, HEX);
  Serial.print(F(" byte card UID:"));
  for (byte i = 0; i < uid->size; i++) {
    if(uid->uidByte[i] < 0x10)
      Serial.print(F(" 0"));
    else
      Serial.print(F(" "));
    Serial.print(uid->uidByte[i], HEX);
  }
  Serial.println();
}

void readUidFromEeprom(MFRC522::Uid* result) {
  EEPROM.get(UID_EEPROM_LOCATION, result);
  delay(1000);
}

void storeUidInEeprom(MFRC522::Uid *uid) {
  EEPROM.put(UID_EEPROM_LOCATION, uid);
  EEPROM.commit();
  delay(1000);
}

void printBytesFromEeprom() {
  Serial.print("256 bytes from EEPROM: ");
  for (int i = 0; i < 256; i++) {
    byte myByte = EEPROM.read(UID_EEPROM_LOCATION + i);
    if(myByte < 0x10)
      Serial.print(F(" 0"));
    else
      Serial.print(F(" "));
    Serial.print(myByte, HEX);
  }
  Serial.println();
}

I'm an experienced Java developer, but new to C++. I could have made any number of basic errors.
When I run the above on my ESP32-S3-DevKitC-1, I get the following output:
ESP-ROM:esp32s3-20210327
Build:Mar 27 2021
rst:0x1 (POWERON),boot:0x8 (SPI_FAST_FLASH_BOOT)
SPIWP:0xee
mode:DIO, clock div:1
load:0x3fcd0108,len:0x43c
load:0x403b6000,len:0xbd0
load:0x403ba000,len:0x29c8
entry 0x403b61d8
Serial started.
EEPROM started 256
256 bytes from EEPROM:  E4 2C CE 3F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID Before Write: 4 byte card UID: 00 80 E0 60
256 bytes from EEPROM:  94 2D CE 3F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID was put.
256 bytes from EEPROM:  94 2D CE 3F FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID from Read: C0 byte card UID: 79 CD 3F 00 00 00 00 00 00 00 00 0C FA 3B C7 00 00 00 00 04 00 00 00 4C 2F CE 3F 01 00 00 80 00 00 00 00 F0 2D CE 3F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 2E CE 3F 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

There are two unexpected things from this output:

The output of readUidFromEeprom() is different than the input to storeUidInEeprom()

Any help would be welcome!

readUidFromEeprom(MFRC522::Uid& result)

You wrote:
void readUidFromEeprom(MFRC522::Uid* result) {
  EEPROM.get(UID_EEPROM_LOCATION, result);
  delay(1000);
}

The EEPROM.get() method expects a reference to the variable you are
setting. Here, you are providing a pointer instead. The outcome is
that this call is updating the result local variable (the pointer),
rather than the memory region pointed by it.
You may try this:
void readUidFromEeprom(MFRC522::Uid* result) {
  EEPROM.get(UID_EEPROM_LOCATION, *result);  // notice the `*' operator
  delay(1000);
}

Same thing for EEPROM.put().
Edit: As suggested by Juraj in a comment, it can make more sense to
have readUidFromEeprom() accept a reference rather than a pointer:
void readUidFromEeprom(MFRC522::Uid &result) {
  EEPROM.get(UID_EEPROM_LOCATION, result);
  delay(1000);
}

But then you have to also change the caller:
readUidFromEeprom(uidFromRead);

Well...
I still don't know why the above wasn't working. But if I switch to my own byte encoding in EEPROM (the obvious one that I assumed put() used, then I get the right behavior:
/**
 * This is a simple script to experiment with reading and writing MFRC522::Uid
 * structures to eeprom.
 */

#include <MFRC522.h>
#include <EEPROM.h>

#define UID_EEPROM_LOCATION 0
#define EEPROM_SIZE 256

void setup() {

  Serial.begin(115200);   // Initialize serial communications with the PC
  Serial.println("Serial started.");
  EEPROM.begin(EEPROM_SIZE);
  Serial.print("EEPROM started ");
  Serial.println(EEPROM_SIZE);
  printBytesFromEeprom();
  MFRC522::Uid uidToWrite = {
    0x04,
    {B00000000, B10000000, B11100000, B01100000},
    0
  };
  Serial.print("UID Before Write: ");
  printUid(&(uidToWrite));
  storeUidInEeprom(&(uidToWrite));
  printBytesFromEeprom();
  Serial.println("UID was put.");
  MFRC522::Uid uidFromRead;
  readUidFromEeprom(&(uidFromRead));
  printBytesFromEeprom();
  Serial.print("UID from Read: ");
  printUid(&(uidFromRead));
}

void loop() {
}

void printUid(MFRC522::Uid *uid) {
  Serial.print(uid->size, HEX);
  Serial.print(F(" byte card UID:"));
  for (byte i = 0; i < uid->size; i++) {
    if(uid->uidByte[i] < 0x10)
      Serial.print(F(" 0"));
    else
      Serial.print(F(" "));
    Serial.print(uid->uidByte[i], HEX);
  }
  Serial.println();
}

void readUidFromEeprom(MFRC522::Uid* result) {
  byte uidSize = EEPROM.read(UID_EEPROM_LOCATION);
  for (byte i = 0; i < uidSize; i++) {
    result->uidByte[i] = EEPROM.read(UID_EEPROM_LOCATION + 1 + i);
  }
  byte uidSak = EEPROM.read(UID_EEPROM_LOCATION + 2 + uidSize);
  result->size = uidSize;
  result->sak = uidSak;
}

void storeUidInEeprom(MFRC522::Uid *uid) {
  EEPROM.write(UID_EEPROM_LOCATION, uid->size);
  for (byte i = 0; i < uid->size; i++) {
    EEPROM.write(UID_EEPROM_LOCATION + 1 + i, uid->uidByte[i]);
  }
  EEPROM.write(UID_EEPROM_LOCATION + 2 + uid->size, uid->sak);
  EEPROM.commit();
}

void printBytesFromEeprom() {
  Serial.print("256 bytes from EEPROM: ");
  for (int i = 0; i < 256; i++) {
    byte myByte = EEPROM.read(UID_EEPROM_LOCATION + i);
    if(myByte < 0x10)
      Serial.print(F(" 0"));
    else
      Serial.print(F(" "));
    Serial.print(myByte, HEX);
  }
  Serial.println();
}

And output as expected is:
ESP-ROM:esp32s3-20210327
Build:Mar 27 2021
rst:0x1 (POWERON),boot:0x8 (SPI_FAST_FLASH_BOOT)
SPIWP:0xee
mode:DIO, clock div:1
load:0x3fcd0108,len:0x43c
load:0x403b6000,len:0xbd0
load:0x403ba000,len:0x29c8
entry 0x403b61d8
Serial started.
EEPROM started 256
256 bytes from EEPROM:  04 00 80 E0 60 FF 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID Before Write: 4 byte card UID: 00 80 E0 60
256 bytes from EEPROM:  04 00 80 E0 60 FF 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID was put.
256 bytes from EEPROM:  04 00 80 E0 60 FF 00 FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF FF
UID from Read: 4 byte card UID: 00 80 E0 60

On the ESP23 platform, consider using the Preferences library. EEPROM in arduino-esp32 is emulated using the Preferences library. Might mess up the calls to MFRC522 lib though.
Preferences docs include the API and tutorial.


text:
My ESP32-S3 DevkitC-1 has two USB micro ports labeled 'USB' and 'UART'. What are they for?
I'm new to micro-controllers. I've got an ESP32-S3-DevKitC-1 and I'm trying to do a simple hello world with the Serial. I'm using the Arduino IDE for flashing and serial monitoring. My code is:
/**
 * As simple as it gets, right? Setup the Serial, wait on it. The periodically print during the loop.
 */
void setup() {
  Serial.begin(9600);   // Initialize serial communications with the PC
  while (!Serial);
}

void loop() {
  Serial.println("Hello World");
  delay(1000);
}

I've tried various baud rates. I've also tried a few different configurations for flashing-- this includes flashing over the UART port with upload mode 'UART0/Hardware CDC' and 'USB-OTG CDC (TinyUSB)'. I'm basically at guess and check right now and am looking for some tips or resources to understand the ports. My serial always shows gibberish. I've even tried miniterm like this:
pyserial-miniterm /dev/cu.usbserial-1410 9600

How do you install the Arduino-ESP32 core on your IDE? Arduino-ESP32 is still only support the ESP32-S3 on "development" release only, if you installed the ESP32-S3 with the "stable" release, it won't work with ESP32-S3 yet. See the installing.

The USB port connects directly to the D+/D- pins of the ESP32, which allows it to act as a USB host. CircuitPython, for instance, uses this functionality to look like a USB flash drive. You could also write software that might have the ESP32 mimic a keyboard or mouse or other simple USB devices over this port. You generally will not use it to program the board, though CircuitPython does install its own firmware updates from files written to the USB flash drive its boot loader presents.
The UART port connects to a USB/serial chip which is connected to the RX and TX pins of the ESP32. If you want to flash firmware to the board in a traditional way (using esptool.py) you'd use this connector. You may need to press the BOOT button to get the device into firmware download mode.
The ESP32 defaults to 115200 baud, which is why you'd see gibberish at 9600 baud - that would be the boot loader messages.
You'll need to ensure that the firmware you're trying to flash to it is built for the correct model CPU and also for the amount of PSRAM on your board. I would stick with 115200 baud for the serial speed so that you'll be able to see the boot loader messages as well as any output of your program, if it's correctly built and flashed to the board. [edit: as @hcheung pointed out there is no official stable support for the S3 in the Arduino Core at the time this question was asked]
You can learn more about your device by reading the official Espressif documentation on it.

That did it. I was using the wrong baud rate for my serial monitor and had changed my upload speed during debugging so that broke too. Thank you!

Glad you got it working!

I had to spent some additional time debugging my smart hardware electronics for a home automation wall mount switch based on the ESP32 S3 ( see it on my GitHub here )

because I was able to upload the firmware code into it however when reading serial output it only displayed "gibberish" characters.
On the internet I could not find the answer, so I had to work harder to find the solution. Common problems found when dealing with serial output errors are:

poor UART ground
absence of a 500 Ohm resistor on the TX line
UART cable to long
track coupling and track length mismatch

are all hardware issues that cause serial communication errors and malfunctioning. However, for the ESP32 there's one missing on the list above.
On this particular hardware, I had incorrectly soldered the RTC crystal of 32,768MHz into the MCU crystal place which is for one of 40MHz. The result was, it is possible to do firmware upload using a 32,768Mhz crystal for the MCU however, and due to the incorrect clock frequency, serial output is no longer 115200bps and displays "gibberish" characters.
In summary make sure the crystal has the correct clock frequency value.

so you used a wrong crystal on your PCB and you add this as an answer to the question about the two USB connectors on an official dev kit?

Don't expect to get an answer tailored to your understanding. Read all here, and make your own assessment of what can be wrong  So, on my case, i accidentality used a different crystal. Firmware upload is still possible , no errors. However, serial communication is affected and shows "gibberish" . So in sum, check the crystal if has the correct frequency and if is working properly.


text:
Having issues Connecting to a web server and pulling the data back
I have some arduino code where I am trying to pull information from four different locations.  Three are working great and the fourth I am not getting any response.
These two strings work perfect in a browser and I get the proper data response.
http ://10.196.1.163:8086/query?db=Garden&q=SELECT * FROM "Station" WHERE station = 61 ORDER BY DESC LIMIT 1
Or
http://10.197.1.57:8086/query?db=Garden&q=SELECT%20*%20FROM%20%22Station%22%20WHERE%20station%20=%2091%20ORDER%20BY%20DESC%20LIMIT%201

{"results":[{"statement_id":0,"series":[{"name":"Station","columns":["time","altitude","humid","moist","press","rainfall","soiltemp","station","temp","type","vbat","winddir","windspeed"],"values":[["2022-01-08T21:13:58Z",1269,29.2,0,28.5,0,0,91,73.4,9,4.32,0,0]]}]}]}

The code below is what I am trying to use.  It appears to make the connection but brings nothing back.
What I see in the console is:
  19:55:42.024 -> Starting connection to server: 10.196.1.163 InfluxDB Garden DB...
  19:55:42.024 -> connected to server
  19:55:42.024 ->

The next line is starting to connect to the next server which brings back the JSON data fine.
I have been assuming that I was having issues because of the alternate port 8086 I was connecting to, but I am not sure.  I have been looking and finding examples similar to what I am doing.
I must be just missing something, but I am not sure what. I have been working off and on for this issue for a couple of months.
void getLocalDataQuery2() {
  Serial.println("\nStarting connection to server: 10.196.1.163 InfluxDB Garden DB...");
  if (client.connect(server2, 8086)) {
    Serial.println("connected to server");
    client.print("GET /query?");
    client.print("db=Garden");
    client.println("&q=SELECT%20*%20FROM%20%22Station%22%20WHERE%20station%20=%2091%20ORDER%20BY%20DESC%20LIMIT%201");
    client.println("Host: 10.196.1.163");
    client.println("Connection: close");
    client.println();
  } else {
    Serial.println("unable to connect");
    while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
      // unsuccessful, retry in 4 seconds
      Serial.print("failed ... ");
      delay(4000);
      Serial.print("retrying ... ");
    }
  }
  String line = "";

  while(client.available())
  {
    line = client.readStringUntil('\n');

    Serial.print("Line : ");
    Serial.println(line);
  }
}

My solution to this was to setup a webserver running php code in a Docker container. The php code ran the influxdb query and sends the results

A client doesn't receive data immediately after sending a request. So client.available() returns 0 at first and your while loop is skipped.
The readStringUntil is one of the functions which wait for the next byte until timeout (1 second by default). So you can call readStringUntil first and it will wait for the data to arrive.
One way would be to replace the while loop with a do while loop, but the do while loop is strange and even experienced programmers don't like to use it.
In real application the first line of a HTTP response is important, because it contains the response status. The rest of the response header lines can be skipped.
So why not add reading of the first line before the while loop? This way readStringUntil will wait for the response and read the first line.
  String line = client.readStringUntil('\n');
  line.trim();
  Serial.print("Status line : ");
  Serial.println(line);

  while (client.available())
  {
    line = client.readStringUntil('\n');
    line.trim();
    Serial.print("Line : ");
    Serial.println(line);
  }

I tried this suggestion and still get no data back.  I see the following:
17:04:36.537 -> Starting connection to server: 10.196.1.163 InfluxDB Garden DB...
17:04:36.582 -> connected to server
17:04:37.558 -> Status line :
17:04:37.558 ->


text:
Burn code to Attiny13/85 the easy way
Totally newbie here. I need to burn 50 blank Attiny13 chips with the following code:
https://github.com/mstratman/relay-bypass/blob/main/relay-bypass/relay-bypass.ino
AFAIK the code can be used by anyone since its license is MIT (https://mas-effects.com/relay.pdf)
What do you think is the easiest and quickest way to burn that code to my chips?
I have a Windows PC, an Arduino Uno, and USBASP, a chip socket, and the 50 chips. Never used arduino before. I do have a MiniPro TL866 programmer which is very easy to use, just upload the bin file, select the chip and click burn... Not sure if it would work with Attiny chips. If there is any hardware that would be easier/quicker to do the job I would buy it though.
Thank you!

start by determining if the programmer is capable of programming the chips

is your chip socket ZIF? If not, I would wait until I got one of those.

Is this spam, John Mayland 22? A simple yes or no.

This isn't a reasonable question here, asking if some unknown hardware could be better than the hardware you mentioned sounds to me like you are promoting the mentioned hardware.


text:
Why my pushbutton always reads LOW?
This is the code I used in  my project
void setup() {
  Serial.begin(9600);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(10,OUTPUT);
  pinMode(11,OUTPUT);
  pinMode(12,OUTPUT);
  pinMode(5,INPUT);
}
void loop() {
  Serial.println(digitalRead(5));
  if(digitalRead(5)==HIGH){
    blink(12,100);
    blink(11,100);
    blink(10,100);
    blink(9,100);
    blink(8,100);
    blink(7,100);
    blink(6,100);
    Serial.println("blink done");
  }

}
void blink(int a,int b)
{
  digitalWrite(a,HIGH);
  delay(b);
  digitalWrite(a,LOW);
  delay(b);
}

Project link
https://www.tinkercad.com/things/55vY18FFxDR-blinking-led-wave/editel?sharecode=xQAM80Uu6sJ-hBnLLd04KasomJ2eNNzWLgKZMARe4ig

connect only the switch, resistor and LED ... determine which two pins are connected when you press the button ... I suspect that the top left pin is always connected to the bottom left pin

L1 and L2 or R1 and R2(L for left, R for Right) are connected when the button is open.
[link]https://www.tinkercad.com/things/kMT2yOJpFzg-analog-read/editel?returnTo=%2Fdashboard%3Fcollection%3Ddesigns%26type%3Dcircuits&sharecode=OoTMPbTeJWJGX6WAKZCwLJWxiERzOEBsVfjqZH9p4Kw
this is where I checked it.

you have brown wire connected to L1, which is always connected to L2, and L2 is connected to ground ... why are you surprised that the brown wire is always grounded?

Yes I am aware of it, but the issue I am concerned about is that it neither displays 1 nor does the blink function after pressing the button. I tried moving the D5 pin jumper to j30 and it displayed 1 and the blink started to work (as R1 and R2 are connected but it defies the purpose of switch).

You mean when you short 5V to GND by pressing button (that is how you have that wired), it's not working? Maybe polyfuse is taking some time to reset, or USB port protection

remove the 5 V wire at a30 ... move D5 to j30 ... enable internal pullup resistor pinMode(5,INPUT_PULLUP);

I changed the if condition digitalRead as LOW and as @jsotola said I have changed the pinMode to INPUT_PULLUP, IT WORKED...somehow....
It is highly appreciated if you could explain why the 5 v wire and that typical pushbutton connection didn't work

in the circuit above, D5 is always connected to GND ... connecting 5 V to GND does not do anything to raise the voltage at D5 ... in a real circuit, a connection between 5 V and GND could easily damage something

Understood but why the below given typical pushbutton circuit even works and not here.
Is it possible to remake that pushbutton here......?
My simulation references:
https://imgur.com/a/jUagd1q     (image)
https://imgur.com/a/vnZSJ6H     (video)

When you press the button, you short the bottom blue (GND) and the bottom red (+5V) lines. That will in the least serious case cause your Arduino to reset, but could also damage the button, burn a wire or a capacitor, or brick your Arduino. There's some protection on the board to prevent serious damage or even injury to someone, but still you should absolutely avoid shorting +5V to GND.
The fix is actually quite simple: Replace the short blue wire with a large resistor, something like 10k. Then the Button will still read low when it's not pressed, but read high when it's pressed. That's called a "pull-down" resistor.

the OP is running a simulation ... the short circuit probably is not simulated ... your answer is applicable to real hardware only

That's an point to be noted but it did not work here as it is just a simulation.


text:
WiFiClient.cpp:517 flush(): fail on fd 48, errno: 11, "No more processes" what it mean?
Hello i wrote this sketch that upload a temperature reading of a DHT22 sensor to a phpMyAdmin server in localHost, the sketch work fine, the data been upload every 5 min to the server than ESP go t sleep, but every time the code has been executed i have the printout in the console of this error which i don't understand what mean.
[  1937][E][WiFiClient.cpp:517] flush(): fail on fd 48, errno: 11, "No more processes"

here below my sketch:
the sketch include the timer every 5 min to wakeup esp read the temperature and post to the server.
#include <Arduino.h>
#include <DHT.h>
#include <Adafruit_Sensor.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>

// FOR T sensor
#define TsensorPin 4
#define DHTTYPE DHT22
DHT dht(TsensorPin, DHTTYPE);
String sensorName = "DHT22";
String sensorLocation = "Casa1";
float h;
float t;
float f;
float hif;
float hic;

// for wifi connection
const char* ssid     = "Captain Spiko";
const char* password = "123456789d";

// server data
const char* serverName = "http://192.168.50.158/esp_web/post_esp.php";
String apiKeyValue = "123456789";

// for awake and sleep
#define uS_TO_S_FACTOR 1000000
#define TIME_TO_SLEEP  300
RTC_DATA_ATTR int bootCount = 0;

void print_wakeup_reason(){
  esp_sleep_wakeup_cause_t wakeup_reason;

  wakeup_reason = esp_sleep_get_wakeup_cause();

  switch(wakeup_reason)
  {
    case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
    case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
    case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
    case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
    case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
    default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
  }
}

void readTemperature(){

  h = dht.readHumidity();
  t = dht.readTemperature();
  f = dht.readTemperature(true); // in F

  // Compute heat index in Fahrenheit (the default)
  hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  hic = dht.computeHeatIndex(t, h, false);

  Serial.print(F("Humidity: "));
  Serial.print(h);
  Serial.print(F("%  Temperature: "));
  Serial.print(t);
  Serial.print(F("°C "));
  Serial.print(f);
  Serial.print(F("°F  Heat index: "));
  Serial.print(hic);
  Serial.print(F("°C "));
  Serial.print(hif);
  Serial.println(F("°F"));
}

void activateSleep(){
  Serial.println("Going to sleep now");
  delay(1000);
  Serial.flush();
  esp_deep_sleep_start();
}

bool setupWifi(){
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  if (WiFi.status() == WL_CONNECTED){
    return true;
  } else {
    return false;
  }

}

void postData(){
  if(WiFi.status()== WL_CONNECTED){
    WiFiClient client;
    HTTPClient http;
    http.begin(client, serverName);
    http.addHeader("Content-Type", "application/x-www-form-urlencoded");
    // Prepare your HTTP POST request data
    String httpRequestData = "api_key=" + apiKeyValue + "&sensor=" + sensorName
                          + "&location=" + sensorLocation + "&value1=" + String(h)
                          + "&value2=" + String(t) + "&value3=" + String(f) + "";
    Serial.print("httpRequestData: ");
    Serial.println(httpRequestData);
    int httpResponseCode = http.POST(httpRequestData);
    if (httpResponseCode>0) {
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
    }
    else {
      Serial.print("Error code: ");
      Serial.println(httpResponseCode);
    }
    http.end();
  }else {
    Serial.println("WiFi Disconnected");
  }
}

/// @brief  Set up
void setup() {

  Serial.begin(115200);
  delay(1000);
  ++bootCount; // tiene il conto dei restart
  Serial.println("Boot number: " + String(bootCount));
  print_wakeup_reason();
  if (setupWifi() == true){
    esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);// set up next wake up after 30 sec
    Serial.println(F("DHTxx test!"));
    dht.begin();
  };

}

/// @brief loop func
void loop() {
  readTemperature();
  postData();
  activateSleep();
}

at which device and in which program are you seeing the error?

I’m using VS code with platformio, I see this error on the esp32 serial print out, the one that post the data to the server .

FD probably means File Descriptor and 48 is the number. If it's Linux-like, basically everything is treated as a file: files, sockets, processes, ...

If setupWifi() == false, then dht.begin(); is never called but it still enters loop() and tries to read temperatures. Not sure if that's good or eventually runs into undefined behavior.

Also, I don't get why esp_sleep_enable_timer_wakeup() is only activated if it was possible to connect to the Wifi. If it was not possible to connect to the Wifi, you still goto into deep sleep. But you don't want to wake up after 30 seconds then?

if (WiFi.status() == WL_CONNECTED){ return true; } else {return false; } is cargo cult programming. It can be simplified to return WiFi.status() == WL_CONNECTED. Similar for if (setupWifi() == true), which is equal to if (setupWifi())

I think you ran into the issue described on Github issues for WifiClient.
A user has loooked into this and found that the error message does not match the problem:

errno 11 (EAGAIN) happens when you go to read (via BSD recv function) bytes from a stream with MSG_DONTWAIT flag and there are no bytes to be read. The ESP error string "No more processes" is misleading. It's really "No data available, try again later." or maybe "No data to process".

It seems that there's no fix for the package yet as of today, but another user has posted a derived class that fixes the problem:

File wifiFix.h:
#pragma once

class WiFiClientFixed : public WiFiClient {
public:
  void flush() override;
};

File wifiFix.cpp:
#include <WiFi.h>
#include <lwip/sockets.h>
#include "wifiFix.h"

#define WIFI_CLIENT_FLUSH_BUFFER_SIZE    (1024)

void WiFiClientFixed::flush() {
  int res;
  size_t a = available(), toRead = 0;
  if (!a) {
      return;//nothing to flush
  }
  auto *buf = (uint8_t *) malloc(WIFI_CLIENT_FLUSH_BUFFER_SIZE);
  if (!buf) {
      return;//memory error
  }
  while (a) {
      // override broken WiFiClient flush method, ref https://github.com/espressif/arduino-esp32/issues/6129#issuecomment-1237417915
      res = read(buf, min(a, (size_t)WIFI_CLIENT_FLUSH_BUFFER_SIZE));
      if (res < 0) {
          log_e("fail on fd %d, errno: %d, \"%s\"", fd(), errno, strerror(errno));
          stop();
          break;
      }
      a -= res;
  }
  free(buf);
}

File main.cpp:
#include "wifiFix.h"
WiFiClient* wifi = new WiFiClientFixed();

Finally, instead of http.begin(url);, use http.begin(*wifi, url);

In Platformio.ini I changed config to "platform = espressif32@3.5.0" from "platform = espressif32". It solved this issue for me

How does this resolve the problem, i dont get the direct coloration?

This bug is solved in Espressif Arduino Core 2.0.14 which is out since last month. If you're using PlatformIO add this to your platformio.ini file:
platform = https://github.com/tasmota/platform-espressif32/releases/download/2023.10.05/platform-espressif32.zip

This is not from the official PlatformIO branch but from Tasmota, a trusted source in the PlatformIO community. See the github site: https://github.com/tasmota/platform-espressif32


text:
integer overflow in expression of type 'int' results
i need to wake up my ESP every 60 min to read some data and post it to server, all process working fine when i use numbers of minute below 60 (converted in microsecond x 1000000) but when i use 60 min above i get the following message:

src/main.cpp:137:49: warning: integer overflow in expression of type 'int' results in '-694967296' [-Woverflow]
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);// set up next wake up after 30 sec

How can i make my ESP wake up every 60 min or above?
simplify code:
// for awake and sleep
#define uS_TO_S_FACTOR 1000000
#define TIME_TO_SLEEP  60 // minute

void setup(){
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * 60 * uS_TO_S_FACTOR);// error if time to sleep more than 60 min
}

More or less the same question here. On the ESP32 the long  and int types have the same range.

Change that line to:
esp_sleep_enable_timer_wakeup((uint64_t) TIME_TO_SLEEP * 60 * uS_TO_S_FACTOR);

That forces the compiler to do 64-bit arithmetic on the constant rather than defaulting to "int" arithmetic.


text:
Sending an image captured using ov7670 using arduino and serially transmit it to python
I am working on using an ov7670 camera module with arduino uno,capturing the image frame wise and transmitting the image serially line by line of each frame to python for image processing, however i am getting very distorted images once is use the serial.write() command,how do i send the bytes without using serial.write().
This is the link i used for setting up the Ov7670

You didn't show your code, nor a sample of a distorted image, nor your python code. What exactly makes you think, that Serial.write() is the problem here?


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:
Share interrupt service between class
I would like to share interrupt routine between class. I followed this tutorial.
But I need to call a member function in callback function, I have the issue :

This is my code :
Timer.h
static void (*__handleISR)(void);

class Timer
{
    public:
        Timer();
        ~Timer();
        static void init();
        static void handleISR(void (*function)(void));
};

Timer.cpp
Timer::Timer()
{
}

Timer::~Timer()
{}

void Timer::init()
{
    TCCR2A = 0; //default
    TIMSK2 = 0b00000001; // TOIE2
}

ISR (TIMER2_OVF_vect)
{
    // 256-6=250 --> (250 x 16uS = 4mS)
    // Recharge le timer pour que la prochaine interruption se declenche dans 4mS
    TCNT2 = 6;

    __handleISR();
}

Device.h
class Device
{
    public:
        Device();

    private:
        void isr();
};

Device.cpp
Device::Device()
{
    Timer::init();
    Timer::handleISR(isr);
}

void Device::isr()
{
    // Do my stuff
}

If I set function isr() static, it works. But I need to call member from Device in isr().
How I can call non static member function ? Or another solution ?

Do none of these results help you? https://arduino.stackexchange.com/search?q=invalid+use+non+static+member

nop the solution is with static member

This is not an Arduino specific question but a C++ question, and as such you might get more or better answers on StackOverflow. Anyway, I'll suggest a possible solution.
A member method always receives a pointer to its object as a hidden first argument that we know as this. Only via this argument such a method is able to access member attributes or member methods.
A class method does not have this parameter.
The function type you define is compatible only to functions or class methods.
So you need to provide a pointer (or reference) to the Device object.
I reduced your example and replaced the interrupt macro with something a standard C++ compiler accepts, as this is not part of the issue.
Timer.h
#ifndef TIMER_H
#define TIMER_H

#include "Device.h"

class Timer
{
    public:
        static void setCallback(void (*function)(Device*), Device*);
};

#endif

Timer.cpp
#include "Timer.h"

#define ISR(f) void f()

static void (*_function)(Device*);
static Device* _device;

void Timer::setCallback(void (*function)(Device*), Device* device)
{
    _function = function;
    _device = device;
}

ISR(TIMER2_OVF_vect)
{
    _function(_device);
}

Device.h
#ifndef DEVICE_H
#define DEVICE_H

class Device
{
    public:
        Device();

    private:
        static void isr(Device* device);
        void isr();
};

#endif

Device.cpp
#include "Device.h"
#include "Timer.h"

Device::Device()
{
    Timer::setCallback(isr, this);
}

void Device::isr(Device* device)
{
    device->isr();
}

void Device::isr()
{
    // Do my stuff
}

If you don't need the Device object, you don't need a member method. Then go with a class method, as you already found out.

it works, thank you very much :)


text:
Controlling the 5V pin on the Arduino nano 33 BLE
Following the guidance on this post  I have enabled the 5V pin.  That same post suggests that I control that pin with D12, though I find it weird since there is already a D12 pin.  When I try and run some code the D12 pin is performing exactly as I expect, but the 5V pin is doing nothing.
Looking through the tech specs it says "the 5V pin does NOT supply voltage but is rather connected, through a jumper, to the USB power input." which I find odd, since if its connected to the power input, should it not be supplying voltage?
Could someone clarify if its possible to use the 5V pin like a digital pin, and if so how?

Following the guidance on this post I have enabled the 5V pin. That same post suggests that I control that pin with D12, though I find it weird since there is already a D12 pin. When I try and run some code the D12 pin is performing exactly as I expect, but the 5V pin is doing nothing.

5 V pin is the the 12th pin of the PCB

Looking through the tech specs it says "the 5V pin does NOT supply voltage but is rather connected, through a jumper, to the USB power input." which I find odd, since if its connected to the power input, should it not be supplying voltage?

it says that the 5V pin is connected to the USB power input through a jumper and the jumper is not connected from factory

the 5V pin does NOT supply voltage but is rather connected, through a jumper, to the USB power input could mean that the pin is not a power input for the arduino

@jsotola it can be both because it is connected to USB power input and to the 5 V to 3.3 V regulator which powers the rest of the board. but the pads are not connected to prevent using the 5 V pin without a solder bridge. https://content.arduino.cc/assets/NANO33BLE_V4.0_sch.pdf

Thank you for the clarification, but it does not answer the question.  Is it possible to use the 5V pin like a digital pin?  If so, how?

@Pablo, the pin is just on a 5 V rail of the board. there is no logic, just 5 V power.


text:
Variable scope error
guys.
I'm writing here because I cannot find an obvious error, so I'm stuck. Could you please help me?
Here's the code:
int arrayAAA[] = {6, 8, 10, 12};
int arrayBBB[] = {9, 15, 27, 41};

const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

int newArrayLength = 0;

void setup() {

    Serial.begin(9600);

}

void loop() {

  String dir = "AAA";

  if (dir == "AAA"){

      //Copy existing array to the new one...
      newArrayLength = arrayAAALength;              //Get the size of source array
      int newArray[newArrayLength];                 //Make the new array of the same size
      memcpy(newArray, arrayAAA, sizeof(arrayAAA)); //Copy content of the source array to the new one

      /*
      for (int i = 0; i < newArrayLength; i++){
          Serial.print(newArray[i]); //Here everything works just fine...
          Serial.print("   ");
      }
       */
  }

  for (int i = 0; i < newArrayLength; i++){
      Serial.print(newArray[i]); //But here I see this error: 'newArray' was not declared in this scope
      Serial.print("   ");
  }

  Serial.println();
  Serial.println();

}

What I'm trying to do is to copy the array to a new one, but depending on the circumstances I need to take different source arrays (AAA or BBB).
The problem is in checking the values of an newly crreated array:
'newArray' was not declared in this scope

if I try to check its valus outside of if statment.
It seems my stupid mistake, but I can't find it.

After a careful study of C/C++ documentation, I finally managed to use pointers in Arduino :)
So, the final code became like this:
int arrayAAA[] = {6, 8, 10, 12};
int arrayBBB[] = {9, 15, 27, 41};

//Create a pointer, which will point to any of your arrays of your choice
int *newArray;

const int arrayAAALength = sizeof(arrayAAA)/sizeof(int);
const int arrayBBBLength = sizeof(arrayBBB)/sizeof(int);

void setup() {

    Serial.begin(9600);

    //Uses the address of arrayAAA (i.e. inherits the content of arrayAAA).
    //&: points to address of a chosen array.
    //[0]: is a must to grab all values!
    newArray = &arrayAAA[0];

    Serial.print("arrayAAA:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(arrayAAA[i]);
    }
    Serial.println();

    Serial.print("newArray:");
    for (int i = 0; i < arrayAAALength; i++){
        Serial.print("   ");
        Serial.print(newArray[i]);
    }
    Serial.println();
}

void loop(){
    //Left empty
}

And it works perfectly, just what I expected!

The clue is in the indenting:
  if (dir == "AAA"){

      //Copy existing array to the new one...
      newArrayLength = arrayAAALength;              //Get the size of source array
      int newArray[newArrayLength];                 //Make the new array of the same size <<<==== DEFINED IN THE SCOPE OF "IF"
      memcpy(newArray, arrayAAA, sizeof(arrayAAA)); //Copy content of the source array to the new one

      /*
      for (int i = 0; i < newArrayLength; i++){
          Serial.print(newArray[i]); //Here everything works just fine...
          Serial.print("   ");
      }
       */
  }

  for (int i = 0; i < newArrayLength; i++){
      Serial.print(newArray[i]); //But here I see this error: 'newArray' was not declared in this scope <<=== USED IN THE SCOPE OF "FOR"
      Serial.print("   ");
  }

As you can see by the indenting the definition of newArray is in a different block of code which you come right out of before you use it.
You must define newArray at a scope that is outside where you use it.
From that code you don't actually need to copy the contents of one array into another - you can just point to the array you want to use with a pointer.  Alternatively, if you do need to clone the array contents (for some other purpose we don't know of) then you should pre-create an array that is big enough to hold either of your other arrays.
int newArray[max(arrayAAALength, arrayBBBLength)];

Yes, I'd like to point to another array. This would be much more effective. But how can I do it right? I tried to use this code: int *newArray = &arrayAAA, but it leads to another error: invalid types 'int[int]' for array subscript.

It's a very bad idea to create arrays on the stack in the way you describe. If you want a run-time-sized array, use std::vector. If you must have an array, use unique_ptr<int[]>, which will take care of deallocating the space when the variable gets out of scope. Adding examples as an answer so I can format them properly

(as to why it's a bad idea: it usually adversely affects caching, and may blow your stack, which is a real concern in some memory-constrained systems, or in massively multithreaded environments where you really want to use the smallest stack frame possible. While the arduino isn't such an environment, habits you acquire here may transfer to other jobs, and then you'll be trying to find really insidious bugs which could have been prevented by proper code hygiene.).

@JayEye Sorry, but your thinking is wrong there. On a memory constrained system like the Arduino it is far better to use the stack than the heap. The stack is a LIFO system so all allocation / deallocation is linear. Using the heap leads to fragmentation, and on a system that has no ability to do heap defragmentation even slight amounts of fragmentation can lead to big problems further down the line as the heap grows out of control. You don't get that with the stack. And with no frame swapping, since there is no OS or threads or anything like that, you don't get any performance hit ...

... by having a large frame. Yes, it is possible to smash your stack into the heap, but it's easier to avoid than the tangled mess of swiss cheese that the heap would become from growing up into the stack. In general dynamic allocation on a small MCU is frowned upon. Also many MCU compilers don't even have STL available for use - simply because it is too heavyweight and causes too many heap problems for reliable use. Yes, your comments are perfectly valid in other environments and other situations, but not for tiny MCUs like the Arduino.

Made corrections per @Majenko's comment
The following will not work on real Arduinos, but it did work for me on the ESP8266 and the Teensy3, which are what I use mostly, and the only ones I tested the code for: https://github.com/jayeye/jardino/tree/master/esp8266/ase25017
#include <vector>
  ...
  size_t vector_size = 42;
  std::vector<int> foo(vector_size);  // foo is a vector of 42 integers

Another correction: Exceptions do not work even on the aforementioned platforms, so do not access the vector with .at(n)
If you must have an array, use a unique_ptr with an array allocator:
#include <memory>
  ...
  size_t vector_size = 42;
  std::unique_ptr<int[]> arr(new int[vector_size]);

When arr goes out of scope, the array will be automatically freed.
You can always use malloc(), but you'll have to remember to free() it, and that's always a source of bugs.

That can't work on an Arduino. There is no STL, and hence no vector. Also... If you want to get an exception - what is an exception? There are no exceptions. You are thinking PC programming, not MCU programming. The two are vastly different and take completely different mindsets.

Two lessons here: test on the most common platform (I had tested the code on the esp8266, which is what I had handy at the moment), and don't make assertions without testing them (about exceptions -- I never use them, they are forbidden by the Google style guide, and for good reason, but I tried to be too smart here and failed :) )

also, what's this "PC programming". I don't program PCs, I program large linux clusters :)