SlideShare a Scribd company logo
Integrated Computer Solutions Inc. www.ics.com 1
Integrated Computer Solutions Inc. www.ics.com
About ICS
● Founded in 1987
● Largest source of independent Qt expertise in North America
● Trusted Qt Service Partner since 2002
● Exclusive Open Enrollment Training Partner in North America
● Provides integrated custom software development and user experience (UX) design
● Embedded, touchscreen, mobile and desktop applications
● HQ in Waltham, MA with offices in California, Canada, Europe
Boston UX
● Part of the ICS family, focusing on UX design
● Designs intuitive touchscreen interfaces for high-impact embedded and
connected medical, industrial and consumer devices
Integrated Computer Solutions Inc. www.ics.com
What we will cover
3
Overview of MCUs and their features
● Current scope of MCU-based applications
● Convergence of microcontrollers and microprocessors
● Peripherals available and protocols used in today´s projects
Discussion on programming approaches
● Pros and cons of programming bare-metal vs RTOS
● Running Python scripts on MCUs
Challenges in firmware implementation (with example code)
● Application fragments implemented with the ubiquitous ESP32 MCU
● Network-enabled demo that connects to a Mender server and retrieves over-the-air
updates
Integrated Computer Solutions Inc. www.ics.com
Current scope of MCU-based applications
4
● Reduce the cost of the project
○ Hardware costs lower than MPU-based (less peripherals)
○ Firmware development costs equal or higher (more tools available on
embedded Linux, for example Qt, imply less time for implementation)
○ => Bottom line will depend on the expected size of production.
● Solve specific tasks within a system containing other controllers
○ Split the application into smaller subtasks handled by several MCUs
○ Tough timing requirements (high speed protocols)
Integrated Computer Solutions Inc. www.ics.com
Convergence of MCU and MPU fields
5
● Traditional approach
○ MPUs = external storage and runtime memory
○ MCUs = single chip processors
○ MCUs ran customized firmware on devices, MPUs ran OS on desktops with
general-purpose applications
● Today: blurring boundaries
○ Improvements in levels of integration
○ Widespread growth of Linux for devices, i.e. ‘non-computers’
○ Reduced MCU development time.
■ Versatile hardware configuration options
■ Small OS available (mostly FreeRTOS)
■ Hardware abstraction layers (STM32´s CubeMx, for example)
■ Large ecosystems of developers bring many open source code
Integrated Computer Solutions Inc. www.ics.com
STM32CubeMX: MCU setup with auto-code generation
Integrated Computer Solutions Inc. www.ics.com
Today´s peripherals
7
● MCUs embed as many peripherals as possible inside the device, in line with the
targeted market: automotive, consumer goods with low power needs, etc.
○ Timers, counters, Pulse Width Modulation (PWM)
○ Serial ports (USART, SPI, I2
C, CAN, Ethernet, …)
○ ADCs & DACs (analog/digital converters)
○ Radiofrequency transceivers (WiFi, Bluetooth, …)
○ Cryptographic accelerators
● External peripherals:
○ Inertial Measurement Units: accelerometers, gyroscopes, magnetometers
○ Weather sensors: temperature, humidity, pressure
○ Other RF transceivers (Zigbee, 5G, LoRa…)
○ …
Integrated Computer Solutions Inc. www.ics.com
SPI I2
C
8
Serial Peripheral Interface
● Full-duplex
● Originally was 1:1, then extended
to 1:N
Inter-Integrated Circuit
● Bus topology
● Addressing mechanism needed,
peripheral specific
Integrated Computer Solutions Inc. www.ics.com
CAN
9
Controller Area Network
● Bus topology
● No device ID, but message ID
● Frames
○ Data
○ Remote
○ Error
○ Overload
● Bitwise arbitration
● Widespread usage in automobile and
industrial automation
● Higher layers (CANOpen)
Integrated Computer Solutions Inc. www.ics.com
Bare-metal development
10
● Firmware duties:
○ interaction with peripherals/hardware resources (lower level)
○ business logic (higher level)
○ The glue needed to accomplish with the business logic also needs to
provide concurrency
● On bare-metal programming, the operating system is “us” (developers)
○ Concurrency implemented as a round-robin of “never-blocking” functions..
Integrated Computer Solutions Inc. www.ics.com
Bare-metal example
11
void main_loop() {
// ….
while (1) {
// …
slow_status = aSlowTask ( slow_params,
slow_result);
fast_status = aFastTask ( fast_params,
fast_result);
do_business_logic ( slow_status,
slow_params,
slow_result,
fast_status,
fast_params,
fast_result );
}
}
Integrated Computer Solutions Inc. www.ics.com
Example (continued)
12
char neverBLockingTask (char *params, char *result) {
switch (stateMachine) {
//…
case WAIT_ANSWER:
if ( timedOut(&timer) ) {
stateMachine = HANDLE_TIMEOUT;
result = ANSWER_TIMEOUT;
} else {
receiveData( rxBuff + buffLen, *buffLen);
if (*buff_len==0) {
result = ANSWER_PENDING;
} else {
if ( ! fullAnswerReceived( *rxBuff, uint16_t *buffLen) ) {
result = ANSWER_PENDING;
} else {
stateMachine = IDLE;
result = ANSWER_RECEIVED;
}
}
}
break;
// …
} // switch
return result;
}
Integrated Computer Solutions Inc. www.ics.com
Running Python scripts on MCUs
13
● Traditionally, MCUs languages are C and C++
○ compilers, debuggers
● Python popularity
○ Huge community
○ Sintax simplicity
○ Excellent libraries
○ Good for data science/machine learning
○ Zoomers (Generation Z) prefer .py rather than .c
● Micropython: a small Python 3 interpreter and runtime for MCUs (bare-metal)
○ Open Source, MIT License
○ Footprint: 256 kb flash, 16 kb RAM
○ Not as performant as C (Python runtime needs to parse the script)
Integrated Computer Solutions Inc. www.ics.com
Micropython example
14
from machine import SPI, Pin
spi = SPI(0, baudrate=400000)
cs = Pin(4, mode=Pin.OUT, value=1)
txdata = b"12345678"
rxdata = bytearray(len(txdata))
try:
cs(0)
spi.write_readinto(txdata, rxdata)
finally:
cs(1)
Integrated Computer Solutions Inc. www.ics.com
FreeRTOS
15
● Small kernel, it provides concurrency, with a small computing overhead
○ Open source and lightweight: footprint is around 4Kbytes
○ Concurrency implemented through threads.
○ Inter-task communication
■ Queues
■ Semaphores
■ Mutexes
https://www.freertos.org/Inter-Task-Communication.html
Integrated Computer Solutions Inc. www.ics.com
FreeRTOS example
16
Two tasks communicating through queues
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
QueueHandle_t q=NULL;
void app_main()
{
q=xQueueCreate(20,sizeof(unsigned long));
if (q != NULL) {
vTaskDelay(1000/portTICK_PERIOD_MS); // one second delay
xTaskCreate(&producer_task,"producer_task",2048,NULL,5,NULL);
xTaskCreate(&consumer_task,"consumer_task",2048,NULL,5,NULL);
} else {
printf("Queue creation failed");
}
}
Integrated Computer Solutions Inc. www.ics.com
FreeRTOS example (cont)
17
void producer_task(void *pvParameter)
{
unsigned long counter=1;
BaseType_t resultQueue;
while(1) {
resultQueue = xQueueSend( q,
&counter,
(TickType_t )0);
if (pdTrue == resultQueue) {
printf("sent to the queue: %lun",counter);
counter++;
}
vTaskDelay(1000/portTICK_PERIOD_MS);
}
}
void consumer_task(void *pvParameter)
{
unsigned long counter;
BaseType_t resultQueue;
while(1) {
resultQueue = xQueueReceive( q,
&counter,
(TickType_t ) 0);
if (pdTrue == resultQueue) {
printf("received from the queue: %lu n",counter);
}
vTaskDelay(20/portTICK_PERIOD_MS);
}
}
Integrated Computer Solutions Inc. www.ics.com
About ESP32
18
Integrated Computer Solutions Inc. www.ics.com
ESP32 flash management
19
● Bootloader
● Flexible application partition options:
○ flat
○ ota_0/ota_1 (a.k.a. A/B partition)
● Optional user data, called ‘storage’ (can be FAT, or plain)
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x4000,
otadata, data, ota, 0xd000, 0x2000
phy_init, data, phy, 0xf000, 0x1000,
ota_0, app, ota_0, 0x10000, 0x140000,
ota_1, app, ota_1, , 0x140000,
storage, data, fat, , 0x140000,
Integrated Computer Solutions Inc. www.ics.com
A microcontroller challenge…
20
Could a third-party Over-The-Air updates solution like Mender
be implemented on a ESP32 module?
● Mender originally targeted for Linux cards, not MCUs…
● Enough flash space?
Integrated Computer Solutions Inc. www.ics.com
Updating capabilities
21
Integrated Computer Solutions Inc. www.ics.com
Web management console
22
Integrated Computer Solutions Inc. www.ics.com
ESP32: flash partitioning trade-offs…
23
● with the storage partition
○ flash space divided by 3
○ full download before updating
○ uncompress after download feasible
# Name, Type, SubType, Offset, Size,
nvs, data, nvs, 0x9000, 0x4000,
otadata, data, ota, 0xd000, 0x2000
phy_init, data, phy, 0xf000, 0x1000,
ota_0, app, ota_0, 0x10000, 0x140000,
ota_1, app, ota_1, , 0x140000,
storage, data, fat, , 0x140000,
● without the storage partition
○ flash space divided by 2
○ partial downloads, update by chunks
○ needs uncompressed artifacts
# Name, Type, SubType, Offset, Size,
nvs, data, nvs, 0x9000, 0x4000,
otadata, data, ota, 0xd000, 0x2000
phy_init, data, phy, 0xf000, 0x1000,
ota_0, app, ota_0, 0x10000, 0x1F8000,
ota_1, app, ota_1, , 0x1F8000,
Integrated Computer Solutions Inc. www.ics.com
Understanding a 3rd party file format
24
● Based on tar format
○ Header
○ One or more files
packed, including
version, payload type,
checksum.
● Mender utility for artifact preparation
● Compression options (gzip, lzma or none)
Integrated Computer Solutions Inc. www.ics.com
Moving from challenge into action
25
● #1 receive firmware by chunks
○ firmware footprint around 2 Mbytes
○ Receive buffer size tradeoffs
● #2 parse a tar file on the fly
○ At proper offset, obtain the firmware file size
○ At proper offset, get fragments of the firmware file as they
arrive.
Integrated Computer Solutions Inc. www.ics.com
Receive firmware by chunks
26
● Use HTTP Range header
● Tested with cURL first, then implemented on the ESP32 HTTP
API
GET /api/devices/v1/deployments/device/deployments/next?artifact_name=fw_v1_0.mender&device_type=ESP32 HTTP/1.1
Host: docker.mender.io
Range: bytes=0-1023
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-1023/1246515
Content-Length: 1024
...
(binary content)
Integrated Computer Solutions Inc. www.ics.com
Receive firmware by chunks (cont.)
27
if (body_length>0)
{
offset=0;
esp_http_client_handle_t client = esp_http_client_init(&config);
to=-1;
while (1)
{
from=to+1;
if (from>=body_length-1)
{ /* Reached the end of GET answer, run latest OTA API call , for latest bootloader setup */
esp_ota_end(update_handle);
esp_ota_set_boot_partition(update_partition);
result=MENDER_DOWNLOAD_OK;
break;
}
to=from+MENDER_RESPONSE_BUFFER-1;
if (to>body_length-1)
{
to=body_length-1;
}
sprintf (range_string,"bytes=%d-%d", from, to);
esp_http_client_set_header(client, "Range", range_string);
esp_http_client_perform(client);
content_length = esp_http_client_get_content_length(client);
artifact_processBlock( client->response_buffer, ...);
// …
}
}
Integrated Computer Solutions Inc. www.ics.com
Parse a tarball by chunks
28
● Understand the tarball definition
● Understand artifacts structure (tar inside a tar)
● Implement the stream parser.
Integrated Computer Solutions Inc. www.ics.com
Parse a tarball by chunks
29
int artifact_processBlock ( char *inbuff, size_t inbuff_length, size_t *offset, char *outbuff, size_t *outbuff_length, size_t outbuff_size)
{
//….
if (*offset + inbuff_length <= FILESIZE_OFFSET + FILESIZE_LENGTH) { // start of file size reached, end of file size not reached
if (*offset< FILESIZE_OFFSET) { // start of buffer before start of file size
size_t amount = inbuff_length-(FILESIZE_OFFSET-*offset);
memcpy (filesizeBuffer+filesizeBufferLength, inbuff+(FILESIZE_OFFSET-*offset), amount);
filesizeBufferLength += amount;
} else { // start of buffer after start of file size
size_t amount = inbuff_length;
memcpy (filesizeBuffer+filesizeBufferLength, inbuff, amount);
filesizeBufferLength += amount;
}
if (FILESIZE_LENGTH == filesizeBufferLength) {
convertBufferToFileSize (filesizeBuffer, &fileSize);
fileSizeValid = true;
}
*offset += inbuff_length;
result = 0;
goto exit_func;
}
// …..
Integrated Computer Solutions Inc. www.ics.com
Security aspects
30
● Open source version:
○ Transport Secure Layer protocol, TLS
○ Self signed or Certificate Authority
○ Provisioning @ factory plant
● Paid plans
○ Same as above, plus mutual TLS authentication
Integrated Computer Solutions Inc. www.ics.com
Conclusions
● Big MCU/MPUs ecosystems raise the bar for more complex projects
● Modules integrating MCU and radio chips provide quick yet powerful resource
for IoT.
● Cybersecurity concerns for IoT devices.
● Peripherals integrated to the MCU processor. Serial links (SPI, I2C, CAN,
USART) for off-chip peripherals,
● FreeRTOS and similar small footprint simplifies implementation on MCUs
Integrated Computer Solutions Inc. www.ics.com
All images were taken from STM32, Mender’s online documentation.
Questions?
gstola@ics.com

More Related Content

PDF
Introduction to FreeRTOS
 
PDF
GPU Ecosystem
DOC
Sahil_Resume
PDF
Cloud, Distributed, Embedded: Erlang in the Heterogeneous Computing World
PDF
Taking Back Embedded: The Erlang Embedded Framework
PDF
Erlang Embedded — Concurrent Blinkenlights and More!
PDF
LCE13: Android Graphics Upstreaming
PDF
Intel's Presentation in SIGGRAPH OpenCL BOF
Introduction to FreeRTOS
 
GPU Ecosystem
Sahil_Resume
Cloud, Distributed, Embedded: Erlang in the Heterogeneous Computing World
Taking Back Embedded: The Erlang Embedded Framework
Erlang Embedded — Concurrent Blinkenlights and More!
LCE13: Android Graphics Upstreaming
Intel's Presentation in SIGGRAPH OpenCL BOF

What's hot (20)

PDF
Newbie’s guide to_the_gpgpu_universe
PDF
LAS16-406: Android Widevine on OP-TEE
PDF
The GPGPU Continuum
PDF
The Actor Model applied to the Raspberry Pi and the Embedded Domain
PDF
Making an OpenSource Automotive IVI Media Manager
 
PPTX
Design and Optimize your code for high-performance with Intel® Advisor and I...
PDF
Creating a successful IoT product with MediaTek Labs
PPTX
ProjectVault[VivekKumar_CS-C_6Sem_MIT].pptx
PDF
Developing an embedded video application on dual Linux + FPGA architecture
DOC
Eric Theis resume61.1
PDF
Free / Open Source EDA Tools
PPTX
VLSI Training presentation
PPTX
Getting started with Intel IoT Developer Kit
DOC
CV_Arshad_21June16
PPTX
Security and functional safety
PDF
LPC4300_two_cores
PDF
Introduction to intel galileo board gen2
PDF
MediaTek Linkit Smart 7688 Webinar
ODP
Internet of Smaller Things
PDF
Case Study: Porting Qt for Embedded Linux on Embedded Processors
Newbie’s guide to_the_gpgpu_universe
LAS16-406: Android Widevine on OP-TEE
The GPGPU Continuum
The Actor Model applied to the Raspberry Pi and the Embedded Domain
Making an OpenSource Automotive IVI Media Manager
 
Design and Optimize your code for high-performance with Intel® Advisor and I...
Creating a successful IoT product with MediaTek Labs
ProjectVault[VivekKumar_CS-C_6Sem_MIT].pptx
Developing an embedded video application on dual Linux + FPGA architecture
Eric Theis resume61.1
Free / Open Source EDA Tools
VLSI Training presentation
Getting started with Intel IoT Developer Kit
CV_Arshad_21June16
Security and functional safety
LPC4300_two_cores
Introduction to intel galileo board gen2
MediaTek Linkit Smart 7688 Webinar
Internet of Smaller Things
Case Study: Porting Qt for Embedded Linux on Embedded Processors
Ad

Similar to An In-Depth Look Into Microcontrollers (20)

PDF
TDC2016SP - Trilha Linux Embarcado
PDF
Introduction to Embedded System
PDF
Using Eclipse and Lua for the Internet of Things with Eclipse Koneki, Mihini ...
PPTX
Embedded Systems Introdution
PPTX
Ppt on six month training on embedded system & IOT
PPTX
Microcontroller.pptx
PPT
Lesson 25 Choosing the right core (Lecture 7).ppt
PDF
Using Eclipse and Lua for the Internet of Things - EclipseDay Googleplex 2012
PDF
Embedded OS and Application-2024-01 Embedded system introduction.pdf
PPTX
Microcontroller from basic_to_advanced
PDF
International Journal of Computational Engineering Research(IJCER)
PDF
Open source building blocks for the Internet of Things - Jfokus 2013
PPT
03 top level view of computer function and interconnection
PDF
Data Acquisition and Control System for Real Time Applications
PDF
Esrtos 2012 table of contents
PDF
Firmware Develpment for hybrid (ARM and FPGA) processors
PDF
Programming Embedded Systems With C And Gnu Development Tools 2nd Edition 2nd...
PDF
Arm based controller - basic bootcamp
PDF
Basics of Embedded System
PPTX
8259 Programmable Interrupt Controller.pptx
TDC2016SP - Trilha Linux Embarcado
Introduction to Embedded System
Using Eclipse and Lua for the Internet of Things with Eclipse Koneki, Mihini ...
Embedded Systems Introdution
Ppt on six month training on embedded system & IOT
Microcontroller.pptx
Lesson 25 Choosing the right core (Lecture 7).ppt
Using Eclipse and Lua for the Internet of Things - EclipseDay Googleplex 2012
Embedded OS and Application-2024-01 Embedded system introduction.pdf
Microcontroller from basic_to_advanced
International Journal of Computational Engineering Research(IJCER)
Open source building blocks for the Internet of Things - Jfokus 2013
03 top level view of computer function and interconnection
Data Acquisition and Control System for Real Time Applications
Esrtos 2012 table of contents
Firmware Develpment for hybrid (ARM and FPGA) processors
Programming Embedded Systems With C And Gnu Development Tools 2nd Edition 2nd...
Arm based controller - basic bootcamp
Basics of Embedded System
8259 Programmable Interrupt Controller.pptx
Ad

More from ICS (20)

PDF
Understanding the EU Cyber Resilience Act
 
PDF
Porting Qt 5 QML Modules to Qt 6 Webinar
 
PDF
Medical Device Cybersecurity Threat & Risk Scoring
 
PDF
Exploring Wayland: A Modern Display Server for the Future
 
PDF
Threat Modeling & Risk Assessment Webinar: A Step-by-Step Example
 
PDF
8 Mandatory Security Control Categories for Successful Submissions
 
PDF
Future-Proofing Embedded Device Capabilities with the Qt 6 Plugin Mechanism.pdf
 
PDF
Choosing an Embedded GUI: Comparative Analysis of UI Frameworks
 
PDF
Medical Device Cyber Testing to Meet FDA Requirements
 
PDF
Threat Modeling and Risk Assessment Webinar.pdf
 
PDF
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
 
PDF
Webinar On-Demand: Using Flutter for Embedded
 
PDF
A Deep Dive into Secure Product Development Frameworks.pdf
 
PDF
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
PDF
Practical Advice for FDA’s 510(k) Requirements.pdf
 
PDF
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
 
PDF
Overcoming CMake Configuration Issues Webinar
 
PDF
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
 
PDF
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
 
PDF
Quality and Test in Medical Device Design - Part 1.pdf
 
Understanding the EU Cyber Resilience Act
 
Porting Qt 5 QML Modules to Qt 6 Webinar
 
Medical Device Cybersecurity Threat & Risk Scoring
 
Exploring Wayland: A Modern Display Server for the Future
 
Threat Modeling & Risk Assessment Webinar: A Step-by-Step Example
 
8 Mandatory Security Control Categories for Successful Submissions
 
Future-Proofing Embedded Device Capabilities with the Qt 6 Plugin Mechanism.pdf
 
Choosing an Embedded GUI: Comparative Analysis of UI Frameworks
 
Medical Device Cyber Testing to Meet FDA Requirements
 
Threat Modeling and Risk Assessment Webinar.pdf
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
 
Webinar On-Demand: Using Flutter for Embedded
 
A Deep Dive into Secure Product Development Frameworks.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Practical Advice for FDA’s 510(k) Requirements.pdf
 
Accelerating Development of a Safety-Critical Cobot Welding System with Qt/QM...
 
Overcoming CMake Configuration Issues Webinar
 
Enhancing Quality and Test in Medical Device Design - Part 2.pdf
 
Designing and Managing IoT Devices for Rapid Deployment - Webinar.pdf
 
Quality and Test in Medical Device Design - Part 1.pdf
 

Recently uploaded (20)

PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Nekopoi APK 2025 free lastest update
PDF
Digital Strategies for Manufacturing Companies
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
AI in Product Development-omnex systems
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Introduction to Artificial Intelligence
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
System and Network Administration Chapter 2
PPTX
Reimagine Home Health with the Power of Agentic AI​
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
Odoo POS Development Services by CandidRoot Solutions
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Nekopoi APK 2025 free lastest update
Digital Strategies for Manufacturing Companies
wealthsignaloriginal-com-DS-text-... (1).pdf
AI in Product Development-omnex systems
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
How to Migrate SBCGlobal Email to Yahoo Easily
Introduction to Artificial Intelligence
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Wondershare Filmora 15 Crack With Activation Key [2025
Design an Analysis of Algorithms I-SECS-1021-03
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
System and Network Administration Chapter 2
Reimagine Home Health with the Power of Agentic AI​
How to Choose the Right IT Partner for Your Business in Malaysia
Odoo POS Development Services by CandidRoot Solutions
Operating system designcfffgfgggggggvggggggggg
Which alternative to Crystal Reports is best for small or large businesses.pdf

An In-Depth Look Into Microcontrollers

  • 1. Integrated Computer Solutions Inc. www.ics.com 1
  • 2. Integrated Computer Solutions Inc. www.ics.com About ICS ● Founded in 1987 ● Largest source of independent Qt expertise in North America ● Trusted Qt Service Partner since 2002 ● Exclusive Open Enrollment Training Partner in North America ● Provides integrated custom software development and user experience (UX) design ● Embedded, touchscreen, mobile and desktop applications ● HQ in Waltham, MA with offices in California, Canada, Europe Boston UX ● Part of the ICS family, focusing on UX design ● Designs intuitive touchscreen interfaces for high-impact embedded and connected medical, industrial and consumer devices
  • 3. Integrated Computer Solutions Inc. www.ics.com What we will cover 3 Overview of MCUs and their features ● Current scope of MCU-based applications ● Convergence of microcontrollers and microprocessors ● Peripherals available and protocols used in today´s projects Discussion on programming approaches ● Pros and cons of programming bare-metal vs RTOS ● Running Python scripts on MCUs Challenges in firmware implementation (with example code) ● Application fragments implemented with the ubiquitous ESP32 MCU ● Network-enabled demo that connects to a Mender server and retrieves over-the-air updates
  • 4. Integrated Computer Solutions Inc. www.ics.com Current scope of MCU-based applications 4 ● Reduce the cost of the project ○ Hardware costs lower than MPU-based (less peripherals) ○ Firmware development costs equal or higher (more tools available on embedded Linux, for example Qt, imply less time for implementation) ○ => Bottom line will depend on the expected size of production. ● Solve specific tasks within a system containing other controllers ○ Split the application into smaller subtasks handled by several MCUs ○ Tough timing requirements (high speed protocols)
  • 5. Integrated Computer Solutions Inc. www.ics.com Convergence of MCU and MPU fields 5 ● Traditional approach ○ MPUs = external storage and runtime memory ○ MCUs = single chip processors ○ MCUs ran customized firmware on devices, MPUs ran OS on desktops with general-purpose applications ● Today: blurring boundaries ○ Improvements in levels of integration ○ Widespread growth of Linux for devices, i.e. ‘non-computers’ ○ Reduced MCU development time. ■ Versatile hardware configuration options ■ Small OS available (mostly FreeRTOS) ■ Hardware abstraction layers (STM32´s CubeMx, for example) ■ Large ecosystems of developers bring many open source code
  • 6. Integrated Computer Solutions Inc. www.ics.com STM32CubeMX: MCU setup with auto-code generation
  • 7. Integrated Computer Solutions Inc. www.ics.com Today´s peripherals 7 ● MCUs embed as many peripherals as possible inside the device, in line with the targeted market: automotive, consumer goods with low power needs, etc. ○ Timers, counters, Pulse Width Modulation (PWM) ○ Serial ports (USART, SPI, I2 C, CAN, Ethernet, …) ○ ADCs & DACs (analog/digital converters) ○ Radiofrequency transceivers (WiFi, Bluetooth, …) ○ Cryptographic accelerators ● External peripherals: ○ Inertial Measurement Units: accelerometers, gyroscopes, magnetometers ○ Weather sensors: temperature, humidity, pressure ○ Other RF transceivers (Zigbee, 5G, LoRa…) ○ …
  • 8. Integrated Computer Solutions Inc. www.ics.com SPI I2 C 8 Serial Peripheral Interface ● Full-duplex ● Originally was 1:1, then extended to 1:N Inter-Integrated Circuit ● Bus topology ● Addressing mechanism needed, peripheral specific
  • 9. Integrated Computer Solutions Inc. www.ics.com CAN 9 Controller Area Network ● Bus topology ● No device ID, but message ID ● Frames ○ Data ○ Remote ○ Error ○ Overload ● Bitwise arbitration ● Widespread usage in automobile and industrial automation ● Higher layers (CANOpen)
  • 10. Integrated Computer Solutions Inc. www.ics.com Bare-metal development 10 ● Firmware duties: ○ interaction with peripherals/hardware resources (lower level) ○ business logic (higher level) ○ The glue needed to accomplish with the business logic also needs to provide concurrency ● On bare-metal programming, the operating system is “us” (developers) ○ Concurrency implemented as a round-robin of “never-blocking” functions..
  • 11. Integrated Computer Solutions Inc. www.ics.com Bare-metal example 11 void main_loop() { // …. while (1) { // … slow_status = aSlowTask ( slow_params, slow_result); fast_status = aFastTask ( fast_params, fast_result); do_business_logic ( slow_status, slow_params, slow_result, fast_status, fast_params, fast_result ); } }
  • 12. Integrated Computer Solutions Inc. www.ics.com Example (continued) 12 char neverBLockingTask (char *params, char *result) { switch (stateMachine) { //… case WAIT_ANSWER: if ( timedOut(&timer) ) { stateMachine = HANDLE_TIMEOUT; result = ANSWER_TIMEOUT; } else { receiveData( rxBuff + buffLen, *buffLen); if (*buff_len==0) { result = ANSWER_PENDING; } else { if ( ! fullAnswerReceived( *rxBuff, uint16_t *buffLen) ) { result = ANSWER_PENDING; } else { stateMachine = IDLE; result = ANSWER_RECEIVED; } } } break; // … } // switch return result; }
  • 13. Integrated Computer Solutions Inc. www.ics.com Running Python scripts on MCUs 13 ● Traditionally, MCUs languages are C and C++ ○ compilers, debuggers ● Python popularity ○ Huge community ○ Sintax simplicity ○ Excellent libraries ○ Good for data science/machine learning ○ Zoomers (Generation Z) prefer .py rather than .c ● Micropython: a small Python 3 interpreter and runtime for MCUs (bare-metal) ○ Open Source, MIT License ○ Footprint: 256 kb flash, 16 kb RAM ○ Not as performant as C (Python runtime needs to parse the script)
  • 14. Integrated Computer Solutions Inc. www.ics.com Micropython example 14 from machine import SPI, Pin spi = SPI(0, baudrate=400000) cs = Pin(4, mode=Pin.OUT, value=1) txdata = b"12345678" rxdata = bytearray(len(txdata)) try: cs(0) spi.write_readinto(txdata, rxdata) finally: cs(1)
  • 15. Integrated Computer Solutions Inc. www.ics.com FreeRTOS 15 ● Small kernel, it provides concurrency, with a small computing overhead ○ Open source and lightweight: footprint is around 4Kbytes ○ Concurrency implemented through threads. ○ Inter-task communication ■ Queues ■ Semaphores ■ Mutexes https://www.freertos.org/Inter-Task-Communication.html
  • 16. Integrated Computer Solutions Inc. www.ics.com FreeRTOS example 16 Two tasks communicating through queues #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" QueueHandle_t q=NULL; void app_main() { q=xQueueCreate(20,sizeof(unsigned long)); if (q != NULL) { vTaskDelay(1000/portTICK_PERIOD_MS); // one second delay xTaskCreate(&producer_task,"producer_task",2048,NULL,5,NULL); xTaskCreate(&consumer_task,"consumer_task",2048,NULL,5,NULL); } else { printf("Queue creation failed"); } }
  • 17. Integrated Computer Solutions Inc. www.ics.com FreeRTOS example (cont) 17 void producer_task(void *pvParameter) { unsigned long counter=1; BaseType_t resultQueue; while(1) { resultQueue = xQueueSend( q, &counter, (TickType_t )0); if (pdTrue == resultQueue) { printf("sent to the queue: %lun",counter); counter++; } vTaskDelay(1000/portTICK_PERIOD_MS); } } void consumer_task(void *pvParameter) { unsigned long counter; BaseType_t resultQueue; while(1) { resultQueue = xQueueReceive( q, &counter, (TickType_t ) 0); if (pdTrue == resultQueue) { printf("received from the queue: %lu n",counter); } vTaskDelay(20/portTICK_PERIOD_MS); } }
  • 18. Integrated Computer Solutions Inc. www.ics.com About ESP32 18
  • 19. Integrated Computer Solutions Inc. www.ics.com ESP32 flash management 19 ● Bootloader ● Flexible application partition options: ○ flat ○ ota_0/ota_1 (a.k.a. A/B partition) ● Optional user data, called ‘storage’ (can be FAT, or plain) # Name, Type, SubType, Offset, Size, Flags nvs, data, nvs, 0x9000, 0x4000, otadata, data, ota, 0xd000, 0x2000 phy_init, data, phy, 0xf000, 0x1000, ota_0, app, ota_0, 0x10000, 0x140000, ota_1, app, ota_1, , 0x140000, storage, data, fat, , 0x140000,
  • 20. Integrated Computer Solutions Inc. www.ics.com A microcontroller challenge… 20 Could a third-party Over-The-Air updates solution like Mender be implemented on a ESP32 module? ● Mender originally targeted for Linux cards, not MCUs… ● Enough flash space?
  • 21. Integrated Computer Solutions Inc. www.ics.com Updating capabilities 21
  • 22. Integrated Computer Solutions Inc. www.ics.com Web management console 22
  • 23. Integrated Computer Solutions Inc. www.ics.com ESP32: flash partitioning trade-offs… 23 ● with the storage partition ○ flash space divided by 3 ○ full download before updating ○ uncompress after download feasible # Name, Type, SubType, Offset, Size, nvs, data, nvs, 0x9000, 0x4000, otadata, data, ota, 0xd000, 0x2000 phy_init, data, phy, 0xf000, 0x1000, ota_0, app, ota_0, 0x10000, 0x140000, ota_1, app, ota_1, , 0x140000, storage, data, fat, , 0x140000, ● without the storage partition ○ flash space divided by 2 ○ partial downloads, update by chunks ○ needs uncompressed artifacts # Name, Type, SubType, Offset, Size, nvs, data, nvs, 0x9000, 0x4000, otadata, data, ota, 0xd000, 0x2000 phy_init, data, phy, 0xf000, 0x1000, ota_0, app, ota_0, 0x10000, 0x1F8000, ota_1, app, ota_1, , 0x1F8000,
  • 24. Integrated Computer Solutions Inc. www.ics.com Understanding a 3rd party file format 24 ● Based on tar format ○ Header ○ One or more files packed, including version, payload type, checksum. ● Mender utility for artifact preparation ● Compression options (gzip, lzma or none)
  • 25. Integrated Computer Solutions Inc. www.ics.com Moving from challenge into action 25 ● #1 receive firmware by chunks ○ firmware footprint around 2 Mbytes ○ Receive buffer size tradeoffs ● #2 parse a tar file on the fly ○ At proper offset, obtain the firmware file size ○ At proper offset, get fragments of the firmware file as they arrive.
  • 26. Integrated Computer Solutions Inc. www.ics.com Receive firmware by chunks 26 ● Use HTTP Range header ● Tested with cURL first, then implemented on the ESP32 HTTP API GET /api/devices/v1/deployments/device/deployments/next?artifact_name=fw_v1_0.mender&device_type=ESP32 HTTP/1.1 Host: docker.mender.io Range: bytes=0-1023 HTTP/1.1 206 Partial Content Content-Range: bytes 0-1023/1246515 Content-Length: 1024 ... (binary content)
  • 27. Integrated Computer Solutions Inc. www.ics.com Receive firmware by chunks (cont.) 27 if (body_length>0) { offset=0; esp_http_client_handle_t client = esp_http_client_init(&config); to=-1; while (1) { from=to+1; if (from>=body_length-1) { /* Reached the end of GET answer, run latest OTA API call , for latest bootloader setup */ esp_ota_end(update_handle); esp_ota_set_boot_partition(update_partition); result=MENDER_DOWNLOAD_OK; break; } to=from+MENDER_RESPONSE_BUFFER-1; if (to>body_length-1) { to=body_length-1; } sprintf (range_string,"bytes=%d-%d", from, to); esp_http_client_set_header(client, "Range", range_string); esp_http_client_perform(client); content_length = esp_http_client_get_content_length(client); artifact_processBlock( client->response_buffer, ...); // … } }
  • 28. Integrated Computer Solutions Inc. www.ics.com Parse a tarball by chunks 28 ● Understand the tarball definition ● Understand artifacts structure (tar inside a tar) ● Implement the stream parser.
  • 29. Integrated Computer Solutions Inc. www.ics.com Parse a tarball by chunks 29 int artifact_processBlock ( char *inbuff, size_t inbuff_length, size_t *offset, char *outbuff, size_t *outbuff_length, size_t outbuff_size) { //…. if (*offset + inbuff_length <= FILESIZE_OFFSET + FILESIZE_LENGTH) { // start of file size reached, end of file size not reached if (*offset< FILESIZE_OFFSET) { // start of buffer before start of file size size_t amount = inbuff_length-(FILESIZE_OFFSET-*offset); memcpy (filesizeBuffer+filesizeBufferLength, inbuff+(FILESIZE_OFFSET-*offset), amount); filesizeBufferLength += amount; } else { // start of buffer after start of file size size_t amount = inbuff_length; memcpy (filesizeBuffer+filesizeBufferLength, inbuff, amount); filesizeBufferLength += amount; } if (FILESIZE_LENGTH == filesizeBufferLength) { convertBufferToFileSize (filesizeBuffer, &fileSize); fileSizeValid = true; } *offset += inbuff_length; result = 0; goto exit_func; } // …..
  • 30. Integrated Computer Solutions Inc. www.ics.com Security aspects 30 ● Open source version: ○ Transport Secure Layer protocol, TLS ○ Self signed or Certificate Authority ○ Provisioning @ factory plant ● Paid plans ○ Same as above, plus mutual TLS authentication
  • 31. Integrated Computer Solutions Inc. www.ics.com Conclusions ● Big MCU/MPUs ecosystems raise the bar for more complex projects ● Modules integrating MCU and radio chips provide quick yet powerful resource for IoT. ● Cybersecurity concerns for IoT devices. ● Peripherals integrated to the MCU processor. Serial links (SPI, I2C, CAN, USART) for off-chip peripherals, ● FreeRTOS and similar small footprint simplifies implementation on MCUs
  • 32. Integrated Computer Solutions Inc. www.ics.com All images were taken from STM32, Mender’s online documentation. Questions? gstola@ics.com