Webbsidan är senast uppdaterad:
Arduino C/C++ kodning
Arduino, ESP32, FreeRTOS C/C++ - kodexempel, funktioner & IDE för kodning
Samlar här lite speciella C/C++ funktioner och kodexempel för kodning / programmering av Arduino Uno och ESP32 i Arduino IDE och i VSCode-PlatformIO.
Jämförelse av prestanda Arduino Uno vs ESP32 | ||||||||
SRAM | Flash | Clock | Cores | bit-depth | EEPROM | RTC-SRAM | WIFI/BLE | |
Arduino Uno1 | 2kB | 32kB | 16MHz | 1st | 8 | 1kB | - | - |
ESP32 Uno2 | 520kB | 4MB | 240MHz4 | 2st | 32 | in Flash3 | 8kB+8kB | X |
ESP32 fördel | 260ggr | 128ggr | 15ggr | 2ggr | 4ggr | +++++ | +++++ | +++++ |
2. ESP32 modules || ESP32 datasheet
3. Save Data to ESP32 Flash Permanently using Preferences Library
4. Can be changed dynamic in code between 10MHz and 240MHz
C++ för Arduino Uno och ESP32 Uno, kodat i Arduino IDE
- Pastebin, för att dela kod i sociala media / forum.
- CodeShare, Share Code in Real-time with Developers
- Tutorialspoint: C++
- C++ Programming Language, GeeksforGeeks
- LearnCpp, teaching how to program in C++
- Cplusplus, Tutorials, Reference, Articles
- HTML Character Encoding
- JavaScript String split(), W3schools
- How to return multiple values from a function in C or C++?
- Returning multiple values from a C++ function
- Default function() arguments C++
Default arguments C++ function() / declaration
void print(int x, int y=4); // forward declaration
void print(int x, int y=4){ // error: redefinition of default argument
std::cout << "x: " << x << '\n';
std::cout << "y: " << y << '\n';
}
Arduino Uno såld i över 10 miljoner exemplar
Compatibility of C and C++: The C and C++ programming languages are closely related but have many significant differences.
String class & string array:- Arduino Built-In Examples - Strings
- Initializing a Char*[] string,
char* perc = "%";
char mystr[] = {'h','i',0};
char* myotherstring = "my other string";
char* mythirdstring = "goodbye";
char* myarr[] = {0};
char* myarr[] = {&mystr, myotherstring};
char* myarr[10];
char* myarr[10] = {0};
char* myarr[10] = {&mystr, myotherstring, mythirdstring, 0}; - String.toCharArray(buf, len), len = No. of characters + 1 ('\0')
String myString;
char buf[10];
myString.toCharArray(buf, myString.length() + 1);
Arduino String to char-array, listar även övriga String functions.
How to convert String to char array in C++?: (more efficient?)
int main()
{
string str = "Tutorialspoint";
char buf[str.length() + 1]; // (str.size() ?)
strcpy(buf, str.c_str());
}
- How to convert flash char array to String in Arduino Uno?
One can use a cast to __FlashStringHelper to invoke the right constructor of the String class. It is the constructor which copies the char array from PROGMEM. __FlashStringHelper is intended as return type for the F() macro.
const char charArray[] PROGMEM = "Some text";
void setup() {
Serial.begin(115200);
String s((const __FlashStringHelper*) charArray);
Serial.println(s);
}
void loop() {
}
- Convert character array to string in Arduino:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println();
char buf[10] = "Hello!";
Serial.print("Char array: ");
Serial.println(buf);
String s = String(buf);
Serial.print("String: ");
Serial.println(s);
}
void loop() {
// put your main code here, to run repeatedly:
}
- Arduino String objects
- Tutorialspoint: Arduino - Strings
- C++ for Arduino - 8 tips to use the String class efficiently
C++ for Arduino - What is string interning?, vs F() - dtostrf(), function to convert a variable of type double into its ASCII representation and store it as a string.
- toInt(), converts a String to an integer number
- Arduino PROGMEM, läsa variable-sträng direkt från flash-minnet.
Store data in flash (program) memory instead of SRAM.
F() macro and PROGMEM
The hidden Arduino Macro F() fixes random lock ups
Do you know Arduino? – PROGMEM demystified, PSTR() / F() - On an ESP32: Is using the F()Macro as pointless as using PROGMEM?
Storing constants in flash on ESP32? (use const variable):
"No other processor uses the proprietary AVR progmem stuff.
In most other processors you don´t have the limitation that the AVR has so you can use const and directly access the data rather the way C/C++ intended rather than have to jump through hoops using progmem and indirect access functions.
All the complexity of using indirect access functions is due to the AVR limitation of not being able to directly access the flash."
Skillnaden mellan Arduino Uno R3´s ATMega328 och ESP32 hur enstatic const char*
deklarerad variabel hanteras vs Flash & RAM förklaras av ovan!
ESP32 const char [] // maximum for Flash Memory?
ESP32: Constant data in flash memory / program space?:
Constant data is stored in flash by default in ESP32, and can be accessed on byte, half-word and word basis. You need to use ´const´ qualifier in your program to mark the data constant.
Om modern Harvard Architecture hos ESP32:
Espressif: The ESP32 is a dual-core system with two Harvard Architecture Xtensa LX6 CPUs. All embedded memory, external memory and peripherals are located on the data bus and/or the instruction bus of ESP32 CPUs. Harvard architecture
Difference between Von Neumann and Harvard Architecture. - What is and when to use IRAM_ATTR ?
- How to format strings without the String class efficient, sprintf() / snprintf() / snprintf_P() (typ F()) / PSTR()
With String class:String s = String("weight = ") + String(weight, 4) + String(" kg");
All printf() format strings, Wikipedia
printf() specifier character & format specifier, cplusplus.com
C library function - sprintf() format strings, Tutorialspoint
C library function - (Serial.)printf() format strings, Tutorialspoint
C snprintf() tutorial: explanation and examples
C99 sprintf() för int64_t, uint64_t, int32_t, uint32_t & size_t:
sprintf(BuffTxt, "%jd|%jd|%ju|%ju|%zu", (intmax_t)int64_t, intmax_t)int32_t, (uintmax_t)uint64_t, (uintmax_t)uint32_t, size_t);
printf() format specifiers, cplusplus.com
Fixed width integer types (since C99), cppreference.com
C++ equivalent of sprintf()
- Using PROGMEM with sprintf_P, to use sprintf_P with both format string and arguments stored in PROGMEM in Arduino Uno.
Here´s the correct syntax:
char header_1[] PROGMEM = "Dissolved O2";
Note that the %S has a capital S because header_1 is in PROGMEM.
char buffer[100];
void setup() {
Serial.begin(57600);
sprintf_P(buffer,PSTR( "The column header is %S") ,header_1);
Serial.println(buffer);
}
void loop(){}
- Operators in C and C++
- Variable Scope in C++
- Pointers vs References in C++ function(Arg), GeeksforGeeks
- When do we pass arguments by reference or pointer?, GeeksforGeeks
=> References when pointers aren´t explicitly needed - C casts vs C++ cast styles:
- Google styleguide C++ Casting
- C++ cast syntax styles, Stackoverflow
- C style casts or C++ style casts, Software Engineering
- Explicit type conversion C++, cppreference.com - Loop unrolling:
- Loop-Specific Pragmas, GCC gnu - Google C++ Style Guide
- Arduino Programming Cheat Sheet (pdf)
- Arduino Language Reference
- Arduino Language Reference by type, ArduinoGetStarted
- Tutorialspoint: Arduino Tutorial
- Tutorialspoint: C++
- C++ Programming Language, GeeksforGeeks
- EEPROM Library
- Default function() arguments C++
Default arguments C++ function() / declaration
void print(int x, int y=4); // forward declaration
void print(int x, int y=4){ // error: redefinition of default argument
std::cout << "x: " << x << '\n';
std::cout << "y: " << y << '\n';
}
- Arduino Tutorial: Avoiding the Overflow Issue When Using millis() and micros()
The millis() number will overflow / rollover (go back to zero) after 49 days and 17 hours.
It´s an unsigned long with a maximum value of 4294967295.
Se även 64bit timer (rollover after 292.5 years).
Rollover safe coding:
int period = 1000;
Med aningen bättre precision med bara en millis():
unsigned long time_now = 0;
void setup() {
}
void loop() {
if(millis() - time_now > period){
time_now = millis();
Your code...;
}
}
int period = 1000;
unsigned long lastTime = 0;
void setup() {
}
void loop() {
unsigned long now = millis();
if ((now - lastTime) >= period) {
lastTime = now;
Serial.printlnf("%lu", now);
}
}
- The simplest button debounce solution, in code
How to Implement Hardware Debounce for Switches and Relays When Software Debounce Isn´t Appropriate.
A Guide to Debouncing - Part 2 - Ultimate Guide to Switch Debounce (Part 9)
- Lite länkar hos FrittLiv kring Enkortsdatorer, Arduino & ESP32
- Espressif Wi-Fi Driver API Guides, The primary principle to write a robust application with Wi-Fi API is to always check the error code and write the error-handling code.
- Espressif Wi-Fi Driver: ESP32 Wi-Fi Event Description
- ESP32 Useful Wi-Fi Library Functions (Arduino IDE), RandomNerdTutorials, view all WiFi events via a function()
- ESP32 WiFiMulti: Connect to the Strongest Wi-Fi Network (from a list of networks)
- ESP32 Auto Connect To The Strongest WiFi Network (WifiMulti)
- WifiMulti does not support Static IP (2018)
- Reconnect ESP32 to Wi-Fi Network After Lost Connection
- ESP32 Static/Fixed IP Address
- ESP32 Static/Fixed IP Address, RandomNerdTutorials
- ESP32 Arduino: Set static IP address, techtutorialsx
- ESP32 static/fix IP address, MicrocontrollersLab
- ESP32 Static/Fixed IP Address, ElectroRules
- ESP32 Setting a Custom Hostname (Arduino IDE), WiFi.mode(WIFI_STA);
- ESP32 Setting a Custom Hostname, RandomNerdTutorials
String hostname = "ESP32 Node Temperature";
WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname(hostname.c_str()); //define hostname
- Espressif WiFi API, arduino-esp32
- Espressif Wi-Fi API Reference, ESP32
- Arduino WIFI Library
- Arduino WiFi - WiFi.status(), defined return parametras as WL_CONNECTED
- WiFi with Arduino – Scan Networks
- Scanning of WiFi on ESP32 controller
- ESP32 Arduino Tutorial: Getting started with WiFi, DfRobot,Scanning WiFi networks all data
- How to check if internet is available?, Espressif forum
- I use the following to check for a WiFI connection:
if ((wifiClient.connected()) && (WiFi.status() == WL_CONNECTED))
- ESP_WiFI_Power_Adjust.ino, ESP32
WiFi.setTxPower(WIFI_POWER_19_5dBm);
WiFi.getTxPower();
Available ESP32 RF power parameters:
WIFI_POWER_19_5dBm // 19.5dBm (For 19.5dBm of output, highest. Supply current ~150mA)
WIFI_POWER_19dBm // 19dBm
WIFI_POWER_18_5dBm // 18.5dBm
WIFI_POWER_17dBm // 17dBm
WIFI_POWER_15dBm // 15dBm
WIFI_POWER_13dBm // 13dBm
WIFI_POWER_11dBm // 11dBm
WIFI_POWER_8_5dBm // 8dBm
WIFI_POWER_7dBm // 7dBm
WIFI_POWER_5dBm // 5dBm
WIFI_POWER_2dBm // 2dBm
WIFI_POWER_MINUS_1dBm // -1dBm( For -1dBm of output, lowest. Supply current ~120mA)
- SNTP Time Synchronization - esp_sntp_config::smooth, Espressif
- SNTP_SYNC_MODE_SMOOTH, Espressif
- Getting Current Date and Time with ESP32 using NTP Server-Client and Arduino IDE, with table of the specifiers which can be used to access a particular configuration of the date/time.
- ESP32 NTP Client-Server: Get Date and Time (Arduino Framwork), Random Nerd Tutorials
- ESP32 NTP Time – Setting Up Timezones and Daylight Saving Time, Random Nerd Tutorials
- World timezone Strings for ESP32 NTP Time
- Specifying the Time Zone with TZ, gnu.org
- IANA Time Zone Database
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED){
Serial.print(".");
delay(500);
}
configTime(0, 0, "pool.ntp.org"); // is a cluster of timeservers for anyones use
setenv("TZ", "CET-1CEST,M3.5.0,M10.5.0/3", 1); // Stockholm timezone String
tzset(); // N.B. setenv() & tzset() must be set after each watchdog timer reboot
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
Time servers to use in Sweden (examples):
const char* ntpServer1 = "se.pool.ntp.org";
Projektet pool.ntp.org
const char* ntpServer2 = "europe.pool.ntp.org";
const char* ntpServer3 = "pool.ntp.org";
Hur använder jag pool.ntp.org?
Sweden — se.pool.ntp.org
Connect to Netnod´s NTP Servers, Sweden
Netnod NTP Info, Sweden
ntp.netnod.se, maybe as ntpServer1
- tipsad av kunnig person
Swedish Distributed Time Service - ntp.se
Så ska nog prova med:
const char* ntpServer1 = "ntp.netnod.se";
Kör nu med denna kombinationen av netnod.se, ntp.se och ntp.org vilket fungerar bra!
const char* ntpServer2 = "ntp.se";
const char* ntpServer3 = "europe.pool.ntp.org";
Känns vettigt att ha från några olika väletablerade tidsserverdomäner (2023-10-14).
Enligt rekommendation ska netnod.se vara allra bäst att använda sig av i Sverige.
Netnod har ett samhällsuppdrag i Sverige, finansierat av Post- och telestyrelsen, PTS, att leverera exakt tid över internet.
Sverige först i världen med säker internet-tid, via netnod.se.
Netnod lanserar NTP med NTS-skydd.
What is Network Time Security and why is it important?, netnod.se
How to use NTS, netnod.se
Best practices for connecting to NTP servers, netnod.se
Korrekt och spårbar tid och takt (PTS).
ESP32: System time and SNTP, techtutorialsx
- Espressif: System Time, RTC Timer Clock Sources etc.
- void sntp_set_sync_mode(sntp_sync_mode_t sync_mode), Espressif Set the sync mode.
- Espressif RTC System Time API Reference
- C++ localtime()
- ESP32 Time Library Sync Interval
An application with this initialization code [configTime() called in the setup loop syncs time with NTP server, getLocalTime() function reads the internally kept Time.
] will periodically synchronize the time. The time synchronization period is determined by CONFIG_LWIP_SNTP_UPDATE_DELAY (default value is one hour). To modify the variable, set CONFIG_LWIP_SNTP_UPDATE_DELAY in project configuration. - Getting Date & Time From NTP Server With ESP32, Last Minute Engineers
Once the ESP32 is connected to the network, we use theconfigTime()
function to initialize the NTP client and obtain the date and time from the NTP server.
ThegetLocalTime()
function sends a request packet to an NTP server, parses the time stamp packet received, and stores the date and time information in a time structure, struct tm. - strftime(), Format time as string,"%Y-%m-%d %H:%M:%S"
struct tm, getLocalTime(&tm)
Member Type Meaning Range tm_sec int
seconds after the minute 0-60*
tm_min int
minutes after the hour 0-59
tm_hour int
hours since midnight 0-23
tm_mday int
day of the month 1-31
tm_mon int
months since January 0-11
tm_year int
years since 1900 tm_wday int
days since Sunday 0-6
tm_yday int
days since January 1 0-365
tm_isdst int
Daylight Saving Time flag
*tm_sec
is generally0-59
. The extra range is to accommodate for leap seconds in certain systems.
ESP32 getLocalTime(), struct tm code example
- Espressif SoC ESP32 MCU, System on a Chip (SoC)
- New book by Espressif on ESP32-C3, more than 400 pages, for free!
ESP32-C3 Wireless Adventure, A Comprehensive Guide to IoT
- Practice of IoT Projects
- ESP RainMaker, a complete AIoT platform
- Development Environment
- ESP32-C3
- WiFi & Bluetooth
- Local Control
- Cloud Control
- Smartphone App Development
- Optimisation & Security
- ESP Insights Monitoring
- etc.
Se även ESPHome - 160+ ESP32 Projects, Tutorials and Guides with Arduino IDE, Random Nerd Tutorials
- avr-libc - Standard C library for AVR-GCC
- Save Data to ESP32 Flash Permanently using Preferences Library, ersätter Arduino Uno EEPROM och är effektivare samt behåller värdena även efter uppladdad ny kod till ESP32.
Preferences, Espressif latest, Preferences Type: Bytes uint8_t variable (= array)
OBS! Namespace and key names are character strings and are limited to a maximum of 15 characters.
ESP32 Save Data Permanently using Preferences Library, RandomNerdTutorials
Espressif: Preferences, Library Overview - data types
How do I save and read array values with preferences?
Preferences and save a struct:
struct settings
{
int onbefor;
int offabove;
bool automatic;
bool cent;
};
settings save1 = { 10, 18, true, false };
settings retrieve1 = { 0, 0, 0, 0 };
prefs.begin("Settings"); //namespace
prefs.putBytes("Settings", &save1, sizeof(save1));
prefs.getBytes("Settings", &retrieve1, sizeof(retrieve1));
prefs.end();
- ESP32: Best way to store data frequently?, ESP32 use NOR flash storage, which is usually rated for between 10,000 to 100,000 write cycles.
- ESP32: Maximizing Execution Speed, Optimizing execution speed is a key element of software performance.
- How to use FreeRTOS with Arduino – Real-time operating system, Microcontrollerslab
This is a getting started tutorial on FreeRTOS using Arduino. To demonstrate examples and use of various features of the FreeRTOS operating system, we will use Arduino Uno board and Arduino IDE for writing programs. But you can also use other development boards such as ESP32 and ESP8266. - FreeRTOS - What is An RTOS?
- What and How of FreeRTOS architecture, The Architecture of Open Source Applications
- FreeRTOS Core Libraries - coreMQTT
- Espressif Arduino-ESP32 releases
- Espressif Arduino-ESP32 2.0.1 fick bl.a. Thread-Safe I2C based on ESP-IDF API
- Espressif ESP32 News
- ESP32 Arduino Core´s documentation
- FreeRTOS Documentation:
Mastering the FreeRTOS Real Time Kernel - a Hands On Tutorial Guide
FreeRTOS V10.0.0 Reference Manual - Espressif ESP32 FreeRTOS, Espressif
This section contains documentation of FreeRTOS types, functions, and macros. It is automatically generated from FreeRTOS header files. - Multitasking on ESP32 with Arduino and FreeRTOS
- How to Write Parallel Multitasking Applications for ESP32 using FreeRTOS & Arduino
- ESP32: Tips to increase battery life
- ESP32 Dual Core with FreeRTOS and Arduino IDE
- ESP32 Arduino: Creating a FreeRTOS task
- ESP32 Arduino: Using FreeRTOS functions
- How to use ESP32 Dual Core with Arduino IDE
- ULP Coprocessor programming, Espressif
- Queue, Mutex & Semaphore Inter-Task Communication
- Inter-task Communication, freertos.org, Queues, Mutexes & Semaphores
- Communication Between RTOS Tasks, Open4Tech
- RTOS: Mutex and Semaphore Basics, Open4Tech - As embedded system designers, it is our job to identify the critical sections of the program and use mutexes to protect them.
- ESP32 Passing Values Between FreeRTOS Tasks
- FreeRTOS Queues, see more below
- FreeRTOS Binary Semaphore – Examples of Tasks Interrupt Synchronization using Arduino
- ESP32 Arduino: Communication between tasks using FreeRTOS queues
- ESP32 Arduino: Getting available messages and free spaces of FreeRTOS queue
int messagesWaiting = uxQueueMessagesWaiting(queue);
int emptySpaces = uxQueueSpacesAvailable(queue);
ESP32 Arduino: FreeRTOS queues performance test - Mutex vs Semaphore, A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore. The Mutex is a locking mechanism that makes sure only one thread (task) can acquire the Mutex at a time and enter the critical section. This thread only releases the Mutex when it exits the critical section.
- FreeRTOS Mutexes [Inter-task communication and synchronisation]
- FreeRTOS: Semaphore / Mutexes API functions
- FreeRTOS Binary Semaphore – Examples of Tasks Interrupt Synchronization using Arduino
- Introduction to RTOS - FreeRTOS Semaphore Example
- At Inter-Task communication via Queue messages by xQueueReceive() controlling the Task execution, one can get a similar function as vTaskDelayUntil() via the xTicksToWait in xQueueReceive() by calculating a new xTicksToWait for an absolute until time just before the code-row with the xQueueReceive().
It will give the combined function of xQueueReceive() and vTaskDelayUntil()! - Is it possible to Receive Queue (xQueueReceive) inside periodic task (vTaskDelayUntil)?
- FreeRTOS Queues, Inter-task communication and synchronisation
- Event Bits (or flags) and Event Groups, FreeRTOS Inter-task communication and synchronisation
- Guide to Reduce the ESP32 Power Consumption by 95%
- DFROBOT: FireBeetle ESP32 IoT Microcontroller, 11µA at deep sleep, 2mA light sleep
- Insight Into ESP32 Sleep Modes & Their Power Consumption
- DFROBOT: WiDo - An Arduino Uno Compatible IoT
- FreeRTOS, Cores, Kernel Control & Task Control:
- FreeRTOS, Kernel Control
- FreeRTOS, Task Control
- vTaskDelay(0) vs taskYIELD()
- vTaskDelay(0) vs vTaskDelay(1)
- FreeRTOS, Task Control
- vTaskDelay()
- ESP32: Keep WiFi connection alive with a FreeRTOS task, vTaskDelay()
- vTaskDelayUntil(), freertos.org
- xTaskDelayUntil(), freertos.org
- xTaskAbortDelay, freertos.org
- Be careful when using xTaskAbortDelay() along vTaskDelayUntil()
- How to unblock task in vTaskDelayUntil?
- vTaskDelayUntil(), kubos.com
- vTaskSuspend(), freertos.org
- Use of vTaskSuspend() and vTaskResume() functions
- RTOS Task Notifications
- xTaskNotify / xTaskNotifyIndexed
- "Direct To Task Notifications" för effektivare kod: "Unblocking an RTOS task with a direct notification is 45% faster and uses less RAM than unblocking a task with a binary semaphore."
Perfekt där man har en Task som exekverar regelbundet helt asynkront men man ibland behöver exekvera / unblock synkront från annan Task eller programfunktion.
In Task_LCDbuttonsHandler():
TickType_t xLastWakeTime = xTaskGetTickCount();
const TickType_t xFrequency = 250 / portTICK_PERIOD_MS;
TickType_t xTicksToWait;
while (true)
{
if ((xTaskGetTickCount() - xLastWakeTime) < xFrequency)
{
xTicksToWait = xFrequency - (xTaskGetTickCount() - xLastWakeTime);
}
else
{
xTicksToWait = 1;
}
ulTaskNotifyTake(pdTRUE, xTicksToWait); // Unblocks each 250ms
xLastWakeTime = xTaskGetTickCount();
[...]
}
In StateHandler():
xTaskNotifyGive(TaskLCDbuttonsHandler); // Unblocks Task_LCDbuttonsHandler()
- When can we not use task notificatin as binary semaphore?
- xTaskNotifyGive / xTaskNotifyGiveIndexed
- ulTaskNotifyTake / ulTaskNotifyTakeIndexed
- xTaskNotify / xTaskNotifyIndexed
- Tasks and Co-routines
- ESP32 Espressif Built-in Task Priorities, System Task priority in Core 0 as reference
- ESP32 Speed Optimization
- ESP32 Inter-Processor Call (IPC), ESP32 inter-processor communication
Har tänkt att float- och int-variabler accessas inom en klockcykel så ingen risk för kollision där, men kan ju bli det när en global sådan variabel accessas samtidigt från de två olika CPU-kärnorna! Så ett lite feltänk pga oerfaren inom Multitasking- / Mulitecore-kodande!
Access till globala variabler kan ge konflikt om man inte skapar exklusiv access via Semaphore-Mutex.
Samt om risk för race-condition ge exklusiv access till globala double-variabler (s.k. none-atomic variables) då de tar två klockcykler att accessa, samt troligen samma till alla class-object instanser (eller bara dess funktioner()?) i FreeRTOS Multitasking-koddrift! - FreeRTOS (IDF), Symmetric Multiprocessing
- How to Establish Inter-communication between the Cores / Tasks of ESP32?
- How to use ESP32 Dual Core with Arduino IDE, RandomNerdTutorials
- Minne, minneshantering & minnesläckage:
- Memory leak, Wikipedia
Resource acquisition is initialization (RAII) is an approach to the problem in C++ - Software aging, Wikipedia
- Heap Memory Debugging, Espressif
- Heap Memory Information, Espressif
- Heap Corruption Detection, Espressif
- Heap Tracing, Espressif
- Heap Task Tracking
- How to Diagnose Memory Leaks, Espressif
- ESP.getMinFreeHeap()
- ESP.getMaxAllocHeap()
- ESP.getFreeHeap()
- ESP.getHeapSize()
- esp_get_free_heap_size()
- esp_get_minimum_free_heap_size()
Difference between ESP.getFreeHeap() and esp_get_free_heap_size()? - Heap Memory, Espressif
- Heap Memory Allocation, Espressif
- Memory Types, Espressif
- Performance: Minimizing RAM Usage, Espressif
- Measuring Dynamic Memory Usage, Espressif
- Reducing FreeRTOS Stack Sizes, Espressif
vTaskGetInfo() - Resource Acquisition Is Initialization (RAII), cppreference.com
Resource acquisition is initialization (RAII), Wikipedia
is a C++ programming technique which binds the life cycle of a resource that must be acquired before use (allocated heap memory, thread of execution, open socket, open file, locked mutex, disk space, database connection—anything that exists in limited supply) to the lifetime of an object.
"Get rid of manual memory management and you´ll get rid of leaks. Embrace RAII, and never use a resource unless it´s wrapped in a handler whose single purpose is to wrap that resource." (källa)
- Memory leak, Wikipedia
- FreeRTOS / PlatformIO / Espressif Debugging & Code verification:
- FreeRTOS: uxTaskGetSystemState()
- FreeRTOS:vTaskGetRunTimeStats()
- FreeRTOS: vTaskGetIdleRunTimeCounter()
- vTaskGetRunTimeStats(), GAP8
- vTaskGetRunTimeStats(), ESP-IDF Programming Guide
- vTaskGetRunTimeStats(), KubOS
- FreeRTOS: vTaskGetInfo()
- Espressif: Heap Memory Debugging
- Espressif: Minimizing RAM Usage
- Heap Memory Debugging, ESP-IDF Programming Guide
- Heap Corruption Detection, ESP-IDF Programming Guide
- Espressif: How to Optimize Performance
- uxTaskGetNumberOfTasks(), GAP8
- Measure ESP32 CPU Utilization, StackOverflow
- Core Panic with Bluetooth + freeRTOS, Espressif forum
- ESP32 CPU load test without special configuration.
- Approximate reasonably CPU load per core?, ESP32.com
- FreeRTOS: Run Time Statistics
- Espressif Fatal Errors, Guru Meditation Error: Core 0/1 panic´ed.
- ESP32 Logging library
- ESP32 Logging, log_d etc
- ESP32: How to Log Data (10 Different Ways), RandomNerdTutorials
- ESP Insights, Remotely Monitor Your ESP Devices, Identify Issues Faster
- RTC data store, ESP Insights
- RTC data store II, ESP Insights
- ESP Insights API
- To get started with ESP Insights, kodexempel
- ESP Insights Minimal Diagnostics example
- ESP Insights Getting Started
- ESP Insights Blog, The ESP Journal
- Register Dump and Backtrace:
- maximeborges / esp-stacktrace-decoder
- ESP Stack Trace Decoder, An online ESP stack trace decoder that runs in your browser
(\PlatformIO\Projects\PWMcontroller\.pio\build\wemos_d1_uno32\firmware.elf)
GitHub maximeborges / esp-stacktrace-decoder - Espressif Application Level Tracing Library
- PlatformIO and ESP32: ESP-IDF 4.0, stack trace decoding, reddit
PlatformIO: pio device monitor
Filters - esp32_exception_decoder
To make the exception decoder work it needs debug informations. For this you need to change the build type to debug instead of release. Add build_type = debug to your platformio.ini. källa
GitHub: platform-espressif32/monitor / filter_exception_decoder.py - Register Dump and Backtrace, Espressif
- IDF Monitor adds more details to the backetrace dump, Espressif
- espressif / esp-idf-monitor, GitHub
- C++ Exception Handling, Espressif
- esp-idf / examples /cxx / exceptions/, GitHub
- Core Dump (to Flash), Espressif
- Save / keep data via RTC-memory after a soft-restart / Code-Crasch:
- RTC Slow / Fast Memory, Espressif
- If a system crash causes a restart, it would be a software reset so NOINIT data would be preserved in RTC RAM via RTC_NOINIT_ATTR, GitHub
You can also test a system crash by having an assertion fail such as "assert(0);" which causes a SW_CPU_RESET (software reset). - Variable with RTC_NOINIT_ATTR is not initialized at program start to not erase the value stored in the RTC memory - initialize in setup() for the ESP_RST_POWERON reset reason esp_reset_reason()
- esp_register_shutdown_handler(), Espressif
- esp_system_abort trigger a software abort, Espressif
- Miscellaneous System APIs - Software Reset, Espressif
- Does your design ensure CHIP_PU doesn´t come up until at least 50µs after the power rails, as mentioned in the datasheet? The datasheet also points to the WROOM-32 one, which says:
To ensure the power supply to the ESP32 chip during power-up, it is advised to add an RC delay circuit at the EN pin. The recommended setting for the RC delay circuit is usually R=10kΩ and C=0.1µF. ESP32 Pullup=45kΩ. Även vid hard-reset via GPIO till RST/EN-pin! - ESP Hardware Design Guidelines - External Capacitor
- How to Calculate the Capacitor of the Reset Input of a C51 Microcontroller
- ESP32 Power Supply - do I need input capacitors?
- Purpose of capacitor for MCU reset pin
- Debugging with PlatformIO: Part 1, PIOLabs: Back to the Basics
- Debugging with PlatformIO: Part 2, PIOLabs: Debugging an Embedded Target
- Debugging with PlatformIO: Part 3, PIOLabs: PlatformIO Unified Debugger in CLI mode
- Debugging with PlatformIO: Part 4, PIOLabs: Using Semihosting on ARM Targets
- Analyze your firmware footprint with PlatformIO: Part 1, PIOLabs: Intro and basic analysis
- Analyze your firmware footprint with PlatformIO: Part 2, PIOLabs: Project Inspector
- PIOLabs: Insights, PlatformIO
- FreeRTOS, Interrupt & ISR (Interuppt Service Rutine):
- ESP32 Interrupts, Soft & Hard, Arduino, The Engineering Projects
- Timer Interrupts with ESP32 - Precision sampling rate, iotespresso.com
- Volatile - Variable scope qualifiers, Arduino reference
- What is volatile keyword in C++?, Tutorialspoint
- The interrupt service routine (ISR) and volatile variables, TechExplorations
- ESP32 High Priority Interrupts, Espressif
-
Interrupt Allocation - Overview
esp_intr_alloc()
:
- Allocating an external interrupt will always allocate it on the core that does the allocation.
- Freeing an external interrupt must always happen on the same core it was allocated on.
-Esp_intr_disable()
andesp_intr_enable()
external interrupts from another core is allowed.
Care should be taken when callingesp_intr_alloc()
from a task which is not pinned to a core. During task switching, these tasks can migrate between cores. Therefore it is impossible to tell which CPU the interrupt is allocated on, which makes it difficult to free the interrupt handle and may also cause debugging difficulties. It is advised to usexTaskCreatePinnedToCore()
with a specific CoreID argument to create tasks that allocate interrupts. In the case of internal interrupt sources, this is required.
Conclusion: call theesp_intr_alloc()
from within the Deferred interrupt processing Task to get it pinned to the same core as the Task.
When using Espressif Arduino Framework in PlatformIO / VSCode, Bing Copilot says:
"The interrupt itself is not directly pinned to a specific core. By default, the ESP32 handles interrupts on whichever core is available. However, you can influence which core handles the interrupt by creating a task pinned to a specific core and processing the interrupt within that task.
ISR Execution: The ISR (Interrupt Service Routine) will be executed on the core that is currently available when the interrupt occurs. You cannot directly pin the ISR to a specific core.
Task Handling: To ensure that the processing of the interrupt is handled on a specific core, you create a FreeRTOS task pinned to that core. This task can then handle the interrupt processing." I.e. Deferred interrupt processing.
- FreeRTOS Binary Semaphore – Examples of Tasks Interrupt Synchronization using Arduino, Microcontrollerslab
Deferred interrupt processing
It can be used to unblock a task each time a particular interrupt occurs effectively synchronizing the task with the interrupt. This allows the majority of the interrupt event processing to be implemented within the synchronized task with only a very fast and short portion remaining directly in the interrupt service routine. This is also known as deferred interrupts processing.
Deferred interrupt processing will typically involve recording the reason for the interrupt and clearing the interrupt within the ISR, but then unblocking an RTOS task so the processing necessitated by the interrupt can be performed by the unblocked task, rather than within the ISR.
If the task to which interrupt processing is deferred is assigned a high enough priority then the ISR will return directly to the unblocked task (the interrupt will interrupt one task, but then return to a different task), resulting in all the processing necessitated by the interrupt being performed contiguously in time (without a gap), just as if all the processing had been performed in the ISR itself.
Deferred interrupt context switch: xQueueSendTobackFromISR() will set *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task to unblock, and the unblocked task, "the Deferred interrupt process", has a priority higher than the currently running task. If xQueueSendToBackFromISR() sets this value to pdTRUE then a context switch should be requested before the interrupt is exited. This context switch request is done by a call to portYIELD_FROM_ISR() / taskYIELD_FROM_ISR() (which are the same) at the end of the ISR and is executed after the ISR is closed.
Otherwise will the interrupted Task continue to execute after finished ISR and the context switch to the higher priority Deferred Task happens first at the next Time Slicing tick interrupt of the Preemptive multitasking scheduler, which with the fix 1ms time slice ticks in ESP32 FreeRTOS will cause a random delay of ≤1ms.
This random delay of ≤1ms was very visiable measured by a digital memory oscilloscope in my batterymonitor project, where with the use of portYIELD_FROM_ISR() / taskYIELD_FROM_ISR() the context switch via ISR gets a good real-time function with extremely small variation in the 25µs Deferred ISR Interrupt Latency, ESP32 Interrup ISR → Deferred Task interrupt processing latency! A direct contex switch from ISR to an unblocked Deferred Task! An extreme difference from without Yield() given ≤1ms latency!
To not risk a context switch inside the small ISR by another interrupt one could enclose it inportENTER_CRITICAL_ISR(&Mux) / portEXIT_CRITICAL_ISR(&Mux)
, which blocks all other interrupts. source1, sourc2, sourc3, sourc4, atomic instruction, FreeRTOS Kernel Control
N.B.: FreeRTOS API functions must not be called from within a critical section!
void IRAM_ATTR ISR_deferred(void)
But inside a
{
portENTER_CRITICAL_ISR(&Mux); // Do not use here!
int64_t InterruptTime;
BaseType_t HigherPriorityTaskWoken = pdFALSE;
InterruptTime = esp_timer_get_time();
xQueueSendToBackFromISR(DeferredInterruptQueue, &InterruptTime, &HigherPriorityTaskWoken);
if( HigherPriorityTaskWoken )
{
portYIELD_FROM_ISR();
}
portEXIT_CRITICAL_ISR(&Mux); // Do not use here!
}
portENTER_CRITICAL() / portENTER_CRITICAL_ISR()
: FreeRTOS API functions must not be called from within a critical section, which means that in the above ISR() should notportENTER_CRITICAL_ISR(&Mux)
be used!
DuckDuckGo: "Deferred interrupt processing" -
FreeRTOS: Queues, Inter-task communication and synchronisation
FreeRTOS: Queue Management Modules, all functions / API
FreeRTOS: Queue Set API Functions
ESP32 Arduino: FreeRTOS Queues, techtutorialsx
Queues are the primary form of intertask communications. They can be used to send messages between tasks, and between interrupts and tasks.
In most cases they are used as thread safe FIFO (First In First Out) buffers with new data being sent to the back of the queue, although data can also be sent to the front.
Deferred interrupts processing II: In your abstraction layer for the esp32 you can create a task that waits on some queue. In the interrupt routine [ISR] only post to the queue and return. The task you created then will wake up and call the callback. källa
FreeRTOS Interrupt Management Examples with Arduino, Deferred Interrupt with Queue. - Espressif FreeRTOS Queue API, how to use in an interrupt service routine ISR
- FreeRTOS Interrupt Management Examples with Arduino, Microcontrollerslab
FreeRTOS interrupt provides an interrupt safe version of queue API to read and write data from queues using ISR. These are the two API functions: xQueueSendToBackFromISR(), xQueueReceiveFromISR(). - FreeRTOS: xQueueSendToBackFromISR()
- ESP32 External Interrupts Pins in Arduino – GPIO Interrupt Examples
- ESP32 Interrupt Latency Measurement, is roughly 1.8µs with the CPU running @ 240MHz.
- Button (external) interrupts with ESP32, portENTER_CRITICAL_ISR
FreeRTOS API functions must not be called from within a critical section. - ESP32 Interrupt Tutorial
- Arduino and Esp32 Interrupts (ISR)
- ESP32 External Interrupts using Arduino IDE, digitalPinToInterrupt(pin)
- FreeRTOS: xTimerPendFunctionCallFromISR()
- ESP32 High Resolution Timer, int64_t esp_timer_get_time() returns 64-bit time since startup, in microseconds (µs). int64 = 292,5 years before overflow at µs resolution! The millis() overlows after 49,7days!
Unlike gettimeofday function, values returned by esp_timer_get_time() start from zero after startup or the chip wakes up from deep sleep and do not have timezone or DST adjustments applied.
The millis() can be called in an ISR but it doesn´t increment inside it but gives the time for the interrupt. The esp_timer_get_time() can also be called in an ISR, and do probably not increment either. - Interrupt allocation, Docs Espressif
Care should be taken when allocating an interrupt using a task not pinned to a certain core; while running code not in a critical secion, these tasks can migrate between cores at any moment, possibly making an interrupt operation fail because of the reasons mentioned above. It is advised to always use xTaskCreatePinnedToCore with a specific CoreID argument to create tasks that will handle interrupts.
- Allocating an external interrupt will always allocate it on the core that does the allocation.
- Freeing an external interrupt must always happen on the same core it was allocated on.
- Disabling and enabling external interrupts from another core is allowed.
- ISR can´t be migrated between cores, so they´re defacto ´pinned´ to a core. The core is the one that installs the interrupt.
- Functions called by a Task runs on the same core as the task.
The ESP32 has two cores, with 32 interrupts each. Each interrupt has a certain priority level, most (but not all) interrupts are connected to the interrupt mux.
Because there are more interrupt sources than interrupts, sometimes it makes sense to share an interrupt in multiple drivers.
Multicore issues - IRAM-Safe Interrupt Handlers - Multiple Handlers Sharing A Source - ESP32 Arduino: Timer interrupts, techtutorialsx
- ESP32 Arduino: External interrupts, techtutorials
- Introduction to RTOS - Solution to Part 9 (Hardware Interrupts), Digi-Key
- FreeRTOS Software Timer API Functions
- FreeRTOS: Using Software Timers, Open4Tech
- RTOS Task Notifications, FreeRTOS
- FreeRTOS Binary Semaphores [Inter-task communication and synchronisation], freertos.org
Binary semaphores and mutexes are very similar but have some subtle differences: Mutexes include a priority inheritance mechanism, binary semaphores do not. This makes binary semaphores the better choice for implementing synchronisation (between tasks or between tasks and an interrupt), and mutexes the better choice for implementing simple mutual exclusion. - FreeRTOS Mutexes [Inter-task communication and synchronisation], freertos.org
- ESP32 Arduino: Getting DHT22 sensor measurements with interrupts, techtutorialsx
In terms of implementation, our code will periodically read measurements from the DHT22 sensor. Nonetheless, instead of relying on polling or Arduino delays, we will use the timer interrupts to implement the periodicity of the measurements. - Mutual exclusion between task and interrupt, freertos.org
- What is and when to use IRAM_ATTR? (ISR), Espressif ESP32
- Configuring & Handling ESP32 GPIO Interrupts In Arduino IDE, LastMinuteEngineers
- FunctionalInterrupt.ino - example C++ class, Espressif Arduino ESP32
- attachInterrupt( ) - modes ONLOW_WE & ONHIGH_WE, how do they work?
So ONLOW_WE maps to GPIO_INTR_LOW_LEVEL: "input low level trigger" with wakeup enabled (WE), and ONHIGH_WE to GPIO_INTR_HIGH_LEVEL: "input high level trigger" with wakeup enabled. There is also ONLOW and ONHIGH, that is without wakeup.
So, in simple words, ONLOW_WE will trigger an interrupt if the input signal level is low (not a falling edge) and wake up the ESP32 from light sleep, if it is currently in light sleep.
Espressif Interrupts - A sketch can be woken up from sleep by an interrupt using
attachInterrupt()
with e.g. theONHIGH_WE
., Only ONLOW_WE or ONHIGH_WE interrupts work, no edge, that´s an SDK or CPU limitation. - ESP32 practical power saving: wake up from light sleep via UART and GPIO
- ESP32 practical power saving: manage WiFi and CPU
- ESP32 practical power saving: modem and light sleep
- Espressif: GPIO wakeup (light sleep only)
Tillsammans med Interrupt på samma GPIO:
pinMode(19, INPUT_PULLUP);
I min ISR växlar jag till FALLING-interrupt samt sätter en ISRFlag=false så den bara kan anropa dess deferred interrupt handler en gång. Sedan återställer jag till ONLOW_WE-interrupt i deferred interrupt handler samt sätter ISRFlag=true. På så sätt får jag en flanktriggnings liknande funktion som FALLING trots ONLOW_WE. Tänker även prova med att bara sätta ONLOW_WE-interrupt precis innan ESP32 sätts i light-sleep där.
gpio_wakeup_enable(GPIO_NUM_19, GPIO_INTR_LOW_LEVEL);
esp_sleep_enable_gpio_wakeup();
attachInterrupt(digitalPinToInterrupt(19), ISR_INA226Batt, ONLOW_WE);
I början av ISR:
attachInterrupt(19, ISR, FALLING);
Sist i DeferredInterruptTask:
static int64_t InterruptTime = esp_timer_get_time();
if(ISRFlag)
{
ISRFlag = false;
// Flag (boolean) cleared here and set in DeferredInterrupt-Task
xQueueSendToBackFromISR(DeferredInterruptQueue, &InterruptTime, NULL);
}
attachInterrupt(19, ISR, ONLOW_WE);
ISRFlag = true;
- Insight Into ESP32 Sleep Modes & Their Power Consumption
- ESP32 GPIO inputs/outputs:
- ESP32 Digital Inputs and Digital Outputs (Arduino), RandomNerdTutorials
- ESP32 Pinout Reference: Which GPIO pins should you use?
- ESP32 Pinout – How to use GPIO pins?
Some GPIO pins are used to configure bootloader or flashing mode of ESP32 during application flashing or bootloading.
GPIO0
GPIO2
GPIO4
GPIO5 (must be HIGH during boot)
GPIO12 (must be LOW during boot)
GPIO15 (must be HIGH during boot)
- ESP32 Digital Inputs & Digital Outputs – Arduino Tutorial
- DuckDuckGo: ESP32 PIO direct port manipulation fast
- Faster ESP32, ESP32 GPIO 0/1, how to go straight to the register and write in the memory.
- ESP32 Port Manipulation
- Comparing the speeds of different GPIO Read/Write methods, code
ESP32 GPIO 22:
GPIO.out_w1ts = ((uint32_t)1 << 22); set 1
GPIO.out_w1tc = ((uint32_t)1 << 22); set 0
and
REG_WRITE(GPIO_OUT_W1TS_REG, BIT22); set 1
REG_WRITE(GPIO_OUT_W1TC_REG, BIT22); set 0
are equally fast with 100ns per 1-0-1 output.
Read value from GPIO:
value = (GPIO.in >> 22) & 0x1;
value = (REG_READ(GPIO_IN_REG) & 22);
are equally fast with 50ns per intput.
- ESP32 - GPIO speed lower than expected
- ESP32 Internal Pullup and Pulldown, Espressif
INPUT_PULLUP & INPUT_PULLDOWN:pinMode(19, INPUT_PULLUP);
- Full Guide to ESP32 Pinout Reference: What GPIO Pins Should We Use?
- Pay attention that channels related to the ADC2 interfere with the Wi-Fi. If the Wi-Fi of the ESP32 is running, you better use the ADC1 pins.
- ESP32: Please do not use the interrupt of GPIO36 and GPIO39 when using ADC or Wi-Fi and Bluetooth with sleep mode enabled.
- ESP32 GPIO pins info, restrictions and features, Blynk.Community
- ESP32 Series Datasheet, Espressif
- Kolban´s book on ESP32, drygt 1000 sidor
- Watchdog Timer (WDT), FreeRTOS ESP32: 2022-06-27
- Watchdogs latest ESP32 API-reference ESP-IDF
- Interrupt Watchdog Timer (IWDT)
- Task Watchdog Timer (TWDT) - Watchdog Timers, Espressif ESP32 datasheet
- Watchdog Timers (WDT), ESP32 technical reference manual
- ESP Reset Message Strings
- esp_reset_reason_t, Enumerations Reset reasons
- Watchdogs, ESP-IDF Programming Guide
- Miscellaneous System APIs - Reset Reason
- Watchdogs latest ESP32 API-reference ESP-IDF
- RTOS, Finite State Machine & OOP coding:
- State Machines Part-1: What is a state machine?
- State Machines Part-2: Guard conditions
- State Machines Part-3: Input-Driven State Machines
- State Machines Part-4: State Tables and Entry/Exit Actions
- State Machines Part-5: Optimal Implementation in C
- State Machines Part-6: What is a Hierarchical State Machine?
- Beyond the RTOS - Part 1: Concurrency & "spaghetti" as main challenges of professional developers
- Beyond the RTOS - Part 2: Best practices of concurrent programming and Active Object pattern
- Beyond the RTOS - Part 3: Active Objects implemented on top of FreeRTOS
- Beyond the RTOS Part-4: state machines as "spaghetti" reducers
- RTOS Part-1: What is a Real-Time Operating System?
- Event-Driven Programming Part-1: GUI example, events, event-loop, run-to-completion, no-blocking
- OOP Part-1: Encapsulation (classes) in C and C++
- OOP Part-2: Inheritance in C and C++
- OOP Part-3: Principles - Inheritance, Polymorphism, Encapsulation, Abstraction
- OOP Part-4: Access Control, In-built Packages, Object Class
- OOP Part-5: Abstract Classes, Interfaces, Annotations
- Hierarchical State Machines
- About QM™ - Model-Based Design tool
- PWM, LEDC & Motor Control Pulse Width Modulator (MCPWM), ESP32:
- LED Control (LEDC), Espressif
- ESP32 LEDC Output, ESPHome
- LED Control (LEDC), Arduino-ESP32
- ESP32-IDF — LEDC Get Started
- LEDC, Supported Range of Frequency and Duty Resolutions, Espressif
- LEDC, Timer Configuration, Espressif
- LED PWM Controller (LEDC), Espressif ESP32 technical reference manual
- LED PWM, 80MHz/8MHz oscillator clock & bits accuracy, Espressif ESP32 datasheet
- Change PWM Frequency on-the-fly, Espressif
- Change PWM Duty Cycle using Hardware - fade, Espressif
- Change PWM Duty Cycle Using Software, Espressif
- Change LEDC frequency and pwm on the fly without glitches, ESP32.com
- Motor Control Pulse Width Modulator (MCPWM), Espressif
- Remote Control Transceiver (RMT)
-
ESP32 LEDC Output:
Frequency1
PWM Bit depth
Available steps for transitions (2Bit)
≤1220Hz
16
65536
≤2441Hz
15
32768
≤4882Hz
14
16384
≤9765Hz
13
8192
≤19531Hz
12
4096
≤39062Hz
11
2048
≤78125Hz
10
1024
≤156250Hz
9
512
≤312500Hz
8
256
- The ESP32 PWM hardware has 16 different channels, not pins. You can assign any of these channels to any GPIO pin that you want. But it has to have an output driver or in other words, it should be capable of operating as an output pin.
The ESP32 PWM controller has 8 high-speed channels and 8 low-speed channels, which gives us a total of 16 channels. They´re divided into two groups depending on the speed. For each group, there are 4 timers / 8 channels. This means every two channels share the same timer. Therefore, we can´t independently control the PWM frequency of each couple of channels.
So this means we´ve got 16 channels that we can control their PWM duty cycle independently. But the frequency has to be shared between each couple of channels routed to the same timer. ESP32 PWM Tutorial & Examples
- ESP32 Change CPU Speed / clock frequency: 2022-06-27
- My be fixed frequency intervalls, 240, 160, 80, 40, 20 & 10MHz för ESP32 with 40MHz XTAL crystal frequency, getXtalFrequencyMhz() / getCpuFrequencyMhz() / setCpuFrequencyMhz(10) / getApbFrequency(): ESP32 Change CPU Speed (in Arduino).
N.B. 40MHz, 20MHz & 10MHz only usable in case you are not using Wi-Fi or Bluetooth?!
"The only preferable values entered are 240, 160, and 80MHz, but you can also use lesser values, i.e., 40, 20 and 10MHz, in case you are not using Wi-Fi or Bluetooth [PWM?]."
The normally 80MHz ApbFrequency is also changed with CPU-frequency as it goes <80MHz - does it influence the PWM bit depth vs max frequency above?
- My be fixed frequency intervalls, 240, 160, 80, 40, 20 & 10MHz för ESP32 with 40MHz XTAL crystal frequency, getXtalFrequencyMhz() / getCpuFrequencyMhz() / setCpuFrequencyMhz(10) / getApbFrequency(): ESP32 Change CPU Speed (in Arduino).
- OTA (Over-The-Air) code update ESP32:
- Over-the-Air (OTA) Programming on ESP32 Using Arduino
- Espressif: OTA Web Update
- ESP32 OTA (Over-the-Air) Updates – AsyncElegantOTA using Arduino
- ESP32 Basic Over The Air (OTA), Arduino IDE
- ESP32 Over-the-air (OTA) Programming – Web Updater Arduino
- Librarie: esp32FOTA
- GitHub: esp32FOTA library for Arduino, https support
- ESP32 Secure firmware update Over-The-Air (OTA)
- Atomic variables:
- Programming Atomic Vs. Nonatomic, Codingdeeply
- C11 atomic implementation, GCC Wiki
- Volatile and Atomic variables in C++, how they behave differently in different scenarios!!!
- What´s the difference between the atomic and nonatomic attributes?
- Thread Safety / Race Conditions:
- Thread safety, Wikipedia
- What Is a Race Condition?
- FreeRTOS Queues, In most cases they are used as thread safe FIFO (First In First Out) buffers
- What is a race condition?
- How to make printf/sprintf/strtod thread safe
- FreeRTOS Race Condition bugfix, in ESPAsyncWebServer-esphome
- Multitasking FreeRTOS
- TinyML ESP32 Arduino, TensorFlow:
- TinyML.org
- TinyML unlocks new possibilities for sustainable development technologies
- TinyML is bringing deep learning models to microcontrollers
- Edge AI Anomaly Detection Part 4: Deploy TinyML Model in Arduino to ESP32 | Digi-Key
- TensorFlow Lite for Microcontrollers
- Announcing TensorFlow Lite Micro support on the ESP32
- Easy Tensorflow TinyML on ESP32 and Arduino
- TensorFlow, Meet The ESP32, Setting up TensorFlow Lite for PlatformIO Deployment
- How to set up a TensorFlow Lite environment for the ESP32, Adafruit blog
- TinyML Book, TinyML Machine Learning with TensorFlow Lite on Arduino and Ultra-Low-Power Microcontrollers - hos Amazon.se
-
Introduction to TinyML - hos Amazon.se, köpte denna
"This book is an effort by AI Technology & Systems to demystify the TinyML technology including market, applications, algorithms, tools and technology. The book dive deeper into the technology beyond common application and keep it light for the readers with varying background including students, hobbyists, managers, market researchers and developers. It starts with introduction to TinyML with benefits and scalability."
Med bl.a. kapitel om: Predictive Maintenance Solution Interface, Sensors and Analyses, Industry 4.0 Applications, TinyML and Predictive Maintenance, Sensors and Interface, Sensor Data and Equipment State, etc
Känns som jag ska kunna få en bra uppfattning om TinyML kan göra nytta för PWM-regulator + Batterimonitor! - Use PlatformIO to Build Your tinyML Projects
- Easy TinyML on ESP32 and Arduino
- An Introduction to TinyML, Machine Learning meets Embedded Systems
- What is TinyML?
- Introduction to TensorFlow Lite
- A Beginner´s Introduction To TensorFlow Lite
- TensorFlow Blog
- What´s new in TensorFlow 2.11?
- Intro to TinyML Part 1: Training a Model for Arduino in TensorFlow
- TensorFlowLite_ESP32, PlatformIO library
"Allows you to run machine learning models locally on your ESP32 device. This library runs TensorFlow machine learning models on microcontrollers, allowing you to build AI/ML applications powered by deep learning and neural networks." - TensorFlow Lite Micro for Espressif Chipsets, GitHub
- What is TensorFlow? The machine learning library explained.
- Use PlatformIO to Build Your tinyML Projects
- Webpage Bluetooth:
- Communicating with Bluetooth devices over JavaScript, The Web Bluetooth API allows websites to communicate with Bluetooth devices (as ESP32).
- The Web Bluetooth Security Model
- Bluetooth Low Energy: A Primer, a deep walk through
- Controlling an LED using ESP32 BLE
- ESP32 Bluetooth, BLE - Mobile APP:
- DuckDuckGo: ESP32 BLE mobile app
- DuckDuckGo: ESP32 BLE app remote control
- DuckDuckGo: Bluefruit nRF52 ESP32
- Arduino Bluefruit nRF52 API
- Adafruit: Bluefruit LE Connect
- Adafruits: Bluefruit LE Connect Features
- Adafruits: Bluefruit LE Connect Installation and Setup
- Adafruits: Bluefruit LE Connect Library and Config
- APP: Bluefruit Connect
- DuckDuckGo: remoteXY ESP32 Arduino BLE
- RemoteXY
- APP: RemoteXY: Arduino control
- Arduino libraries RemoteXY
- Easy IOT, DFRobot
- Easy IOT – App Controlled RF Sensor Hub
- Espressif: data via bluetooth from ESP32 to android mobile phone
- BLE ESP32, Bluetooth, Send, Receive, Arduino IDE, MIT App Inventor
- BluetoothLE / BLE, MIT App Inventor
- MIT App Inventor Community
- MIT App Inventor, is changing the way the world creates mobile apps
- ESP32 Web Bluetooth (BLE): Getting Started Guide, RandomNerdTutorials
- ESP32 BLE Peripheral (Server), RandomNerdTutorials
- ESP32 Web Servers:
- Om WIFI connection högre upp
- ESP32 Async Web Server – Control Outputs, by XMLHttpRequest(), RandomNerdTutorials
- Enhancing Your ESP32 Web Server: integration of HTML and CSS
- ESP32 DHT22 Web Server, by XMLHttpRequest(), RandomNerdTutorials
- index_html[] PROGMEM = R"rawliteral("html")rawliteral"
Hela Webbsideskoden i en variabel (C/C++):
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
...
</html>)rawliteral";
...
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});
- ESP32 Publish Sensor Readings to ThingSpeak
ThingSpeak - Pushing Updates to the Web Page with HTML5 Server-Sent Events (php) OBS! Både enheten man surfar från och ESP32´s webbserver måste vara uppkopplade mot samma WiFi-nätverka för att det ska fungera. Råkade ut för det när jag testade att datorn / mobilen var uppkopplad mot lägenhetens WiFi-nätverk och ESP32 webbservern mot WiFi-nätverket från Teltonika RUT241 4G-routern och det fungerar inte, naturligtvis!
- Mozilla: Using server-sent events
- Can I Use: Server-sent events
- W3schools: HTML5 Server-Sent Event (SSE)
- W3schools: HTML5 Server-Sent Events (SSE) API
- Tutorialspoint: HTML5 - Server Sent Events
- What Server-Sent Events is - and how and when to implement it
- JavaScript: Server Sent Events
- Real-time Web Apps with Server-Sent Events
- Server sent events (SSE) - automatic reconnect
- Is an EventSource (SSE) supposed to try to reconnect indefinitely?
- Server Sent Events (SSE), JavaScript.info
- X ESP32 ESPAsyncWebServer-esphome library, med bra README manual, GitHub
- X ESP32 ESPAsyncWebServer-esphome, PlatformIO
- X ESP32 ESPAsyncWebServer readme / Manual
- X ESP32 ESPAsyncWebServer - Manual
- X ESP32 Web Server using Server-Sent Events (Sensor values), RandomNerdTutorials
Json is used to format more complex data, so we could have used "TPH":{"temperature":25.2, "pressure":1012, "humidity":76.8} to send 3 readings in one message (comment). - X Reconnect ESP32 to Wi-Fi Network After Lost Connection
ESP32 Wi-Fi Events: ARDUINO_EVENT_WIFI_STA_DISCONNECTED - X ESP32 Arduino: Getting started with WiFi events, techtutorialsx
- X ESP32 Useful Wi-Fi Library Functions Arduino - ESP32 Wi-Fi Events
WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
WiFi.onEvent(WiFiReconnect, ARDUINO_EVENT_WIFI_STA_DISCONNECTED);
WiFi.onEvent(WiFiReconnect, ARDUINO_EVENT_WIFI_STA_LOST_IP);
WiFi.onEvent(WiFiReconnect, ARDUINO_EVENT_WIFI_STA_STOP);
- ESP ESP32 Wi-Fi Event Description, Espressif
- ESP Event Loop Library, Espressif, WiFi.onEvent() is part of this
- ESP ESP32 Wi-Fi Programming Model, Espressif
- ESP Wi-Fi Event-Handling, Espressif
- ESP How To Write a Wi-Fi Application, It is not a MUST, but it is strongly recommended that you take some time to read this article first, especially if you want to program a robust Wi-Fi application, Espressif
- ESP esp-idf/examples/wifi/, GitHub / Espressif
- X Reconnect to Wi-Fi Network After Lost Connection (Wi-Fi Events)
- X Arduino-esp32: WiFi Auto Reconnect Still Not Working - Is there a best practice to guarantee connection?
- X Espressif Wi-Fi Driver: ESP32 Wi-Fi Event Description
- X ESP32 Arduino: Getting WiFi Event information, techtutorialsx
- ESP32 Arduino HTTP server: external and internal redirects, med flera webbsidor i ESP32
- ESP32 Arduino HTTP server: Getting query parameters
- Ring Buffers (för ESP32 24h databuffers, 1 datapunkt/5min?):
- Espressif: Ring Buffers, med exempel
- Espressif Ring Buffer API Reference
- Ring Buffer Basics, Embedded.com
- WebSockets vs SSE:
- Server-Sent Events: the alternative to WebSockets you should be using
- Polling vs SSE vs WebSocket— How to choose the right one
- Comparing WebSockets and Server-Sent Events
- DucDuckGo: ESP32 SSE vs WebSocket
- ESP32 corrupt heap when handling multiple simultaneous requests, Websockets has been updated / fixed, but SSE (which has similarities with websockets) not. As stated I use Server Sent Events so possible an issue still exists in SSE. (2018, ESPAsyncWebServer)
Så med ESPAsyncWebServer verkar WebSockets stabilare, samt kan då även fixa inställningsvärden till ESP32 typ Batterikapacitet (Ah) samt reset, etc.
- WebSockets & binary data:
- How to create custom events for ´ws´ Web-Socket module?
- WebSocket.addEventListener(event, handler)
- A JSON event-based convention for WebSockets
- fselcukcan/ws: custom-event-emit-and-listen, GitHub
- Introduction to WebSockets
- X WebSocket Data Exchange with JSON for ArduinoJson 6, Steph´s µLab +++
- X ESP32 WebSocket Server: Control Outputs Arduino
- X ESP32 minimal JSON webserver example for PlatformIO (ESPAsyncWebserver)
- X ESPAsyncWebServer JSON response example for ArduinoJson 6
- X ArduinoJson.org, Library
- X ESP32 Remote Control with WebSocket
- WebSockets - Living Standard
- The WebSocket API (WebSockets), Mozilla
- WebSocket, Mozilla
- WebSocket: open event, Mozilla
- WebSocket: close event, Mozilla
- WebSocket: message event, Mozilla
- Writing WebSocket servers, Mozilla
- ESP WebSocket Client, Espressif
- ESPAsyncWebServer#readme (manual)
- ESPAsyncWebServer - Methods for controlling websocket connections, ws.enabled()
- ESPAsyncWebServer - Async WebSocket Event
- ESPAsyncWebServer - Methods for sending data to a socket client
- Några WebSocket server functioner (att utforska):
ws.count();
ws.enabled();
ws.hasClient();
ws.getClients();
ws.ping();
ws.url();
ws._handleEvent();
- Sending message to a specific connected users using webSocket?
- How do i send a message to a specific user in ws library?
- webSocketServer node.js how to differentiate clients
- send message to a specific connected client
- WebSocket: Broadcast / client
- ESP32 WebSocket Server: Control Outputs, Arduino
- WebSockets on the ESP32
- Introducing WebSockets - Bringing Sockets to the Web - JavaScript
Low Latency Client-Server and Server-Client Connections. - ESP32 Websocket server: Sending binary frame to client
- ESP32 websocket server: receiving binary frames
- ESP32 Tutorial: Websocket server - Sending binary frame to client
- ESP32 Arduino web server: Sending data to JavaScript client via websocket
- X ESP32 Web Server (WebSocket) with Multiple Sliders, The communication between the clients and the ESP32 is done using WebSocket protocol. Additionally, whenever there´s a slider change from one client, all clients update their slider values simultaneously.
- ESP32 Plot Sensor Readings in Charts (Multiple Series)
- Websocket "sendBIN" is only limited to uint8 array how to send float array?
- JavaScript typed arrays, Mozilla. JavaScript typed arrays are array-like objects that provide a mechanism for reading and writing raw binary data in memory buffers. Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast. However, as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth, it has become clear that there are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data. This is where typed arrays come in.
- WebSocket Server and Client for Arduino ESP32, PlatformIO
- WebSocket Server and Client for Arduino ESP32, GitHub
- What do continuation frames mean in WebSocket protocol?
- Reconnection of Client when server reboots in WebSocket
- WebSocket: How to automatically reconnect after it dies
- How to reconnect to websocket after close connection
function startWebsocket() {
var ws = new WebSocket('ws://localhost:8080')
ws.onmessage = function(e){
console.log('websocket message event:', e)
}
ws.onclose = function(){
// connection closed, discard old websocket and create a new one in 5s
ws = null
setTimeout(startWebsocket, 5000)
}
}
startWebsocket();
- Reconnecting WebSocket library
- Reconnecting WebSocket, GitHub
- PlatformIO: AsyncMqttClient ESP32, This release makes the client more bulletproof than ever. Simply put: right now, even if you do a loop to publish messages at a very fast rate, the client will not break and will not loose functionality (ACKs will still be sent, etc.).
- MQTT via WebSockets to webpage, see: MQTT
- Protocol Buffers (Protobuf):
is a free and open-source cross-platform data format used to serialize structured data. It is useful in developing programs to communicate with each other over a network or for storing data.- Protocol Buffers, Wikipedia
- Protocol Buffers, developers.google
- ESP32 / ESP8266 Arduino: Protocol Buffers, techtutorialsx
- nanopb, Nanopb is a plain-C implementation of Google´s Protocol Buffers data format. It is targeted at 32 bit microcontrollers, but is also fit for other embedded systems with tight (<10 kB ROM, <1 kB RAM) memory constraints. Finns för ESP32 i PlatformIO.
- Embedded Proto, Embedded Proto is an easy to use C++ Protocol Buffer implementation specifically suited for microcontrollers.
- ESP32 Server-Sent Events (SSE) Web Server (Arduino IDE), MicrocontrollersLab
- Server-Sent Events with ESP32 and DHT11, TheEngineeringProjects
- Display Sensor Readings in Gauges with ESP32 Web Server (SSE), MicrocontrollersLab
- ESP32: mDNS address resolution, ESP32 lokalt IP-Nr => namn
- ESP32 WebSocket Server Arduino – Control GPIOs and Relays, MicrocontrollersLab
- ESP32 with Arduino JSON Using Arduino IDE, Microdigisoft
- ESP32 HTTP GET and HTTP POST (JSON, URL Encoded, Text), Microdigisoft
- ESP32 Client-Server Wi-Fi Communication Between Two Boards
- ESP32 Server Client Wi-Fi Communication using Arduino IDE
- ESP-NOW Two-Way Communication Between ESP32 Boards
- Getting Started with ESP-NOW (ESP32 with Arduino IDE)
- Espressif ESP-NOW
- Espressif ESP-NOW api-reference
- Espressif ESP-NOW libraries
- ESP32: WiFi and ESP-Now simultaneously
- ESP32: ESP-NOW Web Server Sensor Dashboard (ESP-NOW + Wi-Fi)
- JavaScript Canvas Graph, Icons, Gauge & GUI libraries Open source:
- 19 Best JavaScript Data Visualization Libraries
- dygraphs
- RGraph
- Chart.js
- Canvas Gauges
- SVG Gauge
- Gauge Charts
- Grafana
- Grafana Dashboards
- Grafana Dashboard API
-
LVGL - Light and Versatile GUI Library, PlatformIO
LVGL - Light and Versatile GUI Library, homepage
SquareLine Studio, Design and build LVGL GUIs with ease
LVGL: Open-source, fully available on GitHub, used by many developers, and trusted by industry leading companies.
Kan kombineras med openHASP, Control your home-automation devices from a customizable touchscreen UI connected via MQTT via an ESP32.- Popular Created by 300+ developers, used by 100,000+ people and downloaded in every minute. LVGL is available in Arduino, PlatformIO, ESP32, MCUXpresso, Zephyr, NuttX, RT-Thread, ARM CMSIS-Pack and many more.
- Cross-platform Has no external dependencies and can be compiled for any vendor´s any MCU or MPU, and (RT)OS to drive ePaper, OLED or TFT displays, or even monitors.
- Lightweight Needs only 32kB RAM, 128kB Flash, a frame buffer, and at least an 1/10 screen sized buffer for rendering.
- Bindings LVGL is written in C (C++ compatible) and has bindings to MicroPython, PikaScript, JavaScript (React-like) and Berry.
- Unicode Character ´DEGREE SIGN´ (U+00B0)
To use in JavaScript / Canvas:´\u{00B0}C´
°C
- Font Awesome, både Free edition with 1588 icons & Pro
FontAwesome Icon Library, version 5.7.2
Används i: ESP32 Web Server using Server-Sent Events, RandomNerdTutorials
Font Awesome 5 Introduction, alla fria Iconer grupperade i ämnesområden, W3Schools
How to Use Font Awesome Icon v5.7.2 as Content in CSS/HTML - FontAwesomeIcons Svg Icons, med SVG-kod för inlinefont i webbsideskoden.
- SVGViewer, SVG Icons with inline SVG-code
- URL-encoder for SVG, för att använda SVG-kodad icon i en html ico/img-tag
- Use inline SVG as favicon
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,[YOUR ENCODED SVG HERE]" />
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='black' viewBox='0 0 16 16'%3E%3Cpath d='M8 4a.5.5 0 0 1 .5.5V6a.5.5 0 0 1-1 0V4.5A.5.5 0 0 1 8 4zM3.732 5.732a.5.5 0 0 1 .707 0l.915.914a.5.5 0 1 1-.708.708l-.914-.915a.5.5 0 0 1 0-.707zM2 10a.5.5 0 0 1 .5-.5h1.586a.5.5 0 0 1 0 1H2.5A.5.5 0 0 1 2 10zm9.5 0a.5.5 0 0 1 .5-.5h1.5a.5.5 0 0 1 0 1H12a.5.5 0 0 1-.5-.5zm.754-4.246a.389.389 0 0 0-.527-.02L7.547 9.31a.91.91 0 1 0 1.302 1.258l3.434-4.297a.389.389 0 0 0-.029-.518z'/%3E%3Cpath fill-rule='evenodd' d='M0 10a8 8 0 1 1 15.547 2.661c-.442 1.253-1.845 1.602-2.932 1.25C11.309 13.488 9.475 13 8 13c-1.474 0-3.31.488-4.615.911-1.087.352-2.49.003-2.932-1.25A7.988 7.988 0 0 1 0 10zm8-7a7 7 0 0 0-6.603 9.329c.203.575.923.876 1.68.63C4.397 12.533 6.358 12 8 12s3.604.532 4.923.96c.757.245 1.477-.056 1.68-.631A7 7 0 0 0 8 3z'/%3E%3C/svg%3E">
- SVG with Data URIs, CSS-Tricks
<img src='data:image/svg+xml;utf8,[YOUR URL-ENCODED SVG HERE]'
, SVG URL-encoded
<img src="data:image/svg+xml;utf8,
%3Csvg width='1.2rem' height='1.2rem' viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath fill='none' stroke='%23000' stroke-width='2' d='M20,8 C18.5974037,5.04031171 15.536972,3 12,3 C7.02943725,3 3,7.02943725 3,12 C3,16.9705627 7.02943725,21 12,21 L12,21 C16.9705627,21 21,16.9705627 21,12 M21,3 L21,9 L15,9'/%3E%3C/svg%3E">
- SVG ⇄ Code, Convert SVG image to code and vice versa
- SVG Encoder / Converter
- URL-encoder for SVG
- image2cpp, a simple tool to change images into byte arrays (or your array back into an image) for use with Arduino and (monochrome) displays such as OLEDs. It was originally made to work with the Adafruit OLED library.
- Feather icons, SVG-icons
- amCharts 5 Graph Demos
-
PlatformIO IDE i VSCode för Arduino och ESP32 kodning / utveckling:
- PlatformIO, 800+ Boards, 35+ Development Platforms, 20+ Frameworks, C/C++
- PlatformIO IDE for VSCode, beskriver installation & grundläggande användning
Quick Start: This tutorial introduces you to the basics of PlatformIO IDE workflow and a general understanding of how to work with projects in the IDE. - VSCode, Visual Studio Code
- Visual Studio Code - Updates
- PlatformIO core releases
- The Visual Studio Code Server
- PlatformIO IDE for VSCode tillägg / extension
- C/C++ IntelliSense, debugging, and code browsing tillägg / extension
- Code Spell Checker tillägg / extension
- Prettier - Code formatter tillägg / extension
- Todo Tree - Gruntfuggly tillägg / extension
- PlatformIO pio device monitor
- PlatformIO (pio) device serial monitor - Filters, where
time
adds a timestamp with milliseconds for each new line, applied in the Project Configuration File platformio.ini:
monitor_filters = time
- PlatformIO Arduino Plotter, ArduPlot serial plotter
- SerialPlot - Realtime Plotting Software, blivit tipsad om fristående plotter
- SerialPlot, GitHub
- Teleplot for VSCode, VSCode marketplace
- Teleplot User Reviews 5 stjärnor, VSCode marketplace
- Teleplot for VSCode, GitHub
- PlatformIO IDE for VSCode, Serial & UDP Plotter, Teleplot
- nesnes / teleplot-vscode, problems?
- TelePlot included in PlatformIO 3.0.0 (2023-07-10)
- PlatformIO Core 6.0, PlatformIO Labs
- Package Management CLI - pio pkg, PlatformIO
- pio pkg update command in terminal, PlatformIO pio pkg update
- pio system prune, Remove unused data, visa först: pio system prune --dry-run
- Starting with PlatformIO Core 5.1, the package management system does not cleanup unnecessary packages automatically.
- pio settings, Manage PlatformIO settings
- PlatformIO: Get started with ESP-IDF: debugging, unit testing, project analysis
- PlatformIO: Espressif IoT Development Framework (ESP-IDF)
- Espressif: Getting Started with ESP-IDF
- Espressif Systems (ESP32) and PlatformIO Labs joins a partnership in a wide-ranging collaboration on providing a next-generation development ecosystem for IoT solutions.
PlatformIO is the most loved IDE solution for Microsoft Visual Studio Code (VSCode) and the most reviewed extension in the whole Microsoft Marketplace.
PlatformIO IDE is a professional development environment for Embedded, IoT, Arduino, ESP-IDF, FreeRTOS, ARM, AVR, Espressif (ESP8266 / ESP32), and others.
Espressif Systems has been driving the IoT industry by providing highly sophisticated wireless SoC designs optimized for high-end IoT applications, as a truly innovative company. Espressif not only designs powerful AIoT (Artificial Intelligence of Things) chips, but also designs their operating systems and application frameworks. - Ivan Kravets, CEO at PlatformIO Labs: What a moment!, About the partnership PlatformIO-Espressif.
- Espressif provides a minimum 12 year longevity commitment for the product series listed.
- Espressif´s ESP32-C5 is the industry´s first RISC-V SoC solution that supports 2.4 and 5 GHz dual-band Wi-Fi 6, along with Bluetooth LE. - (blog post)
- Espressif´s ESP32-S3: An AI SoC built specifically for the AIoT market. It combines 2.4 GHz Wi-Fi 4 and Bluetooth 5 (LE) with powerful AI acceleration and reliable security features for high-performance applications of voice and face recognition.
- The ESP Journal Blog, Best Practices, Articles and Notes from Espressif folks.
- PlatformIO Labs , Linkedin, with Updates, like blog posts
- PlatformIO / Espressif diverse:
- ESP32 Buyer´s Guide: Different Chips, Firmware, Sensors, 2023 Feb
- Not By AI badge, Your AI-free Content Deserves a Badge
- W3C: HTML Design Principles, Priority of Constituencies
- PlatformIO / Espressif´s Frameworks & Platforms:
- Espressif ESP-IDF Releases
- PlatformIO Espressif32 Releases
- Espressif Arduino-ESP32 Releases
- PlatformIO Espressif32 code examples
- Official IoT Development Framework
- Espressif´s Frameworks
- GitHub: Espressif IoT Solution Overview
- ESP-IDF Programming Guide, for Espressif IoT Development Framework
- Espressif IoT Development Framework,
framework = espidf, framework = arduino, espidf
- PlatformIO: Framework Arduino - Platforms supported
- platformio/framework-arduinoespressif32
- platformio/framework-arduinoespressif32 - latest version
- platformio/framework-arduinoespressif32 - Compatibility, ESP32-versions
- GitHub: espressif/arduino-esp32 - releases
- GitHub: espressif/arduino-esp32
- platformio/framework-espidf
- platformio/framework-espidf - latest version
- platformio/framework-espidf - installation
- GitHub: espressif/esp-idf - releases
- GitHub: espressif/esp-idf
- Espressif 32: development platform for PlatformIO
- platformio/espressif32 - latest version
- GitHub: platformio/platform-espressif32
- GitHub: platformio/platform-espressif32 - releases
- PlatformIO search: platform
- PlatformIO: Platform options, platformio.ini
- Project Configuration File: platformio.ini
-
ESP32 platformio.ini exempel:
[env:wemos_d1_uno32]
platform = espressif32
board = wemos_d1_uno32 ; esp32dev
framework = arduino ;, espidf
monitor_speed = 115200
check_tool = cppcheck
check_skip_packages = yes
build_flags = -DCORE_DEBUG_LEVEL=5 ; 0:None, 1:Error, 2:Warn, 3:Info, 4:Debug, 5:Verbose
board_build.partitions = huge_app.csv
monitor_filters = time ; shows timestamp with ms resolution in Serial monitor
- PlatformIO (pio) device serial monitor - Filters, where
time
adds a timestamp with milliseconds for each new line, applied in the Project Configuration File platformio.ini:
monitor_filters = time
- PlatformIO.ini C++11 & C++17, C++11 är default:
build_unflags = -std=gnu++11
#include <variant> - std::variant from C++17, std::variant represents a type-safe union
build_flags = -std=gnu++17
- PlatformIO: Static Code Analysis
- PlatformIO: Check tools
- PlatformIO: Cppcheck
- PlatformIO: Clang-Tidy
- PlatformIO: Clang-Tidy Supported checks
- Clang-Tidy: All Checks - Boards PlatformIO, supported embedded boards
- Board Espressif 32: WEMOS D1 R32 Uno
- Board Espressif 32: Espressif ESP32 Dev Module
- Board Atmel AVR: Arduino Uno
- PlatformIO: Atmel AVR Development Platform
- PlatformIO: platformio/atmelavr
- GitHub: platformio/platform-atmelavr
- PlatformIO: Espressif 32 Development Platform
- PlatformIO: platformio/espressif32
- GitHub: platformio/platform-espressif32
- Espressif KiCad 6 Library
- .NET nanoFramework, free and Open-Source platform for constrained embedded devices.
- Espressif ESP-IDF, VSCode:
- Espressif ESP-IDF, PlatformIO:
- Espressif IoT Development Framework, ESP-IDF Release Support Schedule, Setup
- Espressif IoT Development Framework, Official development framework for ESP32 chip
- Get started with ESP-IDF and ESP32-DevKitC
- Espressif: Getting Started with ESP-IDF
- I PlatformIO bibliotekshanterare sök på respektive:
framework:espidf
framework:arduino
- Signal K, marine data exchange:
Signal K is a modern and open data format for marine use. Built on standard web technologies including JSON, WebSockets and HTTP, Signal K provides a method for sharing information in a way that is friendly to WiFi, cellphones, tablets and the Internet.
Kan det kanske även vara något inom off-grid solcellssystem?- Signal K, signalk.org hemsida
- Signal K: SensESP Home, lsensor development toolkit for the ESP32 platform.
- GitHub: SensESP, a Signal K library sensor development toolkit for the ESP32 platform.
- Signal K, SensESP 1.0.0
- Sailor Hat with ESP32 (SH-ESP32), sensor development board
- DIY sensors with Signal K
- DIY Sensors with Signal K Part 2 - The Hardware
- DIY Sensors with Signal K Part 3 - The Software
- Signal K: How to include anything in Grafana
- GitHub: Signal K Mobile
- SignalK Monitor app
- MQTT - The Standard for IoT Messaging:
MQTT is an OASIS standard messaging protocol for the Internet of Things (IoT). It is designed as an extremely lightweight publish / subscribe messaging transport that is ideal for connecting remote devices with a small code footprint and minimal network bandwidth. MQTT today is used in a wide variety of industries, such as automotive, manufacturing, telecommunications, oil and gas, etc.- MQTT.org, Lightweight and Efficient
- ESP32 MQTT – Publish and Subscribe with Arduino IDE
- ESP32 MQTT, MQTT protocol is mostly used in IoT
- Espressif: ESP-MQTT
- FreeRTOS: coreMQTT, MQTT C client library for small IoT devices
- MQTT library for Arduino / ESP32
- PlatformIO: AsyncMqttClient-esphome ESP32
- GitHub: async-mqtt-client
- PlatformIO: AsyncMqttClient ESP32, This release makes the client more bulletproof than ever. Simply put: right now, even if you do a loop to publish messages at a very fast rate, the client will not break and will not loose functionality (ACKs will still be sent, etc.).
- GitHub: async-mqtt-client
- MQTT Web App using JavaScript and WebSockets
- MQTT client in html page
- Paho MQTT JavaScript Client library
- Eclipse Paho JavaScript client, GitHub
- Publishing MQTT Data to to a Web Page
- Using The JavaScript MQTT Client With Websockets
- Using MQTT Over WebSockets with Mosquitto
- Display MQTT Data On A Web Page, download
- MQTT: A Conceptual Deep-Dive
- Simplest way to get MQTT output into a web page (RPi)
- A Field Guide to CoAP, - Constrained Application Protocol
- Espressif´s Thread Border Router Certification Leads to Dev Board Release, - Matter
- Node-RED, används ibland ihop med MQTT, byggt på Node.js
- ESP32 MQTT Publish Multiple Sensor Readings to Node-Red with Arduino IDE
- ESP32 MQTT – Publish and Subscribe with Arduino IDE, we´ll publish BME280 sensor readings to the Node-RED
- ESP32 MQTT – Publish DHT11/DHT22 Temperature and Humidity Readings (Arduino IDE), we´ll publish sensor readings to Node-RED Dashboard
- The Most Scalable MQTT Broker, for IoT
- Free Public MQTT Broker
- MQTT Brokers and Cloud Hosting Guide
- InfluxDB - Time Series Data Platform:
Time series engine: Get any data – metrics, events, logs, traces – from everywhere – systems, sensors, queues, databases and networks – and store in a high-performing engine capable of ingesting millions of data points per second. InfluxDB includes a massive community & ecosystem of cloud and open source developers to help you work the way you want to. You need to work with tools that make your apps shine and fit the way you work.
The Industrial IoT solution using InfluxDB provides real-time insight and analytics into manufacturing processes — collecting, storing and visualizing data from sensors, devices, and industrial equipment. InfluxDB is Open Source.
- ESPHome / Home Assistant - Home Automation systems:
ESPHome is a system to control your ESP8266 / ESP32 by simple yet powerful configuration files and control them remotely through Home Automation systems.
Verkar vara en vanlig kombination med ESPHome och Home Assistant, även inom off-grid!
- ESPHome
- GitHub: esphome
- Se även ESP32-C3 Free IoT book 400 pages
- Guide: Home Assistant och ESPHome, automatiserar.se
- Getting Started with ESPHome: Your Beginner´s Guide
- Unlocking the Potential of ESPHome: Your Guide to Custom IoT Creations
- ESP Web Tools, ESPHome m.fl.
- Home Assistant
- Home Assistant //Windows
- Home Assistant Community
- GitHub Home Assistant
- Nu finns en guide för Home Assistant, automatiserar.se
- Guide – Home Assistant, automatiserar.se
- Home Assistant Guide – Raspberry Pi, automatiserar.se
- Home Assistant - Demo
- Home Assistant, smarthemguiden.se
- To run Home Assistant in a Docker container, A Clear and Confident Guide
- Running Home Assistant in a Docker Container
- Docker
- The docker container for Home Assistant, Perfect to run on a Raspberry Pi or a local server
- Raspberry Pi 5 /8GB
- WireGuard - fast and modern VPN:
Blev tipsad om WireGuard för säker kommunikation till min webbsida från ESP32 via Internet, men är osäker på om det går när inhyrd på webbhotell som min webbplats är?
Min ursprungliga tanke är att skicka krypterad loggdata över https:// och tror nog ändå det blir tillräckligt säkert med de bra säkerhetsfunktionerna i RUT241 routern. Ska även skicka data glest från 1ggr/h till 1ggr/dygn adaptivt styrt och däremellan är RUT241 avstängd.
WireGuard® is an extremely simple yet fast and modern VPN that utilizes state-of-the-art cryptography. It aims to be faster, simpler, leaner, and more useful than IPsec, while avoiding the massive headache. It intends to be considerably more performant than OpenVPN. WireGuard is designed as a general purpose VPN for running on embedded interfaces and super computers alike, fit for many different circumstances. Initially released for the Linux kernel, it is now cross-platform (Windows, macOS, BSD, iOS, Android) and widely deployable. It is currently under heavy development, but already it might be regarded as the most secure, easiest to use, and simplest VPN solution in the industry.
Wireguard client library for connecting ESP32 to a VPN server. The WireGuard client library can be used to connect an ESP32 to a WireGuard server, enabling network tunneling and secure communication over possibly insecure transport. Another use case is exposing services running on an ESP32 that is connected through (several) layers of NAT, as is often the case when using mobile network. Note that this requires server-side setup as well.
- Tailscale, Secure, remote access to servers
- ZeroTier, Securely connect any device, anywhere
- Elektronikkonstruktion:
- Lagliga och säkra hemmabyggen, Dator Magazin
- KiCad EDA Schemaritning + PCB-layout Open Source (den jag använder)
- KiCad EDA, Wikipedia
- John´s Basement - KiCad tutorials (YouTube)
- Espressif KiCad 6 Library
- KiCad SPICE Simulation
- SPICE Quick Reference Sheet, PULSE for PWM souce
- Simulating Pulse-Width Modulation (PWM) with a RC Circuit in LTspice, youtube
- How to Pulse AND Step a Load in LTSPICE
- Performing A Circuit Simulation In KiCad
- Simulating a KiCad Circuit
- KiCad Simulation: Examples and Tutorials
- DAC and PWM KiCad Simulation
- KiCad Tutorial - How to simulate circuits in KiCad for beginners, youtube, web
- A Quick KiCad Simulation Tutorial - Charging Capacitor Transient, youtube
-
- LTspice, Analog Devices free SPICE simulator software
- DipTrace Schemaritning + PCB-layout, Free ≤300 pins and 2 signal layers
- DipTrace, Wikipedia
- Felder ISO-Core "clear" Sn100Ni+ 0.5mm 100g, Conrad
- Lödtenn 0.6mm blyfritt 100g, Electrokit
- Övrigt:
- Formelsamling, Formler som är bra att ha.
- Elektronik, Arduino (el.st), väldigt brett om diverse!
- List of 4000 Series IC, med länk till detaljerad info för varje
- Electrical Symbols & Electronic Symbols
- Fan Affinity Laws of centrifugal fans
- Battery Banks & Over-Current Protection, Marine How To
- Fusing & Termination Voltage Drop, Marine How To
- Filtrering av signaler för undetryckande av störningar Noise reduction:
- Simplifiead Moving Average (like a RC-filtering):
MovAverageLevel = MovAverageLevel + (NewLevelRead - MovAverageLevel) / 100;
Or more compact C++ code:
MovAverageLevel += (NewLevelRead - MovAverageLevel) / 100;
If these erroneous readings are like very short spikes, you can make a kind of simplified moving average, where you always just take and add like 1/10, 1/100 or whatever fits of the difference between the current average and the current measurement.
Depends on how often you sample how much to include, but with 1/100 you suppress such an incorrect reading 100 times. - Median filter
- Median filters – An efficient way to remove impulse noise
- Spatial Filters – Averaging filter and Median filter in Image Processing, GeeksForGeeks
- A Median filters, Signal Processing and Modeling Techniques
- 1-D median filtering, MathWorks
- Kalman filter signal processing
- The more correct way to get rid of random peaks (outliers), is to make use of the Nalimov statistical model:
Nalimov statistical model / Nalimov test
- Monte Carlo filtering signal processing
Gjorde några precision strömmätningar för Arduino Uno R3 och ESP32 UNO D1 R32 med exakt samma sketch kompilerad i båda och med samma Olimex Shield-LCD 16x2 på båda.
Med släckt bakgrundsbelysning blev det då:
- Arduino Uno R3 16MHz: 57mA
- ESP32 UNO D1 R32 240MHz: 50mA
- ESP32 UNO D1 R32 10MHz: 20mA
Och med tänd bakgrundsbelysning 33% intensitet +8mA mer.
Strömmatade via USB under mätningarna.
Så trots så extremt mycket mer prestanda är ESP32 strömsnålare, samt har flexibiliteten att man kan anpassa dess klockfrekvens dynamiskt i drift till ens behov för att kunna få strömsnålare drift när det passar.
För riktigt strömsnål ESP32-drift i deep-sleep: Did you set all unused pins as outputs? If pins are left floating as inputs, that can draw current internally. Yes that that was the reason. After resetting the pins that are connected to the DIP switch before going to deep sleep, my deep sleep current is now 12.7µA (233µA before).