Multitasking Programming Tutorial (Arduino)
by danielgass in Circuits > Arduino
103 Views, 0 Favorites, 0 Comments
Multitasking Programming Tutorial (Arduino)
This educational tutorial implements advanced features that introduce interesting programming techniques while simplifying the coding process.
Project features:
- Construction of a two-wheeled vehicle controlled via a web interface.
- Equipped with an ultrasonic sensor.
- The LittleFS file system.
- An asynchronous web server.
- An asynchronous task manager that allows tasks to run in parallel.
- Example Java script.
The main appeal of this project lies in the programming. The technical design is very simple.
Components and Technical Assembly
The assembly requires only a few components. The ESP32 controller can be selected from the ESP32- or ESP8266-based product line.
All files are available here .
Programming - Part 1: the File System
When a program includes web pages, the available memory reserved for the code is insufficient. We’ll use a file system like LittleFS to copy the web page to flash memory separately from the program. The program will then access the files.
- Mounting the LittleFS file system in the ESP32’s flash memory and copying the index.html and style.css files
The index.html file contains our web page and the associated style.css file. They are stored in the program’s “data” subdirectory.
The file system is created from within the Arduino IDE by using the shortcut Ctrl+Shift+P, typing “upload,” and selecting the entry for LittleFS. Before doing this, you must connect the ESP32 (board and port). Arduino formats the flash memory, configures the file system, and loads the two files.
This step only needs to be repeated if the content of the web page changes.
- Accessing the file system from the program:
Declaration and usage are simple. The library to install is “LittleFS_ESP32 lorol”
====> in the program
(declaration section)
#include <LittleFS.h> // file system library
(setup section)
// initialize file system
LittleFS.begin() // start access to the file system
..
server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(LittleFS, “/index.html”, String(), false, processor);});
<====
Programming - Part 2: the Web Server
The server operates in asynchronous mode. This allows other tasks to run without blocking the execution of the main code.
The web page consists of buttons and a progress bar that displays the speed. Depending on which button is pressed, an action is performed on the motors: direction and speed.
====> in the program
(declaration section)
#include <ESPAsyncWebServer.h>
AsyncWebServer server(80); // Creating an asynchronous server on port 80
(setup section)
// Starting the web server
server.begin();
..
// when the web page is called (initial call)
server.on(“/”, HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(LittleFS, “/index.html”, String(), false, processor);
}); // location of the web page in the file system
…
// when the “fast” button is pressed
server.on(“/fas”, HTTP_GET, [](AsyncWebServerRequest *request) {
motAspeed += 10;
motBspeed += 10;
request->send(LittleFS, “/index.html”, String(), false, processor);};
<====
Modifying information on the web page using the “processor” function.
=====> in the program
(declaration section)
// Replacement function for dynamic content
String processor(const String& var) {
motorcontrol();
if (var == “SPEEDEMO”) {
int val = max(motAspeed, motBspeed);
String section;
section = “<label>”;
section += “Speed L = ” + String(motBspeed) + “ Speed R = ” + String(motAspeed) + “ ”;
section += “<progress value= ” + String(val) + “ ” + “max=\”100\“> 10% </progress>”
<=====
Programming - Part 3: Asynchronous Task Manager
In addition to the web server, this multitasking manager allows you to manage tasks in parallel that are independent of one another.
One of these tasks is distance monitoring using the SR-SH04 interface. The task wakes up every second and measures the distance between the vehicle and a potential obstacle. If the measured distance is less than 20 cm, an avoidance maneuver is performed. The vehicle reverses and changes direction automatically.
At the same time, the “web server” task continues to monitor button actions on the web page. You can control the vehicle’s behavior freely. However, if the vehicle gets too close to an obstacle, it is redirected.
====> in the program
(declaration section)
#include <AsyncTask.h>
AsyncTask asyncTask;
(setup section)
// Starting the scheduled asynchronous task
asyncTask.repeat(taskOne, 1000);
(function declaration)
// Asynchronous tasks
void taskOne() { autocontrol();}
// This function monitors the distance and, if necessary, causes the vehicle to back up and change direction.
void autocontrol() {
distance();
if (cm >= 20) {
} else if (cm < 20) {
motAdir = 1; motBdir = 1;
motorcontrol();
delay(2000);
motBdir = 0;
motorcontrol();
delay(1000);
motAdir = 0; motBdir = 0;
motorcontrol(); } }
<====
To schedule additional tasks, simply declare them as follows:
asyncTask.repeat(f, t); where “f” is the function to be called and “t” is the interval between executions in milliseconds.
Program Overview
The program is divided into separate files to make it easier to read and understand.
Main program: esp-web-littleFS-final.ino
Action routes: routes.ino
Motor actions: motor-functions.ino
Ultrasonic sensor: ultrasonic.ino
Fun Extension Program
To add another dimension to the project, a second web page has been added. It is displayed by clicking the “pr1” button. This page uses a Java script that calls a function from the Google graphics library.
The Java script is integrated as follows:
server.on(“/script.js”, HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(LittleFS, “/script.js”, “text/js”); });
The “pr1” trigger specifies the page to use as well as the processing to be performed before the “processor1” page is displayed "
server.on(“/pr1”, HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(LittleFS, “/speed.html”, String(), false, processor1); });
The pre-rendering processing replaces the variable “%SEEDSELECTION%” on the page with the values of the variables to be used. This injects Java code.
// Replacement function for dynamic content
String processor1(const String& var) {
if (var == “SPEEDSECTION”) {
String section = “var valA = ” + String(motAspeed) + “; var valB = ” + String(motBspeed);
return section;
}
return String();
}
The “return” button on the page takes you back to the main page.
server.on(“/ret”, HTTP_GET, [](AsyncWebServerRequest *request) {
request->send(LittleFS, “/index.html”, String(), false, processor); });
Conclusion
This project doesn’t have many components, and assembly is straightforward.
It provides an introduction to multitasking and asynchronous servers.
With LittleFS, web pages (.html), Java scripts (.js), and style sheets (.css) are stored in the file system installed on the controller.
A sample Java script rounds out the exercise.
The references below allow you to explore these features in greater depth. Enjoy!
References:
LittleFS_ESP32:
https://randomnerdtutorials.com/esp32-write-data-littlefs-arduino/
https://randomnerdtutorials.com/esp32-web-server-littlefs/
AsyncTask:
https://www.luisllamas.es/libreria-arduino-asynctask/
https://yiweimao.github.io/blog/async_microcontroller/
https://github.com/luisllamasbinaburo/Arduino-AsyncTask/blob/master/examples/AlternateTask/AlternateTask.ino
Async web server:
https://randomnerdtutorials.com/esp32-async-web-server-espasyncwebserver-library/