MakerSpace Amiens · Microcontrollers

Discovering the microcontroller

Lecture 1: from the chip to the code

Alban Petit

On the agenda

  1. The course
  2. A computer on a chip
  3. Under the hood
  4. From the code to the chip
2UniLaSalle Amiens

What you will be able to do

By the end of this lecture, you will be able to:

  • understand what a microcontroller is, and what sets it apart from a PC
  • name the blocks of a chip: CPU, Flash, RAM, peripherals, bus
  • explain what a register is, and what an interrupt is for
  • say what distinguishes a compiled language (C/C++) from an interpreted language (Python)
  • follow the path from the source code to execution on the chip
  • say why delay() is a problem in a loop()

Common thread of the course: a Pong, then a multiplayer Snake.

The Microcontrollers course

3UniLaSalle Amiens

The course

Where to find help, what lies ahead, and why

Everything is on the website

doc.makerspace-amiens.fr, Workshops section, then Microcontrollers.

  • The syllabus and the assessment
  • The slides of each lecture, including these
  • The concepts: the theory, to reread before each lab
  • The tutorials: each lab, step by step
  • The guides: when something does not work

Each slide ends with a badge that opens the matching page. ↓ for the course page.

The Microcontrollers course

5UniLaSalle Amiens

The course page

5.1UniLaSalle Amiens

Finding the right page

You want to… Go and see
Understand a notion A concept (GPIO, bus, state machine…)
Do it, step by step The lab’s tutorial
Get unstuck A guide (board not found, black screen)
A component’s characteristic Its reference sheet (XIAO, display)
The full details of a chip Its datasheet, on the manufacturer’s website

The site’s search bar finds a page by keyword. The Need help? button, at the bottom right, opens the MakerSpace’s AI assistant.

Course syllabus Recovering an ESP32-S3 board

6UniLaSalle Amiens

Outside the site: the official sources

  • Espressif: the ESP32-S3 datasheet, the Arduino-ESP32 documentation
  • Seeed Studio: the XIAO ESP32S3 board wiki
  • Libraries: their GitHub page, its README and its examples
  • PlatformIO: its documentation, for the project configuration

A forum or an AI assistant helps you search. But when two sources contradict each other, the manufacturer’s documentation settles it.

XIAO ESP32S3

7UniLaSalle Amiens

The course schedule

Session Duration What you do
Lectures 1, 2, 3 3 × 1 h 30 The concepts, in lectures
Lab 1 1 h 30 Install, flash a first program
Lab 2 3 h Test the modules of the kit
Lab 3 3 h Design your board in KiCad
Lab 4 3 h Solder the board, run a Pong on it
Project 24 h A multiplayer Snake, in pairs

The three lectures first, then the labs, then the project. Each stage builds on the previous one.

Course syllabus

8UniLaSalle Amiens

How you are assessed

30 %

The labs: each checkpoint validated in session, including the two validations of your board

70 %

The project: the game, the browser player, the code, the repo and the demonstration

A checkpoint is validated in session, on your setup: come with work that works.

Course assessment

9UniLaSalle Amiens

What you are going to cover

Electronics

  • Read and test a component
  • Wire on a breadboard
  • Design a board, solder it

Embedded software

  • Program in C/C++
  • Never block the program
  • Structure with a state machine

Networking

  • Wi-Fi, web page, WebSocket
  • Design a protocol

Method

  • Test, validate, document
  • Run a project in pairs

Course syllabus

10UniLaSalle Amiens

And in your life as an engineer?

  • Microcontrollers are everywhere: cars, medical, industry, energy
  • You will choose them, specify them, integrate them into your products
  • You will speak the same language as electronics engineers
  • You will be able to prototype a sensor, a test bench, a demonstrator on your own
  • Test, design, document: reflexes for any project

Even if you do not program microcontrollers every day, you will work with those who do.

The Microcontrollers course

11UniLaSalle Amiens

Activity: what is it, for you?

What is a microcontroller, for you?

  • One answer per person, out loud: a word, a sentence, an example
  • No right or wrong answer
12UniLaSalle Amiens

A computer on a chip

Sense, decide, act

There are hundreds of them around you

  • Every phone contains several: touchscreen, battery, radio
  • Wireless earbuds, watches, access badges
  • In every room: projector, smoke detector, thermostat
  • In the corridor: the printer, the vending machine, the badge readers
  • At home: the microwave, the washing machine, the remote control
  • And 50 to 150 in a recent car: windows, airbags, injection

None of them needs a “real” computer. They need a chip costing a few euros, which starts instantly and does its task in a loop.

What is a microcontroller?

14UniLaSalle Amiens

Always the same loop

flowchart LR
  A["Sense<br/>(sensors)"] --> B["Decide<br/>(the program)"]
  B --> C["Act<br/>(actuators)"]
  C -.-> A

A thermostat senses the temperature, decides it is too cold, acts by turning on the heating. Then it starts again, forever.

You will find this loop exactly as is in your Pong: read the joystick, compute the ball’s position, redraw the screen.

What is a microcontroller? Sensors

15UniLaSalle Amiens

The “decide” part is you.


void loop() {
  int temperature = readSensor();    // sense
  if (temperature < 19) {           // decide
    turnOnHeating();                 // act
  }
}

The microcontroller cannot do anything on its own. Without a program, it is an inert chip: the 19 °C threshold and what is done with it, nobody will write them for you.

16UniLaSalle Amiens

The course vocabulary

Term What it is Examples from the project
Sensor Turns a physical quantity into an electrical signal button, joystick, potentiometer
Actuator Turns an electrical signal into an action LED, display, motor, buzzer
Pin A leg of the chip, connected to the outside world D5, D0 (GPIO6, GPIO1)
Program The sequence of instructions you write main.cpp

A button is a sensor, an LED is an actuator.

Sensors

17UniLaSalle Amiens

The physical world does not wait

A microcontroller is judged on its punctuality, not its power.

  • An airbag must fire 20 ms after the impact, never 100
  • The Pong screen is redrawn every 16 ms, otherwise it stutters
  • A servo motor expects a pulse every 20 ms, within 10 µs
  • Meeting the deadline at every pass matters more than being fast once

Deterministic: the same inputs produce the same actions, in the same time, at every pass. On a PC a 200 ms delay goes unnoticed, here it breaks the system. Real time does not mean “fast”, it means “on time”.

What is a microcontroller?

18UniLaSalle Amiens

Why not a “real” computer?

  Regular computer Microcontroller
Tasks Thousands, at the same time A single one, in a loop
Price Several hundred € A few euros, sometimes cents
Power Plugs into the mains Months on a battery
Start-up Several seconds Instant
System A full OS None, usually

This frugality is what makes it so widespread: you can put them everywhere, for next to nothing, without thinking about it.

What is a microcontroller?

19UniLaSalle Amiens

What about the Raspberry Pi?

Microcontroller

A single task, real time, very little energy, instant start-up.

ESP32-S3, Arduino, STM32

Single-board computer

A real operating system (Linux), a screen, full networking, plenty of memory.

Raspberry Pi

The question to ask is not “which is the most powerful” but “what do I really need”. A Raspberry Pi that takes 20 seconds to boot cannot fire an airbag.

What is a microcontroller?

20UniLaSalle Amiens

Who makes microcontrollers?

Manufacturer Country Families Speciality
STMicroelectronics France / Italy STM32 Industry, huge range
NXP Netherlands LPC, i.MX RT Automotive, contactless
Infineon Germany AURIX, PSoC Automotive, power
Renesas Japan RA, RX Automotive, Arduino Uno R4
Microchip United States PIC, AVR The Arduino Uno’s ATmega
Espressif China ESP32 Built-in Wi-Fi, at low cost

The top five share most of the market, driven by the automotive industry. Others rule a niche: Nordic for Bluetooth, Raspberry Pi for education.

What is a microcontroller?

21UniLaSalle Amiens

Espressif, Wi-Fi for everyone

  • 2008: founded in Shanghai
  • 2014: the ESP8266 puts a programmable Wi-Fi chip on sale for a few euros
  • 2016: the ESP32 adds a second core and Bluetooth
  • Makers adopt it: Arduino, open documentation, thousands of projects
  • So does industry: connected plugs, bulbs, sensors

Not the biggest manufacturer, but the reference for Wi-Fi connected devices.

What is a microcontroller?

22UniLaSalle Amiens

The ESP32 family

Chip Cores Radio What for
ESP32 2 × 240 MHz Wi-Fi, Bluetooth The original, versatile
ESP32-S2 1 × 240 MHz Wi-Fi Native USB
ESP32-S3 2 × 240 MHz Wi-Fi, BLE 5 The most powerful with Wi-Fi
ESP32-C3 1 × 160 MHz Wi-Fi, BLE 5 Low price, RISC-V core
ESP32-C6 1 × 160 MHz Wi-Fi 6, BLE, Thread Smart home
ESP32-P4 2 × 400 MHz None Multimedia

S: performance, C: low-cost (RISC-V), P: high performance without radio. The ESP32-S3 is the top of the connected range.

What is a microcontroller?

23UniLaSalle Amiens

Why the ESP32-S3?

  • Built-in Wi-Fi and Bluetooth: player 2 plays from a browser
  • Power to spare: game, colour display and network at the same time
  • Native USB: programmed without a driver, on every system
  • An accessible ecosystem: Arduino, PlatformIO, ESP-IDF
  • Less than €10 per board, and the same chip in real products

In return: it consumes more than a low-power chip, and it lives at 3.3 V.

What is a microcontroller?

24UniLaSalle Amiens

Chip, module or development board?

The chip

ESP32-S3 chip

  • The µC alone, 7 × 7 mm
  • Unusable on its own

The module

ESP32-S3-WROOM-1 module

  • Chip, Flash, crystal
  • Antenna, shielding

The dev board

XIAO ESP32S3 board

  • USB, regulator
  • Buttons, pins

You program the chip. The dev board (XIAO) adds what is needed to connect it to the PC. ↓ to see what it contains.

XIAO ESP32S3

25UniLaSalle Amiens

What is on the XIAO

Schematic of the XIAO ESP32S3

The ESP32-S3 chip in the middle, its 40 MHz crystal, its 8 MB Flash, the antenna and the decoupling capacitors. Schematic: Seeed Studio.

XIAO ESP32S3

25.1UniLaSalle Amiens

The XIAO pinout

Pinout of the XIAO ESP32S3

11 pins, D0 to D10, each with several possible functions. Image: Seeed Studio.

XIAO ESP32S3

25.2UniLaSalle Amiens
  3.3 V, never 5 V

Connecting a GPIO pin directly to 5 V (an Arduino Uno, a sensor powered at 5 V) can destroy the chip irreversibly. It is the most frequent and most expensive mistake in the course: before connecting a module, look up its supply voltage.

GPIO and the digital world

26UniLaSalle Amiens

Under the hood

CPU, memories, peripherals, bus

The block diagram, your mental map

Functional block diagram of the ESP32-S3

Each concept of the course details one of these building blocks.

Architecture of a microcontroller

28UniLaSalle Amiens

Five building blocks, a single chip

Block Role Software access
CPU Executes the instructions one by one direct
Flash Stores the program (persistent) read at run time
RAM Variables, call stack (volatile) fast read/write
Peripherals GPIO, ADC, UART, SPI, PWM through registers
Bus Connects everyone transparent with Arduino

Everything is on the same silicon: a System on Chip. Powering it is all it takes.

Architecture of a microcontroller

29UniLaSalle Amiens

The CPU can only do one thing

Fetch

Fetch: get the next instruction from Flash, at the address given by the program counter.

30UniLaSalle Amiens

The CPU can only do one thing

Fetch
→
Decode

Decode: understand what the instruction asks for, and on which data.

31UniLaSalle Amiens

The CPU can only do one thing

Fetch
→
Decode
→
Execute

Execute: compute in the ALU, or transfer a piece of data. Then start again, 240 million times per second.

Deep down, a CPU only does two things: compute, and move bytes from one place to another.

Architecture of a microcontroller

32UniLaSalle Amiens

240 MHz, what does that mean?

Operation Order of magnitude
An integer multiplication one or two cycles
A digitalWrite() a few dozen cycles
Redrawing the 240 × 320 screen over SPI a few million cycles
Establishing a Wi-Fi connection several hundred million

At 60 frames per second, each frame has 4 million cycles.

Architecture of a microcontroller

33UniLaSalle Amiens

The clock, up close

A square clock signal whose period lasts 4.2 ns at 240 MHz

Each edge moves the CPU forward one step: 240 million times per second.

Architecture of a microcontroller

33.1UniLaSalle Amiens

Two cores, and the right to sleep

  • The ESP32-S3 has two Xtensa LX7 cores: with Arduino, setup()/loop() run on core 1, Wi-Fi occupies core 0 in the background, under the control of a small kernel (FreeRTOS)
  • Cutting the clock of an unused peripheral saves energy
  • Sleep modes (light sleep, deep sleep) switch off all or part of the chip
  • The RTC keeps running in deep sleep to wake the board up at the set time

This is what lets a battery-powered sensor last for months: it sleeps 99.9 % of the time.

Architecture of a microcontroller

34UniLaSalle Amiens

Two memories, two uses

  Flash RAM (SRAM)
Content Compiled program, constants Variables, stack, heap
Persistence Survives a reset Lost at power-off
Speed Slower Very fast
Size 8 MB 512 KB (+ 8 MB PSRAM)

Two separate address spaces: a modified Harvard architecture. ↓ to locate them on the block diagram.

Architecture of a microcontroller

35UniLaSalle Amiens

The memories on the block diagram

Functional block diagram of the ESP32-S3

Find the ROM (the boot program burned in at the factory), the internal SRAM, and the link to the Flash and the PSRAM, outside the chip.

Architecture of a microcontroller

35.1UniLaSalle Amiens

The peripherals glossary

Acronym Full name Role
GPIO General Purpose Input/Output Digital input or output
ADC Analog to Digital Converter Voltage to number
UART / I2C / SPI   Serial buses
Timer Hardware counter Periodic events, PWM
DMA Direct Memory Access Transfer without the CPU
RTC Real-Time Clock Clock, even in sleep
Watchdog Watchdog timer Restarts if stuck

Each acronym will get its own slide in Lecture 2 or Lecture 3.

Architecture of a microcontroller

36UniLaSalle Amiens
  No DAC on the ESP32-S3

Unlike the original ESP32, the ESP32-S3 has no hardware digital-to-analog converter. To produce a variable voltage, you will have to use PWM, which we will see in Lecture 2.

ADC and PWM

37UniLaSalle Amiens

The bus: a shared highway

flowchart TB
  CPU["CPU (drives the bus)"]
  BUS["Shared bus: addresses · data · control"]
  RAM["RAM"]
  PA["Periph. A<br/>(active transmitter)"]
  PB["Periph. B<br/>(high impedance)"]
  CPU --- BUS
  BUS --- RAM
  BUS --- PA
  BUS --- PB

Three bundles: the address says who we are talking to, the data travels, the control specifies “I am reading” or “I am writing”.

Architecture of a microcontroller

38UniLaSalle Amiens

Only one component talks at a time

If two peripherals pushed a value onto the data bus at the same time, one forcing a 0 and the other a 1, it would be a short circuit.

Hence three-state outputs: on top of 0 and 1, a high impedance state that electrically disconnects the component from the line.

At any moment, only one transmitter is active; all the others are listening. The address designates the one allowed to answer.

Remember the term high impedance: it will come back in Lecture 2 with floating inputs, and in Lecture 3 with I2C.

Architecture of a microcontroller

39UniLaSalle Amiens

Registers: the hardware / software interface

Each peripheral is driven through registers: simple memory cells at a fixed address.

  • Writing to a register turns on an LED
  • Reading a register gives the state of a button
  • digitalWrite(LED, HIGH) writes to the right register

Storing a variable and turning on an LED: the same operation, putting a value at an address.

Architecture of a microcontroller

40UniLaSalle Amiens

A register is 32 switches

A 32-bit register often drives 32 things at once: one bit per pin, one bit per option. You only touch the targeted bit, with C’s bitwise operators:

reg |=  (1 << n);      // sets bit n to 1, without touching the others
reg &= ~(1 << n);      // sets bit n to 0
reg ^=  (1 << n);      // toggles bit n
if (reg & (1 << n))    // tests bit n

This is the language of datasheets: the reference manual describes each register bit by bit.

Architecture of a microcontroller

41UniLaSalle Amiens

Breaking down reg |= (1 << n)

The instruction combines three operations:

  1. The shift 1 << n: the value 1 (00000001) shifted n positions to the left. For n = 3: 00001000. It is a mask: only the targeted bit is 1.
  2. The bitwise OR |: 1 OR x gives 1, so the targeted bit becomes 1; 0 OR x gives x, so the others do not change.
  3. The assignment |=: the shorthand for reg = reg | (1 << n);.

Architecture of a microcontroller

42UniLaSalle Amiens

An example, bit by bit

We want to set bit 3 to 1, without touching the others:

reg            1010 0001
1 << 3         0000 1000   the mask
reg | mask     1010 1001   only bit 3 has changed

Bits are numbered from right to left, starting from 0. The same idea works for the other lines: & ~mask sets the bit to 0, ^ mask toggles it, & mask tests it.

Architecture of a microcontroller

43UniLaSalle Amiens

The mask, cell by cell

The register 1010 0001, the mask 0000 1000 and the result 1010 1001: only bit 3 changes

The first eight bits of a 32-bit register: only the targeted bit changes.

Architecture of a microcontroller

43.1UniLaSalle Amiens

Under digitalWrite(), a write

digitalWrite(21, HIGH);                   // the Arduino version
REG_WRITE(GPIO_OUT_W1TS_REG, 1 << 21);    // the register, directly
REG_WRITE(GPIO_OUT_W1TC_REG, 1 << 21);    // sets the pin back to 0

GPIO_OUT_W1TS_REG is just a name for the address 0x60004008. W1TS: write 1 to set, only the bits written as 1 become 1, the others do not move.

Why not GPIO_OUT_REG |= ...? It has to read, modify, rewrite: if an interrupt changes the register in the meantime, its change is lost. W1TS does it in a single write.

Architecture of a microcontroller ESP32-S3 Technical Reference Manual

44UniLaSalle Amiens

Activity: Flash or RAM?

In your Pong, where does each of these live?

  • The code of loop()
  • The game score
  • A sprite’s image, declared const
  • The ball’s position
  • The Wi-Fi network name, hard-coded
  • A local counter, in a function
45UniLaSalle Amiens

Where your variables live

What you write Where it lives For how long
The code, hard-coded strings Flash survives a reset
const uint16_t SPRITE[] = {...}; Flash survives a reset
int score; outside the functions RAM the whole program
int i; in a function RAM, on the stack the duration of the call

The const keyword moves a large array from RAM to Flash: precious for a game’s images.

Architecture of a microcontroller

46UniLaSalle Amiens

The stack and the heap

The stack

  • Local variables, parameters
  • Taken at the call, given back on return
  • Fast, automatic, but small

The heap

  • Memory reserved on demand
  • Used by String, Wi-Fi
  • Fragments over time

A large array declared in a function can overflow the stack: the chip restarts. In a game, prefer fixed-size global variables.

Architecture of a microcontroller

47UniLaSalle Amiens

The memory map

In Flash the code and the constants; in RAM the global variables, the heap going up, the stack going down

If the stack and the heap meet, the chip restarts.

Architecture of a microcontroller

47.1UniLaSalle Amiens

From the code to the chip

Compile, flash, execute

In which language?

  • On a microcontroller, you program in C or C++
  • Arduino is C++
  • You know Python: the logic is the same

What changes is when the code is translated into instructions for the processor.

From hardware to software

49UniLaSalle Amiens

Arduino: three things under one name

Boards

Uno, Nano, Mega: development boards, often built around an ATmega

Software

The Arduino IDE, to write, compile and upload

A framework

setup(), loop(), digitalWrite()… ported to hundreds of chips, including the ESP32-S3

In the course, we use the framework (Arduino-ESP32), with PlatformIO. Neither the board nor the IDE.

From hardware to software

50UniLaSalle Amiens

Why not an Arduino Uno board?

  Arduino Uno XIAO ESP32S3
Processor ATmega328P, 8-bit, 16 MHz ESP32-S3, 2 32-bit cores, 240 MHz
RAM 2 KB 512 KB + 8 MB
Wi-Fi, Bluetooth No Yes
Logic voltage 5 V 3.3 V
Size 69 × 53 mm 21 × 18 mm

The Arduino framework brings simplicity; the ESP32-S3, the power and Wi-Fi needed for a colour display and the browser player.

What is a microcontroller?

51UniLaSalle Amiens

Compiled or interpreted

C / C++: compiled

The compiler translates the whole program beforehand, on your PC, into machine code.

The chip executes it directly.

Python: interpreted

An interpreter translates the code during execution, as it goes.

It must run on the machine that executes it.

From hardware to software

52UniLaSalle Amiens

Why C/C++ on a microcontroller?

  • No interpreter to fit in the chip’s small memory
  • Fast: the chip executes the machine code directly
  • Errors caught early: the compiler reports them before flashing

From hardware to software

53UniLaSalle Amiens

The full journey

flowchart LR
  A["Source code<br/>(.cpp)"] --> B["Compiler<br/>(gcc-xtensa)"]
  B --> C["Binary<br/>(.bin)"]
  C --> D["Flashing<br/>(USB / UART)"]
  D --> E["Execution<br/>ESP32-S3"]

A click on Upload triggers the four steps, always in this order. When something fails, the first question is: at which step?

From hardware to software

54UniLaSalle Amiens

The Arduino-ESP32 toolchain

Element Role
Compiler (gcc for Xtensa) Translates C++ into machine instructions
Arduino core Provides pinMode(), digitalWrite(), analogRead()
Uploader (esptool) Transfers the binary to the Flash, over USB

The IDE only orchestrates these three tools. Arduino IDE or PlatformIO, the chain stays the same: compile, flash, execute.

PlatformIO Arduino IDE

55UniLaSalle Amiens

“Compiling” covers three steps

  1. Preprocessor: handles the #include and #define directives, pastes in the content of the libraries
  2. Compilation: each C++ file becomes object code, separately
  3. Linking: all the objects are assembled into a binary, resolving the references

Telling them apart means knowing how to read an error. It is the most profitable skill of the semester.

From hardware to software

56UniLaSalle Amiens

Reading an error

Message Step Likely cause
expected ';' before ... compilation a syntax mistake, often one line before
'x' was not declared compilation misspelled variable, or missing #include
undefined reference to ... linking library missing from lib_deps
A fatal error occurred: Failed to connect flashing wrong port, charge-only cable, BOOT button

Fix the first error, not the next 40.

From hardware to software

57UniLaSalle Amiens

Reading a successful build

RAM:   [=         ]   6.0% (used 19736 bytes from 327680 bytes)
Flash: [=         ]   8.1% (used 270213 bytes from 3342336 bytes)
========== [SUCCESS] Took 4.21 seconds ==========

A simple Blink already weighs 270 KB: the Arduino core, FreeRTOS and the USB drivers are compiled along with your ten lines.

  • RAM: the global variables (neither the stack nor the heap)
  • Flash: the code and the constants, what flashing writes

Indicative values on the XIAO ESP32S3. Keep an eye on these two lines when you add images.

From hardware to software

58UniLaSalle Amiens
  Flashing keeps failing?

In this order: check that the USB-C cable carries data (many cables only charge), that the right port is selected, then force upload mode: unplug the XIAO, hold BOOT while plugging the cable back in, release and start the upload again. Then press RESET to start the program.

Checking the toolchain

59UniLaSalle Amiens

A whole program in two functions

void setup() {                      // only once, at start-up
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
}

void loop() {                       // in a loop, until power is cut
  digitalWrite(LED_PIN, HIGH);
  delay(500);
  digitalWrite(LED_PIN, LOW);
  delay(500);
}

No main(): the Arduino core writes it, and calls setup() then loop(). With PlatformIO, main.cpp starts with #include <Arduino.h>: without it, none of these functions exist.

From hardware to software

60UniLaSalle Amiens

No PC operating system

On a computer, your program is one process among hundreds. Here, it is the only program on the chip:

  • a small kernel (FreeRTOS) runs Wi-Fi and USB alongside, but all your code lives in a single task: loop()
  • a delay() pauses this task: nothing in your program moves forward, buttons included
  • no clean shutdown: cutting the power stops the program dead

In return, your code is sole master of its time: its behaviour is predictable.

From hardware to software

61UniLaSalle Amiens

Activity: find the bug

void loop() {
  digitalWrite(LED, HIGH);
  delay(500);
  digitalWrite(LED, LOW);
  delay(500);

  if (digitalRead(BUTTON) == LOW) {
    fire();
  }
}

The user presses the button. What happens?

62UniLaSalle Amiens

Answer: the button is almost never read

The program spends 1 second out of 1 in the delay() calls. The digitalRead() is only reached once per pass.

  • A short 200 ms press: seen one time in five
  • Add a screen to refresh: the game becomes unplayable
  • The solution is not to shorten the delay(), it is to never block

From hardware to software

63UniLaSalle Amiens

Never block: check the time


unsigned long lastBlink = 0;
const unsigned long INTERVAL = 500;   // ms
int ledState = LOW;

void loop() {
  if (millis() - lastBlink >= INTERVAL) {
    lastBlink = millis();
    ledState = !ledState;
    digitalWrite(LED_PIN, ledState);
  }
}

The time is compared with a stored time: nothing is ever frozen.

From hardware to software

64UniLaSalle Amiens

delay() versus millis()

With delay, two presses are missed during the waits; with millis, loop runs continuously and reads them

Same LED, same pace: only the second program still sees the button.

From hardware to software

64.1UniLaSalle Amiens

How big is an int?

Type Arduino Uno (8-bit) ESP32-S3 (32-bit)
int 16 bits, up to 32,767 32 bits, up to 2.1 billion
long, unsigned long 32 bits 32 bits
uint8_t 8 bits, from 0 to 255 same
uint32_t 32 bits same

The size of an int depends on the chip: the same code can overflow on one and not on the other. The types from <stdint.h> (uint8_t, int16_t, uint32_t) have the same size everywhere: use them whenever the size matters.

From hardware to software

65UniLaSalle Amiens

millis() goes round the dial

millis() returns a 32-bit unsigned integer: it wraps back to 0 after 2³² ms, i.e. 49.7 days.

if (millis() - lastBlink >= INTERVAL)   // always correct
if (millis() >= lastBlink + INTERVAL)   // wrong at the wrap-around

Subtracting two unsigned numbers gives the real gap even if the counter has gone round, like on a clock: from 11 pm to 1 am, 2 hours have passed.

Always write now - time >= duration.

From hardware to software

66UniLaSalle Amiens

The millis() dial

The counter goes round in 49.7 days; the subtraction gives the small real gap even after the wrap to 0

Like on a clock: from 11 pm to 1 am, 2 hours have passed.

From hardware to software

66.1UniLaSalle Amiens
  delay() is still useful

For a short, one-off pause (initialising a component, waiting at start-up), delay() is perfectly acceptable. It is in loop(), when several tasks must move forward in parallel, that it should be avoided.

From hardware to software

67UniLaSalle Amiens

Or get notified: the interrupt


volatile bool pressDetected = false;

void IRAM_ATTR onPress() {
  pressDetected = true;   // as short as possible
}

void setup() {
  pinMode(BTN_PIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(BTN_PIN), onPress, FALLING);
}

On an edge of the button, the hardware suspends loop(), runs this very short function, then resumes exactly where it left off. IRAM_ATTR places it in internal RAM: without it, the chip ends up crashing.

Architecture of a microcontroller GPIO and the digital world

68UniLaSalle Amiens

The interrupt over time

loop is running, an edge of the button triggers the ISR for a few microseconds, then loop resumes and handles the press

The ISR notes, loop() handles.

Architecture of a microcontroller

68.1UniLaSalle Amiens

Key takeaways

  • A µC = CPU + Flash + RAM + peripherals, on a single chip
  • Sense, decide, act: the “decide” part is your program
  • Flash = the program (persistent), RAM = the data (volatile)
  • Peripherals are driven through registers
  • Code → compilation → linking → flashing → execution
  • A single task, loop(): delay() freezes it, millis() blocks nothing
  • Logic voltage: 3.3 V

Architecture of a microcontroller From hardware to software

69UniLaSalle Amiens

To do on your side

  1. Install VSCode, then the PlatformIO extension
  2. Let PlatformIO download the espressif32 platform: it is long, do not leave it until the last minute
  3. Go through the toolchain check tutorial to know what lies ahead

A working development toolchain before the hands-on work saves a whole session.

Installing VSCode Installing PlatformIO Checking the toolchain

70UniLaSalle Amiens
UniLaSalle Amiens, Demain commence ici