message:
Serial read and send to UDP?

I was trying to send whatever is received from serial by udp, but it doesn't work properly.
the receiver side showing number 50 51 53 ..... the result like below screenshot:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/srZXP.png

can anyone help me please to fix ?

sender sketch:

    #include <ESP8266WiFi.h>
    #include <WiFiUdp.h>

    const char* ssid = "MikroTik";
    const char* password = "12345678";
    unsigned int localPort = 2390;

    WiFiUDP Udp;
    void setup() {
      delay(1000);
      Serial.begin(115200);
      WiFi.begin(ssid, password);
      Udp.begin(localPort);
    }

    void loop() {
      Udp.beginPacket("10.5.50.23", localPort);
      int val = Serial.read();
      Udp.print(val);
      Udp.endPacket();
      delay(10);
    }

receiver sketch:

    #include <ESP8266WiFi.h>
    #include <WiFiUdp.h>

    const char* ssid = "MikroTik";
    const char* password = "12345678";
    unsigned int localPort = 2390;
    char packetBuffer[255];
    WiFiUDP Udp;

    void setup() {
      Serial.begin(115200);
      WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED){
        delay(500);
        Serial.print(".");
      }
      Udp.begin(localPort);
    }

    void loop() {
      delay(10);
      if (Udp.parsePacket()) {
        int len = Udp.read(packetBuffer, 255);
        if (len > 0) {
          packetBuffer[len] = 0;
          Serial.println(packetBuffer);
        }
      }
    }

body:
The problem is with the different interpretations of the binary data and lies in these two lines:

    int val = Serial.read();
    Udp.print(val);

What you write into the Serial Monitor is ASCII encoded text. Each byte of data corresponds to one character. If you write an `a` this is taken as the ASCII representation. In hexadecimal this character is `0x61` and in decimal `97`. Thats the actual value that gets transmitted to the ESP over Serial. Then you read that into an integer. SO `val` would have the value 97. Then you use `Udp.print(val)`. All `print()` functions are there for producing a human readable representation of the data, meaning ASCII encoded (Thats a standard Arduino convention). So basically you said here: "Here you have a number (integer). Print it into the UDP packet in human readable (ASCII) form." So the UDP packet now contains the ASCII string "97". You probably typed the digit `5` and then `4` a few times. Their decimal values are 53 and 52.

There probably also is a function called `Udp.write()`. The `write()` functions by convention don't change the data. They just write it without interpretation. So by using `Udp.write()` the actual binary value of the received data would be send and the letter `a` would appear as letter `a` in the Serial output of the receiver.

This works good as long as you only want to send single bytes in your packets. Also note, that `Serial.read()` will return `-1` if there is no data to read in the buffer. So to handle that you need to step up the sender code:

- Only read from Serial, if there is actually data in the buffer. You can use an if statement for this like:

        if(Serial.available()){ // read in this if statement

- Read all data from Serial up to a specific delimiter character, which marks the end of a complete message. Typically the newline character `\n` is used for that. You can configure the Serial Monitor to use newline as line ending (it then gets appended to the typed text when you press Enter). There are a lot of example codes for this on the web.


sender: user

message:
How to calibrate an accelerometer?

I'm confused about a few points on how to best calibrate an accelerometer, whose data will be used in an orientation sensor fusion algorithm.

As a summary, the most common approaches I've seen take measurements in 6 different orientations (1G in +x, -x, +y, -y, +z, -z), to then arrive at a max, min measured value. Offsets are then calculated as averages: `(max - min)/2`. And then a scaling factor is calculated. There's a few aspects of this that I'm unclear about, and was hoping it's okay to ask in a single question, since they are related.

**1)** the examples calculate the average as written above, rather than `sum all vals / N vals`. Isn't that approach more error-prone?

**2)** should the offset per axis be calculated once for each orientation, and then summed?

**3)** what's the best approach to calculate scale bias?

[Example 1][1] (pseudo-code):

    chordlengthX = (max - min)/2
    chordlengthY = (max - min)/2
    chordlengthZ = (max - min)/2

    avg_rad = (chordlengthX + chordlengthY + chordlengthZ)/3

    scaleX = avg_rad/chordlengthX

    calibratedX = (x - offset)*scaleX

[Example 2][2]:

    rawrange = max - min
    refrange = refmax - refmin // 1G??

    calibratedX = (((x - min)*refrange)/rawrange) +refmin

Something else altogether (as you can probably tell I need to revise my maths)?

**4)** if my surface is not completely level, I cannot trust my measurements since my 1G reference is not accurate?

  [1]: https://github.com/kriswiner/MPU6050/wiki/Simple-and-Effective-Magnetometer-Calibration
  [2]: https://learn.adafruit.com/adxl345-digital-accelerometer/programming

sender: assistant

body:
Most accelerometers are usable out of the box.  (It is the magnetometers that are difficult to use w/o calibration.)

That said, example 1 looks good until the last line.  You need an x-offset which is simply the difference between the x-maximum and x-minimum.

Consider how the coordinates of the X, Y and Z values of an accelerometer would appear if plotted in 3D space.  One that is perfectly aligned would appear spherical.  But if one of the sensors is more sensitive than the others, the 3D plot might take on an egg shape.  You have corrected for this in the first 5 lines of example 1.

Now, if one of the sensors is not centered the 3D plot would be shifted off the 0,0,0 point of the 3D plot.  You can correct for that by finding the  x-offset, y-offset and z-offset.

You should not need to find the value for 1G.  You should not need to find a perfectly flat surface. To calibrate you need to rotate the accelerometer smoothly about its center.  Take care not to expose the accelerometer to greater than 1G during calibration.  Rotate the accelerometer in a random fashion until you are satisfied that all 3 sensors have experienced their most negative and most positive values.


message:
Safely extend TCNT1 / ICR1 to 24 bits using TOV1

I'm hoping to time external events on a '328p Arduino that will occur slowly enough that they'll overflow the 16-bit counter TCNT1. In a different scenario I'd prescale the counter, but I need the full timer resolution in this case for other purposes.

So I enable the TOV1 interrupt and just increment an 8-bit value, letting it roll over as needed.

Then on an ICP1 interrupt, I shift this value << 16 into a 32-bit variable, and add in the value captured in ICR1, yielding a 24-bit value that I can use to measure the slow interval.

Are there hidden gotchas in this plan? Possible race conditions where TOV1 hasn't yet been updated if ICR1 is latched just when TCNT1 has just rolled over, or generates a TOV1 after capturing ICR1 but before I shift in the overflow count?

body:
There is, indeed, a possible race condition. Consider this naive code,
which provides 32-bit timestamps:

```c++
/* Count overflows. */
volatile uint16_t timer1_overflow_count;
ISR(TIMER1_OVF_vect)
{
    timer1_overflow_count++;
}

/* Timestamp input events. */
volatile uint32_t captured_timestamp;
volatile bool did_capture;
ISR(TIMER1_CAPT_vect)
{
    captured_timestamp = timer1_overflow_count << 16 | ICR1;
    did_capture = true;
}
```

Since TIMER1\_CAPT has higher priority than TIMER1\_OVF, then:

 * If `ICF1` rises before `TOV1`, `TIMER1_CAPT_vect` runs first, which
   is fine.

 * If `ICF1` and `TOV1` rise simultaneously, `TIMER1_CAPT_vect` runs
   first, which is still fine, as the captured value is `0xffff`.

 * If `TOV1` rises before `ICF1`, either ISR may run first:

    - if the CPU can process the TIMER1\_OVF IRQ right away, then
      `TIMER1_OVF_vect` runs first and the result is correct

    - if the interrupt processing is delayed until after `ICF1` has
      risen, then `TIMER1_CAPT_vect` runs first and grabs a wrong value
      for `timer1_overflow_count`.

## Solution

There is an unhandled overflow when `bit_is_set(TIFR1, TOV1)`. The
overflow may have happened at the same time or after the capture, in
which case it doesn't affect the timestamp. We know it happened before
the capture when the captured value is small, where “small” could be
defined as having its most significant bit clear. If this is the case,
we have to add `0x10000` to the timestamp we obtained.

A race-proof ISR can be written as follows:

```c++
ISR(TIMER1_CAPT_vect)
{
    uint16_t captured_low = ICR1;
    uint16_t captured_high = timer1_overflow_count;
    if (bit_is_set(TIFR1, TOV1) && !(captured_low & 0x8000)) {
        captured_high++;
    }
    captured_timestamp = (uint32_t) captured_high << 16 | captured_low;
    did_capture = true;
}
```


message:
Why does the official tutorial for LED matrix scanning writes column pin twice?

I was following the official tutorial and confused by the source code.

[Arduino Official built-in example: RowColumnScanning](https://docs.arduino.cc/built-in-examples/display/RowColumnScanning)

```cpp
// when the row is HIGH and the col is LOW,
// the LED where they meet turns on:
digitalWrite(col[thisCol], thisPixel);
// turn the pixel off:
if (thisPixel == LOW) {
  digitalWrite(col[thisCol], HIGH);
}
```

Here is my understanding:

1. If `thisPixel` is `LOW`, the pin `col[thisCol]` would be `HIGH`.
2. If `thisPixel` is `HIGH`, the pin `col[thisCol]` would still be `HIGH`.

# Question

Because it `col[thisCol]` is always `HIGH` regardless of `thisPixel`, does it make sense to have an extra `if` statement?

# In case the URL is dead

[![enter image description here][1]][1]

```cpp
/*
  Row-Column Scanning an 8x8 LED matrix with X-Y input

  This example controls an 8x8 LED matrix using two analog inputs.

  This example works for the Lumex LDM-24488NI Matrix. See
  https://sigma.octopart.com/140413/datasheet/Lumex-LDM-24488NI.pdf
  for the pin connections.

  For other LED cathode column matrixes, you should only need to change the pin
  numbers in the row[] and column[] arrays.

  rows are the anodes
  cols are the cathodes
  ---------

  Pin numbers:
  Matrix:
  - digital pins 2 through 13,
  - analog pins 2 through 5 used as digital 16 through 19
  Potentiometers:
  - center pins are attached to analog pins 0 and 1, respectively
  - side pins attached to +5V and ground, respectively

  created 27 May 2009
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/RowColumnScanning
*/

// 2-dimensional array of row pin numbers:
const int row[8] = {
  2, 7, 19, 5, 13, 18, 12, 16
};

// 2-dimensional array of column pin numbers:
const int col[8] = {
  6, 11, 10, 3, 17, 4, 8, 9
};

// 2-dimensional array of pixels:
int pixels[8][8];

// cursor position:
int x = 5;
int y = 5;

void setup() {
  // initialize the I/O pins as outputs iterate over the pins:
  for (int thisPin = 0; thisPin < 8; thisPin++) {
    // initialize the output pins:
    pinMode(col[thisPin], OUTPUT);
    pinMode(row[thisPin], OUTPUT);
    // take the col pins (i.e. the cathodes) high to ensure that the LEDS are off:
    digitalWrite(col[thisPin], HIGH);
  }

  // initialize the pixel matrix:
  for (int x = 0; x < 8; x++) {
    for (int y = 0; y < 8; y++) {
      pixels[x][y] = HIGH;
    }
  }
}

void loop() {
  // read input:
  readSensors();

  // draw the screen:
  refreshScreen();
}

void readSensors() {
  // turn off the last position:
  pixels[x][y] = HIGH;
  // read the sensors for X and Y values:
  x = 7 - map(analogRead(A0), 0, 1023, 0, 7);
  y = map(analogRead(A1), 0, 1023, 0, 7);
  // set the new pixel position low so that the LED will turn on in the next
  // screen refresh:
  pixels[x][y] = LOW;

}

void refreshScreen() {
  // iterate over the rows (anodes):
  for (int thisRow = 0; thisRow < 8; thisRow++) {
    // take the row pin (anode) high:
    digitalWrite(row[thisRow], HIGH);
    // iterate over the cols (cathodes):
    for (int thisCol = 0; thisCol < 8; thisCol++) {
      // get the state of the current pixel;
      int thisPixel = pixels[thisRow][thisCol];
      // when the row is HIGH and the col is LOW,
      // the LED where they meet turns on:
      digitalWrite(col[thisCol], thisPixel);
      // turn the pixel off:
      if (thisPixel == LOW) {
        digitalWrite(col[thisCol], HIGH);
      }
    }
    // take the row pin low to turn off the whole row:
    digitalWrite(row[thisRow], LOW);
  }
}
```

  [1]: https://i.stack.imgur.com/v9VF7.png

body:
You are right, the `if` does not make sense. Not all tutorials are correct, and even if, they are often not very good.

The reason for the second `digitalWrite()` is to switch the pixel off after it was potentially on. If it stays on when the row is changed, you could see ghosting.

However, I would switch all pixel of a row, delay a bit, and then **in a second loop**, switch them all off again, before I process the next row.


body:
I'm going to split this answer into two parts, the first about matrix displays in general, and the latter considering this particular dubious example.

The fundamental idea of a matrix display is that the LEDs don't need to be on continuously. If they are illuminated sufficiently often and for a sufficient proportion of the time, then the human eye will average things out.

Exactly what "sufficiently often", and a "sufficient proportion" of the time are can be hard to pin down. The former depends on the particular person viewing, but I would aim for at least 100Hz. The latter depends mostly on how bright your LEDs are when turned on (more on that later).

This is useful because it saves you a lot of IO lines, if you wanted individual control of 256 LEDs you would need 256 IO lines. By using a row/column matrix you only need 16. Of course with a row/colum matrix, it isn't possible to illuminate all combinations of LEDs at the same time, but that doesn't actually matter because as long as you illuminate each active LED sufficiently often the human eye won't notice the difference.

It's good practice to turn off the LEDs that you have turned on for one row before moving on to the next row. Otherwise you can get "ghosting" where an unintended LED illuminates. How much of a problem ghosting is in practice depends heavily on the specifics of your matrix drive code.

---

Several things however set this example apart from a "Normal" matrix drive implementation.

* This example only lights a single LED at a time. Most matrix drive implementations light a whole row (or column) at a time. That means the LEDs are illuminated a much greater proportion of the time, it does have downsides though, it means your row drivers have to have enough current drive capacity to drive a whole row at once.
* This example has no series resistors! the current through the LEDs is limited only by the internal resistance of the LEDs and the IO pin drivers in the AVR. This likely results at the LEDs and the GPIO pins operating significantly above their nominal max current!
* There is nothing to control the timing in the code, and the LED on time is very short. Depending on how well the compiler optimizes the code, it may only be a few clock cycles.

Some of these factors cancel each other out, the drive current is likely very high, but it's only applied very briefly and only to one LED at a time. So the overall result is likely that nothing gets fried and the display has a usable brightness.

But nevertheless, I think it's the sort of example that gets Arduino a bad name. It presumably works (or it wouldn't have been posted), but it's driving components out of specification, and the brightness of the display is totally at the mercy of poorly specified internal resistances and code execution speed.


message:
Arduino HX711 load cell lots of drift

I am trying to make [this][1] 50kg load cell work with [this][2] HX711 chip. I currently have the following connections :
<br>

 - Load cell red -> E+
 - Load cell black -> E-
 - Load cell white -> A-
 - Load cell green -> A+

I am using [this][3] library and this code :
```
#include "HX711.h"

#define calibration_factor -7050

HX711 scale;

void setup()
{
  Serial.begin(9600);
  scale.begin(2, 3);
  scale.set_scale(calibration_factor);
  scale.tare();
}

void loop()
{
  Serial.println(scale.get_units(1));
  delay(100);
}
```
The load cell appears to register load changes but the value is constantly going up (or down if the calibration_factor is positive). The value change rate is very high (from 0 to 300 in a couple of seconds).

Edit : I have 2 load cells and both of them do the same thing (with different HX711 chips).

Edit 2 : My question is : has anyone experienced this ? Or does anyone have an idea as to why this is happening ?

  [1]: https://www.robotshop.com/ca/en/micro-load-cell-50-kg.html?gclid=Cj0KCQiA9OiPBhCOARIsAI0y71COwRpGv_NHrT68xsmCCZL6BTN8nYfXpjPnluj4AhdVfCZT5KRI-xcaAjk8EALw_wcB
  [2]: https://www.amazon.ca/-/fr/gp/product/B07MTYT95R/ref=ox_sc_rp_title_rp_1?smid=&psc=1&pf_rd_p=9e23f442-1cd8-4ea2-a936-d77b2d58e3f5&pd_rd_wg=gbmVg&pd_rd_i=B07MTYT95R&pd_rd_w=Ik5oB&pd_rd_r=d4e1d9b9-e72f-453c-b6d9-3bd255d99539
  [3]: https://github.com/bogde/HX711

body: The solution was to solder all the wires, now the drift seems to be very minimal or non existant.


message:
My ESP32 WROOM clone will not register touch sensor when using a 5v power bank with usb cable

I have a very simple touch sensor program that works fine and lights an led to show the sensor works; while hooked up to the computer via usb cable it works fine.  When using a power bank with the same usb cable the board lights up but does not read the touch sensor.  I have tried other cables with the same result.

body: This is hard to explain but your problem in not unique. I hope this helps. It is your ground reference. When connected to the computer which is grounded either/or a ground wire or capacitive coupling to earth. Your body is capacitively connected to ground that way and when you touch the switch it is recognized.  To make it work with the battery pack you need to couple to the person touching it. You can do that capacitively by adding a ground plain to your circuit. This can be a conductive plate that will capacitively couple the ground to the atmosphere or any other practical means.


message:
Are resistors necessary for 8x8 LED matrix?

I was following [the official tutorial of LED matrix integration][source] and couldn't figure out why there is no resistor.

I assumed there are built-in resistors in the LED matrix, so I did an experiment by connecting pin 9 of the LED matrix to v5 of my Arduino Leonardo board and pin 13 of the LED matrix to GND of the same board. You can refer to the schematic diagram below to know I was trying to lit up the LED at the position [0, 0].

Unfortunately, the LED next to [0, 0] burned immediately and I still couldn't figured out it.

![](https://i.stack.imgur.com/haoD5.jpg)

# Question

1. Are resistors necessary for 8x8 LED matrix?
   1. If yes, why the official example doesn't have any resistor?
   2. If no, why my experiment failed?
   3. If no, why are there so many unofficial examples use resistors for each wire?

# Source

https://docs.arduino.cc/built-in-examples/display/RowColumnScanning

# Circuit

![](https://i.stack.imgur.com/PEvsg.png)

# Schematic

![](https://i.stack.imgur.com/jFRqg.png)

[source]: https://docs.arduino.cc/built-in-examples/display/RowColumnScanning

body:
Well done Arduino, you did a great job providing a magic-smoke tutorial [sarkasm off]. IDK how this tutorial could make it into their official docs, it should not be there!

You definitely need series resistors at each column or at each row to protect the LEDs/GPIOs (that's 8 resistors). There may be matrices that integrate resistors, but your one and the one they use in their docs does not.

An alternative is to configure the column GPIOs as inputs with enabled pullups and the row GPIOs as ordinary outputs. This way, current will be limited by the pullup resistors. But as those are quite large (several 10kOhm depending on MCU) the LEDs will be very dim.


message:
High frequency sampling with Arduino

I need to sample signals up to about 200 kHz using the Arduino as a kind of oscilloscope. I have already seen that by itself it is unable to do it, since the sample frequency is about 9.6 kHz. But would it be possible to connect it with an external ADC?

Thanks.

body:
The rule of thumb for scopes is about 5X the frequency. 2X will give you some information but a lot will be missing. What is the voltage range of the input signals? How many bits of accuracy do you need. How about probes? Then there is memory.

You cannot access the internal memory of the Arduino so it will have to be external and dual ported. Dual ported indicates two different sources can access it. How are you going to refresh the memory if dynamic? Static would work but is more expensive.

I would highly recommend you purchase your scope unless this is a learning experience. You can get some very inexpensive scopes for under $100 or even a used one. I think these would work much better then anything you can build for for the same cost.

Many scopes have a interface to external devices can access them, this may be just what you need?


message:
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?

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

1. First create your data directory, where you then place your config.json file. The standard is a directory named "data" inside the sketch folder.
2. 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.


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


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

body:
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:

[![enter image description here][1]][1]

But the signal, which is passed through long line of wire can be look like this:
[![enter image description here][2]][2]

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

  [1]: https://i.stack.imgur.com/macUL.png
  [2]: https://i.stack.imgur.com/9oQsm.png


message:
How to convert serialized JSON string back to JSON object?

How to convert JSON String for example

```Arduino
{"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][1] uses kind of different serialized JSON

Example shown,

```char json[] = "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";```

  [1]: https://arduinojson.org

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

body:
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
  }
```


message:
A library issue with ArduinoOTA for MKR1400GSM

For the past years I've been using [ArduinoOTA][1] along with [ArduinoHttpClient][2] 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!

  [1]: https://github.com/jandrassy/ArduinoOTA
  [2]: https://github.com/arduino-libraries/ArduinoHttpClient

body:
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. <del>The SAMD core doesn't have a new release yet. You can apply **[the fix][1]** to your 1.8.12 installation, or return to 1.8.11 version</del>. EDIT: SAMD core 1.8.13 is already available too.

EDIT: Or you can use [the 'fake programmer' method][2] which doesn't require network port to be detected by the IDE and has a separate configuration.

  [1]: https://github.com/arduino/ArduinoCore-samd/commit/e16354443899fe77ea724452fa5a9272689a5a99
  [2]: https://github.com/jandrassy/ArduinoOTA#ota-upload-from-ide-without-network-port


message:
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?

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


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

body:
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`


message:
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

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


message:
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

body:
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**](https://forum.arduino.cc/t/update-time-from-ds3231/962252/5)


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

body:
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](https://www.arduino.cc/reference/en/libraries/arduinostl/).


message:
Is there any standard for colors of Serial Peripheral Interface wires?

Having DuPont cables like on the picture...

[![DuPont cable coloured -- for what I have in hands.][1]][1]

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

[![Colors on pins][2]][2]

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:

[![Colors and pins.][3]][3]

  [1]: https://i.stack.imgur.com/jfX27.jpg
  [2]: https://i.stack.imgur.com/DdU0H.jpg
  [3]: https://i.stack.imgur.com/ymv6w.jpg

body:
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 ***r**ed is **r**ight 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.


message:
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;
        }
      }

    }

body:
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").


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

body:
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


message:
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
[![enter image description here][1]][1]
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!

  [1]: https://i.stack.imgur.com/mZdo1.png

body:
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][1] on my blog site for some ideas

[![MEGA2560 Implementation][2]][2]
[![ESP32 Implmentation][3]][3]

  [1]: https://www.fpaynter.com/2020/06/replacing-hc-sro4-ultrasonic-sensors-with-vl53l0x-arrays/
  [2]: https://i.stack.imgur.com/aiHaP.png
  [3]: https://i.stack.imgur.com/P33Rg.png


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

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


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


message:
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?

body:
>     #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.


message:
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?

body:
There is a discussion of a similar question at the [Arduino forum][1] 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][2] at Sparkfun, and [Wikipedia][3] has a good starting reference point.

  [1]: https://forum.arduino.cc/t/arduino-rfid-tag-detection/139570
  [2]: https://learn.sparkfun.com/tutorials/rfid-basics/all
  [3]: https://en.wikipedia.org/wiki/Radio-frequency_identification


message:
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);
      // ...

    }

body:
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];


body:
As stated by Mat, the empty string in C++ is `""`. This works:

```c++
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()`.


body:
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, "XXXXXX", baseMac[0], baseMac[1], baseMac[2], baseMac[3], baseMac[4], baseMac[5]);
        return String(macStr);
    }
    // END getMacAddress()


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

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


message:
How exactly do Bicycle LEDs work? (Arduino Project)

Table of contents:
1) What I want to achieve
2) Problem I'm facing
3) What I've tried
4) 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!!

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


body:
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:

1) Use [state variables and state machines][1] to change the mode of operation.

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

  [1]: https://en.wikipedia.org/wiki/Finite-state_machine#Example:_coin-operated_turnstile


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

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


body:
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()][1] in place of Serial.readString().  From the linked to page:

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

  [1]: https://www.arduino.cc/reference/en/language/functions/communication/serial/readstringuntil/


message:
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

body:
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][1].

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][2]. Remember Adafruit always gives you incredibly good instructions for all their products if you're ever stuck.

[![enter image description here][3]][3]

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!

  [1]: https://electronics360.globalspec.com/article/14808/how-to-control-a-dc-motor-with-an-arduino
  [2]: https://www.adafruit.com/product/3190
  [3]: https://i.stack.imgur.com/H4XFn.png


message:
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)?

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


message:
why is my char array empty

following sketch will run totally fine and as expected :
```
#include <Wire.h>

#include "SparkFun_External_EEPROM.h"
ExternalEEPROM ExtEEPROM;
char username[33] = "";
char password[65] = "";

void setup()
{
  Serial.begin(115200);
  delay(1000);
  Wire.begin();
  #define EEPROM_ADDRESS 0b1011000 // 0x58
  ExtEEPROM.setMemorySize(256000/8); // 256kbit = 32kbyte
  ExtEEPROM.setPageSize(64); // 64 byte page size.
  ExtEEPROM.enablePollForWriteComplete();
  ExtEEPROM.setPageWriteTime(10); // max. ms for AT24C128
  if (ExtEEPROM.begin(EEPROM_ADDRESS, Wire) == false)
  {
    Serial.println("No memory detected. Freezing.");
    while (1);
  }
  Serial.println("Memory detected!");

  String uuu = "myusername";
  String ppp = "mypassword";

  uuu.toCharArray(username, sizeof(username) - 1);
  ppp.toCharArray(password, sizeof(password) - 1);
  Serial.print("password=");Serial.println(password);
  ExtEEPROM.put(0, username);
  //delay(100);
  ExtEEPROM.put(0 + sizeof(username), "greatnewpassword");
}

void loop() {
  char xxx[33] = "";
  ExtEEPROM.get(0, xxx);
  Serial.print("xxx=");Serial.println(xxx); // prints the username

  char yyy[33] = "";
  ExtEEPROM.get(0 + sizeof(username), yyy);
  Serial.print("yyy=");Serial.println(yyy); // prints the password
  delay(1000);
}
```

However, if I replace ```ExtEEPROM.put(0 + sizeof(username), "greatnewpassword");``` to ```ExtEEPROM.put(0 + sizeof(username), password);```, then ```yyy``` prints empty in the serial monitor. Why?

body:
`.get` and `.put` are being passed a char pointer, not the contents of a char array. Thus you're not writing the content of the string but the address in memory where it's being stored.

With a string literal that is fixed and never changes, so what you write and what you read are fine. With a variable though the address could be anything, and storing the address of some RAM where a string is stored is pointless.

`.get()` and `.put()` should only be used for atomic, self-contained, types like `int` or `float`, not pointers like `char *`.

Instead you need to be using the `.read(address, buffer, size)` and `.write(address, buffer, size)` functions to read and write the contents of your char arrays.


body:
As Majenko already mentions:

> .get() and .put() should only be used for atomic, self-contained,
> types like int or float, not pointers like char *.

Not sure what atomic means here, but you may .put and .get any data type, especially a struct.

    struct EPROMData {
      char username[33];
      char password[65];
    };
    EPROMData data {"myusername","mypassword"};

    void setup() {
       ...
       ExtEEPROM.put(0,data);
    }
    void loop() {
       EPROMData d;
       ExtEEPROM.get(0,d);
       Serial.print("user="); Serial.println(d.username);
       ...
    }

Sure, if the data type is a pointer or a String object (containing a pointer only), you won't be happy with .put / .get


body:
problem seems to be the lib I am using. I think it can not handle data overlapping page size.

if I replace from this
```
char username[33] = "";
char password[65] = "";
```

to this:
```
char username[16] = "";
char password[16] = "";
```

everything works fine as it saves and reads from the EEPROM via I2C.


message:
RFM69HCW connected to Arduino Nano 33 BLE

I tried to connect my RFM69HCW to Arduino Nano 33 BLE, so that I won't be needing a logic level shifter to downgrade the voltage, since Arduino Nano is already 3.3V. Upon checking its data sheet and pinout, I noticed there's no dedicated pin for CS (Chip Select).

Which pin should I use as CS in the Arduino Nano?

Which pin should I connect the DI0 pin of RFM69HCW in the Arduino Nano?

body: On any Arduino you can use any free digital pin as SPI CS.


body: There is no dedicated CS pin, and you can use any available Dx pin – which enables you, among other things, to have several devices on the same bus. The CS pin allows you to select (hence the S) the right device.


message:
What GSM module I should use for HttpClient, ArduinoHttpClient, WebSockets etc.?

I need to use some API in my project. So I'm gonna use such libraries as listed in the title? What GSM/SIM module do I need for this purpose? I've checked 800L and similar - it only can use plain http, and only via AT command. At least based on this, that's not what I really need. Thanks in advance.

body:
The TinyGSM library implements the Arduino Client class required by networking super libraries you mention in the question.

TinyGSM [supports][1] the SIM800 modems.

  [1]: https://github.com/vshymanskyy/TinyGSM#supported-modems


message:
Wind speed measuring using Hall effect Anemometer

I need your help regarding a problem I am facing while measuring wind speed. In my sketch I get a reading every 20 counts which the magnet goes past the sensor. I need to change it in order to get a reading every 20 seconds. How can I do it with minimum changes to the sketch?

    volatile byte revolutions;

    float rpmilli;
    float speed;

    unsigned long timeold=0;

    void setup()
    {
      Serial.begin(9600);
      attachInterrupt(digitalPinToInterrupt(2), rpm_fun, RISING);

      revolutions = 0;
      rpmilli = 0;
      timeold = 0;
    }

    void loop()
    {
      if (revolutions >= 20) {
        //Update RPM every 20 counts, increase this for better RPM resolution,
        //decrease for faster update

        // calculate the revolutions per milli(second)
        rpmilli = ((float)revolutions)/(millis()-timeold);

        timeold = millis();
        revolutions = 0;

        // WHEELCIRC = 2 * PI * radius (in meters)
        // speed = rpmilli * WHEELCIRC * "milliseconds per hour" / "meters per kilometer"

        // simplify the equation to reduce the number of floating point operations
        // speed = rpmilli * WHEELCIRC * 3600000 / 1000
        // speed = rpmilli * WHEELCIRC * 3600

        speed = rpmilli * 0.6597 * 3600;

        Serial.print("RPM:");
        Serial.print(rpmilli * 60000);
        Serial.print(" Speed:");
        Serial.print(speed);
        Serial.println(" kph");
      }
    }

    void rpm_fun()
    {
      revolutions++;
    }

body:
You can use the `millis()` function to measure time intervals and do things regularly in these intervals. Refer to the `BlinkWithoutDelay` example, that comes with the Arduino IDE, or to one of the many tutorials for the `millis()` function on the web.

Basically you will need to do the following:

1. Declare a timestamp variable to hold the time when the data was displayed last time (in global scope):

        unsigned long timestamp = 0;

2. Declare the interval, that you want the display to happen in:

        #define DISPLAY_INTERVAL  20000

3. In your if statement check if the time difference between now and the timestamp is bigger than the interval

        if(millis() - timestamp > DISPLAY_INTERVAL){

    Note that you should do `millis()` comparisons always this way (by calculating the difference), so that the rollover of `millis()` will not affect the result.


message:
Cannot read values stored in bool* pointer

I'm trying to read values stored in a bool* pointer from a modbus coil call.

I'm using modbus-esp8266 library. it's all ok with Input Registers and Holding Registers but i cannot read the result of a coil read.

    #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.print(event, HEX);
      }
      return true;
    }

    void setup() {
      Serial.begin(115200);
      S.begin(9600, SWSERIAL_8N1);
      mb.begin(&S);
      mb.master();
    }

    void loop() {
    bool* coils;
      if (!mb.slave()) {    // Check if no transaction in progress
        mb.readCoil(1, 1, coils, 1, cb); // Send Read Hreg from Modbus Server
        while(mb.slave()) { // Check if transaction is active
          mb.task();
          delay(10);
        }
        Serial.println(*coils);

      }
      delay(1000);
    }

I get this kind of error when trying to print *coils

    Exception 28: LoadProhibited: A load referenced a page mapped with an attribute that does not permit loads

How to get the boolean result value from it?

body:
When programming an Arduino you are actually writing in the language C.  As such you can search the internet for C programming answers of which there is likely 50 years of answers.

You have defined "coils" as a pointer.  This is done by preceding the name with an asterisk where it is defined.  In this line of code:

    bool* coils;

This means you are using coils to store the memory location of where the actual value is to be stored.  However, in the case of the code in the posted question, the memory location of where the actual value is to be stored is never defined.

*This is like going on a bad clue hut.  You receive instructions to obtain the next clue at a specific location.  But when you get there you find no further instructions.*

Beginning programmers often find pointers confusing.  But later find pointers very useful tools that simplify many otherwise complex programs.

Consider dropping the asterisk in front of "coils" on the two lines of code where is exists and try running the program again.

---

Added later:

Guessing, it may be that the call to readCoil function assumed to be defined in ModbusRTU.h requires a pointer to be passed to in as the 3rd formal variable parameter.  This is more advanced C programming.  If true, then keep your original code but add a line of code setting the value of "coils" to the address of a new bool variable.  Perhaps something along these lines:

    bool* coils;
    bool coils_value;
    coils = &coils_value;


message:
Looking for help with an improved vibration sensing method for Arduino

I am trying to test how vibration waves move through different material...ie how sensitive certain components are.
I am needing a vibration sensor that will send me back some kind of measurement say in the form of an integer between 1 and (a number).

I have tried the 801S with an Arduino board and it was successful. The problem though is it just returns a 1 for vibration and 0 for none. To get the results I had to keep retesting and moving the material further and further away to get it to fail.

I also tried a HiLetgo piezoelectric analog sensor. It does return a number...but the results are all over the place...from 5 to 250. I have a device that supplies a consistent "tap" to be measured...so the HiLetgo had to be letgo.

I did research SE and found this question https://arduino.stackexchange.com/questions/11773/vibration-sensor-for-arduino but it does not answer my question.

body:
I did some experiments a year or so ago to sense vibration through a (physical) office desk top using the inbuilt accelerometer and gyroscope of an Arduino Uno Wi-Fi Rev2. That chip is an [LSM6DSM][1] but I would think that any such module (e.g., [MPU6050][2]) connected to any Arduino could be useful.

There’s a good [comparison article][3] at Seeed Studios introducing vibration sensors for Arduino.

Update. Looking at the similar question linked by the OP I see several comments that the MPU6050 which I suggested  would have poor resolution. You may have to study data sheets (or experiment) to find the best  device for your purpose.

Second update. This [white paper][4], “Measuring vibration with accelerometers” has some good engineering notes about selecting suitable accelerometers for different purposes.

  [1]: https://www.st.com/resource/en/datasheet/lsm6dsm.pdf
  [2]: https://www.cdiweb.com/datasheets/invensense/mpu-6050_datasheet_v3 4.pdf
  [3]: https://www.seeedstudio.com/blog/2020/01/07/vibration-sensors-types-how-to-use-with-arduino-and-raspberry-pi/
  [4]: https://www.ni.com/en-au/innovations/white-papers/06/measuring-vibration-with-accelerometers.html


message:
How can I SPI "Latch" (LE/CS/SS) for a specific number of SCLK cycles?

Context
---
I am working on a project which includes 13 cascaded STMicroelectronics [LED1642GWs](https://www.st.com/en/power-management/led1642gw.html). These LED drivers are essentially 16bit shift registers, whereby the buffered serial data can be loaded to a number of different registers dependant on the required function.

The function is selected through the use of "digital keys", which is selected by number of CLK cycles for which the LE (CS/SS) pin is HIGH. For example, LE being HIGH for 1-2 CLK cycles will switch the 16 outputs as per the buffered bits, whereas LE being HIGH for 3-4 CLK cycles will load the 16 bits to a brightness register.

[![Digital Keys][1]][1]

Question
---
How can I toggle my LE/CS/SS pin for a specific number of SCLK cycles? I had intended to use the [SPI Libary](https://www.arduino.cc/en/Reference/SPI), however I'm not sure this can be supported.

**Many Thanks!**

  [1]: https://i.stack.imgur.com/6knUc.png

body:
I've achieve this by "bit-banging" via a modified `shiftOut()` of [ArduinoCore-avr/cores/arduino/wiring_shift.c](https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring_shift.c), essentially allowing for two data lines on the same clocking:

```c
void keyedShiftOut(
  uint8_t dataPin,
  uint8_t clockPin,
  uint8_t latchPin,
  uint8_t bitOrder,
  uint16_t val,
  uint16_t key)
{
 uint8_t i;

 for (i = 0; i < 16; i++)  {
  if (bitOrder == LSBFIRST) {
   digitalWrite(dataPin, val & 1);
   val >>= 1;
            digitalWrite(latchPin, key & 1);
   key >>= 1;
  } else {
   digitalWrite(dataPin, (val & 0x8000) != 0);
   val <<= 1;
            digitalWrite(latchPin, (key & 0x8000) != 0);
   key <<= 1;
  }

  digitalWrite(clockPin, HIGH);
  digitalWrite(clockPin, LOW);
 }
}
```
I used this to implement the sequence described within the data sheet (Figure 24. Brightness register setting) to set all of my 16 Brightness Registers to a half setting (0x7FFF) with a timed LE providing the digital key. This scoped out as:

[![ScopeOutput][1]][1]

Running on my Arduino Nano 33 IoT this clocked at 150kHz which is sufficient for my application.

  [1]: https://i.stack.imgur.com/w01FK.png


message:
Pulsein() function blocks other tasks from running silmultaneously

I am using a zumo bot with a reflectance sensor used to follow a black line. I want to use an arduino to make the zumo bot stop once it gets a certain distance from an obstacle.

I have an ultrasonic sensor (HC-SR04) which ive connected to the bot.

Both of these tasks work independently but once i merge the code together(so it follows the line aswell as stoping when it detects an object using the ultrasonic sensor), it doesn't work properly.. (the zumo bot no longer follows the line)

I THINK it is to do with the pulsein() function blocking any other tasks but not sure.

My code is below. Can anyone help please?

```

#include <Wire.h>
#include <ZumoShield.h>

ZumoBuzzer buzzer;
ZumoReflectanceSensorArray reflectanceSensors;
ZumoMotors motors;
Pushbutton button(ZUMO_BUTTON);
int lastError = 0;

// This is the maximum speed the motors will be allowed to turn.
// (400 lets the motors go at top speed; decrease to impose a speed limit)
const int MAX_SPEED = 400;
#define echoPin A4
#define trigPin A5

// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

void setup()
{
  reflectanceSensors.init();

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT

  // Initialize the reflectance sensors module

  // Wait for the user button to be pressed and released
  button.waitForButton();

  // Turn on LED to indicate we are in calibration mode
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);

  // Wait 1 second and then begin automatic sensor calibration
  // by rotating in place to sweep the sensors over the line
  delay(1000);
  int i;
  for(i = 0; i < 80; i++)
  {
    if ((i > 10 && i <= 30) || (i > 50 && i <= 70))
      motors.setSpeeds(-200, 200);
    else
      motors.setSpeeds(200, -200);
    reflectanceSensors.calibrate();

    // Since our counter runs to 80, the total delay will be
    // 80*20 = 1600 ms.
    delay(20);
  }
  motors.setSpeeds(0,0);

  // Turn off LED to indicate we are through with calibration
  digitalWrite(13, LOW);

  // Wait for the user button to be pressed and released
  button.waitForButton();

  Serial.begin(9600); // // Serial Communication is starting with 9600 of baudrate speed
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");

}

void loop()
{

  unsigned int sensors[6];

  // Get the position of the line.  Note that we *must* provide the "sensors"
  // argument to readLine() here, even though we are not interested in the
  // individual sensor readings
  int position = reflectanceSensors.readLine(sensors);

  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

  // Our "error" is how far we are away from the center of the line, which
  // corresponds to position 2500.
  int error = position - 2500;

  // Get motor speed difference using proportional and derivative PID terms
  // (the integral term is generally not very useful for line following).
  // Here we are using a proportional constant of 1/4 and a derivative
  // constant of 6, which should work decently for many Zumo motor choices.

  int speedDifference = error / 4 + 6 * (error - lastError);

  lastError = error;

  // Get individual motor speeds.  The sign of speedDifference
  // determines if the robot turns left or right.
  int m1Speed = MAX_SPEED + speedDifference;
  int m2Speed = MAX_SPEED - speedDifference;

  if (m1Speed < 0)
    m1Speed = 0;
  if (m2Speed < 0)
    m2Speed = 0;
  if (m1Speed > MAX_SPEED)
    m1Speed = MAX_SPEED;
  if (m2Speed > MAX_SPEED)
    m2Speed = MAX_SPEED;

  motors.setSpeeds(m1Speed, m2Speed);

  //if (distance <20){
  //  motors.setSpeeds(0,0);
 // }

////////////////////////////////////////////

  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

}
 ```

body:
It is quite likely due to blocking. The description of the `pulseIn()` function in the Arduino site's reference section says:

> Reads a pulse (either HIGH or LOW) on a pin. For example, if value is
> HIGH, pulseIn() waits for the pin to go from LOW to HIGH, starts
> timing, then waits for the pin to go LOW and stops timing. Returns the
> length of the pulse in microseconds or gives up and returns 0 if no
> complete pulse was received within the timeout.

 If you can limit the range within which you want to stop the vehicle, try setting a timeout on `pulseIn()` that will return control once the maximum sound travel time has passed. Maybe that will give you enough response to correct the vehicle's steering. Slowing the vehicle's velocity will help, too (it won't be able deviate as far from it's path as quickly).

Otherwise, you'll probably need a non-blocking equivalent to `pulseIn()`.


message:
Per-Arduino calibration files?

I am planning on having an array of embedded devices in my garden, and each of these is going to have its own analog moisture sensor. Each moisture sensor needs to be individually calibrated.

In an ideal world, I would have the same software on each embedded device, with a configuration file holding the calibration for the attached analog moisture sensor, so that I can minimize the development and CI/CD work.

Is this possible with Arduino, or would I be better off with an embedded device with addressable flash, like an ESP32?

body:
As Edgar Bonet already mentioned, the embedded EEPROM is good to try. I give some options below though:

- In case the configuration file (data) is max. 1 KB, you can use the embedded/internal EEPROM of the Arduino UNO.
- In case the configuration file is larger you have multiple options:
  - On the ESP32 you can use 4 KB EEPROM.
  - If it is higher, on the ESP32 you also can use the SPIFFS file system stored in EEPROM.
  - For other MCUs (ESP32 included), you can use external EEPROM with various sizes, based on SPI or I2C.
- If you want to use a very large configuration file, you could use an SD card, which is much slower of course, which is normally SPI based and can be used on both Arduino and ESP32.

So for a comparison between Arduino Uno / ESP32

    MCU         Solution            Speed Size   External    Wearout
                                                 Hardware
    ----------- ------------------  ----- ------ -------- --------------
    Arduino     Internal EEPROM     High  1 KB      No    EEPROM Wearout
    ESP32       EEPROM Simulation   High  4 KB      No    Flash Wearout

    ESP32       SPIFFS File System  High  <Flash    No    Flash Wearout
                                          Size

    Both        External EEPROM     High  <1MB *   Yes    EEPROM Wearout
    Both        SD Card             Slow  <256GB   Yes          -

*Typically 4 KB to 1 MB, using SPI or I2C