PlatformIO

How to fix PlatformIO ESP8266 WiFi.h: No Such File or Directory

Problem:

When compiling your PlatformIO firmware, you see an error message like

src/main.cpp:2:10: fatal error: WiFi.h: No such file or directory

**************************************************************
* Looking for WiFi.h dependency? Check our library registry!
*
* CLI  > platformio lib search "header:WiFi.h"
* Web  > https://platformio.org/lib/search?query=header:WiFi.h
*
**************************************************************

    2 | #include <WiFi.h>

Solution:

Instead of

#include <WiFi.h>

use

#include <ESP8266WiFi.h>

Now delete the .pio folder from the project directory to ensure a clean build by using:

rm -rf .pio

In case that doesn’t help, see our article on how to fix this issue by adding the WiFi library to the dependencies: How to fix PlatformIO WiFi.h: No Such File or Directory

Posted by Uli Köhler in Arduino, Electronics, ESP8266/ESP32, PlatformIO

How to fix PlatformIO multiple definition of `WiFi’ error

Problem:

When compiling your PlatformIO firmware, you see an error message like

Linking .pio/build/d1_mini_lite/firmware.elf
/home/uli/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/10.3.0/../../../../xtensa-lx106-elf/bin/ld: .pio/build/d1_mini_lite/libbc0/libWiFi.a(WiFi.cpp.o):(.bss.WiFi+0x0): multiple definition of `WiFi'; .pio/build/d1_mini_lite/libd39/libESP8266WiFi.a(ESP8266WiFi.cpp.o):(.bss.WiFi+0x0): first defined here
collect2: error: ld returned 1 exit status
*** [.pio/build/d1_mini_lite/firmware.elf] Error 1

Solution:

Move WiFi in the lib_deps section in platformio.ini to the top of the list. Before the fix:

lib_deps =
    ESP Async [email protected]
    [email protected]
    WiFi

After the fix:

lib_deps =
    WiFi
    ESP Async [email protected]
    [email protected]

Now you need to completely remove the .pio folder from your project directory:

rm -rf .pio

After that, recompile your firmware.

Complete platformio.ini example after fixing the issue:

[env:d1_mini_lite]
platform = espressif8266
board = d1_mini_lite
framework = arduino
monitor_speed = 115200
lib_deps =
    WiFi
    ESP Async [email protected]
    [email protected]

 

Posted by Uli Köhler in Arduino, Electronics, PlatformIO

How to fix PlatformIO WiFi.h: No Such File or Directory

Important note: On the ESP8266, this solution is not recommended. See How to fix PlatformIO ESP8266 WiFi.h: No Such File or Directory instead

Problem:

When compiling your PlatformIO firmware, you see an error message like

src/main.cpp:2:10: fatal error: WiFi.h: No such file or directory

**************************************************************
* Looking for WiFi.h dependency? Check our library registry!
*
* CLI  > platformio lib search "header:WiFi.h"
* Web  > https://platformio.org/lib/search?query=header:WiFi.h
*
**************************************************************

    2 | #include <WiFi.h>

Solution:

Add WiFi to the lib_deps in platformio.ini (create lib_deps if it is not present already):

lib_deps =
    WiFi

and then recompile.

Complete platformio.ini example:

[env:d1_mini_lite]
platform = espressif8266
board = d1_mini_lite
framework = arduino
monitor_speed = 115200
lib_deps =
    ESP Async [email protected]
    [email protected]
    WiFi

 

Posted by Uli Köhler in Arduino, Electronics, PlatformIO

How to fix PlatformIO SPI.h: No Such File or Directory

Problem:

When compiling your PlatformIO firmware, you see an error message like

In file included from .pio/libdeps/esp32dev/Adafruit BusIO/Adafruit_BusIO_Register.h:2:0,
                 from .pio/libdeps/esp32dev/Adafruit INA219/Adafruit_INA219.h:21,
                 from .pio/libdeps/esp32dev/Adafruit INA219/Adafruit_INA219.cpp:31:
.pio/libdeps/esp32dev/Adafruit BusIO/Adafruit_SPIDevice.h:6:17: fatal error: SPI.h: No such file or directory

*************************************************************
* Looking for SPI.h dependency? Check our library registry!
*
* CLI  > platformio lib search "header:SPI.h"
* Web  > https://platformio.org/lib/search?query=header:SPI.h
*
*************************************************************

Solution:

Add SPI to the lib_deps in platformio.ini, for example, before:

lib_deps =
    adafruit/Adafruit INA219 @ ^1.1.1

After:

lib_deps =
    adafruit/Adafruit INA219 @ ^1.1.1
    SPI

and then recompile.

Posted by Uli Köhler in Arduino, Electronics, PlatformIO

How to fix PlatformIO Adafruit_BusIO_Register.h: No Such File or Directory

Problem:

When compiling your PlatformIO firmware, you see an error message like

In file included from .pio/libdeps/esp32dev/Adafruit INA219/Adafruit_INA219.cpp:31:0:
.pio/libdeps/esp32dev/Adafruit INA219/Adafruit_INA219.h:21:37: fatal error: Adafruit_BusIO_Register.h: No such file or directory

*********************************************************************************
* Looking for Adafruit_BusIO_Register.h dependency? Check our library registry!
*
* CLI  > platformio lib search "header:Adafruit_BusIO_Register.h"
* Web  > https://platformio.org/lib/search?query=header:Adafruit_BusIO_Register.h
*
*********************************************************************************

Solution:

Add adafruit/Adafruit BusIO @ ^1.9.3 to the lib_deps in platformio.ini, for example, before:

lib_deps =
    adafruit/Adafruit INA219 @ ^1.1.1

After:

lib_deps =
    adafruit/Adafruit INA219 @ ^1.1.1
    adafruit/Adafruit BusIO @ ^1.9.3

and then recompile.

Posted by Uli Köhler in Arduino, Electronics, PlatformIO

How to fix PlatformIO Wire.h: No Such File or Directory

Problem:

When compiling your PlatformIO firmware, you see an error message like

In file included from .pio/libdeps/esp32dev/Adafruit INA219/Adafruit_INA219.cpp:31:0:
.pio/libdeps/esp32dev/Adafruit INA219/Adafruit_INA219.cpp:29:18: fatal error: Wire.h: No such file or directory

**************************************************************
* Looking for Wire.h dependency? Check our library registry!
*
* CLI  > platformio lib search "header:Wire.h"
* Web  > https://platformio.org/lib/search?query=header:Wire.h
*
**************************************************************

Solution:

Add Wire to the lib_deps in platformio.ini, for example, before:

lib_deps =
    adafruit/Adafruit INA219 @ ^1.1.1

After:

lib_deps =
    adafruit/Adafruit INA219 @ ^1.1.1
    Wire

and then recompile.

Posted by Uli Köhler in Arduino, Electronics, PlatformIO

Teensy 4.1 interrupts at multi-MHz speed using TeensyTimerTool

As shown in our example Teensy 4.1 PlatformIO 2MHz Timer interrupt GPIO output you can use TeensyTimerTool to generate multi-MHz timer interrupts. In our experiments, we could generate GPIO-toggling interrupts up to 4 MHz:

The trick here is to use std::chrono time literals. The TeensyTimerTools PeriodicTimer example only shows us how to use microsecond resolution:

t1.begin(callback, 250'000); // 250ms

but we can simply use 250ns to obtain nanosecond resolution:

t1.begin(callback, 250ns);

Here’s our observation what works and what doesn’t:

  • Multi-MHz GPIO-toggling interrupts as shown in our example only work on GPT1 and GPT2, they do NOT work on PIT and TMRx. We did not investigate the precise reasoning behind this, and there might also be ways to
  • As usual, the interrupt must only contain a small number of instructions. We’re using digitalWriteFast(), but using direct register access would be even faster.
Posted by Uli Köhler in Electronics, Embedded, PlatformIO, Teensy

Teensy 4.1 PlatformIO 2MHz Timer interrupt GPIO output

The following PlatformIO example uses TeensyTimerTool on the Teensy 4.1 to run a simple GPIO toggle interrupt at 4 MHz interrupt frequency (i.e. the interrupt is being run 4 million times each second), resulting in a 2 MHz GPIO output:

#include <Arduino.h>
#include <TeensyTimerTool.h>
using namespace TeensyTimerTool;

PeriodicTimer t1(GPT2);

void callback() // toggle the LED
{
    digitalWriteFast(33, !digitalReadFast(33));
}

void setup()
{
    t1.begin(callback, 250ns);

    pinMode(33, OUTPUT);
}

void loop()
{
}

platformio.ini:

[env:teensy41]
platform = teensy
board = teensy41
framework = arduino
lib_deps = luni64/TeensyTimerTool @ ^0.3.5

The 2MHz output looks like this on the oscilloscope:

Posted by Uli Köhler in PlatformIO, Teensy

How to convert PlatformIO firmware with build offset to firmware without

Some firmwares are build with a build offset to accomodate flash space (like 32k – 0x8000) for a bootloader that is started before the firmware. One of the downsides of using such a firmware is that it always depends on a compatible bootloader to be present (compatibility is mostly defined by how much flash is allocated for the bootloader)

If you want to convert a firmware to a “normal” non-bootloader firmware, this is what you’ll have to do:

  • Set board_build.offset to 0x0 – look not only in your build configuration in platformio.ini and all included files, but also look in the configuration that your config extends, if any.
  • Set board_upload.offset_address to 0x0. This mostly affects uploading with a debugger, but you should always keep this information consistent because debugging that is a huge nightmare.
  • Edit the specific linker script your firmware is using and set the flash offset appropriately:

Look for the MEMORY section like this:

MEMORY
{
FLASH (rx)      : ORIGIN = 0x8008000, LENGTH = 512K
RAM (xrw)      : ORIGIN = 0x20000000, LENGTH = 128K
}

As you can see in

FLASH (rx) : ORIGIN = 0x8008000, LENGTH = 512K

the flash for this STM32 (example) is not at the MCU’s flash address 0x8000000, but at 0x8008000 – basically, the linker is told to skip the 0x8000 (32k) the bootloader occupies (else, it would overwrite the bootloader.

Change this to your MCU’s flash adress. For ARMs like the STM32, this is typically 0x8000000.

Now recompile and your firmware should work without the bootloader.

Posted by Uli Köhler in Embedded, PlatformIO, STM32

How to flash STM32 PlatformIO firmware using dfu-util

First, you need to find the correct firmware file. dfu-util will flash firmware.bin, not firmware.elf. You can find firmware.bin in

.pio/build/[PROFILE_NAME]/firmware.bin

inside your project folder. [PROFILE_NAME] is the name of the build profile you’re using, i.e. the name of the section in platformio.ini. For example:

.pio/build/BIGTREE_OCTOPUS_V1/firmware.bin

Now flash using dfu-util:

dfu-util -a 0 -D .pio/build/PROFILE_NAME/firmware.bin -s 0x08000000

Flags:

  • -a 0. The STM32 appears as four different devices in dfu-util (see dfu-util --list): The flash, option bytes, RAM etc each appear as a separate device. We only care about the flash device, which is always the first (index 0) of those devices, at least in every board I have seen so far
  • -D [filename]Download the firmware to the device
  • -s 0x08000000: Flash at address 0x08000000 which is the address of the STM32 flash.
Posted by Uli Köhler in Embedded, PlatformIO, STM32

How to fix ‘command not found: pio’ even though PlatformIO is installed

Problem:

You have installed PlatformIO on your computer using Visual Studio code, however when you try to run it in your terminal/shell, you see:

$ pio
zsh: command not found: pio

Solution:

PlatformIO is installed in $HOME/.platformio, but not added to the PATH environment variable, so your terminal can’t find it. Add it using

echo "export PATH=\$PATH:/home/${USER}/.platformio/penv/bin" >> ~/.profile

and then logout from your current session and log back in again (or reboot) in order for the changes to take effect. After that, you can run pio from any shell.

Posted by Uli Köhler in Linux, PlatformIO

How to fix pio remote agent start: You are not authorized! Please log in to PlatformIO Account.

Problem:

When running

pio remote agent start

you see an error message like

2021-10-05 17:37:23 [info] Name: Raspberry Pi
2021-10-05 17:37:23 [info] Connecting to PlatformIO Remote Development Cloud                                                                    
2021-10-05 17:37:23 [info] Successfully connected
2021-10-05 17:37:23 [info] Authenticating
2021-10-05 17:37:23 [error] You are not authorized! Please log in to PlatformIO Account.                                                        
2021-10-05 17:37:23 [info] Successfully disconnected

Solution:

You need to login to your PlatformIO account. Run

pio account login

which will prompt you for your username & password. If you don’t have an account, register using

pio account register
Posted by Uli Köhler in PlatformIO

How to fix pio remote agent start: error: can’t find Rust compiler

Problem:

When running pio remote agent start, while PlatformIO installs the Python packages, you see an error log like

```
  generating cffi module 'build/temp.linux-armv7l-3.7/_openssl.c'                                                                                                           
  creating build/temp.linux-armv7l-3.7                                                                                                                                      
  running build_rust                                                                                                                                                        
                                                                                                                                                                            
      =============================DEBUG ASSISTANCE=============================                                                                                            
      If you are seeing a compilation error please try the following steps to                                                                                               
      successfully install cryptography:                                                                                                                                    
      1) Upgrade to the latest pip and try again. This will fix errors for most                                                                                             
         users. See: https://pip.pypa.io/en/stable/installing/#upgrading-pip                                                                                                
      2) Read https://cryptography.io/en/latest/installation/ for specific                                                                                                  
         instructions for your platform.                                                                                                                                    
      3) Check our frequently asked questions for more information:                                                                                                         
         https://cryptography.io/en/latest/faq/                                                                                                                             
      4) Ensure you have a recent Rust toolchain installed:                                                                                                                 
         https://cryptography.io/en/latest/installation/#rust                                                                                                               
                                                                                                                                                                            
      Python: 3.7.3                                                                                                                                                         
      platform: Linux-5.10.60-v7l+-armv7l-with-debian-10.10                                                                                                                 
      pip: n/a                                                                                                                                                              
      setuptools: 58.2.0                                                                                                                                                    
      setuptools_rust: 0.12.1                                                                                                                                               
      =============================DEBUG ASSISTANCE=============================                                                                                            
                                                                                                                                                                            
  error: can't find Rust compiler                                                                                                                                           
                                                                                                                                                                            
  If you are using an outdated pip version, it is possible a prebuilt wheel is available for this package but pip is not able to install from it. Installing from the wheel would avoid the need for a Rust compiler.                                                                                                                                   
                                                                                                                                                                            
  To update pip, run:                                                                                                                                                       
                                                                                                                                                                            
      pip install --upgrade pip                                                                                                                                             
                                                                                                                                                                            
  and then retry package installation.                                                                                                                                      
                                                                                                                                                                            
  If you did intend to build this package from source, try installing a Rust compiler from your system package manager and ensure it is on the PATH during installation. Alternatively, rustup (available at https://rustup.rs) is the recommended way to download and update the Rust compiler toolchain.                                              
                                                                                                                                                                            
  This package requires Rust >=1.41.0.                                                                                                                                      
  ----------------------------------------                                                                                                                                  
  ERROR: Failed building wheel for cryptography
Successfully built pyopenssl
Failed to build cryptography
ERROR: Could not build wheels for cryptography which use PEP 517 and cannot be installed directly
Error: Traceback (most recent call last):
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/platformio/package/manager/core.py", line 127, in inject_contrib_pysite                                       
    from OpenSSL import SSL                                                                                                                                                 
  File "/home/pi/.platformio/packages/contrib-pysite/OpenSSL/__init__.py", line 8, in <module>                                                                              
  File "/home/pi/.platformio/packages/contrib-pysite/OpenSSL/crypto.py", line 12, in <module>                                                                               
  File "/home/pi/.platformio/packages/contrib-pysite/cryptography/x509/__init__.py", line 8, in <module>                                                                    
  File "/home/pi/.platformio/packages/contrib-pysite/cryptography/x509/base.py", line 18, in <module>                                                                       
  File "/home/pi/.platformio/packages/contrib-pysite/cryptography/x509/extensions.py", line 20, in <module>                                                                 
  File "/home/pi/.platformio/packages/contrib-pysite/cryptography/hazmat/primitives/constant_time.py", line 11, in <module>                                                 
ImportError: /home/pi/.platformio/packages/contrib-pysite/cryptography/hazmat/bindings/_constant_time.abi3.so: cannot open shared object file: No such file or directory    

During handling of the above exception, another exception occurred:                                                                                                         

Traceback (most recent call last):                                                                                                                                          
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/platformio/__main__.py", line 115, in main                                                                    
    cli()  # pylint: disable=no-value-for-parameter                                                                                                                         
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/click/core.py", line 1137, in __call__                                                                        
    return self.main(*args, **kwargs)                                                                                                                                       
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/click/core.py", line 1062, in main                                                                            
    rv = self.invoke(ctx)                                                                                                                                                   
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/platformio/commands/__init__.py", line 44, in invoke                                                          
    return super(PlatformioCLI, self).invoke(ctx)                                                                                                                           
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/click/core.py", line 1668, in invoke                                                                          
    return _process_result(sub_ctx.command.invoke(sub_ctx))                                                                                                                 
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/click/core.py", line 1665, in invoke                                                                          
    super().invoke(ctx)                                                                                                                                                     
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/click/core.py", line 1404, in invoke                                                                          
    return ctx.invoke(self.callback, **ctx.params)                                                                                                                          
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/click/core.py", line 763, in invoke                                                                           
    return __callback(*args, **kwargs)                                                                                                                                      
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/click/decorators.py", line 26, in new_func                                                                    
    return f(get_current_context(), *args, **kwargs)                                                                                                                        
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/platformio/commands/remote/command.py", line 40, in cli                                                       
    inject_contrib_pysite(verify_openssl=True)                                                                                                                              
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/platformio/package/manager/core.py", line 129, in inject_contrib_pysite                                       
    build_contrib_pysite_package(contrib_pysite_dir)                                                                                                                        
  File "/home/pi/.platformio/penv/lib/python3.7/site-packages/platformio/package/manager/core.py", line 156, in build_contrib_pysite_package
    subprocess.check_call(args + [dep])
  File "/usr/lib/python3.7/subprocess.py", line 347, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/home/pi/.platformio/penv/bin/python', '-m', 'pip', 'install', '--no-compile', '-t', '/home/pi/.platformio/packages/contrib-pysite', '--no-binary', ':all:', 'pyopenssl >= 16.0.0']' returned non-zero exit status 1.

============================================================

An unexpected error occurred. Further steps:

* Verify that you have the latest version of PlatformIO using
  `pip install -U platformio` command

* Try to find answer in FAQ Troubleshooting section
  https://docs.platformio.org/page/faq.html

* Report this problem to the developers
  https://github.com/platformio/platformio-core/issues

============================================================
```

Solution

You need to install rust using

sudo apt -y install rustc

and then run the original command again:

pio remote agent start

 

Posted by Uli Köhler in PlatformIO

How to install PlatformIO remote agent on Raspberry Pi

This is from the Super Quick installation procedure from the official PlatformIO documentation:

python3 -c "$(curl -fsSL https://raw.githubusercontent.com/platformio/platformio/master/scripts/get-platformio.py)"
sudo apt -y install rustc libffi-dev
echo "export PATH=\$PATH:/home/${USER}/.platformio/penv/bin" >> ~/.profile

Run it as user (whatever user you want to use PlatformIO as – by default, this is the pi user) and not as root!

After running these commands, log out and log back in again in order for the changes to the PATH environment variable to take effect.

After that, run

pio remote agent start

to complete the installation procedure. This will take quite some time.

After logging in, you can use pio from the shell:

$ pio

Usage: pio [OPTIONS] COMMAND [ARGS]...

Options:
  --version          Show the version and exit.
  -f, --force        DEPRECATE
  -c, --caller TEXT  Caller ID (service)
  --no-ansi          Do not print ANSI control characters
  -h, --help         Show this message and exit.

Commands:
  access    Manage resource access
  account   Manage PlatformIO account
  boards    Embedded board explorer
  check     Static code analysis
  ci        Continuous integration
  debug     Unified debugger
  device    Device manager & serial/socket monitor
  home      GUI to manage PlatformIO
  lib       Library manager
  org       Manage organizations
  package   Package manager
  platform  Platform manager
  project   Project manager
  remote    Remote development
  run       Run project targets (build, upload, clean, etc.)
  settings  Manage system settings
  system    Miscellaneous system commands
  team      Manage organization teams
  test      Unit testing
  update    Update installed platforms, packages and libraries
  upgrade   Upgrade PlatformIO to the latest version

 

Posted by Uli Köhler in PlatformIO, Raspberry Pi

What is the default PlatformIO / Arduino ESP32 TIMER_BASE_CLK?

On PlatformIO / Arduino, by default the TIMER_BASE_CLK is 80 MHz (the maximum frequency the ESP32 can run at).

If you want to verify this yourself, use this firmware:

#include <Arduino.h>

void setup() {
    Serial.begin(115200);
    Serial.println(getCpuFrequencyMhz());
}

void loop() {
}

 

Posted by Uli Köhler in Arduino, Electronics, Embedded, ESP8266/ESP32, PlatformIO

What is the default PlatformIO / Arduino ESP32 CPU clock frequency?

On PlatformIO / Arduino, by default the ESP32 clock frequency is 80 MHz (the default 240 MHzCPU frequency divided by 4)

If you want to verify this yourself, use this firmware:

#include <Arduino.h>

void setup() {
    Serial.begin(115200);
    Serial.println(TIMER_BASE_CLK);
}

void loop() {
}

 

Posted by Uli Köhler in Arduino, Electronics, Embedded, ESP8266/ESP32, PlatformIO

How to fix PlatformIO serial monitor scrambled output

Problem:

When using the Monitor function of platformIO, you see strange characters instead of strings being printed, for example:

)�
�␜ܠ��J��1��1!y��!���!��

Solution:

This issue almost always appears due to the Monitor function using the wrong UART speed. You can see from the log in our screenshot above:

--- Miniterm on /dev/ttyUSB0  9600,8,N,1 ---

that PlatformIO is using 9600 baud in this case – but your microcontroller is sending data at a faster speed (or, rarely at a slower speed).

Most firmwares using serial IO use 115200 baud, so that’s what I’d recommend to try first, but if that doesn’t work, look out for config options named baud rate or similar, or for lines of code like

Serial.begin(57600);

in the firmware.

In order to change the Monitor UART speed, open platformio.ini and add

monitor_speed = 115200

Full platformio.ini example for ESP32:

[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200

After that, restart the Monitor function.

Posted by Uli Köhler in Arduino, Electronics, Embedded, ESP8266/ESP32, PlatformIO, STM32

How to fix ESP32 PlatformIO error: ‘LED_BUILTIN’ was not declared in this scope

Problem:

When trying to compile your ESP32 firmware using PlatformIO, you see this error message:

src/main.cpp: In function 'void setup()':
src/main.cpp:22:13: error: 'LED_BUILTIN' was not declared in this scope
     pinMode(LED_BUILTIN, OUTPUT);

Solution:

Important: Some ESP32 boards such as the ESP32-DevKitC have no builtin LED at all ! Either connect an external LED or find another method of doing whatever you are intending to do.

On most ESP32 boards that do have a builtin LED, the LED is connected to pin 2 – however, PlatformIO does not define LED_BUILTIN p. In order to fix the issue, define LED_BUILTIN yourself by using

#define LED_BUILTIN 2

at the top of every file where you see this error.

Posted by Uli Köhler in Electronics, Embedded, ESP8266/ESP32, PlatformIO

How to fix Linux ESP32 PlatformIO PermissionError: [Errno 13] Permission denied: ‘/dev/ttyUSB0’

Problem:

When trying to flash a ESP8266 or ESP32 board on Linux, you see an error message like

Warning! Please install `99-platformio-udev.rules`. 
More details: https://docs.platformio.org/page/faq.html#platformio-udev-rules

Auto-detected: /dev/ttyUSB0
Uploading .pio/build/esp32dev/firmware.bin
esptool.py v3.1
Serial port /dev/ttyUSB0
Traceback (most recent call last):
  File "/home/uli/.platformio/penv/lib/python3.8/site-packages/serial/serialposix.py", line 322, in open
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
PermissionError: [Errno 13] Permission denied: '/dev/ttyUSB0'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/uli/.platformio/packages/tool-esptoolpy/esptool.py", line 4582, in <module>
    _main()
  File "/home/uli/.platformio/packages/tool-esptoolpy/esptool.py", line 4575, in _main
    main()
  File "/home/uli/.platformio/packages/tool-esptoolpy/esptool.py", line 4074, in main
    esp = esp or get_default_connected_device(ser_list, port=args.port, connect_attempts=args.connect_attempts,
  File "/home/uli/.platformio/packages/tool-esptoolpy/esptool.py", line 120, in get_default_connected_device
    _esp = chip_class(each_port, initial_baud, trace)
  File "/home/uli/.platformio/packages/tool-esptoolpy/esptool.py", line 313, in __init__
    self._port = serial.serial_for_url(port)
  File "/home/uli/.platformio/penv/lib/python3.8/site-packages/serial/__init__.py", line 90, in serial_for_url
    instance.open()
  File "/home/uli/.platformio/penv/lib/python3.8/site-packages/serial/serialposix.py", line 325, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 13] could not open port /dev/ttyUSB0: [Errno 13] Permission denied: '/dev/ttyUSB0'

Solution:

As described at the top of the error message, install the PlatformIO udev rules:

curl -fsSL https://raw.githubusercontent.com/platformio/platformio-core/master/scripts/99-platformio-udev.rules | sudo tee /etc/udev/rules.d/99-platformio-udev.rules

then restart udev:

sudo systemctl restart udev

After that, unplug an re-plug your ESP32 board in order for the changes to take effect

Additionally, I recommend adding your user to the dialout group – the Linux group that owns most USB devices:

sudo usermod -a -G dialout $USER

In order for the changes to take effect, log out from your current session completely and log back in again (or reboot). While not strictly neccessary in order to fix this specific error message, it helps in preventing future USB permission issues.

Posted by Uli Köhler in Electronics, Embedded, ESP8266/ESP32, PlatformIO

How to implement 1MHz interrupt in PlatformIO / Arduino on STM32

In our previous post Minimal STM32 HardwareTimer PlatformIO / Arduino timer interrupt blink example we showed how to use HardwareTimer to blink the onboard LED of our STM32F407 board using a timer interrupt.

In this post, we’ll provide an example of how to use HardwareTimer and have a really fast interrupt which runs at 1 MHz – in other words: one million times per second.

#include <Arduino.h>

HardwareTimer timer(TIM1);
bool ledOn = false;

void OnTimer1Interrupt() {
    ledOn = !ledOn;
    digitalWrite(PC13, ledOn ? HIGH : LOW);
}

void setup() {
    pinMode(PC13, OUTPUT);
    // Configure timer
    timer.setPrescaleFactor(21); // Set prescaler to 21 => timer frequency = 168/21 = 8 MHz (from prediv'd by 1 clocksource of 168 MHz)
    timer.setOverflow(8); // Set ARR to 8 => timer frequency = 1 MHz
    timer.attachInterrupt(OnTimer1Interrupt);
    timer.refresh(); // Make register changes take effect
    timer.resume(); // Start timre
}

void loop() {
}

Note that when running such a quick interrupt, you can’t do all too much within the interrupt before the next time the interrupt will run.

Posted by Uli Köhler in C/C++, PlatformIO, STM32