text:
How can I switch the power on/off to cut BIG currents (200A)?
Context: I have an off-grid cabin with PV powered 12V DC. I want to cut power to an inverter (12V DC ->220V AC) when I leave by pressing a button as it draws too much in standby.
Most relays I have seen that can be connected to the Arduino typically handle 10A. My inverter draws up to 180A@12V at full power (2000 W), which is way more than anything I have seen. How can I control the power to this inverter?
Someone told me of hacks that utilize the fact that you get manual switches/relays that handle big current, so you can use the Arduino to control a motor pressing the physical switch, but the concept seems somewhat brittle ... Any other takes?

            ┌────────────┐
            │  PV array  │
            └──────┬─────┘
                   │
             ┌─────┴───┐
             │ Charger │
           ┌─┴─────────┘
           │
           │
  ┌────────┴──┐         ┌─────────┐
  │ Batteries ├─────────┤Inverter ├────────────┐
  └────────┬──┘         └─────────┘            │
           │                                   │
           │                          ┌────────┴─────┐
           │                          │220V circuit  │
       ┌───┴───────────────┐          │  w/appliances│
Has    │ Fuse box          │          └──────────────┘
on/off │ / 12v distribution│
switch!└───────────────────┘

        ┌──────────────┐
        │12V appliances│
        └──────────────┘

What is the model number of the inverter?

I do not have it readily available (it's a 4 hour drive), but it is one of the many generic China versions readily available on BangGood. Paid like 200$ for the 2KW peak/1KW continuous version.

There may be better ways to go about it involving an Arduino, but they will largely be dependent on the capabilities of the device. The typical way inverters themselves solve the cost of standby is by offering a way to probe for a load a regular intervals sometimes called "search". But there's nothing really Arduino related about that aspect of it.

The motorized manual switch idea is good because it uses (builds upon) rated components, so your insurance won't deny a claim if the cabin burns down due to electrical problems stemming from ali express junk. If you want to do it "right", use a suitably rated contactor, not a relay. Or use a manual switch; they aren't any harder to use than a button.

@dandavis Of course there exists ali express junk for this, but if you use a properly rated relay or electric switch for automotive applications, these should conform to local regulations as well. Of course, they won't be in the $5 range.

I don't know the exact physical setup, but a manual switch is probably problematic due to the location of the different components. The wires between the battery and the inverter should be as short as possible, to avoid energy loss. A cable for 180A @ 12V is  very thick. So depending on the layout, it's not possible to install a mechanical switch in a convenient place without adding a lot of extra cable length.

That's exactly it. Cable length issue, Hence the need to disable it using another remote mechanism. Also, I cannot fit search lying on the inside of my walls

@PMF good point about placement, strike my manual switch suggestion. I still worry that automotive starter relays aren't designed to handle long-term current, whereas contactors/solenoids are. I doubt the price differential is enough to justify the risk in a high-stakes situation.

@dandavis Yea, I'll clarify that in my answer. Of course it's important to read the specs regarding long-term currents. The main point actually is that there are 12 V relays or solenoids for high currents, but none (or few?) that operate on 5V directly.

@PMF sorry to be a nit, but this is a possibly life safety or mega buck problem; i want fellow makers to be safe. Might mention that many starter relays consume dozens of watts too, a consideration for solar. A latching contactor is zero rest current.

You might look for something like a "starter relay" for an engine. Those switch on 12 V and can handle currents of 150A and more. I've seen various models on the site of my favorite distributor.
Check the data sheet to make sure the relay can handle a continuous current of 180A, as many starter relays can only handle the current for short periods of time (you're not running the starter motor of an engine for more than a few seconds). Other possible types are 12V-industry-rated high-current relays. Also mentioned in a comment above: The hold-current of the relay shouldn't be to big, so you don't waste energy just for the switch.
You might need to use a 2-step solution, to first convert the 5V output of the Arduino to 12 V to control the relay. (use a small relay for this, or just a mosfet).


text:
How do you use two piezos at the same time?
I'm trying to replicate a short music clip with two piezos, and I want them to play at the same time. While the right piezo is playing, I want the left one to still be looping. The problem is, I'm not sure how.

//Left hand
const int leftPin = 10; /Left pin
const int leftTones[] = {123.4, 103.83, 138.59, 92.50}; //The looping left tones
const int leftDelays[] = {700, 1300, 900, 900}; //How long those tones last
const int leftNotes = 4; //How many left notes there are

//Right hand
const int rightPin = 2; //Right pin
const int rightTones[] = {739.99, 587.33, 587.33, 659.25, 698.46, //The looping right tones
659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 493.88,
554.37, 587.33, 659.25, 587.33, 554.37, 880.00, 783.99, 739.99,
587.33, 587.33, 659.25, 698.46, 659.25, 587.33, 554.37, 587.33,
659.25, 739.99, 987.77, 987.77, 1108.73, 1174.66, 783.99, 739.99,
698.46, 1174.66, 1318.51};
const int rightDelays[] = {700, 1000, 100, 100, 300, 300, 200, //How long those tones last
300, 300, 200, 700, 700, 250, 150, 200, 400, 300, 300, 400, 200,
700, 1000, 100, 100, 300, 300, 200, 400, 300, 200, 700, 700, 300,
200, 400, 300, 200, 400, 300, 200};
const int rightNotes = 40; //How many right notes there are

void setup(){
    pinMode(leftPin, OUTPUT);
    pinMode(rightPin, OUTPUT);
    delay(1000);
}

void loop(){
  for (int i = 0; i < leftNotes; i++){
    tone(leftPin, leftTones[i]);
    delay(leftDelays[i]);
    noTone(leftPin);
  }
  for (int i = 0; i < rightNotes; i++){
    tone(rightPin, rightTones[i]);
    delay(rightDelays[i]);
    noTone(rightPin);
  }
}

With this code, the left piezo plays first, and then the right piezo plays. It should be at the same time.
Edited Code:
long currentMillis = 0;
long leftPreviousMillis = 0; // previous time for left hand
long rightPreviousMillis = 0; // previous time for right hand

const int leftNotes = 4; // The amount of left notes
const int rightNotes = 40; // The amount of right notes
int leftIndex = 0; // The specific index for the left piezo
int rightIndex = 0; // The specific index for the right piezo
const int leftPin = 10; // The left piezo
const int rightPin = 2; // The right piezo

// The specific left pitches (as float)
const float leftTones[] = {123.4, 103.83, 138.59, 92.50};
// How long the left pitches last for
const long leftDelays[] = {700, 1300, 900, 900};

// The specific right pitches (as float)
const float rightTones[] = {739.99, 587.33, 587.33, 659.25, 698.46, 659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 493.88, 554.37, 587.33, 659.25, 587.33, 554.37, 880.00, 783.99, 739.99, 587.33, 587.33, 659.25, 698.46, 659.25, 587.33, 554.37, 587.33, 659.25, 739.99, 987.77, 987.77, 1108.73, 1174.66, 783.99, 739.99, 698.46, 1174.66, 1318.51};
// How long the right pitches last for
const long rightDelays[] = {700, 1000, 100, 100, 300, 300, 200, 300, 300, 200, 700, 700, 250, 150, 200, 400, 300, 300, 400, 200, 700, 1000, 100, 100, 300, 300, 200, 400, 300, 200, 700, 700, 300, 200, 400, 300, 200, 400, 300, 200};

void setup() {
  pinMode(leftPin, OUTPUT);
  pinMode(rightPin, OUTPUT);
  Serial.begin(9600);
  delay(1000);
  tone(rightPin, rightTones[rightIndex]);
  tone(leftPin, leftTones[leftIndex]);
}

void loop() {
  currentMillis = millis();
  // Left hand notes
  if (currentMillis - leftPreviousMillis >= leftDelays[leftIndex]) {
    noTone(leftPin); // Turn off the left note
    leftPreviousMillis = currentMillis;
    leftIndex++;
    if (leftIndex == leftNotes) // Reset left hand index
      leftIndex = 0;
    tone(leftPin, leftTones[leftIndex]); // Turn on the new left note
  }

  // Right hand notes
  if (currentMillis - rightPreviousMillis >= rightDelays[rightIndex]) {
    noTone(rightPin); // Turn off the right note
    rightPreviousMillis = currentMillis;
    rightIndex++;
    if (rightIndex == rightNotes) // Reset right hand index
      rightIndex = 0;
    tone(rightPin, rightTones[rightIndex]); // Turn on the new right note
  }
}

I've done some testing, and I think it's a problem with the tones function. Right now, this code only plays the right hand notes. The problem is this part:
tone(rightPin, rightTones[rightIndex]);
tone(leftPin, leftTones[leftIndex]);

When I do this:
tone(leftPin, leftTones[leftIndex]);
tone(rightPin, rightTones[rightIndex]);

Only the left hand notes are heard. But, it's not perfect. There's little beeps and buzzes every now and then. This leaves me with the conclusion that if there are two tones at the same time, it only plays the one it reads first. I've tested it with simpler code, and it stands true.
So that begs the question, is it even possible to use two piezos at the same time with one Arduino? I'm testing it with the Arduino simulator tinkercad, so maybe that's the problem? My code works for the left piezo, and the right piezo. But when you put them together, everything messes up.

Google "non blocking code" and "timing without delay".  This topic is one of the single most discussed issues about programming.  You'll find that thousands before you have had this problem.  The solution is well documented.

I've completely overwritten my previous code in my edited version right above, but I think may be a problem with the tones function itself. My reasoning is above.

Please don't change your question after you have an answer.

Tone can only be used on one pin at a time. Tone uses unsigned int for it's "frequency" parameter, not floating point numbers. This library claims it can play 2 different ones on 2 different pins: https://github.com/nathanRamaNoodles/Noodle-Synth

It's always good to look at the documentation when you have a question about how a piece of code works.  In this case I looked at the page for the tone function which can be found here.  https://www.arduino.cc/reference/en/language/functions/advanced-io/tone/
And the second sentence on that page says it all:

Only one tone can be generated at a time. If a tone is already playing
on a different pin, the call to tone() will have no effect. If the
tone is playing on the same pin, the call will set its frequency.

Ah, you where faster than me. Also: The Polytone seems promising as alternative.

How do you use two piezos at the same time?

Consider using a finite state machine type of programming method.
As has been discovered, using calls to the delay() function (where the processor does nothing) blocks any other feature of the sketch (user's program). In a finite state machine programming pattern, there are no calls to the delay() function.  Instead the sketch's loop() function is allowed to execute as fast as possible. The trick is to control what code is executed in the loop() function based on a state machine.  And, in this case, use time to change between different states.
In an Arduino platform (the hardware and software you never or seldom see that makes up an Arduino) a counter is always tracking elapsed time.  Use the millis() function to retrieve the current value in milliseconds (1000 milliseconds = 1 second) each time through the loop() function. Consider using a 2 state state machine. In the 1st state get the current counter value, add to it the delay in milliseconds of the next note, start the note playing and finally change the variable tracking states to the 2nd state. The next time through the loop() function, while in the 2nd state, check if the response from calling millis() again is larger then the value saved while in the 1st state.  If it is, stop playing the note and change the variable tracking states to the 1st state.
Once working, create a second similar state machine to play the counter melody.
However, as delta-g has pointed out, the library picked out by the O.P. apparently can not play more than one note at a time.  But,ve7jro has pointed out that this Arduino tunes library may be able to satisfy the requirement of playing 2 notes at the same time as stated in the O.P.'s question.
Creating a state machine in a invaluable programming lesson.  However, this Arduino state machine library is available should the programmer wish to take advantage of it.

I've put my newest code at the bottom of my previous response.

@Harrisino, you have accepted an answer. So don't edit your question into a different one. Only edit it to make it better. If you have a different question, start over by asking a new question. The point of stackexchange is to accumulate questions & answers for people to search through who have similar questions. Think how confusing the altered question will be to those people. BTW, you accepted an answer that says you can not do what your question asked for. I still think a state machine is what you want. And perhaps a better tunes library.

source: Stack Exchange

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

sort: votes


text:
ESP32 SPIFFS Write problem
I'm trying to flash a spiffs on a esp32 but it is not working, i'm using these commands from this source:
to create the image:
mkspiffs -c /data/ -b 4096 -p 256 -s 0x100000 spiffs.bin

my output was this:
/test.txt

looks it worked.
to flash the image:
esptool.py --port /dev/ttyCH341USB0 --baud 115200 write_flash -z 0x110000 spiffs.bin

and the output:
esptool.py v4.7.dev3
Serial port /dev/ttyCH341USB0
Connecting...
Failed to get PID of a device on /dev/ttyCH341USB0, using standard reset sequence.
.
Detecting chip type... Unsupported detection protocol, switching and trying again...
Connecting...
Failed to get PID of a device on /dev/ttyCH341USB0, using standard reset sequence.
.
Detecting chip type... ESP32
Chip is ESP32-D0WD (revision v1.0)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz
MAC: c4:4f:33:24:4f:49
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Flash will be erased from 0x00110000 to 0x0020ffff...
Compressed 1048576 bytes to 2025...
Wrote 1048576 bytes (2025 compressed) at 0x00110000 in 3.2 seconds (effective 2592.1 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

To test the file system im using this code to list all files:
  File root = SPIFFS.open("/");
  File file = root.openNextFile()
  while(file){
    Serial.print("FILE: ");
    Serial.println(file.name());
    file = root.openNextFile();
  }

the image is not being written, when i use this arduino plugin it works fine, but if i run the esptool write command the files are not overrided.
can someone help-me?

How do you know the Arduino Plugin works and the ESP tool doesn't? How do you check that the image has been flashed?

@NickS. using a program to list all files, i've edited the question with it.

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


text:
Feather M0 doesn't show up as a COM or Serial port
I am trying to upload a simple blink program on my Adafruit Feather M0 Radio with LoRa Radio Module to ensure that it connects to my PC. So far, I have:

Gone through 4 data cables
Tested for connection on 3 different devices (laptop on Windows 11, desktop on Windows 10, and computer running CentOS respectively)
Followed the direction for using the board with the IDE here and here

But the Port submenu is greyed out and when it isn't, it just doesn't have the port that recognizes my Feather. When going into Device Manager, I can't see it in the list of devices even when I refresh.

At some point did you double-tap reset?

Yes, many times. The problem persisted afterwards

Had it ever had anything uploaded to it successfully in the past? Is there anything connected it apart from the USB cable?

@timemage No, since I received my feather, I haven't had any success uploading anything to it

When you double-tap reset do you get the fade-in-fade-out indication on the pin13 LED?

Turns out the bootloader/USB firmware wasn't loaded in, which is why the double-tap reset wasn't working. I looked into the option of using another board as a programmer to get the bootloader in my Feather, but it proved to be more of a hassle than I thought so I'm just going to get a replacement. Hope this helps someone out in the future.


text:
ESP8266 - Where to find pin assignment guide for uploading code?
I try to upload a script which starts a webserver on the ESP8266 with a simple web GUI where the user can enter his WLAN credentials.
/*  ============================================================================================================

    Sample code to create a setup web portal using a soft access point on an ESP8266.

    For more info, please watch my video at https://youtu.be/1VW-z4ibMXI

    MrDIY.ca

============================================================================================================== */

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>
ESP8266WebServer    server(80);

struct settings {
  char ssid[30];
  char password[30];
} user_wifi = {};

void setup() {

  EEPROM.begin(sizeof(struct settings) );
  EEPROM.get( 0, user_wifi );

  WiFi.mode(WIFI_STA);
  WiFi.begin(user_wifi.ssid, user_wifi.password);

  byte tries = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    if (tries++ > 30) {
      WiFi.mode(WIFI_AP);
      WiFi.softAP("Setup Portal", "mrdiy.ca");
      break;
    }
  }
  server.on("/",  handlePortal);
  server.begin();
}

void loop() {

  server.handleClient();
}

void handlePortal() {

  if (server.method() == HTTP_POST) {

    strncpy(user_wifi.ssid,     server.arg("ssid").c_str(),     sizeof(user_wifi.ssid) );
    strncpy(user_wifi.password, server.arg("password").c_str(), sizeof(user_wifi.password) );
    user_wifi.ssid[server.arg("ssid").length()] = user_wifi.password[server.arg("password").length()] = '\0';
    EEPROM.put(0, user_wifi);
    EEPROM.commit();

    server.send(200,   "text/html",  "<!doctype html><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>Wifi Setup</title>
Wifi Setup

Your settings have been saved successfully!
Please restart the device.
" );
  } else {

    server.send(200,   "text/html", "<!doctype html><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>Wifi Setup</title>    <form action='/' method='post'>
Wifi Setup

SSID<input type='text' class='form-control' name='ssid'>

Password<input type='password' class='form-control' name='password'>

<button type='submit'>Save</button>
mrdiy.ca
</form> " );
  }
}

I try to figure out how I need to connect the ESP8266 WLAN module with my Arduino Uno in order to be able to upload that script. I've searched the documentation, but I can't find much helpful.
The module has these pins:
3V3 | RX
RST | IO0
EN  | IO2
TX  | GND

But in the documentation there are other pins which I don't have and the pin EN is not even mentioned in the documentation.
I connected it like this (i did not used pull up resistors yet):
[ESP8266 -> Arduino Uno]

3V3 -> 3V3 (bread board)
EN  -> 3V3 (bread board)
RX  -> RX
TX  -> TX
GND -> GND

The connection works and it responds to AT commands.
But if I try to upload a script, then it fails with:
. Variables and constants in RAM (global, static), used 28236 / 80192 bytes (35%)
║   SEGMENT  BYTES    DESCRIPTION
╠══ DATA     1504     initialized variables
╠══ RODATA   1020     constants
╚══ BSS      25712    zeroed variables
. Instruction RAM (IRAM_ATTR, ICACHE_RAM_ATTR), used 59535 / 65536 bytes (90%)
║   SEGMENT  BYTES    DESCRIPTION
╠══ ICACHE   32768    reserved space for flash instruction cache
╚══ IRAM     26767    code in IRAM
. Code in flash (default, ICACHE_FLASH_ATTR), used 239164 / 1048576 bytes (22%)
║   SEGMENT  BYTES    DESCRIPTION
╚══ IROM     239164   code in flash
esptool.py v3.0
Serial port COM4
Connecting........_____....._____....._____....._____....._____....._____....._____

A fatal esptool.py error occurred: Failed to connect to ESP8266: Invalid head of packet (0xF0)

How do I need to connect my module in order to upload code?
I am using this chip. I also tested another chip (i got 4) to check if mine is broken, but I get the same error.

if you are seeing AT commands  then it is connected correctly ... the ESP-01 is preprogrammed with the AT firmware and I'm not certain if it's capable of accepting a program

try this https://www.instructables.com/HOW-TO-UPLOAD-PROGRAM-TO-ESP-01-USING-ARDUINO/

I followed the instructions. Uploading was successfull after I set the Reset of my Arduino to GND. But now my ESP8266 does not work anymore, there is no WLAN connection and it stopped responding to AT commands.

The sketch replaced the AT firmware. You have an esp-01. It is not a development board but a WiFi module, so it doesn't have an USB adapter and auto reset.

@Juraj wow ok, how do I recognize if a board is for development, I thought each one is? Im a arduino beginner, sorry. What can you even do with such a module as mine if you can't program it?

USB connector is a good indicator of a development board. \ you can program an esp-01. you did it. just you need a way to connect it to a computer and you have to know how to put it in bootloader mode. a simplest esp8266 development board is the Wemos D1 mini.

Ok thx, so there is no safe way to know wheter or not a board supports custom development?

The module is built around esp8266ex microcontroller. In order to make it enter into the flash programming mode the following steps must be taken.

Put mcu into reset state by pulling reset line low.

Pull gpio15 low and gpio0 low while still holding reset low.

Release reset, so it will go high and mcu will restart.

While starting the mcu will check pin states (gpio15 low=use spi flash 25xx series pre-attached to gpio6-11, gpio0 low=self programming mode, gpio2 is NOT low) and will enter the waiting state in a few milliseconds.

Release gpio0 and start data transfer to h/w uart0 (attached to gpio1 and gpio3, aka tx and rx).

So you need to ensure that: gpio0 is pulled up; gpio1 and gpio3 are attached to another host's uart by crossover connection; gpio2 is not low; gpio15 is pulled low; both reset and enable are pulled high; and, of course, you have 3v3 power and ground. Also, you need two push buttons to connect reset and gpio0 to ground temporarily. Then press reset, press gpio0 button, release reset, and, finally, release gpio0. Mcu should now wait for the data to flash. Also, when using esptool you need to tell it to skip auto-reset sequence (--before no_reset), as you're doing it manually.
Considering aforementioned pullups, their presence depends on a module you're using. For esp-01s, they all should be already there (except for the two buttons). For esp-01 (without "s"), you'll need to add pull ups for gpio0 and "chip enable" pin yourself.
There's also auto-programming sequence (which is default for esptool) also sometimes referred as "nodemcu reset method" or such. The idea is that the programming software will switch dtr and rts UART extra signals on and off before data transfer. If you have a small circuit between uart chip and esp8266 mcu that is capable to translate dtr/rts signals to reset/gpio0 states to make mcu to enter self programming mode then you won't need any push buttons anymore.
Such circuit can be made of only two npn transistors and two resistors and is searched online easily. Some boards (including nodemcu, of course) may have such circuit along with usb-ttl converter, dc-dc buck converter and usb plug all on-board. But they are bigger in size and slightly more expensive than esp-01, of course.
Also, for esp-01/esp-01s specifically, you can purchase a prebuilt adapter that provides exactly those missing parts (usb plug, dc buck, two transistor auto-circuit, ttl converter chip, some pullups and female header to plug esp-01 module in). So you can flash your modules using this adapter while sparing some space in your circuit too.
(Hint: the presence of auto programming feature could be guessed from the product photo usually by spotting two sot-23 transistors close to each other).
Or you can buy all these parts and solder such adapter board yourself. This might look a bit too much for a beginner, but, on the other hand, it could make an interesting challenge too.

Thx for your answer! There is no gpio15 on my ESP8266

@Black esp8266 is a microcontroller chip and it does have this one and a bunch of others. Esp-01 is a small board that already includes a pull down resistor from gpio15 to ground. So if you failed to spot it, it's not a big deal as you are not supposed to do anything with that pin yourself. At least, for esp-01.


text:
"Done uploading" but Uno still running old sketch
So, this is my first experience, I bought new original Uno, trying write some code there and it stuck in running only one sketch.
Tools->Boards is ok, Tools->Ports is ok.
I try created new sketch from File->Examples->01. Basics->Blink and it uploaded successfully, but Uno still running old code and sending to Serial Monitor data (from empty A0, where was potentiometer)
I tried reinstall Arduino App, trying on Windows, tried with only power (just 12v round port, without USB) and it still launch old sketch.
When I plug Uno to Mac or Windows it immediately start spaming to Serial Monitor same data.
Clicking, pressing, holding "reset" button with plug or unplug on smth else doesn't work.
==============
Here is my last code, which "stuck" on Uno right now:
const int myPin = A0;

void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
}

void loop() {
  int sensorValue = analogRead(myPin);
  // Serial.print("Sensor value: ");
  Serial.println(sensorValue);

}

And proof that upload success:

Here is code of Blink from examples:
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on (HIGH is the voltage level)
  delay(1000);                      // wait for a second
  digitalWrite(LED_BUILTIN, LOW);   // turn the LED off by making the voltage LOW
  delay(1000);                      // wait for a second
}

And proof that upload success:

Here is my Uno without anything but with lighted TX port when I plug it into Mac/Windows (you can see that L/13 bulb light darker than should and I don't know why):

And here is unstoppable spaming in Serial Monitor by sketch from first code:
01:57:24.874 -> 430
01:57:24.874 -> 420
01:57:24.874 -> 425
01:57:24.874 -> 435
01:57:24.874 -> 424
01:57:24.874 -> 425
01:57:24.907 -> 425
01:57:24.907 -> 434
01:57:24.907 -> 422
01:57:24.907 -> 425
01:57:24.907 -> 425
01:57:24.907 -> 433
01:57:24.940 -> 420
01:57:24.940 -> 424
01:57:24.940 -> 423
01:57:24.940 -> 431
01:57:24.940 -> 417
01:57:24.940 -> 423
01:57:24.940 -> 422
01:57:24.973 -> 429
01:57:24.973 -> 415
01:57:24.973 -> 421
01:57:24.973 -> 422
01:57:24.973 -> 424
01:57:24.973 -> 416
01:57:25.005 -> 421
01:57:25.005 -> 428
01:57:25.005 -> 421
01:57:25.005 -> 419
01:57:25.005 -> 418
01:57:25.005 -> 426
01:57:25.036 -> 415
01:57:25.036 -> 417
01:57:25.036 -> 417
01:57:25.036 -> 424
01:57:25.036 -> 411
01:57:25.036 -> 416
01:57:25.036 -> 416
01:57:25.069 -> 424
01:57:25.069 -> 410
01:57:25.069 -> 416
01:57:25.069 -> 416
01:57:25.069 -> 423
01:57:25.069 -> 407
01:57:25.101 -> 415

===========
UPD:
On IDE v. 1.8.19 I got this
Arduino: 1.8.19 (Mac OS X), Board: "Arduino Uno"

Sketch uses 924 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
An error occurred while uploading the sketch
avrdude: verification error, first mismatch at byte 0x0002
         0x5d != 0x5c
avrdude: verification error; content mismatch

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

With checked show verbose during compilation and upload I got more:
Arduino: 1.8.19 (Mac OS X), Board: "Arduino Uno"

/private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/hardware -hardware /Users/mr_belogub/Library/Arduino15/packages -tools /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/tools-builder -tools /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/mr_belogub/Library/Arduino15/packages -built-in-libraries /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/libraries -libraries /Users/mr_belogub/Documents/Arduino/libraries -fqbn=arduino:avr:uno -vid-pid=2341_0043 -ide-version=10819 -build-path /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559 -warnings=none -build-cache /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_cache_275921 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -verbose /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/examples/01.Basics/Blink/Blink.ino
/private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/hardware -hardware /Users/mr_belogub/Library/Arduino15/packages -tools /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/tools-builder -tools /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/mr_belogub/Library/Arduino15/packages -built-in-libraries /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/libraries -libraries /Users/mr_belogub/Documents/Arduino/libraries -fqbn=arduino:avr:uno -vid-pid=2341_0043 -ide-version=10819 -build-path /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559 -warnings=none -build-cache /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_cache_275921 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7 -prefs=runtime.tools.avrdude.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17 -prefs=runtime.tools.arduinoOTA.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.3.0 -verbose /private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/examples/01.Basics/Blink/Blink.ino
Using board 'uno' from platform in folder: /Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6
Using core 'arduino' from platform in folder: /Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6
Detecting libraries used...
/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/variants/standard /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp -o /dev/null
Generating function prototypes...
/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/variants/standard /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp -o /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/preproc/ctags_target_for_gcc_minus_e.cpp
/private/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/AppTranslocation/9AA61328-BD81-4800-BA6D-7F5DD6005876/d/Arduino.app/Contents/Java/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/preproc/ctags_target_for_gcc_minus_e.cpp
Compiling sketch...
/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10819 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/cores/arduino -I/Users/mr_belogub/Library/Arduino15/packages/arduino/hardware/avr/1.8.6/variants/standard /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp -o /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp.o
Compiling libraries...
Compiling core...
Using precompiled core: /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_cache_275921/core/core_arduino_avr_uno_7dc84736bec69d7a3f526b3465643c6f.a
Linking everything together...
/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-gcc -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.elf /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/sketch/Blink.ino.cpp.o /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/../arduino_cache_275921/core/core_arduino_avr_uno_7dc84736bec69d7a3f526b3465643c6f.a -L/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559 -lm
/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.elf /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.eep
/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy -O ihex -R .eeprom /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.elf /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex
/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avr-gcc/7.3.0-atmel3.6.1-arduino7/bin/avr-size -A /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.elf
Sketch uses 924 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude -C/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbmodem1101 -b115200 -D -Uflash:w:/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex:i

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 "/Users/mr_belogub/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf"
         User configuration file is "/Users/mr_belogub/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbmodem1101
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "/var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex"
avrdude: writing flash (924 bytes):

Writing | ################################################## | 100% 0.13s

avrdude: 924 bytes of flash written
avrdude: verifying flash memory against /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex:
avrdude: load data flash data from input file /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex:
avrdude: input file /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex contains 924 bytes
avrdude: reading on-chip flash data:

An error occurred while uploading the sketch
Reading | ################################################## | 100% 0.13s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0002
         0x5d != 0x5c
avrdude: verification error; content mismatch

avrdude done.  Thank you.

@jsotola I thing it strange coz it have not only code and output but more additional info, but ok, i removed and paste like text

if you have additional info that cannot be added any other way than a picture, then it is ok to add a picture

Are you sure the upload was successful? Did you really click "Upload", and not "Check"? I doubt that, because the old sketch still runs, and there can only be one sketch on an Arduino. You might want to repeat the upload and [edit] your question to show us the resulting log of the upload.

@thebusybee yeah, I'm sure, in question was a screenshots but jsotola ask me to remove it.
Now I back screenshots, is it that you ask?

Since I don't hat IDE 2, I cannot say for sure, but I'd expect a preference to show verbose compiler and upload logs. Please enable that and copy the log as text into your question. A popup message is no log. -- Do you have more than one Arduino? If so, are both connected?

@thebusybee I again updated question, added more info in the end

OK, now we see: "avrdude: verification error". The upload was not successful. The next step is to look for similar questions here on SE/Arduino. Please add your findings to the question and tell us why they don't help you.

So, my solution is: burn new bootloader
I bought:
USBASP ISP-AVR V2 (Programmer) - 139 UAH / 3.65 USD
10pin to 6pin connector - 22 UAH / 0.58 USD
(cable was with programmer)

I connect programmer to cable with 10pin female, other 10pin female to 10pin/6pin connector, connector to 6 alone pins on Arduino, Arduino to PC
Install drivers, via IDE choose Tools->Burn Bootloader
And voilà!

It looks like your upload failed:
avrdude: verifying flash memory against /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex:
avrdude: load data flash data from input file /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex:
avrdude: input file /var/folders/g4/0ddwtmhx3y97b4nm8m2ns88c0000gn/T/arduino_build_275559/Blink.ino.hex contains 924 bytes
avrdude: reading on-chip flash data:

An error occurred while uploading the sketch
Reading | ################################################## | 100% 0.13s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0002
         0x5d != 0x5c
avrdude: verification error; content mismatch

This was possibly related to your first sketch outputting to serial constantly. In future I suggest building in a delay before sending data constantly to serial (eg. delay(500)).
Burning a new bootloader removed the problem sketch.
Instead you could have held down the Reset button until the uploading started, and then released it. That would stop the original sketch from running.

authors: Сергей Белогуб


text:
I can't upload my sketch to Arduino Uno using avrdude
I have already spent a couple of days by trying to upload a sketch onto my Arduino Uno R3 board and now it's time to give up, so I'm trying to ask some more experienced developers.
My hardware and software configuration is:

FreeBSD-14.0-RELEASE
Arduino Uno R3 with Atmega16u2 USB-to-Serial chip
avrdude 7.2

The sketch is just empty and compiles without any problem:
#include <Arduino.h>
void setup() {}
void loop() {}

My kldstat output is:
aperechnev@home-pc:~/Projects/stepper-test $ kldstat
Id Refs Address                Size Name
 1   45 0xffffffff80200000  1d34598 kernel
 2    1 0xffffffff81f35000     7718 cryptodev.ko
 3    1 0xffffffff81f3d000     4370 uarduno.ko
 4    2 0xffffffff81f42000     a088 ucom.ko
 5    1 0xffffffff81f4e000   5d51c8 zfs.ko
 6    1 0xffffffff82524000   daa430 nvidia.ko
 7    3 0xffffffff832cf000    1e6a8 linux_common.ko
 8    2 0xffffffff832ee000    6a068 linux.ko
 9    1 0xffffffff83c20000     3250 ichsmb.ko
10    1 0xffffffff83c24000     2178 smbus.ko
11    1 0xffffffff83c27000     2a68 mac_ntpd.ko
12    1 0xffffffff83c2a000    12e08 fusefs.ko
13    1 0xffffffff83c3d000     4d64 geom_uzip.ko

The short description of the problem is avrdude: ser_recv(): programmer is not responding.
Now I'm revealing the detailed description.
I'm uploading my sketch with the following command:
avrdude -v -v -v -v -p atmega328p -c arduino -b 115200 -P /dev/cuaU0 -U flash:w:/home/aperechnev/Projects/stepper-test/firmware.hex:i

And I receive the next output:
avrdude: Version 7.2
         Copyright the AVRDUDE authors;
         see https://github.com/avrdudes/avrdude/blob/main/AUTHORS

         System wide configuration file is /usr/local/etc/avrdude.conf
         User configuration file is /home/aperechnev/.avrduderc
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cuaU0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: send: 0 [30]   [20]
avrdude: send: 0 [30]   [20]
avrdude: send: 0 [30]   [20]
avrdude: recv: . [14]
avrdude: recv: . [10]
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         Serial program mode           : yes
         Parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                           Block Poll               Page                       Polled
           Memory Type Alias    Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- -------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom                 65    20     4    0 no       1024    4      0  3600  3600 0x00 0x00
                                           Block Poll               Page                       Polled
           Memory Type Alias    Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- -------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           flash                  65    10   128    0 yes     32768  128    256  4500  4500 0x00 0x00
                                           Block Poll               Page                       Polled
           Memory Type Alias    Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- -------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lfuse                   0     0     0    0 no          1    1      0  4500  4500 0x00 0x00
                                           Block Poll               Page                       Polled
           Memory Type Alias    Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- -------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           hfuse                   0     0     0    0 no          1    1      0  4500  4500 0x00 0x00
                                           Block Poll               Page                       Polled
           Memory Type Alias    Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- -------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           efuse                   0     0     0    0 no          1    1      0  4500  4500 0x00 0x00
                                           Block Poll               Page                       Polled
           Memory Type Alias    Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- -------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           lock                    0     0     0    0 no          1    1      0  4500  4500 0x00 0x00
                                           Block Poll               Page                       Polled
           Memory Type Alias    Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- -------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           signature               0     0     0    0 no          3    1      0     0     0 0x00 0x00
                                           Block Poll               Page                       Polled
           Memory Type Alias    Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- -------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           calibration             0     0     0    0 no          1    1      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino for bootloader using STK500 v1 protocol
avrdude: send: A [41] . [80]   [20]
avrdude: recv: . [14]
avrdude: recv: . [03]
avrdude: recv: . [10]
avrdude: send: A [41] . [81]   [20]
avrdude: recv: . [14]
avrdude: recv: . [04]
avrdude: recv: . [10]
avrdude: send: A [41] . [82]   [20]
avrdude: recv: . [14]
avrdude: recv: . [04]
avrdude: recv: . [10]
avrdude: send: A [41] . [98]   [20]
avrdude: recv: . [14]
avrdude: recv: . [03]
avrdude: recv: . [10]
         Hardware Version: 3
         Firmware Version: 4.4
avrdude: send: A [41] . [81]   [20]
avrdude: recv: . [14]
avrdude: recv: . [04]
avrdude: recv: . [10]
avrdude: send: A [41] . [82]   [20]
avrdude: recv: . [14]
avrdude: recv: . [04]
avrdude: recv: . [10]
avrdude: send: B [42] . [86] . [00] . [00] . [01] . [01] . [01] . [01] . [03] . [00] . [00] . [00] . [00] . [00] . [80] . [04] . [00] . [00] . [00] . [80] . [00]   [20]
avrdude: recv: . [14]
avrdude: recv: . [10]
avrdude: send: E [45] . [05] . [04] . [d7] . [c2] . [01]   [20]
avrdude: recv: . [14]
avrdude: recv: . [10]
avrdude: send: P [50]   [20]
avrdude: recv: . [14]
avrdude: recv: . [10]
avrdude: AVR device initialized and ready to accept instructions
Reading |                                                    | 0% 0.00 s
avrdude: send: u [75]   [20]
avrdude: recv: . [14] . [1e] . [95] . [0f] . [10]
Reading | ################################################## | 100% 0.00 s
avrdude: device signature = 0x1e950f (probably m328p)
avrdude: Note: flash memory has been specified, an erase cycle will be performed.
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: send: V [56] . [ac] . [80] . [00] . [00]   [20]
avrdude: recv: . [14]
avrdude: recv: . [00]
avrdude: recv: . [10]
avrdude: send: A [41] . [81]   [20]
avrdude: recv: . [14]
avrdude: recv: . [04]
avrdude: recv: . [10]
avrdude: send: A [41] . [82]   [20]
avrdude: recv: . [14]
avrdude: recv: . [04]
avrdude: recv: . [10]
avrdude: send: B [42] . [86] . [00] . [00] . [01] . [01] . [01] . [01] . [03] . [00] . [00] . [00] . [00] . [00] . [80] . [04] . [00] . [00] . [00] . [80] . [00]   [20]
avrdude: recv: . [14]
avrdude: recv: . [10]
avrdude: send: E [45] . [05] . [04] . [d7] . [c2] . [01]   [20]
avrdude: recv: . [14]
avrdude: recv: . [10]
avrdude: send: P [50]   [20]
avrdude: recv: . [14]
avrdude: recv: . [10]

avrdude: processing -U flash:w:/home/aperechnev/Projects/stepper-test/firmware.hex:i
avrdude: reading input file /home/aperechnev/Projects/stepper-test/firmware.hex for flash
         with 3472 bytes in 1 section within [0, 0xd8f]
         using 28 pages and 112 pad bytes
avrdude: writing 3472 bytes flash ...
Writing |                                                    | 0% 0.00 s
avrdude: send: U [55] . [c0] . [06]   [20]
avrdude: recv: . [14]
avrdude: recv: . [10]
avrdude: send: t [74] . [00] . [80] F [46]   [20]
avrdude: recv: . [14]
avrdude: ser_recv(): programmer is not responding
Writing | -------------------------------------------------- | 0% 5.05 s
avrdude stk500_recv() [stk500.c:75] error: programmer is not responding

As I can see, avrdude successfully determines my board, reads its configuration and so on. But then it can't read the response from the board right after it starts uploading the sketch.
I looked at the code of the bootloader (Optiboot) and found the lines that are responsible to process the 0x74 request and it seems like the problem is not in the bootloader.
Even more, my Arduino Board is blinking with TX/RX LEDs, as well as with L LED during the start of uploading, at the stage where avrdude reads its configuration.
And one more interesting thing is that some sketches were successfully uploaded when I pressed the RESET button on my Arduino board during the process of uploading. But it happened just for two times. I've read about this trick somewhere on Stackoverflow, but it's really hard to catch the moment when I must press the reset button.
And one more interesting fact is that my sketches upload without any problem from my MacBook Pro driven by MacOS and Arduino IDE 2.x. So I'm sure that the board isn't burned and the bootloader works okay.
And one more important fact is the output of dmesg when I connect my Arduino board to a USB port of my PC:
ugen1.2: <Arduino Uno Arduino Uno> at usbus1
uarduno0 on uhub4
uarduno0: <Arduino Uno> on usbus1

I have no idea what's the problem and I'm kindly asking for any help.
Many thanks,
Alexander.

Did you check different bootloader protocols, as there are "flavors" of them? If it works with your MacBook, did you look at that command  line? (In the Arduino IDE 1 there is an option to enable the upload log.)

Hi @thebusybee! Thank you for being interested in my problem. Yes, I've just tried another programmer and my sketch was successfully uploaded. So I'll post my own answer to this question.

Please see if it helps: https://forum.arduino.cc/t/cannot-upload-sketch-to-arduino-uno/1220498

Finally I resolved the issue. I used arduino programmer as a parameter to avrdude ... -c arduino, but it can't work with the newer Arduino boards. It was written for the boards that use optiboot as a bootloader, but these days Arduino boards are shipped with urboot bootloader. So to be able to upload sketches onto the newer Arduino boards you should use urclock programmer: avrdude ... -c urclock. And since bootloaders can vary in the size of flash memory they fit in, you also need to pass -xbootsize=<N> parameter to avrdude to avoid bootloader override.
So to upload your sketch you should use something like:
avrdude ... -c urclock ... -xbootsize=1024 ...

I'm going to review existing manuals and suggest some additions, so people will be able to save their time working with Arduino on FreeBSD, Linux and other platforms that aren't Windows or MacOS.

This issue is independent of the OS of the PC. ;-) I'm running Arch-Linux and use the Arduino IDE as well as avrdude directly. One needs to know what options to use, this is the secret. As always. :-D

"but these days Arduino boards are shipped with urboot bootloader"
To be clear, this is not the case for official AVR based Arduinos or faithful clones of them. The current official 1.8.7 AVR board package doesn't even ship with a new enough version of avrdude to support -c urclock.
If someone wants that, it looks like the various MCUdude packages will do -c urclock, MiniCore or MightyCore, etc.


text:
Whats the MPPZ 3610 on Arduino nano every
I'm curious what's the MPPZ chip on my Arduino nano every

You mean MPM3610? https://www.monolithicpower.com/en/mpm3610.html

From Arduino Nano Every datasheet:

MPM3610 (DC-DC)

Regulates input voltage from up to 21V with a minimum of 65% efficiency @minimum load
More than 85% efficiency @12V


text:
Can't upload to nano esp32
Recently bought a nano esp32 to play around with the small size and wifi module. However I'm plagued by the No DFU capable USB device available message.
My efforts and deductions:

I can connect to my Uno boards just fine.
I have reset the bootloader see here successfully, however it opens a new COM port that after reset is gone
Restarted the IDE, Redownloaded the IDE, made sure it's up to date
Tried numerous cabling (eg. cables for ssd's, charging, etc) nothing seems to work except on that one port  that is opened upon the bootloader reset.
The arduino IDE will identify a port (in my case COM 9) and recognize it, however returns this error
I have done the double tap on the RST button
I have made sure that the esp32 is selected and the dependencies for it is installed
I am using just a simple web server sketch
As far as I can tell theres the port that its being picked up as and the actual port it should be on, however the IDE rarely detects it and if it does its only for a moment and is incredibly inconsistent

I am new to this IoT world so there's most likely an oversight on my part but please try to be kind and not stack overflow me into oblivion :D
I should note that I am just trying to upload anything to the nano esp32without this error occurring
Sketch uses 721325 bytes (22%) of program storage space. Maximum is 3145728 bytes.
Global variables use 56580 bytes (17%) of dynamic memory, leaving 271100 bytes for local variables. Maximum is 327680 bytes.
dfu-util 0.11-arduino4

Copyright 2005-2009 Weston Schmidt, Harald Welte and OpenMoko Inc.
Copyright 2010-2021 Tormod Volden and Stefan Schmidt
This program is Free Software and has ABSOLUTELY NO WARRANTY
Please report bugs to http://sourceforge.net/p/dfu-util/tickets/

Cannot open DFU device 2341:0070 found on devnum 20 (LIBUSB_ERROR_NOT_FOUND)
No DFU capable USB device available
Failed uploading: uploading error: exit status 74

Make sure you have the right board selected in the board selector or the Tools > Board menu.

@tepalia, I have the correct board selected: that being Arduino ESP32 Boards


text:
Why does filling up a large char array cause a crash? (ESP8266)
Here's the code in question:
void setup() {
  Serial.begin(115200);
  Serial.println();

  char test[5000];
  int i;

  for (i = 0; i < sizeof(test)-1; i++) {
    test[i] = 'x';
    Serial.println(i);
  }

  Serial.println("Going to print string: ");
  test[i]='\0';
  Serial.println(test);
}

void loop() {
}

The crash I get on my NodeMCU ESP8266, wdt reset. Note that it happened on iteration 835. It's the same iteration every time.
...
834
835

 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 3424, room 16
tail 0
chksum 0x2e
load 0x3fff20b8, len 40, room 8
tail 0
chksum 0x2b
csum 0x2b
v00041d50
~ld

When I decrease the length of the array to 4000, I get a different crash, this time it's Stack smashing detected. Note however, that this time everything was printed successfully and it only crashes after doing everything.
3997
3998
Going to print string:
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

Stack smashing detected.

Exception (5):
epc1=0x40100d43 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

>>>stack>>>

ctx: sys
sp: 3fffffa0 end: 3fffffb0 offset: 0000
3fffffa0:  3fffdad0 00000000 3ffee56c 40100d43
<<<stack<<<

--------------- CUT HERE FOR EXCEPTION DECODER ---------------

 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 3424, room 16
tail 0
chksum 0x2e
load 0x3fff20b8, len 40, room 8
tail 0
chksum 0x2b
csum 0x2b
v00041d50
~ld
...

When I decrease the length of the array further, to 3000, nothing happens and the program runs normally as it should.
What is going on here?

ahhh you're right, fixed, that's due to me renaming variables to make it cleaner for SO, it wasn't there when I was running it. The question still stands.

Does the behavior change if you qualify the array as static?

@EdgarBonet Yes, it actually fixes the problem! Thanks, could you explain or point me to some resource that would explain the reason for this difference? Shouldn't allocated memory be the same whether it's on the stack or on the heap?

@Daavee18 - Likely your build has a memory layout with the (fixed-size) stack proceeded by something else critical. 4096 bytes is way larger than the stack size, so you end up with test pointing to some random memory that's bad to overwrite, but not critical at that point in time. But then test+835 ends up overwriting something required for printing, e.g. the first instruction of println or somesuch.

If you're asking why the compiler doesn't warn you at compile time that you might overflow stack - there are compilers that will do that, but they tend to result in massive numbers of false positives from "potential" callstacks that can't actually occur in practice.

If you're asking why it doesn't error at runtime when you overflow stack - to do so precisely tends to result in significant slowdowns, as it tends to result in a check every function call at a minimum. (And then you have the problem of "whoops, I detected that I'm about to overflow stack... now what? I don't have any stack lefft to e.g. print the problem!")

As I am not familiar with the ESP8266 architecture, I cannot give a
definitive explanation of the issue. It is, however, fairly common to
find platforms where the stack cannot grow past a fixed size that is way
smaller than the available memory. This happens, for example, on
multi-threaded environments, where each thread has its own stack,
allocated at a fixed size. The old trick of putting the stack and the
heap at opposite ends of the physical memory cannot work on such
environments.
For the record, static variables are allocated in the program's data
section, not on the heap, which is used by malloc and new.


text:
How to control a stepper motor using an absolute position sensor which has an error band?
I am using Feather M4 express development board with DC Motor + Stepper FeatherWing and Ethernet FeatherWing stacked on it. The idea is to read the target position from the UDP from 0 t0 360 degrees and control the steps of the stepper motor by reading the current encoder values. I am using this library for reading the encoder values.
The encoder is mounted at an angle of 90 degrees to the starting motor position. I am currently able to read the encoder values but even with the moving average filter, there seems to be inaccurate values sent on the SSI frequently along with the correct values. Since the targetPosition is not stable in spite of the moving average filter, the stepper keeps rotating until it finds the defined targetPosition (which should be 0 or offset of -90 degrees). However, defining the initial targetPosition = 10 seems to bring it to the stable position every time after 2-4 full rotations.
The next issue is, when I send the required angle on the UDP message, the stepsToMove in the moveToPosition() function seems to be the right value, but the stepper just does not move the required number of steps. When the currentPosition < targetPosition, most of the times, the stepper just keeps moving and in effect, blocking the microcontroller.
I am looking for improvements in the software as the hardware cannot be changed.

How can I improve the filter values to get the most accurate encoder values?
How can I add this offset to the rotateToIntialPosition() function and to move it dynamically combined with this offset during the operation in the moveToPosition() function?
Since the encoder is is expected to have an error band, how can I include the +/- 5 degrees in the control loop in the moveToPosition() function?

also posted at https://electronics.stackexchange.com/questions/719639/how-to-read-position-sensor-values-more-accurately-for-stpper-control

This may not be your only issue, but you have a problem with the
function getFilteredEncoderAngle() which is... plain wrong. Imagine
your motor is exactly at angle 0 but, due to noise, you get half of the
readings reporting 0.5°, and the other half at 359.5°. This is a pretty
small amount of noise, with only 0.5° amplitude. The average, of course,
should be zero, but your filter will report 180°: it would be impossible
to get a result that is more wrong than that.
I expect this to wreak havoc on your program every time you cross the
zero angle. Your motor could cross it smoothly as 358° → 359° → 0° → 1°…
but your filter will believe the motor is suddenly spinning very fast in
the opposite direction.
You really need a smoothing filter that is aware that angles are
supposed to wrap at 360°. I have written an answer a few years ago
showing three different ways to implement a wrap-aware smoothing
filter. Rob Tillaart has taken my third approach (my favorite) and
implemented it in the Arduino library runningAngle. Note that this
is not a “plain” running average, but rather an exponentially-weighted
running average.

thanks for the suggestion. I only want to read the absolute position from the encoder and move my stepper to the required position. I am still having a hard time implementing the runningAngle library. I understand the filtered value function is a bad idea. I just want to use the moveToPosition(target_steps) function. What would be your suggestion for this?

@dreamcoder: I don't understand your question. You don't need to implement the runningAngle library, as it has already been implemented by Rob Tillaart. You can install it from the Arduino library manager. For using it, look at the Usage section of the README. You can also look at the example sketch named also “runningAngle”.

I have used the runningAngle library in my sketch and it only makes a marginal improvement. The position sensing encoder still reads half of the values wrong. Which makes the stepper control deviate quite a lot. Is there a way to filter out the wrong values and use only the valid ones?


text:
Arduino : How to write a variable value into a text file and modify it in the SD card?
I want to write a variable value into a text file in the SD card and modify it while reading if needed.
I found a text reading code which reads a desired line in the text file.(not tested)
//reading code
#include <SD.h>

int stepToLoad = 1;
int endOfLineNumber = 0;
int stepCount = 0;
int stringIndex = 0;
File configFile;
char inputString [1280];
char inputChar;

void setup() {
  stepToLoad = 13;
  if (!SD.begin(36)) {
    return;
  }

  if (SD.exists("config.txt")) {
    configFile = SD.open("config.txt");
    getStepCount();
    getStepData();
    configFile.close();
  }
}

void loop() {

}

void getStepData() {

  if (configFile) {
    while (configFile.available()) {
      inputChar = configFile.read(); // Gets one byte from serial buffer
      if (inputChar != '^') { // define breaking char here

        inputString[stringIndex] = inputChar; // Store it
        stringIndex++; // Increment where to write next

      } else {
        endOfLineNumber++;
        stringIndex++;
        if (endOfLineNumber == stepToLoad) { //this is the correct line to load

          break; //break out of the "while" loop
        } else { //not the correct line to load, reset and continue

          stringIndex = 0;
        }
      }

    }

  }
}

void getStepCount() {
  if (configFile) {
    while (configFile.available()) {
      inputChar = configFile.read(); // Gets one byte from serial buffer
      if (inputChar == '^') { // define breaking char here
        stepCount++;
      }
    }
  }
}

As far as I know it is not possible to read a file and meanwhile change a value.
What normally is done is:

Read the file
Store it in memory
Change the value in memory
Write the file

However, since the SRAM memory is very limited, the following approach is better:

For every buffer (512 bytes):

Read 512 bytes buffer
Change values in the buffer if needed
Write 512 bytes to another file
Until the end of the file to read is reached

Remove the original file
Change the name of the new file to the old file

You do not need to recopy the entire file, it is possible to simply read/modify/write the specific blocks containing the data to be changed.

@ChrisStratton True, but looking at the code from the OP, it also processes the entire file. But as you mention, it is not mandatory to read it completely or even sequentially.

How to write a variable value into a text file and modify it in the SD card?

This software design issue depends much on the chosen representation on file. In principle, there are two design dimensions. The first is textual or binary representation. The second is fixed or variable size records.
With textual representation (e.g. Serial.print) values are converted to text and stored on the file. The size of the record (e.g. line) depends on the number of characters needed for the value. New-line is often used as the record delimiter. To locate a specific record the file has to be scanned. There is no way to calculate the position of a record. When reading back the value the textual representation must be parsed and the internal representation in memory restored.
With binary representation (e.g. Serial.write) values are written directly from memory to the file. The size of the record is fixed as the size of a struct. Locating a specific record is easy; record index time record size. The SD library file.seek(position) is perfect to index the record. When reading the value back to memory there is no need for conversion as in textual representation.
It should be added that fixed size textual representation is also possible, e.g. make each line the same length by using a padding character (space, etc).
A text file with variable values is the more difficult as it is both textual representation and variable record. It is also the most inefficient as it requires compute power for the value representation conversions. The major advantage is that the text file can be generated with a ordinary text editor. No special tool or program is needed.
Binary file format with fixed records will require initialization.
Cheers!

It was super complicated for me at first but I understand it now. I'll upload just the DS3231 Code with the SD card functionality
#include <Wire.h>
#include <DS3231.h>
#include <SPI.h>
#include <SD.h>

DS3231 clock;
RTCDateTime dt;
File myFile;
String fileName = "000000.txt";

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

  // Initialize DS3231
  Serial.println("Initialize DS3231");;
  clock.begin();

  // Set sketch compiling time
  clock.setDateTime(__DATE__, __TIME__);

  // Set from UNIX timestamp
  // clock.setDateTime(1397408400);

  // Manual (YYYY, MM, DD, HH, II, SS
  // clock.setDateTime(2016, 12, 9, 11, 46, 00);
}

void getName(){
  String date = clock.dateFormat("mdy", dt);
  fileName[0] = date[0];
  fileName[1] = date[1];
  fileName[2] = date[2];
  fileName[3] = date[3];
  fileName[4] = date[4];
  fileName[5] = date[5];
}

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

  Serial.println("initialization done.");

  getName();

  myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    Serial.print("Writing to file...");
    myFile.println("testing 1, 2, 3.");
    Serial.println("done.");
  }
  else {
    Serial.println("error opening file");
  }
}

void loop()
{
  dt = clock.getDateTime();

  Serial.print("Long number format:          ");
  Serial.println(clock.dateFormat("H:i:s", dt));

  sdCard();
  getName();

  myFile = SD.open(fileName, FILE_WRITE);
  myFile.println("Testing 1...2...3...")

}

So what I did here was initialize the variable for the text name with placeholders and I used the date in a 6 digit format. Both variables being a string, I can set the first position of the text name to be the first position of the date. So all values are replaced. Should be the same thing for an 8 digit text name, but after that there is a limit, not including the file extension.

It's not clear that this answers the question asked, in large part because the question is unanswerably unclear, and needs to be closed.

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


text:
Couldn't connect to local server using Ethernet Shield and Arduino Mega 2560
I'm trying to connect the arduino mega and ethernet shield and try to send some data to a php script. I have connect the ethernet shield to the laptop. Lap is connected to router through wi-fi. Any help in advance please.
#include <SPI.h>
#include <Ethernet.h>

/******************** ETHERNET SETTINGS ********************/

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xD9 };   //physical mac address
byte ip[] = { 192, 168, 1, 5 };                   // ip in lan
byte subnet[] = { 255, 255, 255, 0 };              //subnet mask
byte gateway[] = { 192, 168, 0, 1 };              // default gateway

IPAddress server(192,168,1,2);
EthernetClient client;

void setup() {
    Serial.begin(9600);  // Initialize serial communications with the PC
    while (!Serial);     // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    Ethernet.begin(mac,ip,gateway,subnet);     // initialize Ethernet device
    Serial.print("My IP address: ");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
      Serial.print(Ethernet.localIP()[thisByte], DEC);
      Serial.print(".");
    }
    Serial.println();
    Serial.println("connecting....");
}

void loop()
{
  if (client.connect(server,1234)) { // REPLACE WITH YOUR SERVER ADDRESS
    Serial.println("Server connection OK");
    client.println("GET /add.php?temp1=10&hum1=20 HTTP/1.1");
    client.println("Host:" + server);// SERVER ADDRESS HERE TOO
    client.println("Content-Type: text/plain");
  } else {
    Serial.println("connection failure");
  }

  if (client.connected()) {
    client.stop();// DISCONNECT FROM THE SERVER
    Serial.println("disconnected");
  }

  delay(5000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

Serial Out Put
My IP address: 192.168.1.5.
connecting....
connection failure
connection failure
connection failure
connection failure
connection failure
connection failure
connection failure

and one more thing to add, I create a server on the shield instead of the client. It's working fine, I checked the IP and port using the laptop browser and I can connect to the server. Shield's client is the issue...

I had this problem for quite a long time and then I did a little bit of research!
Here it is in an easy explanation-
When you connect your Ethernet Shield to the Laptop the laptop takes the Ethernet Shield as a source of internet and tries to get an IP Address and other network stuff FROM the shield! BUT what we want is the other way round.
We want the Ethernet shield to take the laptop as a source of internet and get itself an IP assigned by the laptop!
What I do is I make a Laptop-Ethernet Shield network and a Laptop-WiFi network.(Simply means that I connect my laptop to WiFi and Ethernet shield)
Then I JOIN the two networks!
This joining of networks is called network bridging and is done easily, I'll tell you how-
If you're using linux then follow this link here.
else if you're running windows-
1) Connect your Ethernet Shield (With Arduino attached obviously) to the laptop and make sure that your laptop is connected to the WiFi.
2) Go to Network and Sharing Center.
3) Go to Change adapter settings.
4) Select your Wifi adapter and the Ethernet adapter together.
5) Right click on any of the selected adapter and click Bridge connections.
6) Wait till a new network bridge is connected and is done verifying after it's creation.
7) Upload the sketch again on Arduino and you'd be connected.
NOTE
DHCP may not always work as it's a feature of your router/WiFi and not your laptop so try assigning a mannual IP by calling Ethernet.begin(mac,ip) instead of using DHCP by caling Ethernet.begin(mc);
AND do change your ip to 192.168.1.XXX I mean change the last tuple so it does not clash with the ip of any other device.(XXX any number less than 255, generally 100-200)
Do let me know the outcome after trying this out! :D

I did as you pointed, then it created a  new connection with wifi and ethernet, but stii I can't connect.
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xD9 };   //physical mac address
byte ip[] = { 192, 168, 1, 5 };                   // ip in lan
Ethernet.begin(mac,ip);     // initialize Ethernet device

and one more thing to add, I create a server on the shield instead of the client. It's working fine, I checked the IP and port using the laptop browser and I can connect to the server. Shield's client is the issue...

Hi @Manav, now it's working.. I check the apache access log and the request is there, but it's returning 400 - bad request ?
`data = "temp1=10&hum1=20";
client.println("POST /add.php HTTP/1.1");
client.println("Host: " + server); // SERVER ADDRESS HERE TOO
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(data.length());
client.println();
client.print(data);'

192.168.1.120 - - [31/Dec/2016:10:19:52 +0530] "POST /add.php HTTP/1.1" 400 472 "-" "-" 192.168.1.120 - - [31/Dec/2016:10:19:57 +0530] "POST /add.php HTTP/1.1" 400 472 "-" "-"

changing following line worked 'client.println("Host: localhost");' tnx for all the support

Hahaha you're welcome  The key here was network bridging

First your network config is wrong. The gateway is outside the scope of your netmask. This is invalid and may fail the tcpip stack depending on how the Arduino library is implemented.
Second, once you fix this, your laptop needs to be configured as a router to access resources on your network resources unless 192.168.1.2 is the laptop you are connected to.

1)then what is a correct gateway?
2)192.168.1.2 is the laptop

and one more thing to add, I create a server on the shield instead of the client. It's working fine, I checked the IP and port using the laptop browser and I can connect to the server. Shield's client is the issue...

I would say that you need to set the gateway to the IP of the laptop (i.e. 192.168.1.2) in this kind of setup.
So with IP 192.168.1.5/255.255.255.0 with gateway of 192.168.1.2, anything in the range 192.168.1.XXX will be local. If the arduino tried to access anything outside of 192.168.1.XXX then it will be routed through the gateway IP to then routed through the proper route.

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


text:
Programming an ATmega328P by holding it on an Uno's
I was looking at this Uno clone, the Nanino and then happened to read this article on "Manhattan style" circuit design. Anyway, that got me thinking...
If I borrowed someone's Arduino Uno, could I hold a blank ATmega328P on top of the identical chip on that Uno and load a bootloader onto the board's chip as well as my chip? The desired result would be to give my blank ATmega328P a bootloader.

No, the programming scheme on the Uno only works when there already is a bootloader in the chip, and would likely be confused by a second chip if it did have one.  There have been some rumors that certain other programming schemes might somewhat tolerate parallelism, but those are not what the Uno supports.

It's easy enough to use a Uno to program a bootloader onto another chip. I describe this process here.
The idea of holding one chip on top of another is likely to fail for various reasons. Both chips will try to respond to the programming attempt at slightly different times, probably making them both fail to be programmed.
See my post about making a breadboard Arduino. It only takes a few wires to program the target chip.

However this isn't just "paralleling the pins" - it is using one chip to program another, in the way it is designed to do.

If I borrowed someone's Arduino Uno, could I hold a blank ATmega328P on top of the identical chip on that Uno and load a bootloader onto the board's chip as well as my chip? The desired result would be to give my blank ATmega328P a bootloader.

Well burning a bootloader(over a SPI communication) is quite different than simply uploading code(Serial communication), therefore it requires a specific setup which is an AVR-ISP.(In-System Programmer).
So you can't burn a bootloader by simply holding it over the other because of the Uno design.
The IC socket for the Atmega chip on the Uno board is not set for SPI communication so you can't burn a bootloader onto it directly. Instead, you'll have to do a similar setup to Nick Gammon's. Use one arduino as an ISP to burn the bootloader onto another.
Therefore placing the 'raw' chip in the socket and trying to burn the bootloader won't even work.
Note that in this setup, the Uno is communicating as an ISP and it uploads the code to the 'raw' Atmega328 chip. The chip on the Uno already has the bootloader(in fact it is configured/programmed to be an ISP).
Hope it helps!
Best of luck!


text:
Controlling servo via serial port without any delay
I have such code:
void setup() {
Serial.begin(9600);
}
void loop() {

}
void serialEvent() {
  while (Serial.available()) {
   Serial.println(Serial.readString());
  }
  }

When I send there something - it's sent with a delay (1-2 seconds). How can I make it so that Serial.readString() is carried out without delay?
Please, help me)

Don't use readString - it has a 1 second timeout. https://majenko.co.uk/blog/reading-serial-arduino

@Majenko, hmm... In serial port i got such string: engine:100b. How i can got key (engine) and value (100)?

https://majenko.co.uk/blog/splitting-text-c

readString() uses a 1 second timeout to determine when the end of a string occurs. It's not suitable for anything - I have no clue why they included it in the API.
Instead you need to read the data a character at a time (as and when characters become available) and use a suitable string termination indicator to trigger processing of the string.
A common termination indicator is \n (line feed) or \r\n (carriage-return followed by line feed).
Read each character when it arrives on the serial port and add it to a string (not a String, a string - a NULL-terminated array of char). Only when you see \n arrive should you then start examining the string to see what you have received, and act on it accordingly.
I have a blog post here that details reading from serial, and another one here that shows you some techniques for splitting up strings (strtok() is a useful function). There's also plenty of other questions here about splitting strings with answers detailing similar methods.


text:
Sending multiple messages over the serial monitor in nodeMCU
I am trying to send multiple messages wirelessly from one ESP8266-12E NodeMCU to another. I have successfully established the connection and am able to send and receive single messages. The MAC addresses are solely for the verification that the data is going to the right client. My trouble is sending multiple messages which I should be able to observe in the serial monitor.
Here's my server code:
#include <ESP8266WiFi.h>

extern "C" {
  #include <user_interface.h>
}

int32_t freq = 10000;

WiFiServer server(80);                            //Initialize the server on Port 80

void setup() {
  pinMode(D1,OUTPUT);
  pinMode(D2,OUTPUT);
  pinMode(D3,OUTPUT);

  Serial.begin(9600);                             //Start communication between the ESP8266-12E and the monitor window

  analogWriteFreq(freq);

  WiFi.mode(WIFI_AP);                             //This ESP8266-12E is an AccessPoint
  WiFi.softAP("NodeMCU_js", "12345678");          //Provide the (SSID, password)

  IPAddress HTTPS_ServerIP = WiFi.softAPIP();      //Obtain the IP of the Server
  Serial.println("Server IP is: ");                 //Print the IP to the monitor window
  Serial.println(HTTPS_ServerIP);
  server.begin();                                 //Start the HTTP Server

}

void loop() {
  WiFiClient client = server.available();         //Check if a client has connected to the server

  struct station_info *stat_info;
  struct ip_addr *IPaddress;
  IPAddress address;

  if (client) {
    Serial.println("Somebody has connected :)");

    stat_info = wifi_softap_get_station_info();

    while (stat_info != NULL){
      IPaddress = &stat_info->ip;
      address = IPaddress->addr;
      Serial.println();

      Serial.print("Client IP Address = ");
      Serial.print(address);
      Serial.println();

      Serial.print("Client MAC Address = ");
      Serial.print(stat_info->bssid[0],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[1],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[2],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[3],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[4],HEX);
      Serial.print(":");
      Serial.print(stat_info->bssid[5],HEX);
      Serial.println();

      if (stat_info->bssid[0] == 0xDC && stat_info->bssid[1] == 0x4F && stat_info->bssid[2] == 0x22 && stat_info->bssid[3] == 0x17 && stat_info->bssid[4] == 0xEE && stat_info->bssid[5] == 0x95){
          int duty1 = 150;
          int duty2 = 200;
          int duty3 = 250;
          Serial.println("Duty - 1 : "+String(duty1));
          Serial.println("Duty - 2 : "+String(duty2));
          Serial.println("Duty - 3 : "+String(duty3));

          analogWrite(D1,duty1);
          analogWrite(D2,duty2);
          analogWrite(D3,duty3);

          client.println(String(duty1)+"\r");                          //Server's response to the client
          client.println(String(duty2)+"\r");
          client.println(String(duty3)+"\r");
       }
      else {
        Serial.println();
        Serial.println("Client not recognized.");
      }
     stat_info = STAILQ_NEXT(stat_info, next);
    }
  }
}

Here's my client code:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

char ssid[] = "NodeMCU_js";
char password[] = "12345678";

IPAddress server(192,168,4,1);       // the fix IP address of the server

WiFiClient client;                // Creates a client that can connect to to a specified internet IP address and port as defined in client.connect()

void setup() {
  pinMode(D4,OUTPUT);

  WiFi.persistent(false);
  WiFi.mode(WIFI_STA);

  Serial.begin(9600);                 //Serial connection
  WiFi.begin(ssid,password);          //WiFi connection

  while (WiFi.status() != WL_CONNECTED) {         //Wait for the WiFI connection completion
    delay(500);
    Serial.println("Connecting...");
  }
  Serial.println("Connected.");
  client.connect(server,80);
}

void loop() {
  if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status
    String answer1 = client.readStringUntil('\r');
    Serial.println();
    Serial.print("From Server(1): ");
    Serial.print(answer1);
    client.flush();

    String answer2 = client.readStringUntil('\r');
    Serial.println();
    Serial.print("From Server(2): ");
    Serial.print(answer2);
    client.flush();

    String answer3 = client.readStringUntil('\r');
    Serial.println();
    Serial.print("From Server(3): ");
    Serial.print(answer3);
    client.flush();

  }
  else{
    Serial.println("Error in WiFi connection");
  }
}

It would be helpful if I could get the correct way of doing this.
Thanks in advance.

println sends \r\n. read until \n. flush() waits until data are send. you do not send data from client. why do you use flush?

flush() is used for waiting till transmission is completed. It can be used at server or client.

you do not transmit from client. only receive.

I am receiving at the client, as per my client code. Is it recommended to remove flush() at the client?

So I removed the flush() from the client sie and used it at the server. The problem still persists.

and the \r\r\n?

Where do I update \r\r\n?

you have client.println(String(duty1)+"\r"); printLN adds \r\n

It worked! Thanks a lot, Juraj! Could you post it as the answer?

from server you send at the end of line \r\r\n. first \r is in the string and \r\n is added by println. then at the client you read until \r the first line, the you read an empty line until next \r.