text:
L298N DC Motor Driver Conundrum
I am trying to control a single DC motor using a L298N DC Motor Driver. I have a 12V motor plugged into Out1 and Out2, a 7.4 volt battery wired to the 12v in and common ground, a m/m common ground going from the arduino grnd to the L298N common ground, and I have IN1 and IN2 connected to digital pins 2 and 3. I am powering the Uno with USB. I am also running a m/m wire from the Uno 5v to the L298N (I shouldn't have to) in order to power the L298N

I am using a basic code to test the motor
    int motor1pin1 = 2;
int motor1pin2 = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(motor1pin1, OUTPUT);
  pinMode(motor1pin2, OUTPUT);

}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(motor1pin1, HIGH);
  digitalWrite(motor1pin2, LOW);

  delay(1000);

  digitalWrite(motor1pin1, LOW);
  digitalWrite(motor1pin2, HIGH);

  delay(1000);
}

If I wire the 7.4v lipo battery directly to the L298N the red led doesn't go on. It only goes on when I run a 5V wire from the Uno to the L298N. Yet still I get no reaction out of the motor. However if I run a ground from the arduino directly to the out1 or out2, the motor turns in that one direction. Anyone have an idea what I am doing wrong?

I don't see any problem in your wiring and code. The only thing that's not exactly optimal is that the voltage provided by the battery is not just high enough. The L298N's supply voltage is supposed to be at least 2.5V above the logic supply voltage (the logic HIGH level to be precise). That would make 7.5V - you only have 7.4V.
That sounds like a tiny gap, but the battery voltage might drop further under load.
"run a ground from the arduino directly to the out1 or out2" - you should not do that as this can create a short circuit, depending on the state of the EN and IN pins.

According to my datasheet, the L298N only requires that the input voltage be above 6V when the 5V regulated output is being used - otherwise it is 5-35V

It sounds like you don't have the +5V regulator output enabled, which means you DO need the +5V from the UNO.  From the datasheet:  "The module includes an onboard regulator. When enabled by the jumper, +5V is provided as an output.  When disabled, a separate +5V input is required to control the logic level circuitry of this module"

Assuming you have the ENABLE jumper in place to enable motor control, then you should be able to drive the motor full-speed forwards or backwards without the UNO code at all - just use the +5V and GND lines from the UNO as 'logic level probes'.
According to my logic table a LOW (GND) on L1 and a HIGH (+5v) ON L2 will cause a motor connected to OUT1/2 to rotate one way, and reversing the logic on L1/2 will cause it to rotate in the other - at full speed (full speed being whatever the battery supply voltage can provide).
Once you have the motor(s) turning properly, THEN you can add the complexity of trying to control the speed and direction programmatically.  The code you showed does exactly the same as just using the +5 & GND leads as probes - with a 1 second delay between reversals.
Hope this helps
Frank


text:
Achieving low power with Seeeduino Cortex-M0+ powered from 12V battery
I have Seeeduino Cortex-M0+, which is similar to Arduino Zero, both using Atmel SAMD21 MCU. It is powered from 12V battery directly to 12V PWRIN jack. Current draw for LED blink test is 18mA. I tried two low power libraries:

https://github.com/rocketscream/Low-Power
https://github.com/adafruit/Adafruit_SleepyDog

with:

LowPower.standby(); delay(5000);
Watchdog.sleep(5000);

In both cases, the current draw dropped only to 12.7mA, which is still huge. I checked the datasheet of MP1496DJ-LF-2 step-down, switch-mode converter used by this board and its quiescent current is below 1mA, so it doesn't look like the source of high current consumption. I've read posts about Arduino Zero running on 5mA from 12V input in low power. What else can I do in order to get the current closer to 5mA?
I cross-posted at https://electronics.stackexchange.com/questions/607000/achieving-low-power-with-seeeduino-cortex-m0-powered-from-12v-battery

I did a few experiments with external DC/DC converters feeding 5V pin on Seeeduino Cortex-M0+ from 12V battery, bypassing its MP1496DJ-LF-2 power stage. Here are the results:

DC/DC model
sleep current [mA]
LED blink current [mA]

MP1496DJ built-in baseline
12.7
18.0

LM2596S generic
8.6
14.8

Pololu D24V22F5
5.0
11.2

Pololu D24V5F5
3.6
9.3

As @devnull at Electronics Stack has answered, the quiescent current of 5~10 mA from the LDO could be enough to make up for the lost currents.
I don't have any specific suggestions on code or parts, but I can give you some tips regarding methodology. If you're working on the software side to reduce current consumption, you might be better off eliminating the possibility of hardware imperfections entirely. I'd power the board with 3.3V directly and preferably cut the traces to 5V or other unused circuits. Reduce the current consumption to the lowest possible on software side, and then work on the hardware side. You could be better off with an external LDO or a 12V to 3.3V converter with a low quiescent current to power your board.
From my experience, currents can leak from even the most unexpected circuits. There could be a faulty or crappy capacitor with higher than usual leakage current, resistors in voltage dividers with resistance not high enough drawing a couple of mA in total, or some random transistors we didn't think of drinking 1~ mA per chip. Or combinations of everything above being responsible for only a few hundred uA per part, but totals to a few mA in total. It's best to make a board with the most barebone parts or get one.

source: Stack Exchange

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

sort: votes


text:
M5Stack - confused about I2C bus voltage
I've recently got one of these nice M5-Though devices (basically a water-proof M5-Core2). They have these 4-wire sockets to connect their sensors. The I2C socket has 4 pins for +5V, GND, SDA and SCL. According to the schematics (bottom of page), the SDA and SCL lines are directly connected to the GPIO pins of the ESP32. That means that most sensors connected to this socket will run the I2C bus at 5V. Even their own sensors (example) have pull-ups to 5V on the SDA and SCL lines.
Isn't this going to fry the ESP32? Different sources say that it's inputs are not 5V tolerant. So far, I always used the 3.3V line to power external sensors from the ESP32 (or added a level shifter).

you example link shows they have a shifters in front of the i2c gpios, and it explains: "use the 3.3V on SDA and SCL, M5Core GROVE provide 3.3V to data pins, 5V to power pin. only 3.3v allowed on VL53L0x". That said, weak pullups aren't as bad as a low-impedance hi/lo 5v signal, but it's easier to "ban" 5v than dig into specific devices and situations.

@dandavis That sentence also occurred to me, but it doesn't make sense in the context. It appears they have copied something from the documentation of the actual sensor which does no longer apply to the whole module. There is no 3.3V pin on the 4-wire line the sensor is connected with. They do use a shifter for the module, but the other way round (the ESP32 is on the left side there).

it clearly shows the module uses 3.3v pullups(R1+2), and a 3.3v LDO (U2) on the module. This allows greater flexibility for the modules as it's easer to convert 5v to 3.3v than boost a 3.3v feed into a 5v one.

i agree the schematics are a bit confusing, but do you really think they would design, make, and sell a modular system where their modules broke their MCU?

@dandavis I would surely hope they won't. But to me it still seems they're operating the MCU outside its specs. And while their products make a mature impression, their documentation does clearly not. It's not the first time I see a modular system that, when giving it a closer look, doesn't fit together.

No, it's not going to "fry" the ESP32, and here's why:
Yes, there are pullups to 5V. Those are 4.7K in your example. The IO pins are connected to 3.3V through ESD diodes. That means that any voltage over and above 3.3V plus the forward voltage of those diodes will be "diverted" away from the IO pin through the diode. IO pins have these ESD diodes built in, but this board has extra external ones added to make it more rugged.
These ESD diodes can handle a finite amount of current flowing through them - the internal ones only a small amount, but the external ones much more.
The 5V will only be a low current because it is connected with a resistor. We can even do some maths here.
Assuming the ESD diodes have a 0.3V forward voltage (as is reasonably typical) we can say that the voltage across the diode will be 5V - 3.3V - 0.3V = 1.4V.
With a 4.7K resistor as a pullup the current through the diode will be 1.4V / 4700 = 298 microamps.
That's way below the limit you'd expect of a small internal ESD diode, let alone a larger external one.
The "frying" of an IO pin happens when too much current flows through the ESD diode and it blows, "failing short", causing the IO pin to be locked in either a HIGH or LOW state for the rest of eternity. Since the current is nowhere near the kind of levels needed for that it's not going to even remotely stress the diodes, and the inclusion of external diodes makes it even safer.

Thanks, that sounds reasonable. But note that the external diodes in the example are to protect the sensor, not the ESP32. I'm worried about the input side of the ESP. I'll be going to attach another type of sensor, one that can operate directly at 5V and has no internal power converter.

@PMF The ESD diodes are not on the peripheral, they are on the main unit. Section "ESD" in the top right of the main schematic. Specifically D6.

Thanks, I didn't understand that part.

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


text:
Optimizing code for ATtiny10
I'm trying to squeeze code onto an ATtiny10, but I'm just not getting there. I'm using 1060 bytes and only have space for 1024 bytes.
The code is simple enough; I need to read a button pin. If high it needs to pick a random value and that causes one of two random LEDs on the PCB to turn on for two seconds. Is there a way to optimize this code to work on this IC?
int buttonState = 0;

void setup() {
    pinMode(3, INPUT);
}

void loop() {
    buttonState = digitalRead(3);
    if (buttonState == HIGH) {
        bool ranNum=random(0,1);
        if(ranNum == 0) {
            digitalWrite(0, HIGH);
        }
        else {
            digitalWrite(1, HIGH);
        }
        delay(2000);
        digitalWrite(1, LOW);
        digitalWrite(2, LOW);
    }
}

I'm not sure what the compiler would optimize out in this situation, but have you tried using direct port manipulation instead of using digitalWrite(), digitalRead() and pinMode(). When not using this the compiler might optimize these functions out.

Not sure if it helps byte wise but you can change if(ranNum == 0) {             digitalWrite(0, HIGH);         }         else {             digitalWrite(1, HIGH);         } into digitalWrite(ranNum == 0 ? 0 : 1, HIGH);

I'm unsure about how direct port forwarding works i'll look up some tutorials thanks for the suggestion. The ternary operator doesnt seem to save any bytes good suggestion tho

digitalWrite(ranNum & 1, HIGH) -- also use a uint8_t instead of an int.

also also random() is a wrapper around rand() which probably wastes bytes. Use rand() & 1 to get a random 1 or 0.

On such a small device, I would get rid of the Arduino core and program at the avr-libc level.

@EdgarBonet On such a small device I'd get rid of avr-libc and program it in assembly...

Please take a look at an article I wrote some time ago regarding AVR code optimizations.

Are your pins and pinMode()s correct?  pinMode(3,INPUT) seems like the default, and the random HIGHs on 0&1 seem inconsistent with the LOWS on  1&2

How big is the code if you replace random by a constant?

Related: Optimizing code to use less flash memory and SRAM and What can I do if I run out of flash memory or SRAM?

Aren't the LEDs quite weak? Isn't the default I/O input? The code as presented here would seem to switch the internal pull-up resistors on and off (as none of the I/O pins are set up as output). Switching the internal pull-up resistors on and off will produce some light on the LEDs, but not very much. The current through them will only be on the order of 0.1 mA (100 µA). Or is there some kind of driver circuit that makes up for it?

As I stated in a comment, this device would be too small for me to
consider programming it using an Arduino core. I would rather stick with
the avr-libc and direct port manipulation:
#include <stdlib.h>
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    DDRB = _BV(PB0)   // PB0 as output
         | _BV(PB1);  // PB1 as output
    for (;;) {
        loop_until_bit_is_set(PINB, PB3);  // wait for PB3 high
        if (rand() & 1)
            PORTB |= _BV(PB1);  // PB1 high
        else
            PORTB |= _BV(PB0);  // PB0 high
        _delay_ms(2000);
        PORTB &= ~_BV(PB0);     // PB0 low
        PORTB &= ~_BV(PB1);     // PB1 low
    }
}

This is plain C, but I expect it to be accepted by the Arduino IDE as a
valid .ino file. I tried compiling it like this:
avr-gcc -mmcu=attiny10 -Os -Wall -Wextra -DF_CPU=8000000 prog.c -o prog.elf

And it resulted in a program that uses 660 bytes of flash. Most of that
is in the implementation of rand() and its dependencies
(multiplication and division routines).

If rand() is really taking up that much space, you could probably save a lot of it by using a more compact RNG. Here's one of my favorites, which should run fine on an ATTiny and probably generate better randomness too.

You could even use the LSB noise of the ADC to generate a random number. Works pretty well from my experience.

If the button is pressed by a human and your clock is high enough (MHz range), you can use a trick and get rid of the RNG.
You can replace it with a free running counter like this:
unsigned char count = 0;

void loop() {

    count += 1;

    buttonState = digitalRead(3);

    if (buttonState == HIGH) {
        if( (count & 1) == 0) {
            digitalWrite(0, HIGH);
        }
        else {
            digitalWrite(1, HIGH);
        }
        delay(2000);
        digitalWrite(1, LOW);
        digitalWrite(2, LOW);
    }
}

You have count incremented every ⪝10 us (depending on your clock speed, attiny executes one instruction per cycle), so when the user pushes the button, the counter will be sampled.
Note: I assumed loop() is all what the microcontroller has to do, and it's constantly called.

That's better randomness than an RNG.  Since delay and its clock is running, you could use its TCNT0 or TCNT0L instead of count and get faster counting at zero cost.

Neither loop() nor digitalWrite() may not even be called. The underlying GCC compiler is pretty good at inlining, optimising them down to single assembly instructions.

What does it matter, if the function was inlined or not in this context? At the end the function code gets executed, regardless if the compiler inlined it or not.

@next-hack: Function calls are instructions which use up valuable flash space (and need time to execute).

@Michael, I think I quite know that... Still, what's the connection between Redy000's answer and the fact that loop() or DigitalWrite() might be inlined, or implemented as an actual branch ?

Are you sure the pins are correct?
Maybe use a smaller random number generator per https://arduino.stackexchange.com/a/18092/6628 ?
static uint8_t lfsr = 0x01;
const byte LFSR_MASK = 0x8e;

void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(3, INPUT);
}
void loop() {
  //      int buttonState = digitalRead(3);
  if (digitalRead(3)) {
    if (generateNoise()) {
      digitalWrite(0, HIGH);
    }
    else {
      digitalWrite(1, HIGH);
    }
    //delay(2000)
    //for (int i = 31; i; i--)_delay_us(64516);
    _delay_ms(2000);
    digitalWrite(0, LOW);
    digitalWrite(1, LOW);
  }
}

uint8_t generateNoise() {
  // Return 1 bit of noise using a Galois Linear Feedback Shift Register
  // See https://en.wikipedia.org/wiki/Linear_feedback_shift_register#Galois_LFSRs

  if (lfsr & 1) {
    lfsr =  (lfsr >> 1) ^ LFSR_MASK ;
    return (1);
  }
  else         {
    lfsr >>= 1;
    return (0);
  }
}

The RNG didn't help as much as changing the much-disparaged delay.

Your linear feedback register seems indeed quite efficient space-wise. Plugging it into my implementation of the program reduced its size from 660 to 142 bytes!

Great. You could probably afford go to a 16 or 32 bit random state variable for richer randomness.

An 8-bit chip requires multiple instructions for processing 16 bit. Changing ints to either uint8_t or int8_t will save code.
Depending on compiler optimization, replacing
if ( (count & 1) == 0) {
    digitalWrite(0, HIGH);
}
else {
    digitalWrite(1, HIGH);
}

with
digitalWrite((count & 1), HIGH);

could save bytes.

I tried the optimization you suggest on an Uno. It saved two bytes.


text:
Unexpected character added to char buffer array in serial monitor only when SD card initialized
I'm getting an unexpected extra character added to the serial monitor print line only when I initialize an SD card in the code.
Normal
The code below gives me this expected result in the serial monitor:
Serial Monitor
23:31:12.745 -> inputString: abc

Code
const int BUF_DIM = 3;
char inputString[BUF_DIM];

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  inputString[0] = 'a';
  inputString[1] = 'b';
  inputString[2] = 'c';

  Serial.print("inputString: ");
  Serial.println(inputString);
}

void loop() {
}

Unexpected Character
However, the serial monitor prints an unexpected extra M at the end of inputString's value abc when I add initialization of an SD card.
Serial Monitor
23:24:30.319 -> Initializing SD card...initialization done.
23:24:30.319 -> inputString: abcM

Code
#include <SPI.h>
#include <SD.h>

File myFile;

const int BUF_DIM = 3;

char inputString[BUF_DIM];

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  //-------------Toggle this block to see the M dissapear-----------
  Serial.print("Initializing SD card...");
  if (!SD.begin(5)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  myFile = SD.open("DATA.TXT");
  //-------------Toggle this block------------

  inputString[0] = 'a';
  inputString[1] = 'b';
  inputString[2] = 'c';

  Serial.print("inputString: ");
  Serial.println(inputString);
}

Why is this happening and how can I get the serial monitor to behave as expected with the SD card.

const int BUF_DIM = 3;

char inputString[BUF_DIM];
...

  inputString[0] = 'a';
  inputString[1] = 'b';
  inputString[2] = 'c';

...

  Serial.println(inputString);

You have allowed three characters in your array and indeed put three characters there, however you have not put a "null terminator" there at the end (nor is there room for one) so you will naturally get garbage at the end of the string until the processor happens to find a 0x00 byte.
Put it another way, how does the code know to print three characters and not 20 characters? The answer is that the underlying function (Serial.println in this case) looks for a null-terminator.
You need to read up on how null-terminated strings work.

Ahh yes inputString[2] = '\0'; fixed the issue. Didn't know about null-terminators. Thanks!


text:
Is there a definitive reference for the Arduino DUE?
I am looking for a reference document or documentation system that concretely relates at minimum:

Screen printed pin name/number
SAM3X8E pin number
Register number
Channel number
Port name

In my case I am looking to change the PWM characteristics of pins 2 and 3 (as named on the physical board). Various forum posts discuss setting registers, register pin mappings, but nothing seems to quite tie up.
On the Arduino as printed, Pins 2 to 13 are listed as PWM pins, 12 in total. By this page, pins 2 and 3 map to PB25 and PC28 respectively on the SAM3X8E chip. Presumably this suggests Pin 2 is on the 'B' port, and 3 is on the 'C' port. Referencing this page, the sample code goes through 'all 8' PWM ports and pins, which by the register naming scheme PIO_ASBR_Pxx, suggests the pins numbered 16 to 19 are on the B Port, and 21 to 24 are on the 'C' port. Later the PWM ports are again iterated over with the PWM->PWM_CH_NUM[i] where i runs from 0 to PWMCH_NUM_NUMBER - 1, which is suggested as 8 in total.
'Pin 2' on the board then seems to have a mapping to a named pin on the Atmel chip of PB25, somewhere between 21 and 24 on the register name and between 0 and 7 on the channel index. Surely there is a place that attempts to harmonise all of these disparate naming conventions.
Further Information:
For instance, PWM/Digital Pin 2 maps to PB25 on the chip, as per the schematic provided by Majenko. PB25 is not a member of the PWM pins as per the chip datasheet. How am I to understand this?
When referencing the name PIO_ASBR_19, this is the 20th bit in the PIO_ASBR register, but how does this bit map onto the port/pin mapping? Then while the datasheet discusses the 'PIO_ASBR' register, since that can relate to at most 32 pins, the datasheet does not expand on how to map the excess pins.

The name -> pin -> port/bit mapping can be got from the schematic. The PWM mappings of channel -> pin can be got from the SAM3X8E datasheet.

in Arduino store: https://content.arduino.cc/assets/Pinout-Due_latest.pdf

Forgive my simplicity, but it looks like both references, the schematic and the pinout, simply relate the screen printed pin names with the P[A|B|C|D][dd] notation. When I review the (enormous) chip datasheet, I cannot find the majority of the register definitions required to map back to the pin notation. Could you help me interpret that document?

PC7 is Port C bit 7. There's nothing much to interpret. For special peripherals like PWM you just look them up in the port multiplexing table (section 9.3).

@Juraj I can see there is a lot of information, but it still seems to fail to identify 1) What PWM ID (i=0..7) Pin 2 corresponds to, which bit the pin is in any register (16..19, 21..24).

@Majenko: Pin 2 is PB25, that doesn't help in identifying its PWM ID or position in a register.

I see there pins labeled PWML1, PWMH0 . Is it the PWM ID?

Pin 2 is PB25. That's bit 25 in the Port B registers. In the matrix table PB25 has alternate function TIOA0.

@Juraj Perhaps it is, it definitely does not correspond to the 12 pins printed on the board, and I can see Pin 2 and 3 are not members of this set.

I think your confusion may come from the fact that there's two ways of generating PWM: using the "Fast PWM" module and using a timer.

@Majenko you will note from my second link with the example code, PB25 is not one of the registers addressed when enabling the high speed PWM. They are 16..19 on port B and 21..24 on port C, which by the pin mapping I linked, are D47..44 and D9..6 respectively, again different to the datasheet Juraj provided.

Also you may be right, the Arduino strikes me as a bit of a mess when it comes to anything slightly advanced. I might ask a simpler question then, which is how I can get a higher frequency of PWM switching on Pins 2 and 3.

I have always held the opinion that the Due, in general, is one of the worst Arduino boards ever made. I would never recommend it for anything.

The full pinout is available on arduino.cc in Store and in the Getting started section.

For instance, PWM/Digital Pin 2 maps to PB25 on the chip. PB25 is not a member of the PWM pins as per the chip datasheet. How am I to understand this?

The Arduino core uses timers to do PWM on pins without native PWM support.
In analogWrite source code you can see sections for DAC, PWM and TIMER PWM pins.
The information about pins for Arduino core is in variant.cpp.


text:
How to install the application + its configuration to many devices of the same kind? (ESP32)
Being the newbie in the Arduino area... Having more devices, how can I upload some configuration parameters after the code was uploaded? Is it possible?
Situation: I have the simple application for ESP32 with a simple sensor. It is to be used on many physical locations. Each location has its own Wi-Fi with its own SSID and password. An IT person on the location should be able to set the configuration parameters somehow. I would like to learn the possibilities -- to choose what is more suitable.
Separate compilation and upload: If I understand correctly, I can use the arduino-cli compile ... to compile the sketch to binary, and then arduino-cli upload ... to put the binary into the device. This way, I am able to prepare many devices with exactly the same binary content. (If I understand it correctly, then arduino-cli config ... is for setting the development environment, not for configuring the application on the board.)
Configuration: I have noticed the existence of Arduino Preferences Library (Preferences.h). I understand how to use it from inside the code of the application. Can the wanted preferences be uploaded to the board similarly as the sketch is? (I guess no, but asking to be sure.)
I have also noticed the existence of a lightweight file system (SPIFFS), and the ability to create (say) /config.json on the device from inside the application code. There is the plug-in to Arduino IDE to appear as a new tool (.../tool/esp32fs.jar). Then the data/ subdirectory is created in the sketch directory, and its content can be uploaded by another IDE command. That seems to be nice way to upload the configuration in my case; however, ...
Is there any command-line alternative to upload the configuration data that way? Can a single file be uploaded, or is it necessary to erase whole file system area, and upload whole content of the data/ like directory?

for the upload part: you can use "Export compiled binary" in IDE and then use esptool.py to flash the binary without Arduino tools.

Thanks, Juraj. That helped.

There's even an Android app that can be used for the upload on site.

If you don't want to include the individual config data in the sketch for each location there are mainly two possibilities to handle that:

As consumer IOT devices often do you can write your code to create a hotspot with a website, where the IT staff can then connect to and config the device by inputting the config data into the website.
You can use SPIFFS/LittleFS (The second is the successor of the first) to create a config file, which you then can read at the start of your sketch. This file system is saved in flash and can be written with an extra tool.

I would go for the second option. I'm currently still using SPIFFS, so I don't know if the following will be different for LittleFS. Your paths might vary (depending on core/version/OS).

First create your data directory, where you then place your config.json file. The standard is a directory named "data" inside the sketch folder.

Then you need to invoke mkspiffs to create a binary image for your data folder. I'm doing it like this:
 ~/.arduino15/packages/esp32/tools/mkspiffs/0.2.3/mkspiffs -c ./data -d 5 -b 4096 -s 0x170000 -p 256 ${file_path}/spiffs_image.bin

{file_path} is the path of the sketch folder for me. That way the image is placed directly besides the sketch. The options mean the following (I will also paste the help page of the command below):
 -d 5  -->  Debug Level at max (goes from 0 to 5)
 -b 4096  --> block size in bytes
 -s 0x170000  -->  image size in bytes
 -p 256       -->  page size in bytes
 -c ./data    -->  data directory

You can get these information when you look at the verbose output in the Arduino IDE while uploading the filesystem over the tool. They depend on your board and the settings that you use (mostly the partition scheme).

Then you can upload the image file via the esptool.py:
  ~/.arduino15/packages/esp8266/tools/python3/3.7.2-post1/python3 ~/.arduino15/packages/esp32/hardware/esp32/1.0.5/tools/esptool.py --port /dev/ttyUSB0 --baud 921600 --before default_reset --after hard_reset write_flash 0x290000 ${file_path}/spiffs_image.bin

0x290000 is the position in flash, where the data should be written. This also depends on your partition scheme and it should also appear in the Arduino IDE output, where you can copy it from. Note, that I'm invoking the python version here, that comes with the ESP32 core.

This works great for my ESP32 board (using the Wemos LOLIN32 with the "Standard" Partition scheme). Now you will have to think of a fitting workflow. You can have individual data directories and images for each location. Or you can change the file everytime you invoke the commands above (you can even do this in a script).

Here the help output of mkspiffs:
~/.arduino15/packages/esp32/tools/mkspiffs/0.2.3/mkspiffs --help

USAGE:

   /home/christian/.arduino15/packages/esp32/tools/mkspiffs/0.2.3/mkspiffs
                                        {-c <pack_dir>|-u <dest_dir>|-l|-i}
                                        [-d <0-5>] [-a] [-b <number>] [-p
                                        <number>] [-s <number>] [--]
                                        [--version] [-h] <image_file>

Where:

   -c <pack_dir>,  --create <pack_dir>
     (OR required)  create spiffs image from a directory
         -- OR --
   -u <dest_dir>,  --unpack <dest_dir>
     (OR required)  unpack spiffs image to a directory
         -- OR --
   -l,  --list
     (OR required)  list files in spiffs image
         -- OR --
   -i,  --visualize
     (OR required)  visualize spiffs image

   -d <0-5>,  --debug <0-5>
     Debug level. 0 means no debug output.

   -a,  --all-files
     when creating an image, include files which are normally ignored;
     currently only applies to '.DS_Store' files and '.git' directories

   -b <number>,  --block <number>
     fs block size, in bytes

   -p <number>,  --page <number>
     fs page size, in bytes

   -s <number>,  --size <number>
     fs image size, in bytes

   --,  --ignore_rest
     Ignores the rest of the labeled arguments following this flag.

   --version
     Displays version information and exits.

   -h,  --help
     Displays usage information and exits.

   <image_file>
     (required)  spiffs image file

And for the esptool.py:
~/.arduino15/packages/esp8266/tools/python3/3.7.2-post1/python3 ~/.arduino15/packages/esp32/hardware/esp32/1.0.5/tools/esptool.py --help
usage: esptool [-h] [--chip {auto,esp8266,esp32,esp32s2beta}] [--port PORT]
               [--baud BAUD]
               [--before {default_reset,no_reset,no_reset_no_sync}]
               [--after {hard_reset,soft_reset,no_reset}] [--no-stub]
               [--trace] [--override-vddsdio [{1.8V,1.9V,OFF}]]
               [--connect-attempts CONNECT_ATTEMPTS]
               {load_ram,dump_mem,read_mem,write_mem,write_flash,run,image_info,make_image,elf2image,read_mac,chip_id,flash_id,read_flash_status,write_flash_status,read_flash,verify_flash,erase_flash,erase_region,version,get_security_info}
               ...

esptool.py v2.9-dev - ESP8266 ROM Bootloader Utility

positional arguments:
  {load_ram,dump_mem,read_mem,write_mem,write_flash,run,image_info,make_image,elf2image,read_mac,chip_id,flash_id,read_flash_status,write_flash_status,read_flash,verify_flash,erase_flash,erase_region,version,get_security_info}
                        Run esptool {command} -h for additional help
    load_ram            Download an image to RAM and execute
    dump_mem            Dump arbitrary memory to disk
    read_mem            Read arbitrary memory location
    write_mem           Read-modify-write to arbitrary memory location
    write_flash         Write a binary blob to flash
    run                 Run application code in flash
    image_info          Dump headers from an application image
    make_image          Create an application image from binary files
    elf2image           Create an application image from ELF file
    read_mac            Read MAC address from OTP ROM
    chip_id             Read Chip ID from OTP ROM
    flash_id            Read SPI flash manufacturer and device ID
    read_flash_status   Read SPI flash status register
    write_flash_status  Write SPI flash status register
    read_flash          Read SPI flash content
    verify_flash        Verify a binary blob against flash
    erase_flash         Perform Chip Erase on SPI flash
    erase_region        Erase a region of the flash
    version             Print esptool version
    get_security_info   Get some security-related data

optional arguments:
  -h, --help            show this help message and exit
  --chip {auto,esp8266,esp32,esp32s2beta}, -c {auto,esp8266,esp32,esp32s2beta}
                        Target chip type
  --port PORT, -p PORT  Serial port device
  --baud BAUD, -b BAUD  Serial port baud rate used when flashing/reading
  --before {default_reset,no_reset,no_reset_no_sync}
                        What to do before connecting to the chip
  --after {hard_reset,soft_reset,no_reset}, -a {hard_reset,soft_reset,no_reset}
                        What to do after esptool.py is finished
  --no-stub             Disable launching the flasher stub, only talk to ROM
                        bootloader. Some features will not be available.
  --trace, -t           Enable trace-level output of esptool.py interactions.
  --override-vddsdio [{1.8V,1.9V,OFF}]
                        Override ESP32 VDDSDIO internal voltage regulator (use
                        with care)
  --connect-attempts CONNECT_ATTEMPTS
                        Number of attempts to connect, negative or 0 for
                        infinite. Default: 7.

Thanks @chrisl. That seems to be exactly what I need. :)

I usually use BLE to set the WiFi credentials.
After the WiFi connection is taken care of, I usually provision the rest of the configuration data by having a web application in the LAN that I put into "pairing" mode with the MAC address of the ESP. The ESP then downloads the config from the web application. Although I don't have super secret config data, for good measure the application ends the pairing mode after one download and will not serve further config requests.


text:
Limit on connector cable for HC-SR04 ultrasonic sensor
Is there a limit for the connector distance between an arduino and a HC-SR04 ultrasonic sensor?
I have a set-up for measuring a liquid's level in a tank. The benchtop version worked OK, but when I deployed it, I introduced a 10meter cat5 cable connecting the HC-SR04 to the arduino, it is giving me strange distance readings (they are showing the same distance, even though the level has changed significantly).
The 10m of cat5 is the only element that has changed from the benchtop tests.
Is this length of cat5 a potential problem? If so how can I diagnose it? I have a multimeter and basic oscilloscope?
Update:
I measured 4.77v across the sensor's 5v/GND on the breadboard with arduino and 4.65v on the sensor itself.

Check the voltage levels at the sensor and at the input of the Arduino (for the echo and trigger you might need the oscilloscope to get a good reading). Over that length you might have significant voltage drop.

Cat 5.e cable is specially designed to carry on differential (or balanced) signals (that is why it consists of four twisted pairs - each pair is like tunnel for signal)
On the other hand, the ultrasonic sensor utilizes non-balanced, non-differential signal of high frequency, so, the valid length of cable, that couldn't destroy the data in the signal accuracy is about 0.3-0.5 meter only.
You can check my words by comparing a plots of the signal (on controller input pin) with 10cm and 10m cables.
The digital signal must have nice, square form like this:

But the signal, which is passed through long line of wire can be look like this:

And this is bad, because now the controller could not interpret this signal shape correctly.

Is there a way of 'squaring' off the signal at the end of the long cable?

Yes and no, actually. The simplest way to do this - is to place the controller as near as possible to the sensor. The other way implies the idea of using differential signals - for example, use four of RS485 (i.e, the MAX485 integrated circuit) transceivers. Use one pair of them to send the Trig signal from the MCU, and another pair - to send the Echo signal


text:
How to convert serialized JSON string back to JSON object?
How to convert JSON String for example
{"f0":100,"f1":100,"f2":100}

It is what I get from my esp01 side from I2C communication
Now I want it to get it back to my Arduino side variables int f0 ,int f1 ,int f2
But example shown in web site uses kind of different serialized JSON
Example shown,
char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
Can I convert the data I got from I2C communication for using in the method for deserializeJson(jsonobj, stringofdata)
I2C communication side of arduino looks like,
void receiveEvent(size_t howMany) {
  String datain = "";
  while (0 < Wire.available()) {
    char c = Wire.read();
    datain += c;
  }
  Serial.println(datain);
//be careful can't send too much json data I2C crash!
  Serial.println(datain.length());
  DynamicJsonDocument datajson(100);
  if (deserializeJson(datajson, datain)) {
    Serial.print("deserialization ok ");
    digitalWrite(13, HIGH);
    delay(250);
    digitalWrite(13, LOW);
    f0 = datajson["f0"];
    f1 = datajson["f1"];
    f2 = datajson["f2"];

    Serial.println(String(f0) + " " + String(f1) + " " + String(f2));
  }

}

In serial monitor I only see this no deserialization worked
{"f0":0,"f1":0,"f2":0}
22

the return value of deserializeJson is not boolean.

You cannot concatenate string literals (" ") with +. That just adds the pointer addresses together.

I tried with DeserializationError error error inside if condition still no luck

Debug errors like that:
if (err) { Serial.print(F("deserializeJson() failed: ")) Serial.println(err.c_str())
} else { //your code
}

@Juraj I believe you almost answered my question it is not a Boolean  but however it works as Boolean however for a correct deserialization I need to take the inverse of it that, It was my mistake I first thought that gives a Boolean  as correct deserialization as true its not;

The mistake I did was thinking deserializeJson(datajson, datain) gives a Boolean as true for correct deserialization but accually it gives an object of DeserializationError err so need to check if there is no error thus
The new code
// need ! here
  if (!deserializeJson(datajson, datain)) {
    Serial.println("yay it worked");
    Serial.print("deserialization ok ");
    digitalWrite(13, HIGH);
    delay(250);
    digitalWrite(13, LOW);
    f0 = datajson["f0"];
    f1 = datajson["f1"];
    f2 = datajson["f2"];

    Serial.print(f0);
    Serial.print(" ");
    Serial.print(f1);
    Serial.print(" ");
    Serial.println(f2);

//also tested this way and it works too
    Serial.println(String(f0) + " " + String(f1) + " " + String(f2));
  } else {
    // I was coding here thinking its Boolean before
    //error
  }

For reference, here is the documentation of deserializeJson().


text:
A library issue with ArduinoOTA for MKR1400GSM
For the past years I've been using ArduinoOTA along with ArduinoHttpClient on MKR1400 for updating the bin on the fly from a remote web server.
Even without ArduinoOTA's official support for GSM, it has been working like a charm. All it took was adding a condition to ArduinoOTA.h to accept MGRGSM (thanks Juraj) and some playing around with the code to ensure successful operation:
#elif defined(_MKRGSM_H_INCLUDED)
ArduinoOTAClass <GSMServer, GSMClient> ArduinoOTA;

Unfortunately, the other day I went ahead and updated by IDE's libraries without first backing them up and now I lost the ability to perform successful OTA.
What I have done so far is to step back with libraries versions and check the dates of the lib updates (I found a point in time when I knew I compiled a good version before the lib has been updated) but so far nothing, the OTA process starts and it bricks the board.
Any idea? Thanks!

Arduino made changes in platform.txt files for IDE 2.0 pluggable monitor system, which is a system to detect COM ports, network ports and other means to upload to Arduino.
While they did the changes they forgot to test the OTA support with IDE 1 so they broke OTA in AVR and SAMD core. The affected versions of core are AVR 1.8.4 and SAMD 1.8.12.
Arduino already fixed the error in platform.txt in both cores and AVR core already has a new release 1.8.5 with the fix. The SAMD core doesn't have a new release yet. You can apply the fix to your 1.8.12 installation, or return to 1.8.11 version. EDIT: SAMD core 1.8.13 is already available too.
EDIT: Or you can use the 'fake programmer' method which doesn't require network port to be detected by the IDE and has a separate configuration.

Thanks for the information, I tried the fix and returning to 1.8.11, nighter worked, but I was able to get progress with an old backup of the libraries folder and rolling back IDE to 1.81 (I assume newer versions would work as well but didn't have the time to test). For now I can do OTA updates of most types, some do not work like updating an older bin over a new one but what do works may ends up as enough.

@Nino SAMD core 1.8.13 is available

Cool! I can confirm, a fresh new installation works like a charm, thanks a lot Juraj.

I tried all over again, IMHO it's not possible to get a large bin file uncorrupted directly on a SD card. The only way i see is first into the internal memory of the modem and then on the SD card. I made a example:
https://github.com/CptHolzschnauz/Arduino-MKR-1400-OTA-Update

this is not an answer to the Question


text:
How to detect ESP32 vs ESP8266 automatically when uploading the application?
I have the same application for both ESP32 and ESP8266 (the same functionality). The person, who is not an IT expert is expected to launch the dedicated installer program to upload the (first/new) version of the application. How can the installer (the program) detect what version of hardware is connected through USB? The goal is to upload the correct variant of he application. Is it possible at all?

esptool.py reports it

You can attempt to get the "chip ID" from the target board using esptool.py. The ESP8266 has a chip ID, but the ESP32 doesn't.
Running esptool.py --port <serial port> chip_id will either tell you, amongst other things:
Detecting chip type... ESP8266
Chip is ESP8266EX
....
Chip ID: 0x00a70414

Or:
Detecting chip type... ESP32
Chip is ESP32-PICO-D4 (revision 1)
...
Warning: ESP32 has no Chip ID. Reading MAC instead.

You can do similar with the read_mac command. In fact any operation on esptool.py that interacts with the target first probes the target to find out what the target is and report it - commands like chip_id and read_mac are just nice simple examples that return minimal information and don't interact with the target more than just querying the chip.

I suppose that you can't do it wrong anyway, can you? I mean attempting to upload an ESP8266-program to an ESP32 or vice versa will probably just result in an error?


text:
Is possible to use heap_trace_init_standalone() on arduino framework with esp32?
I need to trace memory leak but I can't find a way.
on IDF you can use heap_trace_init_standalone but there is not present on arduino framework.

If you add #include <esp_heap_trace.h> (and define CONFIG_HEAP_TRACING) at the top of your sketch, the method should be available.
It is defined in esp32\tools\sdk\esp32\include\heap\include\esp_heap_trace.h


text:
Reading & writing a configuration file on an Adafruit Circuit Playground Express
I would like to store an application's configuration in a file stored on the Circuit Playground Express (CPX) flash. The application itself needs to be able to update the configuration file. Things I need to store are basic, for example:

NeoPixel brightness (eg. brightness = 0.9)
NeoPixels on/off (eg. NP_enable = [0,0,1,0,1,0,1,1,1,1]

ArduinoJason seems appropriate, but I cannot even get to the point of writing files to the CPX. The TinyUSB libraries are supposed to give the ability to write to the CPX SPI Flash, but I cannot get any of the examples included with this library to compile.
I am trying to compile the msc_external_flash example provided with the TinyUSB library. I get the following 2 errors:
In file included from /home/pi/Arduino/libraries/Adafruit_TinyUSB_Library/examples/MassStorage/msc_external_flash/msc_external_flash.ino:28:0:
/home/pi/Arduino/libraries/Adafruit_TinyUSB_Library/src/Adafruit_TinyUSB.h:31:2: error: #error TinyUSB is not selected, please select it in "Tools->Menu->USB Stack"
#error TinyUSB is not selected, please select it in "Tools->Menu->USB Stack"
^~~~~
msc_external_flash:65:6: error: #error No QSPI/SPI flash are defined on your board variant.h !
#error No QSPI/SPI flash are defined on your board variant.h !
^~~~~

The board selected is SAMD-->Circuit Playground Express.
There is no Tools menu item for selecting the USB stack.
Regarding the second error,
From msc_external_flash.ino:
  #if defined(EXTERNAL_FLASH_USE_QSPI)
    Adafruit_FlashTransport_QSPI flashTransport;
  #elif defined(EXTERNAL_FLASH_USE_SPI)
    Adafruit_FlashTransport_SPI flashTransport(EXTERNAL_FLASH_USE_CS, EXTERNAL_FLASH_USE_SPI);
  #else
    #error No QSPI/SPI flash are defined on your board variant.h !
  #endif

of the files named variant.h, this looks like the best candidate:
/home/pi/.arduino15/packages/arduino/hardware/samd/1.8.12/variants/circuitplay/variant.h
but the file does not contain the string "EXTERNAL_FLASH", nor anything I see that is CPX specific.
Arduino version is 1.8.19, which I am running on a Raspberry Pi 3 B+ running Buster.
Thanks,
Scott

please describe the problem and ask a question ... this site is not a forum

ArduinoJson has an example that reads a configuration file from the SD card. See JsonConfigFile.ino. You can easily adapt it for any other filesystem, such as SPIFFS and LittleFS.

install the Adafruit SAMD core. it looks like you are using the Arduino SAMD core, which has only basic support for the Adaruit board

The board selected is SAMD-->Circuit Playground Express. I can run other CPX examples, like IRNeoPixels, I assume I have the Adafruit SAMD core.

yes but you can't compile Adafruit specialties with the Arduino SAMD core

The problem was using the Arduino SAMD board core instead of the Adafruit SAMD board core. The Adafruit SAMD board core is not visible unless you add:
https://adafruit.github.io/arduino-board-index/package_adafruit_index.json
to the "Additional Boards Manager URLs:" field of the Arduino IDE preferences panel.
Once you do that...
Then install the "Adafruit SAMD Boards" from the Arduino IDE Boards Manager.
Then select the menu item:
Tools -->
Board: -->
Adafruit SAMD (32-bits ARM Cortext-M0+ and Cortext-M4) boards -->
Adafruit Circuit Playground Express (SAMD21)
I have not seen this procedure in any Adafruit documentation.

https://learn.adafruit.com/adafruit-feather-m0-basic-proto/setup


text:
Set time() on ESP8266
If I call configTime() on a ESP8266 using ESP8266 Core, then time() gets changed from uptime to unixtime. However this sends a SNTP request. I have a DS3231 RTC attached without internet. How can I set time() without calling configTime()?
Thanks in advance

Probably settimeofday(...) is what you want.

Whenever you have epoch time, either from RTC, NTP, etc., use the POSIX function settimeofday() to set system time as @Majenko said
The sample code is as follows:
// Assuming we already have Unix `epoch` time, which is time from Jan 1 1970.
// From RTC, NTP, etc.
time_t epoch_t = epoch;

// set the time to UTC
setTime(epoch_t);

// set the system time to UTC
timeval tv = { epoch_t, 0 };
settimeofday(&tv, nullptr);

// Now we can have system time by calling time()
time_t timeNowUTC;
struct tm * timeInfo

timeNowUTC = time(nullptr);
timeInfo = localtime(&timeNowUTC);

For the record, the issue has been solved in Arduino Forum : Update time() from DS3231


text:
Is it possible to use mathematical sets and their operations in arduino?
In python there is the object set that resembles a mathematical set, namely, you can remove elements from it, add elements to it, you can calculate the intersection/union between two sets, etc.
Is there a library or built-in functions that have those capabilities? I have been unlucky because when I use the word "set" as query term for the engine search, it always sends me to something related to the verb to set.

The Standard Template Library (STL) can be installed on the Arduino. It is not there by default. That includes things like sets.
One implementation is here.


text:
Arduino Nano Ble Sense stopped working suddenly
My Arduino Nano 33 BLE Sense stopped working suddenly a while after uploading firmware for an ML project. I've used my board for several ML projects and it worked like a charm.
I can't find the board in the Arduino IDE's port section.
I've tried to reset the board by double-pressing the reset button, but that didn't make any response, not even flashing LEDs.
I've tried changing USB cables, connecting to different ports of the PC, also other PC's but the result was the same.
I've checked the board's outputs, luckily the 3v, 5v, and Vin pins have output and run without any abnormal heating. I'm not sure what's the problem with this board. Maybe the bootloader got corrupted?

it is possible to upload to Nano BLE with Nano IoT selected and vice versa. The result is a deleted bootloader. here I describe what to do for Nano IoT, but the same applies for Nano BLE: https://arduino.stackexchange.com/questions/72955/arduino-nano-33-iot-issue/72973#72973

Thanks for giving me light Juraj.


text:
Is there any standard for colors of Serial Peripheral Interface wires?
Having DuPont cables like on the picture...

... and the RFID RC522 reader with colored wires as found in one of the tutorials.

I know that copper is the same inside of the wires. Anyway, is there any standard or de-facto standard of assigning colors to the meaning of the pins? Black for ground and red for +voltage are known from elsewhere. But what about all the other pins? Here is the detail view for better readability:

Nope, there isn't., except for black for GND and red for Vcc, but even these are just conventions.

btw: do you wire this for SPI or for I2C? for SPI don't wire SDA and for I2C don't wire MISO and MOSI.

@Juraj I2C. The SPI was just example. The question was meant to be more general.

No, there is no standard. However:

Red is often +5V
Black is often GND
I often assign colours numerically according to the resistor colour code:

0 - Black
1 - Brown
2 - Red
3 - Orange
4 - Yellow
5 - Green
6 - Blue
7 - Purple
8 - Grey
9 - White

You may have noticed that that's the same order they appear in the cable too, which is helpful. It's handy when working with things like 8 bit data buses, since you can then easily identify which wire is which.
In some disciplines there are standards, like for audio red is right and left is white (that's the little rhyme I use to remember), and of course there's regulations defining colours for mains cables, but for this kind of thing just use whatever makes sense to you.

Thanks for sharing your experience.


text:
Low power RF decoder possible?
I'm building a panic button project for my grandma which uses a 433MHz RF remote keyfob and a 3.3v Pro Mini connected to an RF receiver, a buzzer and an led. The purpose is that whenever she needs assistance like in the middle of the night, she could simply press the keyfob button and the Arduino will act as an alarm and would go off, alerting me and others. So far I have set everything up and the project works exactly as intended.
How can I further reduce the power consumption on the receiver end of this project so that I can run it using batteries for a long time, like 6 months or so?
The battery I have in mind is either a single 3.2v 5000mAh LiFePo4 battery or 3x AA 2600mAh NiMH Low self discharge cells in series.
My current setup for the receiver has an always active 433MHz RF receiver which draws around 5mA while running at 5v and an Arduino Pro Mini which should consume about another 5mA. I'm using the RC switch Library and the project is currently powered by a USB wall adapter. I haven't used any low power or sleep functionality before so I'm not very informed on those methods.

The biggest saving can be made by making your sketch just always transmit and nothing else. Then put the button in the power connection. Press the button, the power turns on, the Arduino transmits. In fact you could even do away with the Arduino altogether.

But my arduino doesn't transmit anything. It just receives the code the keyfob will send.

Ah, I misunderstood. Ignore that then.

I am not familiar with using the RC switch library, but if you're using a pin that is an interrupt it may be possible to go to sleep and wake when that pin changes state. You may miss the first transmission from your button, but I would hope there would be multiple transmissions sent so you would capture the next one.

why does the receiver need to be battery powered? That's quite unusual as these sorts of things go...10ma isn't that bad. I can see some tweaks halfing that, but that still doesn't really help make or break the feasibility. You have to be awake to answer the phone...

@Majenko Yes, the receiver will be plugged into the interrupt pin. Missing the first transmission is not a problem, the person needing help will press the button multiple times. I think your idea will work out.

@Majenko The reciever needs to be battery powered mainly because the power supply in my country is very unreliable. If the project cannot be run on a battery for an extended period of time, then I'm willing to modify it to have a battery backup system instead. Either way a battery will be involved, preference will be for the low power long backup option.


text:
esp8266 - server.handleClient() fails to call assigned function
I'm trying to get one esp to send integers to a second as a part of a simple remote control, but after multiple days I can't get it to work. The transmitter seems like it's connecting and sending properly as best I can tell, and the receiver is sending some kind of response, but the function I attached with server.on() never gets called.
The code is basically copy and pasted from a tutorial, the only thing I changed was removing code to display the read data to an LCD and display to serial instead.
This is the receiver's code.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char *ssid = "controllerReceiver";
const char *password = "password";

ESP8266WebServer server(80);

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

  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();

  server.on("/data/", HTTP_GET, handleSentVar);
  server.begin();
  Serial.println("server online");
}

void loop() {
  server.handleClient();

}

void handleSentVar() {
  Serial.println("Handling");
  if (server.hasArg("x_value")) { // this is the variable sent from the client
    int readingInt = server.arg("x_value").toInt();
    Serial.println(readingInt);
    server.send(200, "text/html", "Data received");
  }

}

And here is the transmitter
#include <ESP8266WiFi.h>

const char *ssid = "controllerReceiver";
const char *password = "password";

int outputValue = 999;

void setup() {

  Serial.begin(115200);
  delay(10);

  // Explicitly set the ESP8266 to be a WiFi-client
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("connecting...");
    delay(500);
  }

}

void loop() {

  char intToPrint[5];
  itoa(outputValue, intToPrint, 10); //integer to string conversion for OLED library

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const char * host = "192.168.4.1";
  const int httpPort = 80;

  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");

    return;
  }

  // We now create a URI for the request. Something like /data/?sensor_reading=123
  String url = "/data/";
  url += "x_value=";
  url += intToPrint;

  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");

      client.stop();
      return;
    }
  }

}

Running a whole webserver + client is waaay overkill for a remote control. Use UDP packets instead.

Replace "/data/" with "/data" and url += "x_value=" with url += "?x_value=".
The HTTP GET parameters are separated from the path by "?". The on function is executed for a path ("/data").

If you sub server.on("/data/", don't you need the trailing slash in the request also? some web hosts tack that on for you, but the ESP doesn't.

@dandavis, no..

I just tested it by on()ing /test and /test/ with different functions, and they are indeed discrete. This is why there's repetitive stuff like server.on("/read/", getReading);  server.on("/read", getReading); in my old sketches. I now use a macro that subs both the plain and slashed path to make it easier and would have been pleased+surprised to find out it was useless. Maybe async server is different...


text:
ELEGOO Mega 2560 USB and Vin simultaneously?
I'm powering my Arduino clone with an LM317 circuit that regulates Vin voltage to 10V (measured with a multimeter).  While the Arduino is powered by USB only, everything works.  When it's powered using Vin, I get odd behavior.  I then tried plugging in the USB to see what was happening via the serial monitor and my laptop shut down.  I read the Arduino is supposed to handle both USB and Vin simultaneously without shorting out, but now I'm scared to try it again.  Is it safe to try again?  Any idea what would cause my laptop to shut down, or what I could be doing wrong?  Thanks.

When it's powered using Vin, I get odd behavior ... what is the voltage at Vin when everything is powered on? .... odd behavior doesn't really mean anything ... what actually happens?

Is it safe to try again? ... do not believe anyone that says yes without examining your arduino in person

It should be fine if you don't have Vin less than 6V6. There is a circut that compares half of Vin against 3V3 "reference" and if it's less, then it enables "ideal diode" switch from Vusb (but it also allows backfeeding)
Another way how to bakcfeed usb from the Arduinos 5V is short 3V3 to 5V and having 9V on Vin (eg. less than 10V).
However backfeeding USB port shouldn't be causing restarts. Maybe there are a power supply issues and you've got a big voltage potential difference before connecting it into the USB? You can try to measure it


text:
Is there accurate connection procedure for connection between an esp32 and ultrasonic sensor(HC-SR04)?
I am currently working on a project which integrates esp32 and HC-SR04 and send the data from HC-SR04 to my own domain. The connection diagram is this

And the code which I use is this,
const int trigPin = 5;
const int echoPin = 18;
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701

long duration;
float distanceCm;
float distanceInch;

void setup() {
 Serial.begin(115200); // Starts the serial communication
 pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
 pinMode(echoPin, INPUT); // Sets the echoPin as an Input
}

void loop() {
 digitalWrite(trigPin, LOW);
 delayMicroseconds(2);
 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10);
 digitalWrite(trigPin, LOW);

 duration = pulseIn(echoPin, HIGH);

 distanceCm = duration * SOUND_SPEED/2;

 distanceInch = distanceCm * CM_TO_INCH;

 Serial.print("Distance (cm): ");
 Serial.println(distanceCm);
 Serial.print("Distance (inch): ");
 Serial.println(distanceInch);

 delay(1000);
}

But the module doesn't give out the distance. Can anyone suggest a better method for connection. Thanks in advance!

Can you be more specific about the problem? If it "doesn't give out the distance", what happens instead? Does it crash? Does it always return the same distance? Is the distance wildly inaccurate? Or something else? You know what you mean, but we don't.

So normally after connection, the output according to the code comes out something like,
Distance(cm): 0.00
Distance(inch):0.00

But when I connect to an Arduino the sensor works perfectly

please add a connection diagram and test code to your post ... your question should stand on its own, without an outside link

Does your variant of the ESP32 board actually give out 5V on the VIN pin?

I checked it using a multimeter and it gives me only about 3 V. I did the same with the arduino UNO and it gave me about 3.3 V at the 5 V pin.

If the Arduino is giving you 3.3V at the 5V pin either your Arduino is broken, or you are drawing massive currents from it, or your multimeter doesn't work, or you don't know how to use your multimeter properly.

I know how to use a multimeter when I see one @Majenko. I use only one ultrasonic sensor so know way the sensor is gonna draw massive current from the esp32

Then there must be something wrong somewhere if you are only measuring 3.3V on the 5V pin of the Arduino...

Suriya,
You aren't crazy - it appears the ESP32 GPIO pins (at least the ones I tested) won't drive the HC-04 sonar sensor trigger pin sufficiently high to trigger a sonar pulse.  I tested the NewPingExample.pde code example from the NewPing library's 'example' folder on both a MEGA2560 and a ESP32_DevKitC_V4. The MEGA implementation worked right off the bat, but I never could get the ESP module to work.  So, I took a look at the Trigger/Echo pin (by default the NewPing.h file uses the 'Single Pin' mode, so you have to make sure the TRIGGER_PIN and ECHO_PIN defines use the same pin).  The two scope traces below are from the MEGA2560 and the ESP32.  As you can see, the ESP32 output only goes to 1.865V - not high enough to actually trigger the device.  The MEGA implementation output goes to over 3V and consistently triggers the echo (the big rectangle to the right of the narrow trigger signal).
You might want to try using the STMicro VL53L0X time-of-flight LIDAR chip instead - it is much smaller, uses less current, and doesn't suffer from self-interference if you plan to use more than one sensor. See this post on my blog site for some ideas

Thank you for the reply @starship15. I really appreciate your time for clarifying me with results!


text:
ESP8266 ESPAsyncWebServer LittleFS crashes
I am trying to write a simple web page to be served from my ESP8266 based on this tutorial: https://www.mischianti.org/2020/10/26/web-server-with-esp8266-and-esp32-byte-array-gzipped-pages-and-spiffs-2/
However I got a warning saying:

SPIFFS has been deprecated. Please consider moving to LittleFS or other filesystems.

So I thought I would try using LittleFS as a drop in replacement for SPIFFS, it seemed to be working fine but noticed issues with larger files straight away, the ESP8266 would crash frequently but not consistently, however image files even of smaller sizes would fail to load. Anyway I switched back to SPIFFS and everything seems to work fine as the tutorial suggested it would, can anyone tell me what issue with LittleFS I might be experiencing and if it can be fixed?
Also is it bad practice to use SPIFFS even though it seems to work fine?
Thanks

I still use SPIFFS, it works and there's nothing "wrong" with it, especially if you have a lots of little (<4kb) files or you want code that runs on the 8266 and 32 both. If you have large files, littleFS is about 5x faster to read and write. If you're directly shipping the whole file over wifi, the wifi part is going to be slower than either filesystem's access.


text:
I need to run 2 for() loops simultaneously but I cant seem to do it without one executing, then the other after it
I'm controlling 2 servo motors but would like to adjust their variables separately, specifically  their upper and lower values, and their speeds. This code is one that I had found online then separated, since the original code didn't have adjustable variables for both. I'm using an adafruit servo
controller
for (uint16_t microsecL = mainServoClosedL; microsecL < mainServoOpenL; microsecL +=5)
for (uint16_t microsecR = mainServoClosedR; microsecR < mainServoOpenR; microsecR -=5) {
        pwm.writeMicroseconds(mainServoL, microsecL);
        pwm.writeMicroseconds(mainServoR, microsecR);
      }

"I need to do something. This is some code I found." isn't a question. What is your question?

I need to run 2 for() loops simultaneously .... why do you need to have two for() loops?

You didn't specify which chip ur using.  Arduino doesn't like multi-threading (proto).  And since arduino chips only have 1 core they only have 1 thread.
Switch over to ESP32 dual-core chips, they have FreeRTOS that has Tasks.  What your trying to do would be easily achievable with an ESP32 microcontroller.

The answer is simple, but the solution isn't.
The simple part: don't use for loops.
The harder part: you have one loop() function which runs repeatedly. For each iteration of that function you make decisions about what to do during that loop and act on them. Decisions like "Is it time to increase this PWM value?" or "Has this value reached the limit I want for it?" etc.

The micro-controller can't do any more than one thing at a time. What it can do is do that one thing way faster than your servos need it to. So it has (more than) enough time to evaluate each motor's condition and needs and to do it fast enough that you won't notice and they won't be affected by the difference.
The one thing your code mustn't do is to wait for a single something to happen, unless that is absolutely the only thing of interest that could possibly happen next. That is seldom the case in the real world, so the controller must check for all possible events of interest, over and over again, to be able to respond to whichever one does happen next.
In your code snippet, you increase microsecL and decrease microsecR, but not at any particular rate(s). Your loop code probably needs to look at the execution-time clock (the functions `millis()' and 'micros()' will read that for you), and when a suitable interval has passed, adjust one or both of those values and do anything else that might need doing, such as stopping a motor when a time has elapsed or it has reached a final position.


text:
How I can populate a buffer from data read from SPI?
I have wired a Macronix MX35LF1GE4AB Flash memory into an arduino Uno using Logic Level Shifters. What I try to do with it is to dump its contents.
In order to do so, I am implementing the following sketch:
#include <SPI.h>

#define LASTBLOCK 1023
#define LASTPAGE 63
#define LASTBYTE 2111

#define PAGE_READ 13h
#define PAGE_READ_CACHE_SEQUENCIAL 03h
#define READ_FROM_CACHE 3Bh
#define PAGE_READ_CACHE_END 3Fh

#define BUFFER_LEN 2111

int page_to_read = 1;
int block_to_read = 1;

// We store each page to Microcontroiller's ram
byte buffer[BUFFER_LEN];

void setup() {
 SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
// Serial.begin(9600);
}

void loop() {

  // I need to reset the counts before reading any block
  if(page_to_read > LASTPAGE){
    page_to_read = 1;
    block_to_read ++;

  }

  if(block_to_read > LASTBLOCK){
    return ;
  }

  if(page_to_read == LASTPAGE){
     SPI.transfer(PAGE_READ_CACHE_END);
  } else if (page_to_read == 1) {
     SPI.transfer(PAGE_READ);
     SPI.transfer(PAGE_READ_CACHE_SEQUENCIAL);
  }

  SPI.transfer(READ_FROM_CACHE);

  page_to_read++;
}

Now what I want is to populate the buffer byte buffer[BUFFER_LEN] with data, so I can send them over a serial port.
How I can achieve that?

SPI.transfer(buffer, BUFFER_LEN); -- https://www.arduino.cc/en/Reference/SPITransfer

Other than what Nick and Majenko point out, for proper use of SPI library, you should always call SPI.begin() in your setup (unless you are running it as a slave) because it help to setup the proper IO states of MOSI, MISO and SS, etc.. SPI.beginTransaction() should be called before the SPI.transfer(), and SPI.endTransaction() to be called after you done with the data transfer. This allows other tasks to be able to use the SPI bus.

#define BUFFER_LEN 2111
byte buffer[BUFFER_LEN];

That will definitely not work because the Uno has 2048 bytes of RAM, some of which are needed by the system. The serial buffers, for example, are 64 bytes each.

So I'll need a 32byte buffer?

Yes, a smaller buffer will help.

Why do you think you need a buffer at all when you're just outputting through serial?

In order to fan the data read from spi though USB serial, though I can just read them byte by byte. Also I'll need to transcode them as well in hex. Futhermore I'll need to send the page and the block id's in order to recontruct the data into a file in my computer.


text:
Alternatives to Radio Transceivers
So i am creating a haunt project that needs a way of detecting when an Arduino passes it and makes that Arduino do something. the problem I'm having is that none of the transmitter and receiver that has a small enough range that won't interfere with other patrons walking through on the other side of the wall. does anyone have any ideas what i can use?

Not a question about Arduino

RFID tags would be fitting

There is a discussion of a similar question at the Arduino forum where they leaned towards passive UHF RFID tags.
If your budget stretches to it, there would be a range of active RFID tags that might suit.
There’s a good intro to RFID at Sparkfun, and Wikipedia has a good starting reference point.


text:
String type replace function can't replace with no char
I want to replace the ":"(colon) in the MAC address with no char (remove the ":").
But I can't find any good solution.
String.replace(), can't replace with (void).
Note: String.replace(':',(char)0) //also doesn't work
String.remove() is ugly and requires that you know exactly where each iteration is (indexOf()), and this method doesn't return anything, it updates the string directly so you have to call : String.remove() for each occurence.
and String.substring() has most of the same problems as remove, except that it does return the substring, so you can do: String.substring(i,l).substring(i2,l)...
#include <WiFi.h>
String MAC;
char ssid[] = "WiFi SSID"
char psw[] = "WiFi PSW"
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  WiFi.begin(ssid,psw);
  MAC = WiFi.macAddress();
}

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

  Serial.println("MAC Address unformatted")
  Serial.println(MAC);
  String MAC_f = MAC.replace(':', ' ');
  // Now print the MAC without the ":"
  Serial.println(MAC_f);
  // This replaces the ':' with a space.  I want to replace(remove) the ':' with no char
  // Looking for an elegant, simple, 1 liner to accomplish this.

  /* This looks horrible */
  MAC_f = MAC.substring(0,2)+MAC.substring(3, 5)+MAC.substring(6, 8)+MAC.substring(9, 11)+MAC.substring(12, 14)+MAC.substring(15, 17);
  /* .remove also looks terrible */
  MAC_f = MAC;
  MAC_f.remove(2,1);
  MAC_f.remove(2,1);
  // ...

}

Please do not attempt to answer questions in the comments. See How do comments work?. The comments on this question have been deleted, including the ones about "a special message". Appropriate action has been taken in regard to this message.

Don´t use String() manipulations inside loop(). It causes heap fragmentation and program failure. Use a char array instead:
char MAC[18] = "01:23:45:67:89:AB"; // including terminating zero

for (int src = 0, dst = 0; src < sizeof(MAC); src++)
   if (MAC[src] != ':') MAC[dst++] = MAC[src];

It works because the terminating zero is copied to the end of the modified string

@Instigator in which way is this inefficient? Do you know what String.replace() does?

As stated by Mat, the empty string in C++ is "". This works:
MAC_f = MAC;
MAC_f.replace(":", "");

That being said, I concur with SBF's answer: String object are not
friendly with the Arduino's memory. SBF's solution is better than
String::replace().

@Instigator you know the difference between 'x' and "x", right. String.replace() takes String arguments, not char as you wrote. https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/replace/

others a right that String is not totally Arduino friendly, WiFi.macAddress() returns String, SO
though written for ESP32 this is an approach i used
 // Get the station interface MAC address.
 // @return String MAC, no camas
String getMacAddress(void)
{
    WiFi.mode(WIFI_AP_STA);   // required to read NVR before WiFi.begin()
    uint8_t baseMac[6];
    esp_read_mac( baseMac, ESP_MAC_WIFI_STA );  // Get MAC address for WiFi station
    char macStr[18] = { 0 };
    sprintf(macStr, "%02X%02X%02X%02X%02X%02X", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
    return String(macStr);
}
// END getMacAddress()

this maybe is how it should be done, but it doesn't answer the question


text:
Communicate with Sparkfun CAN Bus Shied
i have a Arduino Mega 2560 R3 and a Sparkfun CAN Bus Shied. Im using the SparkFun_CAN-Bus_Arduino_Library-master. I want to communicate over SPI (they have diffrent SPI pins), so i had to change it in defaults.h
Changes:
#define P_MOSI  B,2 //  new pin: 51,    orginal: #define    P_MOSI  B,3
#define P_MISO  B,3 //  new pin :50,    orginal: #define    P_MISO  B,4
#define P_SCK   B,1 //  new pin :52,    orginal: #define    P_SCK   B,5
#define MCP2515_CS B,0 // new pin:53,   orginal:  #define   MCP2515_CS B,2
i connected the pins:
Arduino Mega Pin - Sparkfun pin
51 - 11
50 - 12
52 - 13
53 - 10
also connected: 5v, gnd, rst, (pin 2)
Before i realized that spi pins are diffrent, the can init from demos dont worked.
After changes, init worked but e.g. CAN_Write_Demo i can not see the data in PCAN-View. There is nothing.
I read that PCAN-View is not compatible with my lib so i try the MCP_CAN_lib-master, same problem.
I also tried it with Vector CAN, with both libraries same problem.
Why can't I see the messages?
I also tried other demos e.g. CAN_Read_Demo and sent a can message with PCAN-View but get nothing.
When i run write demos, it dousnt even send anything and when i run read demos e.g. sending from PCAN-View, status from PCAN-View changes instant to BUSHEAVY.
Thank you for helping.

CAN will not send messages into the ether. It must have another node to acknowledge the message. That node needs to be configured for the same bit rate. I use the MCP-CAN_lib-master by Cory Fowler and it works great. You can try the following and if it does not work I would suggest you start with two UNOs and two MPC2515 and get them to work first, the send and receive code is in the examples included with the library. Be careful there are at least three different crystals on the MPC2515 boards, select the correct one. Also be sure the bus is terminated on both ends, that should simply adding a jumper to the CAN module. Hopefully the bus is several feet long, I have heard of problems with short buses although I have never experienced it. Another hint be sure the grounds for all modules are connected. I know that is not necessary but makes getting it started much easier. Also start with something in the 125/250 Kbit rate.

As i know PCAN-View should acknowledge the messages? And i also tried it with a working system where the can bus shield should just listen, but getting nothing (With the working system i see the messages with PCAN-View).

To many unknowns. Post a schematic as you have them wired and your code per forum instructions. Frizz pictures do not count and links to technical information on the hardware you are using are also needed. There are many parts with the same name but different.


text:
How exactly do Bicycle LEDs work? (Arduino Project)
Table of contents:

What I want to achieve
Problem I'm facing
What I've tried
Possible Hypotheses

What I want to achieve
Hi guys, I’m working on a DIY LED Light project to install on my bicycle, where I want to re-create how the actual LED bicycle lights work:
[Stage 1] Press button once: LED lights up forever until button is pressed again
[Stage 2] Press button twice: LED blinks forever until button is pressed again
[Stage 3] Press button thrice: LED turns off (goes back to original state)
Problem I’m facing
After a bit of research, I know how to work out the code for [Stage 1] (by tracking the current and previous button states.) But I’m unable to make [Stage 2] happen.
What I’ve tried
I’ve tried to instead of tracking the previous and current button states, why not use a counter, i.e:
Counter = 0 (initial)
When button is pressed once,
Counter = 1 (LED lights up forever until button is pressed again)
When button is pressed one more time,
Counter = 2 (LED blinks forever until button is pressed again)
When button is pressed one more time,
Counter = 3 (LED switches off, goes back to original LOW state)
Counter resets to = 0 again
This is my code below:
const int ledPin = 8;
const int buttonPin = 7;

int buttonState;
int ledState;
int counter = 0;
int newcounter;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(ledPin, HIGH);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    newcounter = counter + 1;
    delay(500);
    if (newcounter != counter) {
      switch (newcounter) {
        case 1:
            digitalWrite(ledPin, LOW);
            counter = newcounter;
            break;
        case 2:
            digitalWrite(ledPin, HIGH);
            delay(500);
            digitalWrite(ledPin, LOW);
            delay(500);
            digitalWrite(ledPin, HIGH);
            delay(500);
            digitalWrite(ledPin, LOW);
            delay(500);
            digitalWrite(ledPin, HIGH);
            delay(500);
            digitalWrite(ledPin, LOW);
            delay(500);
            digitalWrite(ledPin, HIGH);
            delay(500);
            break;
        case 3:
            digitalWrite(ledPin, HIGH);
            counter = 0;
            break;
        default:
            digitalWrite(ledPin, HIGH);
            counter = 0;
            break;
      }
    }
  }
}

Possible Hypotheses (Please criticise/correct me if I’m wrong)
A) There is a problem with my code (my programming logic etc)
B) Maybe its not a code/program problem? It could be due to the design of the electric circuit (because I’ve seen videos on YouTube where LEDs can be made to blink using capacitors and transistors. But how does the sequence from Stages 1 to 3 happen in a bicycle LED light? (https://www.youtube.com/watch?v=cXCExzIBNsA)
I’ll be eternally grateful if anyone will be able to help! Thank you!!

So what is the question? Does the code "not work" and you are asking "why it does not work"? If it does not work, what does it do then and how do you expect it to work?

First of all, you need to get rid of all those calls to delay() and implement it in a non-blocking way (look at BlinkWithoutDelay.ino).

@SimSon, you can make that an answer :)

does loop() actually "loop"?

You're missing a counter = newcounter; line in your case 2:, but the real problem (probably, since you haven't actually described what "But I’m unable to make [Stage 2] happen" means) is almost certainly that you only have 3 blinks and then your code exits the state and returns back to the start of the loop. Sim Son has already given you one way of fixing that. Your code might work a bit more like you intend it to if you move the entire switch block outside the if (buttonState == HIGH) block. As you've written it, the case with all the blinks only executes if the button is pressed.

Your problem is that your LED control code is all tangled up with your button press and counter code. Separate them out into completely independent code blocks. One that just increments the counter using a button, and one that displays different things depending on the current counter value.

@glen_geek, That's Arduino code. The Aduino library effectively calls while(true) loop();  https://www.arduino.cc/reference/en/language/structure/sketch/loop/

you are not stating what results you are getting.
I do see you are not presetting your state variables.
This is always good practice to avoid random startup conditions.
you have logic that will only run when the button is held
your if (newcounter != counter) and switch statement only run while the button is pressed.
move them outside of the button state check and look to change things ONLY if the button changed.
try this;
it will only act on button change not continiously so changes only happen on each press
i will leave you to play with the switch conditions
const int ledPin = 8;
const int buttonPin = 7;

int buttonState, chngButtonState = 0;
int ledState;
int counter = 0;
int newcounter;

void setup() {
  chngButtonState = buttonState;
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  digitalWrite(ledPin, HIGH);
}

void loop() {
      buttonState = digitalRead(buttonPin);
      if (buttonState == HIGH && !buttonState == chngButtonState ) {     // read once only if changed button state changed not on every loop
        newcounter = counter + 1;
        delay(500);
        chngButtonState = buttonState;      // mae them equal again
        }                // NOTE I moved 1 of the } from the bottom

        if (newcounter != counter) {
          switch (newcounter) {
            case 1:
                digitalWrite(ledPin, LOW);
                counter = newcounter;
                break;
            case 2:
                digitalWrite(ledPin, HIGH);
                delay(500);
                digitalWrite(ledPin, LOW);
                delay(500);
                digitalWrite(ledPin, HIGH);
                delay(500);
                digitalWrite(ledPin, LOW);
                delay(500);
                digitalWrite(ledPin, HIGH);
                delay(500);
                digitalWrite(ledPin, LOW);
                delay(500);
                digitalWrite(ledPin, HIGH);
                delay(500);
                break;
            case 3:
                digitalWrite(ledPin, HIGH);
                counter = 0;
                break;
            default:
                digitalWrite(ledPin, HIGH);
                counter = 0;
                break;
          }
        }
    }

now just play with the Switch statements to get your results.
pinMode(buttonPin, INPUT);
your button wiring is not clear.
Likely, you have the button connected to VCC and pin 7.  You still should have a pulldown resistor from the arduino pin7 to GND to get reliable states.
However; if the button is from a pin7 to GND and no pullup the state will also not change.
If so;
change pinMode(buttonPin, INPUT); to pinMode(buttonPin, INPUT_PULLUP);   and no external pullup resistor is needed.

Think of the "stages" you identified as states or modes of operation, and the button presses cycle between the stages.
Then for "stage 2", you re-write it as a function that doesn't mostly block and idle for 3.5 seconds, but that immediately returns control back to the loop() so you can check for more button presses quickly:
// this function is patterned after the example in
// https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay
void stage2(void){
  const unsigned long interval = 500;
  static unsigned long last = 0;
  if(millis() - last >= interval){
    last += interval;
    digitalWrite(ledPin, !digitalRead(ledPin));
  }
}

and then you switch on stage in the event loop:
      switch (stage) {
        case 0: // idle
            break;
        case 1: // on
            digitalWrite(ledPin, LOW);
            counter = newcounter;
            break;
        case 2: // blinking
            stage2();
            break;
        case 3: // turn off
            digitalWrite(ledPin, HIGH);
            stage = 0;
            break;
        default:
            digitalWrite(ledPin, HIGH);
            counter = 0;
            break;
      }
      ...

This switch-case takes almost no time, and returns control to the event loop, so the user interface can respond quickly to other button presses, or check for other tasks.
I didn't re-write the rest of your code, but these are the key differences between your code and what's running in a bike light:

Use state variables and state machines to change the mode of operation.

Avoid trapping the processor in "blocking" code that uses delays(), for(;;), while();, etc...  Depend instead on the event loop (loop() in the Arduino), to return control to your functions.

There is a simulation of a Bike Light using these coding patterns on Wokwi at https://wokwi.com/arduino/projects/325075981102482003


text:
RFM69HCW connected to Arduino Uno
I have a prototype LoRa Daughter Board that utilizes RFM69HCW transceiver module. I found an interesting blog online that covers everything courtesy of Sparkfun. Here's the link RFM69HCW Tutorial by Sparkfun 2.
I followed everything but the 2 RFM69HCW radios that I am working on didn't communicate to each other. When I checked my prototype board, DI0 of the RFM69HCW has no connection at all. Is it necessary to connect the DI0 to hardware interrupt pin of Arduino Uno? And also, can I connect it directly to the Arduino board if ever? Thanks in advance for whoever will shed light on this one.

You're saying the DIO0 pad on your breakout board doesn't connect internally to the LoRa module mounted on it?

unfortunately, yes @Majenko basically the DI0 pin in my prototype board is with no connection. Was it the reason why the RFM69HCW transceiver modules didn't communicating to each other?


text:
ESP8266 - MAX3485 Modbus not getting data
I'm trying to connect a modbus meter to a nodeMcu LoLin v3
I'm using a MAX3485 module to transfer the TTL to a RS485 connection.
The modbus server has unitId 1, baud rate 9600 and no Parity
This is the scheme. A e B from the module go to the modbus server device

And this is my simple script
#define DIRECTION D3

#include <ModbusRTU.h>
#include <SoftwareSerial.h>

SoftwareSerial S(D2, D1);
ModbusRTU mb;

bool cb(Modbus::ResultCode event, uint16_t transactionId, void* data) { // Callback to monitor errors
  if (event != Modbus::EX_SUCCESS) {
    Serial.print("Error result: 0x");
    Serial.println(event, HEX);

  } else {
    Serial.print("No Error");
  }
  return true;
}

void setup() {
  Serial.begin(115200);
  pinMode(DIRECTION, OUTPUT);
  digitalWrite(DIRECTION, 0);
  S.begin(9600, SWSERIAL_8N1);

  mb.begin(&S);

  mb.client();
}

void loop() {
  uint16_t res[2];

  if (!mb.slave()) {    // Check if no transaction in progress
    mb.readHreg(1, 5, res, 1, cb); // Send Read Hreg from Modbus Server
    while (mb.slave()) { // Check if transaction is active
      mb.task();
      delay(10);

    }
    Serial.println("Res");
    Serial.println(res[0]);
    Serial.println(res[1]);

  }
  delay(1000);
}

I created a Software Serial on D1 and D2 and i'm trying to read from it but no matter what i do, i keep getting error 4 from the response and 2 values in my reg array i do not where they come from...
Error result: 0xE4
Res
59044
16382

Am I missing something?
The modbus server works because i connected it to another client and everything is ok

If you're using a MAX3485 then VCC should be connected to 3.3V, not VIN (which on some boards cannot provide power but instead can only be used to power the board itself).

You might find my answer to this question enlightening...

i do not know if it's 3.3V or 5V... i put it on 3.3V on the ESP8266, nothing changes, it's still powered on


text:
How do I fix my code so that it reads text from the serial monitor?
I have created a code that should print out "Enter true to deactivate alarm" in the serial monitor, then store the user's answer and print "alarm off" if they enter true and "alarm on" otherwise. However, it is returning "alarm on" every time, even if I enter true. Here is my code:
String deactivate = "";
void setup() {
  Serial.println("Enter \"true\" to deactivate alarm");
}
void loop() {
  while (Serial.available() == 0){}
  deactivate = Serial.readString();
  if (deactivate.equals("true"))
  {
    Serial.println("alarm off");
  }
  else
  {
    Serial.println("alarm on");
  }
}

Any help here would be greatly appreciated, I'm new to Arduino and we've been stuck on this step for weeks; I am just really at a loss trying to figure out why it isn't working.

You didn't set the Serial port:
Serial.begin(9600);

Add this in the setup function.
Also check in your serial monitor if the speeds are equal.
If this still doesn't work, print the deactivate variable after assigning, and its length, and every character to see if it adds a newline character or any other unexpected character.
Then if it is a whitespace character, use a function to strip the whitespace, or change the comparison.

Often is the case coders will add "debugging" print statements to aid in understanding what is occurring in their code.  Printing out what you received may help in understanding unexpected results.
That said, consider using Serial.readStringUntil() in place of Serial.readString().  From the linked to page:

Returns
The entire String read from the serial buffer, up to the terminator
character


text:
How to combine servo shield with peristaltic pump?
I am creating a project where I need 16+ (possibly up to 20) servos to open/close liquid flow through tubing, which in turn will be controlled by a peristaltic liquid pump (https://www.adafruit.com/product/1150). Since the adafruit servo shield (https://www.adafruit.com/product/1411) gives you access to 16 servos per shield, it seems like the obvious option. However, this shield wont be able to drive a peristaltic pump. I've been told I can put a adafruit servo shield on top of a adafruit motor shield (https://www.adafruit.com/product/1438), but is this really the most effective way to build this project? I want to have a system that is as compact and cheap as possible, using already-available electronics (although I suppose one option is to build a shield myself, but having not done that before it would take me a very long time).
I am quite new to arduino and its accessories, so I apologise if this is a very simple question.
Best,
N

You don't need a shield to run servos. Maybe you should be looking at a more powerful board that can directly connect to many servos without the need for any additional hardware. There's more than just Arduino boards in the whole ecosystem.

the pump is just a DC motor, as far as the microcontroller is concerned ... there are many tutorials on the web about controlling a motor with a microcontroller

Minimal components for driving a motor like a pump is: MOSFET used as switch (capable of handling the needed current and having a threshold voltage well beloe logic level of the Arduino), a diode used as flyback diode and a resistor to limit the gate current (just to be safe). That enables you to drive the motor in one direction, controlling its speed.

nn123,
Never apologize for asking the simple questions! The only reason I've learned in my life is for asking these kinds of questions. We all have to start somewhere, and should never be embarrassed for what we don't know. The key is being willing to learn and ask for help.
Here's a simple solution to your problem.
The shield is a great idea for you to use. It's very simple to wire (it plugs in :), you have power management system on the shield, and you can control the entire thing with I2C. So I'd definitely stick with that.
In order to drive a DC motor (pump), all you need is a sort of low power MOSFET to power this. You can look up thousands of tutorials on how to power a motor with an Arduino. Here is one for reference.
If you don't want to buy individual components and perfboard to construct your own circuit, you can buy a motor driver from Adafruit just like this one. Remember Adafruit always gives you incredibly good instructions for all their products if you're ever stuck.

This board is perfect for powering low-power motors. Your pump only pulls a maximum of 300mA at 12V, and that shield can do up to 3.6A peak (probably more like 2A continuous). The shield is also a H-bridge, which means you can power the motor forwards & backwards (not sure if this is useful to you).
To hook up the motor driver all you would need is 2 digital pin PWM pins (like 5&6) to control it forward/backwards.
Comment if you have any questions and good luck with the project!

Thank you so much, for your kind words and help! I will read up on what you suggested and I'll comment if I have further questions as I move forward with the project!


text:
Can I power up an Arduino Uno via the 5 V pin while USB is connected at the same time?
I want to use Grbl to control a diy CNC machine. I need to communicate with the CNC using Grbl and this is done via the PC's USB port.
So the PC's USB port is connected to the Arduino Uno which is connected to the shield and the shield and Arduino are powered from an external 5 V power source.
Can someone advise me if this is a power conflict (all grounds are common)?

Powering from the 5V pin and USB at the same time should be avoided. This is because the circuit that controls the power from the USB is triggered from the VIN / barrel jack and needs to be above about 6.5V to cause the USB power to be isolated.
It won't damage your Arduino, but there is a chance that your computer may be unhappy and shut the USB port down. 5V shouldn't cause any damage though, but it may detect that something isn't quite as it should be and take steps to protect itself.
One possible "fix" is to take any suitable disposable USB cable and strip some of the plastic outer casing from it (a couple of inches should do the job) and spread out the wire and foil shielding (assuming it exists). Locate the red wire and cut it. Join the red wires together again through a diode (ideally Schottky to reduce voltage drop) with the anode towards the computer and the cathode (stripe) towards the Arduino. This will isolate any reverse power while still providing the USB 5V to the USB interface chip's VBUS pin.


text:
Arduino's stuck on COM1 and Device Manager Crashing
I just added a few new arduinos, and they are all loading on COM1. Here are some of the strange behaviors:

Three arduinos plugged in, and they are all on COM1. I've never seen multiple devices loading on the same port.
I have other arduinos that still load on the port they were assigned to before. That is, i * attach 4 arduinos, and they load on COM9-12, which is how they have loaded for months.
in Device Manager, when i try to change the COM port, when i click Ok, device manager exits.
when i load device manager with no board plugged in, and i select Show Hidden Devices, and I try to change the COM1 device, the dev mgr crashes again.

The boards are Elegoo Uno R3. Windows 10, ThinkPad T490s. I have been running arduinos in this configuration for 2 years on this laptop with no issues.
Help would be much appreciated. My project has ground to a halt for days!

Do they all identify with the same serial number?

at some point, usb port hardware and com port numbering are associated.  test for this is if the different arduino on same port read the same COM and same arduino on different ports read different.  Only way I can think to reset is to uninstall and reinstall some higher level (see devices by connection)

@Majenko I don't see a property called "serial number". I'm looking in the dropdown menu of device manager tab Details/Property. Trying two boards, the  Location is Port_#0002.Hub_#0005 and Port_#0003.Hub_#0005. The is also a property called "Device Instance Path" that is for one of them "USB\VID_2341&PID_0043\95036303235351312061" and they are different.

@Abel I tried swapping boards and ports, all read COM1. I'm not sure if that's what you meant. If not, please clarify.

that's the behavior I'm talking about.  to remedy, uninstall but don't delete the drivers (heck write down all the driver details just in case) at the higher levels (in devices by connection view) then rescan for hardware changes and it will reinstall. how high you have to go may depend on various things though like hubs.  by your comment, I'd aim for "Hub_#005"

@Abel I uninstalled the device in Device Manager, and rescanned. Behavior doesn't change. Device Manager quitting is very strange, and i suspect a very deep error. Reinstalling the OS is not an option. I have surrendered, and bought a new laptop for this project.

one more thing you could try is to reset the root and generic hub layers (advanced tab at properties from device manager)