# Question
Title: How to compile, upload and monitor via the Linux command line?
Interfacing an Arduino Uno (uploading etc.) with the Arduino IDE (using the Fedora package) works fine under Fedora 21.

But I rather want to use vim + make + vim-quickfix-mode etc.

How can I do that?

Preferably via the tools available from the Fedora repositories.

I assume that the IDE calls externals command line utilities for the uploading etc.

The equivalent to the IDE's serial monitor is probably connecting a terminal emulator (e.g. `screen`) to `/dev/ttyACM0`, right?

Perhaps there is a good example project one can look at the makefile?

# Answer
> 2 votes
A great way to compile for and flash an Arduino device from the command line and integrate with Vim is to use PlatformIO Core (CLI).

Since it's written in Python it's easy to install even when it's not packaged for your Linux distribution. PlatformIO supports many microcontroller devices, not just Arduino ones. Thus, you don't have to switch your development environment when you target another platform. PlatformIO takes care of downloading the right toolchain (compiler etc.) for your target.

## Example

Getting started with PlatformIO and an Arduino Pro Mini 3.3v clone on Fedora 35:

```
mkdir -p ~/local
cd ~/local
python -m venv platformio
source platformio/bin/activate
pip install platformio

```

This installs PlatformIO (CLI) in a virtual environment, i.e. its main command is then available from `~/local/platformio/bin/pio` and `pio` is found in your `PATH` when the virtual environment is activated.

Next, we need to find the right board ID for setting up a new project:

```
pio boards arduino | less

```

That means search for `Pro.*Mini` in the listing. There are several versions of the Pro Mini, in our example the `pro8MHzatmega328` (3.3 V, 8 MHz, ATmega328, 30 kb flash, 2 kB RAM) is the right one as can be validated by looking at the board markings as well as its voltage regulator, and CPU markings.

To set up a new project

```
mkdir ~/project/some_new_project
cd ~/project/some_new_project
pio project init --board pro8MHzatmega328 --ide vim

```

Which prints:

```
The current working directory /home/juser/project/arduino/pro-mini will be used for the project.

The next files/directories have been created in /home/juser/arduino/pro-mini
include - Put project header files here
lib - Put here project specific (private) libraries
src - Put project source files here
platformio.ini - Project Configuration File
Platform Manager: Installing atmelavr
Downloading  [####################################]  100%
Unpacking  [####################################]  100%
Platform Manager: atmelavr @ 3.4.0 has been installed!
Tool Manager: Installing platformio/toolchain-atmelavr @ ~1.70300.0
Downloading  [####################################]  100%
Unpacking  [####################################]  100%
Tool Manager: toolchain-atmelavr @ 1.70300.191015 has been installed!
The platform 'atmelavr' has been successfully installed!
The rest of the packages will be installed later depending on your build environment.

Project has been successfully initialized including configuration files for `vim` IDE.

```

For a first test one can copy a simple blink-led example using the usual `setup()`/`loop()` functions. It's possible to re-use an existing 'sketch' from the Arduino IDE, one just has to add `#include <Arduino.h>` at the top and place it under `src/some-name.cc` or `src/some-name.cpp`.

To compile everything:

```
pio run

```

Which prints:

```
Processing pro8MHzatmega328 (platform: atmelavr; board: pro8MHzatmega328; framework: arduino)
--------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/pro8MHzatmega328.html
PLATFORM: Atmel AVR (3.4.0) > Arduino Pro or Pro Mini ATmega328 (3.3V, 8 MHz)
HARDWARE: ATMEGA328P 8MHz, 2KB RAM, 30KB Flash
DEBUG: Current (avr-stub) On-board (avr-stub, simavr)
PACKAGES:
 - framework-arduino-avr 5.1.0
 - toolchain-atmelavr 1.70300.191015 (7.3.0)
LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 5 compatible libraries
Scanning dependencies...
No dependencies
Building in release mode
Compiling .pio/build/pro8MHzatmega328/src/sos-switch.cc.o
Linking .pio/build/pro8MHzatmega328/firmware.elf
Checking size .pio/build/pro8MHzatmega328/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM:   [          ]   0.4% (used 9 bytes from 2048 bytes)
Flash: [          ]   3.8% (used 1170 bytes from 30720 bytes)
========================= [SUCCESS] Took 0.51 seconds =========================

```

So for this example I created `src/sos-switch.cc` which is compiled to `.pio/build/.../sos-switch.cc.o`.

To upload (flash) the device:

```
pio run --target upload

```

As always, a common pitfall are the permissions of the USB device. For example, on Fedora, my USB2TTL serial device registers as `/dev/ttyUSB0` with read-write permissions for just `root:dialout`. Thus, you have to add your user to the `dialout` group or adjust the permissions by other means.

## Vim Quickfix Mode

For integrating with Vim's quickfix mode a simple makefile is sufficient, e.g.:

```

.PHONY: all
all: build

.PHONY: build
build:
    pio run

.PHONY: upload
upload:
    pio run --target upload

```

Thus, everything is built when `:make` is invoked in Vim, and there one can navigate the quickfix mode as usual.

## Serial Monitoring

An easy way to monitor the serial interface is to use picocom, e.g.:

```
picocom --baud 9600 --echo --imap lfcrlf --noreset /dev/ttyUSB0

```

where:

* `--imap lfcrlf` maps newline to carriage return + newline such that we can just write `Serial.print("multi\nlines\n')` instead of `Serial.print("multi\r\nlines\r\n")` in our program
* `--noreset` tells picocom to **not** clear DTR - without it, when DTR is connected, the Anrdoid device is reset

Of course, one has to terminate picocom when uploading.

---

Alternatively, one can use the PlatformIO monitor command:

```
pio device monitor

```

In contrast to picocom, it doesn't require explicit mapping or DTR handling. However, as with picocom, it must be terminated when uploading/flashing. That means PlatformIO doesn't automatically suspends monitoring when `pio run --target upload` is invoked.

## Closing Remarks

* PlatformIO is currently packaged for Fedora and thus might be directly available in Fedora 36 or so
* the classic Arduino IDE was packaged for Fedora, but isn't available anymore in Fedora 35 because of the big Java package exodus
* there is also a PlatoformIO plugin for VSCode which seems to be quite popular

# Answer
> 30 votes
I use the command-line interface to the `arduino` command.

I run it like this:

```
arduino --upload sketch/sketch.ino --port /dev/ttyUSB*

```

There is a page which describes other command-line tools, like `inotool`. That page also has an example `Makefile`. These alternatives seem enticing, but apparently, as of this writing, none of them work. I'm assuming this is due to some recent changes in Arduino IDE distribution files which they depend on.

Running `arduino` as above is a bit slow, because it has to load Java I guess, but at least it works. There is also an `arduino-builder` command that comes with the Arduino IDE distribution. As of this writing, it was not sufficiently well-documented for me to be able to figure out how to use it. For instance there are no example command lines in the README or in any of the tutorials I came across, and I couldn't figure out how to use it to upload code to the board. However, presumably it is able to give us a faster compile than `arduino`. The README also mentions being able to reuse object files from a previous compile, so there is some make-like functionality.

---

To view serial output I use something like

```
stty -F /dev/ttyUSB* 1000000 raw -clocal -echo
cat /dev/ttyUSB*

```

The number 1000000 should match the number you pass to `Serial.begin()` in your board code. You can also use `screen` if you have a board program which is appropriately interactive, or you can use whatever utility to write directly to the device. By the way, my Due shows up as `/dev/ttyACM0` (rather than `/dev/ttyUSB0` for the Uno).

# Answer
> 11 votes
I would suggest Googling for Makefile projects. I did one a while back for the Blink program, by basically seeing what got generated by the IDE and replicating that in a more general way.

```
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

```

You would need to change `ARDUINO_DIR` at least, to reflect where you installed the IDE. If you use other things like the Wire library you would need to expand it somewhat to compile additional libraries. Again, you can use what the IDE generates itself to guide your changes.

The lines with the leading spaces above would need the **tab** character instead of spaces, as is normal for a Makefile.

# Answer
> 6 votes
What you need is a Makefile. There are a few Makefile projects around for Arduino. Googling for "Arduino Makefile" returns many results including what looks like a good one on Github: https://github.com/sudar/Arduino-Makefile

Compiling from the command line isn't trivial due to the way the Arduino IDE handles libraries.

> The equivalent to the IDE's serial monitor is probably connecting a terminal emulator (e.g. screen) to /dev/ttyACM0, right?

For the serial monitor I would recommend minicom. It is a fully functional terminal emulator (vt102) on the command line.

```
minicom -D /dev/ttyACM0 -b 115200

```

... for example.

# Answer
> 6 votes
# Official CLI tool

The arduino team is developing a **cli** client https://github.com/arduino/arduino-cli

**Announcement**: https://blog.arduino.cc/2018/08/24/announcing-the-arduino-command-line-interface-cli/

You can do almost everything with this, from downloading boards and libraries, to compile and upload scripts. What's missing is the monitoring part (you can use Metamorphic's method using `stty` `cat`, It works!)

The commands are very similar to Metamorphic's answer since this tool is branching out of that one

Instructions in the Github repo and the man page:

```
    $ arduino-cli Arduino Command Line Interface (arduino-cli).

    Usage:   arduino-cli [command]

    Examples: arduino <command> [flags...]

    Available Commands:
      board         Arduino board commands.
      compile       Compiles Arduino sketches.
      config        Arduino Configuration Commands.
      core          Arduino Core operations.
      help          Help about any command
      lib           Arduino commands about libraries.
      sketch        Arduino CLI Sketch Commands.
      upload        Upload Arduino sketches.
      version       Shows version number of Arduino CLI.

```

# Answer
> 2 votes
If you want a fully compatible solution for your arduino project (yes, you can share your project with other people that use just plain Arduino IDE) you need to check amake a tool to simplify the cli of the arduino, I use it with Geany but others are using it with vi, Atom, etc.

It's inspired and the now dead Ino and Arturo projects; please take 5 minutes to test it and please give feedback.

Example use:

```
cd ~/Arduino/Blink/
[move to your arduino project folder]

amake -v uno Blink.ino
[to compile/verify your code]

amake -u uno Blink.ino /dev/ttyUSB0
[to upload your code to an arduino connected via USB]

```

It has some smart glue in there, it can remember the board and file, and even autodetect the usb of the board; so after a successfull "amake -v" command you can do this on the command line and it will work.

```
amake -v
[to compile/verify your code]

amake -u
[to upload your code to an arduino connected via USB]

```

If you use some IDE macros you can craft the compile and upload commands easily, for example using Geany IDE it will became:

* **Compile/Verify:** cd %d; amake -v uno %f
* **Upload:** cd %d; amake -u uno %f

You can get more help running just "amake" or "amake -h" once installed.

Also, it can support **EVERY** board/lib/programmer you have installed/configured in your Arduino IDE, yes, modern board like the Adafuit Trinket M0 / Arduino M0 etc...

Just fire your Arduino IDE, go to the board manager, install support and that's all, jut follow some simple instructions and your are set.

The board you have is not supported? not a problem, detect the fqbn (read the README.md file) and pass it along as the board name.

I'm looking for testers to grow up the number or board aliases and auto detection of the proper USB signatures.

Remember this is a private grown tool, now shared with the public, you know, just a programmer scratching it's itch...

Cheers.

---
Tags: compile
---


title: Capture GRAYSCALE image with ESP32 Cam

text:
# Question
Title: Capture GRAYSCALE image with ESP32 Cam
For one of my projects, I would like to transfer a camera image with the best possible resolution and as many FPS as possible with the ESP32Cam. For this I successfully used the code from https://RandomNerdTutorials.com/esp32-cam-video-streaming-web-server-camera-home-assistant/

A grayscale image would be enough for further processing, if it allows a higher speed.

Problem is, if I set the format to PIXFORMAT\_GRAYSCALE, the ESP only outputs "Camera capture failed".

Are there any other settings to do?

# Answer
> 1 votes
I just tried this with my ESP32Cam with no problems. I would check that you are supplying enough power; I've definitely seen the 'Camera capture failed' when I had power issues. Also, I would try a more recent tutorial on the ESP32Cam; the latest Expressif ESP32 Arduino libraries have AI Thinker ESP32Cam as a device choice. I would try the `CameraWebServer` example in the ESP32 library and see if you still have the problem.

# Answer
> 1 votes
I guess that 1 year later you shouldn't work on this anymore, but for every one that need the grayscale too, here my solution.

For reference I've found here that we can set : s-\>set\_special\_effect(s, 2); Where 2 is grayscale effect.

0 - No Effect 1 - Negative 2 - Grayscale 3 - Red Tint 4 - Green Tint 5 - Blue Tint 6 - Sepia

```
  // Camera init
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
    return;
  }

  sensor_t * s = esp_camera_sensor_get();
  s->set_special_effect(s, 2); // 0 to 6 (0 - No Effect, 1 - Negative, 2 - Grayscale, 3 - Red Tint, 4 - Green Tint, 5 - Blue Tint, 6 - Sepia)

```

---
Tags: esp
---


# Question
Title: Arduino Uno stops accepting command from PS3 Wireless controller?? although it remains connected!
so I was trying to control a bot wirelessly with the help of ps3 controller and USB host shield, i am using Arduino UNO as micro-controller. I was able to connect PS3 controller with Arduino and checked all button presses. It works very smoothly for button presses and shows on serial monitor which button was pressed without any lag. But the issue I am facing is that when I try to call any function on button press, the entire function is getting executed and execution comes back to void loop but Arduino stops accepting commands from ps3. But it shows that PS3 is still connected and the connection isn't lost. I went through different blogs and I found out that some say that issue is with new HOST SHIELD library 2.0 and some say that UNO computation takes time. this is what I have tried.

#define motopinl1 8
#define motopinr1 9
# define motopine1 10

#define motopinl2 11
#define motopinr2 12
#define motopine2 13

#define val 200

void setup() {
Serial.begin(115200);
#if !defined(__MIPSEL__)
while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
if (Usb.Init() == -1) {
  Serial.print(F("\r\nOSC did not start"));
  while (1); //halt
}
Serial.print(F("\r\nPS3 Bluetooth Library Started"));
}

void moveforward()
{

// digitalWrite(motopinl1,LOW);
digitalWrite(motopinr1,LOW);
digitalWrite(motopinl2,LOW);
// digitalWrite(motopinr2,LOW);
analogWrite(motopine1,200);
analogWrite(motopine2,200);
// digitalWrite(motopinl1,HIGH);
//digitalWrite(motopinr2,HIGH);

Serial.println("MoveForward called");
Usb.Task();

}

void moveBackward()
{

digitalWrite(motopinl1,LOW);
//  digitalWrite(motopinr1,LOW);
// digitalWrite(motopinl2,LOW);
digitalWrite(motopinr2,LOW);
analogWrite(motopine1,200);
analogWrite(motopine2,200);
// digitalWrite(motopinr1,HIGH);
//digitalWrite(motopinl2,HIGH);

Serial.println("Movebackward called");
Usb.Task();
}

void moveleft()
{

digitalWrite(motopinl1,LOW);
// digitalWrite(motopinr1,LOW);
digitalWrite(motopinl2,LOW);
// digitalWrite(motopinr2,LOW);
analogWrite(motopine1,200);
analogWrite(motopine2,200);
// digitalWrite(motopinr2,HIGH);
//digitalWrite(motopinr1,HIGH);

Usb.Task();
Serial.println("Moveleft called");
}

void moveright()
{

// digitalWrite(motopinl1,LOW);
//digitalWrite(motopinr1,LOW);
digitalWrite(motopinl2,LOW);
digitalWrite(motopinr2,LOW);
analogWrite(motopine1,200);
analogWrite(motopine2,200);
// digitalWrite(motopinl1,HIGH);
//digitalWrite(motopinl2,HIGH);

Serial.println("Moveright called");
Usb.Task();
}

void stopit()
{
digitalWrite(motopinl1,LOW);
digitalWrite(motopinr1,LOW);
digitalWrite(motopinl2,LOW);
digitalWrite(motopinr2,LOW);
analogWrite(motopine1,0);
analogWrite(motopine2,0);
Usb.Task();
}

void loop() {
Usb.Task();

if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
  if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
   // Serial.print(F("\r\nLeftHatX: "));
    //Serial.print(PS3.getAnalogHat(LeftHatX));
    //Serial.print(F("\tLeftHatY: "));
    //Serial.print(PS3.getAnalogHat(LeftHatY));
    if (PS3.PS3Connected) { // The Navigation controller only have one joystick
      //Serial.print(F("\tRightHatX: "));
      //Serial.print(PS3.getAnalogHat(RightHatX));
      //Serial.print(F("\tRightHatY: "));
      //Serial.print(PS3.getAnalogHat(RightHatY));
    }
  }

  // Analog button values can be read from almost all buttons
  if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
    Serial.print(F("\r\nL2: "));
    Serial.print(PS3.getAnalogButton(L2));
    if (PS3.PS3Connected) {
      Serial.print(F("\tR2: "));
      Serial.print(PS3.getAnalogButton(R2));
    }
  }

  if (PS3.getButtonClick(PS)) {
    Serial.print(F("\r\nPS"));
    PS3.disconnect();
  }
  else {
    if (PS3.getButtonClick(TRIANGLE)) {
      Serial.print(F("\r\nTriangle"));
      moveforward();
      PS3.setRumbleOn(RumbleLow);
    }
    if (PS3.getButtonClick(CIRCLE)) {
      Serial.print(F("\r\nCircle"));
      PS3.setRumbleOn(RumbleHigh);
      moveright();
    }
    if (PS3.getButtonClick(CROSS))
    {
        Serial.print(F("\r\nCross"));
        moveBackward();
    }
    if (PS3.getButtonClick(SQUARE))
    {
      Serial.print(F("\r\nSquare"));
      moveleft();
    }

    if (PS3.getButtonClick(UP)) {
      Serial.print(F("\r\nUp"));
      stopit();
      if (PS3.PS3Connected) {
        PS3.setLedOff();
        PS3.setLedOn(LED4);
      }
    }
    if (PS3.getButtonClick(RIGHT)) {
      Serial.print(F("\r\nRight"));
      if (PS3.PS3Connected) {
        PS3.setLedOff();
        PS3.setLedOn(LED1);
      }
    }
    if (PS3.getButtonClick(DOWN)) {
      Serial.print(F("\r\nDown"));
      if (PS3.PS3Connected) {
        PS3.setLedOff();
        PS3.setLedOn(LED2);
      }
    }
    if (PS3.getButtonClick(LEFT)) {
      Serial.print(F("\r\nLeft"));
      if (PS3.PS3Connected) {
        PS3.setLedOff();
        PS3.setLedOn(LED3);
      }
    }

    if (PS3.getButtonClick(L1))
      Serial.print(F("\r\nL1"));
    if (PS3.getButtonClick(L3))
      Serial.print(F("\r\nL3"));
    if (PS3.getButtonClick(R1))
      Serial.print(F("\r\nR1"));
    if (PS3.getButtonClick(R3))
      Serial.print(F("\r\nR3"));

    if (PS3.getButtonClick(SELECT)) {
      Serial.print(F("\r\nSelect - "));
      PS3.printStatusString();
    }
    if (PS3.getButtonClick(START)) {
      Serial.print(F("\r\nStart"));
      printAngle = !printAngle;
    }
  }
#if 0 // Set this to 1 in order to see the angle of the controller
  if (printAngle) {
    Serial.print(F("\r\nPitch: "));
    Serial.print(PS3.getAngle(Pitch));
    Serial.print(F("\tRoll: "));
    Serial.print(PS3.getAngle(Roll));
  }
#endif
}
#if 0 // Set this to 1 in order to enable support for the Playstation Move controller
else if (PS3.PS3MoveConnected) {
  if (PS3.getAnalogButton(T)) {
    Serial.print(F("\r\nT: "));
    Serial.print(PS3.getAnalogButton(T));
  }
  if (PS3.getButtonClick(PS)) {
    Serial.print(F("\r\nPS"));
    PS3.disconnect();
  }
  else {
    if (PS3.getButtonClick(SELECT)) {
      Serial.print(F("\r\nSelect"));
      printTemperature = !printTemperature;
    }
    if (PS3.getButtonClick(START)) {
      Serial.print(F("\r\nStart"));
      printAngle = !printAngle;
    }
    if (PS3.getButtonClick(TRIANGLE)) {
      Serial.print(F("\r\nTriangle"));
      PS3.moveSetBulb(Red);
    }
    if (PS3.getButtonClick(CIRCLE)) {
      Serial.print(F("\r\nCircle"));
      PS3.moveSetBulb(Green);
    }
    if (PS3.getButtonClick(SQUARE)) {
      Serial.print(F("\r\nSquare"));
      PS3.moveSetBulb(Blue);
    }
    if (PS3.getButtonClick(CROSS)) {
      Serial.print(F("\r\nCross"));
      PS3.moveSetBulb(Yellow);
    }
    if (PS3.getButtonClick(MOVE)) {
      PS3.moveSetBulb(Off);
      Serial.print(F("\r\nMove"));
      Serial.print(F(" - "));
      PS3.printStatusString();
    }
  }
  if (printAngle) {
    Serial.print(F("\r\nPitch: "));
    Serial.print(PS3.getAngle(Pitch));
    Serial.print(F("\tRoll: "));
    Serial.print(PS3.getAngle(Roll));
  }
  else if (printTemperature) {
    Serial.print(F("\r\nTemperature: "));
    Serial.print(PS3.getTemperature());
  }
}
#endif
}```

I haven't connected to bot. I was checking whether function are being executed on button press or not or serial monitor. so there cannot be issue of power supply. problem is PS3 still remains connected, also line of execution returns to void loop, then why it stops further commands. please please do suggest any ideas and methods by which I can solve this problem. thank you.

# Answer
> 0 votes
I found that when you use delay inbuilt function, it completely blocks Arduino from accepting any command, that causes some communication barrier. Although ps3 remains connected, it doesn't accept commands. so all you have to do is to remove all delays from your function and build logic based Millis.

---
Tags: arduino-uno, wireless, networking
---


# Question
Title: Blinking a led using assembly language at different frequencies using two push buttons
I want to blink a led using assembly language and arduino I want the circuit to have a normal state of 5 hz blinking frequency Then use two push buttons to increase or decrease the blinking frequency The up button will increment the blinking frequency by 5 hz step until the led seems to be continuously on While the down button will decrement the blinking frequency by 5 hz step until the normal state again Is this achievable ? And if any one can point me where to start as this the first time i am using assembly language but i am familiar with arduino

# Answer
> 1 votes
Here is one example of how to blink an LED in assembly coding on an Arduino UNO. You can attempt to solve your challenge. If you are stuck, please post the code and the connections and I am sure, you will get help again.

The code is here

```
#define __SFR_OFFSET 0

#include "avr/io.h"

.global main

main:
  sbi   DDRB, 5     ; Set PB5 as output

blink:
  sbi   PINB, 5     ; Toggle PINB
  ldi   r25, hi8(1000)
  ldi   r24, lo8(1000)
  call  delay_ms
  jmp   blink

delay_ms:
  ; Delay about (r25:r24)*ms. Clobbers r30, and r31.
  ; One millisecond is about 16000 cycles at 16MHz.
  ; The inner loop takes 4 cycles, so we repeat it 3000 times
  ldi   r31, hi8(4000)
  ldi   r30, lo8(4000)
1:
  sbiw    r30, 1
  brne    1b
  sbiw    r24, 1
  brne    delay_ms
  ret

```

Link to the project: https://wokwi.com/arduino/projects/290348681199092237

---
Tags: arduino-uno, assembly
---


# Question
Title: Insufficient RX signal delta when using MKR RS485 + Nano, but not Mega
I'm having an issue where an arduino Mega has been used to communicate with an RS485 bus, using an MKR shield \[1\] as a breakout board. When I build it with a Mega, the system works fine. I've torn down and rebuilt multiple times, and it works every time, no troubles.

However when I build it with a nano it does not work - rx is faulty. Devices on the bus can hear the nano, and a response pulse train is sent back correctly, so outgoing communication is fine. However at the RX pin on the nano, the serial signal is present when viewed on an oscilloscope, but ranges between +5V and 4.5V, and the RX LED never flashes.

The layout is a simple wiring, there are no (relevant) external components (there is an LCD, but this works fine), just pin-pin connections.

Why is it the mega seems to work, but the nano not? I'm currently guessing that the /RE pin on the MKR RS485 device (MAX3157 \[2\]) is not being powered properly, and I am seeing the un-amplified serial output? I can't understand why this would be, though, as both the mega and the nano have the same rated max current per-pin.

I've checked the /RE line alone when disconnected, and it is correctly at 5V when not driven, and drives to 0V when the pin is pulled low.

Is there an alternative fix I could use to bring the +5V-4.5V to +5V-0V ? Do I need to have the

\[1\] MKR Shield schematic : https://www.jameco.com/Jameco/Products/ProdDS/2294031Schematic.pdf

\[2\] Max datasheet : https://datasheets.maximintegrated.com/en/ds/MAX3157.pdf

# Answer
> 1 votes
OK, answering myself here. It looks like the output of the shield is unable to drive hard enough against the internal pullups of the nano, for some reason. (Yes, its definitely in input mode, you check check the port values, and it is correct)

Leaving the RX output from the shield to float, it works fine, but if connected to an external pullup resistor, then it does not - and I get the same behaviour as when the RX is tied to the nano.

I've been unable to disable the nano's internal pullups in software for some reason. It looks like I will need to add a buffer to increase the drive current. This is a little irritating as it means another breakout board!

---
Tags: serial, arduino-nano
---


# Question
Title: Reproducing a Fiber Optic Shape Sensor with Arduino?
I want to be able to track the curvature of a human arm as it straightens out and retracts (ex: like live tracking a bicep curl). I don't want to use resistive flex sensors.

I've been trying to find suppliers for this technology demoed here: https://www.youtube.com/watch?v=iAeXp-TpFLU&t=38s

But I cant seem to find anyone who sells directly to consumers. I was thinking about creating a hobbyist level version my own using fiber optic wire, a led, and a light wavelength sensor, using a more powerful Arduino such as the Intel Edison. I have a basic understanding of how this technology works, but I want to learn by attempting to create it.

Is this practical or possible with an Arduino?

if so:

* Are these the correct materials I would need?

if not:

* Why not?
* What kind of equipment would I need to achieve this?
* Is there anywhere to buy this sensor directly?
* Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?

# Answer
> 1 votes
I think nobody here can really give you an answer, if this is possible with an Arduino, since we don't know enough about the technology and the nitty gritty things, that make this a difficult task. So making a hobbyist version won't be easy and maybe really expensive.

In the fiber each bragg grating reflects a bit of the light back. The wave length of this reflected light is dependend on the angle between light and grating. So you get a specific wave length back from each grating, that corresponds to the bending at that particular part of the cable. The task is to measure the many wave lengths, that are being reflected in the fiber, and match them to a particular part of the cable. Since they don't say, how they are solving this, I will mention some ideas here:

1. **Spectral Measurement (Wave length):**
    * From the video I guess, that they use white light to shine into the cable. The gratings will only reflect the wave lengths from this spectrum, that satisfy Bragg's law due to bending angle. You have to measure the wave length directly with a spectrometer. Mostly this is another grating, that will seperate the wave lengths spatially, so that you can measure the spectral structure by using a spatial sensor, for example a camera or a line sensor. You would have to correct for different wave length sensitivities of the camera.
    * Maybe they are only using a laser with 1 wave length. Then the bending would result in a change in intensity reflected from that grating. If you can seperate the signals from the different gratings good enough, you would be able to measure just the change in intensity, which would be easier, since you basically need just a photo transistor or similar for that wave length. (In this case you would need to calibrate the sensor each time as a straight cable and ensure, that the measurement is fast enough for the expected movement).
2. **Matching of signals to each part of the cable:** Here I guess, that they use a time-of-flight sensor, because I cannot think of anything else without further information. This is a really difficult problem, because most available sensors are not sensible enough for measuring quarter inches without being cheap in the first place. You will likely spend a lot of money for a sensor like this. And you building an own time-of-flight sensor with the wanted sensitivity may be as difficult as building the whole device in the first place.
3. **Needed Parts:** Also you will need the fiber itself, which is - as stated - not a normal glas fiber, which you can by everywhere. It is most likely a custom build and you will pay a lot of money, to get one of these. The light source is dependend on the spectral measurement above. For a white light it is important, that all wavelength should have as equal intensity as possible. You would also have to account for the spectral absorption and the overall absorption in the fiber, which restricts the sensitivity and possible lengths.

> Is there anywhere to buy this sensor directly?

Most likely not. In the videos it seems like a device, that was developed by the NASA for a specific application. The video is a proposal for other companies to learn from the NASAs development, so the device is not consumer ready. But you might be able to get a paper about this device by searching the internet for it or by asking the NASA directly. This paper would contain way more information about the device as the videos.

All in all this would be an extremely difficult task. Since you came here (a simple Q&A site) with this difficult question, I think, that you are not really ready for this big of a task. Most likely even the developers at the NASA needed long and much money for this.

---

> Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?

I would propose to build a string of bending strips, which change their resistance according to the bending angle. You can use multiple strips for getting multiple readings for different parts of the human arm. With each strip you build a voltage divider and do an analog measurement. With a bit of calibration you should be able to measure the curls.

# Answer
> 1 votes
Well. is not impossible and the accepted answer is quite dark.

To use a FBG with an Arduino (I advise a ESP32) one needs to have a light\* emitter and also a light receiver for the same end of the fiber. To achieve this, is used an unidirectional optical circulator coupled with both emitter, receiver and the FBG.

The difficulty is in finding those components suitable or sensing and at the same time inexpensive. That said, here https://europepmc.org/article/pmc/6651577 is an article depicting a portable FBG interrogator using a raspberry pi. The Pi uses a 120Mhz MCU , so a ESP32 MCU is also a suitable option.

in sum, it can be done quite easily.

---
Tags: sensors, edison
---


title: Can I use STL on an Arduino Uno?

text:
# Question
Title: Can I use STL on an Arduino Uno?
I started using an Arduino Uno days ago. I'm an experienced C++ dev and I'm kind of confused.

Is the Arduino compiler different than a C++ one? What C++ version does Aruidno Uno use? Why it doesn't it support STL? Is it possible to use STL?

Also, can I configure their cpp file and use my own main function? The loop / setup thing really does annoy me. Thanks!

# Answer
> 2 votes
Yes, there are STL implementations for the Arduino Uno (check the library manager). Note that some of them are unsupported and/or outdated quite a bit. The downside of using STL on the Arduino is also that these classes may use to much memory. Because of it's very limited memory (only 2kb), dynamic memory allocation is quite risky, as memory fragmentation will quickly cause the program to crash.

The Arduino build system uses a pre-build step around the ino files that remove a lot of pain locating header files and setting up build paths from the user. This is a bit confusing at first for an experienced C++ programmer, but it simplifies things a lot, particularly when it comes to using different libraries. This build step automatically locates the include paths for all .h files referenced in the .ino. The system requires that you declare the `loop()` and `setup()` methods, but what you do with them is up to you. You can leave either of them empty, or never return from the loop function, calling into whatever main function you want to use.

As a side note: There are other C++ compiler features that are disabled or unsupported on the Uno because they would make the code to big. These include dynamic type casting using `dynamic_cast<>` and exception handling.

---
Tags: arduino-uno, stl
---


title: ESP32 heap problem

text:
# Question
Title: ESP32 heap problem
I wrote a simple C++ program (just main.cpp and corresponding platform.io files & libraries) to get BME280 sensor readings. It worked fine until I decided to use good programming practices, using header files and separating the read function from main.cpp, I get a heap error, stated below:

```
CORRUPT HEAP: Bad head at 0x3ffb8444. Expected 0xabba1234 got 0x3ffb84c4
abort() was called at PC 0x40083b99 on core 1

ELF file SHA256: 0000000000000000

Backtrace:
0x400857f0:0x3ffb1aa0
0x40085a65:0x3ffb1ac0
0x40083b99:0x3ffb1ae0
0x40083cc5:0x3ffb1b10
0x400d90a3:0x3ffb1b30
0x400d55bd:0x3ffb1df0
0x400d5558:0x3ffb1e40
0x4008a0f1:0x3ffb1e70
0x40081dee:0x3ffb1e90
0x40083a91:0x3ffb1eb0
0x4000bec7:0x3ffb1ed0
0x400e89b5:0x3ffb1ef0
0x400d13ab:0x3ffb1f10
0x400d0f75:0x3ffb1f30
0x400d3ba9:0x3ffb1fb0
0x40086a75:0x3ffb1fd0

Rebooting...

```

Any ideas on that?

By the way, I also used pointers for both the function and the variable passed to it, to no avail.

I also tried a series of combinations with the libraries I am using - Adafruit BME280 and Adafruit Unified Sensor.

Going back to having all the code in one file works...

Thanks

My code:

```
//main.cpp
#include <sensor_readings.h>
#include <settings.h>

void refresh_readings();  // Declare in the header so that the compiler knows about it before it is called in loop()

Adafruit_BME280 bme; // I2C

void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  Serial.begin(9600);
  bool status;

  // (you can also pass in a Wire library object like &Wire2)
  status = bme.begin(0x76);
  if (!status) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }
}

void loop() {
  void (*fcnPtr)(Adafruit_BME280){ &refresh_readings };
  (*fcnPtr)(bme);
  //refresh_readings(bme);
  delay(4000);
}

;platformio.ini
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
lib_deps =
    Adafruit_Sensor
    adafruit/Adafruit Unified Sensor@1.1.4
    adafruit/Adafruit BME280 Library@^2.2.2
upload_port = /dev/cu.SLAB_USBtoUART
monitor_port = /dev/cu.SLAB_USBtoUART
monitor_speed = 9600

//sensor_readings.cpp
#include <sensor_readings.h>
#include <settings.h>

void refresh_readings(Adafruit_BME280 bme) {
  float f_temperature;
  float f_humidity;
  float f_pressure;
  float f_altitude;

  digitalWrite(LED_BUILTIN, HIGH);

  f_temperature = bme.readTemperature();
  f_humidity = bme.readHumidity();
  f_pressure = bme.readPressure() / 100.0F;
  f_altitude = bme.readAltitude(SEALEVELPRESSURE_HPA);

  // Temperature

  Serial.print(f_temperature);
  Serial.println(" °C");

  // Humidity
  Serial.print(f_humidity);
  Serial.println(" %");

  // Pressure
  Serial.print(f_pressure);
  Serial.println(" hPa");

  // Appx altitude
  Serial.print(f_altitude);
  Serial.println(" m");

  digitalWrite(LED_BUILTIN, LOW);
  Serial.println("------------");
}

//sensor_readings.h
#ifndef SENSOR_READINGS_H

    #define SENSOR_READINGS_H

    #include <Arduino.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BME280.h>

    #define SEALEVELPRESSURE_HPA (1013.25)

    void refresh_readings(Adafruit_BME280 bme);

#endif

//settings.h
#ifndef SETTINGS_H
    #define SETTINGS_H
    #define LED_BUILTIN 2   // This is valid for my devkit
#endif

```

# Answer
There's a couple problems with your code.

```
void refresh_readings();  // Declare in the header so that
                          // the compiler knows about it
                          // before it is called in loop()

```

This is a lie! Don't tell your compiler there's a `refresh_readings` function that takes no arguments when you haven't defined one. Remove that line, you already have the function declaration in your header.

```
void (*fcnPtr)(Adafruit_BME280){ &refresh_readings };
(*fcnPtr)(bme);

```

This is just a very convoluted way of typing:

```
refresh_readings(bme);

```

So just use the normal function call syntax.

The main issue as far as I can tell though is that you are copying the `bme` object when passing it to the readings function, which is not advisable in general for this sort of object (they represent a piece of hardware that you can't really copy). That class in particular has a bunch of pointer members, a destructor that deletes them, but no copy constructor as far as I can tell, which is a bad thing.

Change your function to this signature (both in the header and the C++ file):

```
void refresh_readings(Adafruit_BME280& bme);
//                 pass by reference ^

```

And use the normal call syntax (`refresh_readings(bme);`).
> 1 votes

---
Tags: esp32, heap
---


# Question
Title: How to address arbitray leds (WS2812B) in an already defined leds array?
I want to address the first and last three pixels of a 9 pixel strip and apply a gradient to them using FastLED. I can successfully address them but the colors displayed are not correct. Is there something I'm overlooking or misunderstand about the way FastLED works?

```
#include <FastLED.h>

// the whole strip
#define NUM_LEDS 9

#define LED_PIN 6

CRGB leds[NUM_LEDS];

// Define the indexes of the first and last 3 indexes of a 9 pixel strip
int customLeds[6] = {0,1,2,6,7,8};

// My Palette
DEFINE_GRADIENT_PALETTE (heatmap) {
  0, 255, 0, 0,      // Red
  128, 0, 255, 0,    // Green
  255, 0, 0, 255     // Blue
};

CRGBPalette16 myPalette1 = heatmap;

void setup() {
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(20);
}

void loop() {

  for (int i = 0; i < (sizeof(customLeds)); i++) {
   // Each i led get the correct color given their place in the array  - 0, 42.5, 85, 127.5, 170, 212.5, 255
    leds[customLeds[i]] = ColorFromPalette(myPalette1, (i * (255 / sizeof(customLeds))), 255, LINEARBLEND);
  }

  FastLED.show();

}

```

# Answer
So here is the answer I came up with:

```
#include <FastLED.h>

// the whole strip
#define NUM_LEDS 9

#define LED_PIN 6

CRGB leds[NUM_LEDS];

// Define the indexes of the first and last 3 indexes of a 9 pixel strip
bool customLeds[9] = {1, 1, 1, 0, 0, 0, 1, 1, 1};
int customLeds_num = 6;

// My Palette
DEFINE_GRADIENT_PALETTE (heatmap) {
  0, 255, 0, 0,      // Red
  128, 0, 255, 0,    // Green
  255, 0, 0, 255     // Blue
};

CRGBPalette16 myPalette1 = heatmap;

void setup() {
  FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(5);

}

void loop() {

  FastLED.clear();

  //  Keep track of how many leds have been lit
  int customLedIndex1 = 0;

  for (int i = 0; i < NUM_LEDS; i++) {
    // Each i led get the correct color given their place in the array  - 0, 42.5, 85, 127.5, 170, 212.5, 255

    //lights a specific pixel only if it's in the customLeds truth table
    if (customLeds[i]) {
      // works out where on the gradient a specific pixel is
      leds[i] = ColorFromPalette(myPalette1, (customLedIndex1 * (255 / 5)), 255, LINEARBLEND);

      //increments the index for the next pixels value on the gradient
      customLedIndex1++;

    }

  }

  FastLED.show();

  customLedIndex1 = 0;

}

```

The solution involved using a boolean array that indicates which leds needed to be on (true / 1) and which off (false / 0) and then create a separate index (customLedIndex) which counted how many of the leds where lit so they could receive the correct color corresponding to their 'place' in the palette
> 1 votes

---
Tags: arduino-uno, ws2812
---


title: passing variable to function

text:
# Question
Title: passing variable to function
I have the following code to turn on or off led. I would like to modify the function to pass the pin as well. what should X be substituted with?

```
#define BIN_LED 2
#define PIN_LED 3

void led(uint8_t x, bool on) {
 digitalWrite(x, on ? LOW : HIGH);
}

void setup() {}

void loop() {
 led(BIN_LED, true);
 delay(1000);
 led(BIN_LED, false);
 delay(1000);
}

```

# Answer
You've done it. All that's left is to specify a data-type 'X' in the function declaration, just as you've already done for 'on'. 'uint8\_t' would be a reasonable choice.
> 3 votes

---
Tags: arduino-ide
---


# Question
Title: Initializing an object as class member resulting in linking error?
I'm a little dumbfounded as to why this isn't working. I keep getting the following linker error:

```
In file included from src\ac.cpp:1:0:
src/ac.h:9:21: error: expected identifier before numeric constant
 #define RECEIVE_PIN 0
                     ^
src/ac.h:14:26: note: in expansion of macro 'RECEIVE_PIN'
     static IRrecv irrecv(RECEIVE_PIN);
                          ^
src/ac.h:9:21: error: expected ',' or '...' before numeric constant
 #define RECEIVE_PIN 0
                     ^
src/ac.h:14:26: note: in expansion of macro 'RECEIVE_PIN'
     static IRrecv irrecv(RECEIVE_PIN);
                          ^
*** [.pio\build\esp32cam\src\ac.cpp.o] Error 1
*** [.pio\build\esp32cam\src\main.cpp.o] Error 1

```

I am simply trying to initialize the IR receiver with `static IRrecv irrecv(RECEIVE_PIN);`, but the compiler is refusing to link it together.

```
#ifndef _AC_H_
#define _AC_H_

#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>

#define RECEIVE_PIN 0

class IR
{
public:
    static IRrecv irrecv(RECEIVE_PIN);
    static decode_results results;
    void initRecv();
    bool waitForIR();
};

extern IR ir;

#endif

```

If I do `static IRrecv irrecv;` it successfully compiles, but I'm unsure if I can pass the pin variable after the fact.

# Answer
Static data members have to be defined *outside* the class declaration. The initialization happens at the point where the members are defined:

**file ac.h:**

```
//...

class IR
{
public:
    // Static data members are declared only:
    static IRrecv irrecv;
    static decode_results results;
    void initRecv();
    bool waitForIR();
};

```

**file ac.cpp:**

```
#include "ac.h"

#define RECEIVE_PIN 0

// Definitions and initializations of static data members:
IRrecv IR::irrecv(RECEIVE_PIN);
decode_results IR::results;

```
> 2 votes

---
Tags: variables, compilation-errors, linker
---


# Question
Title: Serial Port not recognized by Arduino IDE
I’m attempting to connect with a Adafruit Huzzah Feather ESP8266 board. I’m running a 2018 mbp with Mojave. I loaded the Silabs driver (CP210) to connect with the onboard UART on Huzzah board. I got the Arduino IDE 1.8.8 installed and loaded the 2.5.0 ESP8266 library (I also tried library 2.4.2).

The serial port appears in the IDE (SLAB\_USBtoUART). It also appears when I run the /dev/tty.\* command and in About this Mac. From the IDE when I try to Get Board Info. Nothing. I get the message “Native serial port, can’t obtain info”. Everything seems good, except nothing from the IDE. I pulled up CoolTerm, set it the port and hit the reset on the Huzzah. I see data after hitting reset.

I run the Huzzah board from a powered USB hub through one of the USB-C ports. Tried different combinations, no luck.

I have a very old WIn7 machine, loaded everything like on my mbp, there I can get board info. I would run the IDE on it, except the machine is sooo slow. I would very much like to get it working on my mac. It seems so close, but no cigar.

# Answer
Download usb port driver from the link below http://www.wch-ic.com/downloads/CH341SER\_EXE.html
> -1 votes

---
Tags: esp8266, arduino-ide, mac-os
---


# Question
Title: ESP32 - `Brownout detector was triggered ` upon Wifi begin
I'm Using an ESP32 - NodeMCU. One of the MCU's is acting weird upon boot, while at start I thought it was something to do with its sleep cycle. But, it seems that even on a minimal code as shown below, I get this message at the Serial output: `Brownout detector was triggered`

```
void setup()
{
  Serial.begin(9600);
  Serial.println("\nBegin");
  Serial.println(bootCounter);

  WiFi.begin("Xiaomi", "guy");

  while (WiFi.status() != WL_CONNECTED && millis())
  {
    delay(200);
    Serial.print(".");
  }
}

```

Edit 1: attaching MCU picture.

Can someone please explain ?

Edit 2: A workaround stop alerting

# Answer
Those boards have an inherent weakness in that they don't provide enough decoupling capacitance for the module.

Not all modules are quite the same, and some have more internal decoupling than others (not by design, just due to component tolerances).

I have found that unless you provide adequate decoupling of your own some modules work just fine and some don't. Some brown-out and some fail to flash.

For all my designs now I always provide both a 100nF *and* an 10uF capacitor right at the power pins of the module. However those boards don't provide anything like that.

You need to modify the board to add a capacitor (about 10uF) directly across the power and ground pins (pins 1\[ground\]-2 \[3.3v\]) of the ESP32 module. I like to use an 0805 MLCC capacitor as they fit nicely across the pins and are discrete, but they can be tricky for a novice to solder. So an electrolytic through-hole capacitor can be a simpler proposition (make sure you get the polarity right).
> 6 votes

# Answer
I had the same problem. I found that solution in a forum on Github, which helped at once:

```
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
void setup(){
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector

```
> 4 votes

# Answer
I came across the same issue on my experiments.

What sorted the issue for me was powering the ESP-32\_CAM from the 5V pin on the programmer. Take the cable off the 3V and plug it into the 5V pin on the cam. Then use the jumper on the programmer to select the 5V.

I hope this makes sense and that it helps someone.
> 3 votes

# Answer
After some Tests i recognized, that the problem is between the miro-USB-connector to the Vin Pin. So i soldered a thin wire from Pin 5 of the USB-Connector (5V-Pin) to the Vin-Pin of The Dev-Board. And it works without Problems.
> 1 votes

# Answer
Swapping USB cable solved my issue of continuous brownout detector triggering.

I tried some above answers. Disabling brownout detector as suggested by Vahe Arakelyan helped on Blink sketch, but WiFi including sketches would still fail to run.

Then started to suspect HW and power failure. Did not soldering pins as suggested by user73106, but this made me notice voltage fluctuation. So swapped USB cable and this seemed to keep the voltage steady enough for good operation... It looks like some cable/connector fault may limit the current to allow some low power sketch to run but to fail on more current drawing sketch.
> 1 votes

# Answer
It could even be a software issue, i.e Code, if you use LedCWrite without its setup then it causes this issue.
> 0 votes

---
Tags: wifi, esp32
---


title: Arduino timers. How they work

text:
# Question
Title: Arduino timers. How they work
**Explain this line in simple words.**

```
TCCR0B=TCCR0B&0b11111000|0x01;

```

As the variuos arduinos have different chips. They also have different timers and different pins which use them.

Lately i want to rewrite a code(Arduino Uno) to make it work on a Arduino Micro.

I need to understand how this works in simple words. I normally write web based code(javascript,php...). Just lately i started writing in c++ or a "simplified" c++ in the arduino ide. It's not that hard. But some specific parameters are hard to understand for me. Shortcuts like the following.

```
TCCR0B=TCCR0B&0b11111000|0x01;

```

What does that?

```
TCCR0B

```

`TCCR` = Prefix for timers. Correct?

`0` = Timer1 or 0 call it however you want.

`B` = **What is A,B,C and sometimes D for?** What does this?why in that code is the programmer using B and not A,C or D

`TCCR0B=` Timer 0 B is equal to:

`TCCR0B&` **if Timer 0 B return True .. exists "&" ?**

`0b11111000` **What is this?** i already asked this and the answer was something like "clears the low-order 3 bits". Like i said, i'm not very familiar with c++, bits and other stuff regarding the arduino. I now less about the various chips and also about how they implemented the various parameters from arduino ide to work with those chips. I know that i have here 8 values that i can change from 0 to 1. What does those values change relative to the timer. Please think of me as a 6 year old.

`|0x01;` I got this... it sets the prescaler... 1,8,32.. some timers have differnet values... no problem. I need it at 1.

# Answer
First I'll tackle what

```
TCCR0B=TCCR0B&0b11111000|0x01;

```

means from a pure programming perspective:

Let's break it down into parts:

```
TCCR0B = TCCR0B & 0b11111000 | 0x01;

```

`TCCR0B` is a register. It could be any variable really - it's just "a value" in this context. Just because it happens to control one of the timers is besides the point.

`0b11111000` is a binary representation of a value. It's the same as the hexadecimal number `0xF8`. F is 15. 15 in binary is 1111. 8 is 8 in both hexadecimal and decimal. 8 in binary is 1000. Put the two together and you have 11111000. Incidentally, in decimal that is 248.

`0x01` is hexadecimal for 1 in decimal - it's also 1 in binary.

Between them are *bitwise* operators - `&` is a bitwise `AND` operation, and `|` is a bitwise `OR` operation. `AND` calculates which bits in a pair of binary numbers are both on, and `OR` calculates which bits in a pair of binary numbers are on in either of the numbers.

So take the first one first. Say the `TCCR0B` register contains the value `0x6F`, which is 157 in decimal, or 01101111 in binary. The first operation is to `AND` that with 11111000:

```
01101111
11111000 AND
--------
01101000

```

You can see that the last three bits of the value have been cleared because they aren't 1 in both the left and right operands to the `&` operator.

Ok, so the next operation is to `OR` it with 0x01:

```
01101000
00000001 OR
--------
01101001

```

Effectively the two operands have been overlaid on each other and any bits that are set in either operand will be reflected in the result.

So finally the value is then stored in `TCCR0B`.

In summary that specific operation *clears the lower three bits then sets the lowest bit* of TCCR0B.

Now what that actually means with respect to what the TCCR0B register does can be gleaned from the datasheet for the chip. For instance, take the ATMega328P chip from the Arduino UNO board. Section 14.9.2 "TCCR0B – Timer/Counter Control Register B" of the datasheet describes that register in detail. The bit-wise overview looks like this:

Those bits all correspond 1:1 to the binary bits from above in the same order. So the first stage, clearing of the lowest three bits, sets CS02, CS01 and CS00 to 0. The second stage, ORing 0x01, then sets CS00 to 1.

The datasheet goes on to tell you what those mean:

> * Bits 2:0 – CS02:0: Clock Select
>
> The three Clock Select bits select the clock source to be used by the Timer/Counter.

And a table to show the different meanings of the possible values:

The value that has been masked and created for those three bits is, of course, 001, which in that table is "CLK I/O / (No prescaling)", which is the timer running at the frequency of the IO clock. If you were to set those bits to 010, you'd get "CLK I/O / 8 (From prescaler)". So your masking would change to:

```
TCCR0B = TCCR0B & 0b11111000 | 0x02;

```

Or more explicitly so you can see the bits easier:

```
TCCR0B = TCCR0B & 0b11111000 | 0b010;

```

As to what the "A" and "B" mean (TCCR0A and TCCR0B), there are two registers that are used to control the timer. They each serve a different purpose. TCCR0A has bits that control PWM, and TCCR0B has bits that control the timer itself.

Not to be confused with OCR0A and OCR0B which are two separate numeric values that are compared to the timer's counter value TCNT0 to provide two separate PWM outputs (OC0A as Uno pin D6, and OC0B as Uno pin D5) synchronised from the same timebase. (See sections 14.9.4 OCR0A – Output Compare Register A and 14.9.4 OCR0B – Output Compare Register B in the datasheet)
> 12 votes

# Answer
To add to Majenko's very thorough and excellent answer (which I can't yet upvote because I'm very newbie): Let's try to hone in on the line of code you need:

```
TCCR0B=TCCR0B&0b11111000|0x01;

```

On that particular Ardiuno, TCCR0B is the register that controls the rate of that particular timer. More specifically, the lowest 3 bits (the last in the 8-bit value) control the prescaler. The manufacturer labels those as CS02, CS01, and CS00. The combination of 1s and 0s in those three bits determines if the clock time is scaled or not, and by how much (or even if there is an external clock source). The reproduced table 14-9 will tell you how much the clock is "slowed down". This lets you create a 1Hz (1-second) timer, for example, rather than the 16Mhz (or whatever your particular board runs at) by scaling down how fast the timer "ticks". If you google "Arduino hardware timer calculator" or similar, you can find very helpful tools to help you set the clock frequency you want. *Do that,* since there are dangers to setting the wrong values, and your compiler may not catch what can be a serious error.

I only learned about hardware timers after exploring Arduino for a few years. Turns out they are very, very useful!
> 2 votes

# Answer
The answer, at high level, is: each bit (or group of bits) in a register is, in practice, like a knob that can configure certain parts of the HW. For each peripheral you want to control, you have to understand the block diagrams, the related knobs and in which registers those knobs are located. Sometimes there are multiple (almost) identical instances of a certain HW block and in the ATMega case these instances are often addressed with letters. So registers that have almost identical names, apart from A, B, C, are basically identical, but each of them will affect a separate instance of a certain peripheral. Depending on which pins or interrupt you want to use, you can choose the specific instance of a certain peripheral. You should check the ATMega328p programmer's manual (it's 2k pages, but it's easy to find the desired section.)
> 1 votes

# Answer
I understand your question is not about c++ and bit manipulation.

It's not about "Arduino" neither, because your code line does only make sense for a certain avr microcontroller with a register named `TCCR0B`.

Sure, some arduinos are based on such microcontrollers and the c++ compiler used in the arduino toolchain allows access to those hardware registers via their names used in the datasheets.

Details however are beyond "Arduino" and should be looked up in the corresponding controller datasheet.
> -1 votes

---
Tags: timers
---


# Question
Title: Send same telemetry data to two different serial ports?
I'm using a Teensy 3.5 to control a wall-following robot. The robot sends telemetry to my PC via two independent ports - Serial1 & Serial. Serial is the normal USB port, used when I direct-connect to the robot for troubleshooting, etc. Serial1 is tied to an HC-05 Bluetooth transceiver and it is used to acquire telemetry remotely.

I have to send telemetry to both ports, because I never know which (or either, or both) port(s) are actually active at any one time, so I wind up with lines like the following all over my code:

```
Serial.printf("\nChecking for MPU6050 IMU at I2C Addr 0x%x\n", MPU6050_I2C_ADDR);
Serial1.printf("\nChecking for MPU6050 IMU at I2C Addr 0x%x\n", MPU6050_I2C_ADDR);

```

needless to say this gets old after a while, and is error prone (I might edit one line and forget to copy/paste it to the other one). What I would really like to do is create a function that would accept a printf-style string and send it to both ports, but I'm having trouble figuring out how to do that.

I have tried playing around with strcpy and strcat without much success:

```
  char quotestr[] = "\"";
  char hellostr[] = "hello";
  char instr[] = "%s\n, hellostr";
  char deststr[40];
  memset(deststr, 0, sizeof(deststr));
  strcat(deststr, quotestr);
  strcat(deststr, instr);
  strcat(deststr, quotestr);
  Serial.printf("quotestr = %s\n", quotestr);
  Serial.printf("instr = %s\n", instr);
  Serial.printf("deststr = %s\n", deststr);
  Serial.printf(deststr);

```

But the output is wrong because the '\n' gets interpreted as a CRLF pair even though it is in a string with double-quotes.

```
quotestr = "
instr = %s
, hellostr
deststr = "%s
, hellostr"
"
, hellostr"

```

It seems like there ought to be a way to do this easily, but I can't figure it out. Any help would be appreciated.

TIA,

Frank

# Answer
> 4 votes
you can write a simple T output using the base class `Print`. The standard Arduino `Print` class doesn't have `printf` but from your code it looks like the Teense core has `printf` in `Print`.

```
class TeePrint: public Print {

  Print &out1;
  Print &out2;

public:

  TeePrint(Print &_out1, Print &_out2) : out1(_out1), out2(_out2) {}

  virtual size_t write(uint8_t b) {
    out1.write(b);
    out2.write(b);
    return 1;
  }

};

TeePrint log(Serial, Serial1);

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

  log.printf("abcd %d %s", 1234, "xyz");
}

void loop() {

}

```

# Answer
> 0 votes
The simplest method is a variadic macro:

```
#define PRINTF(...) do { Serial.printf(__VA_ARGS__); Serial1.printf(__VA_ARGS__); } while(0)

```

Then you can just use `PRINTF("foo: %d", bar);` and it will expand it out to the two printfs for you.

---
Tags: serial, teensy
---


# Question
Title: Continuous servo motor won't stop rotating
I want to use Bluetooth to control my continuous servo motor to rotate 360° once, and I used MIT app inventor for the UI to control it.

My continuous servo motor won't stop rotating even though I tried `myservo.write(90)`.

I was wondering if anything is wrong with my hardware, or whether the problem is in my code as I am a beginner at coding and I put different functions together that I found on the internet (I was trying to make the MIT to send letters to the Arduino code where the letter would activate a command to the servo).

Here's my code:

```
#include <SoftwareSerial.h> // TX RX software library for bluetooth

#include <Servo.h> // servo library
Servo myservo; // servo name

int bluetoothTx = 10; // bluetooth tx to 10 pin
int bluetoothRx = 11; // bluetooth rx to 11 pin

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup() {
  myservo.attach(9); // attach servo signal wire to pin 9
  // Setup usb serial connection to computer
  Serial.begin(9600);
  myservo.write(90);  // set servo to mid-point

  // Setup Bluetooth serial connection to android
  bluetooth.begin(9600);
}

void loop() {
  // Read from bluetooth and write to usb serial
  if (bluetooth.available() > 0 ) { // receive number from bluetooth
    int servopos = bluetooth.read(); // save the received number to servopos
    Serial.println(servopos); // serial print servopos current number received from bluetooth

    char c = Serial.read();
    if (c == 'a') {
      myservo.write(180);
      delay(1000);
      myservo.write(90);
    }
    else if (c == 'b') {
      myservo.write(90);
    }
  }
}

```

Would be really great if you could help

# Answer
A "continuous servo" is one in which it stops rotating when the angle is set to 90 degrees, rotates forward when the angle is more than 90 degrees and rotates in reverse when the angle is less than 90 degrees. The further from the angle of 90 degrees, the faster the continuous servo will rotate.

You can not control the angle of a continuous servo. There is no feed back to know when it has rotated, say, 360 degrees.

You can only guess at the timing and send a command like "go to angle 100" to start rotating a continuous servo slowly forward then send a command like "go to to angle 90" to stop it after your "guessed at" time of how log it took to travel, say, a quarter the way around has elapsed.

Here is a similar Stack Exchange question where continuous servos are discussed as well.
> 3 votes

---
Tags: bluetooth, continuous-servo
---


# Question
Title: IRremote and PCM sound libraries interfering
I have a simple sketch which sends IR codes, plays a sound and toggles an LED when you press a button and toggles another LED when it receives that code. The idea is that I have two Arduinos with this same sketch and when you press the button on one, the LED is toggled and so is another LED on the other Arduino. This program works as intended when the sound is not included.

Here is the sketch:

```

#include <IRremote.h> // For the IR transmition and receiving
#include <PCM.h> // For the audio output

IRsend irsend; // Setup the IR transmitter
const int receiver = 8; // Initialize pin 13 as recevier pin.
IRrecv irrecv(receiver); // Create a new instance of receiver
decode_results results;

// Declare arrays to hold sound notes to play
const unsigned char gunShot[] PROGMEM = {}; // There is a huge list of numbers in this array, but I removed them to make the code easier to read

const unsigned char gunClick[] PROGMEM = {}; // There is a huge list of numbers in this array, but I removed them to make the code easier to read

// declare consants
const int button = 13;
const int greenLight = 7;
const int yellowLight = 2;
const int timeBetweenTransmittion = 800; // At least 800 milliseconds between two transmissions
// The speaker is fixed on pin 11

// declare variables
bool toggleGreen = true; // Bool variables to toggle the lights
bool toggleYellow = true;
long int previousTransmittion = 0; // Long int to store the timestamp in millis of the previous transmission

// put your setup code in here, to run once:
void setup()
{
  pinMode(button, INPUT_PULLUP); // Setup the button with an internal pullup resistor
  Serial.begin(9600);
  irrecv.enableIRIn(); // Enable the receiver
  Serial.println("start");
}

// put your main code in here, to run repeatedly:
void loop() {
  if (not digitalRead(button) && millis() > previousTransmittion + timeBetweenTransmittion) // If the button is pressed and it's been enought time since the last transmittion
  {
    Serial.println("send!");

    // Different orders of these lines of code were tried:

    //startPlayback(gunShot, sizeof(gunShot)); // Play shot before sending the code and enabling the receiver (play command 1 for reference)
    //delay(250);

    irsend.sendNEC(1367857, 32); // Send the code

    //startPlayback(gunShot, sizeof(gunShot)); // Play shot between sending the code and enabling the receiver (play command 2 for reference)
    //delay(250);

    irrecv.enableIRIn(); // Sending ir stops the receiver so start the receiver again

    startPlayback(gunShot, sizeof(gunShot)); // Play shot after sending the code and enabling the receiver (play command 3 for reference)
    delay(250);

    // Toggle the yellow light
    digitalWrite(yellowLight, toggleYellow);
    toggleYellow = not toggleYellow;

    previousTransmittion = millis(); // Set the record for latest transmittion to the currnt time
  }

  if (irrecv.decode(&results)) // If we have received an IR signal
  {
    Serial.println (String(results.value, HEX)); // Display HEX results
    if (String(results.value, DEC) == "1367857") // If the code is the right one
    {
      Serial.println("correct code");

      // toggle the green light
      digitalWrite(greenLight, toggleGreen);
      toggleGreen = not toggleGreen;
    }
    irrecv.resume(); // Prepare the receiver for the next code
 }
}

```

// End of sketch

As you can see, I tried putting the play sound line before, between and after the IR transmission lines of code. The delays are there so I can see if the audio starts to play and stops or if it just never plays. Here is what I found from all the combinations:

* In all the combinations (play command 1, 2 and 3), The IR receiver worked as intended if used BEFORE ever pressing the button.
* None of the combinations stop the loop as if I put \<Serial.println("loop");\> at the start of the loop() routine, it continues to print "loop", regardless of what I do.
* In play command 1 and 2, the sound plays when I press the button, but stops after the 250ms delay. Once the button has been pressed once, it doesn't do anything when I press it again (doesn't print "send!" or toggle the light). The receiver receives one more code after pressing the button, but always prints the code "2a", regardless of what button on my tv remote I press (the tv remote usually prints a 6 character hex code). After it prints "2a", it doesn't receive any more codes.
* Play command 3 plays the full sound and sends the right code, and allows me to do it as many times as I want (the button still works after pressing it more than once). However the receiver still no longer works after the first time I press the button. It doesn't receive "2a" the first time after pressing the button unlike the first 2.

I am using the libraries IRremote by shirriff, z3t0 and ArminJo (VERSION 2.6.1) and PCM by David Mellis, Michael Smith (VERSION 1.0.0) (http://highlowtech.org/?p=1963). I don't know if there is a simple way around this problem or if these libraries just cannot be used together.

I have the speaker on pin 11.

If you need anything clarifying please ask. Any help would be appreciated, thanks in advance.

# Answer
The PCM library uses timer 1, and timer 2. The IRremote library uses timer 1. So they both need timer 1. So there's a conflict. So you can't use both libraries at the same time, unfortunately.
> 1 votes

# Answer
It works for me if i put a delay after `startPlayback` followed by a `irrecv.enableIRIn();`

```
startPlayback(sample, sizeof(sample));
delay(1000); // delay needed as long audio is playing
irrecv.enableIRIn(); // enable input from IR receiver after using PCM library startPlayback

```
> 1 votes

---
Tags: arduino-uno, ir, remote-control, speaker, tmrpcm
---


# Question
Title: On a custom ESP32-based PCB, I can' flash anymore after the first successful firmware flash
I have designed and manufactured a custom PCB, with an ESP32 chip on it. I use my FTDI cable to upload my firmware. I have no problem to flash my firmware, and it runs with no problem. So far so good. But then, any successive attempts to flash again is a dead end as it results into a timeout (of course I still press the boot button on my PCB).

If I take a new PCB, the first flash is OK but I cannot do it again.

Note: to make thing as simple as possible, I simply use the Arduino IDE and my do-nothing code as my firmware replacement:

```

void setup() {
  Serial.begin(115200);
  //Serial.setDebugOutput(true);
  Serial.println("Yo from SDL!");
}

// the loop function runs over and over again forever
int _loop = 1;

void loop() {
  Serial.print("Loop #");
  Serial.println(_loop++);
  Serial.println();
  delay(3000);
}

```

\[UPDATED\] Here is the schematic regarding the ESP32 and the GPIO0, GPIO2:

The schematic of the PCB regarding the boot loader

Do you have any clue?!

# Answer
IO2 needs to be connected to a pulldown resistor (your buzzer FET has a pulldown on its input which does the job, which is fortunate). I would consider moving the buzzer elsewhere and keeping IO2 just for the pulldown resistor if possible.

IO0 needs a pullup resistor.

You need some way of resetting the ESP32 through pulling the EN pin low when you want to reprogram it.

Both IO0 and the EN pin are usually controlled through a combination of the DTR and RTS pins of the USB to UART adapter to do the resetting automatically. Without that you will have to manually hold IO0 LOW while briefly pulling EN low to reset the chip.
> 1 votes

---
Tags: esp32, bootloader
---


# Question
Title: ESP32 how to preserve RTC time during brownout
I want to use the ESP32 built-in RTC clock. In my situation, my ESP32 will not have access to an NTP server I do not want to use external RTC modules

ESP32 provides a pin VDD\_RTC will powers the RTC domain exclusively My problem would be solved if I attach a coin cell to this pin. In this case, in the event of a brownout, the VDD\_RTC will be powered and RTC clock preserved.

But, all dev kits I have seen seem to have VDD\_CPU, VDD\_DSIO and VDD\_RTC connected together So, if I would use a battery or some sort of small ups to power my ESP32 during brownout, it will be depleted by the use of GPIOs and CPU and other functions.

Solution would be here to detect brownout and force ESP32 to go to deep sleep, and then wake it up after brownout. But this would require an external source attached to a ESP32 pin to trigger deep sleep, and I don't see any pin to trigger it

Maybe I could have a circuit that would give me a signal when there is a brownout. I could attach this signal to a GPIO pin and trigger an interrupt that makes ESP32 go into deep sleep

But it seems too much for something that I am sure is super basic and should be implemented already somehow in a more convenient way

Could anyone share with me any experiences of how to preserve RTC using minimum external circuitry?

# Answer
> 1 votes
You don't need to do anything special to detect Brownouts. ESP32 itself detects them, and would reset the chip automatically. The reset reason would then indicate a brownout (don't remember the exact name). So you only need to check for the reset reason at the start of your code, whether it is normal powerup, or brownout. The esp won't boot up until the brownout is over, so you don't even need to check when the brownout condition starts nor when it stops.

Moreover, in general (irrespective of brownouts) you don't need any external pins to set the esp32 to sleep, nor do you need them to wake it up. You simply call:

```
esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
esp_deep_sleep_start();

```

The first line tells the esp how long to sleep. The second one initiates deep sleep. The esp32 (unlike the esp8266), will automatically wake itself back up. If a brownout happens while it is asleep, it will boot up again once the brownout is over, but the wake-up reason would be different depending on the case.

The default voltage that triggers the brownout condition is I think 2.8V. This is only configurable in esp-idf, not Arduino. But you don't have to worry about it. Above 2.8V the esp32 continues to keep time correctly. Below 2.8V, it halts, then wakes up once it rises above 2.8V. However, if you don't use an external RTC, and don't use a stable power source, there is no way to keep track of time after the brownout. You can't know how long the brownout was. There is no way to do this. The only option is then to find the pin that supplies the RTC alone, sever it, and wire it to a separate battery. This requires alot of SMD skills.

---
Tags: esp32, rtc
---


title: strcpy_P increases IROM usage by 400%

text:
# Question
Title: strcpy_P increases IROM usage by 400%
Using ESP8266 (NodeMcu 1) in Arduino IDE:

I can't upload my sketch because a single call to **strcpy\_P** seems to increase the IROM usage by about 400%: 25% total usage without the call, 100+% with the call.

And even more strange, it depends on the second parameter of strcpy\_P (the source): If a pointer to a char array is provided, the usage increases dramatically

```
  char * ptr = (char *) pgm_read_word (&myArrays[index]);
  char buffer [1500];

  strcpy_P (buffer, ptr); // can't upload, uses 100+% of available IROM

```

Whereas with PSTR as parameter (just to test) total size of sketch is just 25% of IROM, leaving everything else unchanged:

```
  char * ptr = (char *) pgm_read_word (&myArrays[index]);
  char buffer [1500];

  strcpy_P(buffer, PSTR("Test")); // Ok, does not increase sketch size /IROM  usage

```

What's going on here ?

# Answer
I guess the problem is not the `strcpy_P` function, but your array. Without that function call, the entire array can be removed by the compiler (I presume it's not used anywhere else). As soon as you add code that definitely accesses it, it is included in the code and therefore increases the size of the program so much.
> 2 votes

---
Tags: progmem
---


title: Controlling Arduino through python

text:
# Question
Title: Controlling Arduino through python
How to set the registers of Arduino through python code to vary the sampling rate of Arduino? Can we control Arduino through python?

# Answer
> 1 votes
If you mean can you run a python script on a "PC" and send messages to an Arduino then yes but you would need to write code that ran on the Arduino to receive messages from the "PC" and turn those into actions on the Arduino.

If you mean can you run a python script on an Arduino directly, well yes you can there are python implementations for Arduinos, but if you go down this route you need to remember you only have a small amount of memory and you are going off piste where there will be little or no help.

Honestly I would learn how to program the arduino in C++ and stick to that.

---
Tags: serial, arduino-nano, python, analog-sampling, registers
---


title: Serial hangs on Arduino-Uno

text:
# Question
Title: Serial hangs on Arduino-Uno
I'm having issues with Arduino and RPI3 serial communication, it'll become unresponsive after a little time. Tried increasing BAUD rate and same issue, also happens on Windows as well so RPI is not at fault, and even after increasing the `delay` the hang still happens.

RPI3 python code

```
import serial
import time

if __name__ == '__main__':
  ser = serial.Serial('/dev/ttyACM0', 115200, timeout=1, writeTimeout=0)
  ser.flush()
  last = "on\n"

  while True:
    last = "on\n" if last == "off\n" else "off\n"
    ser.write(last.encode())
    print(last)
    time.sleep(0.5)

```

Arduino code

```
#define BAUD_RATE 115200
const int LED_PIN = 8;
String command;

void setup() {
  Serial.begin(BAUD_RATE);
  pinMode(LED_PIN, OUTPUT);
  delay(100);
}

void loop() {
  Serial.println("I was written in RPI");

  if (Serial.available()) {
    command = Serial.readStringUntil('\n');

    if (command.equals("on")) {
      digitalWrite(LED_PIN, HIGH);
    } else if (command.equals("off")) {
      digitalWrite(LED_PIN, LOW);
    }
  }

  delay(50);
}

```

after less than a minute I'll get this exception from python

`BlockingIOError: [Errno 11] Resource temporarily unavailable`

The Arduino TX and RX led's stay on when it becomes unresponsive rather than flashing like it normally does.

# Answer
> 2 votes
You are flooding the RPi/PC with `"I was written in RPI"` and don't read it. It will work if you read `ser` regularly.

On the delays: A message over a serial line has a transmission time, in your case 20 characters at 115200 baud from Arduino to RPi/PC. With the common 8n1 protocol, characters are sent at 11520 per second. With 20 characters this will take nearly 0.002 seconds, or 2 ms. The receiver needs a smaller delay than the sender to avoid overflows.

If the Arduino were using the USB directly (AFAIK it does not, between its USB interface and the actual AVR is a "real" serial line), the baudrate does not matter. A virtual serial line over USB is always really fast, independent of the announced baudrate. I once used 921600 baud with success. ;-) The baudrate is only used if a real serial line is involved.

---
Tags: arduino-uno, serial, raspberrypi
---


title: A strange bug in my Arduino ALU

text:
# Question
Title: A strange bug in my Arduino ALU
I have discovered a strange error in my Arduino. It's not in the code. I think it's a hardware bug in the ALU of the microcontroller, maybe in clone only. So there is a variable called `feedLimit` and its value is 30, which doesn't really matter. When I print the answer of feedLimit*30*1000 using this command `Serial.println(feedLimit*30*1000)` The answer printed on the serial monitor is 30528, which is obviously incorrect. But when I print feedLimit\*30000, the answer is correct (300000). The answer should be the same in both cases but it's not. I have attached the code as well as a screenshot of the output. Can somebody please let me know if this is a bug in Arduino or something else? I have never experienced this kind of bug at the hardware level. Thanks.

```
int interval, interval2;

int feedingTime = 3; //Must feed once every 3 minutes
int feedLimit = 30;  //If fed 10 times or more within feedingTime span, the fiesh dies
int dieAfter = 30;   //Will die if its not fed in 10 minutes
int feedCounter = 0; //Counts how many time fed in feedingTime span

void setup() {
  Serial.begin(9600);
  pinMode(btnPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);

  Serial.println(feedLimit);
  Serial.println(feedLimit*60*1000);
  Serial.println(feedLimit*60000);
}

```

# Answer
This is not a bug. It's just that you are working with signed 16 bit integers on an 8 bit microcontroller. The maximum an `int` can store is 32767, and literals are 16 bit signed by default.

Your three prints are:

```
  Serial.println(feedLimit);

```

Print 30.

```
  Serial.println(feedLimit*60*1000);

```

Multiply `feedLimit` by 60 = 1800. Multuply 1800 by 1000 = 1800000. Fit 1800000 into 16 bit signed = 30538. Also works the other way: preprocessor multiplies two 16 bit ints to create a new 16 bit int constant: 60 * 1000 = 60000, which is too big to fit in an int and truncates to 27232. Multiply by 30 = 30538 when truncated to 16 bits.1

```
  Serial.println(feedLimit*60000);

```

Multiply 30 by 60000. 60000 is too big to store in an int so it is implicitly promoted to a long. 30 * 60000 = 1800000. The result is a long because you have an implicit long in your calculation.

You have to take care with big numbers on small microcontrollers and keep in mind the limits of each variable type, along with what the default data type for literals is.

* char: -128 to +127
* unsigned char / byte: 0 to 255
* int: -32,768 to +32,767
* unsigned int: 0 to 65,535
* long: -2,147,483,648 to 2,147,483,647
* unsigned long: 0 to 4,294,967,295

You can force literals to be a specific data type by adding a suffix to them:

* L: Long
* UL: Unsigned long

(There are others too but less often used).

So your first (failed) calculation can be fixed by forcing one of the values to be a long:

```
  Serial.println(feedLimit*60*1000L);

```

---

1: It seems avr-gcc isn't clever enough to do this, instead it's always treating each operation separately, and each time it works from int-to-int using two 8-bit registers to represent each value or result.
> 3 votes

---
Tags: arduino-nano, c++, debug, c-preprocessor
---


# Question
Title: How does Arduino board separate USB traffic (uploading code vs. communication)?
A beginner in Arduino programming here (learning Arduino programming while waiting for my board to arrive).

I am trying to understand how Arduino board is able do these two things using only one USB port it has:

1. receive compiled code from a PC (from Arduino IDE: Sketch \> Upload)
2. serial communication between a PC application and the Arduino board (e.g. our own Windows application communicates with the Arduino board)

I just cannot wrap my mind around how does it distinguish between these two cases. I have used boards which have 2 USB ports: one is for programming (uploading your code) and the other one is for serial communication between any PC application and the board.

In my opinion there has to be some way for Arduino to detect when is it being flashed, and when is it being used as a regular serial port.

# Answer
> 3 votes
It doesn't distinguish anything. It's all down to what code is running on the board at any moment.

When you reset or power up the bootloader runs. It listens for uploaded code. If it doesn't get an upload signal from the pc after a short timeout it starts executing your code instead.

---
Tags: usb, bootloader
---


# Question
Title: Why do I get different times when using analogRead() inside while loop?
I have the following code which checks the latency of another board.

```
    int triggerPin = 13;
    int dataPin = 9;
    int ejectorPin = A0;
    unsigned long t_start = 0;
    unsigned long t_end = 0;
    unsigned long t_total = 0;
    int value = 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(triggerPin, OUTPUT);
      pinMode(dataPin, OUTPUT);
      pinMode(ejectorPin, INPUT);
      Serial.begin(9600);
    }

    void loop() {
      t_start = micros();
      while (value < 10 ) {
        digitalWrite(triggerPin, HIGH);
        digitalWrite(dataPin, HIGH);
        delay(5.0);
        digitalWrite(dataPin, LOW);
        digitalWrite(triggerPin, LOW);
        delay(1.0);
        value = analogRead(ejectorPin);
      }
      t_end = micros();

      t_total = (t_end - t_start);
      Serial.println(double(t_total) / 1000);

```

Note that I'm using `analogRead()` inside the while loop. With this method I get **18.3 msec**. However, if I use the `analogRead()` in the while condition:

```
    void loop() {
      t_start = micros();
      while (analogRead() < 10 ) {
        .
        .
        .

```

then I get **30.2 msec**. I thought assigning value of `analogRead()` to a variable would take longer but here it's the opposite.

**Can someone please explain the reason behind this behaviour?**

# Answer
Both of your examples use a while loop, so the while loop is not the issue.

An analogue read, with the prescalers unchanged, takes 104 µs. So, what you are really measuring is your 6 ms delays, plus a slight amount extra for the other code.

Since your first while loop necessarily takes 6+ ms, then you will naturally get a result which is a multiple of 6 ms. This appears to be happening, so you are getting two loops (18 ms). This doesn't prove a huge amount.

---

You need to read up on the Nyquist frequency

To get accurate sampling results you need to sample at twice the rate at which things change. Your first results may merely be the results of aliasing. Your 6 ms delays may cause you to take one sample on one transition, and another sample (maybe) a couple of transitions later. Thus your results are meaningless.
> 2 votes

---
Tags: arduino-uno, timers, analogread
---


title: Arduino as Multiplexer

text:
# Question
Title: Arduino as Multiplexer
This is a kind of an experiment, I just have a question on how Arduino ports work. Consider this sample: there is this target device that I'm trying to control with Arduino. The device uses a typical scanned keyboard (8 output columns and 5 input rows which make contact whenever a user presses a key). I am trying to emulate that keyboard with Arduino. Of course, a standard way to do it would be to read 8 columns and produce appropriate output on the 5 rows. However, Arduino is not fast enough to make it work. So, I am going with multiplexer idea. 8 Arduino's digital pins are connected to columns and 5 Arduino digital pins are connected to rows. GND rail is NOT connected.

So the idea is this. By default all Arduino pins are set to INPUT in init() routine. Whenever I need to emulate a key press, I just set a corresponding row pin to OUTPUT and LOW, same for the column pin. So, that should work as some kind of a multiplexer, since Arduino pins are driven by Mosfets and input state is high impedance, and during output state both pins would be tied to Arduino's GND which makes a hardlink connection between them (setting to HIGH should work to, there's no difference).

Here is the test code which should make a keypress every 5 seconds:

```
pinMode(ROW0_PIN,OUTPUT);
digitalWrite(ROW0_PIN,LOW);
pinMode(COLUMN0_PIN,OUTPUT);
digitalWrite(COLUMN0_PIN,LOW);
Sleep(5000);

pinMode(ROW0_PIN,INPUT);
pinMode(COLUMN0_PIN,INPUT);
Sleep(5000);

```

Now, the thing IS working. However, it only works if *one* column pin is connected. When I connect any two pins, the target device stops responding. What I found is that actually, when I do

`pinMode(COLUMN0_PIN,OUTPUT);digitalWrite(COLUMN0_PIN,LOW);`,

the neighboring pins somehow get activated too, which results in all column outputs connected together and sending signal to row inputs.

If all pins are set to INPUT, it works fine, meaning, no connection between rows and columns.

My qustion is: why is it happening? Let me rephraze it: somehow setting a digital pin to OUTPUT makes other digital pins lose their high impedance state, although all of them are set to input. I haven't checked if this is happening within a hardware port or not, just consider schematics, please.

# Answer
> 4 votes
I have no certainty about what is happening, but I suspect you are seeing the effects of the input clamping diodes. Each digital pin has clamping diodes that keep its potential between GND and Vcc, ±the diode threshold.

* As long as all pins are set to `INPUT`, they can freely float with respect to one another, provided the potential differences stay within Vcc+2×diode\_threshold.
* When you set one pin to `OUPUT` `LOW`, you are tying to to GND. The other pins can still float *above* this one, but only very slightly *below* it. The clamping diodes provide unidirectional current paths from this pin (which is now GND) to every other pin.

---
Tags: pinmode
---


# Question
Title: Why is the IR transmitter tied to one pin
I'm using IRremote.h (https://github.com/Arduino-IRremote/Arduino-IRremote). The receiver allows you to change the pin it is connected to but the transmitter does not. Is there any reason why this is hardcoded in IRremoteInt.h. If it just a PWM pin, can't any PWM pin be used?

```
#if defined(CORE_OC2B_PIN)
#define TIMER_PWM_PIN        CORE_OC2B_PIN  /* Teensy */
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define TIMER_PWM_PIN        9  /* Arduino Mega */
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
#define TIMER_PWM_PIN        14 /* Sanguino */
#else
#define TIMER_PWM_PIN        3  /* Arduino Duemilanove, Diecimila, LilyPad, etc */
#endif

```

There is not much documentation on this.

# Answer
> 0 votes
Got to the bottom of it. As mentioned in the comments, this is tied to the timers. The list is given in Secrets of Arduino PWM. The code can be changed to use a different timer but it will still be tied to a specific pin.

---
Tags: infrared
---


# Question
Title: Avoid the 10 attempts of Avrdude when programmer is not responding
Sometime I update my sketch in the Arduino environment, and when I click on the transfer arrow but forget to plug my arduino (I'm using the UART in my project so every time I need to plug/unplug some wires) it's a drama, avrdude throw this for at least 2 minutes :

> avrdude: stk500\_recv(): programmer is not responding avrdude: stk500\_getsync() attempt 1 of 10: not in sync: resp=0x32

It's a real pain because I can't stop avrdude when this happens. Is there a way to configure the Arduino environment to disable it?

# Answer
Unfortunately, `MAX_SYNC_ATTEMPTS` is a constant in the source code, and one which appears several times.

avrdude is an open source project, so customizing and building it should be relatively straightforward. Since it is a numeric rather than string value, and is checked in several places, simply modifying the binary is likely to be tricky.

One can of course manually kill the process, though it is annoying to have to.

Another approach could be to write a wrapper which might potentially do some sanity checking first (does any other process have the port open?) and then would launch avrdude as its child, passing through all the arguments. By monitoring the output before passing it on, it should be possible to detect this message and terminate the avrdude instance automatically.
> 1 votes

# Answer
I had the same question and found following solution in linux: write a script,

```
#!/bin/bash
avrdude=`ps -C avrdude | tail -n 1 | head -c 7`
kill $avrdude

```

store it and connect it with a shortcut
> 0 votes

---
Tags: arduino-ide, uploading, avrdude
---