text:
Detecting peak frequency in a microphone's output signal
I'm using a simple electrode microphone with an Arduino UNO board with the aim of detecting peak frequencies in the output signal overtime. I set the sampling rate to 1 MHz, but i can't pick up a peak that is above 4000 Hz(I've verified the values with regression but it's only true for the range [200 Hz, 3900 Hz]). So my questions are:

Is this due to the microphone's sensibility or to the Arduino UNO?
Someone suggested me an ESP32, but i don't understand what difference it'll make.

CODE:
#include "arduinoFFT.h"
float peak = 0;
float val = 0;
#define SAMPLES 128            //SAMPLES-pt FFT. Must be a base 2 number. Max 128 for Arduino Uno.
#define SAMPLING_FREQUENCY 1000000 //Ts = Based on Nyquist, must be 2 times the highest expected frequency.

arduinoFFT FFT = arduinoFFT();

unsigned int samplingPeriod;
unsigned long microSeconds;

double vReal[SAMPLES]; //create vector of size SAMPLES to hold real values
double vImag[SAMPLES]; //create vector of size SAMPLES to hold imaginary values

void setup()
{
    Serial.begin(115200);
    samplingPeriod = round(1000000*(1.0/SAMPLING_FREQUENCY)); //Period in microseconds

}

void loop()
{

    for(int i=0; i<SAMPLES; i++)
    {
        microSeconds = micros();
        val = analogRead(0);
        vReal[i] = val;
        vImag[i] = 0;

        while(micros() < (microSeconds + samplingPeriod))
        {

        }
    }

    FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
    FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
    FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);

    peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);
    Serial.println((peak-5063)/122.5);
    Serial.print(";");

i've used the included FFT library, and generated sounds with an app then verified the measured frequencies with the Spectroid app, albeit i had to put the source right at the microphone.

Related: https://arduino.stackexchange.com/questions/44868/max-sample-rate-of-an-arduino-uno

I doubt, that you really have an ADC sampling frequency of 1MHz on an Arduino Uno. 4kHz seems to be about aligned with 2x the max sample rate in the first comment of that question (niquist frequency). The ESP32 was surely suggested, because it runs on a way faster clock. Mine is set to 240MHz by default (in contrast to the Unos 16MHz). Please show us your code

here is my code :

please check the question

If you write big integer literals, make sure that they are interpreted as long. So write 1000000L instead of just 1000000. Then please try again. Also you can use micros() to measure the time, that your measurement loop actually needs. That would make sure, that you are not actually slower with sampling than you think.

So you think there's now way getting around buying another more precise card?

alright i'll try that. thanks.

so i tried the long integer type but it's pretty obvious that the UNO's sampling rate doesn't match for the job. Are there any better arduino cards? I'm only interested in the audible brandwith to suggest a device that alerts in dominance of frequencies at high intensities.

There are only few Arduino boards, which are slower than the Uno. So look at what is available for you and check the clock frequency. Research the max ADC sample rate for those boards. Then you can choose one. The ESP32 is only one possibility.

Hello sir. The output of my microphone is way too low. When measuring the span(max - min) of my signal(wich i'll use later on), the span is always around 2, and i need to cough really lough, and close to the mic for it to change. Is amplification inevitable? Because my microphonealready had an in-built amplifier?

You need a voltage between ground and Vcc of your board (5V on the Uno, 3.3V on boards like the ESP32). Fi your microphone module doesn't provide that, then you need further amplication.

when i coud loud enough the signal peak to peak can reach 2 volts, so i think the amplifier that is built-in is good enough..


text:
How can I do web hosting having all the code of the site stored on an SD?
I am carrying out this project in which the Arduino acts as a web server and hosts a website in which I show the constantly updated temperature of a laboratory.
The problem is running all this code in the Arduino: memory runs out easily.
void loop() {
  int value = analogRead(PIN_LM35);
  float temperature = value / 2.046;
  myFile = SD.open("temperature.txt");
  if (myFile) {
    Serial.println(temperature);
  }
  myFile.close();

  EthernetClient client = server.available();
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        //read char by char HTTP request
        if (readString.length() < 100) {
          //store characters to string
          readString += c;
          //Serial.print(c);
        }

        //if HTTP request has ended
        if (c == '\n') {
          Serial.println(readString); //print to serial monitor for debuging

          client.println(F("HTTP/1.1 200 OK")); //send new page
          client.println(F("Content-Type: text/html"));
          client.println();
          refreshcounter = refreshcounter + 1;
          client.println(F(""));
          client.println(F(""));
          client.print(F("<meta http-equiv=\"refresh\" content=\"2\">"));
          client.println(F("<meta name='apple-mobile-web-app-capable' content='yes' />"));
          client.println(F("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />"));
          client.println(F("<TITLE>TEMPERATURE SENSOR LAB01</TITLE>"));
          client.println(F(""));
          client.println(F(""));
          client.println(F("
TEMPERATURE SENSOR LAB01
"));
          client.println(F("
"));
          client.println(F("
"));
          client.println(F("
Arduino with Ethernet Shield
"));
          client.println(F("
"));
          if (temperature < 24) {
            client.println("
");
            client.println(temperature);
            client.println("
");
          }
          else if (temperature >= 24 && temperature <= 26) {
            client.println("
");
            client.println(temperature);
            client.println("
");
          }
          else {
            client.println("
");
            client.println(temperature);
            client.println(F("
It is recommended to activate the air conditioner.
"));
            client.println("
");
          }
          client.println(F("
Date/Time:
"));
          client.println(F(""));

          client.println("<svg width=\"1000\" height=\"250\">");
          client.println("<rect width=\"150\" height=\"5\" fill=\"gray\">");
          client.println("<animate attributeName=\"x\" from = \"0\" to =\"10000\" dur=\"10s\" fill=\"freeze\" />");
          client.println("</rect");
          client.println("</svg>");

          client.println("
");
          client.println("");
          client.println("");

          delay(1);
          //stopping client
          client.stop();
          //clearing string for next read
          readString = "";
        }
      }
    }
  }
}

I put all the code of the web page on an external SD card to save memory. However, I don’t really know how to use it from the SD card.
The problem that stops me is the fact that the site is not static, but is constantly updated with new temperature data.
How can I do that?

why you don't use F() for every string? With Arduino Uno if you use the Ethernet library and the SD library you run out of flash and SRAM very fast.

I tried, but I was running out of flash memory, too

You may want to detail what library, shield, and board you are using. Is this one of the standard AVR Arduinos? What hardware and library does it have that lets you run it as a server in the first place?

I'd suggest looking into the wifi/ethernet shield library examples or the SD card library examples. You might find one that already does what you need. At very worst you can write a loop that reads characters or lines from the card and server.prints them. Make two files on the card that abut the print line to insert the temperature value, then print File 1, Temperature, File 2.

You wrote:

the site does not have to be static but constantly updated with new
temperature data.

A good option is to use Ajax.
The basic idea is to split the site in two parts:

a static part, potentially large, which contains all the user
interface, the styling, the bells and whistles...
a tiny, dynamic part that contains the data that is constantly updated
and nothing more.

The static part would be served from the SD card when the client sends a
GET / request. The dynamic part would be served from another endpoint,
for example as a reply to GET /temperature. Serving the dynamic part
should be very simple, something like:
client.println(temperature);

Yes, just send the number as ASCII, no HTML formatting. If you ever need
to send more than one number (e.g. multiple temperatures, or temperature
and humidity), format them in JSON. No need to use a library for
that, plain print() should be cheaper and good enough:
client.print(F("{\"temperature\":"));
client.print(temperature);
client.print(F(",\"humidity\":"));
client.print(humidity);
client.print('}');

On the client side, JSON.parse() gets the data back as an easy-to-use
data structure.
Here is a minimal example of what the static part could look like.
Notice the JavaScript code sent to the client. This code is responsible
for querying the temperature every 1000 milliseconds, and updating the
Web page with the new data;
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Ajax test</title>

Ajax test

Temperature: --- °C

A few notes:

This example is purposefully minimal. You may want to add some error
checking, some decorations, some CSS and the such. Handling a
temperature-dependent color also belongs to the client code.

The example uses good old XMLHttpRequest. You may want to try the
more modern fetch API instead:
setInterval(function() {
    fetch("/temperature")
        .then(response => response.json())
        .then(data => { data_field.innerText = data; });
}, 1000);

If you are sending updates frequently enough to significantly load
your Arduino, you may want to look at Server-sent events. This
is a technique that allows you to significantly reduce the overhead of
sending data updates. It is not as popular as Web-sockets, but has the
advantage of being simpler to implement server-side.

If you can put a reverse-proxy between your Arduino and the Internet,
the proxy can handle the static content. Your Arduino then only
handles the dynamic data and wouldn't need an SD card. If you
reverse-proxy Server-sent events, make sure the proxy doesn't buffer
the server response. See for example these tips on configuring
Nginx for this purpose.

The static data could also be served from a completely different Web
site. For this to work, you have to fulfill two conditions:

The Arduino server has to add the header
Access-Control-Allow-Origin: * to its responses.

On the client code, you have to provide the full URL of the Arduino
as an argument of request.open(), fetch() or
new EventSource().

The previous trick also allows you to open the Web page directly from
your local file system, which can be very handy for developing.

Once you get the basic scheme working, Web technologies allow you to
get as fancy as you want. You could create an analogue gauge (with SVG
transform rotate). You could even add a graph, updated in
real time, that shows the time evolution of the temperature, and is
entirely handled by the client.

source: Stack Exchange

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

sort: votes


text:
Getting more Hz while working with 3 serial ports (IMU sensors)
im doing a university project where we use 2 IMU sensors and a SD card reader to save the data from sensors.
As you will probably see from the code, we specify the sensor port we listen to, save data to strings and then we open a port to SD reader and save the data.
Everything is in loop.
The problem is we only get around 5Hz (10Hz with only one sensor) - visible by the timer, which is sadly not enough for our project.
I heard about using a fifo buffer, but im not so good at low level programing. Anyway you can help?
Also, do you think removing all Serial.print could help with a little performance boost?
sensors - https://wiki.dfrobot.com/Serial_6_Axis_Accelerometer_SKU_SEN0386#target_0
uCon - Arduino Uno Rev3
#include <DFRobot_WT61PC.h>
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

#define FILE_BASE_NAME "Pomiar"
#define VCC2 7

const uint8_t CS_PIN = 4;

SoftwareSerial mySerial(2, 3);
SoftwareSerial mySerial2(5, 6);
DFRobot_WT61PC sensor(&mySerial);
DFRobot_WT61PC sensor2(&mySerial2);

File myFile;
File file;

const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;
char fileName[] = FILE_BASE_NAME "00.txt";

void setup()
{

  pinMode(VCC2,OUTPUT);
  digitalWrite(VCC2,HIGH);

  //Use Serial as debugging serial port
  Serial.begin(9600);
  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  while (SD.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      Serial.println(F("Can't create file name"));
      return;
    }
  }

  //Use software serial port mySerial as communication seiral port
  mySerial.begin(9600);
  mySerial2.begin(9600);
  //Revise the data output frequncy of sensor FREQUENCY_0_1HZ for 0.1Hz, FREQUENCY_0_5HZ for 0.5Hz, FREQUENCY_1HZ for 1Hz, FREQUENCY_2HZ for 2Hz,
  //                        FREQUENCY_5HZ for 5Hz, FREQUENCY_10HZ for 10Hz, FREQUENCY_20HZ for 20Hz, FREQUENCY_50HZ for 50Hz,
  //                        FREQUENCY_100HZ for 100Hz, FREQUENCY_125HZ for 125Hz, FREQUENCY_200HZ for 200Hz.
  sensor.modifyFrequency(FREQUENCY_100HZ);
  sensor2.modifyFrequency(FREQUENCY_100HZ);
}

void loop()
{

  long timestamp = millis();

  String acc1 = "";
  String acc2 = "";
  String acc3 = "";
  String gyro1 = "";
  String gyro2 = "";
  String gyro3 = "";
  String angle1 = "";
  String angle2 = "";
  String angle3 = "";

  String acc12 = "";
  String acc22 = "";
  String acc32 = "";
  String gyro12 = "";
  String gyro22 = "";
  String gyro32 = "";
  String angle12 = "";
  String angle22 = "";
  String angle32 = "";

  mySerial.listen();
  if (sensor.available()) {

    acc1 = sensor.Acc.X;
    acc2 = sensor.Acc.Y;
    acc3 = sensor.Acc.Z;
    gyro1 = sensor.Gyro.X;
    gyro2 = sensor.Gyro.Y;
    gyro3 = sensor.Gyro.Z;
    angle1 = sensor.Angle.X;
    angle2 = sensor.Angle.Y;
    angle3 = sensor.Angle.Z;

    Serial.print("Acc\t"); Serial.print(sensor.Acc.X); Serial.print("\t"); Serial.print(sensor.Acc.Y); Serial.print("\t"); Serial.println(sensor.Acc.Z); //acceleration information of X,Y,Z
    Serial.print("Gyro\t"); Serial.print(sensor.Gyro.X); Serial.print("\t"); Serial.print(sensor.Gyro.Y); Serial.print("\t"); Serial.println(sensor.Gyro.Z); //angular velocity information of X,Y,Z
    Serial.print("Angle\t"); Serial.print(sensor.Angle.X); Serial.print("\t"); Serial.print(sensor.Angle.Y); Serial.print("\t"); Serial.println(sensor.Angle.Z); //angle information of X, Y, Z
    Serial.println(" ");
  }

  mySerial2.listen();
  if (sensor2.available()) {

    acc12 = sensor2.Acc.X;
    acc22 = sensor2.Acc.Y;
    acc32 = sensor2.Acc.Z;
    gyro12 = sensor2.Gyro.X;
    gyro22 = sensor2.Gyro.Y;
    gyro32 = sensor2.Gyro.Z;
    angle12 = sensor2.Angle.X;
    angle22 = sensor2.Angle.Y;
    angle32 = sensor2.Angle.Z;

    Serial.print("Acc2\t"); Serial.print(sensor2.Acc.X); Serial.print("\t"); Serial.print(sensor2.Acc.Y); Serial.print("\t"); Serial.println(sensor2.Acc.Z); //acceleration information of X,Y,Z
    Serial.print("Gyro2\t"); Serial.print(sensor2.Gyro.X); Serial.print("\t"); Serial.print(sensor2.Gyro.Y); Serial.print("\t"); Serial.println(sensor2.Gyro.Z); //angular velocity information of X,Y,Z
    Serial.print("Angle2\t"); Serial.print(sensor2.Angle.X); Serial.print("\t"); Serial.print(sensor2.Angle.Y); Serial.print("\t"); Serial.println(sensor2.Angle.Z); //angle information of X, Y, Z
    Serial.println(" ");
  }

  myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc1);
    myFile.print("|");
    myFile.print(acc2);
    myFile.print("|");
    myFile.print(acc3);
    myFile.print("|");
    myFile.print(gyro1);
    myFile.print("|");
    myFile.print(gyro2);
    myFile.print("|");
    myFile.print(gyro3);
    myFile.print("|");
    myFile.print(angle1);
    myFile.print("|");
    myFile.print(angle2);
    myFile.print("|");
    myFile.print(angle3);
    myFile.println("");

    myFile.print(timestamp);
    myFile.print("|");
    myFile.print(acc12);
    myFile.print("|");
    myFile.print(acc22);
    myFile.print("|");
    myFile.print(acc32);
    myFile.print("|");
    myFile.print(gyro12);
    myFile.print("|");
    myFile.print(gyro22);
    myFile.print("|");
    myFile.print(gyro32);
    myFile.print("|");
    myFile.print(angle12);
    myFile.print("|");
    myFile.print(angle22);
    myFile.print("|");
    myFile.print(angle32);
    myFile.println("");

    myFile.close();
  } else {
    Serial.println("error opening test.txt");
  }
}

do you think removing all Serial.print could help with a little performance boost? ... why are you asking this? ... what is preventing you from doing a test?

Have you tried checking via millis() what exactly is taking so much time? And why are you saving all the data in strings? The data is of type float

Converting floats into Strings will take some time, did you benchmark this? -- To get least overhead for debugging, you can simply toggle some pin and measure the time with an oscilloscope. With respect to the communication signals to/from the sensors you will see where the time is spent.

There is a memory device called FRAM, It is available in many sizes. I work with 32Kx8 which is under $5.00 US from my favorite china supplier. No write delays, works with SPI or I2C you can get either already mounted on a PCB. For you I would recommend SPI. It is non volatile memory so it will retain the date when power fails. It is good for over 1 trillion cycles.

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


text:
How to use two timers 1 and 4 simultaneously in Arduino Mega 2560
I activated timer 1 and its interrupt on the 2560 board and it works properly. Now I want to run Timer 4 as well. I installed the Timer 4 library, but when I compile the program, I get the following error. This error also occurs for timers 3 and 5:
C:\Users\win 8\Documents\Arduino\libraries\Timer5\Timer5.cpp:110:6:
note: 'void startSlowCountingTimer5()' previously defined here
 void startSlowCountingTimer5(void) {

Thank you for your help.
The full text of the error is as follows
C:\Users\win 8\Documents\Arduino\libraries\Timer5\Timer5.cpp: In function 'void startSlowCountingTimer5()':

C:\Users\win 8\Documents\Arduino\libraries\Timer5\Timer5.cpp:127:6: error: redefinition of 'void startSlowCountingTimer5()'

 void startSlowCountingTimer5(void) {

C:\Users\win 8\Documents\Arduino\libraries\Timer5\Timer5.cpp:110:6: note: 'void startSlowCountingTimer5()' previously defined here

 void startSlowCountingTimer5(void) {

is it actually an error?

If you want to use Timer4, why did you include the Timer5 library? Please show your code and the whole error message

And also provide a link to every library that you are using

This error also occurs for each of the three timers 3, 4 and 5

I downloaded Timer 1 from the Arduino site, which worked fine.

But I downloaded the library of timers 3, 4 and 5 from this site https://github.com/carlosrafaelgn/ArduinoTimer

This is a bug in the library that was fixed in 2017! Please
upgrade.

Thank you "Edgar" for your guidance. My problem is solved.


text:
Arduino compiler shows different value of sram memory
I have this code that shows the available sram memory
    int freeRam()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

void setup()
{
  Serial.begin(9600);
  Serial.println(freeRam());
}

void loop()
{
}

The arduino compiler shows a different value.

the arduino compiler shows 1856 bytes and
Serial port shows 1850 bytes

What is the correct value?

probably both ..

Did you take the used space on the stack into account?

Both are correct depending on what value you are interested in. The compiler tells you the size of the global variables. Your code tells you how much memory is free at any one time. Running code requires memory (most often the stack growing to accommodate local variables and the "stack frame" with a copy of the CPU registers in it every time you call a function).
In other words the compiler tells you how much is in your glass when it's handed to you by the barman but your code tells you how much is in there once you have taken a sip.


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:
ESP32 Wipe Sensitive Key Data
Is it possible to ensure that keys (e.g. ssid, ssl certs) are wiped from the memory of a esp32?
I'm new to the esp32, coming from a IoT device security perspective.
Say a person was testing an esp32 application that utilized WIFI, in which sensitive keys are embedded in the firmware. They then overwrote the esp32 with a small led blink firmware in an attempt to clear said keys.
I would like to know if flashing a small "blink" program will be sufficient to remove the keys, so the esp32 could be repurposed without worry that a firmware dump would reveal past firmware information.
This question is specifically targeting scenarios where the esp32 is for development purposes (fuse bits are never burnt - mind I think there is a security flaw where chip can be dumped anyhow).

You can use esptool.py to run an erase_flash operation.

Erase Flash: erase_flash & erase_region
To erase the entire flash chip (all data replaced with 0xFF bytes):
esptool erase_flash

To erase a region of the flash, starting at address 0x20000 with length 0x4000 bytes (16KB):
esptool erase_region 0x20000 0x4000
The address and length must both be multiples of the SPI flash erase sector size. This is 0x1000 (4096) bytes for supported flash chips.
-- esptool basic commands

As far as copy protection goes you can encrypt the flash contents so even if the chip is read directly without the decryption key they won't be able to make any sense of the data.

Thanks for the information Majenko! I was wondering if in addition to your answer, if flashing blink firmware (or any other small custom firmware) will be sufficient in overwriting all existing firmware data? If true, then perhaps erase_flash will not be required.

@PathToLife I'm not sure if doing a normal code upload wipes all the flash or not. You could try doing a big upload followed by a small upload then read all the flash with esptool and see what remains of the big upload...

Is there a way to create an application that, when replaced by someone inexperienced or malicious (that is, without the erase operation) will not leak data (easily)? I speak of data stored in the NVS or LittleFS or similar. I don't want to outright encrypt the entire device, though, since that has limitations and would break "free" software.

@RDragonrydr You could manually encrypt the data you store in the NVS using your own software in your sketch. Without the keys (which are in the sketch, so would be overwritten by new code) decrypting the data would be nigh on impossible.,


text:
Why are there no clear types given on the Arduino API docs?
For exmaple, I look at the page for digitalWrite and all I get is this for the signature:
digitalWrite(pin, value)

No return value type, no paramater type, nothing.
Instead, in a seperate section it says
Returns
Nothing

And then it says
Parameters
pin: the Arduino pin number.
value: HIGH or LOW.

What is "value"? An int? uint8_t? bool? Why is the API written in such a weird ambigious way?
I would expect something like
void digitalWrite(uint8_t pin, uint8_t value)

Like I am used to from other "proper" API documentations.

Because it's written for novices by novices

I found void digitalWrite(pin_size_t pinNumber, PinStatus status);. that is why.

Most pages in Language/Functions do document the data types (I count 74 out of 137). This is more than it used to be, as documenting the types is an ongoing effort. You may participate by sending pull requests to arduino/reference-en.

See Specify data types in function definitions. I raised this issue in 2015 - that issue is still open 7 years later.

Try going to that Github page and supporting my request that the documentation be improved. Good luck!

re:"What is "value"? An int? uint8_t? bool?": all of those work in that context, so I don't see an issue.


text:
how to save float with 3 decimal places
i am transmitting sensor data from my atmega328p to my esp8266. The Sensordata has 3 decimal places. The esp8266 sends this data to my pc and there I see only two digits. This is because the data is saved with two digits in the float variables.
Is there a way to save them with 3? The way to multiply and later to divide does not work because of some issues on my pc server so I need to hand it straight with 3 digits.

This is because the data is saved with two digits in the float variables.

No, it's not. It's because Serial.println() by default prints only 2 decimal places. You can specify the number of decimal places to print in the function:
Serial.println(myVal, 3);


text:
How to efficiently code a long duration timer
I'm working on a battery-powered project. I'm trying to write code, which checks the battery voltage every 30 minutes and changes the color of a LED accordingly. Should I still be using millis() or is there a more efficient way to create a timer which tracks these longer time periods? Should I be concerned that the value of millis resets every 50 days, with an example timer like this:
bool timer(unsigned long &last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - last_time >= period) {
    last_time = now;
    return true;
  }
  return false;
}

Should I still be using millis() or is there a more efficient way to create a timer which tracks these longer time periods?

For longer time periods you really should use an RTC. You will get much better accuracy (assuming accuracy is what you want). You can also use an alarm on the RTC and use it to trigger an interrupt every 30 minutes and wake the MCU from sleep (so as to save precious battery power) to check the voltage.

Should I be concerned that the value of millis resets every 50 days, with an example timer like this:

Using that method, where you subtract the previous time from the current time, no, there is nothing to worry about. That is the recommended method to work around the wrapping of the millis() count.

thank you for responding. The board is based on the SAMD21G18A microprocessor (arduino zero). Do you think the following library will work, or would I need an external RTC? https://www.arduino.cc/reference/en/libraries/rtczero/

@ZhelyazkoGrudov That should work fine.

Thank you so much :)

There are various notions of efficiency, depending on what resource you
want to optimize for. For a battery-powered project, the most relevant
is likely to be energy-efficiency. Then, your code may not be the main
issue.
If you plan for your LED to be turned on continuously, this is going to
significantly tax your battery. Your first concern should then be to
minimize the power drain of the LED itself: make the current through it
as low as convenient, and maybe consider powering it through a DC-DC
converter in order to avoid wasting too much energy in the series
resistor. If your Arduino has a power-indicator LED, you should also
unsolder it. If it has a second microcontroller that it always on (like
the Uno), you should find a way to disable it.
Regarding the energy consumption of the CPU running your code, the only
way to be energy-efficient is to have it sleep most of the time, and
wake it up only when there is useful job to do. Unfortunately, the
Arduino core provides no standard way to sleep. You may have to look
into architecture-specific solutions, or search for a library that
abstracts this for you. On an AVR, for example, you may be able to
significantly lower the consumption by calling
sleep_mode() once within your loop(). This will put your
device in a “shallow” sleep mode, and it will be woken up by the next
timer interrupt (these happen every 1.024 ms). If you want to go to
deep sleep, you will have to arrange a wake-up source other than the
timer interrupt. An RTC could be an option. However, if you do not need
the 30 minute period to be accurate, you may as well use the
watchdog timer (which is ultra-low power) as an interrupt source.
There are many other things to be aware of when you care about power
consumption. I recommend reading Power saving techniques for
microprocessors, by Nick Gammon, which covers most of the
relevant issues. Note, however, that it discusses mostly AVR.

Thanks for the detailed answer, Edgar. Lots to unpack and consider. It's a SAMD21 based board, so I can use its library to put it into sleep, and then interrupt from the Bosch sensor to wake it up. For now will try to power LED through PWM to avoid hardware change, maybe that helps? The accuracy of the timer is not essential, so will explore watchdog vs rtc. And thank you for linking the article.

@ZhelyazkoGrudov: Yes, with PWM you can control the average current through the LED, which affects both its brightness and the battery usage.

Amazing, thank you!

A library I like for this kind of task is Ticker
#include <Ticker.h>

void batterycheck() {
    // called by battcheck ticker every 30 minutes
    // read_voltage...
    // set_led_color...
}

Ticker battcheck(batterycheck, 30*60*1000, 0);

setup() {
    battcheck.start();
}

loop() {
    battcheck.update();
}

There's no advantage over doing it manually but I found this library after writing almost exactly the same code for a project that had a bunch of timers running concurrently.

Thanks for linking this, I'll give it a test

Your posted code will never fail.
See http://gammon.com.au/millis
Let me put it this way. Does your clock "fail" at midnight?
Subtracting the start time from time now always works (even after 50 days) because of the way unsigned integers work.

Didn't know the article existed! Thanks for posting! Ashamed to admit I became one of those people asking the question. :)

Thank you @NickGammon for writing your millis article.  I use this instead of having to explain it with my arduino friends.  I figured this out myself many years ago ago and then stumbled on your explanation in your forum a few days later.  If I had just read it sooner you would have saved me some introspective head scratching.  My summary has always been "never compare times, compare durations" and "later minus earlier always works to compute durations - as long as the maximum durations of interest are within the range of the counter."


text:
Bootloader Burning Issue
I have a custom CCA that utilizes an ATMEGA328 but with an external clock of 1MHz that I originally burned the ADABOOT bootloader on using an Arduino Nano.  Everything worked as expected, only issue is I noticed the boot up time is a little long and after some research it seems that putting the Opti bootloader on may help with this.
Thus, I am trying to burn the opti bootloader onto my CCA, this time using an Elegoo Uno R3.  I successfully was able to upload the ArduinoISP sketch onto the Uno but when I go to burn the bootloader I get the following error:
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:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM7
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x03
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x03

avrdude done.  Thank you.

Error while burning bootloader.

I'm wondering if there is some sort of communication error since my custom CCA has the other bootloader on with different boards.txt settings than the default
f_cpu = 8000000L
upload speed = 7200
low fuse = 0XCB
high fuse = 0xDA
extended fuse = 0xFD
When I perform the loopback test I don't get an echo on the serial monitor.  I see both the "Rx" and "Tx" lights blink on the Uno, not sure if something is up there... Do you need to have a certain sketch uploaded for that to work?
Thanks,
Pete

did you select the programmer in Tools menu to "Arduino as ISP"?


text:
Use of ESPAsyncWebServer.h with ArduinoJson version 6 for Master-Client transactions
I want to communicate two (2) ESP32's via Json commands using ESPAsyncWeb.h. The master should have specific operations to execute and respond to the client, and the client should be able to send specific Json commands to ask questions and receive responses. I have tried the method below but is throwing me weird errors such as

cannot bind non-const lvalue reference of type 'ArduinoJson::JsonObject&' {aka 'ArduinoJson6185_91::OBjectRef&'} to an rvalue of type 'ArduinoJson6185_91::enable_if<true, ArduinJson6185_91::ObjectRef>::type' {aka 'ArduinoJson6185_91::ObjectRef'}

I am not sure how to implement the operations for sending Json and receiving response from the Server using ArduinoJson 6. If anyone could enligthen me on how to conduct such transactions I'd appreciate it.
 void setup(){

//start serial comm
//Broadcast as WiFi SoftAP

 server.on("/command", HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &json)
          {JsonObject& jsonObj = json.as<JsonObject>();
           uint8_t command = jsonObj["C"];
           String response;
           switch(command){
                           case 0: response = "{\"SCAN\":\"received_scan\"}";
                           request -> send(200, "application/json", response);
                           return;
                           case 1: /*...similar stuff */

                           case 2: /*...*/
}});
server.begin();
}

Have you tried following the examples in the ESPAsyncWebServer documentation? The code you used is different from the example.

cannot bind non-const lvalue reference of type 'ArduinoJson::JsonObject&' {aka 'ArduinoJson6185_91::ObjectRef&'} to an rvalue of type 'ArduinoJson6185_91::enable_if<true, ArduinJson6185_91::ObjectRef>::type' {aka 'ArduinoJson6185_91::ObjectRef'}

In other words, "cannot assign JsonObject to JsonObject&".
The compiler refuses to save a reference to a temporary variable because the reference would inevitably dangle.
To fix this issue, you must remove the ampersand (&) after JsonObject, like so:
JsonObject jsonObj = json.as<JsonObject>();

And it would be best if you also did the same for JsonVariant.
BTW, the cast from JsonVariant to JsonObject isn't necessary in your case, so you could simplify your program to:
server.on("/command", HTTP_POST,
          [](AsyncWebServerRequest* request, JsonVariant json) {
            switch (json["C"].as<uint8_t>()) {
              case 0:
                request->send(200, "application/json",
                              "{\"SCAN\":\"received_scan\"}");
                return;

              case 1: /*...similar stuff */

              case 2: /*...*/
            }
          });

I recommend that you have a look at ArduinoJson's documentation; I heard it's pretty good ;-)


text:
How to use Sim7020_mini NB-IOT module

I bough Sim7020_mini module. I put IOT Sim card, and plug-in antenna,
connect Rx,Tx into USB-TTL, then put supply into VIN (5 volt), LED
power was lid on. Arduino Serial Monitor set into 115200, but no
character appear, also I enter AT, no answer. I already making sure my
wiring. Measuring STATUS pin 42 showing 1.8 volt, means not active.
Schematic look like wrong, according to sim7020 Hardware design v1.02,
to put SIM7020 to On we should give LOW pulse 1 second into PWRKEY.
But STATUS pin still 1.8 volt.
May anyone has successful using this such module? Any clue?

First question about using SIM7020_mini Module
Thank you @hcheung for clue about 1.8 volt.
The SIM7020_mini module already equipped with logic level shifter between 1.8v and 3.3v.
I know SIM 7020C already Up, pin STATUS (42) is HIGH, pin NETLIGHT (41) blinking.
Here is my schematic, I just want to enter AT Command first. But on my Serial Monitor (Arduino) doesn't show any character received.

simulate this circuit – Schematic created using CircuitLab
When I type 'AT' it's echoed back to screen Serial Monitor. When I reverse Tx/Rx between SIM7020_mini module and USB-TTL, no character echoed. When I restart SIM7020_mini module, there is no character received by Serial Monitor.

Can you provide a picture of all the header pins naming? or a link to where you purchase the module?

Pin Header 1: VIN, GND, PCE, GIO1, RESET, TXD, RXD
Pin Header 2: VBAT, GND, DTR, RI, RGIO0, EINT, DET
SIM7020_mini module

VBAT: Lithium battery input positive 3.7-4. 2V
GND: Lithium battery input negative
DTR: Control module sleep and wake up
RI: Ringing indicator
RTC_GPI0O: PSM mode indication, before and after entering PSM mode, the pin changes from high to low
RTC_EINT: wake up from PSM mode, when this pin changes from high to low, exit PSM mode
SIM DET: SIM card insertion detect
VIN: Power input positive 5V (1A)
GND: negative power
PCE: Power enable control
GPI01: General purpose input/output port
RESET: reset control
TXD: Serial transmission
RXD: serial receiver

My fault, AT command on Serial Monitor (Arduino IDE) should be ending with Carriage Return, while my Serial Monitor using New Line
Thank you for responses.


text:
Using a 5 pin button with Arduino Correctly
I am trying to build a simple motor test sketch, currently, to test a NEMA 23 stepper motor and the DM542T stepper driver.
Here is the code, and I am having trouble figuring out how to properly wire the 5-lead button (+, -, Common, NO, NC)
Here is the code
// Pin numbers
const int buttonPin = 2;
const int directionPin = 8;
const int stepPin = 9;

// Other constants
const int NumSteps = 5000; // steps
const int Speed = 500;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(directionPin, OUTPUT);
  pinMode(stepPin, OUTPUT);
  digitalWrite(directionPin, LOW);
  digitalWrite(stepPin, LOW);
}

void loop() {
  if (digitalRead(buttonPin)) {
    // Move in one direction
    for (int distance = 0; distance < NumSteps; distance++) {
      digitalWrite(stepPin, HIGH);
      delayMicroseconds(Speed);
      digitalWrite(stepPin, LOW);
      delayMicroseconds(Speed);
    }
   // Reverse direction
   digitalWrite(directionPin, !digitalRead(directionPin));
 }
  delay(5);
}

The button is a momentary button, so I am holding it in to simulate a latching button.
I have the buttons Common and Neg leads wired together, and connected to the Gnd pin on the Arduino (mega rev3)
I have the buttons Positive and the NC wired together and connected to pin 2.
Wiring that button in that manner, works fine in the button-controlled blink sketch, but is not working here (LED on the button doesn't light up and the motor test doesn't run).
Note: I am using a 5 lead momentary button as that what the project these motors will be for will be using.
Any help appreciated.

Can you link to the buttons product page or datasheet? A simple button with 5 pins is not very common, so it is important how the button is  using the pins.

There is no datasheet for it. It is a standard 5 lead LED button with +,-,common,NC,NO. It worked fine when wired for the button controlled blink sketch with NO not connected, NC and + wired together to 5V and Common and - wired together to Gnd. The led on the button lights up and the led on the Mega lights up when you press the button

Oh, haven't seen, that it is an LED button. Can you please make a diagram which connections you really have? It is difficult to interpret with the text (and you have different wirings in the question and your comment). You can also use the builtin schematic editor of the question editor. Use a normal switch and an LED to simulate your 5 pin switch

first thought, do not connect the LED to the switch .... second thought, if the button works in a blink sketch, then use the working switch code in the motor sketch

You don't need a sketch to control the on-board LED. Just wire the + to 5V and the - to Gnd and the button will turn the on-board LED on/off. If it's an LED halo or lighted button combine the NO and + to 5V and the common and - to Gnd.

The button's pins are as follows:

+: The LED's anode
-: The LED's cathode
C: The common pin of the switch
NC: Normally Closed - is normally connected to the C pin until the button is pressed
NO: Normally Open - is connected to the C pin when you press the button

So to use the button as a button the two pins you care about are C and NO. Use those pins (in any order) as you would any normal button with a pullup resistor (or the internal INPUT_PULLUP resistor).
To use the LED can be a little more tricky. Most of this style of button have the LED set up for 12V usage. While you may get a slight glow from it from 5V you would probably need to switch it with a transistor and power it from 12V to get it to light up properly. However your button may be rated differently and need a different voltage.

So, in this case which would you use as the signal and send to pin 2, the NO wire or the common? The other would go to Gnd I believe.

@dinotom It really doesn't matter. They are just lumps of metal that touch when you press the button, and since you're not using the NC pin which is which for C and NO makes absolutely no difference.

Yep, used the NO to pin 2 and the C to Gnd, serial monitor shows it changing. Onto the next problem, the button isn't turning the motors on. Connecting pos to 5V and Neg to Gnd does get the light on the button to flicker, weird it works as described before. Ill post a different question later if I can't figure that one out myself. Motors first.


text:
Is it legal to "simulate" Yubikey OTP autentication with an Arduino in own product?
I found the following Github Repo that makes it possible to build your own Yubikey with an Arduino Leonardo device.
https://github.com/pagong/arduino-yksim
Pretty cool. However I am wondering if using this is legal at all?
YubiCo is a company and they sell sticks with the YubiKey OTP feature. The verification process happens through their servers. Somehow I can't quite imagine that the company YubiCo tolerates that their processes and products could be easily replaced by open source products? Maybe they have any patents or utility models? And I was not able to find any licensing information which makes sense since official firmware seems to be closed source. So I guess it makes sense that no licensing information is available since the yksim project is a reverse engineered thing?! But I'll admit quite frankly: I have no idea of all this.
I would also like to use this library and possibly also for my customer projects, but I need to know whether this is really allowed.
Hope someone can help me here and I know that the internet is no source for a 100% sure legal advice. But maybe someone has a clue or a hint for me.

This is the wrong forum, go to https://law.stackexchange.com/

https://opensource.stackexchange.com/ would be another place that might have good insight into this.

According to https://www.yubico.com/blog/secure-hardware-vs-open-source/

The YubiKey hardware with its integral firmware has never been open sourced, whereas almost all of the supporting applications are open source.

I am not a lawyer, however it would seem that providing you aren't copying their (non open source) hardware, but are merely replicating the functionality, then this would appear to be OK. Disclaimer: I may be wrong.
Having said that, I agree with the comment under the question, you should probably ask at https://law.stackexchange.com/
Questions about the legality of an Arduino application really are legal questions, not technical ones.


text:
Linux avrdude: stk500_getsync()
When trying to flash my genuine arduino micro with avrdude from cmd on a Manjaro system I get the infamous error
avrdude: stk500_getsync() attempt x of 10 ...
Im adding this post to the many other that ask about this error because all of them are trying to use the IDE to flash the arduino, whereas I can use it no problem on both Linux and Windows, but when using avrdude from cmd on Linux I get this error. This confirms that the board is fine and there are no shorts on the reset pin or any other possible physical cause of this issue, something appears to be wrong in the avrdude configuration.
This is my Makefile:
default: build

build:
    avr-gcc -mmcu=atmega32u4 main.c -o main

flash:
    avr-objcopy -O ihex -R .eeprom main main.hex
    avrdude -F -V -c arduino -p m32u4 -P /dev/ttyACM0 -b 115200 -U flash:w:main.hex

Can you suggest anyway to fix this?
EDIT:
Problem Solved!
The error was in the -c parameter, for the atmega 32u4 it's supposed to be avr109 and not arduino.

In the IDE you can set the preference for verbose output on upload, and then watch the log. It might show all commands that the IDE uses.

There are two common ways of resetting an Arduino into the bootloader:

For UART based boards (Uno, Mega2560 etc) just opening the port resets the board
For USB based boards (Micro, etc with the 32u4 chip) you have to manually tell it to reset

Yours is option 2 - unless you tell it to reset the board it won't do anything. The IDE normally handles that for you.
But it's simple: just cause the CDC/ACM port to be opened at 1200 baud and closed again. The simplest method is to use stty to do it for you:
stty -F /dev/ttyACM0 speed 1200

You should find that it then resets the board. Adding a short delay to allow the USB to reset would be good too. So your whole programming routine could look something like:
flash:
    avr-objcopy -O ihex -R .eeprom main main.hex
    stty -F /dev/ttyACM0 speed 1200
    sleep 1
    avrdude -F -V -c arduino -p m32u4 -P /dev/ttyACM0 -b 115200 -U flash:w:main.hex

In Makefiles I find it useful to set the port as an overridable variable:
PORT?=/dev/ttyACM0

Then use ${PORT} everywhere instead of /dev/ttyACM0 - then you can use make PORT=/dev/ttyACM1 if you need to without having to edit the Makefile. Great if you have multiple boards.

I was indeed thinking about the reset, thanks for the explanation! When I run the flash command the I get the following and then it stucks without going any further: avr-objcopy -O ihex -R .eeprom main main.hex \n stty -F /dev/ttyACM0 speed 1200 \n 9600 \n What is this about?

This Arduino Makefile comes with a small script that does exactly this on a Micro, and has different logic for other board types.

@EdgarBonet I'm trying to learn low level programming, thats why I'm doing it with a MakeFile, I don't want to use a python script.


text:
What is wrong with the way I write and or read the EEPROM adresses?
Consider:
#include <EEPROM.h>

byte guifactor1 = 1;
byte guifactor2 = 2;
byte guifactor3 = 3;
byte guifactor4 = 4;
byte guifactorgas = 5;
byte guifactorwater = 6;

volatile unsigned long count1factor;
volatile unsigned long count2factor;
volatile unsigned long count3factor;
volatile unsigned long count4factor;
volatile unsigned long countgasfactor;
volatile unsigned long countwaterfactor;

void loop(){
if (guifactor1 > -1){
    EEPROM.write(1, guifactor1);
    EEPROM.commit();
    count1factor = EEPROM.read(1);
    Serial.println(count1factor);
  }

  if (guifactor2 > -1){
    EEPROM.write(2, guifactor2);
    EEPROM.commit();
    count2factor = EEPROM.read(2);
    Serial.println(count2factor);
  }

  if (guifactor3 > -1){
    EEPROM.write(3, guifactor3);
    EEPROM.commit();
    count3factor = EEPROM.read(3);
    Serial.println(count3factor);
  }

  if (guifactor4 > -1){
    EEPROM.write(4, guifactor4);
    EEPROM.commit();
    count4factor = EEPROM.read(4);
    Serial.println(count4factor);
  }

  if (guifactorgas > -1){
    EEPROM.write(5, guifactorgas);
    EEPROM.commit();
    countgasfactor = EEPROM.read(5);
    Serial.println(countgasfactor);
  }

  if (guifactor1 > -1){
    EEPROM.write(6, guifactorwater);
    EEPROM.commit();
    countwaterfactor = EEPROM.read(6);
    Serial.println(countwaterfactor);
  }
}

void setup(){

}

The problem I have with my code is that it either doesn’t write the value to the EEPROM or it doesn’t read the value as it doesn’t print anything to the monitor.
I expected to read 1 2 3 4 5 6 from the monitor as I write the bytes to the EEPROM and then transfer the value to the unsigned long and print the variable.

What problem do you actually have? You didn't include any problem description. From your code I would say: guifactor1 and its siblings will be implicitly initialized with zero (since they are global and you don't explicitly initialize them). Checking guifactor1 > -1 won't ever be true, since you initialized them to zero and don't change them anymore, and also they are unsigned longs, so they cannot ever carry a negative value. You should rethink the logic of your program.

What does it print to Serial?

Your problem description is still too vague. Please describe exactly what you expected the code to do and what is actually did. Provide the expected and actual output. And write a minimal compilable example code, that shows your problem. We cannot debug code that we cannot see

What is the sense behind the if statements? guifactor1 and siblings still cannot ever be -1, since byte is the same as unsigned char which also cannot hold negative values. Also you still don't change these variables ever. So you won't see anything. The code inside the if statements is never reached

the question was about the reading and writing to the eeprom i have not given all of my code and it isnt finished i was just testing

If you are asking just about the code lines reading and writing the EEPROM, then the answer is "Nothing is wrong with it." The problem must be somewhere in the code that you refuse to show. And we just cannot help you with that. Our mind reading powers are limited.

the problem is solved

You know that EEPROMs are limited in the number of write operation, do you? As you're writing to EEPROM in loop without any delay, this code is one way to kill the EEPROM quite fast.

If your problem is solved, please mark the answer. Or if it does not answer your question, write an own. This site is to help many, not only you.

You forgot to call Serial.begin() in setup().
As a side note, your if tests are useless. The compiler warns me that:
comparison is always true due to limited range of data type

For reference: the previous answer, valid for the initial question
where guifactor1 and co. were all unsigned long.

The program does nothing because all the actions are conditioned on
tests such as
if (guifactor1 > -1)

and these tests are always false. The reason they are false is because
arithmetic comparison operators such as < perform usual arithmetic
conversions on their operands prior to doing the actual
comparison. Since guifactor1 is unsigned long, and this type has a
higher conversion rank than int (the type of -1), the second operand
is implicitly converted to unsigned long, yielding ULONG_MAX.

this is not my entire code. i didnt upload all of it because it could be a bit overwelming. i edited the code above so that the problem is a bit more clear i also changed the unsigned long to a byte.

@JayvandeWetering: Please, test the program you posted (not your original code, but the exact code that is in your question, as you just amended it) and make sure it does show the incorrect behavior.

i have tested the program i posted and it still either doesnt write or doesnt read from the eeprom

@JayvandeWetering: How do you know it doesn't write or doesn't read? Please update your question with the relevant details.

i think i updated the question enough so that it is clear what is expected and what is the actual output


text:
Sending float values from Python to Arduino using Serial communication
I need to send an array of floating-point numbers from python to Arduino Mega. For that, I read many sources [this this this this this] this] and many more links for the same I referred. But unable to solve the problem.
I tried to send the angles to Arduino through python and return these values to python to print.
Below is the Python code in which I try to send the array named angle and tries to print the values received from Arduino.
import cv2
import numpy as np
import serial
import struct
import time

ser = serial.Serial('COM3', 9600, timeout = 1)
time.sleep(2)
if(ser.isOpen() == False):
    ser.open()
print('com3 is open', ser.isOpen())

angle = [120.2,154.2,14.25]
ser.write(struct.pack('>fff', 10.5,11.9,48.2)) # B for interger and f for float
#ser.write(struct.pack('>f', angle)) # B for interger and f for float

time.sleep(2)
ser.flush()

data = ser.readline()
data = str(data.decode("utf"))
print(data)

ser.close()

Below is the Arduino code:
float f1; float f2; float f3;

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

Serial.println("Arduino is in parseFloat!");
}

void loop() {

  if (Serial.available() > 0)
  {
    d1 = Serial.parseFloat(); d2 = Serial.parseFloat(); d3 = Serial.parseFloat();

    ad = d1 +2.5;
    Serial.println(ad)
  }
delay(2000);
}

The error I got is:
I got no error or warnings but there is no output also for the print commands as shown in below Figure.

I need help to send the values to Arduino using python.

You seem to be sending binary instead of text.

You aren't giving your Arduino time to reboot after opening the serial port and before sending it any data...

There are two things going on here.
First of all, if you look up the readline() method in Python that is referenced in the PySerial manual, you'll see the following:
readline(size=- 1, /)

Read and return one line from the stream. If size is specified, at most size bytes will be read.
The line terminator is always b'\n' for binary files; for text files, the newline argument to open() can be used to select the line terminator(s) recognized.

In your program, you are actually sending more than one line back to serial port from the Arduino. The first line is the ASCII-encoded "Arduino is in ParseFloat!". The second one is the test float calculation. If you don't account for the fact you are expecting multiple "lines" from the serial port,  you wouldn't see the test calculation, because you are not actually reading it. For encoded data, it states that the line ends at the '\n' char/digit (10).
Try it out change the "println" to "print" in your Arduino program and add another message either in the setup or the loop. Run your Python program. What do you see? Now change the "print" back to println". Run your Python program again. What do you see now?
Secondly, Edgar Bonet points out the second issue. The write() method in the PySerial API requires data to be a bytes array, but it's the way you are encoding it. It seems that the Arduino Serial class expects a ASCII-encoded byte-array, rather than a float byte-array (the floats encoded as a single-precision floating point number), which is what you are sending.
If you change your code to something like this (for example):
angle = [120.2,154.2,14.25]
ser.write(str(angle).encode('utf-8'))

you should be able to see your test calculation come back, granted that you read what I wrote in the first part of this answer.

By removing println, I successfully send and receive values.


text:
Ubuntu Serial Port Briefly showing on arduino IDE
I am using a NodeMcu with Arduino IDE on Ubuntu.
I have managed to upload the blink script and it work.
Now, when i plug the nodemcu, the serial port /dev/ttyUSB0 is briefly available in the IDE.
After 2 seconds, the port menu is grayed out again and I can't use it.
Same with ls /dev/tty* /dev/ttyUSB0 is briefly available.
/dev/tty    /dev/tty23  /dev/tty39  /dev/tty54      /dev/ttyS10  /dev/ttyS26
/dev/tty0   /dev/tty24  /dev/tty4   /dev/tty55      /dev/ttyS11  /dev/ttyS27
/dev/tty1   /dev/tty25  /dev/tty40  /dev/tty56      /dev/ttyS12  /dev/ttyS28
/dev/tty10  /dev/tty26  /dev/tty41  /dev/tty57      /dev/ttyS13  /dev/ttyS29
/dev/tty11  /dev/tty27  /dev/tty42  /dev/tty58      /dev/ttyS14  /dev/ttyS3
/dev/tty12  /dev/tty28  /dev/tty43  /dev/tty59      /dev/ttyS15  /dev/ttyS30
/dev/tty13  /dev/tty29  /dev/tty44  /dev/tty6       /dev/ttyS16  /dev/ttyS31
/dev/tty14  /dev/tty3   /dev/tty45  /dev/tty60      /dev/ttyS17  /dev/ttyS4
/dev/tty15  /dev/tty30  /dev/tty46  /dev/tty61      /dev/ttyS18  /dev/ttyS5
/dev/tty16  /dev/tty31  /dev/tty47  /dev/tty62      /dev/ttyS19  /dev/ttyS6
/dev/tty17  /dev/tty32  /dev/tty48  /dev/tty63      /dev/ttyS2   /dev/ttyS7
/dev/tty18  /dev/tty33  /dev/tty49  /dev/tty7       /dev/ttyS20  /dev/ttyS8
/dev/tty19  /dev/tty34  /dev/tty5   /dev/tty8       /dev/ttyS21  /dev/ttyS9
/dev/tty2   /dev/tty35  /dev/tty50  /dev/tty9       /dev/ttyS22  /dev/ttyUSB0
/dev/tty20  /dev/tty36  /dev/tty51  /dev/ttyprintk  /dev/ttyS23
/dev/tty21  /dev/tty37  /dev/tty52  /dev/ttyS0      /dev/ttyS24
/dev/tty22  /dev/tty38  /dev/tty53  /dev/ttyS1      /dev/ttyS25

After 2 seconds:
/dev/tty    /dev/tty23  /dev/tty39  /dev/tty54      /dev/ttyS10  /dev/ttyS26
/dev/tty0   /dev/tty24  /dev/tty4   /dev/tty55      /dev/ttyS11  /dev/ttyS27
/dev/tty1   /dev/tty25  /dev/tty40  /dev/tty56      /dev/ttyS12  /dev/ttyS28
/dev/tty10  /dev/tty26  /dev/tty41  /dev/tty57      /dev/ttyS13  /dev/ttyS29
/dev/tty11  /dev/tty27  /dev/tty42  /dev/tty58      /dev/ttyS14  /dev/ttyS3
/dev/tty12  /dev/tty28  /dev/tty43  /dev/tty59      /dev/ttyS15  /dev/ttyS30
/dev/tty13  /dev/tty29  /dev/tty44  /dev/tty6       /dev/ttyS16  /dev/ttyS31
/dev/tty14  /dev/tty3   /dev/tty45  /dev/tty60      /dev/ttyS17  /dev/ttyS4
/dev/tty15  /dev/tty30  /dev/tty46  /dev/tty61      /dev/ttyS18  /dev/ttyS5
/dev/tty16  /dev/tty31  /dev/tty47  /dev/tty62      /dev/ttyS19  /dev/ttyS6
/dev/tty17  /dev/tty32  /dev/tty48  /dev/tty63      /dev/ttyS2   /dev/ttyS7
/dev/tty18  /dev/tty33  /dev/tty49  /dev/tty7       /dev/ttyS20  /dev/ttyS8
/dev/tty19  /dev/tty34  /dev/tty5   /dev/tty8       /dev/ttyS21  /dev/ttyS9
/dev/tty2   /dev/tty35  /dev/tty50  /dev/tty9       /dev/ttyS22
/dev/tty20  /dev/tty36  /dev/tty51  /dev/ttyprintk  /dev/ttyS23
/dev/tty21  /dev/tty37  /dev/tty52  /dev/ttyS0      /dev/ttyS24
/dev/tty22  /dev/tty38  /dev/tty53  /dev/ttyS1      /dev/ttyS25

How can I fix that? I have try all the usb ports.
The NodeMCU settings:

Actually Using Ubuntu 22.04 LTS
EDIT:
While running sudo dmesg -w and connecting the mcu I get:
[ 3726.038486] usb 1-1: new full-speed USB device number 13 using xhci_hcd
[ 3726.220532] usb 1-1: New USB device found, idVendor=10c4, idProduct=ea60, bcdDevice= 1.00
[ 3726.220536] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 3726.220537] usb 1-1: Product: CP2102 USB to UART Bridge Controller
[ 3726.220538] usb 1-1: Manufacturer: Silicon Labs
[ 3726.220539] usb 1-1: SerialNumber: 0001
[ 3726.229998] cp210x 1-1:1.0: cp210x converter detected
[ 3726.231005] usb 1-1: cp210x converter now attached to ttyUSB0
[ 3727.565688] usb 1-1: usbfs: interface 0 claimed by cp210x while 'brltty' sets config #1
[ 3727.566375] cp210x ttyUSB0: cp210x converter now disconnected from ttyUSB0
[ 3727.566391] cp210x 1-1:1.0: device disconnected

the USB device here is the USB chip on the NodeMcu board, not the esp8266,

You may tail -f /var/log/syslog right before plugging in the board, and see if anything interesting shows up.

sudo dmesg -w will show you what's going on. Maybe it's shutting down the port because it's drawing too much current?

I have edited the post with result of the command.

From these logs, it looks like the brltty daemon tried to mess with the serial port. Can you disable this daemon and try again?

I had this same problem and eventually I traced it down to two bad cables. It would appear, up then the port would disappear or change so the serial monitor would fault. Try several cables, it is the easiest solution if it is the problem. I generally do not unplug the cable from the Arduino, just the USB one and leave cables on each of the Arduino.

This could be happening because Brltty application. Remove it and try again.
sudo apt remove brltty
sudo apt autoclean && sudo apt autoremove

brother you don't know you just saved my life
for the last 2 days i was looking for this

I'm glad about it...


text:
Why the led is always on in proteus?
I am simulating a circuit with arduino, which determine if there is current at input, then turn the led on at the output. The problem is the light is always on even when the button is open at the input.

This is my code:
void setup() {
  pinMode(7, OUTPUT);
  pinMode(8, INPUT);
  digitalWrite(7, LOW);
}

void loop() {
  int on = digitalRead(8);
  digitalWrite(7, on);
}

Why does this happen and how do I solve it?
Any help would be appreciated.

What happens when you add a pulldown resistor to your input pin (a resistor like 10k from input pin to ground)

And are you trying to connect 10V to an Arduino input? Thats bad. In reality that would destroy the input pin hardware

@chrisl I get it. But in reality, does it randomly still work like in simulation or the input pin just die immediately?

At 10V I would guess: Yes it will die immediately. As I remember there are clamping diodes integrates into the pins hardware, which let the overflow voltage dissipate. They will get destroyed, though we cannot know if they fail short or not

Microcontroller inputs don't detect the presence of current. They compare a voltage to a threshold.
In reality the input pin is closest to a capacitor. You press your button and it charges that capacitor to above the threshold voltage for "HIGH". Then you release the button but that capacitor remains charged and still reading "HIGH". You need something to reduce the charge on that capacitor to below the "LOW" threshold voltage.
This is most normally done with a resistor between the GPIO pin and GND which will "bleed off" that charge and give you a LOW reading when the button is released.
This is a "pull down" resistor (you can also reverse it and have a "pull up" resistor and the button connected to GND) and is an essential part of any input that doesn't itself generate both the HIGH and LOW voltages required (any switch or button).
Also 10V on a GPIO pin will destroy your Arduino.

I have added a 10k resistor which connect ground and input pin as you and chrisl suggest and it works well. But about 10V source, why does my circuit still work, why proteus doesn't warn me about that?

@Becker It's only a simulation - an approximation. They probably just didn't think people would do that sort of thing and didn't program it to warn you.

I get it. Thanks a lot for your answer.


text:
Arduino + Solar Charger Shield V2.2: Battery and Solar panels selection
first of all I would like to apologize for the, probably very basic and stupid questions for you, but I'm not an electronic expert..
I'm implementing my project using an Arduino Mega 2560 (I need more pins.. this is the most important reason that it drives the Arduino choice)
I'll put my project in an external environment without the electricity source. For this reason my idea is to use a battery with a solar panel as power input to charge the battery.
I also applied some low-power techniques in order to reduce energy consumption as much as possible.
Regarding the solar panel and battery connections I purchased this Arduino Solar Shield.
Solar Charger Shield V2.2 - Seeed Wiki
And here I'm a bit (a lot) confused about the choice of the battery and the solar panel(s) to be purchased.
First of all, my idea is to use multiple (2 or 4) solar panels in order to exploit as much as possible the solar light (multiple positions) but I'm not able (I'm not sure) about the solar panel selection to purchase.
Considering that the maximum current that the solar shield could be delivered is 700mA can I use 4 solar panels like this
https://www.seeedstudio.com/1W-Solar-Panel-80X100.html
(applying also 4 applying 4 diodes to avoid reverse current)?
About this the possible number or size of the solar panels Do I need to consider the amount of th Current at Peak Power?
For example, using 4 solar panels with 170mA as Current at Peak Power, 4*170 = 680 that it's > of the current of the solar shield.
So, is this wrong? Do I reduce the amount of the panels or do I use a different panel?
About the Solar input voltage it's 4.8~6V.
These are the specifications about the solar panel:
Dimensions: 100x80x2.5(±0.2) mm
Typical voltage: 5.5V
Typical current: 170mA
Open-circuit voltage: 8.2 V
Maximum load voltage: 6.4V
Maximum load voltage, Open-circuit voltage are > Solar input voltage. Is it a risk?
About the lipo battery, can I use a battery 3.7v and about the mAh value as high as possible (for example this https://www.amazon.it/2100mAh-Lithium-Polymer-Replacement-Bluetooth/dp/B095BTSMYH/?th=1 ?)
What about the maximum current value (in this case 5A)? Is it ok?
In case, can you suggest me something else?
** *********** EDIT *********** **
As suggested I'm updating my question in order to give additional info about my scenario.
My project will be installed in an external environment (with some atmospheric protections IP67).
The location, from solar irradiation point of view, it's a good place: https://globalsolaratlas.info/detail?m=site&c=40.283716,17.586365,9&a=18.056138,39.997805,18.056138,40.420456,18.535172,40.420456,18.535172,39.997805,18.056138,39.997805&s=40.11799,18.382874
About my project:

I'll have to take the measurements from more sensors:
starting from 1 to 10/15 humidity/temperature (DHT22) sensor;
starting from 1 to 10/15 load cells (4 load cells for each HX711);
I'll send the data using some transmissions using a LORA Shield.

I don't need to retrieve the measurements continuously or in very short periods.
The idea is to sleep my Arduino (in low power with all power sensors disconnected) and, using a RTC DS3231 module, to wake-up it on regular intervals, read the data, send it via LORA and go to sleep again.
The idea is to wake-up every 15 minutes. The time that I imagine about the measurements and the send will take a few seconds (around 30s in case I can approximate it to 1 minute).
And at the moment I don't have the exact measurements about the used current (because I can connect all here.. but I need to purchase the solar panels and the battery in order to make a real test also)..So, the idea now is to approximate.. In case I can adjust something later.
At the moment, measuring the current I have.
around 0.35mA when the Arduino is sleeping.
I probably can reduce it again because I have to remove 2 power led indicators (1 on my DS3231, one on my LORA shield... and, in case, also the power led on my Arduino).
When the Arduino works (live mode) probably I can consider around 90/100mA (probably this is too much) for 30s).
I'm not expert but, using this values I calculated the average about the used current in 1 hour:
((100mA * 4 minutes) + (0,35mA * 56 minutes)) /60 = 7mA/m
420 mA/h
I'll need 5v about the voltage.
I don't have any limitation about the size or the space.
I think that considering 7days without solar power supply or bad water conditions could be enough (in my opinion it's too much)

This is a question that's better suited for the electrical engineering SO, but I can give you some pointers to reword and re-post your question so it's not as broad.
Right now you have a few unknown variables to juggle, so you should be jotting down your thoughts on all of the following:

Where will the unit be placed and/or located? How long do you expect it to go without needing to have its battery recharged?
What is the continuous power consumption? You should know your approximate continuous current consumption and at which voltage you will be running the Arduino and the sensors that you connect to it
What environmental conditions do you expect the unit to experience? Do you have a limiting factor on size or space?
How much are you willing to pay?

You can definitely use multiple solar panels, but you'd have to connect them in parallel (so they maintain the same voltage), and even then, the linked charger shield can only go up to 900 mA of charging current. The 600-700 mA is the supported power output of the battery, or the max current that the shield can provide to your system thru the shield. It can be larger if you lower the system's voltage and stay within the maximum limits of the charger shield.
With regards to your second question, yes, current at peak power is a good metric for your approximations. If you go thru my questions, you will know how much your systems consumes in a day and choose a battery that can discharge no more than X amount of percent per day (depending on the type of battery). Your goal is to be able to charge that battery back at least close to its full capacity--your solar panels or the amount of thereof, as well as your charger, will be dictated by that.
For the Voc of the solar panel - ideally, it would be less than the solar input voltage. It's the voltage of the panel without a load connected to it. Of course, you will have a load connected to the solar panel and thus the typical voltage will be around what's stated, but if you don't want to damage your charger, you have to make sure your SP will be properly loaded under most conditions! It will be safer to connect multiple smaller SPs to get the current that will keep the system up and charge your battery.
With regards to the battery current - you have to check which current it is. Is it the charging current? Output current? Be mindful that you are limited by your charger in this case (3W output, 900 mA charging current).
Hope this gives you a start! It's a good question, but you need to do some more reading and you need to have a better idea of the design for your system before we can be more helpful.
Edit:
Per the updated information...
I will use your estimates, but do consider that for sensors that require power, you can add them and make your calculations more accurate. Also, while LoRA is low-power, it will consume some power too, and you can factor that in.
Let's assume your numbers are correct and the average current consumption averages out to ~ 420 mA/h. Then, if you want to  keep the system alive for 7 days, you'll need a battery with a capacity of 420 mA/h * 24 hours/day * 7 days -> 70,560 mAh or 70.560 Ah. At 5 volts, your system effectively requires 0.420 A/h * 5 V -> 2.1 Watts/hour  (finicky units here, eh?). That would translate to ~353 Watts/week. Also, 5V means you will need a battery that can provide that voltage - a lower voltage battery will not support your system.
The next thing you have to consider then is the battery type - there are a few, but the ones I'd go for are either Li-ion or VRLA (valve-regulated lead acid). There is a tradeoff between cost - Li-ion batteries cost more, but they are typically better in the majority of factors rather than SLA (sealed lead acid) batteries. Doing some googling, you could get a 70-100 Ah SLA/VRLA for ~$200-300 and a Li-ion for ~$400-500. Do note, however, that you can discharge Li-ion batteries more deeply than VRLA ones - it's recommended to keep the charge on the VRLA batteries around ~50% and preferably around ~75% to extend its life. You can discharge Li-ion batteries up to 80% or a bit more and that's fine, they don't suffer as extensive reduction in their lifetime like SLAs.
To put that into perspective, if you have an application that requires ~8 Ah, then ideally for a VRLA you'd need to size a battery such that it doesn't go below 50% for your worst-case application scenario. That is, if you think you'll need the device to run for 7 days without any sun, then you'll need a battery of a 16 Ah capacity or more. Even bigger if you want to extend its lifetime. For Li-ion, aiming at a bit higher than 8 Ah should be fine. For your application, that means getting a SLA battery that's > 140 Ah (unless it's a deep discharge SLA battery) or a Li-ion battery that's close to 70 Ah.
Now, it must be noted that most batteries that provide those capacities typically come in 12V, so you would have to add a buck-converter to convert from 12V to the battery voltage your charger needs (3-4.5V). The charger you linked states that it can provide up to 3W out, which is 600 mA max at 5V. That would support your application as your average current draw is less than 600 mA.
For charging, however, you have to keep in mind that your system, on average, draws 420 mA/hour. So the charger's charging capabilities would actually be 900 - 420 -> 480 mA/hour. That means that based on worst-case considered direct solar irradiation hourly data in the link you provided, you'd get ~ 8 hours of direct sunlight (again, worst case!). So 8 hours you can charge -> 480 * 8 = 3840 mAh and you'll lose 6720 (420 * 16) mAh. That is not good, because you're losing the charge on the battery each day.
That means 2 things -  you have to get a charger that permits a larger charging current within the maximum charging current of the battery rating AND you have to get enough panels (OR a big enough panel) to be able to provide that current. With the panels that you linked, the max current per panel is ~170 mA for the typical voltage of 5.5V. To provide a charging current of ~ 900 mA, you'd need 5 panels, but as mentioned above, that still wouldn't be enough. So, back to the drawing board...
I hope this is enough to help you make more progress on your design.

Thanks for your useful advice. I'll update my question in order to give some additional inputs as you suggested.

I updated my answer as well based on your numbers. Depending whether you truly want to power the system for 7 days without sun (which, based on the link you provided, is probably unlikely, but I didn't look too deeply into the location's weather), you'd have to update your design. Even then, you have to do it. It's an iterative design and maybe creating an Excel sheet/Python script to help you keep track of things will probably make this easier.

Wow, thanks a lot for this info!
Honestly, I didn't get one point: suppose that I would like to use (and suppose that it could be a valid solution)  the solar shield that I linked to in the post. What do I have to consider to understand how many solar panels I can use?
Eg: try to suppose that I have to use the linked solar panel, can I use in parallel how many SP I want?So, What could happen if I connect 5 sp (170mA * 5)? Is it a risk? Would I risk burning it?

It would not be a valid solution for 7 days. It could maybe help you keep the system up for a day, granted that you're getting the 8 hours of sun a day. Each panel can provide 1 watt and in the spec sheet for the charger circuit, it says that it can handle up to 1080 mA (the current resistor is set for the charging current to be 900 mA). 5 SP should be good. If you want to be conservative, you can go with 4 SP - that for sure won't damage the charger. To know for sure you'll have to see what's the typical voltage of the panel at the brightest time of the day and how much current is produced.


text:
Why is there an extra pixel in the smiley for the Grove LCD RGB Backlight from Seeed Studio?
While testing the CustomCharacter.ino example for the Grove LCD RGB Backlight from Seeed Studio on an Arduino 101 card, there is an extra pixel that appears above an eye of the smiley and the smiley gets shifted one row down also. (see attached picture just below, with some manual changes in the library, while trying to fix the problem)

Actually, depending on the order of the characters assignments, the smiley is finally displayed correctly, such as in the following minimal working example, where the two createChar() assignments have been swapped (1 is before 0) and both smileys are displayed correctly:
#include <Wire.h>
#include "rgb_lcd.h"

rgb_lcd lcd;

byte smiley[8] = {
    0b00000,
    0b00000,
    0b01010,
    0b00000,
    0b00000,
    0b10001,
    0b01110,
    0b00000
};

void setup()
{
    lcd.begin(16, 2);
    lcd.createChar(1, smiley);
    lcd.createChar(0, smiley);
    lcd.setCursor(0, 0);
    lcd.write((unsigned char)0);
    lcd.write(1);
}

void loop() {}

If I happen to put lcd.createChar(0, smiley); back before lcd.createChar(1, smiley);, the error (the shift in the pixels rows + the extra activated pixel) occurs again for the second smiley.
Could anybody explain why this actually happens and, hopefully, give some way to fix the display?

There is an additional pixel row above the pattern you defined, and the last row is missing. You seem to have a one-off error in your code.

@thebusybee: Indeed! I did not spot that fact. I could not tell why that self-defined character is not displayed properly. I have checked the "frownie" character at the same location, for example, and that one is displayed correctly.

If the shown code reproduces the issue (the display does not match the code), then I'd say the library is faulty. Their initialization code looks wrong to me. You might want to correct it, do some research.

OK. The setup() function showed here is an adaptation of mine of the one original one in CustomCharacter.ino.

Well, I mean rgb_lcd::begin(). Such HD44780 compatible displays should to be initialized to 8-bit mode first. But it seems as if the method doesn't do this. However, as the LCD apparently is initialized, this has no consequences. But it is a smell about the quality of the library. -- The method rgb_lcd::createChar() looks OK. -- I would try to go one level deeper and bypass the library, using I²C directly to gain maximum control. -- What does the display show with your simplified program, both cases: 0 before 1, and 1 before 0? Are both smileys correct or wrong?

With the "1/0 order" for rgb_lcd::createChar(), both smileys are displayed correctly. Whereas, with the "0/1 order", the second one is displayed with the problems spotted before.

That is strange. The next step I would take is to insert some debugging messages over the serial line, just to watch rgb_lcd::createChar() doing its job correctly. Would you mind to try this? -- Alternatively, I would look into the generated assembly code just to be sure that it is correct. But this needs some expertise. -- Oh, and please [edit] your question to add the new information. New visitors will not necessarily read the comments down here.


text:
Code question: LCD keypad Shield. How do I define the buttons?
I am trying to adapt a alarm clock sketch that used external buttons, but I would like to utilize a LCD Keypad Shield.  The data sheet says all the buttons are on pin A0, so every button is "set time" in the original sketch.
After reading this post
I found the values when I press each button, :
Right    0
Up     100
Down   257
Left   410
Select 640

and have tried to define them by modifying the existing code:
LiquidCrystal lcd(2, 3, 4, 5, 6, 7); //Arduino pins to lcd
#define bt_time   A0
#define bt_up     A1
#define bt_down   A2
#define bt_alarm  A3

With:
LiquidCrystal lcd(8, 9, 4, 5, 6, 7); //Arduino pins to lcd
int lcd_key     = 0;
int adc_key_in  = 0;
#define bt_time   0
#define bt_up     1
#define bt_down   2
#define bt_alarm  3

#define buzzer 10

int read_LCD_buttons()
{
 adc_key_in = analogRead(0);      // read the value from the sensor
 // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
 // we add approx 50 to those values and check to see if we are close
 if (adc_key_in < 50)   return bt_time;
 if (adc_key_in < 150)  return bt_up;
 if (adc_key_in < 307)  return bt_down;
 if (adc_key_in < 690)  return bt_alarm;

}

I got this from here
It doesn't work.... when you press the buttons nothing happens.
It up loads with no errors, but the buttons don't do anything.
Please help, your my only hope.
Edit:
The linked "Real_Time_Clock_With_Alarm.ino" is the source file, all I have changed is the above code.  It works except I can't interact with it...  because no buttons....  I have also tested the hardware with other sketch and it works as expected.

What do you return if no button is pressed? And how can it ever be not less than 4600 when the ADC gives you 0-1023 (or 0-4096 on some better boards)?

To true, typo it should have been 690 not 4600.....

You haven't answered my first question though: what do you return if no button is pressed?

you code says analogRead(0) ... is that same as analogRead(A0)?

What does “It doesn't work” mean? Could you please write a minimal test sketch, post it here, explain how it behaves and how that is different from what you expect?

@jsotola In short, yes. In more detail:  Those shields are a 5V design that practically work with the UNO/Leonardo/Mega boards, all of which use a wiring_analog.c implementation that behaves the same for A0 and 0.

In your current revision, you're checking < 307 and then < 690 but two of your observed readings 410 and 640 sit between these numbers.


text:
Tone() function pauses between notes
I tried to experiment with the tone() function that comes with the arduino library.
I played around with the standard code example located here:
https://www.arduino.cc/en/Tutorial/BuiltInExamples/toneMelody
This is the code:
#include "pitches.h"

int melody[] =
{
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};

int noteDurations[] =
{
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup()
{
   for (int thisNote = 0; thisNote < 8; thisNote++)
   {
      int noteDuration = 1000 / noteDurations[thisNote];
      tone(8, melody[thisNote], noteDuration);

      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);

      // stop the tone playing:
      noTone(8);

   }
}

void loop()
{
  // no need to repeat the melody.
}

However, the problem is that there is always a pause between notes.
In musical terms, this is called staccato.
I want to be able to play short melodies where there are no delays between the notes, and one note progresses to the next naturally. By the way, this is called legato in music theory.
Now, in this example, the delay between the notes sounds good because this "music piece" is supposed to be played this way. But in every other song that i experimented with, there were always some pauses between notes.
This is what this song sounds like: https://soundcloud.com/nikowow-1/normal
Naturally, my mind went to the delay(pauseBetweenNotes) function. So i thought this is what causes the delay between the notes. So i set it up to 0.5. This is what it sounds like: https://soundcloud.com/nikowow-1/05a
As you can hear, it just speeds up the whole song. The delay between the notes remain, but the whole song is sped up (in a higher tempo, so to speak).
In order to better hear the delay between the notes, please take a listen at the song when i selected a value of 3 - causing a smaller tempo, so that the delay between the notes can be more easily audible: https://soundcloud.com/nikowow-1/3a-1
I want to create some melodies where there are no delays between the notes and i am stuck.
EDIT: If you remove the delay line alltogether, the song is played so quickly that only a click sound is heard.

https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay

@VE7JRO Thank you! But sorry but i dont understand. How can this be implemented in the tone() function?

I'm probably messing something. So, I'll just ask: What happens if you remove (or comment out) delay(pauseBetweenNotes); altogether?

@timemage Sorry i ommited this in the question and will edit it. But if you remove the delay, the song is played so quickly that only a feint click is heard.

I see. They made it non-blocking. That's not really what I expected from ArduinoLand.

Replace the delay with a millis timer.

@VE7JRO, why do you point them to millis()? that is not a solution to what the question asks. btw: https://arduino.stackexchange.com/questions/17355/playing-melody-with-tone-without-using-delay/89697#89697

@Juraj This was it! Thank you so much! If you want, you can make a proper answer, so i can upvote and mark it as the selected answer. Once again, thanks a ton!

@Juraj because ditching the use of delay is the most important lesson an Arduino user can learn.

@VE7JRO, OP is not there yet

@Juraj - The blocking delay will be the next question :)

I am not sure i understand what you suggest. I should replace delay with a millis timer to do the delay work? I thought millis only counts time. Does it also perform countdown until a specific time?

@VE7JRO, that question would be a duplicate of https://arduino.stackexchange.com/questions/17355/playing-melody-with-tone-without-using-delay/89697

there is
      // to distinguish the notes, set a minimum time between them.
      // the note's duration + 30% seems to work well:
      int pauseBetweenNotes = noteDuration * 1.30;
      delay(pauseBetweenNotes);

so the *1.30 creates the pause.
if you change it to
   int pauseBetweenNotes = noteDuration;

there will be no pause between notes.
The tone length is specified with the last parameter of the tone() function (noteDuration here).


text:
Anyone had Digispark Attiny85 not SEEN by some USB controllers but seen via HUB or DOCK on same device?
I have purchased a couple of different types of DigiSpark Attiny85 clones (couldn't find originals available) and they have worked great except some devices (so far, just laptops) don't see the device AT ALL.
It's not that they don't recognise it and so is a driver issue - there is nothing to apply the driver to, no indication that the thing is even plugged in other than the light comes on (so I know it has power).
More frustratingly, if I plug the Digisparks in to any problematic device via a docking station, USB hub, etc. everything works as expected (confirming the drivers are ok) and I can write scripts to the digispark.
I've tried updating the Nucleous bootloader but the problem persists.  I get this problem on three modern laptops (HP & 2 Dells) but my older Lenovo laptops have no problems.  Not sure if here is an issue with modern USB controllers?
UPDATE: Everything points towards it just being an issue with Digispark's and some USB 3.0 controllers.  The clock is correctly set at 16.5Mhz so not sure what else to do other than write these-off as a reliable device.
Anyone had any experience of this or have any suggestions?
Thanks!

It might be the bit-banging implementation of the USB protocol via the built-in oscillator, I don't know, it's just a thought. Modern USB controllers might be picky on timing. Perhaps you can check and adjust the frequency of this oscillator. I have one of these "fake" clones (rev.3) and it works on a new and an old ThinkPad.

@thebusybee, thanks for comment - from what I've read, there seems to be issues with timing specifically with some USB 3.0 controllers which is inline with what you've said and my observations (http://digistump.com/board/index.php?topic=1622.0).
I'm not familiar with adjusting the frequency and haven't seen anything on this subject in the various posts about this issue so I suspect it might just be an inherent issue that isn't going away.  I've tried updating micronucleous to the latest version too but no luck.

Not sure why I was down-voted but I've read the criteria and don't feel like it was warranted.  Does anyone have any suggestions so I can avoid it in the future.  Personally, I'll never down-vote with commenting why I've done so.

Well, I did not downvote, because you did some research and made your issue clear. Oh, BTW, you surely mean "without commenting why", don't you? -- Perhaps someone with a logic analyzer and some USB decoder and a similar setup can shed some light on the problem. Many years ago I needed 2 weeks to find protective diodes with too large capacitance this way. -- Or, if you happen to use Linux, you could try to track the system's messages while plugging in. Or you use Wireshark and its USB driver to check at a very low level. -- Anyway, I cannot help further right now, sorry.

@thebusybee, yep you're right - I missed the "out" out If you know what I mean!).  Really appreciate the help - I'm going to give up on these boards as they are just too hit and miss!

It appears the problem is down to issues around Attiny85 timing with USB 3.0 chipsets and so isn't something that can be solved.

The four USB traces on the digistump board are NOT to perfect specification and don't work with 4/5 conductor USB3 ports.  Use a dremel or band saw and cut about 2/3 of the end off the digistump Printed Circuit Board USB plug. Leave enough of the original four traces to solder to.  Cut off the plug end from an older USB cord. After carefully cutting away and cleaning off the plastic and old wires on the actual USB plug, it fits perfectly to line up to the old (now shorter) traces on the digistump. Be sure trace sides are the same direction on old and new plug and solder all four connections.  Add some superglue and/or silicone for strength and it should work every time with any USB port.
WZ


text:
Using SAM4 series microcontroller with Arduino IDE
I am looking to use SAM4S series microcontroller by Atmel/Microchip and trying to program it using Arduino IDE.

Can I use the bootloader provided by Adafruit for Feather M4 Express [uses SAMD51]  or  Feather M4 Can Express [uses SAME51] both of which are ARM Cortex M4 based just like the SAM4S series?

If yes, how do I work around few different features such as different FLASH memory and RAM of my SAM4S16B IC compared to that of SAMD51 or SAME51?

Could you suggest any other ways for using SAM4S with Arduino IDE? I, personally, did not find any direct resources for the same.

Is it even possible to use SAM4S with Arduino IDE provided that I don't have to write my own bootloader or API's etc?

Appreciate your help in the matter.
Thank you.

If no one has written a SAM4 core for Arduino then no, you can't. If someone has, then the resources you need will be in that core and their respective website / repository.

As for "Can I use any old Arm M4 based code?" the answer is a vehement "no". Just cus the CPU is M4 doesn't make it the same chip. It's like old home computers. The C64 and BBC both used the 6502, but you won't run code for one on the other.

Thanks Majenko for all your insights. This really cleared a lot of things for me. No one has written for SAM4 so I guess I won't be able to use itwith Arduino just yet. Appreciate your help.

If you're feeling adventurous, clever, and have a lot of time on your hands, you could write and maintain your own SAM4 core :)

Haha, I don't feel any of those things at the moment xD. I think I would rather switch to SAMD51 or SAME51 ICs; both of which do have arduino support from adafruit and sparkfun. Thanks !


text:
Quaternion values from Arduino 9-axis motion shield seem very wrong
I am currently usinga BNO055 sensor fitted on the Arduino Nine-axis motion shield to measure ocean wave heights and periods. To do this, I'd like to use the quaternions provided, however I have a slight issue. A quaternion should be <cos(theta/2), Xsin(theta/2), Ysin(theta/2), Z*sin(theta/2)>, with X, Y and Z the coordinates of a unit vector and theta the angle of rotation around that vector. Therefore, I expect all three to be inferior to one.
However, when I run a simple code to see the raw data, the W given by my sensor when on the table is 16 375, and X, Y and Z values are in the high hundreds range...
This gives me a wave height of hundreds of thousands of kilometers :slightly_smiling_face:
Does anyone know why this happens? Do I need to divide the quaternion by it's norm to get the correct result? Or maybe I am misunderstanding the use of a quaternion?
Oh, and I have calibrated the sensor beforehand
Thanks in advance for your help

I am not familiar with this sensor, so I am just guessing.
The sensor is likely giving you fixed-point numbers. Judging from
the real part, there are most likely 14 bits right of the implicit
radix point. If that is the case, the actual quaternion can be computed
as:
float w = raw_w / 16384.0;
float x = raw_x / 16384.0;
float y = raw_y / 16384.0;
float z = raw_z / 16384.0;

You can check whether this is reasonable by computing the norm, which
should be very close to one.

Thank you so much, I didn't understand the explanation but your solution worked!