body:
I have the following circuit:

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

(The Arduino is powered via the USB)

The problem is that I the reading from the fan's tachometer signal are incorrect,

I tried to add the two resistors as voltage dividers but still the readings are wrong.
When I check the voltage of the tachometer signal with a multimeter, in the time the multimeter is connected the readings are somewhat correct (not 100%).

Here is a snippet from the fan's documentation:
[![enter image description here][2]][2]

(BTW: When I used a different 12v pwm fan and didn't use a voltage divider the readings were incorrect only in the time I switched the 12v power off until the fan stopped spinning (after it stopped spinning the tachometer stopped sending signals so the rpm was 0 which was correct).)

Working code (correct tacho signal value):

    const byte tachpin = 2;

    unsigned int tacho = 0;
    long int startTime = 0;
    long int elapsed = 0;

    void setup() {
      Serial.begin(9600);
       // Configure Timer 1 for PWM @ 25 kHz.
        TCCR1A = 0;
        TCCR1B = 0;
        TCNT1  = 0;
        TCCR1A = _BV(COM1A1)
               | _BV(COM1B1)
               | _BV(WGM11);
        TCCR1B = _BV(WGM13)
               | _BV(CS10);
        ICR1   = 320;

        pinMode(tachpin, INPUT_PULLUP);
        attachInterrupt(digitalPinToInterrupt(tachpin), tachisr, RISING);
        startTime = millis();
    }

    void tachisr(){
      tacho++;
    }

    void loop() {
          elapsed = millis() - startTime;
          if(elapsed > 1000) {
            int tachcopy = 0;
            noInterrupts();
            tachcopy = tacho;
            tacho = 0;
            interrupts();
            rpm = (tachcopy / 2.0) * (60000 / elapsed);
            Serial.println(rpm,DEC);
          }
          startTime = millis();
    }

Correct reading from working code

>rpm = 0, tachcopy = 0\
rpm = 1150, tachcopy = 39\
rpm = 2360, tachcopy = 80\
rpm = 2655, tachcopy = 90\
rpm = 2773, tachcopy = 94\
rpm = 2655, tachcopy = 90\
rpm = 1268, tachcopy = 43

Not working code (incorrect tachometer signal):

    const byte tachpin = 2;

    unsigned int tacho = 0;
    long int startTime = 0;
    long int elapsed = 0;
    long int rpm = 0;
    unsigned int pwmValue = 0;
    unsigned int outValue = 0;
    unsigned int seconds_counter = 0;

    void setup() {
      Serial.begin(9600);
       // Configure Timer 1 for PWM @ 25 kHz.
        TCCR1A = 0;
        TCCR1B = 0;
        TCNT1  = 0;
        TCCR1A = _BV(COM1A1)
               | _BV(COM1B1)
               | _BV(WGM11);
        TCCR1B = _BV(WGM13)
               | _BV(CS10);
        ICR1   = 320;

        // Set the PWM pins as output.
        pinMode( 9, OUTPUT); //!!!ADDED LINE!!!

        pinMode(tachpin, INPUT_PULLUP);
        attachInterrupt(digitalPinToInterrupt(tachpin), tachisr, RISING);
        startTime = millis();
    }

    void tachisr(){
      tacho++;
    }

    //!! ADDED FUNCTION !!!
    void analogWrite25k(int value)
    {

        OCR1A = value;

    }

    void loop() {

          elapsed = millis() - startTime;
          if(elapsed > 1000) {
            int tachcopy = 0;
            noInterrupts();
            tachcopy = tacho;
            tacho = 0;
            interrupts();
            startTime = millis();
            rpm = (tachcopy / 2.0) * (60000 / elapsed);
            Serial.print("rpm = ");
            Serial.print(rpm,DEC);
            Serial.print(", tachcopy = ");
            Serial.println(tachcopy,DEC);

            seconds_counter++;
          }

          analogWrite25k(100); //!!!ADDED LINE!!!

    }

Not working code output:

>rpm = 737854, tachcopy = 25012\
rpm = 738591, tachcopy = 25037\
rpm = 737824, tachcopy = 25011\
rpm = 738591, tachcopy = 25037\
rpm = 738562, tachcopy = 25036\
rpm = 737854, tachcopy = 25012\
rpm = 738562, tachcopy = 25036\
rpm = 737854, tachcopy = 25012\
rpm = 738562, tachcopy = 25036\
rpm = 737824, tachcopy = 25011\
rpm = 738591, tachcopy = 25037\
rpm = 737854, tachcopy = 25012\
rpm = 738562, tachcopy = 25036\
rpm = 737854, tachcopy = 25012\
rpm = 738562, tachcopy = 25036\
rpm = 737854, tachcopy = 25012

Readings when using 10K ohm resistor as pull up (instead of the voltage divider (10K+4.7K))  and maxing out analogWrite25k - `analogWrite25k(320);`:

>  rpm = 6165\
  rpm = 6401\
  rpm = 6136\
  rpm = 6136\
  rpm = 6165\
  rpm = 6018\
  rpm = 6283\
  rpm = 5870\
  rpm = 6047\
  rpm = 6578\
  rpm = 6460\
  rpm = 6224\
  rpm = 5782\
  rpm = 6047\
  rpm = 6136\
  rpm = 6136\
  rpm = 6313\
  rpm = 5988\
  rpm = 6224\
  rpm = 6195\
  rpm = 6136\
  rpm = 5900

Which is interesting because the max speed of the fan is ~3000rpm (so rpm readings are about x2 max fan rpm when maxing out analogWrite25k)

**Update:**

Added debounce + 10K Ohm to Arduino 5V:

    #define DEBOUNCE 10
    //Interrupt handler. Stores the timestamps of the last 2 interrupts and handles debouncing
    unsigned long volatile ts1=0,ts2=0;
    //Calculates the RPM based on the timestamps of the last 2 interrupts. Can be called at any time.
    unsigned int calcRPM(){
        unsigned long ts1_copy, ts2_copy;
        noInterrupts();
        ts1_copy = ts1;
        ts2_copy = ts2;
        interrupts();

        Serial.print(ts1_copy);
        Serial.print(" / ");
        Serial.print(ts2_copy);
        Serial.print(" / ");
        Serial.println(ts2_copy - ts1_copy);
        return (60000000.0 / (ts2_copy - ts1_copy ) / 2.0);
    }

    void tachisr2() {
        unsigned long m=micros();
        if((m-ts2)>DEBOUNCE){
            ts1=ts2;
            ts2=m;
        }
    }

Output after adding debounce:

>    rpm = 2953.92\
    90923308 / 90923320 / 12\
    rpm = 2500000.00\
    91948328 / 91958496 / 10168\
    rpm = 2950.43\
    92994188 / 92994200 / 12\
    rpm = 2500000.00\
    94031032 / 94031040 / 8\
    rpm = 3750000.00\
    95047108 / 95057256 / 10148\
    rpm = 2956.25\
    96093308 / 96093320 / 12\
    rpm = 2500000.00\
    97119144 / 97129296 / 10152\
    rpm = 2955.08

When the value is ~2900 it is the correct value.

**Update 2**

Hope you can help me with another problem, The rpm value is scattering on a range of up to 120rpm+ even on low fan cycle of 800 rpm, of course when the elapsed time wait is bigger the scattering range is lower, the rpm reading might be not precise by about ~10%, I saw videos of [live speed reading from BIOS][3] of PC fan connected to PC motherboard and some of the fans are more precise (maybe because of BIOS code? (maybe there is a standard that specifies minimum time before reading the tacho counter?)), The question is are the tachometer sensors on 12V PC fans not supposed to be super precise by design or do I still have some problems with my circuit?, If I want a more precise rpm reading should I use an external tachometer sensor? which one is the best? optical/magnet based?
(btw my current circuit doesn't include the 4.7KOhm resistor from the schematic, only 10KOhm pull up to 5V)

  [1]: https://i.stack.imgur.com/wZ7WC.png
  [2]: https://i.stack.imgur.com/ejMKW.png
  [3]: https://www.youtube.com/watch?v=8dZ-ZqsTAjw&t=130s

title: Bad readings from 12V pwm fan tachometer signal

Answers: 1

body:
**1. Open Collector Output of a module.**

The power for the open collector output should come from the MCU, not (indirectly) from the sensor's power supply. It is very similar to wiring a push button switch on the low side.
Usually, the internal pullup resistor of the Arduino pin which is connected to the module passes enough power to detect the status of this output (as you have done). This internal pullup resistor has a value of around 30k. It is also possible to add a lower value external pull up resistor, if required say because of electrical noise, between the Arduino's 5v power rail and the pin. Ensure, however, that the current is within the tolerance of the connected device.

Measuring PWM voltages with a multimeter will not be successful, as you have discovered. These tend to integrate and show an average voltage. Say 12 volts at a 50% duty cycle will be read as 6 volts. Use an oscilloscope to see the voltage across the wave form.

**2. Electrical Interference.**

Your figure here `tachcopy = 25012` indicate that your 25KHz signal is leaking through and being detected as pulses from the sensor. Powering the open collector via the Nano's 5v power rail (as above) may eliminate this. Maybe also better decoupling on the 12 volt power supply (say adding a big capacitor).

**3. Code Issues**

Your code has an number of issues which should be cleaned up. Some may show up after only about 25 days. Some may show up after the next recompilation and some affect the accuracy of the results.

- `unsigned int tacho = 0;` should be volatile.
- `int tachcopy = 0;` should be unsigned int to match the data tape it is copying.
- Variables which are derived from millis() should be unsigned long (uint32_t) as here: `elapsed = millis() - startTime;`.
- This `(60000 / elapsed)` should be forced to a floating point division say `(60000.0 / elapsed)`
- This could be in setup() instead of loop(): `analogWrite25k(100);
   //!!!ADDED LINE!!!`

**4. "rpm readings is about x2 max fan rpm"**

I can't explain that. It may be that the sensor output needs to be debounced.

**5. Sample debounce routine (lockout principle)**
```
// Simple debounce routine. Based on original code.
// After accepting a pulse locks out further pulses for 3 ms
// Should be OK for 100Hz (period 10ms)

void tachisr(){
  // ISR (external interrupt)
  static uint32_t lastAcceptedPulseAtMs = 0 ; // static initialised once only
  uint32_t ms = millis() ;
  if ( ms - lastAcceptedPulseAtMs >= 3 ) {  // 3 ms - tune if required
    lastAcceptedPulseAtMs = ms ;
    tacho++;
  }
}
```
Note: An ISR should be quick to execute and should not contain Serial.print() etc.


body:
This question has been asked before and I have carefully read the other questions, but the solutions have not worked in my case, and the details are not the same as mine.

**Description**

The Arduino Uno is stuck at uploading with the error `avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00`, with the base sketch.

**Details**

- I am trying with the base empty sketch.
- Nothing is wired, nothing connected

**Important Remarks**
- A second Arduino UNO works perfectly fine with the same setup
- Loopback test worked - [Loopback test instructions][1]
- Cable and drivers work fine
- Correct port is selected
- Rebooting, resetting, upgrading the Arduino IDE have not solved the problem

**Important details**
- The TX LED is slightly but constantly on, and measuring the value of the TX Pin (Digital 1) outputs a value of 2.0 V. This also happens when feeding the Arduino with a 12 V supply, without USB. **EDIT** Got rid of this part by burning the bootloader via ISP with another Arduino - [Bootloader burn instructions][2]
- Checking the COM devices via powershell `mode` outputs something different between the two Arduinos: a locked value of `Baud: 115200` for the one not working, while for the one that works it displays `Baud: None`.

  [1]: https://support.arduino.cc/hc/en-us/articles/360020366520-How-to-do-a-loopback-test
  [2]: https://support.arduino.cc/hc/en-us/articles/4841602539164-Burn-the-bootloader-on-UNO-Mega-and-classic-Nano-using-another-Arduino

title: Arduino UNO stuck at 'uploading' with base sketch, nothing wired

Answers: 1

body:
> A second Arduino UNO works perfectly fine with the same setup

Sounds like your Uno is faulty. You could read my post here:

https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293

Also https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader/15937#15937

The Unos should be simply replaceable. That is, if your setup works on one, then unless you have done something weird to the other one (such as changing the fuses) then that should work too.

Is it a genuine one? Or a cheap knock-off? If it's cheap, well you got what you paid for. Get another.

I have [a post on my forum](http://www.gammon.com.au/forum/?id=11633) which lets you detect chip signatures and fuses (use your working Uno to run that). It may shed some light on what is happening.


body: I have an Arduino UNO with SIM808 and I'm trying to send my GPS data to the Firebase. I have successfully get a location from SIM808 via serial. However I found that Arduino only supported HTTP communication while the Firebase accepted only HTTPS requests. How can I connect them (Arduino and Firebase) so I can send data to Firebase. Any guide and help can help me a lot thank you so much :)

title: How to Send GPS Data to Firebase via SIM808 GSM Module

Answers: 0


body:
I have an Arduino Pro Micro only sending data via com port, connected to a PC.
I don't use the USB protocol and I think the Arduino send request with USB and it's the reason why my computer wakes up

I checked the device manager and there is no power management tab for the arduino, so I can't refuse the Arduino to wake the system up.
Also my BIOS don't have any option to wake up on a particular key combination

title: how to avoid an Arduino pro micro waking up a pc

Answers: 2

body:
Assuming the computer is turning on due to the data received over the USB cable from the DEEJ box and not from simply plugging in the USB cable from the DEEJ box.

Consider, if this project otherwise works, re-writing the Arduino Sketch to not send out any data until after a specific digital GPIO pin goes from 1 to 0. Place a N.O. push button switch to ground on that digital GPIO pin. Remember to program that pin as a GPIO input with a pull up. If this works, not only will the DEEJ box control volumes, but might also be able to turn on the computer.

body:
I just figured out window wakes up when the deej program is running with the Arduino connected,but when the Arduino is connected without the program running there is no problem.
So trouble is deej


body:
I bought a couple of ESP32CAMs from aliexpress... althought [the listing][1] shows them with two buttons, I got the ESP32-CAM-MB boards with just the reset button...

I have my computer set up to dual boot Windows and Linux so when I got an error in windows, I rebooted and installed the ESP32 boards for Arduino 2.1 and went ahead. I had to also install esptool and pyserial for it to work, but it ended up recognizing the port and every time I try to program it the flash flashes, but the programmer responds with

>     A fatal error occurred: Failed to connect to ESP32: Wrong boot mode detected (0xb)! The chip needs to be in download mode.

When I enable the serial console and press the reset button I get the following:

```
ets Jul 29 2019 12:21:46

rst:0x1 (POWERON_RESET),boot:0x1b (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:4
load:0x3fff0034,len:6968
load:0x40078000,len:13072
ho 0 tail 12 room 4
load:0x40080400,len:3896
entry 0x40080688
[0;32mI (31) boot: ESP-IDF v4.1-dirty 2nd stage bootloader[0m
[0;32mI (31) boot: compile time 16:15:01[0m
[0;32mI (31) boot: chip revision: 3[0m
[0;32mI (34) boot_comm: chip revision: 3, min. bootloader chip revision: 0[0m
[0;32mI (41) boot.esp32: SPI Speed      : 40MHz[0m
[0;32mI (46) boot.esp32: SPI Mode       : DIO[0m
[0;32mI (51) boot.esp32: SPI Flash Size : 4MB[0m
[0;32mI (55) boot: Enabling RNG early entropy source...[0m
[0;32mI (60) boot: Partition Table:[0m
[0;32mI (64) boot: ## Label            Usage          Type ST Offset   Length[0m
[0;32mI (71) boot:  0 nvs              WiFi data        01 02 00009000 00005000[0m
[0;32mI (79) boot:  1 otadata          OTA data         01 00 0000e000 00002000[0m
[0;32mI (86) boot:  2 app0             OTA app          00 10 00010000 00300000[0m
[0;32mI (94) boot:  3 spiffs           Unknown data     01 82 00310000 000f0000[0m
[0;32mI (101) boot: End of partition table[0m
[0;32mI (106) boot_comm: chip revision: 3, min. application chip revision: 0[0m
[0;32mI (113) esp_image: segment 0: paddr=0x00010020 vaddr=0x3f400020 size=0x1d2048 (1908808) map[0m
[0;32mI (849) esp_image: segment 1: paddr=0x001e2070 vaddr=0x3ffbdb60 size=0x04d3c ( 19772) load[0m
[0;32mI (857) esp_image: segment 2: paddr=0x001e6db4 vaddr=0x40080000 size=0x00400 (  1024) load[0m
[0;32mI (858) esp_image: segment 3: paddr=0x001e71bc vaddr=0x40080400 size=0x08e54 ( 36436) load[0m
[0;32mI (880) esp_image: segment 4: paddr=0x001f0018 vaddr=0x400d0018 size=0x9df74 (647028) map[0m
[0;32mI (1127) esp_image: segment 5: paddr=0x0028df94 vaddr=0x40089254 size=0x0b6a0 ( 46752) load[0m
[0;32mI (1159) boot: Loaded app from partition at offset 0x10000[0m
[0;32mI (1159) boot: Disabling RNG early entropy source...[0m
�
SD Size: 29557MB  OK
```

I can see that the board is in `SPI_FAST_FLASH_BOOT` mode which according to the [linked documentation][2] is wrong... but how to I get it to reboot in the correct mode?

[Others have had similar issues][3], but they use another tool stack, so I am not sure what their solution would translate to in the Arduino 2.1 IDE...

[![stacked][4]][4]
[![bottoms][5]][5]
[![tops][6]][6]

  [1]: https://www.aliexpress.com/item/1005002808966055.html
  [2]: https://docs.espressif.com/projects/esptool/en/latest/esp32/advanced-topics/boot-mode-selection.html#manual-bootloader
  [3]: https://www.reddit.com/r/esp32/comments/qjflp4/bought_a_shady_esp32cammb_that_doesnt_have_a_gp0/
  [4]: https://i.stack.imgur.com/cahAL.jpg
  [5]: https://i.stack.imgur.com/5ENAx.jpg
  [6]: https://i.stack.imgur.com/5Di1x.jpg

title: unable to program esp32cam via cloned esp32-cam-mb

Answers: 1

body:
While making sure I included all the correct links and pictures in the question, I found the answer - if an SD card is inserted, the flashing cannot be performed.

Removing the SD card and resetting the ESP32 works. I now have a very bright flashing LED


body:
I have constantly been getting this error while trying to upload a sketch on Wemos D1 Mini R1 & R2 type board.

> A fatal esptool.py error occurred: Write timeout

I've recently updated my Arduino IDE, so I assumed that it might be due to a bad installation. But after reinstalling everything including the Board Manager lib for ESP, Arduino IDE itself nothing worked. When I click on the Board Info, it displays an error "Native serial port, can't obtain info".

I've also tried different type of ESP boards (e.g. NodeMCU) but for all boards the problem is same. When I plug an Arduino to the same USB Port, it auto-detect the board, but when I plug-in the ESP boards, it doesn't recognize the boards automatically. So my guess is it has something to do with the CH34X driver. However I have tried reinstalling few versions of the driver from authentic sources, but nothing made an impact.

Any help is appreciated.

Following is the full trace of log getting printed:

    . Variables and constants in RAM (global, static), used 28104 / 80192 bytes (35%)
    ║   SEGMENT  BYTES    DESCRIPTION
    ╠══ DATA     1496     initialized variables
    ╠══ RODATA   920      constants
    ╚══ BSS      25688    zeroed variables
    . Instruction RAM (IRAM_ATTR, ICACHE_RAM_ATTR), used 59667 / 65536 bytes (91%)
    ║   SEGMENT  BYTES    DESCRIPTION
    ╠══ ICACHE   32768    reserved space for flash instruction cache
    ╚══ IRAM     26899    code in IRAM
    . Code in flash (default, ICACHE_FLASH_ATTR), used 232148 / 1048576 bytes (22%)
    ║   SEGMENT  BYTES    DESCRIPTION
    ╚══ IROM     232148   code in flash
    esptool.py v3.0
    Serial port COM8
    Connecting...

    A fatal esptool.py error occurred: Write timeout

Following is the IDE Settings while uploading:

[![Arduino-IDE-upload-settings-for-D1-Mini-(ESP8266)][1]][1]

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

title: Error while uploading "A fatal esptool.py error occurred: Write timeout"

Answers: 3

body:
I've run into this a bunch recently, and typically, but not always, the cause is that I was using a GPIO pin that was reserved and couldn't be used during boot up. It's surprising how many of the pins cannot be used.

Check out this chart I found and saved, unfortunately I do not know the source, but I have found it to be very accurate, and I reference it a lot:

[![take a look at this graph I found][1]][1]

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

body:
I had the same problem.

My solution:

Program for blinking led ESP8266MOD (cheap Chinese esp8266mod module)

I used Arduino IDE 2.1.0

info from https://vimalb.github.io/IoT-ESP8266-Starter/Lesson_01/lesson.html

Connect resistor 220 Ohm and LED in serial. Connect resistor on D8 and the LED

on G (Ground). I used a breadboard and connect 5V pin on the esp board and

the pin G on the esp board to the Red en Bleu line on mij breadbord.

Write the program.

    // Base ESP8266

    #include <ESP8266WiFi.h>

    WiFiClient WIFI_CLIENT;

    #define LIGHT_SENSOR A0

    #define LED 15    // this is pin D8 on the board

    #define BUTTON 4

    void setup() {

      // Initialize the serial port

      Serial.begin(115200);

      // Configure light sensor pin as an input

      pinMode(LIGHT_SENSOR, INPUT);

      // Configure LED pin as an output

      pinMode(LED, OUTPUT);

      // Configure BUTTON pin as an input with a pullup

      pinMode(BUTTON, INPUT_PULLUP);

    }

    void loop() {

      // Turn the LED on (HIGH is the voltage level)

      digitalWrite(LED, HIGH);

      // Wait for 1000 milliseconds

      delay(1000);

      // Turn the LED off by making the voltage LOW

      digitalWrite(LED, LOW);

      // Wait another 1000 milliseconds

      delay(1000);

      // Send a message over the serial port

      Serial.println("Finished loop");

    }

Compile the program.

If Fault check the program.

Go to Tools -> Port  (I used com6)

Push the reset button on the espboard and keep it.

Connect the usb-cable on the espboard.

Release the reset button.

Besure everthing is connect.

Upload the program by using the upload button arduino IDE.

Start the serial monitor and check text "Finished loop" every 2 seconds.

Maybe this will help

body:
The "most common reason" mentioned in [this answer][1] was actually the problem I had. Unfortunately I was using a charge only cable even though the cable package clearly said it was a data-cable. At times, these cheap electronics products confuses us a lot and we often miss to critically scrutinize the most obvious problems. As described in [this Adafruit tutorial][2] this problem seems to be a very common one.

  [1]: https://raspberrypi.stackexchange.com/a/140835
  [2]: https://learn.adafruit.com/getting-started-with-raspberry-pi-pico-circuitpython/circuitpython


body:
pretty new to arduino stuff and was hoping to get some help with my code.

I'm trying to use 2 ToF sensors and get continuous readings from them. I understand that I have to use the xshut feature and switch them on and off to alternate them but I'm stuck in an error loop and I'm not quite sure where to go from here. Does anyone know what's going on and how to solve this?

Here's my code:

    /* Includes ------------------------------------------------------------------*/
    #include <Arduino.h>
    #include <Wire.h>
    #include <vl53l4cd_class.h>
    #include <string.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <stdint.h>
    #include <assert.h>
    #include <stdlib.h>
    #include <SPI.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_ST7789.h>
    #include <WiFi.h>
    //#include <ESPAsyncWebServer.h>
    #define DEV_I2C Wire
    #define SerialPort Serial
    char report[64];
    //address we will assign if dual sensor is present
    uint8_t sensor1add = 0x30;
    uint8_t sensor2add = 0x31;
    // set the pins to shutdown
    #define xshut1 A0
    #define xshut2 A1
    #define GFX_BL DF_GFX_BL
    //this holds the measurement
    VL53L4CD_Result_t results1;
    VL53L4CD_Result_t results2;
    float sensor1, sensor2;
    //Components.
    VL53L4CD sensor1_vl53l4cd_sat(&DEV_I2C, A0);
    VL53L4CD sensor2_vl53l4cd_sat(&DEV_I2C, A1);
    //init Wifi
    /*void initWifi(){
        Serial.print("Setting AP (Access Point)...");
      // No password
      WiFi.softAP (ssid);
      // Start WiFi Access Point
      IPAddress IP = WiFi.softAPIP();
      Serial.print("AP IP address: ");
      Serial.print(IP);
        // Print ESP8266 Local IP Adress
      Serial.println(WiFi.localIP());
    }*/
    //init sensors
    void initSensor(VL53L4CD sensorX, uint8_t sensoradd)
    {
      // Init sensor1
      //Set sensor address.
      sensorX.VL53L4CD_SetI2CAddress(sensoradd);
      // Configure VL53L4CD satellite component.
      sensorX.begin();
      // Switch off VL53L4CD satellite component.
      sensorX.VL53L4CD_Off();
      //Initialize VL53L4CD satellite component.
      sensorX.InitSensor();
      // Program the highest possible TimingBudget, without enabling the
      // low power mode. This should give the best accuracy
      sensorX.VL53L4CD_SetRangeTiming(200, 0);
      sensorX.VL53L4CD_SetOffset(-10);
      // Start Measurements
      sensorX.VL53L4CD_StartRanging();
    }
    //getSensor1Reading
    void getSensor1Reading(uint8_t status, uint8_t NewDataReady)
    {
      sensor1_vl53l4cd_sat.VL53L4CD_On();
      Serial.println("Sensor 1 is on");
      if ((!status) && (NewDataReady != 0)) {
        // (Mandatory) Clear HW interrupt to restart measurements
        sensor1_vl53l4cd_sat.VL53L4CD_ClearInterrupt();
        // Read measured distance. RangeStatus = 0 means valid data
        sensor1_vl53l4cd_sat.VL53L4CD_GetResult(&results1);
        snprintf(report, sizeof(report), "Status = %3u, Distance = %5u mm, Signal = %6u kcps/spad\r\n",
                 results1.range_status,
                 results1.distance_mm,
                 results1.signal_per_spad_kcps);
        sensor1 = results1.distance_mm;
        Serial.println((String)"This is Sensor1 " + (float)sensor1 + (String)"mm");
      }
      sensor1_vl53l4cd_sat.VL53L4CD_Off();
    }
    //getSensor2Reading
    void getSensor2Reading(uint8_t status, uint8_t NewDataReady)
    {
      sensor2_vl53l4cd_sat.VL53L4CD_On();
      Serial.println("Sensor 2 is on");
      if ((!status) && (NewDataReady != 0)) {
        // (Mandatory) Clear HW interrupt to restart measurements
        sensor2_vl53l4cd_sat.VL53L4CD_ClearInterrupt();
        // Read measured distance. RangeStatus = 0 means valid data
        sensor2_vl53l4cd_sat.VL53L4CD_GetResult(&results2);
        snprintf(report, sizeof(report), "Status = %3u, Distance = %5u mm, Signal = %6u kcps/spad\r\n",
                 results2.range_status,
                 results2.distance_mm,
                 results2.signal_per_spad_kcps);
        sensor2 = results2.distance_mm;
        Serial.println((String)"This is Sensor2 " + (float)sensor2 + (String)"mm");
      }
      sensor2_vl53l4cd_sat.VL53L4CD_Off();
    }
    /*void offset()
    {
    }*/
    /* Setup ---------------------------------------------------------------------*/
    void setup()
    {
      // Initialize serial for output.
      SerialPort.begin(115200);
      SerialPort.println("Starting...");
      // Initialize I2C bus.
      DEV_I2C.begin();

      initSensor(sensor1_vl53l4cd_sat, sensor1add);
      initSensor(sensor2_vl53l4cd_sat, sensor2add);
    }
    void loop()
    {
      uint8_t NewDataReady1 = 0;
      uint8_t NewDataReady2 = 0;
      uint8_t status1;
      uint8_t status2;
      do {
        status1 = sensor1_vl53l4cd_sat.VL53L4CD_CheckForDataReady(&NewDataReady1);
        status2 = sensor2_vl53l4cd_sat.VL53L4CD_CheckForDataReady(&NewDataReady2);
      } while (!NewDataReady1 || !NewDataReady2);
      getSensor1Reading(status1, NewDataReady1);
      getSensor2Reading(status2, NewDataReady2);
      if (!sensor1_vl53l4cd_sat.VL53L4CD_CheckForDataReady(&NewDataReady1))
      {
        Serial.println((String)"NewDataReady1 is not ready");
      }
      else if (!sensor2_vl53l4cd_sat.VL53L4CD_CheckForDataReady(&NewDataReady2))
      {
        Serial.println((String)"NewDataReady2 is not ready");
      }
      else{Serial.println("New data unable to be parsed");}
    }

But I keep getting this error:

    --- forcing DTR inactive
    --- forcing RTS inactive
    --- Terminal on COM9 | 115200 8-N-1
    --- Available filters and text transformations: colorize, debug, default, direct, esp32_exception_decoder, hexlify, log2file, nocontrol, printable, send_on_enter, time
    --- More details at https://bit.ly/pio-monitor-filters
    --- Quit: Ctrl+C | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H
    This is Sensor1 0.00mm
    This is Sensor2 30.00mm
    [  2883][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
    [  3884][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error 263
    [  3884][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
    [  3886][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
    [  3893][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
    [  3900][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
    [  3907][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
    [  3914][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1
    [  3921][E][Wire.cpp:499] requestFrom(): i2cWriteReadNonStop returned Error -1

title: Using 2 VL53L4CD ToF sensors and getting error after getting first reading

Answers: 0


body:
I saw [this video][1] from James Bruton. See the links to the GitHub repos in the video description.

I bought [a few AS5048B boards from AMS][2], so I can measure the position of my stepper motors.

In the `sosandroid` repo, I ran `program_address` and was able to get one of them working, but they all have the same I2C address, and because I want to have 6 of them running simultaneously, it of course won't work. I know I could get an I2C multiplexer...

I also tried setting the A1 and A2 pins on the AS5048B to high and low, which change the I2C address (for a total of 4)... But I want to change the I2C address permanently for each board.

It looks to me like `program_address` is supposed to permanently program the I2C address, which the user can specify in the .ino file:

    // Construct our AS5048B object with an I2C address of 0x40
    AMS_AS5048B mysensor(0x40);

But no matter what I set it to (e.g. `0x40, 0x41, 0x42, 0x43, 0x44`), [the Arduino I2C scanner][3] always finds `0x44`, which is the default address, so the `program_address` must not be working.

EDIT: the default address is actually `0x40`. I must have programmed it to `0x44` without knowing (I was playing around with this board trying to figure this all out).

I know that normally the I2C addresses cannot be changed, but it looks like [this one][4] can:

Here's a snippet from the link above. It says the OTP bits can be programmed/burned (only once!). My understanding is that the I2C address is saved in the OTP bits.

> Program the OTP bits permanently:
> 1. Write dec.253 into the OTP control register (dec.3) to enable the special programming mode
> 2. Set the Burn bit (dec.8) in the OTP control register (dec.3) to enable automatic programming procedure
> 3. Write dec.0 into the OTP control register (dec.3) to disable the special programming mode

I am using the Teensy 4.1 using PlatformIO in VS Code, and I also tried using an Arduino Uno in the Arduino IDE.

My wiring is as follows:

[![wiring][5]][5]

**So how do I program the I2C address on the AS5048B boards?**

EDIT:
-----
- I changed an image to text, and cleaned things up.

As @6v6gt requested, I used the I2C scanner and it is still showing 0x40 (on this particular board), so it must not have been programmed (unless it's possible to program it to 0x40 even though 0x40 is its default value). The only thing I changed from the `program_address` repo is this line in the .ino file:

    // Construct our AS5048B object with an I2C address of 0x40
    AMS_AS5048B mysensor(0x48);

I changed the 0x40 to 0x48. But now I am getting this in the serial monitor:

    Angle degree : I2C error: 2
    359.9780273437

Since I must have programmed the other board to 0x44 successfully, I am trying to think of what I did differently, but I don't remember.

There are hundreds of lines of code in `program_address` (and the .h and .cpp file), so I probably shouldn't post all of it here. But here's [the GitHub repo][6].

  [1]: https://www.youtube.com/watch?v=KN4wAZHtbzc
  [2]: https://www.mouser.ca/ProductDetail/985-AS5048B-TS_EK_AB
  [3]: https://playground.arduino.cc/Main/I2cScanner/
  [4]: https://ams.com/documents/20143/36005/AS5048_AN000386_1-00.pdf/3fc346bf-2379-6a45-9adb-1fe5407b8889
  [5]: https://i.stack.imgur.com/jUHkC.png
  [6]: https://github.com/sosandroid/AMS_AS5048B/tree/master/examples/program_address

title: How to change the I2C address of the AS5048B?

Answers: 2

body:
> but they all have the same I2C address

No, they have 4 possible addresses, based on how you configure A1 and A2. So you can have 4 different addresses immediately.

> But I want to change the I2C address permanently for each board.

For each board, set up A1 and A2 differently.

This only gives you 4 different addresses, not 6. You could conceivably connect 8 devices to two different Atmega328 chips, and have them do the readings and forward the results using a protocol you devise, to your "main" board. The Atmega328 chips only cost around $US 5 each so this isn't a big deal.

Another approach would be to run SDA and SCL through a multiplexer chip, so that you enable one batch of 4 chips and then the other batch. Without trying it out, it is hard to say if this would work satisfactorily.

body:
The device slave I2C address consists of the hardware setting on pins A1, A2 **and upper MSBs programmable by the user.** It is the setting of the MSBs, in addition to A1/A2 that I believe the OP is after.

The information provided by @Nick Gammon concerning A1 and A2 is correct, but does not consider the other 5 bits (the MSBs). It appears that you can, indeed, permanently set a new I2C slave address on the device.

You need to read the [programming application note][1] very carefully, but they explain how to burn those bits into the register....it seems straightforward and is really just four steps, but I suppose it can be a little daunting, e.g.,
"***slave address consist of 5 programable bits (MSBs) and the hardware setting of Pins A1 and A2 I²C address <4> is by default not programmed and due
to the inversion defined as '1'***"

The application note gives an example of the 4 steps....
[![enter image description here][2]][2]

It may be the case that you already changed the I2C address default to 0x44 by following the instructions. [edited to add] Can you post the complete program [Arduino IDE code] that you used to *try* to change the I2C address?

  [1]: https://ams.com/documents/20143/36005/AS5048_AN000386_1-00.pdf/3fc346bf-2379-6a45-9adb-1fe5407b8889
  [2]: https://i.stack.imgur.com/Bv7Mb.jpg


body:
I am using an Arduino Uno with a SIM900A module. I want to send a simple SMS but it is not working, as it either has no response in Serial monitor or there are reversed question marks. I have attached a picture of my setup.

[![Current setup, but I have tried with different connections, different wires, different PC and different power supply. Nothing works!][1]][1]

My module didn't work on day, then worked for a day and then now has stopped working, but it is not a hardware issue, as the board switches on and when I try to call the connected SIM, a ring is heard, meaning it has been connected.

I am using a 12V 2A power supply for the board, but I have previously tried with a 12V 1.5A power supply as well, and at the beginning even tried with the Arduino 5V pin. So I do not believe it is a power supply issue either.

Next, I checked the wiring. I confirmed the wires were working by testing them on another sensor, and then used them for this module. I also checked the connections. I have connected the GND pin of the SIM900A to the GND of the Arduino, connected the RX to D9 and then connected the TX to D10. This worked at first, but now shows no response in Serial monitor, so then I tried to reverse the pins (RX to D10 and TX to D9) while keeping the code the same, which produced reversed question marks. But then, upon trying again, this also produced no response.

One of the common online answers was a mismatch in baud rates, so I tried changing the GSM's baud rate from 9600 to everything up to 115200. When the reversed question marks were produced, changing the baud rate just produced weirder characters, and now, as there is no response at all, changing the baud rate has no impact.

I have also tried using pins 2 & 3 and 7 & 8 instead of 9 & 10, but there is no difference.

The code I am currently using is as follows, and is copied directly from [here][2], but I have tried multiple other codes from different solutions to no avail:

```#include <SoftwareSerial.h>

SoftwareSerial mySerial(9, 10);

void setup()
{
  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  delay(100);
}

void loop()
{
  if (Serial.available()>0)
   switch(Serial.read())
  {
    case 's':
      mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
     delay(1000);  // Delay of 1 second
     mySerial.println("AT+CMGS=\"+91xxxxxxxxxx\"\r"); // Replace x with mobile number
     delay(1000);
     mySerial.println("Technolab creation");// The SMS text you want to send
     delay(100);
     mySerial.println((char)26);// ASCII code of CTRL+Z for saying the end of sms to  the module
      delay(1000);
      break;

    case 'r':
      mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to receive a live SMS
      delay(1000);
      break;
  }

 if (mySerial.available()>0)
   Serial.write(mySerial.read());
}
```

Please help me out, I've tried everything I can think of.

  [1]: https://i.stack.imgur.com/gXcHL.jpg
  [2]: https://www.technolabcreation.com/sim900a-gsm-module-and-arduino-sending-and-receiving-sms-using-at-commands/

title: Arduino Uno not interfacing with GSM SIM900A Module

Answers: 0


body:
I am relatively new to arduino and coding in general and im just looking for a code to write a single string of binary code e.g.; "01000111101"
To a specified output pin instead of copying and pasting

"Digital write (high)
Digital write (low)
Etc."

preferably with the option to change speed between bits.
Would be very appreciative for someone to help me out

title: How to write single binary code to output pin

Answers: 1

body:
If timing is not critical, consider dividing the number of interest by 2. If there was a remainder set the Arduino pin to 1. If not set it to 0. Then delay for as long as needed. Keep doing this until there is nothing left to divide 2 into.

However, sending out data in serial fashion is as old as computers. Likely older. Consequently there are a lot of built in features which do this.  Specifically, it is not necessary to explicitly code up a function to convert a value to serial data. Even on an Arduino.


body:
I am trying to connect my IPhone to an HC-08 Bluetooth module on an Arduino. The HC-08 is showing up in the new device section of android devices but it does not show up on an IPhone's Bluetooth device adding page. Also although it shows up on Android it will not successfully pair. I have an IPhone 13 which uses Bluetooth v5 and the HC-08 uses Bluetooth v4. I think Bluetooth v5 should be backwards compatible so that should not be the issue.

Here are my questions:

 1. Could the problem be that I need to write some Arduino initialization code? Currently I am not writing any code and just trying to connect to the device to my phone.
 2. Is it common that these modules will stop working over time? I have had this for several years and never used it.
 3. Is there another common reason that this will not show up in the Bluetooth menu of an IPhone such as a security setting?

title: HC-08 Compatibility issues with iPhone

Answers: 0


body:
I'm new to bit register manipulation and am trying to set input and output values of some pins. The code sample I have on hand does it this way::

    DDRD |= (1 << 2);
    DDRD |= (1 << 4);
    DDRD &= ~(1 << 5);
    PORTD |= (1 << 2);
    PORTD &= ~(1 << 4);
    PORTD &= ~(1 << 5);

I have two questions:
1. This is part of a code where I'm attempting to determine the time for a capacitor's discharge between pins 2 and 4. The arduino helpfiles mention that there may be a benefit to triggering both pins at once. Therefore: Is it is it possible to do `DDRD |= B00010100;` and `PORTD |= B00000100;` or combine the first three `DDRD`  lines so it happens simultaneously, or does it have to be separately called?

2. Why is it `PORTD &= ~(1 << 4)` and not `PORTD |= ~(1 << 4);`Can this conflict with the previous state of PORTD.

title: Good practice to assign shift-register pins at the same time?

Answers: 1

body:
>     DDRD |= (1 << 2);
>     DDRD |= (1 << 4);

The equivalent to that is:

    DDRD |= (1 << 2) | (1 << 4);

However I prefer `bit` because it does the shift for you:

    DDRD |= bit(2) | bit(4);

---

> Why is it `PORTD &= ~(1 << 4)` and not `PORTD |= ~(1 << 4);`

`PORTD &= ~(1 << 4)` is turning a bit **off**. First you invert the sense of the bit with the **ones complement operator** (~) and then by **anding** it, it means that all bits are retained except that one. So this is basically turning bit 4 off. If you used `|=` it would turn all of the other bits **on**.

Equivalent code:

    PORTD &= ~bit(4);

Based on your example you meant bit 5 not bit 4.

---

>     PORTD |= (1 << 2);
>     PORTD &= ~(1 << 4);
>     PORTD &= ~(1 << 5);

That is turning on bit 2, and turning off bits 4 and 5, and leaving the rest unchanged.

---

> Thanks. In that case would DDRD &= B00000000; DDRD |= B00010100; have a similar result ...

If you do `DDRD &= B00000000;` then you are setting all bits to zero. So the simple equivalent to the above would be:

    DDRD = B00010100;

This is a straight assignment, so you don't need to clear any bits.

Or, you could write:

    DDRD = bit(2) | bit(4);

---

> Do you know if bit() faster or is it cleaner compared to 1 << x; or is it better for me to hook up a scope to test this myself?

It is **exactly the same**. `bit` is just a `#define`  in the Arduino.h file, as follows:

    #define bit(b) (1UL << (b))

So all it does is save you writing the brackets and the shift left operator. It expands out to the same as what you were writing and thus will execute at the same speed, and take the same amount of memory.


body:
I am working on an autonomous robot using two 4-pin stepper motors, HC-SR04 ultrasonic sensor, 2 L298N motor drivers (one for each motor), and an Arduino Uno. My problem is that when I use the stepper motors with the Stepper library, only one motor works at a time. My solution was to control the one step at a time in a short period of time, which worked, however, this introduces a new problem. The ultrasonic sensor requires a delay to work, but this makes the movement of the robot quite slow and jittery as it works only by one step at a time. When I remove the delay from the ultrasonic sensor, it starts returning the correct value, but then also returning 0 right after each correct value. My solution was to ignore the returned 0, but this is not ideal.

How can I use two stepper motors at the same time and use an Ultrasonic sensor?

Here is my code:

    #include <Stepper.h>
    #include <Ultrasonic.h>

    /*
     * Pass as a parameter the trigger and echo pin, respectively,
     * or only the signal pin (for sensors 3 pins), like:
     * Ultrasonic ultrasonic(13);
     */
     Ultrasonic ultrasonic(13, 12);
     int distance;

     int driveSpeed = 100;
     int stepsPerRevolution = 200;
     int leftMotorStep = 0;
     int rightMotorStep = 0;

     // Time interval between steps for both motors
     const int stepInterval = 10;  // Adjust as needed

     // Last step time for each motor
     unsigned long leftMotorLastStepTime = 0;
     unsigned long rightMotorLastStepTime = 0;

     Stepper rightMotor(stepsPerRevolution, 8, 9, 10, 11);
     Stepper leftMotor(stepsPerRevolution, 4, 5, 6, 7);

     void setup() {
       Serial.begin(9600);
       rightMotor.setSpeed(driveSpeed);
       leftMotor.setSpeed(driveSpeed);
     }
     void loop() {
       distance = ultrasonic.read();

       Serial.print("Distance in CM: ");
       Serial.println(distance);
       delay(250); //This delay makes the motors behave strangely

       if (distance < 15) {
         Serial.println("AVOIDING OBSTACLE!");
         // Perform obstacle avoidance behavior
         avoidObstacle();
       } else if (distance < 30) {
         Serial.println("APPROACHING OBSTACLE!");
         // Perform slow approach behavior
         slowApproach();
       } else {
         Serial.println("DRIVING!");
         // Perform normal driving behavior
         drive();
       }
     }

     void avoidObstacle() {
       // Stop the robot
       halt();

       // Rotate the robot to avoid the obstacle
       leftM();

       // Delay to allow the rotation to complete
       delay(1000);
     }

     void slowApproach() {
       // Slow down the motors
       int slowSpeed = 50;
       rightMotor.setSpeed(slowSpeed);
       leftMotor.setSpeed(slowSpeed);

       // Move the robot forward slowly
       forwardM();

       // Delay to allow the slow approach
       delay(1000);
     }

     void drive() {
       // Set the motors back to the normal speed
       rightMotor.setSpeed(driveSpeed);
       leftMotor.setSpeed(driveSpeed);

       // Move the robot forward
       forwardM();
     }

     void forwardM() {
       rightMotor.step(1);
       leftMotor.step(1);
     }
     void leftM() {
       rightMotor.step(1);
       leftMotor.step(-1);
     }
     void rightM() {
       rightMotor.step(-1);
       leftMotor.step(1);
     }
     void reverseM() {
       rightMotor.step(-1);
       leftMotor.step(-1);
     }
     void halt() {
       rightMotor.step(0);
       leftMotor.step(0);
     }

title: How to drive two Stepper motors and use an Ultrasonic sensor together?

Answers: 1

body:
Try this code.

Here is a simulation. https://wokwi.com/projects/366108641014000641

Click on the sensor to set the distance in the simulation

NOTE: centimeters is `cm`, not `CM`.

Not tested on hardware.

```lang-cpp

// https://arduino.stackexchange.com/questions/93302/how-to-drive-two-stepper-motors-and-use-an-ultrasonic-sensor-together

#include <Stepper.h>
#include <Ultrasonic.h>

/*
 * Pass as a parameter the trigger and echo pin, respectively,
 * or only the signal pin (for sensors 3 pins), like:
 * Ultrasonic ultrasonic(13);
 */

 Ultrasonic ultrasonic(13, 12);

 int distance;

 int slowSpeed          =  100;
 int driveSpeed         = 1000;
 int stepsPerRevolution =  100;
 int leftMotorStep      =    0;                         // current step speed and direction
 int rightMotorStep     =    0;

 int stepSpeed          =   10;                         // this is the motor speed

 const int stepInterval =    1;                         // Time interval between steps for both motors

 unsigned long leftMotorLastStepTime  = 0;              // Last step time for each motor
 unsigned long rightMotorLastStepTime = 0;

 Stepper rightMotor(stepsPerRevolution, 8, 9, 10, 11);
 Stepper leftMotor (stepsPerRevolution, 4, 5,  6,  7);

 void setup() {
   Serial.begin(9600);
   rightMotor.setSpeed(1);
   leftMotor. setSpeed(1);
 }

 void loop() {

  distance = ultrasonic.read();

  Serial.print("Distance in cm: ");
  Serial.print(distance);  Serial.print("\t");

  switch (distance) {                              // used switch/case for cleaner looking code
    case 0 ... 14:
      Serial.println("avoid");
      avoidObstacle();                             // Perform obstacle avoidance behavior
      break;

    case 15 ... 29:
      Serial.println("approach");
      slowApproach();                              // Perform slow approach behavior
      break;

    default:
      Serial.println("drive");
      drive();                                     // Perform normal driving behavior
      break;
  }

  rightMotor.step(rightMotorStep);                 // this actually moves the motors
  leftMotor .step(leftMotorStep);
}

 void avoidObstacle() {
   halt();                                          // Stop the robot
   leftM();                                         // Rotate the robot to avoid the obstacle
 }

 void slowApproach() {
   rightMotor.setSpeed(slowSpeed);                  // Slow down the motors
   leftMotor. setSpeed(slowSpeed);
   forwardM();                                      // Move the robot forward slowly
 }

 void drive() {
   rightMotor.setSpeed(driveSpeed);                 // Set the motors back to the normal speed
   leftMotor. setSpeed(driveSpeed);
   forwardM();                                      // Move the robot forward
 }

 void forwardM() {
   rightMotorStep =  stepSpeed;                     // select direction of step only
   leftMotorStep  =  stepSpeed;                     // do not move motor
 }                                                  // actual stepping is done at end of loop()
 void leftM() {
   rightMotorStep =  stepSpeed;
   leftMotorStep  = -stepSpeed;
 }
 void rightM() {
   rightMotorStep = -stepSpeed;
   leftMotorStep  =  stepSpeed;
 }
 void reverseM() {
   rightMotorStep = -stepSpeed;
   leftMotorStep  = -stepSpeed;
 }
 void halt() {
   rightMotorStep =  0;
   leftMotorStep  =  0;
 }

```


body: When the XIAO ESP32C3 is charging a LiPo battery, there is a small LED on the board that lights up. Is there any way to access this information in an Arduino program?

title: Determine if a XIAO ESP32C3 is charging

Answers: 1

body:
No, according to the [schematic](https://files.seeedstudio.com/wiki/XIAO_WiFi/Resources/Seeeduino-XIAO-ESP32C3-SCH.pdf) it's not wired to any pin on MCU.

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

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


body:
I have connected "Reyax RYLR998" Lora module to ESP32 UART2, but AT commands passed through Hardware serial not working.

```c++
#define RXD2 16
#define TXD2 17

void setup()
{
    Serial.begin(115200);
    Serial2.begin(115200, SERIAL_8N1, RXD2, TXD2);

    Serial.print("\nSetting Lora Module \n");

    Serial2.print("AT+BAND=865000000\r\n");
    if (Serial2.available())
        Serial.println(Serial2.read());
    delay(1000);

    Serial2.print("AT+ADDRESS=1\r\n");
    if (Serial2.available())
        Serial.println(Serial2.read());
    delay(1000);

    Serial2.print((String)"AT+NETWORKID=5\r\n");
    if (Serial2.available())
        Serial.println(Serial2.read());
    delay(1000);
}

void loop()
{
    while (Serial2.available())
    {
        Serial.print(char(Serial2.read()));
    }
}
```
I tried

```c++
Serial2.print((String)"AT+NETWORKID=5\n");
Serial2.println((String)"AT+NETWORKID=5\r");
Serial2.print((String)"AT+NETWORKID=5\r");
```

Nothing worked, no response from AT command,
Please help me I have been working on same problem for 2days.

[![Connection of RYLR998 with EPS32][1]][1]

[![Here all AT commands works well][2]][2]

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

title: How to pass AT commands to Lora from ESP32 UART?

Answers: 0


body:
I am looking at the documentation for the Arduino Zero, and I am a little confused.

It indicates that pins 13, 12, and 11 can be used for CIPO, COPI and SCK, but using `SPI.begin()` puts the signals on the 6-pin header SPI pinout, which makes sense since it is designated for SPI.

Is there a way to switch to the digital pins via C code? Or do I need to edit the header files?  We are using another board that can only attach to the digital pins.

title: Remap SPI functions to default pins Arduino Zero via software?

Answers: 1

body:
EDIT: Provably wrong answer below, see comments from though.
*********************

Unfortuantely the Arduino Zero doesn't support remapping of SPI pins as far as I know. Many other modern boards do, like the ESP8266/ESP32, but not the Zero, at least as far as I can tell.


body:
I encountered an issue when I try to send AT commands from Arduino nano to ESP01 I tried to find any tutorial for more helps, but I find nothing. please someone can help me.

I tried the tutorial from this link.
https://electronicslovers.com/2017/11/learn-how-to-setup-wifi-module-esp8266.html

But nothing happens when I type AT in serial monitor. I didn't see any response from the ESP module.

Answers: 0


body:
I need some hand here. I wrote some code for a small arduino console-like device that has five pushbuttons, 128x64 I2C OLED display and arduino nano. And it doesn't work when uploaded to arduino nano - display goes blank.

**Anamnesis**: The Code includes two classes: menu class and button class. When I upload the code on my device - it doesn’t display anything on oled but arduino still executes the code. Wiring is not an issue. But when I remove games_menu or pongLevel_menu or settings_menu and sound_menu from class objects and comment lines where these objects are used, the code works just fine.

**Question**: Maybe the thing is that arduino nano has some kind of memory, where it stores class objects, and my code uses too much of this memory. Since I am kinda new to arduino and programming - I can make mistakes. Can you please help me with this problem? Minimum reproducible code (sorry, I know that it looks like a big chunk of code but that's what I can shrink it to so that it still reproduces the problem):

```
#include "Wire.h"
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"
Adafruit_SSD1306 display(128, 64, &Wire, -1);
//------------variables-------------
    //--------menu variables--------
    unsigned long sec;
    byte selY = 12;
    boolean up;
    boolean down;
    boolean left;
    boolean right;
    boolean a;
    boolean b;
    int location = 0;

    //--------stopwatch variables--------
    unsigned long startTime;
    bool stTimeB = 1;
    unsigned long millisec;
    byte seconds;
    byte minutes;
    byte hours;
//--------classes-------
    //----class menu----
    class menu {
    public:
      menu(String caption, String item1, String item2, String item3, String item4, unsigned int minn, unsigned int maxx);
      void play();

    private:
     String cap;
     String it1;
     String it2;
     String it3;
     String it4;
     unsigned int _min;
     unsigned int _max;
  };
  menu::menu(String caption, String item1, String item2, String item3, String item4, unsigned int minn, unsigned int maxx){
    cap = caption;
    it1 = item1;
    it2 = item2;
    it3 = item3;
    it4 = item4;
    _min = minn;
    _max = maxx;

    }

  void menu::play(){
    if(up == 1 && millis() - sec > 199){
      selY -= 10;
      sec = millis();
    }
    if(down == 1 && millis() - sec > 199){
      selY += 10;
      sec = millis();
    }
    if(selY < _min){
      selY = _max;
    }
    if(selY > _max){
      selY = _min;
    }

    display.clearDisplay();
    display.setTextSize(1);
    display.setTextColor(WHITE);
    display.setCursor(50, 0);
    display.print(cap);
    display.drawLine(0, 9, 128, 9, WHITE);
    display.setCursor(6, 13);
    display.print(it1);
    display.setCursor(6, 23);
    display.print(it2);
    display.setCursor(6, 33);
    display.print(it3);
    display.setCursor(6, 43);
    display.print(it4);
    display.drawRoundRect(1, selY, 122, 11, 4, WHITE);
    display.display();

  }
    //--------class button--------
    class button {
  public:
    button(byte xx, byte yy, byte rr, byte var, String caption11, String caption22, String type_, byte tSize);
    void disp();
    void changeCap(bool caption);
    bool getStatus();
    void update_();

  private:
   byte x;
   byte y;
   byte r;
   byte txtSize;
   bool capB = 0; // 1
   bool pres = 0;
   byte btnPin;
   String caption1;
   String caption2;
   String type;
};
button::button(byte xx, byte yy, byte rr, byte var, String caption11, String caption22, String type_, byte tSize){
  x = xx;
  y = yy;
  r = rr;
  btnPin = var;
  caption1 = caption11;
  caption2 = caption22;
  type = type_;
  txtSize = tSize;
  }

void button::disp(){
  display.setTextSize(txtSize);
  if(pres == 0){
    display.drawRoundRect(x, y, (((caption1.length() + 2)*(5*txtSize)) + (caption1.length() - 1)), ((7+4)*txtSize), r, WHITE);
    display.setTextColor(WHITE);
  }
  else{
    display.fillRoundRect(x, y, (((caption2.length() + 2)*(5*txtSize)) + (caption2.length() - 1)), ((7+4)*txtSize), r, WHITE);
    display.setTextColor(BLACK);
  }

  if(pres == 0){display.setTextColor(WHITE); }
  if(pres == 1){display.setTextColor(BLACK);}

  if(capB == 0){
    if(pres == 1){display.setTextColor(BLACK);}
    if(pres == 0){display.setTextColor(WHITE);}
    display.setCursor(x+(5*txtSize), y+(2*txtSize));
    display.print(caption1);
  }
  else{
    display.setCursor(x+(5*txtSize), y+(2*txtSize));
    display.print(caption2);
  }
}

bool button::getStatus(){
  return pres;
}
void button::update_(){
  if(type == "push_button"){
    if(!digitalRead(btnPin) == 1 && millis() - sec > 19){
      pres = 1;
      sec = millis();
    }
    if(!digitalRead(btnPin) == 0){
      pres = 0;
    }
  }
  if(type == "switch"){
    if(!digitalRead(btnPin) == 1 && millis() - sec > 189){
      pres = !pres;
      sec = millis();
    }
  }
}

void button::changeCap(bool captionB){
  capB = captionB;
}
//--------class objects--------
menu main_menu("main", "games", "stopwatch", "timer...", "settings", 12, 42);
    menu games_menu("games", "pong", "guess a number...", " ", " ", 12, 22);
      menu pongLevel_menu("level", "easy", "hard", "expert", "impossible ", 12, 42);
    menu settings_menu("settings", "sound", "credits", " ", " ", 12, 22);
        menu sound_menu("sound", "on", "off", " ", " ", 12, 22);

button startB(25, 32, 6, 14, "start", "stop", "switch", 2);

//--------functions-----------
void buttonsUpdate(){
  up = !digitalRead(A0);
  down = !digitalRead(A2);
  left = !digitalRead(12);
  right = !digitalRead(A1);
  a = !digitalRead(4);
}
void resetTime(){
    millisec = 0;
    seconds = 0;
    minutes = 0;
    hours = 0;
}
void cookTime(){ // logic for stopwatch and calcuulating milliseconds, seconds, minutes and hours
  startB.update_();
  if(startB.getStatus() == 1){startB.changeCap(1);digitalWrite(13,1);}
  if(startB.getStatus() == 0){startB.changeCap(0);stTimeB = 1;digitalWrite(13,0);}

  if(startB.getStatus() == 1){
    if(stTimeB == 1){resetTime(); startTime = millis(); stTimeB = 0; }
    millisec = ((millis()-startTime)/10) % 100;
    seconds = ((millis()-startTime)/1000)`;
    minutes = ((millis()-startTime)/(1000*60))`;
    hours = ((millis()-startTime)/(1000*60*60))`;
  }
}

void dispStopwatch(){ // display stopwatch
  cookTime();
  display.clearDisplay();
  startB.disp();
  display.setTextColor(WHITE);
  display.setTextSize(2);
  display.setCursor(8, 10);
  display.print(hours);
  display.print("|");
  display.print(minutes);
  display.print("|");
  display.print(seconds);
  display.print("|");
  display.print(millisec);
  display.display();
}

void setup() {
  Wire.begin();
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  pinMode(13, OUTPUT);
  // buttons' pins setup
  pinMode(A0, INPUT_PULLUP); // up
  pinMode(A1, INPUT_PULLUP); // right
  pinMode(12, INPUT_PULLUP); // left
  pinMode(A2, INPUT_PULLUP); // down

  pinMode(4, INPUT_PULLUP);  // a
 }

void loop() {
 buttonsUpdate();
  if(up == 1 && down == 1){location = 0;}

  if(location == 0){//main menu
    main_menu.play();
    if(a == 1 && selY == 12/*if a btn is clicked while selected first item*/ && millis() - sec > 199){location = 1/*games*/; sec = millis();}
    if(a == 1 && selY == 22/*if a btn is clicked while selected first second*/ && millis() - sec > 199){location = 2/*stopwatch*/; sec = millis();}
    //if(a == 1 && selY == 32 && millis() - sec > 199){location = 3/*timer*/; sec = millis();}
    if(a == 1 && selY == 42/*if a btn is clicked while selected first fourth*/ && millis() - sec > 199){location = 4/*settings*/; sec = millis();}
  }

  if(location == 1){//game menu
        games_menu.play();
        if(a == 1 && selY == 12 && millis() - sec > 199){location = 11/*pong*/; sec = millis();}
      }
          if(location == 11){//pong levels
          pongLevel_menu.play();
          }

  if(location == 2){//stopwatch
        dispStopwatch();
  }
  if(location == 4){//settings
        settings_menu.play();
        if(a == 1 && selY == 12 && millis() - sec > 199){location = 41/*sound*/; sec = millis();}
        if(a == 1 && selY == 22 && millis() - sec > 199){location = 42/*credits*/; sec = millis();}
      }
          if(location == 41){// sound menu
            sound_menu.play();
          }
          if(location == 42){// credits
           // drawBitmap();
          }
}
```

title: Arduino sketch doesn't work when uploaded to arduino nano and OLED display shows npothing (possible issue: lack of memory)

Answers: 0


body: I'm trying to connect a GSM module(sim800L) with a NodeMCU to execute remote operations. But the GSM module cannot be powered using the NodeMCU. So, what are the other ways to power the board as well as the module. Also I want to connect directly to a wall power supply instead of using a battery.

title: Powering a NodeMCU as well as a GSM module

Answers: 1

body:
After a bit of researching, I have found the following solution:-

A DC-DC buck converter (such as the LM2596) can convert a 12 V 2A rated power supply down to 4 V (the value is adjustable) which can then be used to power the module.


body:
I'm using Freenove's ESP32 WROVER Module with their GPIO expansion board as shown in the image below:

[![Circuit image][1]][1]

I'm trying to integrate Sparkfun's microSD module in the circuit. [Here's my sketch][2]. However, I'm unable to mount the card despite it works fine using an ESP32-CAM board with integrated SD card reader.

Any clues on what I'm doing wrong?

  [1]: https://i.stack.imgur.com/uYA7m.jpg
  [2]: https://www.dropbox.com/s/1isx64ksknl4cnr/esp32_microsd_module.ino?dl=0

title: Can't mount microSD card with Freenove ESP32 WROVER Module and Sparfun MicroSD module

Answers: 1

body:
Your pinout to the SD is unclear from the picture, but I can see that you are using **pin 15**, which is the MTDO strapping pin- which will cause issues for sure.

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

You can learn more here about using alternative pins here:

https://randomnerdtutorials.com/esp32-spi-communication-arduino/

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


body:
I'm working on a project to build a plant monitor that works from the outside with Arduino that picks up light and water values from it's environment then uses a nRF24L01 with an antenna and I've come across a roadblock in the code with using a transmitter and receiver, heres the code fully below.

Appreciate any help, been stuck for weeks trying to figure this out.

Transmitter Code
```
/*
 * NAME: <Mario Ronci>
 * Healthy Plant Monitor  V2  T
 *
 *
 */

 //** **/
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>
//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

int ldrValue;
int sensorPin = A0;    // select the input pin for the Water Comparator
int sensorValue = 0;
int light_threshold = 650;
int water_threshold = 850;
String dark_message = " ALERT:Plant is Dark!";
String bright_message =" Brightness Achieved! ";
String water_message1 = " Plant has enough water.";
String water_message2 = " Need Water...!";
String healthy_message = "Plant is Healthy!";
String unhealthy_message = "Unhealthy...!";
//String engineerinfo = "Mario Ronci 2023";

void setup() {

  pinMode(LDR, INPUT);
  pinMode(POT, INPUT);
  pinMode(10, OUTPUT);
  pinMode(9, OUTPUT);
  Serial.begin(9600);
  Serial.println(engineerinfo);
  // put your setup code here, to run once:
radio.begin();
  //set the address
  radio.openWritingPipe(address);
  //Set module as transmitter
  radio.stopListening();

}

//This checks if the plant is getting enough light,//
//by taking a acceptable or unacceptable light value
//from a LDR and prints the value to the serial monitor
//and if the light value is acceptable

void ldrCheck(int device, int duration1,int duration2){

ldrValue = analogRead(device);

if(ldrValue >= light_threshold)

{
  messageLight = light_message + String(ldrValue);
  sendByteMessage(); // Call the function to send the byte message
   delay(duration1);// Wait for some time before sending the next message

}

if(ldrValue < light_threshold){
  messageLight = dark_message + String(ldrValue)
  byte messageBytes[message.length() + 1]; // Create a byte array to store the message
  delay(duration2);
}

void sendByteMessage() {
  byte messageBytes[message.length() + 1]; // Create a byte array to store the message

  // Convert the string message into a byte array
  message.getBytes(messageBytes, message.length() + 1);

  // Send the byte array through the transmitter
  radio.write(&messageBytes, sizeof(messageBytes));
}

}

////This checks if the plant is getting enough water,//
//by taking a acceptable or unacceptable hydration value
//from a LDR and prints the value to the serial monitor
//and if the hydration value is acceptable , the yellow LED will turn on
//and blink, if it's not it will print a message to the serial monitor
//to alert you

//********* Note replace POT with hydrometer code*********//
void potCheck(int device,int duration3){

potValue = analogRead(device2);

if(potValue > water_threshold)
{
  Serial.print(potValue);
  Serial.println(water_message1);

}

else{
  Serial.println(water_message2);

}

}

//This checks if the plant is getting enough water and light
//, if it's not it will print a message to the serial monitor
//to alert you and if it is getting enough it will print a
//message to the serial monitor telling you the plant is healthy

void healthyCheck(int led_4,int duration4,int duration5){

if((ldrValue >= light_threshold) && (potValue > water_threshold)){
digitalWrite(led_4, HIGH);
Serial.println(healthy_message);
delay(duration4);
}

else{
digitalWrite(led_4,HIGH);
delay(duration5);
digitalWrite(led_4,LOW);
delay(duration5);
Serial.println(unhealthy_message);

}

}

void loop(){

//This calls the function/method

//in loop call transmitter

ldrCheck(LDR, 1000,100 );
sendByteMessage(LDR)
potCheck();
healthyCheck(2000,800);

}

```

Receiver Code

```
#include <nRF24L01.h>
#include <printf.h>
#include <RF24.h>
#include <RF24_config.h>

//Create an rf24 object

RF24 radio(9,8) ; //CE,CSN

//address through which two modules communicate.

const byte address[6]  = "00001";

void setup() {

while(!Serial);
 Serial.begin(9600);

 radio.begin();

 //set the address
 radio.openReadingPipe(0, address);

 //set module as receiver
 radio.startListening();

}

void loop() {
  //Read the data if available in buffer

  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.print(ldrValue);
    Serial.println(light_message);
  }
```

**What specifically do you need help with?**

I'm trying to modify original code to work with the transmitter and receiver functionality
before I had code that used leds meaning the plant monitor would turn on certain colored LEDs based on condition.Now in V2 of this project i decided to do away with the LED's and make the goal to have communication between the componets from the outside to send messages about the plant status inside where another arduino would print to the serial monitor

I need help with having the transmitter code work with the conditional statements atm I'm confused where to insert the each piece of code so the transmitter sends a message to the receiver and prints in the serial monitor.It should work as the componets take inputs from the environment like the ldr, then that value is stored and applied to if statment , if x is this value then send this message and then the transmitter sends the message to the receiver that prints it to the serial monitor

**What have you tried?**

I've tried to create a seperate variable for the message I want to send along with the analog sensor values from the ldr.( I've not gotten to the hydrometer yet I only got the wiring for it done) Turn the ldr from int to a string and then call the variable in the byte message function within a function for checking for ldr values. Then in the receiver code i tried testing by writing Serial Print for each value but It's not working and I think its because the value is out of scope.Not in the same sketch.

**What do you think the problem is?**

I think it may be the order of the code and or syntax,maybe if I put the transmitter code outside of the ldr check function it would work, but im not sure. Could also be that the datatypes are strings and ints and changing that to the bytes isn't as straightfoward as I thought.

The actual build and components

Master  (  transmitter ) takes inputs from the environment using a Ldr and hydrometer
both water and light values and sends it to the slave microcontroller the receiver, wiring is correct.
[![enter image description here][1]][1]

Slave ( receiver) processes the values from the transmitter and prints them in the serial monitor the messsage it recieves will depend on conditions such as light value thresholds  and water value thresholds in simple terms if the light  or water values exceed a certain value or are below a certain value it will send a different message for each situation.

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/BIsNK.jpg
  [2]: https://i.stack.imgur.com/nS2YM.jpg

title: How do I use a transmitter and receiver to send string messages conditionally to a receiver?

Answers: 1

body:
I figured the issue out.

1. code was a mess but after troubleshooting it for a while the if statements didn't make sense and had no good flow to them plus too complicated. I had copied and pasted some code without making sense of it.

2. It worked when I focused on one component like @jstola said. The photoresistor only and so the main thing is to add the conditional then turn string into a byte message and then void loop sends byte message to receiver arduino. Then the next part there were symbols appearing in the serial monitor and that was weird. So I experimented with the char data type instead of string and worked. Also use chatgpt as well for some syntax help.

Now I have base to work from. So next is to tackle the hydrometer.

**Transmitter Code - with photoresistor only**

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(9, 8); // Create an instance of the RF24 object

const byte address[6] = "00001"; // Set the pipe address

int ldrValue;
int sensorPin = A2;    // Select the input pin for the LDR
int light_threshold = 650;
String light_message = "Plant has enough light :";
String dark_message ="Alert: Plant is Dark! :" ;
String water_message1 = " Plant has enough water.";
String water_message2 = " Need Water...!";
String healthy_message = "Plant is Healthy!";
String unhealthy_message = "Unhealthy...!";

void setup() {

  pinMode(sensorPin, INPUT);
  radio.begin();
  radio.openWritingPipe(address);
  radio.stopListening();

}

void loop() {
  ldrCheck(sensorPin, 1000, 100);
}

void ldrCheck(int device, int duration1, int duration2) {
  ldrValue = analogRead(device);

  if (ldrValue >= light_threshold) {
    String message = light_message + String(ldrValue);
    sendByteMessage(message);
    delay(duration1);
  }
  else {
    String message = dark_message + String(ldrValue);
    sendByteMessage(message);
    delay(duration2);
  }
}

void sendByteMessage(String message) {
  byte messageBytes[message.length() + 1];
  message.getBytes(messageBytes, message.length() + 1);
  radio.write(&messageBytes, sizeof(messageBytes));
}

```

**reciever Code - with photoresistor only**

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <printf.h>
#include <RF24_config.h>

RF24 radio(9, 8); // Create an instance of the RF24 object

byte address[6] = "00001"; // Set the pipe address

void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(1, address);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    char message[32] = ""; // Create a character array to store the message
    radio.read(&message, sizeof(message));
    processMessage(message);
  }
}

void processMessage(char* message) {
  String receivedMessage = String(message); // Convert the character array to a String
  Serial.println(receivedMessage);
  delay(1000);
}

```

result:

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

[Video][2]

  [1]: https://i.stack.imgur.com/VOy7X.png
  [2]: https://www.linkedin.com/posts/mario-ronci-a1a774b0_agriculture-agriculturetechnology-environmental-activity-7074186222914416640-A_di?utm_source=share&utm_medium=member_desktop


body:
Parameters file defines the creation of entities and stored in flash. Its structure is given, and all fields ( keys & values ) are given.
In current phase - those parameters are hard-coded in a `const char* cont_params`, as shown below.

My goal, is when array is empty, for example `RF_2entity` - means that current MCU does not uses its RF abilities, and will not init any RF entities. The way `RF_2entity` is defined below, as empty array, `[]` , ArduinoJSON's `isNull()` function return `0` in that case.

How can I keep parameters file's structure and logic, rather that fill its values with `255` for example.

      Serial.begin(115200);
      StaticJsonDocument<1200> doc;
      const char *cont_params = "{\"entityType\": [1,1,1,1],\
                        \"SWname\": [\"SW_0\",\"SW_1\",\"SW_2\",\"SW_3\"],\
                        \"SW_buttonTypes\": [2,1,1,1],\
                        \"SW_timeout\": [10,11,12,13],\
                        \"SWvirtCMD\":[0,0,0,0],\
                        \"Winname\": [],\
                        \"WextInputs\": [],\
                        \"WinvirtCMD\":[],\
                        \"RF_2entity\": [],\
                        \"v_file\": 0.5}";
      DeserializationError err = deserializeJson(doc, cont_params);
      JsonArray array = doc["Winname"].as<JsonArray>();
      serializeJsonPretty(array,Serial);
      Serial.println(array.isNull());

output:

    []0

title: ArduinoJSON - How to check if array is empty

Answers: 1

body:
The method `isNull()` is not what you want. It tells you whether the instance holds an array at all or not. And of course, your specific instance holds an array, though an empty one. Therefore, the method correctly returns `false`, aka `0`.

As [the API documentation][1] shows, there are more methods to use.

What you want is `size()`, which returns the number of elements in the array. It will even return `0` on an instance without an array.

  [1]: https://arduinojson.org/v6/api/jsonarray/


body:
I'm using an Arduino Due to make a feedback loop using python, but this does not seem to function. The python code I'm using is the following:

    from serial import Serial
    board = Serial('COM11',9600)
    board.write('100'.encode()) # 100 is taken as an example

In fact, if I just use Arduino to measure the sensor voltage, it succeeds. It's the same if the voltage is sent without measuring the sensor. But, as soon as I put both simultaneously, the sensor is good but nothing is read by the Arduino.
However, if I send the voltage not using Python but using the Arduino IDE, everything is okay.

It seems that the Arduino can't do the two operations at the same time, but this is weird. Here is my Arduino code:

```
int const controller = DAC0; // Set the controller output pin
int const sensor = A1; // Set the sensor pin
double MeanNumber = 500;

void setup() {
  Serial.begin(9600);
  pinMode(controller, OUTPUT);
  analogReadResolution(12);
}

double get_voltage(int Measure)
{
  double voltage;
  voltage = Measure * 3.3 / 4095.0;
  return voltage;
}

void loop() {
  double Measure = 0;

  double voltage;
  for (int i = 0; i < int(MeanNumber); i++) // Realize an average each MeanNumber value
  {
    Measure = Measure + analogRead(sensor) / MeanNumber;
    delay(1);
  }

  // Send the averaged measure to python
  voltage = get_voltage(Measure);
  Serial.println(voltage,4);

  // Get the feedback from python
  if (Serial.available() > 0)
  {// Verify if data are available
    String receivedData = Serial.readString(); // Read the voltage value from bytes to string
    float value = receivedData.toFloat(); // Convert the voltage into float
    analogWrite(controller,value); // Send the signal via the Arduino
  }

}
```

Do you have an idea of what is wrong with my job?

title: Sending values with pyserial does not function if there is also sensing on Arduino Due

Answers: 1

body: Opening a Serial connection will reset the Arduino.  The python code may be doing that when it creates the port.  Put a Serial.print("Starting") line in your setup function to see if that's what is happening.


body:
My IDE shows "Adafruit Radio - Si4713 Test", but without "RDS on!", which is supposed to show up. The radio I use (Inscabin M60) shows static. Am I doing something wrong?

*Adafruit Radio - Si4713 Test
Couldn't find radio?
Adafruit Radio - Si4713 Test
Couldn't find radio?
Adafruit Radio - Si4713 Test
Couldn't find radio?
Adafruit Radio - Si4713 Test
Couldn't find radio*
Adafruit Radio - Si4713 Test
The italic represents where I made a mistake.
This is the code, where I only changed the error message. I previously changed the #define FMSTATION to 9670, but KTCK has taken that signal, so I changed it back.
/***************************************************
  This is an example for the Si4713 FM Radio Transmitter with RDS

  Designed specifically to work with the Si4713 breakout in the
  adafruit shop
  ----> https://www.adafruit.com/products/1958

  These transmitters use I2C to communicate, plus reset pin.
  3 pins are required to interface
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution

  Many thx to https://github.com/phrm/fmtx/blob/master/firmware/firmware.ino !

 ****************************************************/

    #include <Wire.h>
    #include <Adafruit_Si4713.h>
    #define _BV(n) (1 << n)

    #define RESETPIN 12

    #define FMSTATION 10230      // 10230 == 102.30 MHz

    Adafruit_Si4713 radio = Adafruit_Si4713(RESETPIN);

    void setup() {
      Serial.begin(9600);
      Serial.println("Adafruit Radio - Si4713 Test");

      if (! radio.begin()) {  // begin with address 0x63 (CS high default)
        Serial.println("Couldn't find radio");
        while (1);
      }

      // Uncomment to scan power of entire range from 87.5 to 108.0 MHz
      /*
      for (uint16_t f  = 8750; f<10800; f+=10) {
       radio.readTuneMeasure(f);
       Serial.print("Measuring "); Serial.print(f); Serial.print("...");
       radio.readTuneStatus();
       Serial.println(radio.currNoiseLevel);
       }
       */

      Serial.print("\nSet TX power");
      radio.setTXpower(115);  // dBuV, 88-115 max

      Serial.print("\nTuning into ");
      Serial.print(FMSTATION/100);
      Serial.print('.');
      Serial.println(FMSTATION % 100);
      radio.tuneFM(FMSTATION); // 102.3 mhz

      // This will tell you the status in case you want to read it from the chip
      radio.readTuneStatus();
      Serial.print("\tCurr freq: ");
      Serial.println(radio.currFreq);
      Serial.print("\tCurr freqdBuV:");
      Serial.println(radio.currdBuV);
      Serial.print("\tCurr ANTcap:");
      Serial.println(radio.currAntCap);

      // begin the RDS/RDBS transmission
      radio.beginRDS();
      radio.setRDSstation("AdaRadio");
      radio.setRDSbuffer( "Adafruit g0th Radio!");

      Serial.println("RDS on!");

      radio.setGPIOctrl(_BV(1) | _BV(2));  // set GP1 and GP2 to output
    }

    void loop() {
      radio.readASQ();
      Serial.print("\tCurr ASQ: 0x");
      Serial.println(radio.currASQ, HEX);
      Serial.print("\tCurr InLevel:");
      Serial.println(radio.currInLevel);
      // toggle GPO1 and GPO2
      radio.setGPIO(_BV(1));
      delay(500);
      radio.setGPIO(_BV(2));
      delay(500);
    }

title: Adafruit Si4713/IDE not working

Answers: 0


body: I am currently controlling two servos using the Arduino IDE, but now need to integrate my Arduino code into a Python script. I read about how to use PyFirmata and went through the process of uploading StandardFirmata to my Arduino Mega 2560 board after changing the samplingInterval value to 99, instead of the default 19. However, having followed the exact procedure of translating Arduino code to Python and downloading/using the correct pyfirmata package, the board simply does not react. I tested the board, the individual servos, power, etc. and have even used the ArduinoMega module in pyfirmata, but there is absolutely no reaction when using the Python code. I have looked through multiple online forums and it seems that this is a recurring issue, but no one has posted a solution (as per my knowledge) to the problem and it would be of great help if someone could help me fix this. Please let me know if you would like to see any of the code, it is very simple and I do not mind sharing it if required. Thanks in advance!

title: Connecting Arduino Mega 2560 to Python with PyFirmata

Answers: 0


body:
I am trying to build a project where I have connected 8 Sparkfun TOF Sensors to an I2C MUX which is connected to a Sparkfun RedBoard.

I need to read and display the data from each sensor on the serial monitor right now and later on an OLED Display. The issue I am facing is that it is reading data only from the first sensor and then it stops running.

I have pasted my code below. I am new to all of this so any help would be appreciated on how to fix this issue.  The `enableMux()` and `disableMux()` functions are from the GitHub example code libraries. I want to know if the issue is that I am not enabling my ports properly or if the issue is with my data reading. Do I need to initialize each sensor individually?
```
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include "SparkFun_TMF882X_Library.h"

#define sensors 8
SparkFun_TMF882X  myTMF882X;

void setup()
{
  Serial.begin(9600);
  while(!Serial);
  Wire.begin();
  for(byte x=0;x<sensors;x++)
  {
    enableMuxPort(x);
    if(!myTMF882X.begin())
    {
        Serial.println("Error - The TMF882X failed to initialize - is the board connected?");
        while(1);
    }
    else
    Serial.print(x+1);
    Serial.println(" TMF882X started.");
    disableMuxPort(x);
  }
}

void loop()
{
    delay(500);
    for(byte x=0;x<sensors;x++)
    {
      enableMuxPort(x);
      struct tmf882x_msg_meas_results myResults;

      myTMF882X.startMeasuring(myResults);
      Serial.print(myResults.num_results);
      unsigned int distance = myResults.results[0].distance_mm;
      Serial.print("Sensor ");
      Serial.print(x+1);
      Serial.print(" distance: ");
      Serial.print(distance);
      Serial.print("mm");
      Serial.println();
      disableMuxPort(x);
    }
}
```

Hardware Used:

>Microcontroller: Sparkfun Redboard Turbo\
MUX: SparkFun Qwiic Mux Breakout - 8 Channel (TCA9548A) - BOB-16784 - SparkFun Electronics\
Sensor: Qwiic dToF Imager (TMF882X) Hookup Guide - SparkFun Learn

Below is the output I am getting:
```
1 TMF882X started.

2 TMF882X started.

3 TMF882X started.

4 TMF882X started.

5 TMF882X started.

6 TMF882X started.

7 TMF882X started.

8 TMF882X started.

9Sensor 1 distance: 3325mm

0Sensor 2 distance: 0mm
```

title: Unable to read the sensor data from all the sensors connected

Answers: 0


body:
I am dealing with an Arduino Nano board rev 3.0 from Gravitech.
There is a program inside that I'd like to download to a HEX file. Thus I can upload it to other Arduino Nano boards.

I'm a newbie with Arduino. Therefore I've read much documentation on the internet and I came to the point to use `avrdude` in the command line as Arduino IDE does not provide a feature to perform a download to an HEX file (as far as I've understood).

I've installed all the necessary software on my Mac OS Mojave (avrdude v7.0 using 'Mac Ports'). And after powering up and connecting the Arduino Nano board to a USB port of my Mac, I launched the following command line:

`avrdude -p m328p -D -c arduino -P /dev/tty.usbserial-A9077L99 -U flash:r:programme_arduino.bin:r -v -x attempts=4`

I obtain the classical message
>stk500_recv(): programmer is not responding

I've noticed that the 'Rx' led and the 'L' led were blinking during the attempts.

From your perspective, do the options look good (-p -c ...)?

[![Arduino Nano Gravitech v3.0][1]][1]

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

title: Arduino Uno Gravitech Rev 3.0 with avrdude CLI (Mac OS) - Is my script correct?

Answers: 1

body:
Your first problem is the no-response complaint. You said "I've noticed that the 'Rx' led and the 'L' led blank during the attempts." Is "blank" a typo (i.e., the LEDs *do* blink?) or did you mean they do nothing? Are you using the same cable you used to program the nano? Can you swap with another cable? Test this cable with another nano? Is the port ID typed correctly (/dev/...etc)?

Double-check the programmer ID (-c option) and part number (-p option) by querying AVRDUDE (specify '?' instead of a valid value on each of those).

For the -U option, you'll want to name the output file with a .hex extension, and specify the file-format as 'i' for intel hex:<br>
 `-U flash:r:programme_arduino.hex:i`

[Here is the AVRDUDE reference][1] I used.

Update:

I agree that your port ID must be correct and the cable is working, since your LEDs are blinking. But you get an error message about "not responding". Does the Nano have a bootloader in it? Could the boot-loader have been damaged when you uploaded the code (e.g., the code is large enough to over-write some of the bootloader)?

Is binary code in the Nano the only copy, or do you have the source code for it? If you have the source, you can recompile it (if necessary) and retrieve the resulting .hex file. Would that solve your problem? By setting the IDE to produce verbose output, you'll see the path to the temporary files, including the .hex file. Then use Finder (or a Terminal command, if you are comfortable with that) to copy that temporary .hex file to someplace safe.

Update 2:

> Are bootloader ROM area and Flash ROM area two different memory areas?

Not separate - the boot-loader is placed at the top of Flash. It is possible for a large enough program to over-write it - I'm not sure whether that has to be specifically allowed, such as by setting fuses. If it does get over-written, it obviously becomes unusable.

I wonder if the flash can be read using a hardware programmer? Do note that these chips have lockout-fuses that can be set to prevent further programming or reading of the flash.

Since the code in this device seems valuable to you, I would suggest putting this Nano board aside, and only experiment with another, hopefully identical, board. On the new board -
- Upload a sketch to it;
- Copy the AVRDUDE command line used to by the IDE to upload it, and modify it as you've already described. Of course, this command will already have the board-specific parameters;
- Use the modified command to download the sketch to another file, and compare it to the file that was just uploaded.

Once you can do this successfully, apply that last step to copy the sketch from your valuable Nano, then put that board away again. Load and test the downloaded code on your experimental Nano. Don't forget to include the valuable Nano's EEPROM - it might contain some critical data.

  [1]: http://www.avrlearning.com/140/avrdude-command-line-reference.php


body:
Basically, how do I modify my code listed below to turn **ON** each of the three LEDs one at a time in a repetitive sequence while keeping the push-button pressed?
- Red (3 sec),
- Yellow (1 sec), and
- Green (3 sec).

I'm trying to get all three LEDs to turn **OFF** when the push button is released.

The code I wrote that doesn't allow me to achieve what I'm trying to do (I'm not sure where I went wrong):
```
#define Button_Pin 2  //Push Button Pin
#define LED_Pin_1 11 //Red LED
#define LED_Pin_2 10 //Yellow LED
#define LED_Pin_3 9  //Green LED

byte Button_State;

void setup() {
  pinMode(Button_Pin, INPUT);
  pinMode(LED_Pin_1,  OUTPUT);
  pinMode(LED_Pin_2,  OUTPUT);
  pinMode(LED_Pin_3,  OUTPUT);

  Serial.begin(9600);
  Serial.println("Design Part B - Digital I-O Control");
  delay(1000);
}

void loop() {
  Button_State = digitalRead(Button_Pin);
  Serial.print("Button State: ");
  Serial.print(Button_State);

  if (Button_State == 1){
    digitalWrite(LED_Pin_1, HIGH);
    delay(3000); //Wait for 3 Secs
    digitalWrite(LED_Pin_2, HIGH);
    delay(1000); //Waits for 1 Sec
    digitalWrite(LED_Pin_3, HIGH);
    delay(3000);
    Serial.println(" --> Button Pressed --> LED ON");
  }
  else{
    digitalWrite(LED_Pin_1, LOW);
    digitalWrite(LED_Pin_2, LOW);
    digitalWrite(LED_Pin_3, LOW);
    Serial.println(" Button is Released --> LED OFF");
  }
}
```

[![The circuit layouts being used][1]][1]

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

title: How do I turn on 3 LEDs in a repetitive sequence where all three LEDs would then turn OFF when the push button used is released?

Answers: 2

body:
You need a [state machine](https://en.wikipedia.org/wiki/Finite-state_machine) (to remember which LED is currently on) and use `millis()` to find the current time, in a loop, which is testing whether the switch is closed or not.

If the switch is closed you compare the time now (with `millis()`) to the time you turned that particular LED on. When the time is up you advance the "state" (eg. a counter) to the next one, and remember the new time that this state change happened.

body:
Having examined several sample sketches, including the recommended one, and watching instructional YouTube videos to grasp the fundamentals of Arduino programming, I am delighted to announce that my understanding of programming the Arduino and comprehending its functions has significantly improved, considering my novice status.

I can confidently assert that this question has been resolved, and I have enclosed the code that fulfills the initial requirements that was asked of me.

    #define pushButton_pin 2
    #define grn_LED_pin 9
    #define yel_LED_pin 10
    #define red_LED_pin 11

    bool pushButton_state;

    void setup() {
    pinMode(pushButton_pin, INPUT);
    pinMode(grn_LED_pin, OUTPUT);
    pinMode(yel_LED_pin, OUTPUT);
    pinMode(red_LED_pin, OUTPUT);

    Serial.begin(115200);

    Serial.println("Use push button (digital input) to control 3 LEDs (digital
    output)");
    delay(1000);
    }

    void loop() {
    pushButton_state = digitalRead(pushButton_pin);
    Serial.println(pushButton_state);
    if (pushButton_state == 1) {
    digitalWrite(grn_LED_pin, LOW);
    digitalWrite(yel_LED_pin, LOW);
    digitalWrite(red_LED_pin, HIGH);
    Serial.println(" :push button state is 1, red LED is ON");
    delay(2000);
    digitalWrite(grn_LED_pin, LOW);
    digitalWrite(yel_LED_pin, HIGH);
    digitalWrite(red_LED_pin, LOW);
    Serial.println(" :push button state is 1, yel LED is ON");
    delay(1000);
    digitalWrite(grn_LED_pin, HIGH);
    digitalWrite(yel_LED_pin, LOW);
    digitalWrite(red_LED_pin, LOW);
    Serial.println(" :push button state is 1, grn LED is ON");
    delay(2000);
    } else {
    digitalWrite(grn_LED_pin, LOW);
    digitalWrite(yel_LED_pin, LOW);
    digitalWrite(red_LED_pin, LOW);
    Serial.println(" :push button state is 0, all LEDs OFF");
    }
    delay(500);
    }


body:
My circuit uses an Arduino Nano which I communicate via Α4 and A5 via I2C. There are several BMP280, HMC5883 and MPU6050 sensors on the I2C line. While I was dealing with these other two sensors, my MPU6050 stopped working. She started outputting single zeroes regardless of the movements. I found similar problems and it was suggested to conduct a search and if it is searched to try some other code.I tried and nothing helped. They also wrote about power supply problems, but the board I use has resistors between the microcircuit and the SCL/CLK terminals. I also heard about FIFO, but did not understand anything.
I don't know what I did wrong because before that it was working fine. I will add the code I used.

    /*
    The contents of this code and instructions are the intellectual property of Carbon Aeronautics.
    The text and figures in this code and instructions are licensed under a Creative Commons Attribution - Noncommercial - ShareAlike 4.0 International Public Licence.
    This license lets you remix, adapt, and build upon your work non-commercially, as long as you credit Carbon Aeronautics
    (but not in any way that suggests that we endorse you or your use of the work) and license your new creations under the identical terms.
    This code and instruction is provided "As Is” without any further warranty. Neither Carbon Aeronautics or the author has any liability to any person or entity
    with respect to any loss or damage caused or declared to be caused directly or indirectly by the instructions contained in this code or by
    the software and hardware described in it. As Carbon Aeronautics has no control over the use, setup, assembly, modification or misuse of the hardware,
    software and information described in this manual, no liability shall be assumed nor accepted for any resulting damage or injury.
    By the act of copying, use, setup or assembly, the user accepts all resulting liability.

    1.0  5 October 2022 -  initial release
    */

        #include <Wire.h>
        float RateRoll, RatePitch, RateYaw;
        void gyro_signals(void) {
          Wire.beginTransmission(0x68);
          Wire.write(0x1A);
          Wire.write(0x05);
          Wire.endTransmission();
          Wire.beginTransmission(0x68);
          Wire.write(0x1B);
          Wire.write(0x8);
          Wire.endTransmission();
          Wire.beginTransmission(0x68);
          Wire.write(0x43);
          Wire.endTransmission();
          Wire.requestFrom(0x68,6);
          int16_t GyroX=Wire.read()<<8 | Wire.read();
          int16_t GyroY=Wire.read()<<8 | Wire.read();
          int16_t GyroZ=Wire.read()<<8 | Wire.read();
          RateRoll=(float)GyroX/65.5;
          RatePitch=(float)GyroY/65.5;
          RateYaw=(float)GyroZ/65.5;
        }
        void setup() {
          Serial.begin(57600);
          pinMode(13, OUTPUT);
          digitalWrite(13, HIGH);
          Wire.setClock(400000);
          Wire.begin();
          delay(250);
          Wire.beginTransmission(0x68);
          Wire.write(0x6B);
          Wire.write(0x00);
          Wire.endTransmission();
        }
        void loop() {
          gyro_signals();
          Serial.print("Roll rate [°/s]= ");
          Serial.print(RateRoll);
          Serial.print(" Pitch Rate [°/s]= ");
          Serial.print(RatePitch);
          Serial.print(" Yaw Rate [°/s]= ");
          Serial.println(RateYaw);
          delay(50);
        }

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

here is what it outputs now ("0"), although before it was perfectly responsive. At least it accurately displayed the + or - sign along with some values

The type of MPU6050 I used:[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/PQnEE.png
  [2]: https://i.stack.imgur.com/IqCYR.png
  [3]: https://i.stack.imgur.com/2h7S2.png

title: MPU6050 when searching is at address 0x68 but as a result shows only "0"

Answers: 0


body: So PWM goes from 0 to 5V. How could I do -2.5 - 2.5V? Basically I am asking how to add offset to PWM signal. Should I use operational amplifier? How would I use it? I never had to deal with them, but I have LM2904P laying around.

title: How to offset PWM output so it would also have negative amplitude?

Answers: 1

body:
Consider removing the average of the PWM voltage by subtracting the [Direct Current (DC)][1] component of the PWM output.

Often, between different audio amplifiers stages, the DC component of the signal is removed through the use of [coupling capacitors][2]. The above link offers these guide lines for picking the value of the capacitor:

> Below is a basic rough guideline of capacitors that can be used for
> various frequencies.
>
> For coupling a 100Hz signal, a 10μF capacitor can be used.
>
> For a 1000Hz signal, a 1μF capacitor can be used.
>
> For a 10KHz signal, a 100nF capacitor can be used.
>
> For a 100KHz signal, 10nF capacitor can be used.
>
> For a 1MHz signal, a 1nF capacitor can be used.
>
> For a 10MHz signal, a 100pF capacitor can be used.
>
> For a 100MHz signal, a 10pF capacitor can be used.
>
> This is a rough estimate that will be effective the majority of the
> time. The only variable that could affect the above values is the
> resistance in parallel to the capacitor.

Consider the last paragraph above when designing your circuit.  The lower the input impedance of the circuit you are driving the more likely the possibility of unexpected results.  At which point you might consider adding the OpAmp suggest in the question.

  [1]: https://en.wikipedia.org/wiki/Direct_current
  [2]: http://www.learningaboutelectronics.com/Articles/What-is-a-coupling-capacitor