2.3 Floating-Point Numbers

Overview

Floating-point numbers are essential for handling decimal values in Arduino and MicroPython programming. However, due to their inherent approximation nature, comparing them directly for equality can be problematic. This section explores how to effectively use and compare floating-point numbers in your sketches.

What We Will Learn in This Section

  • Declaring and manipulating floating-point variables.
  • Challenges with comparing floating-point values.
  • Implementing a solution using tolerance checks.

Why Is This Lesson Important to You?

Understanding the behaviour of floating-point numbers helps ensure accurate calculations and condition checks in Arduino projects, preventing unexpected errors.

Components List

  • ESP32
  • USB cable for programming and power
  • Computer with Arduino IDE installed

Circuit Diagram (With Connection)

Not applicable for this topic.

Arduino CodeHere’s an explanation of the code:

 

float value = 1.1;

void setup() {
  Serial.begin(9600);
}

void loop() {
  value = value - 0.1;
 
  if (value == 0) {
    Serial.println("The value is exactly zero");
  } else if (almostEqual(value, 0)) {
    Serial.print("The value ");
    Serial.print(value, 7); // Print to 7 decimal places
    Serial.println(" is almost equal to zero, restarting countdown");
    value = 1.1;
  } else {
    Serial.println(value);
  }
 
bool almostEqual(float a, float b) {
  const float DELTA = 0.00001; // Maximum difference to be almost equal
  if (a == 0) return fabs(b) <= DELTA;
  if (b == 0) return fabs(a) <= DELTA;
  return fabs((a - b) / max(fabs(a), fabs(b))) <= DELTA;
}

 

  1. Variable Declaration
float value = 1.1;
  • float value = 1.1;: Declares a floating-point variable value and initializes it with 1.1.
  1. Setup Function
void setup() {
  Serial.begin(9600);
}
  • void setup(): Runs once when the microcontroller starts.
  • Serial.begin(9600);: Initializes serial communication at a baud rate of 9600. This allows you to send and receive data via the Serial Monitor.
  1. Loop Function
void loop() {
  value = value – 0.1;
  • void loop(): This function runs repeatedly in a continuous loop.
  • value = value – 0.1;: Subtracts 0.1 from the current value of value each time the loop runs.
  1. Conditional Statements
if (value == 0) {
  Serial.println(“The value is exactly zero”);
} else if (almostEqual(value, 0)) {
  Serial.print(“The value “);
  Serial.print(value, 7); // Print to 7 decimal places
  Serial.println(” is almost equal to zero, restarting countdown”);
  value = 1.1;
} else {
  Serial.println(value);
}
  • if (value == 0): Checks if value is exactly zero. If true, it prints “The value is exactly zero”.
  • else if (almostEqual(value, 0)): If value is not exactly zero, this condition checks if value is “almost equal” to zero by calling the almostEqual() function. If true, it prints the value to 7 decimal places and resets value to 1.1.
  • else: If neither condition is true, it simply prints the current value.
  1. The almostEqual Function
bool almostEqual(float a, float b) {
  const float DELTA = 0.00001; // Maximum difference to be almost equal
  if (a == 0) return fabs(b) <= DELTA;
  if (b == 0) return fabs(a) <= DELTA;
  return fabs((a – b) / max(fabs(a), fabs(b))) <= DELTA;
}
  • almostEqual(float a, float b): This function checks if two floating-point numbers a and b are nearly equal.
  • const float DELTA = 0.00001;: Defines a small threshold value (DELTA) that determines how close two numbers must be to be considered “almost equal.”
  • fabs(): This function returns the absolute value of a floating-point number.
  • if (a == 0) return fabs(b) <= DELTA;: If a is zero, checks if b is within the threshold.
  • if (b == 0) return fabs(a) <= DELTA;: If b is zero, checks if a is within the threshold.
  • return fabs((a – b) / max(fabs(a), fabs(b))) <= DELTA;: For non-zero values, it compares the relative difference between a and b to the threshold DELTA.

MicroPython

import time
import math

value = 1.1

def almost_equal(a, b, delta=0.00001):
    if a == 0:
        return abs(b) <= delta
    if b == 0:
        return abs(a) <= delta
    return abs((a - b) / max(abs(a), abs(b))) <= delta

while True:
    value -= 0.1
   
    if value == 0:
        print("The value is exactly zero")
    elif almost_equal(value, 0):
        print(f"The value {value:.7f} is almost equal to zero, restarting countdown")
        value = 1.1
    else:
        print(value)
   
    time.sleep(0.25)

 

Here’s an explanation of the code:

  1. Importing Modules
import time
import math
  • import time: Imports the time module to use functions related to time, such as sleep for delays.
  • import math: Although imported, the math module is not used in this particular code. It could be removed unless needed for other operations.
  1. Variable Declaration
value = 1.1
  • value = 1.1: Declares a floating-point variable value and initializes it with 1.1.
  1. Defining the almost_equal Function
def almost_equal(a, b, delta=0.00001):
    if a == 0:
        return abs(b) <= delta
    if b == 0:
        return abs(a) <= delta
    return abs((a – b) / max(abs(a), abs(b))) <= delta
  • def almost_equal(a, b, delta=0.00001):: Defines a function almost_equal that checks if two floating-point numbers a and b are nearly equal, within a small threshold (delta).
  • delta=0.00001: This sets the default value of delta to 0.00001, representing the maximum difference for the numbers to be considered almost equal.
  • if a == 0:: If a is zero, the function checks if b is within the threshold.
  • if b == 0:: If b is zero, the function checks if a is within the threshold.
  • return abs((a – b) / max(abs(a), abs(b))) <= delta: For non-zero values, the function calculates the relative difference between a and b and checks if it’s within the threshold delta.
  1. Main Loop
while True:
    value -= 0.1
  • while True:: Starts an infinite loop, which runs continuously.
  • value -= 0.1: Decreases value by 0.1 each time the loop runs.
  1. Conditional Statements
if value == 0:
    print(“The value is exactly zero”)
elif almost_equal(value, 0):
    print(f“The value {value:.7f} is almost equal to zero, restarting countdown”)
    value = 1.1
else:
    print(value)
  • if value == 0:: Checks if value is exactly zero. If true, prints “The value is exactly zero.”
  • elif almost_equal(value, 0):: If value is not exactly zero, this condition checks if value is “almost equal” to zero using the almost_equal function. If true, it prints the value to 7 decimal places and resets value to 1.1.
  • else:: If neither condition is true, it simply prints the current value.
  1. Delay
time.sleep(0.25)
  • time.sleep(0.25): Pauses the loop for 0.25 seconds before continuing.

Summary

  • Precision Issues: Floating-point numbers are approximations. Precision issues can arise, especially with repetitive calculations.
  • Comparison Challenges: Use tolerance-based methods to compare floating-point numbers.
  • Tolerance Setting: Adjust the delta value for your application’s needs.
  • Application Context: Understand the context and constraints of floating-point operations.
  • Microcontroller Constraints: Efficient handling of floating-point operations is crucial due to limited resources.

2.2 Simple Data Types 

Overview

In this section, we delve into the fundamental concept of Arduino data types. Choosing the right data type is critical for efficient memory usage and accurate representation of values on ESP32 boards. Understanding these data types equips you with the knowledge to optimize your code and leverage the capabilities of the Arduino platform effectively.

 What We Will Learn in This Section

In this section, we will explore the various Arduino data types available for use on ESP32 boards. You will learn:

  • The range and usage scenarios for each numeric data type, including int, unsigned int, long, unsigned long, float, double, char, and byte.
  • Differences between 8-bit and 32-bit board data types and considerations for choosing the appropriate type.
  • Practical examples and guidelines for selecting the right data type based on application requirements.
  • How to avoid common pitfalls and ensure compatibility with library functions and hardware interfaces.
  • Insight into using boolean types (bool) for logical conditions and digital I/O operations.

 Why Is This Lesson Important to You?

Understanding Arduino data types is fundamental to programming your ESP32 effectively for several reasons:

  • Optimized Memory Usage: Choosing the right data type ensures efficient use of memory on your ESP32 board, which is crucial especially in embedded systems with limited resources.
  • Accuracy in Data Representation: Different data types have varying ranges and precision levels. Selecting an appropriate type ensures accurate representation of numeric values, whether they are integers, floating-point numbers, or characters.
  • Compatibility with Libraries and Functions: Many libraries and functions in Arduino are designed to work with specific data types. Using incompatible types can lead to errors or incorrect behavior in your code.
  • Enhanced Code Readability: Clear and precise data type selection improves the readability and maintainability of your code, making it easier for you and others to understand and modify as needed.
  • Avoiding Common Pitfalls: Mismanagement of data types, such as overflow or underflow issues, can lead to unexpected results or even system failures. Understanding data types helps you avoid these pitfalls.
  • Foundation for Advanced Programming: Mastering data types sets the groundwork for tackling more complex projects and integrating additional features and peripherals into your ESP32 applications.

Arduino Data Types for 8-bit Boards (e.g., Uno)

Arduino supports several data types optimized for different ranges and types of data manipulation on 8-bit microcontroller boards such as the Uno. Understanding these data types helps in efficient memory usage and ensures compatibility with various Arduino libraries and functions.

Numeric Types

Data Type Bytes Range Use
int 2 -32768 to 32767 Represents signed integer values
unsigned int 2 0 to 65535 Represents only positive integer values
long 4 -2147483648 to 2147483647 Represents a wide range of signed integer values
unsigned long 4 0 to 4294967295 Represents only positive values with a wide range
float 4 3.4028235E+38 to -3.4028235E+38 Represents floating-point numbers with decimal precision
double 4 Same as float Double-precision floating-point numbers (not always distinct from float on 8-bit boards)
bool 1 false (0) or true (1) Represents Boolean values (true/false)
char 1 -128 to 127 Represents a single character or a signed integer value
byte 1 0 to 255 Represents an 8-bit unsigned value

Other Types

  • String: Represents a sequence of characters typically used for text manipulation.
  • void: Used in function declarations where no value is returned.

Discussion

  • Memory and Performance: 8-bit boards like the Uno have limited memory compared to 32-bit boards. Choosing the appropriate data type ensures efficient use of available resources.
  • Numeric Range: Understanding the range of each data type helps in selecting the right type based on the expected values in your application.
  • Compatibility: Libraries and functions in Arduino often expect specific data types. Choosing compatible types ensures seamless integration and correct operation of these libraries.
  • Overflow and Underflow: Care should be taken to avoid overflow (when a value exceeds the maximum capacity of a data type) and underflow (when a value falls below the minimum capacity), especially with signed integers.
  • Boolean Usage: Booleans (bool) are commonly used for conditions and digital state representation (e.g., HIGH and LOW).

Arduino Data Types for 32-bit Boards

Arduino supports various data types optimized for 32-bit microcontroller boards, offering expanded ranges and precision suitable for more complex applications compared to 8-bit boards like the Uno.

Numeric Types

Data Type Bytes Range Use
short int 2 -32768 to 32767 Represents signed short integer values
unsigned short int 2 0 to 65535 Represents unsigned short integer values
int 4 -2147483648 to 2147483647 Represents signed integer values
unsigned int 4 0 to 4294967295 Represents unsigned integer values
long 4 -2147483648 to 2147483647 Represents signed long integer values
unsigned long 4 0 to 4294967295 Represents unsigned long integer values
float 4 ±3.4028235E+38 Represents floating-point numbers with decimal precision
double 8 ±1.7976931348623158E+308 Double-precision floating-point numbers
bool 1 false (0) or true (1) Represents Boolean values (true/false)
char 1 -128 to 127 Represents a single character or a signed integer value
byte 1 0 to 255 Represents an 8-bit unsigned value

Other Types

  • String: Represents a sequence of characters typically used for text manipulation.
  • void: Used in function declarations where no value is returned.

Discussion

  • Memory and Performance: 32-bit boards offer expanded memory compared to 8-bit boards, allowing for more complex calculations and data processing.
  • Numeric Range: With wider ranges for integer and floating-point types, 32-bit boards can handle larger values and more precise calculations.
  • Compatibility: Libraries and functions in Arduino often expect specific data types. Choosing compatible types ensures seamless integration and correct operation of these libraries.
  • Floating-Point Precision: float and double provide varying degrees of precision for applications requiring decimal calculations.
  • Boolean Usage: Booleans (bool) are commonly used for conditions and digital state representation (e.g., HIGH and LOW).

MicroPython Data Types for 8-bit Boards

MicroPython offers a range of data types tailored for 8-bit microcontroller boards, providing flexibility and efficiency in memory usage and operations.

Numeric Types

Data Type Bytes Range Use
int 2 -32768 to 32767 Represents signed integer values
uint 2 0 to 65535 Represents unsigned integer values
bool 1 False (0) or True (1) Represents Boolean values (True/False)
float 4 3.4028235E+38 to -3.4028235E+38 Represents floating-point numbers with decimal precision

Other Types

  • str: Represents a string of characters, used for text manipulation.
  • bytes: Represents a sequence of bytes, typically used for binary data handling.
  • bytearray: Mutable version of bytes, allowing modifications after creation.
  • NoneType: Represents the absence of a value, similar to void in other languages.

Discussion

  • Memory Efficiency: 8-bit boards have limited memory compared to 32-bit counterparts. Choosing appropriate data types ensures efficient memory usage and optimal performance.
  • Numeric Range: int and uint provide options for signed and unsigned integers, respectively, accommodating various application needs.
  • Floating-Point Precision: float offers decimal precision for calculations requiring fractional values, albeit with limitations compared to 32-bit boards.
  • Boolean Usage: bool is crucial for conditionals and digital state representation (e.g., True and False), essential for control flow in programs.
  • String Handling: str and bytes facilitate text and binary data manipulation, essential for communication protocols and data storage.

MicroPython Data Types for 32-bit Boards

MicroPython supports a robust set of data types tailored for 32-bit microcontroller boards, offering enhanced memory handling and computational capabilities.

Numeric Types

Data Type Bytes Range Use
int 4 -2147483648 to 2147483647 Represents signed integer values
uint 4 0 to 4294967295 Represents unsigned integer values
bool 1 False (0) or True (1) Represents Boolean values (True/False)
float 4 ±3.4028235E+38 Represents floating-point numbers with decimal precision
complex 8 Complex numbers Represents numbers with real and imaginary parts

Other Types

  • str: Represents a string of characters, used for text manipulation.
  • bytes: Represents a sequence of bytes, typically used for binary data handling.
  • bytearray: Mutable version of bytes, allowing modifications after creation.
  • NoneType: Represents the absence of a value, similar to void in other languages.

Discussion

  • Enhanced Precision: 32-bit boards offer extended range and precision for int and float types compared to 8-bit counterparts, supporting complex calculations and data processing tasks.
  • Memory Management: Larger memory space allows for efficient handling of larger data sets and complex algorithms, critical for applications requiring extensive computational power.
  • Complex Numbers: The complex type supports operations involving real and imaginary parts, beneficial for scientific computations and signal processing.
  • String and Byte Handling: str and bytes facilitate versatile data manipulation, essential for communication protocols, file handling, and data storage in IoT and embedded systems.

 

Summary

Understanding data types is crucial for effective programming with Arduino and MicroPython on ESP32 boards. Here are key takeaways:

  • Memory Management: Choose appropriate data types to optimize memory usage.
  • Precision: Use int and float effectively for numeric data handling.
  • Boolean and Complex Types: Utilize bool for logical operations and complex for scientific calculations.
  • String and Byte Handling: Leverage str, bytes, and bytearray for versatile data manipulation.

2.1 A Fundamental Structure Arduino and MicroPython Sketch

Overview

In this section, you’ll learn about the fundamental structure of an Arduino sketch and MicroPython script, which is essential for programming the ESP32.

What We Will Learn in This Section

  • Understanding the components of an Arduino and MicroPython sketch.
  • Familiarising with the setup() and loop() functions.
  • Implementing basic LED control using an Arduino sketch and MicroPython script.

Why Is This Lesson Important to You?

Understanding the structure of an Arduino sketch is crucial as it forms the basis for programming your ESP32 board effectively. This knowledge allows you to create and execute code to control various peripherals and sensors connected to your ESP32.

Components List:

  • ESP32 Development Board: To execute the Arduino sketch and control peripherals.
  • USB Cable: For programming and powering the ESP32 board.
  • LED: An LED connected to the onboard LED pin (often pin 13 on many Arduino-compatible boards).
  • Resistors: Typically, a current-limiting resistor for the LED (usually 220 ohms is sufficient).
  • Breadboard (optional): For prototyping and connecting components temporarily.
  • Jumper Wires: To make connections between components and the ESP32 board.
  • Computer with Arduino IDE: For writing, compiling, and uploading the Arduino sketch to the ESP32 board.

These components are essential for setting up and running the basic LED control project outlined in the section. Adjustments may be needed based on specific board variations or project requirements.

Circuit Diagram

 A Fundamental Structure Arduino and MicroPython Sketch

Component Connection ESP32 Pin How to Connect
LED Anode (long leg) GPIO 13 Connect to GPIO 13 through a current-limiting resistor.
Cathode (short leg) GND Connect to GND.
USB Cable USB USB Connect ESP32 to the computer via USB for programming and power.

Arduino Code

// Define the GPIO pin connected to the LED
const int LED_PIN = 13; // Use GPIO 13 for onboard LED on most ESP32 boards

void setup()
{
  pinMode(LED_PIN, OUTPUT); // Initialize the LED pin as an output
}

void loop()
{
  digitalWrite(LED_PIN, HIGH);   // Turn the LED on (HIGH level)
  delay(1000);                   // Wait for 1 second
  digitalWrite(LED_PIN, LOW);    // Turn the LED off (LOW level)
  delay(1000);                   // Wait for 1 second
}

 

Here’s an explanation of the code:

  1. Defining the GPIO Pin
const int LED_PIN = 13;
  • const int LED_PIN = 13;: This line defines a constant integer LED_PIN and assigns it the value 13. This value represents the GPIO pin number connected to the LED. In this case, GPIO 13 is typically used for the onboard LED on many ESP32 boards.
  1. Setup Function
void setup()
{
  pinMode(LED_PIN, OUTPUT);
}
  • void setup(): This is the setup function that runs once when the ESP32 is powered on or reset.
  • pinMode(LED_PIN, OUTPUT);: This line configures GPIO 13 as an output pin. This means the pin can now send a voltage signal to control the LED.
  1. Loop Function
void loop()
{
  digitalWrite(LED_PIN, HIGH);
  delay(1000);
  digitalWrite(LED_PIN, LOW);
  delay(1000);
}
  • void loop(): This function runs repeatedly, allowing the code inside it to be executed in a continuous loop.
  • digitalWrite(LED_PIN, HIGH);: This command sends a HIGH signal to the LED pin, turning the LED on by applying a voltage.
  • delay(1000);: The program waits for 1000 milliseconds (1 second) before executing the next instruction.
  • digitalWrite(LED_PIN, LOW);: This command sends a LOW signal to the LED pin, turning the LED off by removing the voltage.
  • delay(1000);: Again, the program waits for 1 second before repeating the loop.

MicroPython Code

from machine import Pin
import time

# Define the GPIO pin connected to the LED
LED_PIN = 13  # Use GPIO 13 for onboard LED on most ESP32 boards

# Initialize the LED pin
led = Pin(LED_PIN, Pin.OUT)

# Loop to blink the LED
while True:
    led.on()    # Turn the LED on
    time.sleep(1)  # Wait for 1 second
    led.off()   # Turn the LED off
    time.sleep(1)  # Wait for 1 second

 

Here’s an explanation of the code:

  1. Importing Modules
from machine import Pin
import time
  • from machine import Pin: Imports the Pin class from the machine module, which allows you to control GPIO pins on the ESP32.
  • import time: Imports the time module, which provides functions to work with time, such as delays.
  1. Defining the GPIO Pin
LED_PIN = 13
  • LED_PIN = 13: Defines the GPIO pin number for the LED. GPIO 13 is typically used for the onboard LED on many ESP32 boards.
  1. Initializing the LED Pin
led = Pin(LED_PIN, Pin.OUT)
  1. Main Loop
while True:
    led.on()
    time.sleep(1)
    led.off()
    time.sleep(1)led = Pin(LED_PIN, Pin.OUT): Initializes the LED pin as an output pin by creating a Pin object. The Pin.OUT parameter specifies that the pin will be used for output, allowing it to control the LED.
  • while True:: Starts an infinite loop, which will run continuously until the program is stopped.
  • led.on(): Turns the LED on by sending a HIGH signal to GPIO 13.
  • time.sleep(1): Pauses the program for 1 second.
  • led.off(): Turns the LED off by sending a LOW signal to GPIO 13.
  • time.sleep(1): Pauses the program for 1 second before repeating the loop.

Output

Summary

Understanding and implementing basic LED control with both Arduino and MicroPython on an ESP32 board lays a solid foundation for more advanced projects. Here are key takeaways:

  • Arduino vs. MicroPython: Arduino offers a familiar C/C++-like environment, ideal for beginners and those comfortable with structured programming. MicroPython, on the other hand, provides a Pythonic interface, facilitating rapid prototyping and ease of use.
  • Hardware Setup: Ensure your ESP32 board is correctly connected and powered via USB. Double-check pin configurations to match your board’s layout and specifications.
  • Programming Concepts: Concepts such as pin initialization (pinMode in Arduino, Pin class in MicroPython), digital output (digitalWrite in Arduino, on() and off() methods in MicroPython), and timing (using delay() in Arduino, time.sleep() in MicroPython) are fundamental to controlling peripherals like LEDs.
  • Further Exploration: Experiment with different GPIO pins, modify blinking patterns, or integrate additional sensors and actuators to expand your project’s functionality.

Chapter-1 Introducing the ESP32

Overview

In this chapter, we will introduce you to the ESP32 microcontroller, explore its features, and help you get started with programming it. We will also look at different ESP32 development boards and how to choose the right one for your projects. Finally, we will guide you through setting up and using Thonny IDE with MicroPython to start coding your ESP32.

Overview of the ESP32 Microcontroller

The ESP32 is a versatile and powerful microcontroller developed by Espressif Systems. It is designed for a wide range of applications, offering a combination of high performance and low power consumption. The ESP32 integrates a dual-core processor with Wi-Fi and Bluetooth capabilities, making it suitable for both standalone applications and IoT (Internet of Things) projects.

Key aspects include:

  • Processor: Dual-core Xtensa® 32-bit LX6 microprocessor.
  • Clock Speed: Up to 240 MHz.
  • Memory: Includes SRAM and flash memory.
  • Wireless Communication: Integrated Wi-Fi and Bluetooth (classic and BLE).

Applications and Use Cases

The ESP32’s flexibility makes it ideal for a broad spectrum of applications:

  • IoT Devices: Suitable for smart home devices, remote sensors, and connected appliances.
  • Wearables: Used in fitness trackers, health monitoring devices, and smartwatches.
  • Industrial Automation: Employed in SCADA systems, remote monitoring, and control applications.
  • Consumer Electronics: Found in smart speakers, smart lighting, and interactive toys.
  • Prototyping and Development: Popular among hobbyists and developers for creating prototypes and custom electronics projects.

Key Features and Benefits

  • Dual-Core Processor: Provides significant processing power and efficiency, allowing for multitasking and complex computations.
  • Wi-Fi and Bluetooth Integration: Offers versatile connectivity options for networking and communication.
  • Low Power Consumption: Equipped with various sleep modes to extend battery life in portable and remote applications.
  • Large GPIO Count: Provides a substantial number of general-purpose input/output pins for interfacing with sensors, actuators, and peripherals.
  • Rich Peripheral Set: Includes support for UART, SPI, I2C, PWM, ADC, DAC, and more, facilitating diverse hardware interfacing.
  • Flexible Development Environment: Compatible with popular development frameworks such as Arduino IDE, ESP-IDF, and MicroPython, making it accessible for different skill levels.

The ESP32 stands out as a powerful and adaptable microcontroller, providing developers with a comprehensive set of features for creating innovative and connected devices.

1.1. ESP32 Specifications

Category Specification
Processor Details
Core Dual-core Xtensa® 32-bit LX6 microprocessor
Clock Speed Up to 240 MHz
Performance Up to 600 DMIPS (Dhrystone MIPS) per core
Memory
RAM 520 KB of internal SRAM
Flash Typically 4 MB of external SPI flash (some boards offer 8 MB or 16 MB)
External Memory Support for external PSRAM in some models
Wireless Capabilities
Wi-Fi Integrated 802.11 b/g/n Wi-Fi
Frequency 2.4 GHz band
Modes Station (STA), Access Point (AP), Station + Access Point
Bluetooth
Classic Bluetooth Supports Bluetooth 2.1 + EDR (Enhanced Data Rate)
Bluetooth Low Energy (BLE) Compatible with Bluetooth 4.2 specification
GPIO Pins and Peripherals
General-Purpose Input/Output (GPIO) Pins 34 GPIOs available (not all accessible on every board)
Features Configurable as input, output, or both; supports PWM, touch, ADC, DAC, etc.
Analog-to-Digital Converter (ADC)
Resolution 12-bit
Channels Up to 18 channels (depends on board and configuration)
Digital-to-Analog Converter (DAC)
Resolution 8-bit
Channels 2 channels (DAC1 and DAC2)
Pulse Width Modulation (PWM)
Channels Up to 16 channels for PWM output
Resolution 16-bit resolution
Serial Communication Interfaces
UART Up to 3 UART interfaces
SPI Up to 3 SPI interfaces
I2C Up to 2 I2C interfaces
Timer
Hardware Timers 4 hardware timers
Touch Sensors
Capacitive Touch Up to 10 touch channels available
RTC (Real-Time Clock) Includes low-power RTC and backup battery support for timekeeping

Table comparing the ESP32 and ESP8266 across various aspects:

Feature ESP32 ESP8266
Processor Dual-core Xtensa® 32-bit LX6, up to 240 MHz Single-core Tensilica LX106, up to 80 MHz
Processing Power Higher processing power due to dual-core and faster clock speed Lower processing power due to single-core and slower clock speed
Memory (RAM) 520 KB SRAM 160 KB SRAM
Flash Memory Typically 4 MB, with some variants up to 16 MB Typically 4 MB
Wireless Capabilities Wi-Fi 802.11 b/g/n, Bluetooth 4.2 (Classic & BLE) Wi-Fi 802.11 b/g/n
Bluetooth Yes (Classic & BLE) No
GPIO Pins 34 GPIOs (varies by board) 17 GPIOs
ADC Channels Up to 18 channels, 12-bit resolution 1 ADC channel, 10-bit resolution
DAC Channels 2 DAC channels, 8-bit resolution No DAC channels
PWM Channels Up to 16 channels, 16-bit resolution Up to 16 channels, 8-bit resolution
UART Up to 3 UARTs 1 UART
SPI Up to 3 SPI interfaces 1 SPI interface
I2C Up to 2 I2C interfaces 1 I2C interface
Touch Sensors Up to 10 capacitive touch channels No capacitive touch channels
RTC (Real-Time Clock) Integrated, with backup battery support No built-in RTC
Typical Use Cases Complex IoT applications, wearable devices, smart home automation, advanced projects Basic IoT applications, simpler projects, cost-sensitive applications

This comparison highlights the ESP32’s superior processing power, additional wireless capabilities, and more versatile I/O options compared to the ESP8266. The ESP32 is suitable for more complex applications, while the ESP8266 remains a popular choice for simpler and cost-effective projects.

1.2. ESP32 Development Boards

Overview of Common ESP32 Development Boards

  1. ESP32 DEVKIT V1 
    1. Description: One of the most popular ESP32 development boards, widely used for prototyping and development.
    2. Features:
      1. Onboard USB-to-Serial converter for easy programming.
      2. Integrated Wi-Fi and Bluetooth.
      3. 30 GPIOs, though not all are accessible.
      4. Various built-in peripherals like LEDs, buttons, and connectors.
    3. Differences: Primarily distinguished by its ease of use and compatibility with many development environments.
ESP32 DEVKIT V1 
  • ESP32-WROOM-32
    1. Description: A module rather than a development board, used as a core component in various ESP32 boards.
    2. Features:
      1. Integrated 4 MB Flash.
      2. Dual-core CPU.
      3. Compact and designed for integration into custom PCBs.
    3. Differences: Focuses on being a core module for custom designs, requiring additional components and layout for use.
  • ESP32-WROOM-32U
    1. Description: A variant of the WROOM-32 module with an external antenna connector.
    2. Features:
      1. Improved range and signal strength due to external antenna.
      2. Similar to ESP32-WROOM-32 in processing power and memory.
    3. Differences: Designed for applications requiring better wireless performance.
  • ESP32-WROOM-32D
    1. Description: Another variant of the ESP32 module with different packaging.
    2. Features:
      1. Enhanced performance and reliability.
      2. Slightly different pinout and mechanical design compared to WROOM-32.
    3. Differences: Mostly internal improvements and packaging differences.
  • ESP32-PICO-KIT
    1. Description: A compact development board featuring the ESP32-PICO-D4 module.
    2. Features:
      1. Integrated crystal oscillator and flash memory.
      2. Smaller form factor compared to DEVKIT V1.
      3. Ideal for compact or portable projects.
    3. Differences: Designed for smaller, more space-constrained applications.
  • ESP32-DevKitC
    1. Description: A compact, versatile development board similar to DEVKIT V1.
    2. Features:
      1. Onboard USB-to-Serial converter.
      2. Standard GPIO pinout and additional peripherals.
      3. Often includes a variety of connectivity options.
    3. Differences: Variations in USB connector type and layout compared to DEVKIT V1.
  • ESP32-CAM
    1. Description: A development board specifically designed for camera applications.
    2. Features:
      1. Integrated OV2640 camera module.
      2. Onboard microSD card slot.
      3. Compact size.
    3. Differences: Optimised for image processing and camera-related applications.

Note: Image Source By Google

1.3 Features and Differences Between Boards

  • Processor and Memory: All ESP32 boards feature the same dual-core processor and general memory capabilities, but variations in Flash size and additional features can be found across different boards.
  • Connectivity: Most boards include built-in Wi-Fi and Bluetooth, but some variants, like the ESP32-WROOM-32U, offer improved wireless performance with an external antenna.
  • Size and Form Factor: Boards vary in size, from compact modules like the ESP32-PICO-KIT to larger, more feature-rich boards like the ESP32-DevKitC and ESP32-WROOM-32.
  • Additional Features: Specific boards offer unique features like integrated cameras (ESP32-CAM), audio processing (ESP32-LyraT), or enhanced GPIO accessibility.
  • Application Focus: Boards are designed for different application needs, including general-purpose development (ESP32-DevKit V1), compact applications (ESP32-PICO-KIT), and specialized tasks (ESP32-CAM, ESP32-LyraT).

Choosing the right development board depends on your project’s specific requirements, such as size constraints, additional peripherals, and application focus.

1.4. How to Choose an ESP32 Development Board?

When selecting an ESP32 development board, consider the following factors to ensure it meets your project’s requirements:

Factors to Consider

  1. Number of GPIOs
    • Requirement: Determine how many General-Purpose Input/Output (GPIO) pins you need for sensors, actuators, or other peripherals.
    • Recommendation: Choose a board with sufficient GPIOs, considering that not all pins are always available or easily accessible.
  2. Wi-Fi and Bluetooth Requirements
    • Wi-Fi: All ESP32 boards support Wi-Fi, but performance may vary based on the antenna and design.
    • Bluetooth: If you need Bluetooth functionality, ensure the board supports both Bluetooth Classic and BLE (Bluetooth Low Energy).
    • Recommendation: For applications requiring robust wireless connectivity, consider boards with external antenna options or modules like the ESP32-WROOM-32U.
  3. Form Factor
    • Size: The physical size of the board can impact how it fits into your project, especially if space is constrained.
    • Recommendation: For compact or embedded applications, consider smaller boards like the ESP32-PICO-KIT. For prototyping, larger boards like the ESP32-DevKit V1 offer more space for connections.
  4. Additional Features
    • Integrated Peripherals: Features such as ADCs, DACs, PWM channels, or specialized modules (e.g., cameras or audio codecs) can be crucial depending on your project.
    • Recommendation: If your project requires specific peripherals, choose a board that includes these features, like the ESP32-CAM for camera applications or ESP32-LyraT for audio processing.
  5. Development Environment and Support
    • Software Compatibility: Ensure the board is compatible with your preferred development environment (e.g., Arduino IDE, ESP-IDF, MicroPython).
    • Community and Documentation: Boards with strong community support and comprehensive documentation can ease the development process.
    • Recommendation: Popular boards like the ESP32-DevKit V1 have extensive community support and resources.
  6. Power Supply and Consumption
    • Power Requirements: Consider the power supply requirements and consumption of the board, especially for battery-operated or low-power applications.
    • Recommendation: Look for boards with power management features or low-power modes if battery life is a concern.
  7. Cost
    • Budget: Cost can vary based on the features and form factor of the board.
    • Recommendation: Balance your budget with the required features. Basic boards like the ESP32-DevKit V1 are cost-effective for general-purpose projects, while specialized boards may be more expensive.

My Recommendations Based on Project Needs

  1. General Prototyping:
    • Recommended Board: ESP32-DevKit V1
    • Reason: Provides a good balance of features, GPIOs, and community support. Suitable for most development and prototyping needs.
  2. Compact Projects:
    • Recommended Board: ESP32-PICO-KIT
    • Reason: Smaller size makes it ideal for projects with space constraints while retaining key features.
  3. Wireless Performance:
    • Recommended Board: ESP32-WROOM-32U
    • Reason: Includes an external antenna for better wireless performance, suitable for applications requiring strong connectivity.
  4. Camera Applications:
    • Recommended Board: ESP32-CAM
    • Reason: Integrated camera module and microSD card slot make it perfect for image processing and related projects.
  5. Audio Processing:
    • Recommended Board: ESP32-LyraT
    • Reason: Includes audio codec and microphone, designed specifically for audio and voice applications.

By evaluating these factors and matching them with your project requirements, you can select the most suitable ESP32 development board for your needs.

1.5. What is the Best ESP32 Development Board for Beginners?

For beginners, the ideal ESP32 development board should be easy to use, well-supported, and versatile enough to handle a range of introductory projects. Here are some features that make a board beginner-friendly and popular choices:

Features that Make a Board Beginner-Friendly

  1. Ease of Setup
    • Onboard USB-to-Serial Converter: Simplifies the connection between the board and your computer, making it easier to upload code without needing additional hardware.
    • Pre-flashed Bootloader: Reduces the setup complexity by allowing direct programming and debugging.
  2. Availability of Documentation and Tutorials
    • Extensive Resources: Boards with a large community and plenty of documentation, tutorials, and example projects make learning easier.
  3. User-Friendly Development Environment
    • Compatibility with Popular IDEs: Boards that work seamlessly with Arduino IDE or other widely-used development environments offer a smoother learning curve.
  4. Accessible GPIOs and Peripherals
    • Clear Pinout: Easy-to-read pinout diagrams and accessible GPIO pins help beginners experiment with various inputs and outputs without confusion.
  5. Support for Basic Peripherals
    • Integrated Components: Built-in LEDs, buttons, or screens can help beginners quickly see results from their code and learn more interactively.
  6. Community Support
    • Active Forums and Groups: Boards with active support communities provide help and advice, which can be invaluable for troubleshooting and learning.

1.6. ESP32 DEVKIT DOIT

The ESP32 DEVKIT DOIT is a widely used development board for the ESP32 microcontroller. It’s designed to provide an accessible platform for prototyping and developing with the ESP32, offering a range of features suited for various applications.

Key Features:

  • Processor: Dual-core Xtensa® 32-bit LX6 microprocessor, up to 240 MHz.
  • Memory: Typically 4 MB of Flash and 520 KB of SRAM.
  • Connectivity: Integrated Wi-Fi (802.11 b/g/n) and Bluetooth (Classic and BLE).
  • USB-to-Serial Converter: Built-in USB-to-Serial bridge (often based on the CP2104 or CH340G) for easy programming and debugging.
  • Power Supply: Powered via USB (5V) or external power source (e.g., 3.3V or 5V).

Pinout and Features

Pinout:

  • GPIO Pins: 30 GPIOs (some shared with other functions).
    • Digital I/O: All GPIOs can be used for digital input/output.
    • Analog I/O: Several GPIOs support ADC (Analog-to-Digital Converter) input.
    • PWM: Supports Pulse Width Modulation on multiple GPIOs.
    • DAC: Includes two DAC channels for analog output.
  • UART: Up to 3 UART interfaces, typically UART0 and UART1 are available.
  • SPI: Up to 3 SPI interfaces.
  • I2C: Up to 2 I2C interfaces.
  • Touch: Some GPIOs support capacitive touch input.
  • LED: Often includes a built-in LED for simple status indications.
  • Button: Typically includes a user-programmable button for resets or custom functions.
  • External Connections: Includes headers for connecting external peripherals, sensors, and actuators.

Typical Use Cases

  1. General Prototyping
    • Description: Ideal for building and testing various electronic projects due to its versatile GPIOs and built-in features.
    • Examples: Developing IoT devices, sensors, or automation systems.
  2. Educational Projects
    • Description: Suitable for learning and experimenting with microcontroller programming, wireless communication, and sensor interfacing.
    • Examples: Educational kits, student projects, and experiments.
  3. Smart Home Applications
    • Description: Can be used to create smart home devices such as sensors, controllers, and actuators.
    • Examples: Home automation systems, smart lighting, and environmental monitoring.
  4. Prototype Development
    • Description: Used for prototyping custom electronic devices and systems before creating a final product.
    • Examples: Prototyping new products, developing custom hardware solutions, and integrating with other components.
  5. Wireless Communication Projects
    • Description: Leverages the ESP32’s integrated Wi-Fi and Bluetooth capabilities for creating connected devices and communication systems.
    • Examples: Bluetooth beacons, Wi-Fi-enabled gadgets, and remote control systems.

The ESP32 DEVKIT DOIT is a versatile and accessible development board, making it an excellent choice for both beginners and experienced developers working on a wide range of projects.

1.7. ESP32 GPIOs Pinout Guide

ESP32 GPIOs Pinout Guide

Note: Image source By google

 Table summarising the pins and their functions for the ESP32:

Pin Category Pins Description
Power & Ground V5, V3.3, GND – V5 (5V): 5V power supply – V3.3 (3.3V): 3.3V power supply – GND: Ground
Digital I/O GPIO0 – GPIO19, GPIO21 – GPIO23, GPIO25 – GPIO27, GPIO32 – GPIO39 General-purpose digital input/output pins
Analog Pins ADC1: GPIO34, GPIO35, GPIO36, GPIO39 ADC2: GPIO0, GPIO2, GPIO4, GPIO12, GPIO13, GPIO14, GPIO15, GPIO25, GPIO26, GPIO27 Analog-to-digital conversion channels
PWM Multiple GPIOs Pulse Width Modulation output on various pins
DAC GPIO25, GPIO26 Digital-to-Analog Conversion
I2C GPIO21 (SDA), GPIO22 (SCL) I2C communication – SDA: Data line – SCL: Clock line
SPI Multiple GPIOs Serial Peripheral Interface communication, including MOSI, MISO, and SCK
UART GPIO1 (TX), GPIO3 (RX) (UART0) GPIO16 (TX), GPIO17 (RX) (UART1) Universal Asynchronous Receiver/Transmitter – TX: Transmit – RX: Receive

Note: For an actual pinout diagram, you should refer to the datasheet or documentation specific to your ESP32 development board, as pin labels and functions can vary slightly between different boards.

Official Website

1.8 Functions of Each Pin

Category Pin Description
Power Pins
V5 V5 Provides 5V power, usually used to power the board.
V3.3 V3.3 Provides 3.3V power for the ESP32 and connected peripherals.
GND GND Ground pin.
Digital I/O Pins GPIO0 – GPIO39 Can be used for digital input or output. Some GPIOs have specific functions or limitations (e.g., GPIO34 to GPIO39 are input-only).
Analog Pins
ADC1 Channels ADC1 Can read analog voltages and convert them to digital values. Useful for sensors and other analog inputs.
ADC2 Channels ADC2 Similar to ADC1 but may be affected by Wi-Fi usage.
PWM Output Multiple GPIOs Can be configured to output PWM signals for motor control, LED dimming, and other applications.
DAC (Digital-to-Analog Conversion) GPIO25, GPIO26 Can output analog voltages, useful for generating audio signals or other analog outputs.
I2C
GPIO21 (SDA) GPIO21 Data line for I2C communication.
GPIO22 (SCL) GPIO22 Clock line for I2C communication.
SPI
MOSI MOSI Master Out Slave In line for SPI communication.
MISO MISO Master In Slave Out line for SPI communication.
SCK SCK Serial Clock line for SPI communication.
UART
GPIO1 (TX) GPIO1 Transmit line for UART0.
GPIO3 (RX) GPIO3 Receive line for UART0.
GPIO16, GPIO17 GPIO16, GPIO17 Used for UART1.

Tips for Using GPIOs Effectively

  1. Avoid Using Reserved Pins
    • Some GPIOs are used for bootstrapping or have special functions. Refer to the datasheet to avoid conflicts (e.g., GPIO0, GPIO2).
  2. Consider Voltage Levels
    • Ensure that input signals are within the acceptable voltage range for GPIOs (0-3.3V). Use level shifters if interfacing with 5V logic.
  3. Configure Pin Modes Properly
    • Configure GPIOs as input or output according to your application needs. Incorrect configuration can lead to unexpected behavior or damage.
  4. Use Internal Pull-ups/Pull-downs
    • For input pins, you can use internal pull-up or pull-down resistors to stabilize the signal and avoid floating inputs.
  5. Be Mindful of ADC2 Usage
    • ADC2 channels can be affected by Wi-Fi usage, which may impact readings. Use ADC1 for more stable analog readings if Wi-Fi is active.
  6. Check Maximum Current Ratings
    • Ensure that GPIOs do not exceed their maximum current ratings (typically around 12 mA per pin). Use external drivers if higher currents are required.
  7. Utilize External Interrupts Carefully
    • Some GPIOs can be used for external interrupts. Ensure correct configuration and debouncing to handle interrupts efficiently.
  8. Refer to Board-Specific Documentation
    • Pinout and functionality can vary between different ESP32 boards. Always check the specific documentation for your development board.

1.9. How to Program the ESP32?

 Table summarising the most common methods and tools for programming the ESP32, along with their overviews and advantages:

Programming Method Overview Advantages
Arduino IDE The Arduino IDE supports the ESP32 through an additional board package. – User-friendly interface- Extensive library support- Strong community resources
ESP-IDF ESP-IDF (Espressif IoT Development Framework) is the official development framework for the ESP32. – Full control over ESP32 hardware and features- Suitable for advanced and production-level projects
MicroPython MicroPython is a lightweight version of Python designed for microcontrollers, including the ESP32. – Easy-to-learn Python programming- Rapid development and testing of scripts
PlatformIO PlatformIO is an open-source ecosystem for IoT development that supports ESP32 among other platforms. – Integration with popular IDEs like VS Code – Support for multiple platforms and libraries
Lua (NodeMCU) NodeMCU is a firmware based on the Lua script interpreter, designed for easy development on ESP8266 and ESP32. – Scripting language with a simple learning curve – Easy to use for basic IoT applications

This table provides a clear overview of each programming method, highlighting their main features and benefits. You can choose the method that best suits your project’s requirements and your programming preferences.

1.10. ESP32 with Arduino IDE

Programming the ESP32 using the Arduino IDE is straightforward and widely supported. Below is a step-by-step guide for setting up and using the Arduino IDE with the ESP32.

Step Action Details Image Suggestion
1. Install Arduino IDE Download & Install Visit the Arduino website and follow OS-specific instructions.
2. Add ESP32 Board URL Navigate to Preferences: Go to File > Preferences Open Arduino IDE. In the “Additional Boards Manager URLs” field, add 

https://dl.espressif.com/dl/package_esp32_index.json.

3. Install ESP32 Board Package Tools > Board > Boards Manager Search “ESP32” in the search bar. Find the esp32 entry by Espressif Systems and click “Install.” Wait for the installation to complete.
4. Select Your ESP32 Board Tools > Board Select your specific ESP32 board from the list (e.g., “ESP32 Dev Module”).
5. Select Port Tools > Port Connect your ESP32 to the computer via USB and select the appropriate COM port.
6. Set Up Board Options Tools > Board & other settings Configure additional settings as needed: Flash Frequency: 80 MHz or 160 MHz. Flash Mode: QIO/DIO. Partition Scheme: Default.
7. Configure Upload Speed Tools > Upload Speed Select a suitable upload speed (e.g., 115200 bps).
8. Select Programmer Tools > Programmer Ensure “esptool” is selected. This is typically the default setting.
9. Load a Basic Example File > Examples > Basics > Blink Open the Blink example. Save as a new project and modify the code if necessary (e.g., change the LED pin).
10. Upload Code Click Upload button Click the right arrow icon to compile and upload the code to the ESP32.
11. Monitor Serial Output Tools > Serial Monitor Open Serial Monitor. Set the baud rate to match your code (e.g., 115200 bps) and view the output.

Troubleshooting Tips

  • Board Not Recognized: Ensure drivers for the USB-to-Serial converter are installed. For Windows, you might need drivers for chips like CP2104 or CH340G.
  • Upload Issues: Ensure that the correct port is selected and that the ESP32 is properly connected. Check for any loose connections.
  • Compilation Errors: Ensure you have installed all necessary libraries and that the code is compatible with the ESP32.

Thonny MicroPython (Python) IDE for ESP32 and ESP8266

1.11 What is MicroPython?

Overview of MicroPython and Its Benefits

MicroPython is a lean and efficient implementation of the Python 3 programming language designed specifically for microcontrollers and embedded systems. It provides a subset of Python’s features, optimised to run on constrained hardware with limited resources.

Benefits of MicroPython:

  • Ease of Use: Python is known for its clear and readable syntax, which simplifies programming for beginners and professionals alike.
  • Interactive Development: Supports a REPL (Read-Eval-Print Loop) for interactive coding, which is excellent for rapid prototyping and debugging.
  • Rich Libraries: Provides a subset of Python’s standard libraries and additional modules tailored for hardware interaction.
  • Community and Documentation: Extensive documentation and a growing community help support development and troubleshooting.
  • Cross-Platform: Runs on various microcontrollers, including the ESP32, ESP8266, STM32, and others, making it versatile for different hardware platforms.

1.12 Table outlining the Comparison table for the Arduino and MicroPython code: between MicroPython and Arduino:

Aspect MicroPython Arduino
Programming Language Python 3 (MicroPython variant) C/C++ (Arduino language is a simplified version of C/C++)
Ease of Learning Easier for beginners due to Python’s simple syntax Steeper learning curve due to C/C++ complexities
Development Environment Thonny, uPyCraft, or other Python IDEs Arduino IDE or other C/C++ IDEs
Real-Time Interaction REPL (Read-Eval-Print Loop) for interactive coding No built-in REPL; relies on serial monitor for interaction
Code Uploading Scripts uploaded via USB using IDE or firmware tools Code compiled and uploaded via Arduino IDE
Libraries and Modules Extensive standard libraries and third-party modules available Limited to libraries provided by Arduino or third-party sources
File System Supports file systems (e.g., FAT) for storing scripts and data No built-in file system; data typically stored in EEPROM or external memory
Performance Generally slower due to interpreted nature Faster execution as it compiles to native machine code
Memory Management Automatic garbage collection Manual memory management (e.g., dynamic memory allocation)
Power Consumption Typically higher due to Python interpreter Often lower, depending on the board and code complexity
Hardware Abstraction More abstracted, allowing for easier scripting of hardware Lower-level access to hardware with direct register manipulation
Community and Support Growing community with Python-centric resources Large, established community with extensive resources
Use Cases Ideal for rapid prototyping and scripting Suited for low-level hardware control and real-time applications

This table highlights the main differences between MicroPython and Arduino, focusing on their programming languages, development environments, and typical use cases.

1.13 Applications and Use Cases for MicroPython on Microcontrollers

MicroPython is well-suited for a variety of applications in the world of embedded systems and microcontrollers:

Category Description Examples
IoT Devices Use MicroPython to develop Internet of Things (IoT) devices that communicate over networks and the internet. – Smart home devices   – Weather stations   – Remote sensors
Educational Projects MicroPython is an excellent tool for teaching and learning programming and electronics due to its simplicity and interactive nature. – Educational kits   – Student projects   – Classroom experiments
Prototyping and Development Rapidly develop and test prototypes for hardware projects, utilizing MicroPython’s interactive features and hardware modules. – Prototyping new hardware designs   – Testing sensor integrations   – Developing custom controllers
Automation and Control Automate tasks and control systems using MicroPython to interact with sensors, actuators, and other peripherals. – Home automation systems   – Industrial automation   – Robotic controls
Embedded Systems Develop embedded systems where Python’s ease of use can significantly speed up development compared to traditional embedded programming languages. – Custom embedded solutions   – Data loggers   – Simple devices
Data Collection and Analysis Collect data from sensors and perform basic processing and analysis using MicroPython’s capabilities. – Environmental monitoring   – Health tracking devices   – Data acquisition systems

1.14 Installing Thonny IDE

Thonny IDE is a user-friendly Python IDE that is well-suited for beginners, including those working with MicroPython on microcontrollers. It provides a simple interface and integrated tools for coding, debugging, and running Python scripts.

Downloading Thonny IDE from the Official Website

  1. Visit the Thonny Website:
  2. Select the Appropriate Version:
    • Choose the version of Thonny IDE that matches your operating system (Windows, macOS, or Linux).

Installation Steps for Different Operating Systems

  1. Windows:
    • Download: Click on the Windows installer link (e.g., thonny-<version>-win32.exe or thonny-<version>-win64.exe depending on your system).
    • Run the Installer: Double-click the downloaded .exe file to start the installation.
    • Follow the Wizard: Proceed through the installation wizard. The default options are generally fine for most users.
    • Finish: Once installation is complete, you can launch Thonny from the Start menu or desktop shortcut.
  2. macOS:
    • Download: Click on the macOS installer link (e.g., thonny-<version>-macos.dmg).
    • Open the Disk Image: Double-click the .dmg file to open it.
    • Drag to Applications: Drag the Thonny icon to the Applications folder.
    • Launch Thonny: Open the Applications folder and double-click Thonny to start the IDE.
  3. Linux:
    • Download: Download the Linux package for your distribution (e.g., .deb for Debian-based systems like Ubuntu, or .rpm for Red Hat-based systems).
    • Install Using Package Manager:

For .deb files: Use the terminal command:

sudo dpkg -i thonny-<version>-amd64.deb

sudo apt-get install -f  # To fix any dependency issues

For .rpm files: Use the terminal command:

sudo rpm -i thonny-<version>-x86_64.rpm

Alternatively, you can install Thonny via Python’s package manager:
pip install thonny

  • Launch Thonny: You can usually find Thonny in your applications menu or by typing thonny in the terminal.

Setting Up Thonny IDE for MicroPython

Step Action Details Image 
1. Open Thonny Launch Thonny IDE Open Thonny from your OS’s application menu or shortcut.
2. Configure Python Interpreter Select Python Version: Go to Tools > Options (or Thonny > Preferences on macOS).  Interpreter Tab: Ensure the correct Python interpreter is selected. If using MicroPython, select the MicroPython interpreter.
3. Set Up MicroPython (if needed) Install MicroPython: Ensure MicroPython is installed on your device.  Select MicroPython: Go to Tools > Options, choose MicroPython (ESP32) or another relevant option.  Configure Port: Select the correct port for your device. Thonny should detect available ports automatically.
4. Configure Editor Settings Editor Preferences: Configure settings like font size, line numbers, and indentation.  Theme: Choose a light or dark theme. Go to Tools > Options and adjust the settings according to your preference.
5. Install Additional Packages (if needed) Use Thonny’s package manager to install additional Python packages or MicroPython modules. Search for and install packages directly within the IDE.
6. Test the Setup Run a Simple Script: Create and run a script with a simple print statement: print(“Hello, Thonny!”) Click the Run button to execute the script and ensure the setup is correct.

By following these steps, you’ll have Thonny IDE installed and configured, ready for Python or MicroPython development.

Flashing MicroPython Software

Step Action Details
1. Introduction Flash MicroPython Firmware Write MicroPython firmware to the device’s flash memory.
2. Prerequisites Drivers: – CP210x – CH340 – FTDI  Tools: – esptool  Firmware: – MicroPython firmware Drivers: Install necessary drivers for USB-to-Serial communication. Tools: Install esptool using pip install esptool. Firmware: Download the appropriate firmware from the MicroPython website.
3. Preparation Boot Mode Some devices may need to enter a specific mode during flashing (e.g., bootloader mode).
4. Install esptool Install esptool Use the command: pip install esptool.
5. Erase Flash Memory Erase existing firmware Command: esptool.py –chip esp32 erase_flash.
6. Flash Firmware Flash MicroPython firmware Command: esptool.py –chip esp32 write_flash -z 0x1000 esp32-xxxx.bin. Replace esp32-xxxx.bin with the path to your firmware file.
7. Verify Installation Reset Device Reset the ESP32 (press “EN” button).
8. Test MicroPython Connect and Test Use a terminal program or Thonny IDE to access the MicroPython REPL. Test with print(“Hello, MicroPython!”).

Details and Notes

  • Drivers: Ensure you have the correct drivers installed for your specific USB-to-Serial chip.
  • Tools: esptool is a common tool for flashing ESP32 and ESP8266 devices.
  • Firmware: Download the firmware that matches your hardware. Double-check the version compatibility.
  • Boot Mode: Some microcontrollers require entering a special mode to accept new firmware. Refer to your device’s documentation for instructions.
  • Test MicroPython: Once flashed, you can interact with your device using Python scripts in the MicroPython environment.

1.15 Thonny IDE Overview

Thonny IDE is a user-friendly Integrated Development Environment (IDE) designed specifically for Python programming, including MicroPython development. It offers a clean interface and essential features that simplify coding and debugging, especially for beginners.

Overview of the Thonny IDE Interface

  1. Editor Area:
    • This is where you write and edit your Python scripts. The editor provides syntax highlighting, code completion, and indentation features to help with coding.
  2. Shell/REPL Area:
    • Located at the bottom of the IDE, this is where you interact directly with the MicroPython interpreter. You can enter and execute Python commands interactively.
  3. File Explorer:
    • Shows the directory structure of your project or file system. You can open, create, and manage files directly from this pane.
  4. Toolbar:
    • Provides quick access to common functions such as running scripts, stopping execution, and saving files.
  5. Status Bar:
    • Displays information about the current file and interpreter, such as the file path and interpreter version.
  6. Debugger:
    • Allows you to set breakpoints, step through code, and inspect variables for debugging purposes. Useful for understanding code flow and troubleshooting issues.

Key Features and Tools Available

  1. Integrated Python Shell:
    • Run Python commands interactively, test snippets of code, and see immediate results.
  2. Code Editor:
    • Features syntax highlighting, automatic indentation, and code completion. Supports multiple file types and provides error highlighting.
  3. MicroPython Support:
    • Configurable for MicroPython development. Thonny can communicate with microcontrollers running MicroPython and supports uploading scripts directly to the device.
  4. Debugging Tools:
    • Includes step-by-step execution, breakpoints, and variable inspection. Helps in troubleshooting and understanding code behavior.
  5. File Management:
    • Easily manage project files and directories. Supports file operations like open, save, delete, and create new files.
  6. Installation and Environment Management:
    • Allows for easy installation of packages and management of Python environments. Useful for managing dependencies and libraries.

1.16 Running Your First Script

Running your first MicroPython script is a great way to verify that your development environment is set up correctly and to start getting familiar with MicroPython. Here’s how you can write and run a simple “Hello, World!” script using Thonny IDE.

Writing a Simple “Hello, World!” Script in MicroPython

  1. Open Thonny IDE:
    • Launch Thonny IDE on your computer.
  2. Create a New Script:
    • Go to File > New to open a new script editor window.
  3. Write the Script:

In the new editor window, type the following code:

print(“Hello, World!”)

  • This script uses the print function to output the message “Hello, World!” to the MicroPython REPL (Read-Eval-Print Loop).
  1. Save the Script:
    • Save the script by going to File > Save.
    • Choose a filename (e.g., hello_world.py) and select a location on your computer to save the file.

1.17 Uploading the Script

Uploading and saving scripts to your ESP32 or ESP8266 using Thonny IDE is a straightforward process. Here’s a step-by-step guide on how to do it, along with tips for managing and organizing your scripts.

Steps to Upload and Save Scripts to the ESP32/ESP8266 Using Thonny

  1. Connect Your Microcontroller:
    • Ensure that your ESP32 or ESP8266 is connected to your computer via USB.
    • Make sure Thonny IDE is configured to use the correct MicroPython interpreter and serial port.
  2. Open Thonny IDE:
    • Launch Thonny IDE on your computer.
  3. Write or Open Your Script:
    • You can either write a new script or open an existing one:
      • To write a new script, go to File > New and enter your code.
      • To open an existing script, go to File > Open and select the script file.
  4. Save the Script to the Microcontroller:
    • Save As a File on the Microcontroller:
      • With your script open in the editor, go to File > Save or use the Save button (disk icon).
      • In the save dialog, select the MicroPython device (usually listed as /pyboard or similar) from the dropdown menu.
      • Choose a filename (e.g., main.py) and click Save.
      • Saving as main.py makes the script automatically run when the device boots up.
    • Save the Script Directly:
      • You can also use File > Save as… and select the MicroPython device from the file location list.
      • This will upload the script to the root directory of the device’s file system.
  5. Verify Script Upload:

Once the upload is complete, you can check if the script is saved on your device by using the REPL: