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

title: High frequency sampling with Arduino

Answers: 1

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?


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

title: How to install the application + its configuration to many devices of the same kind? (ESP32)

Answers: 2

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.


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

title: Limit on connector cable for HC-SR04 ultrasonic sensor

Answers: 1

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


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

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

Answers: 1

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


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

title: A library issue with ArduinoOTA for MKR1400GSM

Answers: 2

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

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


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

title: How to detect ESP32 vs ESP8266 automatically when uploading the application?

Answers: 1

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.


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

title: Is possible to use heap_trace_init_standalone() on arduino framework with esp32?

Answers: 1

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`


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

title: Reading & writing a configuration file on an Adafruit Circuit Playground Express

Answers: 1

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.


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

title: Set time() on ESP8266

Answers: 1

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)


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

title: Is it possible to use mathematical sets and their operations in arduino?

Answers: 1

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/).


body:
My Arduino Nano 33 BLE Sense stopped working suddenly a while after uploading firmware for an ML project. I've used my board for several ML projects and it worked like a charm.

I can't find the board in the Arduino IDE's port section.

I've tried to reset the board by double-pressing the reset button, but that didn't make any response, not even flashing LEDs.

I've tried changing USB cables, connecting to different ports of the PC, also other PC's but the result was the same.

I've checked the board's outputs, luckily the 3v, 5v, and Vin pins have output and run without any abnormal heating. I'm not sure what's the problem with this board. Maybe the bootloader got corrupted?

title: Arduino Nano Ble Sense stopped working suddenly

Answers: 0


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

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

Answers: 1

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.


body:
I'm building a panic button project for my grandma which uses a 433MHz RF remote keyfob and a 3.3v Pro Mini connected to an RF receiver, a buzzer and an led. The purpose is that whenever she needs assistance like in the middle of the night, she could simply press the keyfob button and the Arduino will act as an alarm and would go off, alerting me and others. So far I have set everything up and the project works exactly as intended.

How can I further reduce the power consumption on the receiver end of this project so that I can run it using batteries for a long time, like 6 months or so?

The battery I have in mind is either a single 3.2v 5000mAh LiFePo4 battery or 3x AA 2600mAh NiMH Low self discharge cells in series.

My current setup for the receiver has an always active 433MHz RF receiver which draws around 5mA while running at 5v and an Arduino Pro Mini which should consume about another 5mA. I'm using the RC switch Library and the project is currently powered by a USB wall adapter. I haven't used any low power or sleep functionality before so I'm not very informed on those methods.

title: Low power RF decoder possible?

Answers: 0


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

    }

title: esp8266 - server.handleClient() fails to call assigned function

Answers: 1

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


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

title: ELEGOO Mega 2560 USB and Vin simultaneously?

Answers: 1

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


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

title: Is there accurate connection procedure for connection between an esp32 and ultrasonic sensor(HC-SR04)?

Answers: 1

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


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

However I got a warning saying:

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

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

Also is it bad practice to use SPIFFS even though it seems to work fine?

Thanks

title: ESP8266 ESPAsyncWebServer LittleFS crashes

Answers: 0


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

title: I need to run 2 for() loops simultaneously but I cant seem to do it without one executing, then the other after it

Answers: 2

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.


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

title: How I can populate a buffer from data read from SPI?

Answers: 1

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.


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

title: Alternatives to Radio Transceivers

Answers: 1

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


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

    }

title: String type replace function can't replace with no char

Answers: 3

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


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

title: Communicate with Sparkfun CAN Bus Shied

Answers: 1

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.


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

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

Answers: 2

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


body:
I have a prototype LoRa Daughter Board that utilizes RFM69HCW transceiver module. I found an interesting blog online that covers everything courtesy of Sparkfun. Here's the link [RFM69HCW Tutorial by Sparkfun 2.][1]

I followed everything but the 2 RFM69HCW radios that I am working on didn't communicate to each other. When I checked my prototype board, DI0 of the RFM69HCW has no connection at all. Is it necessary to connect the DI0 to hardware interrupt pin of Arduino Uno? And also, can I connect it directly to the Arduino board if ever? Thanks in advance for whoever will shed light on this one.

  [1]: https://learn.sparkfun.com/tutorials/rfm69hcw-hookup-guide/all

title: RFM69HCW connected to Arduino Uno

Answers: 0


body:
I'm trying to connect a modbus meter to a nodeMcu LoLin v3

I'm using a MAX3485 module to transfer the TTL to a RS485 connection.
The modbus server has unitId 1, baud rate 9600 and no Parity

This is the scheme. A e B from the module go to the modbus server device
[![Connection][1]][1]

  [1]: https://i.stack.imgur.com/fPx9X.jpg

And this is my simple script

    #define DIRECTION D3

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

    SoftwareSerial S(D2, D1);
    ModbusRTU mb;

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

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

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

      mb.begin(&S);

      mb.client();
    }

    void loop() {
      uint16_t res[2];

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

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

      }
      delay(1000);
    }

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

    Error result: 0xE4
    Res
    59044
    16382

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

title: ESP8266 - MAX3485 Modbus not getting data

Answers: 0


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

title: How do I fix my code so that it reads text from the serial monitor?

Answers: 2

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/


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

title: How to combine servo shield with peristaltic pump?

Answers: 1

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


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

title: Can I power up an Arduino Uno via the 5 V pin while USB is connected at the same time?

Answers: 1

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.


body:
I just added a few new arduinos, and they are all loading on COM1. Here are some of the strange behaviors:

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

The boards are Elegoo Uno R3. Windows 10, ThinkPad T490s. I have been running arduinos in this configuration for 2 years on this laptop with no issues.

Help would be much appreciated. My project has ground to a halt for days!

title: Arduino's stuck on COM1 and Device Manager Crashing

Answers: 0


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

title: why is my char array empty

Answers: 3

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.


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

title: RFM69HCW connected to Arduino Nano 33 BLE

Answers: 2

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.


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

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

Answers: 1

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


body:
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++;
    }

title: Wind speed measuring using Hall effect Anemometer

Answers: 1

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.


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

title: Cannot read values stored in bool* pointer

Answers: 1

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;


body:
I am trying to connect JTAG debugger to my esp32 according to the following steps https://www.instructables.com/How-to-Use-a-Debugger-on-an-ESP32/
but still I am facing issue in debugging. I am working with MAC
below is the error I am facing while debugging

```
No dependencies
Building in debug mode
Checking size .pio/build/uno/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [          ]   0.4% (used 9 bytes from 2048 bytes)
Flash: [          ]   3.5% (used 1118 bytes from 32256 bytes)
Configuring upload protocol...
AVAILABLE: arduino
CURRENT: upload_protocol = arduino
Looking for upload port...
Auto-detected: /dev/cu.usbserial-1201
Uploading .pio/build/uno/firmware.hex
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

*** [upload] Error 1
```

title: How would I link inline debugger with esp32 on Mac?

Answers: 0


body:
I am trying to use an Adafruit BLE module and an RFM69 module on the same Arduino.

The higher-level functions in each included library (Adafruit_BLE.h, RFM69.h) both use the SPI.h library to talk to each respective module.

I think all I need to do is make a copy of the SPI.h file, and edit it to make the SS pin for one of the modules different.

Is there a better way to do this?

title: How do I use BLE module and RFM69 module together?

Answers: 0


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

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

Answers: 1

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


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

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

Answers: 1

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


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

}
 ```

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

Answers: 1

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


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

title: Per-Arduino calibration files?

Answers: 1

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


body:
I am using esp32 CAM by Arduino IDE and send an image file by ftp using SIM800l GSM/GPRS  module  to a server and every thing is ok .
I can perform http request also and read some data from a website and every thing is ok.

Problem is ftp for large file  and http request can not work at the same time .
if I send AT+HTTPINIT after AT+FTPEXTPUT=1 , it fails
or if I send AT+FTPEXTPUT=1  after  AT+HTTPINIT again it fails .

I close http connection by AT+SAPBR=0,1 but problem exist

How to solve this problem?
How is possible to clear the setting done in the  the sim800l without restarting the module by AT+CFUN=1,1 ?

title: sim800l ftp error after http request

Answers: 1

body:
I found the way to solve the problem .
Http request must be terminated with command AT+HTTPTERM . After this command large ftp works and command AT+FTPEXTPUT=1 is without error . After termination of ftp if we want to do http request again the command AT+FTPEXTPUT=0 must be executed


body:
I'm new here so I hope I do everything right.
Right now, I'm trying to program an IR remote that controls the direction of the 28BYJ-48 stepper motor. When I try to press the down button (The button that turns the stepper motor counter-clockwise,) It keeps going clockwise (Which the up button is supposed to do.) Does anyone have an idea of what I could do to fix this? (By the way, I'm 100% sure I have wired everything correctly. I am using the Arduino Uno.) Thank you.

```#include <IRremote.hpp>

#include <Stepper.h>
#define STEPS 32
int remotePin =6;
IRrecv IR(remotePin);
decode_results cmd;

int stepsPerRevolution;
 Stepper myStepper(STEPS, 8,9,10,11);

void setup() {
  IR.enableIRIn();
}

void loop() {
   if (IR.decode(&cmd)) {

  switch(cmd.value){

 case 0xFF629D:
            myStepper.setSpeed(500);
            stepsPerRevolution = 2048;
            myStepper.step(70);
            break;

    case 0xFFA857:
            myStepper.setSpeed(500);
            stepsPerRevolution = -2048;
            myStepper.step(70);
            break;
  }
  IR.resume();
  }
}
```

title: 28BYJ-48 Stepper motor not turning counter-clockwise

Answers: 0


body:
I've got this simple program for testing DS18B20 temperature sensors.
```
#include "OneWire.h"
#include "DallasTemperature.h"

#define ONE_WIRE_BUS D3

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

void setup()
{
  Serial.begin(19200);
  sensors.begin();
  delay(1000);  //time for serial to connect
  Serial.print(sensors.getDeviceCount());
  Serial.println(" sensors found");
  Serial.print(sensors.getDS18Count());
  Serial.println(" DS18 sensors found");
}

void loop()
{
  sensors.requestTemperatures(); // Send the command to get temperatures

  Serial.print("Temperature for Device 1 is: ");
  Serial.println(sensors.getTempFByIndex(0));

  Serial.print("Temperature for Device 2 is: ");
  Serial.println(sensors.getTempFByIndex(1));

  delay(5000);

}
```

I'm compiling for the Wemos D1 mini.
When I compile on the Arduino IDE, the code runs as expected. It reports two devices, then gives the temperature reading from each device.
When I compile using VSCode and the Arduino extension, the code compiles and uploads successfully, the program reports 2 devices, just like the Arduino IDE compilation does, but then it prints -196.60 for the temperature reading, which is the "no device" value.

Same breadboard, same host computer - the only difference is the IDE. I'd much prefer to stick with VSCode, but if the resulting executable is wrong, then it's a non-starter.

Why the different results? More importantly, how do I get the VSCode to produce the same (correct) output as the Arduino IDE?

UPDATE:
Apparently the issue has something to do with the serial monitor. The project I'm actually trying to build has an OLED display for the temperature. The temperature is correct if the VSCode serial monitor is closed. Open the monitor and the incorrect values appears. Close the monitor and the correct values appear again.

UPDATE 2:
The problem remains over a range of serial port speeds, from 19200 to 115200. I didn't try outside that range.

UPDATE 3:
Code compiled using VSCode but run observing through the Arduino IDE serial monitor has the correct behavior - ie, shows the correct temperatures.

title: VSCode vs. Arduino IDE - same program, different behavior

Answers: 1

body: Further testing by OP isolated a bug in the Arduino Extension for VSCode which was logged as an issue at https://github.com/microsoft/vscode-arduino/issues/1467


body:
Here my sample code for an Arduino Leonardo-based custom board:

    #include <LiquidCrystal.h>

    const int rs = 3, en = 0, d4 = 4, d5 = 30, d6 = 12, d7 = 6;
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

    void setup()
    {
      pinMode(2, OUTPUT);
      digitalWrite(2, LOW);

      Serial.begin(115200);

      lcd.begin(16, 2);
      lcd.print("Hello world");
    }

    void loop()
    {
    }

And here my schematic:

[![schematic][1]][1]

The MCU is an ATmega32U4.
Running the code above the display is completely empty, I also tried to change the values of R4 and R5 but nothing changes. I don't see anything, not even the background of each character.

The display is a common HD44780 compatible one.

I retrieved the pin numbers from here:

> /opt/arduino-1.8.19/hardware/arduino/avr/variants/leonardo/pins_arduino.h

Am I missing anything?

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

title: LiquidCrystal issue with HD44780 display

Answers: 1

body:
The error is, that V0 has VDD level by the way you connected the resistors. The "lower end" of your ladder needs to be at GND, pin 1.

The pin 15 (A) is the anode of the backlight, and is not connected to the LCD driver circuit. BTW, to lit the backlight, you need to connect pin 16 (K), too. See the data sheet for details.

Use a potentiometer for V0, wiper to V0 and the ends to VDD and GND, respectively.

Just a side note: From the back of my memory, V0 can be commonly connected by a single resistor or directly to GND, since the wiper of the potentiometer was mostly at the GND end. It will give _some_ contrast, depending on the temperature.