SunFounder ESP32 Starter Kit

Thanks for choosing our ESP32 Starter Kit.

Note

This document is available in the following languages.

Please click on the respective links to access the document in your preferred language.

_images/esp32_ultimate_kit.png

Welcome to the ESP32 Learning Kit! This comprehensive package is designed to offer both beginners and seasoned developers a deep dive into the versatile world of the ESP32 microcontroller. With the ESP32 WROOM 32E at its core, and a range of accompanying components like LEDs, sensors, motors, and more, users can explore a vast array of projects.

Whether you’re keen on basic electronics, IoT integrations, this kit has it all. For MicroPython enthusiasts, we provide a structured introduction to MicroPython, complete with IDE setups and basic syntax lessons. Arduino users are not left behind, with a dedicated section on getting started with Arduino, and a suite of basic projects to jumpstart the learning process.

For the creatives, there’s a delightful section on integrating with Scratch, allowing for a blend of programming and storytelling. Each project in the kit is meticulously outlined, ensuring you understand the objectives, the circuit assembly, and the programming aspects.

With a myriad of game projects, practical applications, and troubleshooting FAQs, this kit promises an enriching learning experience for all. Dive in and let the ESP32 adventure begin!

If you have any questions or other interesting ideas, feel free to send an email to service@sunfounder.com.

Download the Code

Here is the complete code package for the ESP32 Starter Kit. You can click on the following link to download it:

Once the download is complete, unzip the file and open the relevant example code or project files in the corresponding software. This will allow you to browse and utilize all the code and resources provided by the kit.

For Arduino User

Here is the complete code package for the ESP32 Starter Kit. You can click on the following link to download it:

Once the download is complete, unzip the file and open the relevant example code or project files in the corresponding software. This will allow you to browse and utilize all the code and resources provided by the kit.

1. Get Started

1.1 Install Arduino IDE(Important)

The Arduino IDE, known as Arduino Integrated Development Environment, provides all the software support needed to complete an Arduino project. It is a programming software specifically designed for Arduino, provided by the Arduino team, that allows us to write programs and upload them to the Arduino board.

The Arduino IDE 2.0 is an open-source project. It is a big step from its sturdy predecessor, Arduino IDE 1.x, and comes with revamped UI, improved board & library manager, debugger, autocomplete feature and much more.

In this tutorial, we will show how to download and install the Arduino IDE 2.0 on your Windows, Mac, or Linux computer.

Requirements

  • Windows - Win 10 and newer, 64 bits

  • Linux - 64 bits

  • Mac OS X - Version 10.14: “Mojave” or newer, 64 bits

Download the Arduino IDE 2.0

  1. Vist Arduino IDE 2.0.0 Page.

  2. Download the IDE for your OS version.

    _images/sp_001.png

Installation

Windows
  1. Double click the arduino-ide_xxxx.exe file to run the downloaded file.

  2. Read the License Agreement and agree it.

    _images/sp_002.png
  3. Choose installation options.

    _images/sp_003.png
  4. Choose install location. It is recommended that the software be installed on a drive other than the system drive.

    _images/sp_004.png
  5. Then Finish.

    _images/sp_005.png
macOS

Double click on the downloaded arduino_ide_xxxx.dmg file and follow the instructions to copy the Arduino IDE.app to the Applications folder, you will see the Arduino IDE installed successfully after a few seconds.

_images/macos_install_ide.png
Linux

For the tutorial on installing the Arduino IDE 2.0 on a Linux system, please refer to: https://docs.arduino.cc/software/ide-v2/tutorials/getting-started/ide-v2-downloading-and-installing#linux

Open the IDE

  1. When you first open Arduino IDE 2.0, it automatically installs the Arduino AVR Boards, built-in libraries, and other required files.

    _images/sp_901.png
  2. In addition, your firewall or security center may pop up a few times asking you if you want to install some device driver. Please install all of them.

    _images/sp_104.png
  3. Now your Arduino IDE is ready!

    Note

    In the event that some installations didn’t work due to network issues or other reasons, you can reopen the Arduino IDE and it will finish the rest of the installation. The Output window will not automatically open after all installations are complete unless you click Verify or Upload.

1.2 Introduce of Arduino IDE

_images/sp_ide_2.png
  1. Verify: Compile your code. Any syntax problem will be prompted with errors.

  2. Upload: Upload the code to your board. When you click the button, the RX and TX LEDs on the board will flicker fast and won’t stop until the upload is done.

  3. Debug: For line-by-line error checking.

  4. Select Board: Quick setup board and port.

  5. Serial Plotter: Check the change of reading value.

  6. Serial Monitor: Click the button and a window will appear. It receives the data sent from your control board. It is very useful for debugging.

  7. File: Click the menu and a drop-down list will appear, including file creating, opening, saving, closing, some parameter configuring, etc.

  8. Edit: Click the menu. On the drop-down list, there are some editing operations like Cut, Copy, Paste, Find, and so on, with their corresponding shortcuts.

  9. Sketch: Includes operations like Verify, Upload, Add files, etc. More important function is Include Library - where you can add libraries.

  10. Tool: Includes some tools - the most frequently used Board (the board you use) and Port (the port your board is at). Every time you want to upload the code, you need to select or check them.

  11. Help: If you’re a beginner, you may check the options under the menu and get the help you need, including operations in IDE, introduction information, troubleshooting, code explanation, etc.

  12. Output Bar: Switch the output tab here.

  13. Output Window: Print information.

  14. Board and Port: Here you can preview the board and port selected for code upload. You can select them again by Tools -> Board / Port if any is incorrect.

  15. The editing area of the IDE. You can write code here.

  16. Sketchbook: For managing sketch files.

  17. Board Manager: For managing board driver.

  18. Library Manager: For managing your library files.

  19. Debug: Help debugging code.

  20. Search: Search the codes from your sketches.

1.3 Install the ESP32 Board(Important)

To program the ESP32 microcontroller, we need to install the ESP32 board package in the Arduino IDE. Follow the step-by-step guide below:

Install the ESP32 Board

  1. Open the Arduino IDE. Go to File and select Preferences from the drop-down menu.

    _images/install_esp321.png
  2. In the Preferences window, locate the Additional Board Manager URLs field. Click on it to activate the text box.

    _images/install_esp322.png
  3. Add the following URL to the Additional Board Manager URLs field: https://espressif.github.io/arduino-esp32/package_esp32_index.json. This URL points to the package index file for the ESP32 boards. Click the OK button to save the changes.

    _images/install_esp323.png
  4. In the Boards Manager window, type ESP32 in the search bar. Click the Install button to start the installation process. This will download and install the ESP32 board package.

    _images/install_esp324.png
  5. Congratulations! You have successfully installed the ESP32 board package in the Arduino IDE.

Upload the Code

  1. Now, connect the ESP32 WROOM 32E to your computer using a Micro USB cable.

    _images/plugin_esp32.png
  2. Then select the correct board, ESP32 Dev Module, by clicking on Tools -> Board -> esp32.

    _images/install_esp325.png
  3. If your ESP32 is connected to the computer, you can choose the correct port by clicking on Tools -> Port.

    _images/install_esp326.png
  4. Additionally, Arduino 2.0 introduced a new way to quickly select the board and port. For ESP32, it is usually not automatically recognized, so you need to click on Select other board and port.

    _images/install_esp327.png
  5. In the search box, type ESP32 Dev Module and select it when it appears. Then, choose the correct port and click OK.

    _images/install_esp328.png
  6. Afterward, you can select it through this quick access window. Note that during subsequent use, there may be times when ESP32 is not available in the quick access window, and you will need to repeat the above two steps.

    _images/install_esp329.png
  7. Both methods allow you to select the correct board and port, so choose the one that suits you best. Now, everything is ready to upload the code to the ESP32.

1.4 Install libraries (Important)

A library is a collection of pre-written code or functions that extend the capabilities of the Arduino IDE. Libraries provide ready-to-use code for various functionalities, allowing you to save time and effort in coding complex features.

There are two main ways to install libraries:

Install from Library Manager

Many libraries are available directly through the Arduino Library Manager. You can access the Library Manager by following these steps:

  1. In the Library Manager, you can search for the desired library by name or browse through different categories.

    Note

    In projects where library installation is required, there will be prompts indicating which libraries to install. Follow the instructions provided, such as “The DHT sensor library library is used here, you can install it from the Library Manager.” Simply install the recommended libraries as prompted.

    _images/install_lib3.png
  2. Once you find the library you want to install, click on it and then click the Install button.

    _images/install_lib2.png
  3. The Arduino IDE will automatically download and install the library for you.

Manual Installation

Some libraries are not available through the Library Manager and need to be manually installed. To install these libraries, follow these steps:

  1. Open the Arduino IDE and go to Sketch -> Include Library -> Add .ZIP Library.

    _images/a2dp_add_zip.png
  2. Navigate to the directory where the library files are located, such as the esp32-starter-kit\c\libraries folder, and select the desired library file, like ESP32-A2DP.zip. Then, click Open.

    _images/a2dp_choose.png
  3. After a short while, you will receive a notification indicating a successful installation.

    _images/a2dp_success.png
  4. Repeat the same process to add the ESP8266Audio.zip library.

Note

The libraries installed using either of the above methods can be found in the default library directory of the Arduino IDE, which is usually located at C:\Users\xxx\Documents\Arduino\libraries.

If your library directory is different, you can check it by going to File -> Preferences.

_images/install_lib1.png

2. Displays

2.1 Hello, LED!

Just as printing “Hello, world!” is the first step in learning to program, using a program to drive an LED is the traditional introduction to learning physical programming.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.1_led.png

This circuit works on a simple principle, and the current direction is shown in the figure. The LED will light up after the 220ohm current limiting resistor when pin26 outputs high level. The LED will turn off when pin26 outputs low level.

Wiring

_images/2.1_hello_led_bb.png

Upload Code

  1. You can open the file 2.1_hello_led.ino under the path of esp32-starter-kit-main\c\codes\2.1_hello_led. Or copy this code to the Arduino IDE directly .

  2. Then connect the ESP32 WROOM 32E to your computer using a Micro USB cable.

  3. Select the board (ESP32 Dev Module) and the appropriate port.

    _images/choose_board.png
  4. Now, click the Upload button to upload the code to the ESP32 board.

    _images/click_upload.png
  5. After the code is uploaded successfully, you will see the LED blinking.

How it works?

  1. Declare an integer constant named ledPin and assigns it the value 26.

    const int ledPin = 26;  // The GPIO pin for the LED
    
  2. Now, initialize the pin in the setup() function, where you need to initialize the pin to OUTPUT mode.

    void setup() {
        pinMode(ledPin, OUTPUT);
    }
    
    • void pinMode(uint8_t pin, uint8_t mode);: This function is used to define the GPIO operation mode for a specific pin.

      • pin defines the GPIO pin number.

      • mode sets operation mode.

      The following modes are supported for the basic input and output:

      • INPUT sets the GPIO as input without pullup or pulldown (high impedance).

      • OUTPUT sets the GPIO as output/read mode.

      • INPUT_PULLDOWN sets the GPIO as input with the internal pulldown.

      • INPUT_PULLUP sets the GPIO as input with the internal pullup.

  3. The loop() function contains the main logic of the program and runs continuously. It alternates between setting the pin high and low, with one-second intervals between the changes.

    void loop() {
        digitalWrite(ledPin, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(1000);                       // wait for a second
        digitalWrite(ledPin, LOW);    // turn the LED off by making the voltage LOW
        delay(1000);                       // wait for a second
    }
    
    • void digitalWrite(uint8_t pin, uint8_t val);: This function sets the state of the selected GPIO to HIGH or LOW. This function is only used if the pinMode was configured as OUTPUT.

      • pin defines the GPIO pin number.

      • val set the output digital state to HIGH or LOW.

2.2 Fading

In the previous project, we controlled the LED by turning it on and off using digital output. In this project, we will create a breathing effect on the LED by utilizing Pulse Width Modulation (PWM). PWM is a technique that allows us to control the brightness of an LED or the speed of a motor by varying the duty cycle of a square wave signal.

With PWM, instead of simply turning the LED on or off, we will be adjusting the amount of time the LED is on versus the amount of time it is off within each cycle. By rapidly switching the LED on and off at varying intervals, we can create the illusion of the LED gradually brightening and dimming, simulating a breathing effect.

By using the PWM capabilities of the ESP32 WROOM 32E, we can achieve smooth and precise control over the LED’s brightness. This breathing effect adds a dynamic and visually appealing element to your projects, creating an eye-catching display or ambiance.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.1_led.png

This project is the same circuit as the first project 2.1 Hello, LED!, but the signal type is different. The first project is to output digital high and low levels (0&1) directly from pin26 to make the LED light up or turn off, this project is to output PWM signal from pin26 to control the brightness of the LED.

Wiring

_images/2.1_hello_led_bb.png

Code

Note

  • You can open the file 2.2_fading_led.ino under the path of esp32-starter-kit-main\c\codes\2.2_fading_led.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code is uploaded successfully, you can see the LED breathing.

How it works?

  1. Define constants and variables。

    const int ledPin = 26; // The GPIO pin for the LED
    int brightness = 0;
    int fadeAmount = 5;
    
    • ledPin: The GPIO pin number where the LED is connected (in this case, GPIO 26).

    • brightness: The current brightness level of the LED (initially set to 0).

    • fadeAmount: The amount by which the LED’s brightness will change in each step (set to 5).

  2. Initializes the PWM channel and configures the LED pin.

    void setup() {
        ledcSetup(0, 5000, 8); // Configure the PWM channel (0) with 5000Hz frequency and 8-bit resolution
        ledcAttachPin(ledPin, 0); // Attach the LED pin to the PWM channel
    }
    

    Here we use the LEDC (LED control) peripheral which is primarly designed to control the intensity of LEDs, although it can also be used to generate PWM signals for other purposes.

    • uint32_t ledcSetup(uint8_t channel, uint32_t freq, uint8_t resolution_bits);: This function is used to setup the LEDC channel frequency and resolution. It will return frequency configured for LEDC channel. If 0 is returned, error occurs and ledc channel was not configured.

      • channel select LEDC channel to config.

      • freq select frequency of pwm.

      • resolution_bits select resolution for ledc channel. Range is 1-14 bits (1-20 bits for ESP32).

    • void ledcAttachPin(uint8_t pin, uint8_t chan);: This function is used to attach the pin to the LEDC channel.

      • pin select GPIO pin.

      • chan select LEDC channel.

  3. The loop() function contains the main logic of the program and runs continuously. It updates the LED’s brightness, inverts the fade amount when the brightness reaches the minimum or maximum value, and introduces a delay.

    void loop() {
        ledcWrite(0, brightness); // Write the new brightness value to the PWM channel
        brightness = brightness + fadeAmount;
    
        if (brightness <= 0 || brightness >= 255) {
            fadeAmount = -fadeAmount;
        }
    
        delay(50); // Wait for 20 milliseconds
        }
    
    • void ledcWrite(uint8_t chan, uint32_t duty);: This function is used to set duty for the LEDC channel.

      • chan select the LEDC channel for writing duty.

      • duty select duty to be set for selected channel.

2.3 Colorful Light

In this project, we will delve into the fascinating world of additive color mixing using an RGB LED.

RGB LED combines three primary colors, namely Red, Green, and Blue, into a single package. These three LEDs share a common cathode pin, while each anode pin controls the intensity of the corresponding color.

By varying the electrical signal intensity applied to each anode, we can create a wide range of colors. For example, mixing high-intensity red and green light will result in yellow light, while combining blue and green light will produce cyan.

Through this project, we will explore the principles of additive color mixing and unleash our creativity by manipulating the RGB LED to display captivating and vibrant colors.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

RGB LED

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.3_rgb.png

The PWM pins pin27, pin26 and pin25 control the Red, Green and Blue pins of the RGB LED respectively, and connect the common cathode pin to GND. This allows the RGB LED to display a specific color by superimposing light on these pins with different PWM values.

Wiring

_images/rgb_pin.jpg

The RGB LED has 4 pins: the long pin is the common cathode pin, which is usually connected to GND; the left pin next to the longest pin is Red; and the two pins on the right are Green and Blue.

_images/2.3_color_light_bb.png

Code

Here, we can choose our favorite color in drawing software (such as paint) and display it with RGB LED.

Note

  • You can open the file 2.3_rgb_led.ino under the path of esp32-starter-kit-main\c\codes\2.3_rgb_led.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

_images/edit_colors.png

Write the RGB value into color_set(), you will be able to see the RGB light up the colors you want.

How it works?

  1. Define the GPIO pins, the PWM channels and the frequency (in Hz) and resolution (in bits).

    // Define RGB LED pins
    const int redPin = 27;
    const int greenPin = 26;
    const int bluePin = 25;
    
    // Define PWM channels
    const int redChannel = 0;
    const int greenChannel = 1;
    const int blueChannel = 2;
    
    // Define PWM frequency and resolution
    const int freq = 5000;
    const int resolution = 8;
    
  2. The setup() function initializes the PWM channels with the specified frequency and resolution, and then attaches the LED pins to their corresponding PWM channels.

    void setup() {
        // Set up PWM channels
        ledcSetup(redChannel, freq, resolution);
        ledcSetup(greenChannel, freq, resolution);
        ledcSetup(blueChannel, freq, resolution);
    
        // Attach pins to corresponding PWM channels
        ledcAttachPin(redPin, redChannel);
        ledcAttachPin(greenPin, greenChannel);
        ledcAttachPin(bluePin, blueChannel);
    }
    

    Here we use the LEDC (LED control) peripheral which is primarly designed to control the intensity of LEDs, although it can also be used to generate PWM signals for other purposes.

    • uint32_t ledcSetup(uint8_t channel, uint32_t freq, uint8_t resolution_bits);: This function is used to setup the LEDC channel frequency and resolution. It will return frequency configured for LEDC channel. If 0 is returned, error occurs and ledc channel was not configured.

      • channel select LEDC channel to config.

      • freq select frequency of pwm.

      • resolution_bits select resolution for ledc channel. Range is 1-14 bits (1-20 bits for ESP32).

    • void ledcAttachPin(uint8_t pin, uint8_t chan);: This function is used to attach the pin to the LEDC channel.

      • pin select GPIO pin.

      • chan select LEDC channel.

  3. The loop() function cycles through various colors (red, green, blue, yellow, purple, and cyan) with one-second intervals between each color change.

    void loop() {
        setColor(255, 0, 0); // Red
        delay(1000);
        setColor(0, 255, 0); // Green
        delay(1000);
        setColor(0, 0, 255); // Blue
        delay(1000);
        setColor(255, 255, 0); // Yellow
        delay(1000);
        setColor(80, 0, 80); // Purple
        delay(1000);
        setColor(0, 255, 255); // Cyan
        delay(1000);
    }
    
  4. The setColor() function sets the desired color by writing the appropriate duty cycle values to each PWM channel. The function takes in three integer arguments for red, green, and blue color values.

    void setColor(int red, int green, int blue) {
        // For common-anode RGB LEDs, use 255 minus the color value
        ledcWrite(redChannel, red);
        ledcWrite(greenChannel, green);
        ledcWrite(blueChannel, blue);
    }
    
    • void ledcWrite(uint8_t chan, uint32_t duty);: This function is used to set duty for the LEDC channel.

      • chan select the LEDC channel for writing duty.

      • duty select duty to be set for selected channel.

2.4 Microchip - 74HC595

Welcome to this exciting project! In this project, we will be using the 74HC595 chip to control a flowing display of 8 LEDs.

Imagine triggering this project and witnessing a mesmerizing flow of light, as if a sparkling rainbow is jumping between the 8 LEDs. Each LED will light up one by one and quickly fade away, while the next LED continues to shine, creating a gorgeous and dynamic effect.

By cleverly utilizing the 74HC595 chip, we can control the on and off states of multiple LEDs to achieve the flowing effect. This chip has multiple output pins that can be connected in series to control the sequence of LED illumination. Moreover, thanks to the chip’s expandability, we can easily add more LEDs to the flowing display, creating even more spectacular effects.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

74HC595

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.4_74hc595_led.png
  • When MR (pin10) is high level and CE (pin13) is low level, data is input in the rising edge of SHcp and goes to the memory register through the rising edge of SHcp.

  • If the two clocks are connected together, the shift register is always one pulse earlier than the memory register.

  • There is a serial shift input pin (DS), a serial output pin (Q7’) and an asynchronous reset button (low level) in the memory register.

  • The memory register outputs a Bus with a parallel 8-bit and in three states.

  • When OE is enabled (low level), the data in memory register is output to the bus(Q0 ~ Q7).

Wiring

_images/2.4_74hc595_bb.png

Code

Note

  • Open the 2.4_74hc595.ino file under the path of esp32-starter-kit-main\c\codes\2.4_74hc595.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

When you finish uploading the codes to the ESP32 board, you can see the LEDs turning on one after another.

How it works?

  1. Declare an array, store several 8 bit binary numbers that are used to change the working state of the eight LEDs controlled by 74HC595.

    int datArray[] = {B00000000, B00000001, B00000011, B00000111, B00001111, B00011111, B00111111, B01111111, B11111111};
    
  2. loop() function.

    void loop()
        {
            for(int num = 0; num <10; num++)
            {
                digitalWrite(STcp,LOW); //Set ST_CP and hold low for as long as you are transmitting
                shiftOut(DS,SHcp,MSBFIRST,datArray[num]);
                digitalWrite(STcp,HIGH); //pull the ST_CPST_CP to save the data
                delay(1000);
            }
        }
    
    • Iterates through the datArray[], sequentially sending the binary values to the shift register.

    • The digitalWrite(STcp, LOW) and digitalWrite(STcp, HIGH) commands latch the data into the storage register.

    • shiftOut() function sends the binary values from datArray[] to the shift register using the data pin (DS) and shift register clock pin (SHcp). MSBFIRST means to move from high bits.

    • Then create a 1-second pause between each LED pattern update.

2.5 7 Segment Display

Welcome to this fascinating project! In this project, we will explore the enchanting world of displaying numbers from 0 to 9 on a seven-segment display.

Imagine triggering this project and witnessing a small, compact display glowing brightly with each number from 0 to 9. It’s like having a miniature screen that showcases the digits in a captivating way. By controlling the signal pins, you can effortlessly change the displayed number and create various engaging effects.

Through simple circuit connections and programming, you will learn how to interact with the seven-segment display and bring your desired numbers to life. Whether it’s a counter, a clock, or any other intriguing application, the seven-segment display will be your reliable companion, adding a touch of brilliance to your projects.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

7-segment Display

BUY

74HC595

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.5_74hc595_7_segment.png

Here the wiring principle is basically the same as 2.4 Microchip - 74HC595, the only difference is that Q0-Q7 are connected to the a ~ g pins of the 7 Segment Display.

Wiring

74HC595

LED Segment Display

Q0

a

Q1

b

Q2

c

Q3

d

Q4

e

Q5

f

Q6

g

Q7

dp

Wiring

_images/2.5_segment_bb.png

Code

Note

  • Open the 2.5_7segment.ino file under the path of esp32-starter-kit-main\c\codes\2.5_7segment.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code is uploaded successfully, you will be able to see the LED Segment Display display 0~9 in sequence.

How it works?

In this project, we are using the shiftOut() function to write the binary number to the shift register.

Suppose that the 7-segment Display display the number “2”. This bit pattern corresponds to the segments f, c and dp being turned off (low), while the segments a, b, d, e and g are turned on (high). This is “01011011” in binary and “0x5b” in hexadecimal notation.

Therefore, you would need to call shiftOut(DS,SHcp,MSBFIRST,0x5b) to display the number “2” on the 7-segment display.

_images/7_segment2.png

The following table shows the hexadecimal patterns that need to be written to the shift register to display the numbers 0 to 9 on a 7-segment display.

Glyph Code

Numbers

Binary Code

Hex Code

0

00111111

0x3f

1

00000110

0x06

2

01011011

0x5b

3

01001111

0x4f

4

01100110

0x66

5

01101101

0x6d

6

01111101

0x7d

7

00000111

0x07

8

01111111

0x7f

9

01101111

0x6f

Write these codes into shiftOut() to make the LED Segment Display display the corresponding numbers.

2.6 Display Characters

Now, we will explore the fascinating world of character display using the I2C LCD1602 module.

Through this project, we will learn how to initialize the LCD module, set the desired display parameters, and send character data to be displayed on the screen. We can showcase custom messages, display sensor readings, or create interactive menus. The possibilities are endless!

By mastering the art of character display on the I2C LCD1602, we will unlock new avenues for communication and information display in our projects. Let’s dive into this exciting journey and bring our characters to life on the LCD screen

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

I2C LCD1602

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

Usage Description

IO21

SDA

IO22

SCL

Schematic

_images/circuit_2.6_lcd.png

Wiring

_images/2.6_i2clcd1602_bb.png

Code

Note

  • Open the 2.6_lcd1602.ino file under the path of esp32-starter-kit-main\c\codes\2.6_lcd1602.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

  • The LiquidCrystal I2C library is used here, you can install it from the Library Manager.

    _images/lcd_lib.png

When this program is uploaded, the I2C LCD1602 will display the welcome message, “Hello, Sunfounder!”, for 3 seconds. After that, the screen will show a “COUNT:” label and the count value, which increments every second.

Note

If the code and wiring are correct, but the LCD still fails to display any content, you can adjust the potentiometer on the back to increase the contrast.

How it works?

By calling the library LiquidCrystal_I2C.h, you can easily drive the LCD.

#include <LiquidCrystal_I2C.h>

Library Functions:

  • Creates a new instance of the LiquidCrystal_I2C class that represents a particular LCD attached to your Arduino board.

    LiquidCrystal_I2C(uint8_t lcd_Addr,uint8_t lcd_cols,uint8_t lcd_rows)
    
    • lcd_AddR: The address of the LCD defaults to 0x27.

    • lcd_cols: The LCD1602 has 16 columns.

    • lcd_rows: The LCD1602 has 2 rows.

  • Initialize the lcd.

    void init()
    
  • Turn the (optional) backlight on.

    void backlight()
    
  • Turn the (optional) backlight off.

    void nobacklight()
    
  • Turn the LCD display on.

    void display()
    
  • Turn the LCD display off quickly.

    void nodisplay()
    
  • Clear display, set cursor position to zero.

    void clear()
    
  • Set the cursor position to col,row.

    void setCursor(uint8_t col,uint8_t row)
    
  • Prints text to the LCD.

    void print(data,BASE)
    
    • data: The data to print (char, byte, int, long, or string).

    • BASE (optional): The base in which to print numbers.

      • BIN for binary (base 2)

      • DEC for decimal (base 10)

      • OCT for octal (base 8)

      • HEX for hexadecimal (base 16).

2.7 RGB LED Strip

In this project, we will delve into the mesmerizing world of driving WS2812 LED strips and bring a vibrant display of colors to life. With the ability to individually control each LED on the strip, we can create captivating lighting effects that will dazzle the senses.

Furthermore, we have included an exciting extension to this project, where we will explore the realm of randomness. By introducing random colors and implementing a flowing light effect, we can create a mesmerizing visual experience that captivates and enchants.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

WS2812 RGB 8 LEDs Strip

BUY

Schematic

_images/circuit_2.7_ws2812.png

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Note

IO33 is not available for this project.

The WS2812 LED strip is a type of LED strip that requires a precise pulse-width modulation (PWM) signal. The PWM signal has precise requirements in both time and voltage. For instance, a “0” bit for the WS2812 corresponds to a high-level pulse of about 0.4 microseconds, while a “1” bit corresponds to a high-level pulse of about 0.8 microseconds. This means the strip needs to receive high-frequency voltage changes.

However, with a 4.7K pull-up resistor and a 100nf pull-down capacitor on IO33, a simple low-pass filter is created. This type of circuit “smooths out” high-frequency signals, because the capacitor needs some time to charge and discharge when it receives voltage changes. Therefore, if the signal changes too quickly (i.e., is high-frequency), the capacitor will not be able to keep up. This results in the output signal becoming blurred and unrecognizable to the strip.

Wiring

_images/2.7_rgb_strip_bb.png

Code

Note

  • You can open the file 2.7_rgb_strip.ino under the path of esp32-starter-kit-main\c\codes\2.7_rgb_strip. Or copy this code into Arduino IDE.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

  • The Adafruit NeoPixel library is used here, you can install it from the Library Manager.

    _images/rgb_strip_lib.png

When the code is successfully uploaded, the LEDs on the strip will sequentially turn on with a yellow color and then turn off, creating a simple chasing effect.

How it works?

  1. Include the Adafruit NeoPixel library: This line imports the Adafruit NeoPixel library so that the sketch can use its functions and classes to control the LED strip.

    #include <Adafruit_NeoPixel.h> // Include the Adafruit NeoPixel library
    
  2. Define constants for the LED strip.

    #define LED_PIN 13 // NeoPixel LED strip
    #define NUM_LEDS 8 // Number of LEDs
    
  3. Create an instance of the Adafruit_NeoPixel class.

    // Create an instance of the Adafruit_NeoPixel class
     Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800);
    

    This line creates an instance of the Adafruit_NeoPixel class called strip and configures it with the number of LEDs, the pin connected to the LED strip, and the signal parameters (GRB color order and 800 kHz data rate).

    • Adafruit_NeoPixel (uint16_t n, int16_t p = 6, neoPixelType t = NEO_GRB + NEO_KHZ800)

    NeoPixel constructor when length, pin and pixel type are known at compile-time. Ruturn Adafruit_NeoPixel object. Call the begin() function before use.

    • n: Number of NeoPixels in strand.

    • p: Arduino pin number which will drive the NeoPixel data in.

    • t: Pixel type - add together NEO_* constants defined in Adafruit_NeoPixel.h, for example NEO_GRB+NEO_KHZ800 for NeoPixels expecting an 800 KHz (vs 400 KHz) data stream with color bytes expressed in green, red, blue order per pixel.

  4. Initialize the WS2812 RGB strip and sets the initial color of the strip to black (off).

    void setup() {
        strip.begin(); // Initialize the NeoPixel strip
        strip.show(); // Set initial color to black
    }
    
    • void begin (void): Configure NeoPixel pin for output.

    • void show (void): Transmit pixel data in RAM to NeoPixels.

  5. In the loop() function, the LEDs on the strip will sequentially turn on with a yellow color and then turn off, creating a simple chasing effect.

    void loop() {
    // Turn on LEDs one by one
    for (int i = 0; i < NUM_LEDS; i++) {
        strip.setPixelColor(i, 100, 45, 0); // Set the color of the i-th LED to red
        strip.show(); // Update the LED strip with the new colors
        delay(100); // Wait for 100 milliseconds
    }
    
    // Turn off LEDs one by one
    for (int i = 0; i < NUM_LEDS; i++) {
        strip.setPixelColor(i, 0, 0, 0); // Set the color of the i-th LED to black (turn it off)
        strip.show(); // Update the LED strip with the new colors
        delay(100); // Wait for 100 milliseconds
    }
    }
    
    • void setPixelColor (uint16_t n, uint8_t r, uint8_t g, uint8_t b)

    Set a pixel’s color using separate red, green and blue components. If using RGBW pixels, white will be set to 0.

    • n: Pixel index, starting from 0.

    • r: Red brightness, 0 = minimum (off), 255 = maximum.

    • g: Green brightness, 0 = minimum (off), 255 = maximum.

    • b: Blue brightness, 0 = minimum (off), 255 = maximum.

3. Sounds

3.1 Beep

This is a simple project to make an active buzzer beep quickly four times every second.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Buzzer

-

Transistor

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_3.1_buzzer.png

When the IO14 output is high, after the 1K current limiting resistor (to protect the transistor), the S8050 (NPN transistor) will conduct, so that the buzzer will sound.

The role of S8050 (NPN transistor) is to amplify the current and make the buzzer sound louder. In fact, you can also connect the buzzer directly to IO14, but you will find that the buzzer sound is smaller.

Wiring

Two types of buzzers are included in the kit. We need to use active buzzer. Turn them around, the sealed back (not the exposed PCB) is the one we want.

_images/buzzer.png

The buzzer needs to use a transistor when working, here we use S8050 (NPN Transistor).

_images/3.1_buzzer_bb.png

Code

Note

  • You can open the file 3.1_beep.ino under the path of esp32-starter-kit-main\c\codes\3.1_beep.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code is uploaded successfully, you will hear a beep every second.

3.2 Custom Tone

We have used active buzzer in the previous project, this time we will use passive buzzer.

Like the active buzzer, the passive buzzer also uses the phenomenon of electromagnetic induction to work. The difference is that a passive buzzer does not have oscillating source, so it will not beep if DC signals are used. But this allows the passive buzzer to adjust its own oscillation frequency and can emit different notes such as “doh, re, mi, fa, sol, la, ti”.

Let the passive buzzer emit a melody!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Buzzer

-

Transistor

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_3.1_buzzer.png

When the IO14 output is high, after the 1K current limiting resistor (to protect the transistor), the S8050 (NPN transistor) will conduct, so that the buzzer will sound.

The role of S8050 (NPN transistor) is to amplify the current and make the buzzer sound louder. In fact, you can also connect the buzzer directly to IO14, but you will find that the buzzer sound is smaller.

Wiring

Two types of buzzers are included in the kit. We need to use passive buzzer. Turn them around, the exposed PCB is the one we want.

_images/buzzer.png

The buzzer needs to use a transistor when working, here we use S8050 (NPN Transistor).

_images/3.1_buzzer_bb.png

Code

Note

  • Open the 3.2_custom_tone.ino file under the path of esp32-starter-kit-main\c\codes\3.2_custom_tone.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code is successfully uploaded, you will hear the passive buzzer play a sequence of 7 musical notes.

How it works?

  1. Define constants for the buzzer pin and PWM resolution.

    const int buzzerPin = 14; //buzzer pin
    const int resolution = 8;
    
  2. Define an array containing the frequencies of the 7 musical notes in Hz.

    int frequencies[] = {262, 294, 330, 349, 392, 440, 494};
    
  3. Create a function to play a given frequency on the buzzer for a specified duration.

    void playFrequency(int frequency, int duration) {
        ledcWriteTone(0, frequency); // Start the tone
        delay(duration); // Wait for the specified duration
        ledcWriteTone(0, 0); // Stop the buzzer
    }
    
    • uint32_t ledcWriteTone(uint8_t chan, uint32_t freq);: This function is used to setup the LEDC channel to 50 % PWM tone on selected frequency.

      • chan select LEDC channel.

      • freq select frequency of pwm signal.

    This function will return frequency set for channel. If 0 is returned, error occurs and ledc cahnnel was not configured.

  4. Configure the PWM channel and attach the buzzer pin in the setup() function.

    void setup() {
        ledcSetup(0, 2000, resolution); // Set up the PWM channel
        ledcAttachPin(buzzerPin, 0); // Attach the buzzer pin to the PWM channel
    }
    
    • uint32_t ledcSetup(uint8_t channel, uint32_t freq, uint8_t resolution_bits);: This function is used to setup the LEDC channel frequency and resolution. It will return frequency configured for LEDC channel. If 0 is returned, error occurs and ledc channel was not configured.

      • channel select LEDC channel to config.

      • freq select frequency of pwm.

      • resolution_bits select resolution for ledc channel. Range is 1-14 bits (1-20 bits for ESP32).

    • void ledcAttachPin(uint8_t pin, uint8_t chan);: This function is used to attach the pin to the LEDC channel.

      • pin select GPIO pin.

      • chan select LEDC channel.

  5. In the loop() function, play the sequence of 7 notes with a brief pause between each note and a 1-second pause before repeating the sequence.

    void loop() {
        for (int i = 0; i < 7; i++) {
            playFrequency(frequencies[i], 300); // Play each note for 300ms
            delay(50); // Add a brief pause between the notes
        }
        delay(1000); // Wait for 1 second before replaying the sequence
        }
    

4. Actuators

4.1 Motor

In this engaging project, we’ll explore how to drive a motor using the L293D.

The L293D is a versatile integrated circuit (IC) commonly used for motor control in electronics and robotics projects. It can drive two motors in both forward and reverse directions, making it a popular choice for applications requiring precise motor control.

By the end of this captivating project, you will have gained a thorough understanding of how digital signals and PWM signals can effectively be utilized to control motors. This invaluable knowledge will prove to be a solid foundation for your future endeavors in robotics and mechatronics. Buckle up and get ready to dive into the exciting world of motor control with the L293D!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

DC Motor

BUY

L293D

-

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_4.1_motor_l293d.png

Wiring

Note

Since the motor requires a relatively high current, it is necessary to first insert the battery and then slide the switch on the expansion board to the ON position to activate the battery supply.

_images/4.1_motor_l293d_bb.png

Code

Note

  • Open the 4.1_motor.ino file under the path of esp32-starter-kit-main\c\codes\4.1_motor.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

Once the code is successfully uploaded, you will observe the motor rotating clockwise for one second, then counter-clockwise for one second, followed by a two-second pause. This sequence of actions will continue in an endless loop.

Learn More

In addition to simply making the motor rotate clockwise and counterclockwise, you can also control the speed of the motor’s rotation by using pulse-width modulation (PWM) on the control pin, as shown below.

Note

  • Open the 4.1_motor_pwm.ino file under the path of esp32-starter-kit-main\c\codes\4.1_motor_pwm.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

The previous code directly sets the two pins of the motor to high or low voltage levels to control the motor’s rotation and stopping.

Here we use the LEDC (LED control) peripheral to generate PWM signals to control the motor’s speed. Through two for loops, the duty cycle of channel A is increased or decreased from 0 to 255 while keeping channel B at 0.

This way, you can observe the motor gradually increasing its speed to 255, then decreasing to 0, infinitely looping like this.

If you want the motor to rotate in the opposite direction, simply swap the values of channel A and channel B.

4.2 Pumping

In this intriguing project, we will delve into controlling a water pump using the L293D.

In the realm of water pump control, things are a bit simpler compared to controlling other motors. The beauty of this project lies in its simplicity - there’s no need to worry about the direction of rotation. Our primary goal is to successfully activate the water pump and keep it running.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Centrifugal Pump

-

L293D

-

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_4.1_motor_l293d.png

Wiring

Note

It is recommended here to insert the battery and then slide the switch on the expansion board to the ON position to activate the battery supply.

_images/4.2_pump_l293d_bb.png

Code

Note

  • You can open the file 4.2_pump.ino under the path of esp32-starter-kit-main\c\codes\4.2_pump.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

Connect the tubing to the pump and place it inside the water-filled container. Once the code has been successfully uploaded, you will observe the water in the container gradually being drained. During this experiment, please ensure that the electrical circuit is kept away from water to prevent short-circuiting!

4.3 Swinging Servo

A Servo is a type of position-based device known for its ability to maintain specific angles and deliver precise rotation. This makes it highly desirable for control systems that demand consistent angle adjustments. It’s not surprising that Servos have found extensive use in high-end remote-controlled toys, from airplane models to submarine replicas and sophisticated remote-controlled robots.

In this intriguing adventure, we’ll challenge ourselves to manipulate the Servo in a unique way - by making it sway! This project offers a brilliant opportunity to dive deeper into the dynamics of Servos, sharpening your skills in precise control systems and offering a deeper understanding of their operation.

Are you ready to make the Servo dance to your tunes? Let’s embark on this exciting journey!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Servo

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_4.3_servo.png

Wiring

  • Orange wire is signal and connected to IO25.

  • Red wire is VCC and connected to 5V.

  • Brown wire is GND and connected to GND.

_images/4.3_swinging_servo_bb.png

Code

Note

  • Open the 4.3_servo.ino file under the path of esp32-starter-kit-main\c\codes\4.3_servo. Or copy this code into Arduino IDE.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

  • The ESP32Servo library is used here, you can install it from the Library Manager.

    _images/servo_lib.png

Once you finish uploading the code, you can see the servo arm rotating in the range 0°~180°.

How it works?

  1. Include the ESP32Servo library: This line imports the ESP32Servo library, which is required to control the servo motor.

    #include <ESP32Servo.h>
    
  2. Define the servo and the pin it is connected to: This section declares a Servo object (myServo) and a constant integer (servoPin) to represent the pin that the servo motor is connected to (pin 25).

    // Define the servo and the pin it is connected to
    Servo myServo;
    const int servoPin = 25;
    
  3. Define the minimum and maximum pulse widths for the servo: This section sets the minimum and maximum pulse widths for the servo motor (0.5 ms and 2.5 ms, respectively).

    // Define the minimum and maximum pulse widths for the servo
    const int minPulseWidth = 500; // 0.5 ms
    const int maxPulseWidth = 2500; // 2.5 ms
    
  4. The setup function initializes the servo motor by attaching it to the specified pin and setting its pulse width range. It also sets the PWM frequency for the servo to the standard 50Hz.

    void setup() {
        // Attach the servo to the specified pin and set its pulse width range
        myServo.attach(servoPin, minPulseWidth, maxPulseWidth);
    
        // Set the PWM frequency for the servo
        myServo.setPeriodHertz(50); // Standard 50Hz servo
    }
    
    • attach (int pin, int min, int max): This function attaches the servo motor to the specified GPIO pin and sets the minimum and maximum pulse widths for the servo.

      • pin: The GPIO pin number that the servo is connected to.

      • The min and max: the minimum and maximum pulse widths, respectively, in microseconds. These values define the range of motion of the servo motor.

    • setPeriodHertz(int hertz): This function sets the PWM frequency for the servo motor in hertz.

      • hertz: The desired PWM frequency in hertz. The default PWM frequency for servos is 50Hz, which is suitable for most applications.

  5. The loop function is the main part of the code that continuously runs. It rotates the servo motor from 0 to 180 degrees, then back to 0 degrees. This is done by mapping the angle to the corresponding pulse width and updating the servo motor with the new pulse width value.

    void loop() {
        // Rotate the servo from 0 to 180 degrees
        for (int angle = 0; angle <= 180; angle++) {
            int pulseWidth = map(angle, 0, 180, minPulseWidth, maxPulseWidth);
            myServo.writeMicroseconds(pulseWidth);
            delay(15);
        }
    
        // Rotate the servo from 180 to 0 degrees
        for (int angle = 180; angle >= 0; angle--) {
            int pulseWidth = map(angle, 0, 180, minPulseWidth, maxPulseWidth);
            myServo.writeMicroseconds(pulseWidth);
            delay(15);
        }
    }
    
    • writeMicroseconds(int value): This function sets the pulse width of the servo motor in microseconds.

      • value: The desired pulse width in microseconds.

      The writeMicroseconds(int value) function takes an integer value as its argument, representing the desired pulse width in microseconds. This value should typically fall within the range specified by the minimum and maximum pulse widths (minPulseWidth and maxPulseWidth) defined earlier in the code. The function then sets the pulse width for the servo motor, causing it to move to the corresponding position.

5. Sensors

5.1 Reading Button Value

In this interactive project, we’ll venture into the realm of button controls and LED manipulation.

The concept is straightforward yet effective. We’ll be reading the state of a button. When the button is pressed down, it registers a high voltage level, or ‘high state’. This action will then trigger an LED to light up.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Button

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO14, IO25, I35, I34, I39, I36, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

  • Conditional Usage Pins (Input)

    The following pins have built-in pull-up or pull-down resistors, so external resistors are not required when using them as input pins:

    Conditional Usage Pins

    Description

    IO13, IO15, IO2, IO4

    Pulling up with a 47K resistor defaults the value to high.

    IO27, IO26, IO33

    Pulling up with a 4.7K resistor defaults the value to high.

    IO32

    Pulling down with a 1K resistor defaults the value to low.

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.1_button.png

To ensure proper functionality, connect one side of the button pin to 3.3V and the other side to IO14. When the button is pressed, IO14 will be set to high, causing the LED to light up. When the button is released, IO14 will return to its suspended state, which may be either high or low. To ensure a stable low level when the button is not pressed, IO14 should be connected to GND through a 10K pull-down resistor.

Wiring

_images/5.1_button_bb.png

Note

A four-pin button is designed in an H shape. When the button is not pressed, the left and right pins are disconnected, and current cannot flow between them. However, when the button is pressed, the left and right pins are connected, creating a pathway for current to flow.

Code

Note

  • You can open the file 5.1_button.ino under the path of esp32-starter-kit-main\c\codes\5.1_button.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

Once the code is uploaded successfully, the LED lights up when you press the button and goes off when you release it.

At the same time you can open the Serial Monitor in the upper right corner to observe the value of the button, when the button is pressed, “1” will be printed, otherwise “0” will be printed.

_images/button_serial.png

How it works

The previous projects all involved outputting signals, either in the form of digital or PWM signals.

This project involves receiving input signals from external component to the ESP32 board. You can view the input signal through the Serial Monitor in Arduino IDE.

  1. In the setup() function, the button pin is initialized as an input and the LED pin is initialized as an output. The Serial communication is also initiated with a baud rate of 115200.

    void setup() {
        Serial.begin(115200);
        // initialize the button pin as an input
        pinMode(buttonPin, INPUT);
        // initialize the LED pin as an output
        pinMode(ledPin, OUTPUT);
    }
    
    • Serial.begin(speed): Sets the data rate in bits per second (baud) for serial data transmission.

      • speed: in bits per second (baud). Allowed data types: long.

  2. In the loop() function, the state of the button is read and stored in the variable buttonState. The value of buttonState is printed to the Serial Monitor using Serial.println().

    void loop() {
        // read the state of the button value
        buttonState = digitalRead(buttonPin);
        Serial.println(buttonState);
        delay(100);
        // if the button is pressed, the buttonState is HIGH
        if (buttonState == HIGH) {
            // turn LED on
            digitalWrite(ledPin, HIGH);
    
        } else {
            // turn LED off
            digitalWrite(ledPin, LOW);
        }
    }
    

    If the button is pressed and the buttonState is HIGH, the LED is turned on by setting the ledPin to HIGH. Else, turn the LED off.

    • int digitalRead(uint8_t pin);: To read the state of a given pin configured as INPUT, the function digitalRead is used. This function will return the logical state of the selected pin as HIGH or LOW.

      • pin select GPIO

    • Serial.println(): Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or ‘r’) and a newline character (ASCII 10, or ‘n’).

5.2 Tilt It!

The tilt switch is a simple yet effective 2-pin device that contains a metal ball in its center. When the switch is in an upright position, the two pins are electrically connected, allowing current to flow through. However, when the switch is tilted or tilted at a certain angle, the metal ball moves and breaks the electrical connection between the pins.

In this project, we will utilize the tilt switch to control the illumination of an LED. By positioning the switch in a way that triggers the tilt action, we can toggle the LED on and off based on the switch’s orientation.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Tilt Switch

-

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO14, IO25, I35, I34, I39, I36, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

  • Conditional Usage Pins (Input)

    The following pins have built-in pull-up or pull-down resistors, so external resistors are not required when using them as input pins:

    Conditional Usage Pins

    Description

    IO13, IO15, IO2, IO4

    Pulling up with a 47K resistor defaults the value to high.

    IO27, IO26, IO33

    Pulling up with a 4.7K resistor defaults the value to high.

    IO32

    Pulling down with a 1K resistor defaults the value to low.

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.2_tilt.png

When the tilt switch is in an upright position, IO14 will be set to high, resulting in the LED being lit. Conversely, when the tilt switch is tilted, IO14 will be set to low, causing the LED to turn off.

The purpose of the 10K resistor is to maintain a stable low state for IO14 when the tilt switch is in a tilted position.

Wiring

_images/5.2_tilt_switch_bb.png

Code

Note

  • You can open the file 5.2_tilt_switch.ino under the path of esp32-starter-kit-main\c\codes\5.2_tilt_switch.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After code upload successfully, the LED will be turned on when the switch is upright, and turned off when the switch is tilted.

5.3 Detect the Obstacle

This module is commonly installed on the car and robot to judge the existence of the obstacles ahead. Also it is widely used in hand held device, water faucet and so on.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Obstacle Avoidance Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO13, IO14, IO27, IO26, IO25, IO33, I35, I34, I39, I36, IO4, IO18, IO19, IO21, IO22, IO23

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.3_avoid.png

When the obstacle avoidance module does not detect any obstacles, IO14 returns a high level. However, when it detects an obstacle, it returns a low level. You can adjust the blue potentiometer to modify the detection distance of this module.

Wiring

_images/5.3_avoid_bb.png

Code

Note

  • You can open the file 5.3.detect_the_obstacle.ino under the path of esp32-starter-kit-main\c\codes\5.3.detect_the_obstacle.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code is uploaded successfully, if the IR obstacle avoidance module detects something blocking in front of it, “0” will appear on the serial monitor, otherwise “1” will be displayed.

5.4 Detect the Line

The line-tracking module is used to detect the presence of black areas on the ground, such as black lines taped with electrical tape.

Its emitter emits appropriate infrared light into the ground, which is relatively absorbed and weakly reflected by black surfaces. The opposite is true for white surfaces. If reflected light is detected, the ground is currently indicated as white. If it is not detected, it is indicated as black.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Line Tracking Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO13, IO14, IO27, IO26, IO25, IO33, I35, I34, I39, I36, IO4, IO18, IO19, IO21, IO22, IO23

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.4_line.png

When the line tracking module detects a black line, IO14 returns a high level. On the other hand, when it detects a white line, IO14 returns a low level. You can adjust the blue potentiometer to modify the sensitivity of this module’s detection.

Wiring

_images/5.4_line_bb.png

Code

Note

  • You can open the file 5.4_detect_the_line.ino under the path of esp32-starter-kit-main\c\codes\5.4_detect_the_line.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

If the line tracking module detects a black line after the code has been uploaded successfully, “Black” will be shown in the Serial Monitor. Otherwise, “White” will be printed.

5.5 Detect Human Movement

Passive infrared sensor (PIR sensor) is a common sensor that can measure infrared (IR) light emitted by objects in its field of view. Simply put, it will receive infrared radiation emitted from the body, thereby detecting the movement of people and other animals. More specifically, it tells the main control board that someone has entered your room.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

PIR Motion Sensor Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO13, IO14, IO27, IO26, IO25, IO33, I35, I34, I39, I36, IO4, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Note

IO32 cannot be used as input pin in this project because it is internally connected to a 1K pull-down resistor, which sets its default value to 0.

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.5_pir.png

When the PIR module detects motion, IO14 will go high, and the LED will be lit. Otherwise, when no motion is detected, IO14 will be low, and the LED will turn off.

Note

The PIR module has two potentiometers: one adjusts sensitivity, the other adjusts detection distance. To make the PIR module work better, you need to turn both of them counterclockwise to the end.

_images/PIR_TTE.png

Wiring

_images/5.5_pir_bb.png

Code

Note

  • You can open the file 5.5_pir.ino under the path of esp32-starter-kit-main\c\codes\5.5_pir.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code has been uploaded successfully, the LED will light up and then go off when the PIR module detects someone passing.

Note

The PIR module has two potentiometers: one adjusts sensitivity, the other adjusts detection distance. To make the PIR module work better, you need to turn both of them counterclockwise to the end.

_images/pir_back.png

5.6 Two Kinds of Transistors

This kit is equipped with two types of transistors, S8550 and S8050, the former is PNP and the latter is NPN. They look very similar, and we need to check carefully to see their labels. When a High level signal goes through an NPN transistor, it is energized. But a PNP one needs a Low level signal to manage it. Both types of transistor are frequently used for contactless switches, just like in this experiment.

Let’s use LED and button to understand how to use transistor!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Button

BUY

Transistor

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO14, IO25, I35, I34, I39, I36, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

  • Conditional Usage Pins (Input)

    The following pins have built-in pull-up or pull-down resistors, so external resistors are not required when using them as input pins:

    Conditional Usage Pins

    Description

    IO13, IO15, IO2, IO4

    Pulling up with a 47K resistor defaults the value to high.

    IO27, IO26, IO33

    Pulling up with a 4.7K resistor defaults the value to high.

    IO32

    Pulling down with a 1K resistor defaults the value to low.

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Way to connect NPN (S8050) transistor

_images/circuit_5.6_S8050.png

In this circuit, when the button is pressed, IO14 is high.

By programming IO26 to output high, after a 1k current limiting resistor (to protect the transistor), the S8050 (NPN transistor) is allowed to conduct, thus allowing the LED to light up.

_images/5.6_s8050_bb.png

Way to connect PNP(S8550) transistor

_images/circuit_5.6_S8550.png

In this circuit, IO14 is low by the default and will change to high when the button is pressed.

By programming IO26 to output low, after a 1k current limiting resistor (to protect the transistor), the S8550 (PNP transistor) is allowed to conduct, thus allowing the LED to light up.

The only difference you will notice between this circuit and the previous one is that in the previous circuit the cathode of the LED is connected to the collector of the S8050 (NPN transistor), while this one is connected to the emitter of the S8550 (PNP transistor).

_images/5.6_s8550_bb.png

Code

Note

  • You can open the file 5.6_transistor.ino under the path of esp32-starter-kit-main\c\codes\5.6_transistor.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

Two types of transistors can be controlled using the same code. When we press the button, the ESP32 will send a high-level signal to the transistor; when we release it, it will send a low-level signal.

  • The circuit using the S8050 (NPN transistor) will light up when the button is pressed, indicating that it is in a high-level conduction state;

  • The circuit using the S8550 (PNP transistor) will light up when the button is released, indicating that it is in a low-level conduction state.

5.7 Feel the Light

The photoresistor is a commonly used device for analog inputs, similar to a potentiometer. Its resistance value changes based on the intensity of the light it receives. When exposed to strong light, the resistance of the photoresistor decreases, and as the light intensity decreases, the resistance increases.

By reading the value of the photoresistor, we can gather information about the ambient light conditions. This information can be used for tasks such as controlling the brightness of an LED, adjusting the sensitivity of a sensor, or implementing light-dependent actions in a project.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Photoresistor

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO14, IO25, I35, I34, I39, I36

  • Strapping Pins

    The following pins are strapping pins, which affect the startup process of the ESP32 during power on or reset. However, once the ESP32 is booted up successfully, they can be used as regular pins.

    Strapping Pins

    IO0, IO12

Schematic

_images/circuit_5.7_photoresistor.png

As the light intensity increases, the resistance of the light-dependent resistor (LDR) decreases, resulting in a decrease in the value read on I35.

Wiring

_images/5.7_photoresistor_bb.png

Code

Note

  • Open the 5.7_feel_the_light.ino file under the path of esp32-starter-kit-main\c\codes\5.7_feel_the_light.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code is uploaded successfully, the Serial Monitor prints out the photoresistor values from 0 ~ 4095. The stronger the current ambient brightness, the larger the value displayed on the serial monitor.

Note

For the ESP32, the resolution is between 9 to 12 and it will change the ADC hardware resolution. Else value will be shifted.

Default is 12 bits (range from 0 to 4096) for all chips except ESP32S3 where default is 13 bits (range from 0 to 8192).

You can add analogReadResolution(10); to setup() function to set a different resolution, such as 20.

5.8 Turn the Knob

A potentiometer is a three-terminal device that is commonly used to adjust the resistance in a circuit. It features a knob or a sliding lever that can be used to vary the resistance value of the potentiometer. In this project, we will utilize it to control the brightness of an LED, similar to a desk lamp in our daily life. By adjusting the position of the potentiometer, we can change the resistance in the circuit, thereby regulating the current flowing through the LED and adjusting its brightness accordingly. This allows us to create a customizable and adjustable lighting experience, similar to that of a desk lamp.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Potentiometer

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO14, IO25, I35, I34, I39, I36

  • Strapping Pins

    The following pins are strapping pins, which affect the startup process of the ESP32 during power on or reset. However, once the ESP32 is booted up successfully, they can be used as regular pins.

    Strapping Pins

    IO0, IO12

Schematic

_images/circuit_5.8_potentiometer.png

When you rotate the potentiometer, the value of I35 will change. By programming, you can use the value of I35 to control the brightness of the LED. Therefore, as you rotate the potentiometer, the brightness of the LED will also change accordingly.

Wiring

_images/5.8_potentiometer_bb.png

Code

Note

  • You can open the file 5.8_pot.ino under the path of esp32-starter-kit-main\c\codes\5.8_pot.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code is uploaded successfully, rotate the potentiometer and you will see the brightness of the LED change accordingly. At the same time you can see the analog and voltage values of the potentiometer in the serial monitor.

How it works?

  1. Define constants for pin connections and PWM settings.

    const int potPin = 14; // Potentiometer connected to GPIO14
    const int ledPin = 26; // LED connected to GPIO26
    
    // PWM settings
    const int freq = 5000; // PWM frequency
    const int resolution = 12; // PWM resolution (bits)
    const int channel = 0; // PWM channel
    

    Here the PWM resolution is set to 12 bits and the range is 0-4095.

  2. Configure the system in the setup() function.

    void setup() {
        Serial.begin(115200);
    
        // Configure PWM
        ledcSetup(channel, freq, resolution);
        ledcAttachPin(ledPin, channel);
    }
    
    • In the setup() function, the Serial communication is started at a baud rate of 115200.

    • The ledcSetup() function is called to set up the PWM channel with the specified frequency and resolution, and the ledcAttachPin() function is called to associate the specified LED pin with the PWM channel.

  3. Main loop (executed repeatedly) in the loop() function.

    void loop() {
    
        int potValue = analogRead(potPin); // read the value of the potentiometer
        uint32_t voltage_mV = analogReadMilliVolts(potPin); // Read the voltage in millivolts
    
        ledcWrite(channel, potValue);
    
        Serial.print("Potentiometer Value: ");
        Serial.print(potValue);
        Serial.print(", Voltage: ");
        Serial.print(voltage_mV / 1000.0); // Convert millivolts to volts
        Serial.println(" V");
    
        delay(100);
    }
    
    • uint32_t analogReadMilliVolts(uint8_t pin);: This function is used to get ADC value for a given pin/ADC channel in millivolts.

      • pin GPIO pin to read analog value.

    The potentiometer value is directly used as the PWM duty cycle for controlling the LED brightness via the ledcWrite() function, as the range of values is also from 0 to 4095.

5.9 Measure Soil Moisture

This capacitive soil moisture sensor is different from most of the resistive sensors on the market, using the principle of capacitive induction to detect soil moisture.

By visually reading the values from the soil moisture sensor, we can gather information about the moisture level in the soil. This information is useful for various applications, such as automatic irrigation systems, plant health monitoring, or environmental sensing projects.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Soil Moisture Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO14, IO25, I35, I34, I39, I36

  • Strapping Pins

    The following pins are strapping pins, which affect the startup process of the ESP32 during power on or reset. However, once the ESP32 is booted up successfully, they can be used as regular pins.

    Strapping Pins

    IO0, IO12

Schematic

_images/circuit_5.9_soil_moisture.png

By inserting the module into the soil and watering it, the value read on I35 will decrease.

Wiring

_images/5.9_moisture_bb.png

Code

Note

  • Open the 5.9_moisture.ino file under the path of esp32-starter-kit-main\c\codes\5.9_moisture.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

Once the code is successfully uploaded, the serial monitor will print out the soil moisture value.

By inserting the module into the soil and watering it, the value of the soil moisture sensor will become smaller.

5.10 Thermometer

A thermistor is a temperature sensor that exhibits a strong dependence on temperature, and it can be classified into two types: Negative Temperature Coefficient (NTC) and Positive Temperature Coefficient (PTC). The resistance of an NTC thermistor decreases with increasing temperature, while the resistance of a PTC thermistor increases with increasing temperature.

In this project, we will be using an NTC thermistor. By connecting the NTC thermistor to an analog input pin of the ESP32 microcontroller, we can measure its resistance, which is directly proportional to the temperature.

By incorporating the NTC thermistor and performing the necessary calculations, we can accurately measure the temperature and display it on the I2C LCD1602 module. This project enables real-time temperature monitoring and provides a visual interface for temperature display.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Thermistor

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO14, IO25, I35, I34, I39, I36

  • Strapping Pins

    The following pins are strapping pins, which affect the startup process of the ESP32 during power on or reset. However, once the ESP32 is booted up successfully, they can be used as regular pins.

    Strapping Pins

    IO0, IO12

Schematic

_images/circuit_5.10_thermistor.png

When the temperature rises, the resistance of the thermistor decreases, causing the value read on I35 to decrease. Additionally, by using a formula, you can convert the analog value into temperature and then print it out.

Wiring

_images/5.10_thermistor_bb.png

Note

  • The thermistor is black and marked 103.

  • The color ring of the 10K ohm resistor is red, black, black, red and brown.

Code

Note

  • Open the 5.10_thermistor.ino file under the path of esp32-starter-kit-main\c\codes\5.10_thermistor.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code is successfully uploaded, the Serial Monitor will print out the Celsius and Fahrenheit temperatures.

How it works?

Each thermistor has a normal resistance. Here it is 10k ohm, which is measured under 25 degree Celsius.

When the temperature gets higher, the resistance of the thermistor decreases. Then the voltage data is converted to digital quantities by the A/D adapter.

The temperature in Celsius or Fahrenheit is output via programming.

Here is the relation between the resistance and temperature:

RT =RN expB(1/TK - 1/TN)

  • RT is the resistance of the NTC thermistor when the temperature is TK.

  • RN is the resistance of the NTC thermistor under the rated temperature TN. Here, the numerical value of RN is 10k.

  • TK is a Kelvin temperature and the unit is K. Here, the numerical value of TK is 273.15 + degree Celsius.

  • TN is a rated Kelvin temperature; the unit is K too. Here, the numerical value of TN is 273.15+25.

  • And B(beta), the material constant of NTC thermistor, is also called heat sensitivity index with a numerical value 3950.

  • exp is the abbreviation of exponential, and the base number e is a natural number and equals 2.7 approximately.

Convert this formula TK=1/(ln(RT/RN)/B+1/TN) to get Kelvin temperature that minus 273.15 equals degree Celsius.

This relation is an empirical formula. It is accurate only when the temperature and resistance are within the effective range.

Learn More

You can also display the calculated Celsius and Fahrenheit temperatures on the I2C LCD1602.

Note

  • You can open the file 5.10_thermistor_lcd.ino under the path of euler-kit/arduino/5.10_thermistor_lcd.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

  • The LiquidCrystal I2C library is used here, you can install it from the Library Manager.

5.11 Toggle the Joystick

If you play a lot of video games, then you should be very familiar with the Joystick. It is usually used to move the character around, rotate the screen, etc.

The principle behind Joystick’s ability to allow the computer to read our actions is very simple. It can be thought of as consisting of two potentiometers that are perpendicular to each other. These two potentiometers measure the analog value of the joystick vertically and horizontally, resulting in a value (x,y) in a planar right-angle coordinate system.

The joystick of this kit also has a digital input, which is activated when the joystick is pressed.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Joystick Module

BUY

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Analog Input

    IO14, IO25, I35, I34, I39, I36

    For Digital Input

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_5.11_joystick.png

The SW (Z-axis) pin is connected to IO33, which has a built-in 4.7K pull-up resistor. Therefore, when the SW button is not pressed, it will output a high level. When the button is pressed, it will output a low level.

I34 and I35 will change their values as you manipulate the joystick. The range of values is from 0 to 4095.

Wiring

_images/5.11_joystick_bb.png

Code

Note

  • Open the 5.11_joystick.ino file under the path of esp32-starter-kit-main\c\codes\5.11_joystick.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

Open the serial monitor after the code has been uploaded successfully to see the x,y,z values of the joystick.

  • The x-axis and y-axis values are analog values that vary from 0 to 4095.

  • The Z-axis is a digital value with a status of 1 or 0 ( when pressed, it is 0 ).

5.12 Measuring Distance

The ultrasonic module is used for distance measurement or object detection. In this project, we will program the module to obtain obstacle distances. By sending ultrasonic pulses and measuring the time it takes for them to bounce back, we can calculate distances. This enables us to implement distance-based actions or obstacle avoidance behaviors.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Ultrasonic Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO13, IO14, IO27, IO26, IO25, IO33, IO32, I35, I34, I39, I36, IO4, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_5.12_ultrasonic.png

The ESP32 sends a set of square wave signals to the Trig pin of the ultrasonic sensor every 10 seconds. This prompts the ultrasonic sensor to emit a 40kHz ultrasound signal outward. If there is an obstacle in front, the ultrasound waves will be reflected back.

By recording the time it takes from sending to receiving the signal, dividing it by 2, and multiplying it by the speed of light, you can determine the distance to the obstacle.

Wiring

_images/5.12_ultrasonic_bb.png

Code

Note

  • Open the 5.12_ultrasonic.ino file under the path of esp32-starter-kit-main\c\codes\5.12_ultrasonic.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

After the code is successfully uploaded, the serial monitor will print out the distance between the ultrasonic sensor and the obstacle ahead.

How it works?

About the application of ultrasonic sensor, we can directly check the subfunction.

float readSensorData(){// ...}
  • The trigPin of the ultrasonic module transmits a 10us square wave signal every 2us.

    // Trigger a low signal before sending a high signal
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    // Send a 10-microsecond high signal to the trigPin
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    // Return to low signal
    digitalWrite(trigPin, LOW);
    
  • The echoPin receives a high level signal if there is an obstacle within the range and use the pulseIn() function to record the time from sending to receiving.

    unsigned long microsecond = pulseIn(echoPin, HIGH);
    
  • The speed of sound is 340 meters per second, which is equivalent to 29 microseconds per centimeter. By measuring the time it takes for a square wave to travel to an obstacle and return, we can calculate the distance traveled by dividing the total time by 2. This gives us the distance of the obstacle from the source of the sound wave.

    float distance = microsecond / 29.00 / 2;
    

Note that the ultrasonic sensor will pause the program when it is working, which may cause some lagging when writing complex projects.

5.13 Temperature - Humidity

The DHT11 is a temperature and humidity sensor commonly used for environmental measurements. It is a digital sensor that communicates with a microcontroller to provide temperature and humidity readings.

In this project, we will be reading the DHT11 sensor and printing out the temperature and humidity values it detects.

By reading the data provided by the sensor, we can obtain the current temperature and humidity values in the environment. These values can be used for real-time monitoring of environmental conditions, weather observations, indoor climate control, humidity reports, and more.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

DHT11 Humiture Sensor

BUY

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_5.13_dht11.png

Wiring

_images/5.13_dht11_bb.png

Code

Note

  • Open the 5.13_dht11.ino file under the path of esp32-starter-kit-main\c\codes\5.13_dht11.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

  • The DHT sensor library library is used here, you can install it from the Library Manager.

    _images/dht_lib.png

After the code is uploaded successfully, you will see the Serial Monitor continuously print out the temperature and humidity, and as the program runs steadily, these two values will become more and more accurate.

How it works?

  1. Includes the DHT.h library, which provides functions to interact with the DHT sensors. Then, set the pin and type for the DHT sensor.

    #include "DHT.h"
    
    #define DHTPIN 14  // Set the pin connected to the DHT11 data pin
    #define DHTTYPE DHT11 // DHT 11
    
    DHT dht(DHTPIN, DHTTYPE);
    
  2. Initializes serial communication at a baud rate of 115200 and initializes the DHT sensor.

    void setup() {
        Serial.begin(115200);
        Serial.println("DHT11 test!");
        dht.begin();
    }
    
  3. In the loop() function, read temperature and humidity values from the DHT11 sensor, and print them to the serial monitor.

    void loop() {
        // Wait a few seconds between measurements.
        delay(2000);
    
        // Reading temperature or humidity takes about 250 milliseconds!
        // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
        float humidity = dht.readHumidity();
        // Read temperature as Celsius (the default)
        float temperture = dht.readTemperature();
    
        // Check if any reads failed and exit early (to try again).
        if (isnan(humidity) || isnan(temperture)) {
            Serial.println("Failed to read from DHT sensor!");
            return;
        }
        // Print the humidity and temperature
        Serial.print("Humidity: ");
        Serial.print(humidity);
        Serial.print(" %\t");
        Serial.print("Temperature: ");
        Serial.print(temperture);
        Serial.println(" *C");
    }
    
    • The dht.readHumidity() function is called to read the humidity value from the DHT sensor.

    • The dht.readTemperature() function is called to read the temperature value from the DHT sensor.

    • The isnan() function is used to check if the readings are valid. If either the humidity or temperature value is NaN (not a number), it indicates a failed reading from the sensor, and an error message is printed.

Learn More

You can also display the temperature and humidity on the I2C LCD1602.

Note

  • You can open the file 5.10_thermistor_lcd.ino under the path of euler-kit/arduino/5.10_thermistor_lcd.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

  • The LiquidCrystal_I2C and DHT sensor library libraries are used here, you can install them from the Library Manager.

5.14 IR Receiver

An infrared receiver is a component that receives infrared signals and can independently detect and output signals compatible with TTL level. It is similar in size to a regular plastic-packaged transistor and is commonly used in various applications such as infrared remote control and infrared transmission.

In this project, we will use an infrared receiver to detect signals from a remote control. When a button on the remote control is pressed and the infrared receiver receives the corresponding signal, it can decode the signal to determine which button was pressed. By decoding the received signal, we can identify the specific key or command associated with it.

The infrared receiver allows us to incorporate remote control functionality into our project, enabling us to interact with and control devices using infrared signals.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

IR Receiver

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO15, IO0, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_5.14_receiver.png

When you press a button on the remote control, the infrared receiver detects the signal, and you can use an infrared library to decode it. This decoding process allows you to obtain the key value associated with the button press.

Wiring

_images/5.14_ir_receiver_bb.png

Code

Note

  • Open the 5.14_ir_receiver.ino file under the path of esp32-starter-kit-main\c\codes\5.14_ir_receiver.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

  • The IRremoteESP8266 library is used here, you can install it from the Library Manager.

    _images/receiver_lib.png

After the code is uploaded successfully, press the different keys on the remote control and you will see the names of these keys appear in the serial monitor.

Note

  • The IRremoteESP8266 library includes implementations for many different infrared protocols and devices, so the size of the library is relatively large. When the compiler has to process more code, the compilation time will also increase accordingly. Please be patient and wait for the compilation to finish.

  • The new remote control features a plastic tab at the end to insulate the battery inside. To power up the remote when using it, simply remove this plastic piece.

How it works?

  1. This code uses the IRremoteESP8266 library to receive infrared (IR) signals using an IR receiver module.

    #include <IRremoteESP8266.h>
    #include <IRrecv.h>
    
    // Define the IR receiver pin
    const uint16_t IR_RECEIVE_PIN = 14;
    
    // Create an IRrecv object
    IRrecv irrecv(IR_RECEIVE_PIN);
    
    // Create a decode_results object
    decode_results results;
    
  2. In the setup() function, serial communication is started at a baud rate of 115200, and the IR receiver is enabled using irrecv.enableIRIn().

    void setup() {
        // Start serial communication
        Serial.begin(115200);
    
        // Start the IR receiver
        irrecv.enableIRIn();
    }
    
  3. When you press a key on the remote control, the serial monitor will print the key name if it is received by the IR receiver.

    void loop() {
        // If an IR signal is received
        if (irrecv.decode(&results)) {
            String key = decodeKeyValue(results.value);
            if (key != "ERROR") {
                // Print the value of the signal to the serial monitor
                Serial.println(key);
            }
            irrecv.resume(); // Continue to receive the next signal
        }
    }
    
    • Firstly, check if an IR signal is received using the irrecv.decode() function.

    • If a signal is received, then call the decodeKeyValue() function to decode the value of the signal.

    • If the signal is successfully decoded, the decoded value is printed to the serial monitor using Serial.println().

    • Finally, irrecv.resume() is called to continue to receive the next signal.

  4. The decodeKeyValue() function takes the decoded value of the IR signal as an argument and returns a string representing the key pressed on the remote control.

    String decodeKeyValue(long result)
    {
        switch(result){
            case 0xFF6897:
            return "0";
            case 0xFF30CF:
            return "1";
            case 0xFF18E7:
            return "2";
            case 0xFF7A85:
            ...
    
    • The function uses a switch statement to match the decoded value with the corresponding key and returns the string representation of the key.

    • If the decoded value does not match any known key, the function returns the string “ERROR”.

6. Funny Projects

6.1 Fruit Piano

Have you ever wanted to play the piano but couldn’t afford one? Or maybe you just want to have some fun with diy a fruit piano? Well, this project is for you!

With just a few touch sensors on the ESP32 board, you can now play your favorite tunes and enjoy the experience of playing the piano without breaking the bank.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Resistor

BUY

Buzzer

BUY

Transistor

BUY

About the Touch Pins

The ESP32 microcontroller has built-in touch sensor functionality, which allows you to use certain pins on the board as touch-sensitive inputs. The touch sensor works by measuring changes in capacitance on the touch pins, which are caused by the electrical properties of the human body.

Here are some key features of the touch sensor on the ESP32:

  • Number of touch pins

    The ESP32 has up to 10 touch pins, depending on the specific board. The touch pins are typically labeled with a “T” followed by a number.

    • GPIO4: TOUCH0

    • GPIO0:TOUCH1

    • GPIO2: TOUCH2

    • GPIO15: TOUCH3

    • GPIO13: TOUCH4

    • GPIO12: TOUCH5

    • GPIO14: TOUCH6

    • GPIO27: TOUCH7

    • GPIO33: TOUCH8

    • GPIO32: TOUCH9

    Note

    The GPIO0 and GPIO2 pins are used for bootstrapping and flashing firmware to the ESP32, respectively. These pins are also connected to the onboard LED and button. Therefore, it is generally not recommended to use these pins for other purposes, as it could interfere with the normal operation of the board.

  • Sensitivity

    The touch sensor on the ESP32 is very sensitive and can detect even small changes in capacitance. The sensitivity can be adjusted using software settings.

  • ESD Protection

    The touch pins on the ESP32 have built-in ESD (Electrostatic Discharge) protection, which helps to prevent damage to the board from static electricity.

  • Multitouch

    The touch sensor on the ESP32 supports multitouch, which means that you can detect multiple touch events simultaneously.

Schematic

_images/circuit_6.1_fruit_piano.png

The idea behind this project is to use touch sensors to detect when a user touches a specific pin. Each touch pin is associated with a specific note, and when the user touches a pin, the corresponding note is played on the passive buzzer. The result is a simple and affordable way to enjoy the experience of playing the piano.

Wiring

_images/6.1_fruit_piano_bb.png

In this project, you need to remove the ESP32 WROOM 32E from the expansion board and then insert it into the breadboard. This is because some pins on the expansion board are connected to resistors, which will affect the capacitance of the pins.

Code

Note

  • You can open the file 6.1_fruit_piano.ino under the path of esp32-starter-kit-main\c\codes\6.1_fruit_piano directly.

  • Or copy this code into Arduino IDE.

You can connect fruits to these ESP32 pins: 4, 15, 13, 12, 14, 27, 33, 32.

When the script runs, touching these fruits will play the notes C, D, E, F, G, A, B and C5.

How it works?

  • touchRead(uint8_t pin);

    This function gets the touch sensor data. Each touch sensor has a counter to count the number of charge/discharge cycles. When the pad is touched, the value in the counter will change because of the larger equivalent capacitance. The change of the data determines if the pad has been touched or not.

    • pin GPIO pin to read TOUCH value

    This function returns a value between 0 and 4095, with a lower value indicating a stronger touch input.

Note

threshold needs to be adjusted based on the conductivity of different fruits.

You can run the script first to see the values printed by the shell.

0: 60
1: 62
2: 71
3: 74
4: 73
5: 78
6: 80
7: 82

After touching the fruits on pins 12, 14, and 27, the printed values are as follows. Therefore, I set the threshold to 30, which means that when a value less than 30 is detected, it is considered to be touched, and the buzzer will emit different notes.

0: 60
1: 62
2: 71
3: 9
4: 12
5: 14
6: 75
7: 78

6.2 Flowing Light

Have you ever wanted to add some fun and interactive element to your living space? This project involves creating a running light using WS2812 LED strip and a obstacle avoidance module. The running light changes direction when an obstacle is detected, making it an exciting addition to your home or office decor.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Obstacle Avoidance Module

BUY

WS2812 RGB 8 LEDs Strip

BUY

Schematic Diagram

_images/circuit_6.2_flowing_led.png

The WS2812 LED strip is composed of a series of individual LEDs that can be programmed to display different colors and patterns. In this project, the strip is set up to display a running light that moves in a particular direction and changes direction when an obstacle is detected by the obstacle avoidance module.

Wiring

_images/6.2_flowing_light_bb.png

Code

Note

  • You can open the file 6.2_flowing_led.ino under the path of esp32-starter-kit-main\c\codes\6.2_flowing_led directly.

  • Or copy this code into Arduino IDE.

This project extends the functionality of the 2.7 RGB LED Strip project by adding the ability to display random colors on the LED strip. Additionally, an obstacle avoidance module has been included to dynamically change the direction of the running light.

6.3 Reversing Aid

Imagine this: You’re in your car, about to reverse into a tight parking spot. With our project, you will have an ultrasonic module mounted on the rear of your vehicle, acting as a digital eye. As you engage the reverse gear, the module springs to life, emitting ultrasonic pulses that bounce off obstacles behind you.

The magic happens when these pulses return to the module. It swiftly calculates the distance between your car and the objects, transforming this data into real-time visual feedback displayed on a vibrant LCD screen. You’ll witness dynamic, color-coded indicators depicting the proximity of obstacles, ensuring you have a crystal-clear understanding of the surrounding environment.

But we didn’t stop there. To immerse you further into this driving experience, we incorporated a lively buzzer. As your car inches closer to an obstacle, the buzzer’s tempo intensifies, creating an auditory symphony of warnings. It’s like having a personal orchestra guiding you through the complexities of reverse parking.

This innovative project combines cutting-edge technology with an interactive user interface, making your reversing experience safe and stress-free. With the ultrasonic module, LCD display, and lively buzzer working harmoniously, you’ll feel empowered and confident while maneuvering in tight spaces, leaving you free to focus on the joy of driving.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Ultrasonic Module

BUY

Buzzer

-

Transistor

BUY

I2C LCD1602

BUY

Schematic

_images/circuit_6.4_reversing_aid.png

The ultrasonic sensor in the project emits high-frequency sound waves and measures the time it takes for the waves to bounce back after hitting an object. By analyzing this data, the distance between the sensor and the object can be calculated. To provide a warning when the object is too close, a buzzer is used to produce an audible signal. Additionally, the measured distance is displayed on an LCD screen for easy visualization.

Wiring

_images/6.4_aid_ultrasonic_bb.png

Code

Note

  • You can open the file 6.3_reversing_aid.ino under the path of esp32-starter-kit-main\c\codes\6.3_reversing_aid directly.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

  • The LiquidCrystal I2C library is used here, you can install it from the Library Manager.

After the code is successfully uploaded, the current detected distance will be displayed on the LCD. Then the buzzer will change the sounding frequency according to different distances.

Note

If the code and wiring are correct, but the LCD still fails to display any content, you can adjust the potentiometer on the back to increase the contrast.

How it works?

This code helps us create a simple distance measuring device that can measure the distance between objects and provide feedback through an LCD display and a buzzer.

The loop() function contains the main logic of the program and runs continuously. Let’s take a closer look at the loop() function.

  1. Loop to read distance and update parameters

    In the loop, the code first reads the distance measured by the ultrasonic module and updates the interval parameter based on the distance.

    // Update the distance
    distance = readDistance();
    
    // Update intervals based on distance
    if (distance <= 10) {
        intervals = 300;
    } else if (distance <= 20) {
        intervals = 500;
    } else if (distance <= 50) {
        intervals = 1000;
    } else {
        intervals = 2000;
    }
    
  2. Check if it’s time to beep

    The code calculates the difference between the current time and the previous beep time, and if the difference is greater than or equal to the interval time, it triggers the buzzer and updates the previous beep time.

    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= intervals) {
        Serial.println("Beeping!");
        beep();
        previousMillis = currentMillis;
    }
    
  3. Update LCD display

    The code clears the LCD display and then displays “Dis:” and the current distance in centimeters on the first line.

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Dis: ");
    lcd.print(distance);
    lcd.print(" cm");
    
    delay(100);
    

6.4 Digital Dice

This project builds upon the 2.5 Number Display project by adding a button to control the digit displayed on the seven-segment display.

In this project, a random number is generated and displayed on the seven-segment display to simulate a dice roll. When the button is pressed, a stable number (randomly selected from 1 to 6) is displayed on the seven-segment display. Pressing the button again will initiate the simulation of a dice roll, generating random numbers as before. This cycle continues each time the button is pressed.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

74HC595

BUY

7-segment Display

BUY

Button

BUY

Schematic

_images/circuit_6.6_electronic_dice.png

This project builds upon the 2.5 7 Segment Display project by adding a button to control the digit displayed on the seven-segment display.

The button is directly connected to IO13 without an external pull-up or pull-down resistor because IO13 has an internal pull-up resistor of 47K, eliminating the need for an additional external resistor.

Wiring

_images/6.6_DICE_bb.png

Code

Note

  • Open the 6.4_digital_dice.ino file under the path of esp32-starter-kit-main\c\codes\6.4_digital_dice.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

This project is based on 2.5 7 Segment Display with a button to start/pause the scrolling display on the 7-segment Display.

When the button is pressed, the 7-segment display scrolls through the numbers 1-6, and when the button is released, it displays a random number.

6.5 Color Gradient

Are you ready to experience a world of color? This project will take you on a magical journey where you can control an RGB LED and achieve smooth color transitions. Whether you’re looking to add some color to your home decor or seeking a fun programming project, this project has got you covered. Let’s dive into this colorful world together!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Potentiometer

BUY

RGB LED

BUY

Schematic

_images/circuit_6.5_color_gradient_ar.png

Wiring

_images/rgb_pin.jpg

The RGB LED has 4 pins: the long pin is the common cathode pin, which is usually connected to GND; the left pin next to the longest pin is Red; and the two pins on the right are Green and Blue.

_images/6.5_color_rgb_bb.png

Code

Note

  • You can open the file 6.5_color_gradient.ino under the path of esp32-starter-kit-main\c\codes\6.5_color_gradient.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

This project uses an RGB LED and a potentiometer to create a color mixing effect. The potentiometer is used to adjust the hue value of the LED, which is then converted into RGB values using a color conversion function. The RGB values are then used to update the color of the LED.

How it works?

This project builds upon the 2.3 Colorful Light project by adding a potentiometer to adjust the hue value of the LED. The hue value is then converted to RGB values using a color conversion function.

  1. In the loop function, read the value of the potentiometer and convert it to a hue value (0-360).

    int knobValue = analogRead(KNOB_PIN);
    float hueValue = (float) knobValue / 4095.0;
    int hue = (int) (hueValue * 360);
    
  2. Convert the hue value to RGB values using the HUEtoRGB() function, and update the LED with the new color values.

    int red, green, blue;
    HUEtoRGB(hue, &red, &green, &blue);
    setColor(red, green, blue);
    
  3. The setColor() function sets the value of the red, green, and blue channels using the LEDC library.

    void setColor(int red, int green, int blue) {
        ledcWrite(redChannel, red);
        ledcWrite(greenChannel, green);
        ledcWrite(blueChannel, blue);
    }
    
  4. The HUEtoRGB function converts a hue value to RGB values using the HSL color model.

    void HUEtoRGB(int hue, int* red, int* green, int* blue) {
        float h = (float) hue / 60.0;
        float c = 1.0;
        float x = c * (1.0 - fabs(fmod(h, 2.0) - 1.0));
        float r, g, b;
        if (h < 1.0) {
            r = c;
            g = x;
            b = 0;
    ...
    

6.6 Plant Monitor

Welcome to the Plant Monitor project!

In this project, we will be using an ESP32 board to create a system that helps us take care of our plants. With this system, we can monitor the temperature, humidity, soil moisture, and light levels of our plants, and ensure that they are getting the care and attention they need to thrive.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

DHT11 Humiture Sensor

BUY

I2C LCD1602

BUY

Centrifugal Pump

-

L293D

-

Button

BUY

Photoresistor

BUY

Resistor

BUY

Soil Moisture Module

BUY

Schematic

_images/circuit_6.8_plant_monitor_l293d.png

The system uses a DHT11 sensor to measure the temperature and humidity levels of the surrounding environment. Meanwhile, a soil moisture module is used to measure the moisture level of the soil and a photoresistor is used to measure the light level. The readings from these sensors are displayed on an LCD screen, and a water pump can be controlled using a button to water the plant when needed.

IO32 has an internal pull-down resistor of 1K, and by default, it is at a low logic level. When the button is pressed, it establishes a connection to VCC (high voltage), resulting in a high logic level on IO32.

Wiring

Note

It is recommended here to insert the battery and then slide the switch on the expansion board to the ON position to activate the battery supply.

_images/6.8_plant_monitor_l293d_bb.png

Code

Note

  • You can open the file 6.6_plant_monitor.ino under the path of esp32-starter-kit-main\c\codes\6.6_plant_monitor.

  • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

  • Always displaying “Unknown COMxx”?

  • The LiquidCrystal_I2C and DHT sensor library libraries are used here, you can install them from the Library Manager.

  • After uploading the code, the I2C LCD1602 alternately displays temperature and humidity, as well as soil moisture and light intensity analog values, with a 2-second interval.

  • The water pump is controlled using a button press. To water the plants, hold down the button, and release it to stop watering.

Note

If the code and wiring are correct, but the LCD still fails to display any content, you can adjust the potentiometer on the back to increase the contrast.

6.7 Guess Number

Are you feeling lucky? Want to test your intuition and see if you can guess the right number? Then look no further than the Guess Number game!

With this project, you can play a fun and exciting game of chance.

Using an IR remote control, players input numbers between 0 and 99 to try and guess the randomly generated lucky point number. The system displays the player’s input number on an LCD screen, along with upper and lower limit tips to help guide the player towards the right answer. With every guess, players get closer to the lucky point number, until finally, someone hits the jackpot and wins the game!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

IR Receiver

BUY

I2C LCD1602

BUY

Schematic

_images/circuit_6.7_guess_number.png

Wiring

_images/6.7_guess_receiver_bb.png

Code

Note

  • You can open the file 6.7_guess_number.ino under the path of esp32-starter-kit-main\c\codes\6.7_guess_number directly.

  • The LiquidCrystal_I2C and IRremoteESP8266 libraries are used here, refer to Manual Installation for a tutorial to install.

  • After the code is successfully uploaded, press any number button on the remote control to start the game.

  • Input a number using the number buttons on the remote control. To input a single digit, you need to press the cycle key to confirm.

  • The system will show the input number and the upper and lower limit tips on the LCD screen.

  • Keep guessing until you correctly guess the lucky point number.

  • After a successful guess, the system will show a success message and generate a new lucky point number.

Note

If the code and wiring are correct, but the LCD still fails to display any content, you can adjust the potentiometer on the back to increase the contrast.

How it works?

  1. In the setup() function, the I2C LCD screen and IR receiver are initialized. Then call the initNewValue() function to generate a new random lucky number, and a welcome message is displayed on the LCD screen.

    void setup() {
        // Initialize the LCD screen
        lcd.init();
        lcd.backlight();
    
        // Start the serial communication
        Serial.begin(9600);
    
        // Enable the IR receiver
        irrecv.enableIRIn();
    
        // Initialize a new lucky point value
        initNewValue();
    }
    
  2. In the loop function, the code waits for a signal from the IR receiver. When a signal is received, the decodeKeyValue function is called to decode the signal and get the corresponding button value.

    void loop() {
    // If a signal is received from the IR receiver
    if (irrecv.decode(&results)) {
        bool result = 0;
        String num = decodeKeyValue(results.value);
    
        // If the POWER button is pressed
        if (num == "POWER") {
            initNewValue(); // Initialize a new lucky point value
        }
    
        // If the CYCLE button is pressed
        else if (num == "CYCLE") {
            result = detectPoint(); // Detect the input number
            lcdShowInput(result); // Show the result on the LCD screen
        }
    
        // If a number button (0-9) is pressed,
        //add the digit to the input number
        //and detect the number if it is greater than or equal to 10
        else if (num >= "0" && num <= "9") {
            count = count * 10;
            count += num.toInt();
            if (count >= 10) {
                result = detectPoint();
            }
            lcdShowInput(result);
        }
        irrecv.resume();
    }
    }
    
    • Depending on the button value, the appropriate function is called. If a number button is pressed, the count variable is updated, and the detectPoint function is called to detect if the input number is correct. The lcdShowInput function is called to show the input number and the upper and lower limit tips on the LCD screen.

    • If the POWER button is pressed, the initNewValue function is called to generate a new lucky point number and show the welcome message on the LCD screen.

    • If the CYCLE button is pressed, the detectPoint function is called to detect if the input number is correct. The lcdShowInput function is called to show the input number and the upper and lower limit tips on the LCD screen.

7. Bluetooth&SD Card&Camera&Speaker

7.1 Bluetooth

This project provides a guide to develop a simple Bluetooth Low Energy (BLE) serial communication application using the ESP32 microcontroller. The ESP32 is a powerful microcontroller that integrates Wi-Fi and Bluetooth connectivity, making it an ideal candidate for developing wireless applications. BLE is a low-power wireless communication protocol that is designed for short-range communication. This document will cover the steps to set up the ESP32 to act as a BLE server and communicate with a BLE client over a serial connection.

About the Bluetooth Function

The ESP32 WROOM 32E is a module that integrates Wi-Fi and Bluetooth connectivity into a single chip. It supports Bluetooth Low Energy (BLE) and Classic Bluetooth protocols.

The module can be used as a Bluetooth client or server. As a Bluetooth client, the module can connect to other Bluetooth devices and exchange data with them. As a Bluetooth server, the module can provide services to other Bluetooth devices.

The ESP32 WROOM 32E supports various Bluetooth profiles, including the Generic Access Profile (GAP), Generic Attribute Profile (GATT), and Serial Port Profile (SPP). The SPP profile allows the module to emulate a serial port over Bluetooth, enabling serial communication with other Bluetooth devices.

To use the Bluetooth function of the ESP32 WROOM 32E, you need to program it using an appropriate software development kit (SDK) or using the Arduino IDE with the ESP32 BLE library. The ESP32 BLE library provides a high-level interface for working with BLE. It includes examples that demonstrate how to use the module as a BLE client and server.

Overall, the Bluetooth function of the ESP32 WROOM 32E provides a convenient and low-power way to enable wireless communication in your projects.

Operation Steps

Here are the step-by-step instructions to set up Bluetooth communication between your ESP32 and mobile device using the LightBlue app:

  1. Download the LightBlue app from the App Store (for iOS) or Google Play (for Android).

    _images/bluetooth_lightblue.png
  2. Open the 7.1_bluetooth.ino file located in the esp32-starter-kit-main\c\codes\7.1_bluetooth directory, or copy the code into the Arduino IDE.

  3. To avoid UUID conflicts, it is recommended to randomly generate three new UUIDs using the Online UUID Generator, and fill them in the following lines of code.

    #define SERVICE_UUID           "your_service_uuid_here"
    #define CHARACTERISTIC_UUID_RX "your_rx_characteristic_uuid_here"
    #define CHARACTERISTIC_UUID_TX "your_tx_characteristic_uuid_here"
    
    _images/uuid_generate.png
  4. Select the correct board and port, then click the Upload button.

    _images/bluetooth_upload.png
  5. After the code has been successfully uploaded, turn on Bluetooth on your mobile device and open the LightBlue app.

    _images/bluetooth_open.png
  6. On the Scan page, find ESP32-Bluetooth and click CONNECT. If you don’t see it, try refreshing the page a few times. When “Connected to device!” appears, the Bluetooth connection is successful. Scroll down to see the three UUIDs set in the code.

    _images/bluetooth_connect.png
  7. Click the Receive UUID. Select the appropriate data format in the box to the right of Data Format, such as “HEX” for hexadecimal, “UTF-8 String” for character, or “Binary” for binary, etc. Then click SUBSCRIBE.

    _images/bluetooth_read.png
  8. Go back to the Arduino IDE, open the Serial Monitor, set the baud rate to 115200, then type “welcome” and press Enter.

    _images/bluetooth_serial.png
  9. You should now see the “welcome” message in the LightBlue app.

    _images/bluetooth_welcome.png
  10. To send information from the mobile device to the Serial Monitor, click the Send UUID, set the data format to “UTF-8 String”, and write a message.

    _images/bluetooth_send.png
  11. You should see the message in the Serial Monitor.

    _images/bluetooth_receive.png

How it works?

This Arduino code is written for the ESP32 microcontroller and sets it up to communicate with a Bluetooth Low Energy (BLE) device.

The following is a brief summary of the code:

  • Include necessary libraries: The code begins by including necessary libraries for working with Bluetooth Low Energy (BLE) on the ESP32.

    #include "BLEDevice.h"
    #include "BLEServer.h"
    #include "BLEUtils.h"
    #include "BLE2902.h"
    
  • Global Variables: The code defines a set of global variables including the Bluetooth device name (bleName), variables to keep track of received text and the time of the last message, UUIDs for the service and characteristics, and a BLECharacteristic object (pCharacteristic).

    // Define the Bluetooth device name
    const char *bleName = "ESP32_Bluetooth";
    
    // Define the received text and the time of the last message
    String receivedText = "";
    unsigned long lastMessageTime = 0;
    
    // Define the UUIDs of the service and characteristics
    #define SERVICE_UUID           "your_service_uuid_here"
    #define CHARACTERISTIC_UUID_RX "your_rx_characteristic_uuid_here"
    #define CHARACTERISTIC_UUID_TX "your_tx_characteristic_uuid_here"
    
    // Define the Bluetooth characteristic
    BLECharacteristic *pCharacteristic;
    
  • Setup: In the setup() function, the serial port is initialized with a baud rate of 115200 and the setupBLE() function is called to set up the Bluetooth BLE.

    void setup() {
        Serial.begin(115200);  // Initialize the serial port
        setupBLE();            // Initialize the Bluetooth BLE
    }
    
  • Main Loop: In the loop() function, if a string was received over BLE (i.e., receivedText is not empty) and at least 1 second has passed since the last message, the code prints the received string to the serial monitor, sets the characteristic value to the received string, sends a notification, and then clears the received string. If data is available on the serial port, it reads the string until a newline character is encountered, sets the characteristic value to this string, and sends a notification.

    void loop() {
        // When the received text is not empty and the time since the last message is over 1 second
        // Send a notification and print the received text
        if (receivedText.length() > 0 && millis() - lastMessageTime > 1000) {
            Serial.print("Received message: ");
            Serial.println(receivedText);
            pCharacteristic->setValue(receivedText.c_str());
            pCharacteristic->notify();
            receivedText = "";
        }
    
        // Read data from the serial port and send it to BLE characteristic
        if (Serial.available() > 0) {
            String str = Serial.readStringUntil('\n');
            const char *newValue = str.c_str();
            pCharacteristic->setValue(newValue);
            pCharacteristic->notify();
        }
    }
    
  • Callbacks: Two callback classes (MyServerCallbacks and MyCharacteristicCallbacks) are defined to handle events related to Bluetooth communication. MyServerCallbacks is used to handle events related to the connection state (connected or disconnected) of the BLE server. MyCharacteristicCallbacks is used to handle write events on the BLE characteristic, i.e., when a connected device sends a string to the ESP32 over BLE, it’s captured and stored in receivedText, and the current time is recorded in lastMessageTime.

    // Define the BLE server callbacks
    class MyServerCallbacks : public BLEServerCallbacks {
        // Print the connection message when a client is connected
        void onConnect(BLEServer *pServer) {
        Serial.println("Connected");
        }
        // Print the disconnection message when a client is disconnected
        void onDisconnect(BLEServer *pServer) {
        Serial.println("Disconnected");
        }
    };
    
    // Define the BLE characteristic callbacks
    class MyCharacteristicCallbacks : public BLECharacteristicCallbacks {
        void onWrite(BLECharacteristic *pCharacteristic) {
            // When data is received, get the data and save it to receivedText, and record the time
            std::string value = pCharacteristic->getValue();
            receivedText = String(value.c_str());
            lastMessageTime = millis();
            Serial.print("Received: ");
            Serial.println(receivedText);
        }
    };
    
  • Setup BLE: In the setupBLE() function, the BLE device and server are initialized, the server callbacks are set, the BLE service is created using the defined UUID, characteristics for sending notifications and receiving data are created and added to the service, and the characteristic callbacks are set. Finally, the service is started and the server begins advertising.

    // Initialize the Bluetooth BLE
    void setupBLE() {
        BLEDevice::init(bleName);                        // Initialize the BLE device
        BLEServer *pServer = BLEDevice::createServer();  // Create the BLE server
        // Print the error message if the BLE server creation fails
        if (pServer == nullptr) {
            Serial.println("Error creating BLE server");
            return;
        }
        pServer->setCallbacks(new MyServerCallbacks());  // Set the BLE server callbacks
    
        // Create the BLE service
        BLEService *pService = pServer->createService(SERVICE_UUID);
        // Print the error message if the BLE service creation fails
        if (pService == nullptr) {
            Serial.println("Error creating BLE service");
            return;
        }
        // Create the BLE characteristic for sending notifications
        pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID_TX, BLECharacteristic::PROPERTY_NOTIFY);
        pCharacteristic->addDecodeor(new BLE2902());  // Add the decodeor
        // Create the BLE characteristic for receiving data
        BLECharacteristic *pCharacteristicRX = pService->createCharacteristic(CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE);
        pCharacteristicRX->setCallbacks(new MyCharacteristicCallbacks());  // Set the BLE characteristic callbacks
        pService->start();                                                 // Start the BLE service
        pServer->getAdvertising()->start();                                // Start advertising
        Serial.println("Waiting for a client connection...");              // Wait for a client connection
    }
    

Please note that this code allows for bidirectional communication - it can send and receive data via BLE. However, to interact with specific hardware like turning on/off an LED, additional code should be added to process the received strings and act accordingly.

7.2 Bluetooth Control RGB LED

This project is an extension of a previous project(7.1 Bluetooth), adding RGB LED configurations and custom commands such as “led_off”, “red”, “green”, etc. These commands allow the RGB LED to be controlled by sending commands from a mobile device using LightBlue.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

RGB LED

BUY

Operation Steps

  1. Build the circuit.

    _images/rgb_pin.jpg

    The RGB LED has 4 pins: the long pin is the common cathode pin, which is usually connected to GND; the left pin next to the longest pin is Red; and the two pins on the right are Green and Blue.

    _images/2.3_color_light_bb.png
  2. Open the 7.2_bluetooth_rgb_led.ino file located in the esp32-starter-kit-main\c\codes\7.2_bluetooth_rgb_led directory, or copy the code into the Arduino IDE.

  3. To avoid UUID conflicts, it is recommended to randomly generate three new UUIDs using the Online UUID Generator provided by the Bluetooth SIG, and fill them in the following lines of code.

    Note

    If you have already generated three new UUIDs in the 7.1 Bluetooth project, then you can continue using them.

    #define SERVICE_UUID           "your_service_uuid_here"
    #define CHARACTERISTIC_UUID_RX "your_rx_characteristic_uuid_here"
    #define CHARACTERISTIC_UUID_TX "your_tx_characteristic_uuid_here"
    
    _images/uuid_generate.png
  4. Select the correct board and port, then click the Upload button.

  5. After the code has been successfully uploaded, turn on Bluetooth on your mobile device and open the LightBlue app.

    _images/bluetooth_open.png
  6. On the Scan page, find ESP32-Bluetooth and click CONNECT. If you don’t see it, try refreshing the page a few times. When “Connected to device!” appears, the Bluetooth connection is successful. Scroll down to see the three UUIDs set in the code.

    _images/bluetooth_connect.png
  7. Tap the Send UUID, then set the data format to “UTF-8 String”. Now you can write these commands: “led_off”, “red”, “green”, “blue”, “yellow”, and “purple” to see if the RGB LED responds to these instructions.

    _images/bluetooth_send_rgb.png

How it works?

This code is an extension of a previous project(7.1 Bluetooth), adding RGB LED configurations and custom commands such as “led_off”, “red”, “green”, etc. These commands allow the RGB LED to be controlled by sending commands from a mobile device using LightBlue.

Let’s break down the code step by step:

  • Add new global variables for the RGB LED pins, PWM channels, frequency, and resolution.

    ...
    
    // Define RGB LED pins
    const int redPin = 27;
    const int greenPin = 26;
    const int bluePin = 25;
    
    // Define PWM channels
    const int redChannel = 0;
    const int greenChannel = 1;
    const int blueChannel = 2;
    
    ...
    
  • Within the setup() function, the PWM channels are initialized with the predefined frequency and resolution. The RGB LED pins are then attached to their respective PWM channels.

    void setup() {
        ...
    
        // Set up PWM channels
        ledcSetup(redChannel, freq, resolution);
        ledcSetup(greenChannel, freq, resolution);
        ledcSetup(blueChannel, freq, resolution);
    
        // Attach pins to corresponding PWM channels
        ledcAttachPin(redPin, redChannel);
        ledcAttachPin(greenPin, greenChannel);
        ledcAttachPin(bluePin, blueChannel);
    
    }
    
  • Modify the onWrite method in the MyCharacteristicCallbacks class. This function listens for data coming from the Bluetooth connection. Based on the received string (like "led_off", "red", "green", etc.), it controls the RGB LED.

    // Define the BLE characteristic callbacks
    class MyCharacteristicCallbacks : public BLECharacteristicCallbacks {
        void onWrite(BLECharacteristic *pCharacteristic) {
            std::string value = pCharacteristic->getValue();
            if (value == "led_off") {
                setColor(0, 0, 0); // turn the RGB LED off
                Serial.println("RGB LED turned off");
            } else if (value == "red") {
                setColor(255, 0, 0); // Red
                Serial.println("red");
            }
            else if (value == "green") {
                setColor(0, 255, 0); // green
                Serial.println("green");
            }
            else if (value == "blue") {
                setColor(0, 0, 255); // blue
                Serial.println("blue");
            }
            else if (value == "yellow") {
                setColor(255, 150, 0); // yellow
                Serial.println("yellow");
            }
            else if (value == "purple") {
                setColor(80, 0, 80); // purple
                Serial.println("purple");
            }
        }
    };
    
  • Finally, a function is added to set the RGB LED color.

    void setColor(int red, int green, int blue) {
        // For common-anode RGB LEDs, use 255 minus the color value
        ledcWrite(redChannel, red);
        ledcWrite(greenChannel, green);
        ledcWrite(blueChannel, blue);
    }
    

In summary, this script enables a remote control interaction model, where the ESP32 operates as a Bluetooth Low Energy (BLE) server.

The connected BLE client (like a smartphone) can send string commands to change the color of an RGB LED. The ESP32 also gives feedback to the client by sending back the string received, allowing the client to know what operation was performed.

7.3 Bluetooth Audio Player

The aim of the project is to provide a simple solution for playing audio from a Bluetooth-enabled device using the built-in DAC of the ESP32.

The project involves the use of the ESP32-A2DP library to receive audio data from a Bluetooth-enabled device. The received audio data is then transmitted to the internal DAC of the ESP32 using the I2S interface. The I2S interface is configured to operate in master mode, transmit mode, and DAC built-in mode. The audio data is then played back through the speaker connected to the DAC.

When using the internal DAC of the ESP32, it is important to note that the output voltage level is limited to 1.1V. Therefore, it is recommended to use an external amplifier to boost the output voltage level to the desired level. It is also important to ensure that the audio data is in the correct format and sample rate to prevent distortion or noise during playback.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Audio Module and Speaker

-

Operating Steps

  1. Build the circuit.

    As this is a mono amplifier, you can connect IO25 to the L or R pin of the audio amplifier module.

    The 10K resistor is used to reduce high-frequency noise and lower the audio volume. It forms an RC low-pass filter with the parasitic capacitance of the DAC and audio amplifier. This filter decreases the amplitude of high-frequency signals, effectively reducing high-frequency noise. So, adding the 10K resistor makes the music sound softer and eliminates unwanted high-frequency noise.

    If your SD card’s music is already soft, you can remove or replace the resistor with a smaller value.

    _images/7.3_bluetooth_audio_player_bb.png
  2. Open the code.

    • Open the 7.3_bluetooth_audio_player.ino file under the path of esp32-starter-kit-main\c\codes\7.3_bluetooth_audio_player.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

    • The ESP32-A2DP library is used here, refer to Manual Installation for a tutorial to install.

  3. After selecting the correct board and port, click on the Upload button.

  4. Once the code is uploaded successfully, turn on the Bluetooth-enabled device and search for available devices, then connect to the ESP32_Bluetooth.

    _images/connect_bluetooth.png
  5. Play audio on the device and the audio should be played through the speaker connected to the ESP32.

Code Explanation

  1. The code starts by including the BluetoothA2DPSink.h library, which is used to receive audio data from the Bluetooth-enabled device. The BluetoothA2DPSink object is then created and configured with the I2S interface settings.

    #include "BluetoothA2DPSink.h"
    
    BluetoothA2DPSink a2dp_sink;
    
  2. In the setup function, the code initializes an i2s_config_t struct with the desired configuration for the I2S (Inter-IC Sound) interface.

    void setup() {
    const i2s_config_t i2s_config = {
        .mode = (i2s_mode_t) (I2S_MODE_MASTER | I2S_MODE_TX | I2S_MODE_DAC_BUILT_IN),
        .sample_rate = 44100, // corrected by info from bluetooth
        .bits_per_sample = (i2s_bits_per_sample_t) 16, // the DAC module will only take the 8bits from MSB
        .channel_format =  I2S_CHANNEL_FMT_RIGHT_LEFT,
        .communication_format = (i2s_comm_format_t)I2S_COMM_FORMAT_STAND_MSB,
        .intr_alloc_flags = 0, // default interrupt priority
        .dma_buf_count = 8,
        .dma_buf_len = 64,
        .use_apll = false
    };
    
    a2dp_sink.set_i2s_config(i2s_config);
    a2dp_sink.start("ESP32_Bluetooth");
    
    }
    
    • The I2S interface is used to transfer digital audio data between devices.

    • The configuration includes the I2S mode, sample rate, bits per sample, channel format, communication format, interrupt allocation flags, DMA buffer count, DMA buffer length, and whether to use the APLL (Audio PLL) or not.

    • The i2s_config_t struct is then passed as an argument to the set_i2s_config function of the BluetoothA2DPSink object to configure the I2S interface for audio playback.

    • The start function of the BluetoothA2DPSink object is called to start the Bluetooth audio sink and begin playing audio through the built-in DAC.

7.4 SD Card Write and Read

This project demonstrates the core capabilities of using an SD card with the ESP32 microcontroller. It showcases essential operations such as mounting the SD card, creating a file, writing data to the file, and listing all files within the root directory. These operations form the basis of many data logging and storage applications, making this project a crucial stepping stone in understanding and utilizing the ESP32’s built-in SDMMC host peripheral.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Operating Steps

  1. Before connecting the USB cable, insert the SD card into the SD card slot of the extension board.

    _images/insert_sd.png
  2. Connect ESP32-WROOM-32E to the computer using the USB cable.

    _images/plugin_esp32.png
  3. Select the appropriate port and board in the Arduino IDE and upload the code to your ESP32.

    Note

    • Open the 7.4_sd_read_write.ino file under the path of esp32-starter-kit-main\c\codes\7.4_sd_read_write.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

  4. After the code is uploaded successfully, you will see a prompt indicating the successful file write, along with a list of all the filenames and sizes on the SD card. If you don’t see any printout after opening the serial monitor, you need to press the EN (RST) button to rerun the code.

    _images/sd_write_read.png

    Note

    If you see the following information.

    E (528) vfs_fat_sdmmc: mount_to_vfs failed (0xffffffff).
    Failed to mount SD card
    

    First, check if your SD card is properly inserted into the expansion board.

    If it is inserted correctly, there might be an issue with your SD card. You can try using an eraser to clean the metal contacts.

    If the problem persists, it is recommended to format the SD card, please refer to How to format the SD card?.

How it works?

The purpose of this project is to demonstrate the usage of the SD card with the ESP32 board. The ESP32’s built-in SDMMC host peripheral is used to connect with the SD card.

The project begins by initializing the serial communication and then attempts to mount the SD card. If the SD card fails to mount successfully, the program will print an error message and exit the setup function.

Once the SD card is mounted successfully, the program proceeds to create a file named “test.txt” in the root directory of the SD card. If the file is successfully opened in write mode, the program writes a line of text - “Hello, world!” to the file. The program will print a success message if the write operation is successful, otherwise, an error message will be printed.

After the writing operation is complete, the program closes the file and then opens the root directory of the SD card. It then begins to loop through all the files in the root directory, printing the filename and filesize of each file found.

In the main loop function, there are no operations. This project focuses on SD card operations such as mounting the card, creating a file, writing to a file, and reading the file directory, all of which are executed in the setup function.

This project serves as a useful introduction to handling SD cards with the ESP32, which can be crucial in applications that require data logging or storage.

Here’s an analysis of the code:

  1. Include the SD_MMC library, which is needed to work with SD cards using ESP32’s built-in SDMMC host peripheral.

    #include "SD_MMC.h"
    
  2. Inside the setup() function, the following tasks are performed.

    • Initialize the SD card

    Initialize and mount the SD card. If the SD card fails to mount, it will print “Failed to mount SD card” to the serial monitor and stop the execution.

    if(!SD_MMC.begin()) { // Attempt to mount the SD card
        Serial.println("Failed to mount card"); // If mount fails, print to serial and exit setup
        return;
    }
    
    • Open the file

    Open a file named "test.txt" located in the root directory of the SD card in write mode. If the file fails to open, it prints “Failed to open file for writing” and returns.

    File file = SD_MMC.open("/test.txt", FILE_WRITE);
    if (!file) {
        Serial.println("Failed to open file for writing"); // Print error message if file failed to open
        return;
    }
    
    • Write data to the file

    Write the text “Test file write” to the file. If the write operation is successful, it prints “File write successful”; otherwise, it prints “File write failed”.

    if(file.print("Test file write")) { // Write the message to the file
        Serial.println("File write success"); // If write succeeds, print to serial
    } else {
        Serial.println("File write failed"); // If write fails, print to serial
    }
    
    • Close the file

    Close the opened file. This ensures that any buffered data is written to the file and the file is properly closed.

    file.close(); // Close the file
    
    • Open the root directory

    Open the root directory of the SD card. If the directory fails to open, it prints “Failed to open directory” and returns.

    File root = SD_MMC.open("/"); // Open the root directory of SD card
    if (!root) {
        Serial.println("Failed to open directory"); // Print error message if directory failed to open
        return;
    }
    
    • Print each file’s name and size

    The loop starting with while (File file = root.openNextFile()) iterates over all the files in the root directory, printing each file’s name and size to the serial monitor.

    Serial.println("Files found in root directory:"); // Print the list of files found in the root directory
    while (File file = root.openNextFile()) { // Loop through all the files in the root directory
          Serial.print("  ");
          Serial.print(file.name()); // Print the filename
          Serial.print("\t");
          Serial.println(file.size()); // Print the filesize
          file.close(); // Close the file
    }
    
  3. This loop() function is an empty loop and does nothing in the current program. However, in a typical Arduino program, this function would continuously loop over and execute the code within it. In this case, since all the required tasks have been performed in the setup function, the loop function is not needed.

    void loop() {} // Empty loop function, does nothing
    

7.5 MP3 Player with SD Card Support

Welcome to the exciting world of music with your ESP32! This project brings the power of audio processing to your fingertips, making your ESP32 not just an amazing microcontroller for computing but also your personalized music player. Imagine walking into your room and having your favorite track playing right from this tiny device. That’s the power we’re bringing to your hands today.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Audio Module and Speaker

-

Operating Steps

  1. Insert your SD card into the computer using a card reader, and then format it. You can refer to the tutorial at How to format the SD card?.

  2. Copy your favorite MP3 file to your SD card.

    _images/mp3_music.png
  3. Insert the SD card into the SD card slot of the extension board.

    _images/insert_sd.png
  4. Build the circuit.

    As this is a mono amplifier, you can connect IO25 to the L or R pin of the audio amplifier module.

    The 10K resistor is used to reduce high-frequency noise and lower the audio volume. It forms an RC low-pass filter with the parasitic capacitance of the DAC and audio amplifier. This filter decreases the amplitude of high-frequency signals, effectively reducing high-frequency noise. So, adding the 10K resistor makes the music sound softer and eliminates unwanted high-frequency noise.

    If your SD card’s music is already soft, you can remove or replace the resistor with a smaller value.

    _images/7.3_bluetooth_audio_player_bb.png
  5. Connect ESP32-WROOM-32E to the computer using the USB cable.

    _images/plugin_esp32.png
  6. Modify the code.

    Modify the line of code file = new AudioFileSourceSD_MMC("/To Alice.mp3"); to reflect your file’s name and path.

    Note

    • Open the 7.5_mp3_player_sd.ino file under the path of esp32-starter-kit-main\c\codes\7.5_mp3_player_sd. Or copy this code into Arduino IDE.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

    • The ESP8266Audio library is used here, refer to Manual Installation for a tutorial to install.

  7. Select the appropriate port and board in the Arduino IDE and upload the code to your ESP32.

  8. After successfully uploading the code, you will hear your favorite music playing.

How it works?

  • The code uses several classes from the ESP8266Audio library to play an MP3 file from an SD card through I2S:

    #include "AudioFileSourceSD_MMC.h"
    #include "AudioOutputI2S.h"
    #include "AudioGeneratorMP3.h"
    #include "SD_MMC.h"
    #include "FS.h"
    
    • AudioGeneratorMP3 is a class that decodes MP3 audio.

    • AudioFileSourceSD_MMC is a class that reads audio data from an SD card.

    • AudioOutputI2S is a class that sends audio data to the I2S interface.

  • In the setup() function, we initialize the SD card, open the MP3 file from the SD card, set up the I2S output on the ESP32’s internal DAC, set the output to mono, and start the MP3 generator.

    void setup() {
        // Start the serial communication.
        Serial.begin(115200);
        delay(1000);
    
        // Initialize the SD card. If it fails, print an error message.
        if (!SD_MMC.begin()) {
            Serial.println("SD card mount failed!");
        }
    
        // Open the MP3 file from the SD card. Replace "/To Alice.mp3" with your own MP3 file name.
        file = new AudioFileSourceSD_MMC("/To Alice.mp3");
    
        // Set up the I2S output on ESP32's internal DAC.
        out = new AudioOutputI2S(0, 1);
    
        // Set the output to mono.
        out->SetOutputModeMono(true);
    
        // Initialize the MP3 generator with the file and output.
        mp3 = new AudioGeneratorMP3();
        mp3->begin(file, out);
    }
    
  • In the loop() function, we check if the MP3 generator is running. If it is, we continue looping it; otherwise, we stop it and print “MP3 done” to the serial monitor.

    void loop() {
        // If the MP3 is running, loop it. Otherwise, stop it.
        if (mp3->isRunning()) {
            if (!mp3->loop()) mp3->stop();
        }
        // If the MP3 is not running, print a message and wait for 1 second.
        else {
            Serial.println("MP3 done");
            delay(1000);
        }
    }
    

7.6 Take Photo SD

This document describes a project that involves taking a photo using the ESP32-CAM and saving it to an SD card. The aim of the project is to provide a simple solution for capturing images using the ESP32-CAM and storing them on an SD card.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Related Precautions

When using the ESP32-CAM, it is important to note that the GPIO 0 pin must be connected to GND to upload a sketch. Additionally, after connecting GPIO 0 to GND, the ESP32-CAM onboard RESET button must be pressed to put the board in flashing mode. It is also important to ensure that the SD card is properly mounted before saving images to it.

Operating Steps

  1. Insert your SD card into the computer using a card reader, and then format it. You can refer to the tutorial at How to format the SD card?.

  2. Then, remove the card reader and insert the SD card into the expansion board.

    _images/insert_sd.png
  3. Now, plug in the camera.

  4. Connect ESP32-WROOM-32E to the computer using the USB cable.

    _images/plugin_esp32.png
  5. Open the code.

    Note

    • Open the 7.6_take_photo_sd.ino file under the path of esp32-starter-kit-main\c\codes\7.6_take_photo_sd.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

  6. Now, enable PSRAM.

    _images/sp230516_150554.png
  7. Set the partition scheme to Huge APP (3MB No OTA/1MB SPIFFS).

    _images/sp230516_150840.png
  8. Select the appropriate port and board in the Arduino IDE and upload the code to your ESP32.

  9. After the successful upload of the code, press the Reset button to take a photo. Additionally, you can check the Serial Monitor to see the following information indicating the successful capture.

    Picture file name: /picture9.jpg
    Saved file to path: /picture9.jpg
    Going to sleep now
    
    _images/press_reset.png
  10. Now, remove the SD card from the expansion board and insert it into your computer. You will be able to view the photos you just took.

    _images/take_photo1.png

How it works?

This code operates an AI Thinker ESP32-CAM to take a photo, save it to an SD card, and then put the ESP32-CAM into deep sleep. Here is a breakdown of the key parts:

  • Libraries: The code starts with the inclusion of the necessary libraries for the ESP32-CAM, file system (FS), SD card, and EEPROM (used for storing data across power cycles).

    #include "esp_camera.h"
    #include "Arduino.h"
    #include "FS.h"                // SD Card ESP32
    #include "SD_MMC.h"            // SD Card ESP32
    #include "soc/soc.h"           // Disable brownour problems
    #include "soc/rtc_cntl_reg.h"  // Disable brownour problems
    #include "driver/rtc_io.h"
    #include <EEPROM.h>  // read and write from flash memory
    
  • Pin Definitions: This section sets up constants that represent the ESP32-CAM’s pin connections to the camera module.

    #define PWDN_GPIO_NUM 32
    #define RESET_GPIO_NUM -1
    #define XCLK_GPIO_NUM 0
    #define SIOD_GPIO_NUM 26
    #define SIOC_GPIO_NUM 27
    
    #define Y9_GPIO_NUM 35
    #define Y8_GPIO_NUM 34
    #define Y7_GPIO_NUM 39
    #define Y6_GPIO_NUM 36
    #define Y5_GPIO_NUM 21
    #define Y4_GPIO_NUM 19
    #define Y3_GPIO_NUM 18
    #define Y2_GPIO_NUM 5
    #define VSYNC_GPIO_NUM 25
    #define HREF_GPIO_NUM 23
    #define PCLK_GPIO_NUM 22
    
  • Global Variables: A global variable pictureNumber is declared to keep track of the number of pictures taken and saved to the SD card.

    int pictureNumber = 0;
    
  • Setup Function: In the setup() function, several tasks are accomplished:

    • First, the brown-out detector is disabled to prevent the ESP32-CAM from resetting during high current draws (like when the camera is operating).

      WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);  //disable brownout detector
      
    • The Serial communication is initialized for debugging.

      Serial.begin(115200);
      
    • The camera configuration is set up with camera_config_t, including the GPIO pins, XCLK frequency, pixel format, frame size, jpeg quality, and framebuffer count.

      camera_config_t config;
      config.ledc_channel = LEDC_CHANNEL_0;
      config.ledc_timer = LEDC_TIMER_0;
      config.pin_d0 = Y2_GPIO_NUM;
      config.pin_d1 = Y3_GPIO_NUM;
      config.pin_d2 = Y4_GPIO_NUM;
      config.pin_d3 = Y5_GPIO_NUM;
      config.pin_d4 = Y6_GPIO_NUM;
      config.pin_d5 = Y7_GPIO_NUM;
      config.pin_d6 = Y8_GPIO_NUM;
      config.pin_d7 = Y9_GPIO_NUM;
      config.pin_xclk = XCLK_GPIO_NUM;
      config.pin_pclk = PCLK_GPIO_NUM;
      config.pin_vsync = VSYNC_GPIO_NUM;
      config.pin_href = HREF_GPIO_NUM;
      config.pin_sscb_sda = SIOD_GPIO_NUM;
      config.pin_sscb_scl = SIOC_GPIO_NUM;
      config.pin_pwdn = PWDN_GPIO_NUM;
      config.pin_reset = RESET_GPIO_NUM;
      config.xclk_freq_hz = 20000000;
      config.pixel_format = PIXFORMAT_JPEG;
      
    • The camera is then initialized with the configuration, and if it fails, an error message is printed.

      esp_err_t err = esp_camera_init(&config);
      if (err != ESP_OK) {
          Serial.printf("Camera init failed with error 0x%x", err);
          return;
      }
      
    • The SD card is initialized, and if it fails, an error message is printed.

      if (!SD_MMC.begin()) {
          Serial.println("SD Card Mount Failed");
          return;
      }
      
      uint8_t cardType = SD_MMC.cardType();
      if (cardType == CARD_NONE) {
          Serial.println("No SD Card attached");
          return;
      }
      
    • A photo is captured with the camera and stored in the framebuffer.

      fb = esp_camera_fb_get();
      if (!fb) {
          Serial.println("Camera capture failed");
          return;
      }
      
    • The EEPROM is read to retrieve the number of the last picture, then the picture number for the new photo is incremented.

      EEPROM.begin(EEPROM_SIZE);
      pictureNumber = EEPROM.read(0) + 1;
      
    • A path for the new picture is created on the SD card, with a filename corresponding to the picture number.

      String path = "/picture" + String(pictureNumber) + ".jpg";
      
      fs::FS &fs = SD_MMC;
      Serial.printf("Picture file name: %s\n", path.c_str());
      
    • After saving the photo, the picture number is stored back into EEPROM for retrieval in the next power cycle.

      File file = fs.open(path.c_str(), FILE_WRITE);
      if (!file) {
          Serial.println("Failed to open file in writing mode");
      } else {
          file.write(fb->buf, fb->len);  // payload (image), payload length
          Serial.printf("Saved file to path: %s\n", path.c_str());
          EEPROM.write(0, pictureNumber);
          EEPROM.commit();
      }
      file.close();
      esp_camera_fb_return(fb);
      
    • Finally, the onboard LED (flash) is turned off and the ESP32-CAM goes into deep sleep.

      pinMode(4, OUTPUT);
      digitalWrite(4, LOW);
      rtc_gpio_hold_en(GPIO_NUM_4);
      
    • Sleep Mode: The ESP32-CAM goes into deep sleep after taking each photo to conserve power. It can be woken up by a reset or by a signal on specific pins.

      delay(2000);
      Serial.println("Going to sleep now");
      delay(2000);
      esp_deep_sleep_start();
      Serial.println("This will never be printed");
      
  • Loop Function: The loop() function is empty because after the setup process, the ESP32-CAM immediately goes into deep sleep.

Note that for this code to work, you need to ensure that GPIO 0 is connected to GND when uploading the sketch, and you might have to press the on-board RESET button to put your board into flashing mode. Also, remember to replace “/picture” with your own file name. The size of the EEPROM is set to 1, which means it can store values from 0 to 255. If you plan to take more than 255 pictures, you’ll need to increase the EEPROM size and adjust how you store and read the pictureNumber.

8. Bluetooth&SD Card&Camera&Speaker

8.1 Real-time Weather From @OpenWeatherMap

The IoT Open Weather Display project utilizes the ESP32 board and an I2C LCD1602 module to create a weather information display that retrieves data from the OpenWeatherMap API.

This project serves as an excellent introduction to working with APIs, Wi-Fi connectivity, and data display on an LCD module using the ESP32 board. With the IoT Open Weather Display, you can conveniently access real-time weather updates at a glance, making it an ideal solution for home or office environments.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

I2C LCD1602

BUY

Get OpenWeather API keys

OpenWeather is an online service, owned by OpenWeather Ltd, that provides global weather data via API, including current weather data, forecasts, nowcasts and historical weather data for any geographical location.

  1. Visit OpenWeather to log in/create an account.

    _images/OWM-1.png
  2. Click into the API page from the navigation bar.

    _images/OWM-2.png
  3. Find Current Weather Data and click Subscribe.

    _images/OWM-3.png
  4. Under Current weather and forecasts collection , subscribe to the appropriate service. In our project, Free is good enough.

    _images/OWM-4.png
  5. Copy the Key from the API keys page.

    _images/OWM-5.png

Complete Your Device

  1. Build the circuit.

    _images/2.6_i2clcd1602_bb.png
  2. Open the code.

    • Open the iot_1_open_weather.ino file located in the esp32-starter-kit-main\c\codes\iot_1_open_weather directory, or copy the code into the Arduino IDE.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

    • The LiquidCrystal I2C and Arduino_JSON libraries are used here, you can install them from the Library Manager.

  3. Locate the following lines and modify them with your <SSID> and <PASSWORD>.

    // Replace the next variables with your SSID/Password combination
    const char* ssid = "<SSID>";
    const char* password = "<PASSWORD>";
    
  4. Fill in the API keys you copied earlier into openWeatherMapApiKey.

    // Your Domain name with URL path or IP address with path
    String openWeatherMapApiKey = "<openWeatherMapApiKey>";
    
  5. Replace with your country code and city.

    // Replace with your country code and city
    // Fine the country code by https://openweathermap.org/find
    String city = "<CITY>";
    String countryCode = "<COUNTRY CODE>";
    
  6. After the code runs, you will see the time and weather information of your location on the I2C LCD1602.

Note

When the code is running, if the screen is blank, you can turn the potentiometer on the back of the module to increase the contrast.

8.2 Camera Web Server

This project combines the ESP32 board with a camera module to stream high-quality video over a local network. Set up your own camera system effortlessly and monitor any location in real-time.

With the project’s web interface, you can access and control the camera feed from any device connected to the network. Customize camera settings to optimize the streaming experience and easily adjust settings with the user-friendly interface.

Enhance your surveillance or live streaming capabilities with the versatile ESP32 Camera Streaming project. Monitor your home, office, or any desired location with ease and reliability.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

How to do?

  1. First plug in the camera.

  2. Then, connect ESP32-WROOM-32E to the computer using the USB cable.

    _images/plugin_esp32.png
  3. Open the code.

    • Open the iot_2_camera_server.ino file located in the esp32-starter-kit-main\c\codes\iot_2_camera_server directory, or copy the code into the Arduino IDE.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

  4. Locate the following lines and modify them with your <SSID> and <PASSWORD>.

    // Replace the next variables with your SSID/Password combination
    const char* ssid = "<SSID>";
    const char* password = "<PASSWORD>";
    
  5. Now, enable PSRAM.

    _images/sp230516_1505541.png
  6. Set the partition scheme to Huge APP (3MB No OTA/1MB SPIFFS).

    _images/sp230516_1508401.png
  7. After selecting the correct board (ESP32 Dev Module) and port, click the “Upload” button.

  8. You will see a successful WiFi connection message and the assigned IP address in the Serial Monitor.

    .....
    WiFi connected
    Starting web server on port: '80'
    Starting stream server on port: '81'
    Camera Ready! Use 'http://192.168.18.77' to connect
    
  9. Enter the IP address in your web browser. You will see a web interface where you can click Start Stream to view the camera feed.

    _images/sp230516_151521.png
  10. Scroll back to the top of the page, where you will see the live camera feed. You can adjust the settings on the left side of the interface.

    _images/sp230516_180520.png

Note

  • This ESP32 module supports Face Detection. To enable it, set the resolution to 240x240 and toggle the Face Detection option at the bottom of the interface.

  • This ESP32 module does not support Face Recognition.

8.3 Custom Video Streaming Web Server

The Custom Video Streaming Web Server project offers an opportunity to learn how to create a web page from scratch and customize it to play video streams. Additionally, you can incorporate interactive buttons, such as ON and OFF, to control the LED’s brightness.

By building this project, you will gain hands-on experience in web development, HTML, CSS, and JavaScript. You will learn how to create a responsive web page that can display video streams in real-time. Moreover, you will discover how to integrate interactive buttons to control the LED’s state, providing a dynamic user experience.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

How to do?

  1. First plug in the camera.

  2. Build the circuit.

    _images/iot_3_html_led_bb.png
  3. Then, connect ESP32-WROOM-32E to the computer using the USB cable.

    _images/plugin_esp32.png
  4. Open the code.

    • Open the iot_3_html_cam_led.ino file located in the esp32-starter-kit-main\c\codes\iot_3_html_cam_led directory, or copy the code into the Arduino IDE.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

  5. Locate the following lines and modify them with your <SSID> and <PASSWORD>.

    // Replace the next variables with your SSID/Password combination
    const char* ssid = "<SSID>";
    const char* password = "<PASSWORD>";
    
  6. After selecting the correct board (ESP32 Dev Module) and port, click the Upload button.

  7. You will see a successful WiFi connection message and the assigned IP address in the Serial Monitor.

    WiFi connected
    Camera Stream Ready! Go to: http://192.168.18.77
    
  8. Enter the IP address in your web browser. You will be directed to the web page shown below, where you can use the customized ON and OFF buttons to control the LED.

    _images/sp230510_180503.png
  9. Insert a battery into the expansion board and remove the USB cable. Now you can place the device anywhere you desire within the Wi-Fi range.

    _images/plugin_battery.png

8.4 IoT Communication with MQTT

This project focuses on utilizing MQTT, a popular communication protocol in the Internet of Things (IoT) domain. MQTT enables IoT devices to exchange data using a publish/subscribe model, where devices communicate through topics.

In this project, we explore the implementation of MQTT by building a circuit that includes an LED, a button, and a thermistor. The ESP32-WROOM-32E microcontroller is used to establish a connection to WiFi and communicate with an MQTT broker. The code allows the microcontroller to subscribe to specific topics, receive messages, and control the LED based on the received information. Additionally, the project demonstrates publishing temperature data from the thermistor to a designated topic when the button is pressed.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Button

BUY

Thermistor

BUY

Code Upload

  1. Build the circuit.

    Note

    When establishing a connection to WiFi, only the 36, 39, 34, 35, 32, 33 pins can be employed for analog reading. Please ensure the thermistor is connected to these designated pins.

    _images/iot_4_matt_bb.png
  2. Then, connect ESP32-WROOM-32E to the computer using the USB cable.

    _images/plugin_esp32.png
  3. Open the code.

    • Open the iot_4_mqtt.ino file located in the esp32-starter-kit-main\c\codes\iot_4_mqtt directory, or copy the code into the Arduino IDE.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

    • The PubSubClient library is used here, you can install it from the Library Manager.

      _images/mqtt_lib.png
  4. Locate the following lines and modify them with your <SSID> and <PASSWORD>.

    // Replace the next variables with your SSID/Password combination
    const char* ssid = "<SSID>";
    const char* password = "<PASSWORD>";
    
  5. Find the next line and modify your unique_identifier. Guarantee that your unique_identifier is truly unique as any IDs that are identical trying to log in to the same MQTT Broker may result in a login failure.

    // Add your MQTT Broker address, example:
    const char* mqtt_server = "broker.hivemq.com";
    const char* unique_identifier = "sunfounder-client-sdgvsda";
    

Topic Subscription

  1. To avoid interference from messages sent by other participants, you can set it as an obscure or uncommon string. Simply replace the current topic SF/LED with your desired topic name.

    Note

    You have the freedom to set the Topic as any character you desire. Any MQTT device that has subscribed to the identical Topic will be able to receive the same message. You can also simultaneously subscribe to multiple Topics.

    void reconnect() {
        // Loop until we're reconnected
        while (!client.connected()) {
            Serial.print("Attempting MQTT connection...");
            // Attempt to connect
            if (client.connect(unique_identifier)) {
                Serial.println("connected");
                // Subscribe
                client.subscribe("SF/LED");
            } else {
                Serial.print("failed, rc=");
                Serial.print(client.state());
                Serial.println(" try again in 5 seconds");
                // Wait 5 seconds before retrying
                delay(5000);
            }
        }
    }
    
  2. Modify the functionality to respond to the subscribed topic. In the provided code, if a message is received on the topic SF/LED, it checks whether the message is on or off. Depending on the received message, it changes the output state to control the LED’s on or off status.

    Note

    You can modify it for any topic you are subscribed to, and you can write multiple if statements to respond to multiple topics.

    void callback(char* topic, byte* message, unsigned int length) {
        Serial.print("Message arrived on topic: ");
        Serial.print(topic);
        Serial.print(". Message: ");
        String messageTemp;
    
        for (int i = 0; i < length; i++) {
            Serial.print((char)message[i]);
            messageTemp += (char)message[i];
        }
        Serial.println();
    
        // If a message is received on the topic "SF/LED", you check if the message is either "on" or "off".
        // Changes the output state according to the message
        if (String(topic) == "SF/LED") {
            Serial.print("Changing state to ");
            if (messageTemp == "on") {
                Serial.println("on");
                digitalWrite(ledPin, HIGH);
            } else if (messageTemp == "off") {
                Serial.println("off");
                digitalWrite(ledPin, LOW);
            }
        }
    }
    
  3. After selecting the correct board (ESP32 Dev Module) and port, click the Upload button.

  4. Open the serial monitor and if the following information is printed, it indicates a successful connection to the MQTT server.

    WiFi connected
    IP address:
    192.168.18.77
    Attempting MQTT connection...connected
    

Message Publication via HiveMQ

HiveMQ is a messaging platform that functions as an MQTT broker, facilitating fast, efficient, and reliable data transfer to IoT devices.

Our code specifically utilizes the MQTT broker provided by HiveMQ. We have included the address of the HiveMQ MQTT broker in the code as follows:

// Add your MQTT Broker address, example:
const char* mqtt_server = "broker.hivemq.com";
  1. At present, open the HiveMQ Web Client in your web browser.

  2. Connect the client to the default public proxy.

    _images/sp230512_092258.png
  3. Publish a message in the Topic you have subscribed to. In this project, you can publish on or off to control your LED.

    _images/sp230512_140234.png

Message Publication to MQTT

We can also utilize the code to publish information to the Topic. In this demonstration, we have coded a feature that sends the temperature measured by the thermistor to the Topic when you press the button.

  1. Click on Add New Topic Subscription.

    _images/sp230512_092341.png
  2. Fill in the topics you desire to follow and click Subscribe. In the code, we send temperature information to the topic SF/TEMP.

    void loop() {
        if (!client.connected()) {
            reconnect();
        }
        client.loop();
    
        // if the button pressed, publish the temperature to topic "SF/TEMP"
        if (digitalRead(buttonPin)) {
                long now = millis();
                if (now - lastMsg > 5000) {
                lastMsg = now;
                char tempString[8];
                dtostrf(thermistor(), 1, 2, tempString);
                client.publish("SF/TEMP", tempString);
            }
        }
    }
    
  3. Hence, we can monitor this Topic on HiveMQ, allowing us to view the information you have published.

    _images/sp230512_154342.png

8.5 CheerLights

CheerLights is a global network of synchronized lights that can be controlled by anyone.

Join the @CheerLights LED color-changing community, which allows LEDs around the world to change colors simultaneously.

You can place your LEDs in a corner of your office to remind yourself that you are not alone.

In this case, we also utilize MQTT, but instead of publishing our own messages, we subscribe to the “cheerlights” topic. This allows us to receive messages sent by others to the “cheerlights” topic and use that information to change the color of our LED strip accordingly.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

WS2812 RGB 8 LEDs Strip

BUY

How to do?

  1. Build the circuit.

    _images/iot_5_cheerlight_bb.png
  2. Then, connect ESP32-WROOM-32E to the computer using the USB cable.

    _images/plugin_esp32.png
  3. Open the code.

    • Open the iot_5_cheerlights.ino file located in the esp32-starter-kit-main\c\codes\iot_5_cheerlights directory, or copy the code into the Arduino IDE.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

    • The PubSubClient and Adafruit_NeoPixel libraries are used here, you can install them from the Library Manager.

      _images/mqtt_lib.png
  4. Locate the following lines and modify them with your <SSID> and <PASSWORD>.

    // Replace the next variables with your SSID/Password combination
    const char* ssid = "<SSID>";
    const char* password = "<PASSWORD>";
    
  5. Find the next line and modify your unique_identifier. Guarantee that your unique_identifier is truly unique as any IDs that are identical trying to log in to the same MQTT Broker may result in a login failure.

    // Add your MQTT Broker address:
    const char* mqtt_server = "mqtt.cheerlights.com";
    const char* unique_identifier = "sunfounder-client-sdgvsasdda";
    
  6. After selecting the correct board (ESP32 Dev Module) and port, click the Upload button.

  7. At this point, you can see that your RGB strip is displaying a certain color. Place it on your desk and you will notice that it periodically changes colors. This is because other @CheerLights followers are changing the color of your lights!

  8. Open the Serial Monitor. You will see messages similar to the following:

WiFi connected
IP address:
192.168.18.77
Attempting MQTT connection...connected
Message arrived on topic: cheerlights.
Message: oldlace
Changing color to oldlace

Control global @CheerLights devices

  1. Join the Discord Server and utilize the CheerLights bot to set the color. Simply type /cheerlights in any of the channels on the CheerLights Discord Server to activate the bot.

    _images/sp230511_163558.png
  2. Follow the instructions provided by the bot to set the color. This will allow you to control CheerLights devices globally.

    _images/sp230511_163849.png

8.6 Temperature and Humidity Monitoring with Adafruit IO

In this project, we will guide you on how to use a popular IoT platform. There are many free (or low-cost) platforms available online for programming enthusiasts. Some examples are Adafruit IO, Blynk, Arduino Cloud, ThingSpeak, and so on. The usage of these platforms is quite similar. Here, we will be focusing on Adafruit IO.

We will write an Arduino program that uses the DHT11 sensor to send temperature and humidity readings to Adafruit IO’s dashboard. You can also control an LED on the circuit through a switch on the dashboard.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

DHT11 Humiture Sensor

BUY

Setting up the Dashboard

  1. Visit Adafruit IO, then click on Start for free to create a free account.

    _images/sp230516_102503.png
  2. Fill out the form to create an account.

    _images/sp230516_102629.png
  3. After creating an Adafruit account, you’ll need to reopen Adafruit io. Click on the Dashboards, then click on New Dashboard.

    _images/sp230516_103347.png
  4. Create a New Dashboard.

    _images/sp230516_103744.png
  5. Enter the newly created Dashboard and create a new block.

    _images/sp230516_104234.png
  6. Create 1 Toggle block.

    _images/sp230516_105727.png
  7. Next, you’ll need to create a new feed here. This toggle will be used to control the LED, and we’ll name this feed “LED”.

    _images/sp230516_105641.png
  8. Check the LED feed, then move to the next step.

    _images/sp230516_105925.png
  9. Complete the block settings (mainly Block Title, On Text, and Off Text), then click on the Create block button at the bottom right to finish.

    _images/sp230516_110124.png
  10. We also need to create two Text Blocks next. They will be used to display temperature and humidity. So, create two feeds named temperature and humidity.

    _images/sp230516_110657.png
  11. After creation, your Dashboard should look something like this:

    _images/sp230516_111134.png
  12. You can adjust the layout by using the Edit Layout option on the Dashboard.

    _images/sp230516_111240.png
  13. Click on API KEY, and you will see your username and API KEY displayed. Note these down as you’ll need them for your code.

    _images/sp230516_111641.png

Running the Code

  1. Build the circuit.

    _images/iot_6_adafruit_io_bb.png
  2. Then, connect ESP32-WROOM-32E to the computer using the USB cable.

    _images/plugin_esp32.png
  3. Open the code.

    • Open the iot_6_adafruit_io.ino file located in the esp32-starter-kit-main\c\codes\iot_6_adafruit_io directory, or copy the code into the Arduino IDE.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

    • The Adafruit_MQTT Library and DHT sensor library are used here, you can install them from the Library Manager.

  4. Find the following lines and replace <SSID> and <PASSWORD> with the specific details of your WiFi network.

    /************************* WiFi Access Point *********************************/
    
    #define WLAN_SSID "<SSID>"
    #define WLAN_PASS "<PASSWORD>"
    
  5. Then replace <YOUR_ADAFRUIT_IO_USERNAME> with your Adafruit IO username and <YOUR_ADAFRUIT_IO_KEY> with the API KEY you just copied.

    // Adafruit IO Account Configuration
    // (to obtain these values, visit https://io.adafruit.com and click on Active Key)
    #define AIO_USERNAME "<YOUR_ADAFRUIT_IO_USERNAME>"
    #define AIO_KEY      "<YOUR_ADAFRUIT_IO_KEY>"
    
  6. After selecting the correct board (ESP32 Dev Module) and port, click the Upload button.

  7. Once the code is successfully uploaded, you will observe the following message in the serial monitor, indicating successful communication with Adafruit IO.

    Adafruit IO MQTTS (SSL/TLS) Example
    
    
    Connecting to xxxxx
    WiFi connected
    IP address:
    192.168.18.76
    Connecting to MQTT... MQTT Connected!
    Temperature: 27.10
    Humidity: 61.00
    
  8. Navigate back to Adafruit IO. Now you can observe the temperature and humidity readings on the dashboard, or utilize the LED toggle switch to control the on/off state of the external LED connected to the circuit.

    _images/sp230516_143220.png

8.7 ESP Camera with Telegram Bot

In this project, we’ll demonstrate how to integrate the ESP32 with your favorite messaging application. For this demonstration, we’re using Telegram.

Create a Telegram Bot, allowing you to control your circuit from anywhere, capture photos, and manage the flash. Moreover, whenever someone passes by your device, it will snap a new photo and send a notification to your Telegram account.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

PIR Motion Sensor Module

BUY

Creating a Telegram Bot

  1. Head to Google Play or the App Store and download and install Telegram.

  2. Search for botfather in the Telegram app, and once it appears, click on it to open. or you can directly access this link: t.me/botfather.

    _images/sp230515_135927.png
  3. Upon opening, you’ll be presented with a chat window. Send the command /start.

    _images/sp230515_140149.png
  4. Enter /newbot and follow the provided instructions to create your bot. Once successful, the BotFather will provide you with the access link and API for your new bot.

    _images/sp230515_140830.png

Authorizing Telegram Users

As anyone can interact with the bot you’ve created, there’s a risk of information leakage. To address this, we want the bot to only respond to authorized users.

  1. In your Telegram account, search for IDBot or open the link: t.me/myidbot.

    _images/sp230515_144241.png
  2. Send the command /getid. Save the provided ID for later use in our program.

    _images/sp230515_144614.png

Upload the Code

  1. First plug in the camera.

  2. Build the circuit.

    _images/iot_7_cam_telegram_bb.png
  3. Open the code.

    • Open the iot_7_cam_telegram.ino file located in the esp32-starter-kit-main\c\codes\iot_7_cam_telegram directory, or copy the code into the Arduino IDE.

    • After selecting the board (ESP32 Dev Module) and the appropriate port, click the Upload button.

    • Always displaying “Unknown COMxx”?

    • The UniversalTelegramBot and ArduinoJson libraries are used here, you can install them from the Library Manager.

  4. Locate and modify the following lines with your WiFi details, replacing <SSID> and <PASSWORD>:

    // Replace the next variables with your SSID/Password combination
    const char* ssid = "<SSID>";
    const char* password = "<PASSWORD>";
    
  1. Update the next line, replacing <CHATID> with your Telegram ID, which you obtained from @IDBot.

    // Use @myidbot to find out the chat ID of an individual or a group
    // Also note that you need to click "start" on a bot before it can
    // message you
    String chatId = "<CHATID>";
    
  2. Update the next line, substituting <BOTTOKEN> with the token of your Telegram BOT, which was provided by @BotFather.

    // Initialize Telegram BOT
    String BOTtoken = "<BOTTOKEN>";
    
  3. After selecting the correct board (ESP32 Dev Module) and port, click the Upload button.

  4. Open the Serial Monitor. If an IP address is printed, this indicates successful execution.

    Connecting to xxxx
    ESP32-CAM IP Address: 192.168.18.76
    Init Done!
    
  5. Now, you can interact with your ESP32 via Telegram.

    _images/sp230515_161237.png

8.8 Camera with Home Assistant

This project will guide you in setting up a video stream web server for the ESP32 camera and integrating it with the popular home automation platform, Home Assistant. This integration will allow you to access the server from any device on your network.

Note

Before diving into this project, you need to have an operating system with Home Assistant installed.

We recommend installing the Home Assistant OS on a Raspberry Pi.

If you don’t have a Raspberry Pi, you can also install it on a virtual machine running on Windows, macOS, or Linux.

For installation instructions, refer to the official website link: https://www.home-assistant.io/installation/

Please proceed with this project only after successful installation.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

1. Configuration in ESP Home

  1. First plug in the camera.

  2. Connect your ESP32 to the host where you’ve installed the Home Assistant system (e.g., if installed on a Raspberry Pi, connect to the Pi).

    _images/plugin_esp32.png
  3. Install ESPHome Addon.

    _images/sp230629_145928.png
  4. Click START, then OPEN WEB UI.

    _images/sp230629_172645.png
  5. Add new devices.

    _images/sp230629_172733.png
  6. A prompt might appear. Click CONTINUE.

    _images/sp230629_172816.png
  7. Create a configuration. Here, you can enter any desired name for Name. For WiFi, enter details of the network on which your Home Assistant system is present.

    _images/sp230629_172926.png
  8. Select the ESP32 as the device type.

    _images/sp230629_173043.png
  9. When you see a fireworks celebration icon, it means you’ve successfully created the device. Click skip (DO NOT click INSTALL).

    _images/sp230629_173151.png

    At this point, you’ve only added the device in ESPHome. To integrate the ESP32 module into Home Assistant, additional configurations are needed:

  10. Click EDIT.

    _images/sp230629_173322.png
  11. After entering the .yaml interface, modify the ssid and password with your WiFi details.

    _images/sp230629_174301.png
  12. Under the captive_portal section, paste the following code:

    # Example configuration entry
    esp32_camera:
        external_clock:
            pin: GPIO0
            frequency: 20MHz
        i2c_pins:
            sda: GPIO26
            scl: GPIO27
        data_pins: [GPIO5, GPIO18, GPIO19, GPIO21, GPIO36, GPIO39, GPIO34, GPIO35]
        vsync_pin: GPIO25
        href_pin: GPIO23
        pixel_clock_pin: GPIO22
        power_down_pin: GPIO32
    
        # Image settings
        name: My Camera
        # ...
    

    Note

    For more details on the .yaml configuration for ESP32, you can refer to ESP32 Camera - ESPHome.

  13. Save, then click INSTALL.

    _images/sp230629_174447.png
  14. Choose the USB port method for installation.

    _images/sp230629_174852.png

    Note

    The initial compilation will download dependency packages, which might take around 10 minutes. Please be patient. If the process stalls for a long time, check if there’s enough disk space on your system.

  15. Wait for the INFO Successfully compiled program. message, indicating firmware compilation is complete.

    _images/sp230630_115109.png

    Note

    At this point, you should see the node as ONLINE. If not, ensure your ESP32 is on the same network segment or try rebooting the device.

    _images/sp230630_153024.png

2. Configuration in Home Assistant

After integrating with Esphome, you still need to configure the camera in homeassistant.

  1. Go to Settings > Devices & Services.

    _images/sp230630_155917.png
  2. Now you should see the esphome tab. Click CONFIGURE.

    _images/sp230630_155736.png
  3. Click SUBMIT.

    _images/sp230630_162218.png
  4. Wait for the Success message.

    _images/sp230630_162311.png
  5. In Overview, click the top-right menu and select Edit Dashboard.

    _images/sp230630_164745.png
  6. Click ADD CARD.

    _images/sp230630_164850.png
  7. Choose Picture entity.

    _images/sp230630_164935.png
  8. In the entity field, select the ESP32 you just added. Then save.

    _images/sp230630_165019.png
  9. Lastly, click DONE to exit the EDIT interface.

    _images/sp230630_165235.png

Now, you can view your camera feed on Home Assistant.

8.9 Blynk-based Intrusion Notification System

This project demonstrate a simple home intrusion detection system using a PIR motion sensor (HC-SR501). When the system is set to “Away” mode through the Blynk app, the PIR sensor monitors for motion. Any detected movement triggers a notification on the Blynk app, alerting the user of potential intrusion.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

PIR Motion Sensor Module

BUY

1. Circuit Assembly

_images/iot_9_blynk_bb.png

2. Blynk Configuration

2.1 Initializing Blynk

  1. Navigate to the BLYNK and select START FREE.

    _images/09_blynk_access.png
  2. Enter your email to initiate the registration process.

    _images/09_blynk_sign_in.png
  3. Confirm your registration through your email.

    _images/09_blynk_password.png
  4. After confirmation, Blynk Tour will appear. It is recommended to select “Skip”. If Quick Start also appears, consider skipping it as well.

    _images/09_blynk_tour.png

2.2 Template Creation

  1. First, create a template in Blynk. Follow the subsequent instructions to create the Intrusion Alert System template.

    _images/09_create_template_1_shadow.png
  2. Assign a name to the template, select ESP32 Hardware, and select Connection Type as WiFi, then select Done.

    _images/09_create_template_2_shadow.png

2.3 Datastream Generation

Open the template you just set up, let’s create two datastreams.

  1. Click New Datastream.

    _images/09_blynk_new_datastream.png
  2. In the popup, choose Virtual Pin.

    _images/09_blynk_datastream_virtual.png
  3. Name the Virtual Pin V0 as AwayMode. Set the DATA TYPE as Integer with MIN and MAX values as 0 and 1.

    _images/09_create_template_shadow.png
  4. Similarly, create another Virtual Pin datastream. Name it Current Status and set the DATA TYPE to String.

    _images/09_datastream_1_shadow.png

2.4 Setting Up an Event

Next, we’ll set up an event that sends an email notification if an intrusion is detected.

  1. Click Add New Event.

    _images/09_blynk_event_add.png
  2. Define the event’s name and its specific code. For TYPE, choose Warning and write a short description for the email to be sent when the event happens. You can also adjust how often you get notified.

    Note

    Make sure the EVENT CODE is set as intrusion_detected. This is predefined in the code, so any changes would mean you need to adjust the code as well.

    _images/09_event_1_shadow.png
  3. Go to the Notifications section to turn on notifications and set up email details.

    _images/09_event_2_shadow.png

2.5 Fine-Tuning the Web Dashboard

Making sure the Web Dashboard interacts perfectly with the Intrusion Alert System is vital.

  1. Simply drag and place both the Switch widget and the Label widget onto the Web Dashboard.

    _images/09_web_dashboard_1_shadow.png
  2. When you hover over a widget, three icons will appear. Use the settings icon to adjust the widget’s properties.

    _images/09_blynk_dashboard_set.png
  3. In the Switch widget settings, select Datastream as AwayMode(V0). Set ONLABEL and OFFLABEL to display “away” and “home”, respectively.

    _images/09_web_dashboard_2_shadow.png
  4. In the Label widget settings, select Datastream as Current Status(V1).

    _images/09_web_dashboard_3_shadow.png

2.6 Saving the Template

Lastly, don’t forget to save your template.

_images/09_save_template_shadow.png

2.7 Making a Device

  1. It’s time to create a new device.

    _images/09_blynk_device_new.png
  2. Click on From template to start with a new setup.

    _images/09_blynk_device_template.png
  3. Then, pick the Intrusion Alert System template and click on Create.

    _images/09_blynk_device_template2.png
  4. Here, you’ll see the Template ID, Device Name, and AuthToken. You need to copy these into your code so the ESP32 can work with Blynk.

    _images/09_blynk_device_code.png

3. Code Execution

  1. Before running the code, make sure to install the Blynk library from the Library Manager on the Arduino IDE.

    _images/09_blynk_add_library.png
  2. Open the iot_9_intrusion_alert_system.ino file, which is located in the esp32-starter-kit-main\c\codes\iot_9_intrusion_alert_system directory. You can also copy its content into the Arduino IDE.

  3. Replace the placeholders for BLYNK_TEMPLATE_ID, BLYNK_TEMPLATE_NAME, and BLYNK_AUTH_TOKEN with your own unique IDs.

    #define BLYNK_TEMPLATE_ID "TMPxxxxxxx"
    #define BLYNK_TEMPLATE_NAME "Intrusion Alert System"
    #define BLYNK_AUTH_TOKEN "xxxxxxxxxxxxx"
    
  4. You also need to enter your WiFi network’s ssid and password.

    char ssid[] = "your_ssid";
    char pass[] = "your_password";
    
  5. Choose the correct board (ESP32 Dev Module) and port, then click the Upload button.

  6. Open the Serial monitor (set baud rate to 115200) and wait for a successful connection message.

    _images/09_blynk_upload_code.png
  7. After a successful connection, activating the switch in Blynk will start the PIR module’s surveillance. When motion is detected (state of 1), it will say, “Somebody here!” and send an alert to your email.

    _images/09_blynk_code_alarm.png

4. Code explanation

  1. Configuration & Libraries

    Here, you set up the Blynk constants and credentials. You also include the necessary libraries for the ESP32 and Blynk.

    /* Comment this out to disable prints and save space */
    #define BLYNK_PRINT Serial
    
    #define BLYNK_TEMPLATE_ID "xxxxxxxxxxx"
    #define BLYNK_TEMPLATE_NAME "Intrusion Alert System"
    #define BLYNK_AUTH_TOKEN "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
    
    #include <WiFi.h>
    #include <WiFiClient.h>
    #include <BlynkSimpleEsp32.h>
    
  2. WiFi Setup

    Enter your WiFi credentials.

    char ssid[] = "your_ssid";
    char pass[] = "your_password";
    
  3. PIR Sensor Configuration

    Set the pin where the PIR sensor is connected and initialize the state variables.

    const int sensorPin = 14;
    int state = 0;
    int awayHomeMode = 0;
    BlynkTimer timer;
    
  4. setup() Function

    This function initializes the PIR sensor as an input, sets up serial communication, connects to WiFi, and configures Blynk.

    • We use timer.setInterval(1000L, myTimerEvent) to set the timer interval in setup(), here we set to execute the myTimerEvent() function every 1000ms. You can modify the first parameter of timer.setInterval(1000L, myTimerEvent) to change the interval between myTimerEvent executions.


    void setup() {
    
        pinMode(sensorPin, INPUT);  // Set PIR sensor pin as input
        Serial.begin(115200);           // Start serial communication at 115200 baud rate for debugging
    
        // Configure Blynk and connect to WiFi
        Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
    
        timer.setInterval(1000L, myTimerEvent);  // Setup a function to be called every second
    }
    
  5. loop() Function

    The loop function continuously runs Blynk and the Blynk timer functions.

    void loop() {
       Blynk.run();
       timer.run();
    }
    
  6. Blynk App Interaction

    These functions are called when the device connects to Blynk and when there’s a change in the state of the virtual pin V0 on the Blynk app.

    • Every time the device connects to the Blynk server, or reconnects due to poor network conditions, the BLYNK_CONNECTED() function is called. The Blynk.syncVirtual() command request a single Virtual Pin value. The specified Virtual Pin will perform BLYNK_WRITE() call.

    • Whenever the value of a virtual pin on the BLYNK server changes, it will trigger BLYNK_WRITE().


    // This function is called every time the device is connected to the Blynk.Cloud
    BLYNK_CONNECTED() {
        Blynk.syncVirtual(V0);
    }
    
    // This function is called every time the Virtual Pin 0 state changes
    BLYNK_WRITE(V0) {
        awayHomeMode = param.asInt();
        // additional logic
    }
    
  7. Data Handling

    Every second, the myTimerEvent() function calls sendData(). If the away mode is enabled on Blynk, it checks the PIR sensor and sends a notification to Blynk if motion is detected.

    • We use Blynk.virtualWrite(V1, "Somebody in your house! Please check!"); to change the text of a label.

    • Use Blynk.logEvent("intrusion_detected"); to log event to Blynk.


    void myTimerEvent() {
       sendData();
    }
    
    void sendData() {
       if (awayHomeMode == 1) {
          state = digitalRead(sensorPin);  // Read the state of the PIR sensor
    
          Serial.print("state:");
          Serial.println(state);
    
          // If the sensor detects movement, send an alert to the Blynk app
          if (state == HIGH) {
            Serial.println("Somebody here!");
            Blynk.virtualWrite(V1, "Somebody in your house! Please check!");
            Blynk.logEvent("intrusion_detected");
          }
       }
    }
    

Reference

8.10 Android Application - RGB LED Operation via Arduino and Bluetooth

The objective of this project is to develop an Android application capable of manipulating the hue of an RGB LED through a smartphone using Bluetooth technology.

This Android application will be constructed utilizing a complimentary web-based platform known as MIT App Inventor 2. The project presents an excellent opportunity to gain familiarity with the interfacing of an Arduino with a smartphone.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

RGB LED

BUY

1. Creation of the Android Application

The Android application will be fashioned using a free web application known as MIT App Inventor. MIT App Inventor serves as an excellent starting point for Android development, owing to its intuitive drag-and-drop features allowing for the creation of simplistic applications.

Now, let’s begin.

  1. Here is the login page: http://ai2.appinventor.mit.edu. You will require a Google account to register with MIT App Inventor.

  2. After logging in, navigate to Projects -> Import project (.aia) from my computer. Subsequently, upload the control_rgb_led.aia file located in the path esp32-starter-kit-main\c\codes\iot_10_bluetooth_app_inventor.

    _images/10_ble_app_inventor1.png
  3. Upon uploading the .aia file, you will see the application on the MIT App Inventor software. This is a pre-configured template. You can modify this template after you have familiarized yourself with MIT App Inventor through the following steps.

    _images/10_ble_app_inventor2.png
  4. In MIT App Inventor, you have 2 primary sections: the Designer and the Blocks.

    _images/10_ble_app_inventor3.png
  5. The Designer allows you to add buttons, text, screens, and modify the overall aesthetic of your application.

    _images/10_ble_app_inventor2.png
  6. Subsequently, you have the Blocks section. The Blocks section facilitates the creation of bespoke functions for your application.

    _images/10_ble_app_inventor5.png
  7. To install the application on a smartphone, navigate to the Build tab.

    _images/10_ble_app_inventor6.png
    • You can generate a .apk file. After selecting this option, a page will appear allowing you to choose between downloading a .apk file or scanning a QR code for installation. Follow the installation guide to complete the application installation.

    • If you wish to upload this app to Google Play or another app marketplace, you can generate a .aab file.

2. Upload the code

  1. Build the circuit.

    _images/rgb_pin.jpg

    The RGB LED comprises 4 pins: the elongated pin is the common cathode pin, typically connected to GND; the pin to the left of the longest pin represents Red; and the two pins on the right symbolize Green and Blue.

    _images/2.3_color_light_bb.png
  2. Subsequently, connect the ESP32-WROOM-32E to your computer using a USB cable.

    _images/plugin_esp32.png
  3. Open the iot_10_bluetooth_app_inventor.ino file situated in the esp32-starter-kit-main\c\codes\iot_10_bluetooth_app_inventor directory, or copy the code into the Arduino IDE.

  4. Upon selecting the appropriate board (ESP32 Dev Module) and port, click the Upload button.

3. App and ESP32 Connection

Ensure that the application created earlier is installed on your smartphone.

  1. Initially, activate Bluetooth on your smartphone.

    _images/10_ble_mobile1.png
  2. Navigate to the Bluetooth settings on your smartphone and find ESP32RGB.

    _images/10_ble_mobile2.png
  3. After clicking it, agree to the Pair request in the pop-up window.

    _images/10_ble_mobile3.png
  4. Now open the recently installed Control_RGB_LED APP.

    _images/10_ble_mobile4.png
  5. In the APP, click on Connect Bluetooth to establish a connection between the APP and ESP32.

    _images/10_ble_mobile5.png
  6. Select the xx.xx.xx.xx.xx.xx ESP32RGB that comes up. if you changed SerialBT.begin("ESP32RGB"); in the code, then just select the name of your setting.

    _images/10_ble_mobile6.png
  7. If you have been waiting for a while and still can’t see any device names, it may be that this APP is not allowed to scan surrounding devices. In this case, you need to adjust the settings manually.

    • Long press the APP icon and click on the resulting APP Info. If you have another method to access this page, follow that.

      _images/10_ble_mobile8.png
    • Navigate to the Permissions page.

      _images/10_ble_mobile9.png
    • Locate Nearby devices, and select Always to allow this APP to scan for nearby devices.

      _images/10_ble_mobile10.png
    • Now, restart the APP and repeat steps 5 and 6 to successfully connect to Bluetooth.

  8. Upon successful connection, you will automatically return to the main page, where it will display connected. Now you can adjust the RGB values and change the color of the RGB display by pressing the Change Color button.

    _images/10_ble_mobile7.png

Arduino Video Course

Embark on a journey through the Arduino world with the comprehensive Arduino Video Course, using SunFounder’s ESP32 Starter Kit. This series begins with an introduction to the Arduino ecosystem and the capabilities of the ESP32 board, setting the stage for a deep dive into practical applications and programming techniques. You’ll learn the basics of controlling LEDs, understanding serial communication, and manipulating various components like RGB LEDs, buttons, and shift registers. The course progresses to more advanced topics, including array handling, interfacing with LCD displays, and utilizing LED strips for visual effects. Towards the latter part of the series, you’ll delve into controlling different types of motors, from simple DC motors to servo motors, and even operating a mini water pump, culminating in a well-rounded understanding of Arduino programming and hardware interfacing. Whether you’re a beginner or looking to sharpen your skills, this course provides a thorough exploration from foundational concepts to intricate project executions.

Projects

Video 1: Introduce this Kit

This video serves as an introduction to SunFounder’s ESP32 IoT Learning Kit. It covers various aspects of the kit, highlighting its features and capabilities:

  • ESP32 Microcontroller: Features the ESP32 microcontroller with built-in Wi-Fi and Bluetooth.

  • Arduino IDE Installation: Guides viewers through installing the Arduino IDE.

  • ESP32 Board Setup: Demonstrates board setup and driver installation.

  • Selecting the ESP32 Dev Module: Explains board selection in Arduino IDE.

  • Library Installation: Shows how to install necessary libraries.

  • Project Examples: Introduces various project examples for Arduino and MicroPython.

Video

Video 2: What’s ESP32, Camera Extension Board?

This video introduces the SunFounder ESP32 IoT Learning Kit and its components, providing a solid foundation for further exploration and projects.

  • Introduction: Unboxing and overview of the kit.

  • ESP32 Microcontroller: Explaining the ESP32 microcontroller with Wi-Fi and Bluetooth.

  • Camera Extension Board: Details about the camera expansion board and its features.

  • Kit Components: A comprehensive list of all the components included in the kit.

Video

Video 3: “Hello LED” Project

In Tutorial 3, we delve into the “Hello LED” project, providing a comprehensive overview of the project:

  • Components: A detailed look at the components involved in the project, including resistors, LEDs, and breadboards, explaining their roles and functions.

  • Circuit Setup: Step-by-step guidance on setting up the LED circuit, including proper resistor usage and connections on the breadboard.

  • Arduino Code: An in-depth explanation of the Arduino code used in the project, highlighting key elements and the upload process to the ESP32.

  • Testing: Practical instructions on how to test the LED blink demonstration, ensuring that the project works as intended.

This tutorial not only equips you with the knowledge needed to complete the “Hello LED” project but also provides a foundational understanding of resistors, LEDs, and breadboards in electronics and IoT applications.

Video

Related On-line Tutorials

Video 4: Data Types, Variables, and Serial Monitor

This tutorial provides crucial knowledge for working with data types, variables, and the Serial Monitor in Arduino programming.

  • Data Types: Explanation of integer, character, float, double, string, and boolean data types.

  • Defining Variables: How to define variables, including data type selection, naming, and assignment.

  • Updating Variables: Demonstrating how to update variables with new values.

  • Variable Naming: Guidelines for naming variables to avoid reserved words.

  • Constants: Introduction to constants and how to declare them.

  • Serial Monitor Usage: The significance of the Serial Monitor in Arduino development and basic usage instructions.

  • Printing in Serial Monitor: Demonstrating how to print text, numbers, binary, hexadecimal, and ASCII characters in the Serial Monitor.

Video

Video 5: LED Fade - Controlling LED Brightness

This tutorial covers controlling LED brightness by fading in or out using the SunFounder ESP32 module:

  • LED Brightness Control: Explains controlling LED brightness using PWM (Pulse Width Modulation). Discusses digital signals, duty cycles, and how varying duty cycles control LED brightness.

  • Wiring Diagram and Setup: Provides a detailed wiring diagram for connecting an LED with a 220 Ohm resistor to the ESP32. Demonstrates the physical setup on a breadboard.

  • Code Explanation: Describes the Arduino code for fading an LED. Covers functions like ledcSetup, ledcAttachPin, and ledcWrite, explaining parameters and usage.

  • Practical Demonstration: Shows how to upload the code to ESP32, check the wiring, and observe the LED fading effect. Tips for adjusting fade speed and brightness levels.

This comprehensive guide is ideal for beginners to learn about LED control with ESP32, offering step-by-step instructions, code details, and practical demonstrations.

Video

Related On-line Tutorials

Video 6: Controlling RGB LEDs

This comprehensive tutorial provides a step-by-step guide to understanding and implementing RGB LED control using the ESP32, from basic concepts to practical applications.

  • RGB LED Overview: Describes the structure and functionality of RGB LEDs, including common anode and cathode setups.

  • Wiring Guide: Provides details on connecting the RGB LED to the ESP32 module.

  • Code Explanation: Discusses the Arduino code necessary for manipulating RGB LED colors through PWM channels.

  • Color Control Demo: Demonstrates how to create different colors by adjusting the red, green, and blue values on the ESP32.

Aimed at beginners, the tutorial offers a comprehensive introduction to using RGB LEDs with the ESP32 module.

Video

Related On-line Tutorials

Video 7: Arrays and Loops in Arduino Programming

This tutorial is designed to provide a thorough understanding of using arrays and loops in Arduino programming, specifically tailored for beginners using the ESP32 module.

  • Introduction to Arrays: Explains what an array is, how to define it with multiple values, and how to access and modify its elements.

  • Defining and Filling Arrays: Shows how to define an empty array with a predefined size and fill it with values using indexes.

  • Using Loops with Arrays: Introduces different types of loops - for loop, while loop, and do-while loop - and their usage in accessing and modifying array elements.
    • For Loop: Demonstrates iterating over an array’s elements, with detailed explanation on the loop’s structure and incrementing index.

    • While Loop: Explains the while loop that executes code blocks based on a condition and showcases decrementing a value until a condition is met.

    • Do-While Loop: Focuses on do-while loop which ensures the code block is executed at least once before checking the condition.

  • Practical Examples: Includes examples on updating array values, printing all elements of an array, and using conditional statements within loops.

Video

Video 8: Walking Light with 74HC595 Shift Register

This tutorial is designed for learners to understand how to use a shift register with the ESP32 for controlling multiple LEDs, creating a dynamic lighting effect.

  • Introduction: Uses ESP32 microcontroller and 74HC595 shift register.

  • Components: Includes ESP32, breadboard, jumper wires, resistors, LEDs, and the 74HC595 chip.

  • 74HC595 Features: Explains its serial-in, parallel-out functionality.

  • Wiring Guide: Provides step-by-step instructions for wiring the components.

  • Arduino Code: Discusses code for controlling LED sequences with the shift register.

  • Demonstration: Shows how to adjust light patterns and speed using the code.

Video

Related On-line Tutorials

Video 9: Toggle LED with Push Button

This tutorial is aimed at beginners, providing a practical guide to using a push button to control an LED with the ESP32.

  • Project Focus: Teaches how to read a push button’s state and toggle an LED on and off.

  • Components: Includes ESP32, breadboard, jumper wires, resistors, LED, and push button.

  • Wiring and Setup: Provides wiring instructions for connecting the push button and LED to ESP32.

  • Arduino Code: Explains the code for button state reading and LED toggling.

  • Practical Demonstration: Showcases the LED being toggled using the push button.

Video

Related On-line Tutorials

Video 10: Digital Counter with Seven-Segment Display

This tutorial is designed for learners who want to explore digital displays and counters using the ESP32 module.

  • Project Scope: Create a 0-9 counter, reverse it, and display letters A-E using ESP32.

  • Components: Includes ESP32, seven-segment display, 74HC595 shift register, resistors, and wiring.

  • Seven-Segment Basics: Explains segment control for displaying numbers and letters.

  • Wiring Guide: Details how to wire the display to the ESP32 and shift register.

  • Arduino Code: Describes the code for controlling the counter and display segments.

  • Demonstrations: Shows practical applications, including digit and letter display.

Video

Related On-line Tutorials

Video 11: Using LCD1602/LCD2004 with ESP32

Learn to use LCD screens with ESP32 for displaying text and other information:

  • LCD Types: Tutorial covers both LCD1602 (16 characters, 2 lines) and LCD2004 (20 characters, 4 lines).

  • Key Features: Explains adjusting contrast and using I2C communication for simpler wiring.

  • Components: Utilizes the ESP32 board, LCD screen, and necessary wires.

  • Wiring Guide: Step-by-step instructions on connecting the LCD to ESP32, including power connections and data lines.

  • Arduino Code: Detailed explanation of the Arduino code for displaying text on the LCD.

  • Demonstrations: Shows practical applications like displaying a counter and custom text on the LCD.

  • Contrast Adjustment: Tips on setting the right contrast for clear visibility.

  • LCD Color Recommendation: Advises on choosing a green LCD for better display quality over blue.

Video

Related On-line Tutorials

Video 12: Using WS2812 RGB Strip

This tutorial is perfect to learn how to utilize the WS2812 LED strip with ESP32 for creating various colors and controlling individual LEDs:

  • WS2812 LED Strip Introduction: A flexible strip with adhesive back, 5050 LEDs, and individual control capabilities.

  • Technical Details: The WS2812 LEDs support 256 color levels and can be cascaded via a single wire. Each LED is 5mm x 5mm with a specified operating voltage and temperature range.

  • Color Control: Learn to create any color with RGB (Red, Green, Blue) combinations. Includes understanding of color codes in both binary and hexadecimal formats.

  • Wiring Guide: Simple wiring with power, ground, and data connections. The data line connects to pin 14 of the ESP32.

  • Arduino Programming: Detailed explanation of Arduino code for controlling the strip.

  • Interactive Projects: Step-by-step instructions for several projects like a walking light LED, back and forth light movement, and controlling individual LEDs with specific colors.

  • Color Picker Tool: How to use an RGB color picker to understand and choose specific colors for the LEDs.

Video

Related On-line Tutorials

Video 13: Arduino Beep with Active Buzzer

Here, you will learn how to use an active buzzer with the ESP32 module for generating sound:

  • Active Buzzer Introduction: Learn to control an active buzzer using a transistor. The buzzer emits sound when powered up.

  • Buzzer Components: The tutorial uses an active buzzer, a 1K resistor, jumper wires, and an S8050 transistor.

  • Wiring and Schematic: Understand the wiring schematic for connecting the buzzer to the ESP32.

  • Buzzer Specifications: The active buzzer operates within a voltage range of 3 to 8 volts and has an internal oscillating frequency of around 2700 Hz.

  • Arduino Programming: The tutorial covers the setup, loop functions, and how to control the buzzer using digital signals.

  • Interactive Project: The project demonstrates how to generate a beeping sound with the buzzer, controlled by the ESP32.

  • Demonstration: Once the code is uploaded, the ESP32 module activates the buzzer, producing a beeping sound.

Video

Related On-line Tutorials

Video 14: Playing Custom Music Note

In this tutorial, you’ll learn how to use the SunFounder ESP32 IoT Learning Kit to play custom musical notes:

  • Passive Buzzer Introduction: Unlike the previous tutorial with an active buzzer, this one uses a passive buzzer which requires an external signal for sound generation.

  • Wiring Guide: Detailed instructions to correctly wire the passive buzzer to the ESP32 module.

  • Buzzer Specifications: The passive buzzer operates on 3 to 5 volts and can produce varying tones based on the input signal frequency.

  • Arduino Code Overview: The tutorial explains how to write and upload code to ESP32 for generating different musical notes through PWM signals.

  • Musical Note Project: Create a setup to play a series of musical notes with the passive buzzer controlled by ESP32.

  • Project Execution: Demonstrates the playing of musical notes once the code is successfully uploaded to the ESP32 module.

Video

Related On-line Tutorials

Video 15: DC Motor Speed Control with ESP32 L293D

This tutorial covers controlling a DC motor using ESP32 and the L293D motor driver:

  • Motor Control Basics: Learn how to control a DC motor’s direction and speed with ESP32.

  • L293D Motor Driver: Introduction to the L293D driver, essential for interfacing the motor with ESP32.

  • Two Projects: The first project controls motor direction, and the second adjusts the motor’s speed.

  • Arduino Code Explanation: Detailed walkthrough of the Arduino code for motor speed and direction control.

  • Practical Demonstration: See the motor in action, demonstrating speed variation and directional change.

Video

Related On-line Tutorials

Video 16: Mini Water Pump using ESP32 and L293D

This tutorial teaches how to control a 5V DC water pump with ESP32 and L293D motor driver:

  • Water Pump Basics: Understand the functionality of a 5V DC water pump included in the SunFounder kit.

  • Using L293D with ESP32: Learn how L293D motor driver helps in interfacing the water pump with ESP32.

  • Project Setup: Step-by-step guidance on connecting the water pump to ESP32 using L293D.

  • Arduino Programming: Detailed walkthrough of the Arduino code for controlling the water pump.

  • Practical Demonstration: Experience the water pump in action, showing how to start and stop it using ESP32.

Video

Related On-line Tutorials

Video 17: Controlling Servo Motor

Learn how to control a servo motor using ESP32 and a potentiometer in this comprehensive tutorial:

  • Understanding Servo Motors: Introduction to micro servo motors, their types, and applications. The tutorial focuses on the SG90 servo motor.

  • Servo Motor Control: Detailed explanation of how to control the servo motor’s precise angles using ESP32.

  • Hardware Setup: Instructions for setting up the servo motor with the ESP32 module and a potentiometer.

  • Arduino Programming: The tutorial covers programming the ESP32 to control the servo motor, including reading potentiometer values and mapping them to servo angles.

  • Practical Demonstration: Observe the servo motor in action, showing how its position changes in response to the potentiometer adjustments.

Video

Related On-line Tutorials

Video 18: Detecting Tilt

This video tutorial demonstrates how to use an ESP32 microcontroller with a tilt switch to control an LED, showcasing the setup, wiring, coding, and testing phases of the project.

  • Project Overview: Introduction to using the SunFounder ESP32 for detecting tilt angles with a tilt switch and LED indication.

  • Component Details: Explanation of the tilt switch mechanism, and the list of components required for the project.

  • Wiring Setup: Step-by-step guide on connecting the tilt switch and LED to the ESP32, including a schematic overview.

  • Coding Tutorial: Detailed walkthrough of the Arduino code needed to read the tilt switch state and control the LED.

  • Practical Demonstration: Real-time testing to show how the LED’s state changes in response to the tilt switch’s position.

  • Board and Port Selection: Instructions on how to select the ESP32 board and correct port in the Arduino IDE before code upload.

Video

Related On-line Tutorials

Video 19: Detecting Obstacles

Learn how to use an ESP32 module and an infrared obstacle avoidance sensor to detect obstacles, with practical demonstrations including buzzer feedback.

  • Starter Kit Components: Detailed look at the ESP32 starter kit from SunFounder.

  • Obstacle Avoidance Module: Explains the module’s operation, wiring, and adjustment.

  • Arduino Setup: Setting up the Arduino IDE for ESP32 development.

  • Coding Walkthrough: Guide to coding for obstacle detection and buzzer feedback.

  • Sensitivity Adjustment: How to adjust the module’s sensitivity for reliable detection.

Video

Related On-line Tutorials

Video 20: Line Tracking

This tutorial demonstrates how to use the ESP32 module with a line detection module for robotics applications, including real-time line following and auditory feedback via a buzzer.

  • Starter Kit Overview: Components and capabilities of the SunFounder ESP32 starter kit.

  • Line Detection Mechanism: How the line detection module uses infrared to distinguish between different colored lines on surfaces.

  • Setup Instructions: Step-by-step guide on wiring and coding the ESP32 with the line detection module and buzzer.

  • Sensitivity Adjustment: Tips for adjusting the line detection module’s sensitivity for optimal performance.

  • Practical Demonstration: Showcasing the module’s ability to follow a line and provide auditory feedback when detecting lines.

Video

Related On-line Tutorials

Video 21: Detecting Human

Learn how to set up a human motion detection system using a PIR sensor with the ESP32 module, and get notified through LED and buzzer alerts.

  • Starter Kit Components: Overview of the SunFounder ESP32 starter kit and its 320+ components for various projects.

  • PIR Sensor Mechanics: Understanding the functionality of the PIR motion sensor, including its adjustment knobs for delay and sensitivity.

  • Wiring and Coding: Instructions on connecting the PIR sensor to the ESP32 and coding the module to react to motion detection.

  • Sensitivity Adjustment: Tips for adjusting the PIR sensor to fine-tune motion detection range and response time.

  • Practical Demonstration: Showcasing the project in action, with the ESP32 triggering LED and buzzer alerts upon detecting motion.

Video

Related On-line Tutorials

Video 22: Feeling The light

Learn how to measure and interpret light intensity using a Light Dependent Resistor (LDR) with ESP32, from circuit setup to programming and readings analysis.

  • LDR Functionality: Understand how LDRs react to light and their application in measuring light intensity.

  • Circuit Setup: Step-by-step guide on connecting LDR to ESP32, including breadboard arrangement and component connections.

  • Programming ESP32: Detailed instructions on writing and uploading code to ESP32 using Arduino IDE to read and interpret light intensity.

  • Analog-to-Digital Conversion: Insights into how ESP32 converts analog signals from LDR into digital values for light intensity analysis.

  • Reading and Analysis: Demonstrating the process of reading analog values and converting them to voltage for precise light intensity measurement.

  • Practical Application: Tips on using these measurements for practical applications, like controlling devices based on light levels.

Video

Related On-line Tutorials

Video 23: Reading Voltage of potentiometer

Learn how to use the ESP32 module to read DC voltage from a potentiometer and adjust LED brightness through analog to digital conversion and PWM.

  • Potentiometer Basics: Understanding how potentiometers measure voltage and their role in controlling LED brightness.

  • Analog to Digital Conversion: How to set up the ESP32 to convert analog signals from a potentiometer to digital values.

  • PWM for LED Dimming: Implementing pulse-width modulation on the ESP32 to adjust LED brightness based on potentiometer readings.

  • Project Setup: Detailed guide on wiring, coding, and troubleshooting for effective voltage measurement and LED control.

Video

Related On-line Tutorials

Video 24: Measuring Soil Mositure

Learn how to measure soil moisture accurately using a capacitive soil moisture sensor with an ESP32 microcontroller, including wiring, coding, and practical demonstrations.

  • Introduction: Discover how to utilize a capacitive soil moisture sensor with an ESP32 microcontroller for applications like irrigation automation and environmental sensing.

  • Components: Understand the essential components needed for the project, including the ESP32 microcontroller, camera extension board, jumper wires, and soil moisture sensor module.

  • Sensor Operation: Gain insights into how the soil moisture sensor module operates, including its circuitry and the principle behind capacitance measurement.

  • Wiring Setup: Learn how to properly wire the soil moisture sensor to the ESP32 microcontroller, both directly and using the SunFounder ESP32 camera extension module.

  • Arduino Code: Explore the process of uploading and configuring Arduino code to read analog values from the sensor and display them on the serial monitor.

  • Buzzer Implementation: Discover how to implement a buzzer to provide alerts based on predefined moisture thresholds, demonstrated through practical testing with different soil moisture levels.

Video

Related On-line Tutorials

Video 25: Measuring Temperature

Learn how to measure temperature accurately using an NTC thermistor with an ESP32 microcontroller, including wiring, coding, and demonstrations with an LCD display.

  • NTC Thermistors: Understand how Negative Temperature Coefficient thermistors work for temperature measurement.

  • ESP32 Microcontroller: Explore the features of the ESP32 microcontroller, including Wi-Fi and Bluetooth capabilities.

  • Wiring Setup: Learn the proper wiring setup to connect the NTC thermistor and other components to the ESP32.

  • Temperature Calculation: Discover the formula used to calculate temperature from the resistance measured by the NTC thermistor.

  • LCD Display: Connect an LCD display to the ESP32 to visualize temperature values in Celsius and Fahrenheit.

  • SunFounder Extension Module: Utilize the SunFounder ESP32 camera extension module for standalone operation, complete with a built-in battery and charger.

Video

Related On-line Tutorials

Video 26: Using Joystick

Learn how to wire a joystick to an ESP32 microcontroller, covering detailed explanations, wiring configurations, code implementation, and testing.

  • Joystick components: Understand the components of the joystick, including variable resistors and switches.

  • Wiring configuration: Follow step-by-step instructions on how to wire the joystick to the ESP32 microcontroller, covering connections for analog pins, switches, power, and ground.

  • Code implementation: Learn how to write and upload code to the ESP32 microcontroller using the Arduino IDE, including code for reading joystick values and taking actions based on those values.

  • Testing and troubleshooting: Discover how to test the joystick setup using the serial monitor and troubleshoot common issues, such as incorrect wiring or code errors.

Video

Related On-line Tutorials

Video 27: Measuring Distanc

Learn how to use an ultrasonic sensor with an ESP32 microcontroller for accurate distance measurement and trigger actions based on distance thresholds.

  • Ultrasonic Sensor Basics: Understand how ultrasonic sensors work by emitting waves and measuring their reflection for distance calculation.

  • Documentation Reference: Access the documentation on docs.sunFounder.com for setup guidance for the ESP32 and ultrasonic sensor.

  • Ultrasonic Sensor Specifications: Learn about the HC-SR04 ultrasonic sensor’s specifications, including pin configuration and operating parameters.

  • Wiring Configuration: Follow instructions to correctly wire the ultrasonic sensor to the ESP32 microcontroller for seamless integration.

  • Code Explanation: Dive into the code explanation for interfacing with the ultrasonic sensor, including initializing pins and calculating distance from time measurements.

  • Practical Demonstration: Witness a practical demonstration of distance measurement using the setup, including accuracy verification and triggering actions based on predefined distance thresholds.

Video

Related On-line Tutorials

Video 28: DHT11 Temperature Sensor with LCD

Learn how to set up a DHT11 temperature and humidity sensor with an ESP32 microcontroller, covering wiring, code explanation, and practical demonstrations.

  • DHT11 Sensor Setup: Learn how to connect the DHT11 sensor to the ESP32 and read temperature and humidity data.

  • Arduino IDE Libraries: Instructions on installing and using the necessary libraries for the DHT11 sensor.

  • Code Explanation: Detailed walkthrough of the Arduino code for accurate data reading and display.

  • LCD Data Display: Steps to display temperature and humidity readings on an LCD screen.

  • Buzzer Alert System: How to implement a buzzer that activates when the temperature exceeds a specific limit.

  • ESP32 Power Management: Overview of powering the ESP32 and managing its power consumption efficiently.

Video

Related On-line Tutorials

Video 29: Reading IR remote key press

Learn how to connect and program an ESP32 board to decode infrared signals from a remote control, including setting up a buzzer for audible feedback on specific button presses.

  • IR Receiver Setup: Instructions on wiring the IR receiver to the ESP32 board and the necessary components for the setup.

  • Library Installation: Guide on installing the IRremote ESP8266 Library to handle infrared signals within the Arduino IDE.

  • Signal Decoding: How to decode infrared signals from a remote control and map them to specific actions using ESP32.

  • Buzzer Feedback: Demonstrating how to add a buzzer that activates when a certain remote control button is pressed.

  • Remote Control Keys: Explanation of decoding and using various keys from the remote control for different inputs.

  • Safe Power Management: Tips on managing the ESP32’s power consumption and ensuring the safety of connected components.

Video

Related On-line Tutorials

Video 30: Servo Control with MQTT

Learn how to control servo motors remotely over Wi-Fi using an ESP32 microcontroller and MQTT protocol, from setting up MQTT with Adafruit IO to wiring the servo and programming the ESP32.

  • Servo Motor Control: Control the position of a servo motor remotely with an ESP32 microcontroller.

  • Introduction to MQTT: Understand MQTT protocol’s lightweight, bidirectional, and scalable nature, essential for IoT applications.

  • Setting Up Adafruit IO: Step-by-step guide to creating an account, setting up a dashboard, and configuring MQTT feeds for communication.

  • Wiring the Servo Motor: Learn how to wire the servo motor to the ESP32 and external power supply.

  • Explaining the Code: Understand the Arduino code for ESP32, including Wi-Fi and MQTT setup, servo motor control, and error handling.

  • Project Demonstration: See the project in action, controlling the servo motor remotely over Wi-Fi and MQTT, with a demonstration of the need for an external power supply for the servo.

Video

Video 31: Flowing Light

Learn how to create an interactive flowing light effect using a WS2812 LED strip, controlled by an ESP32 board and reacting to obstacles with color changes.

  • WS2812 LED Strip Control: Using ESP32 to individually control the colors and patterns of an LED strip.

  • Infrared Obstacle Avoidance: Integration of an obstacle sensor to dynamically change the light pattern upon detection.

  • Arduino IDE and Libraries: Guidance on installing the Adafruit NeoPixel library and setting up the Arduino environment for ESP32.

  • Sensor Adjustment: Detailed instructions on adjusting the infrared obstacle sensor for optimal performance.

  • Dynamic Light Interaction: Demonstrating how the LED strip changes direction and color based on obstacle detection.

  • Code Customization: Tips on modifying the code to customize the LED response, including setting specific colors for certain conditions.

Video

Related On-line Tutorials

Video 32: Reversing Aid

Learn how to create a vehicle reversing aid using ESP32, featuring distance measurement with an ultrasonic sensor, visual feedback on an LCD, and audio alerts with a buzzer.

  • Ultrasonic Sensor Integration: Utilizing the sensor for accurate distance measurement to obstacles.

  • LCD Feedback: Displaying real-time distance measurements for the driver’s convenience.

  • Audio Alerts: Programming the buzzer to emit faster beeps as the vehicle gets closer to an obstacle, enhancing safety.

  • Energy Efficiency: Demonstrating how to safely power the buzzer from the ESP32 by measuring current consumption.

  • Comprehensive Guide: Detailed explanation of wiring, coding, and the logic behind varying beep intervals based on distance.

  • Real-World Application: Showcasing the system installed on a vehicle and tested against a wall to simulate reversing towards an obstacle.

Video

Related On-line Tutorials

Video 33: Digital Dice

This tutorial shows how to build a digital dice using an ESP32 board and a 7-segment display, featuring a push button to roll the dice and display numbers 1 through 6 randomly.

  • Digital Dice Concept: Introduction to the project and its electronic components.

  • Wiring Setup: Step-by-step guide to connecting the ESP32 board with the 7-segment display and push button.

  • Code Walkthrough: Detailed explanation of the Arduino code for number generation and display management.

  • Random Number Generation: Methodology for creating random dice outcomes with a push button.

  • Display Initialization: Tips for ensuring the 7-segment display shows a clear screen upon startup.

  • Project Assembly: Instructions for assembling and troubleshooting the digital dice project for optimal performance.

Video

Related On-line Tutorials

Video 34: Color Gradient

Learn to create vibrant color gradients using an ESP32 board, an RGB LED, and a potentiometer, showcasing how to wire and program the components for dynamic color changes.

  • RGB LED Basics: Introduction to RGB LED functionality, including anode/cathode configurations.

  • Wiring Setup: Step-by-step guide for connecting the RGB LED and potentiometer to the ESP32.

  • Arduino Programming: Detailed code explanation for translating potentiometer input into a wide range of colors using PWM.

  • Color Theory Application: Demonstrating how to mix red, green, and blue to achieve various hues and gradients.

  • Potentiometer Control: How to use a potentiometer to seamlessly adjust the color output of the RGB LED.

  • Practical Demonstration: Live demonstration of changing the RGB LED colors by adjusting the potentiometer, highlighting the project’s interactive nature.

Video

Related On-line Tutorials

Video 35: Plant Monitor

This tutorial demonstrates how to build a smart plant monitoring system using an ESP32 board, which measures temperature, humidity, soil moisture, and light, and displays the data on an LCD. It also includes a manual water pump control feature.

  • Comprehensive Monitoring: Utilizes DHT11, soil moisture sensor, and LDR to monitor plant health indicators.

  • LCD Display Integration: Shows real-time data readings on an LCD screen for easy monitoring.

  • Water Pump Control: Includes a manual push button to activate a water pump for plant watering.

  • ESP32 and Component Overview: Explains the functionality of each component and their integration.

  • Practical Demonstration: Shows the system in action, providing a clear example of its capabilities.

  • Arduino Code and Setup: Walks through the Arduino code required for the project, including setup and sensor readings.

Video

Related On-line Tutorials

Video 36: Guessing Number Game

This tutorial guides you through creating an engaging number guessing game controlled via an infrared remote, utilizing an ESP32 board and an LCD for real-time feedback.

  • Component Overview: Introduction to using the ESP32, infrared receiver and transmitter, and LCD display for building interactive projects.

  • Wiring Setup: Detailed instructions on connecting the infrared receiver to the ESP32 and interfacing with the LCD display.

  • Arduino Coding: Step-by-step code walkthrough for receiving infrared signals, generating random numbers, and displaying game status on the LCD.

  • Game Mechanics: How to use the infrared remote to guess numbers within a range, with the game providing hints towards the correct answer.

  • Environment Setup: Configuring the Arduino IDE for ESP32 development, including board and port selection.

  • Live Demonstration: Showing the game in action, highlighting the interaction between the infrared remote inputs and LCD feedback.

Video

Related On-line Tutorials

Video 37: Bluetooth

Learn how to set up Bluetooth Low Energy (BLE) communication between an ESP32 module and a smartphone, including pairing, sending, and receiving messages using the Arduino IDE and the Light Blue app.

  • BLE Communication Setup: Introduction to setting up BLE communication using an ESP32 module.

  • Light Blue App Installation: Instructions on installing and using the Light Blue app for BLE testing with a smartphone.

  • UUID Generation: How to generate a unique UUID for BLE services to ensure unique identification.

  • Arduino Code Walkthrough: Detailed explanation of the Arduino code necessary for establishing BLE communication.

  • Device Pairing and Messaging: Step-by-step guide on pairing the ESP32 with a smartphone and exchanging messages.

  • Practical Demonstration: Real-time demonstration of sending and receiving messages between the ESP32 and a smartphone via BLE.

Video

Related On-line Tutorials

Video 38: Bluetooth Control RGB LED

Learn how to wirelessly control an RGB LED’s color using an ESP32 module via Bluetooth commands from a mobile app, including setup, coding, and a live demonstration.

  • Understanding RGB LEDs: Explanation of RGB LED pins, and how to wire them with resistors for color control.

  • Project Setup: Step-by-step guide on connecting the ESP32 to an RGB LED and resistors on a breadboard.

  • Arduino Programming: How to program the ESP32 using the Arduino IDE to receive Bluetooth commands and control the LED color.

  • Bluetooth Communication: Setting up and using the Light Blue app to send color change commands to the ESP32.

  • Code Breakdown: Detailed explanation of the code, focusing on Bluetooth service creation, handling color commands, and adjusting LED colors.

  • Live Demo: Showing real-time color changes on the RGB LED when receiving commands from the mobile app.

This tutorial is perfect for beginners interested in exploring wireless communication and LED control with the ESP32. Join us to add a splash of color to your projects!

Video

Related On-line Tutorials

Video 39: Bluetooth Audio Player

Learn how to build a Bluetooth audio player using ESP32, DAC, and an audio amplifier, from wiring to code setup and practical demonstration.

  • ESP32 Setup: Utilizing ESP32 with a digital-to-analog converter (DAC) for audio output.

  • Library Installation: Installing the ESP32 A2DP library for Bluetooth audio functionality.

  • Amplification: Connecting an audio amplifier to enhance the audio signal.

  • Wiring Configuration: Detailed instructions on wiring ESP32, amplifier, and resistor.

  • IDE Setup: Setting up the Arduino IDE environment for programming.

  • Bluetooth Pairing: Pairing and connecting the ESP32 Bluetooth audio player with a mobile device for seamless audio playback.

Video

Related On-line Tutorials

Video 40: Reading and writing to Micro SD Card

Learn how to effectively utilize micro SD cards with the SunFounder ESP32 IoT Learning Kit, covering formatting, code implementation, and practical demonstrations.

  • Introduction: Get started with using micro SD cards in conjunction with the SunFounder ESP32 learning kit.

  • Formatting SD Card: Understand the requirements for formatting micro SD cards and ensure compatibility with the ESP32.

  • Arduino Code: Explore the Arduino code provided for reading and writing files to the SD card.

  • Board Setup: Learn how to select the ESP32 board and COM port in the Arduino IDE for seamless integration.

  • Uploading and Testing: Follow along with the process of uploading code to the ESP32 and monitoring serial output for file operations.

Video

Related On-line Tutorials

Video 41: MP3 Player with SD Card Support

Learn how to play audio files from a micro SD card using the SunFounder ESP32 learning kit, connecting the ESP32 with an audio amplifier and speaker for sound output.

  • Introduction: Discover how to combine micro SD card functionality with the ESP32 for audio playback.

  • Audio Amplifier: Understand the importance of using an audio amplifier to drive speaker output effectively.

  • MP3 Player with SD Card Support: Access documentation and code examples for implementing an MP3 player with micro SD card support.

  • Hardware Setup: Follow step-by-step instructions for connecting the audio amplifier, speaker, and ESP32 board.

  • File Formatting: Ensure the micro SD card is formatted to FAT32 with a maximum capacity of 32 GB for compatibility.

  • Arduino IDE Setup: Learn how to select the ESP32 board and COM port in the Arduino IDE, as well as install necessary libraries for audio playback.

Video

Related On-line Tutorials

Video 42: Capturing Photos

Learn how to capture photos using the SunFounder ESP32 camera extension board, from setting up the hardware to understanding the code and retrieving the captured photos.

  • Introduction: Explore the process of capturing photos with the ESP32 camera extension board.

  • Camera Extension Board Setup: Follow instructions for connecting the ESP32 board and camera extension board.

  • Code Explanation: Understand the code logic for capturing and saving photos on the micro SD card.

  • Photo Numbering: Learn about the numbering system used for saving photos and storing them on the micro SD card.

  • Camera Resolution: Discover the resolution capabilities of the OV2640 camera model used in the setup.

  • Arduino IDE Setup: Step-by-step guide for configuring the Arduino IDE to upload the code and operate the camera extension board.

Video

Related On-line Tutorials

Video 43: IoT Internet Weather Station

Learn how to create a real-time weather station using the SunFounder ESP32 IoT Learning Kit and the OpenWeatherMap API, from setting up hardware to displaying weather data on an LCD screen.

  • OpenWeatherMap API: Access weather data like temperature and humidity through the OpenWeatherMap API.

  • Hardware setup: Connect the ESP32 board, extension board, jumper wires, and LCD screen following the provided wiring diagram.

  • Code explanation: Understand the Arduino code for Wi-Fi setup, API requests, JSON parsing, and displaying weather data on the LCD.

  • Selecting ESP32 board and port: Learn how to choose the ESP32 board and the correct port in Arduino IDE for uploading the code.

  • Modifying code for display: Adjust the code to accurately display weather information on the LCD screen, including handling temperature values.

  • Demonstration: See the weather station in action, displaying real-time weather data on the LCD screen.

Video

Related On-line Tutorials

Video 44: Camera Web Server

Learn how to set up and stream video with the ESP32 camera extension board, covering hardware connection, code configuration, accessing the stream, and adjusting stream settings.

  • Hardware setup: Attach the ESP32 camera extension board to the ESP32 board following the provided demonstration.

  • Code explanation: Understand the Arduino code for configuring Wi-Fi, camera settings, and streaming configurations.

  • Setting up in Arduino IDE: Instructions on selecting the ESP32 board and port in the Arduino IDE for uploading the code.

  • Accessing the stream: Learn how to access the video stream via a web browser using the ESP32’s IP address.

  • Stream settings: Explore various stream settings like resolution, effects, and flipping options to customize the video output.

  • Demonstration: Witness a live demonstration of video streaming from the ESP32 camera extension board and discover its advantages over other camera options.

Video

Related On-line Tutorials

Video 45: Camera Web Server

Learn how to set up and stream video with the ESP32 camera extension board, covering hardware connection, code configuration, accessing the stream, and adjusting stream settings.

  • Hardware setup: Attach the ESP32 camera extension board to the ESP32 board following the provided demonstration.

  • Code explanation: Understand the Arduino code for configuring Wi-Fi, camera settings, and streaming configurations.

  • Setting up in Arduino IDE: Instructions on selecting the ESP32 board and port in the Arduino IDE for uploading the code.

  • Accessing the stream: Learn how to access the video stream via a web browser using the ESP32’s IP address.

  • Stream settings: Explore various stream settings like resolution, effects, and flipping options to customize the video output.

  • Demonstration: Witness a live demonstration of video streaming from the ESP32 camera extension board and discover its advantages over other camera options.

Video

Related On-line Tutorials

Video 46: IoT Communication with MQTT

Learn how to integrate an ESP32 microcontroller with a temperature sensor, LED, and push button for MQTT communication in this comprehensive tutorial.

  • Introduction: Discover how to use an ESP32 microcontroller with a temperature sensor, LED, and push button.

  • MQTT Protocol: Understand the lightweight, bidirectional, and scalable nature of MQTT, along with its reliability and security features.

  • Wiring Setup: Get insights into the wiring connections required for the temperature sensor, LED, and push button.

  • Arduino Code Explanation: Dive into the Arduino code setup, including Wi-Fi configuration, MQTT client setup, and message handling.

  • Board and COM Port Selection: Learn how to select the ESP32 board and COM port in the Arduino IDE.

  • HiveMQ Free Broker Demonstration: See a step-by-step demonstration of using the HiveMQ Free broker for MQTT communication, including publishing temperature data and controlling the LED remotely.

Video

Related On-line Tutorials

Video 47: CheerLights

Learn how to create an IoT CheerLights system using an ESP32 microcontroller, enabling synchronized color changes globally through MQTT communication.

  • MQTT Communication: Understand how MQTT works for subscribing to feeds and receiving information, demonstrated with the CheerLights feed.

  • Hardware Setup: Learn how to connect the ESP32 microcontroller with the camera extension module and WS2812 LED lights.

  • Library Installation: Install necessary libraries for MQTT communication and controlling WS2812 LEDs in the Arduino IDE.

  • Coding: Explore the code for setting up Wi-Fi, connecting to MQTT server, handling messages, and changing LED colors accordingly.

  • Board and Port Selection: Get instructions on selecting the ESP32 Dev board and the correct port in the Arduino IDE.

  • Demonstration: See a demo of the CheerLights system in action, including local and global color changes through MQTT and monitoring via the serial monitor.

Video

Related On-line Tutorials

Video 50: Temperature and Humidity Monitoring with Adafruit IO

Learn how to set up an ESP32 IoT project using MQTT and Adafruit IO, from hardware setup to code uploading and dashboard creation.

  • ESP32 Starter Kit Introduction: Overview of the components needed for the project.

  • MQTT Explanation: Understand the significance of MQTT in IoT applications.

  • Adafruit IO Setup: Step-by-step guide to creating an account and dashboard on Adafruit IO.

  • Hardware Wiring Guide: Detailed instructions on wiring the ESP32, DHT11 temperature sensor, and LED.

  • Arduino Code Walkthrough: Explanation of the code including library installation, Wi-Fi setup, and MQTT connection.

  • Project Demonstration: Watch the process of uploading the code, monitoring data on Adafruit IO dashboard, and remotely controlling the LED.

Video

Related On-line Tutorials

Video 50: Control RGB LED from anywhere in the world

Learn how to control RGB LEDs remotely using an ESP32 microcontroller, Wi-Fi, and MQTT protocol, including hardware setup, Adafruit IO configuration, MQTT basics, Arduino coding, and Color Picker usage.

  • Introduction to the project: Using ESP32 microcontroller with Wi-Fi and MQTT to control RGB LEDs.

  • What is MQTT: Lightweight messaging protocol for bidirectional communication.

  • Adafruit IO setup: Creating Adafruit IO account, configuring dashboards, feeds, and controls.

  • Wiring explained: Explanation of wiring connections for RGB LEDs with resistors to ESP32.

  • Code explained: Overview of Arduino code for subscribing to MQTT topics and controlling LEDs.

  • Selecting ESP32 board and COM port: Demonstrating board and port selection in Arduino IDE.

  • Project demonstration: Live demo of adjusting RGB LED colors using sliders and Color Picker.

  • What is RGB LED?: Explanation of RGB LED structure and operation.

  • RGB Color: Understanding RGB color combinations and mixing using a Color Picker.

Video

Video 51: IoT Temperature Monitoring System

Learn how to create a temperature monitoring system using an ESP32 microcontroller and Wi-Fi connectivity, covering hardware setup, code development, and accessing temperature data via a web server.

  • IoT Introduction: Understand the basics of Internet of Things (IoT) and its applications.

  • Wi-Fi Setup: Configure the ESP32 microcontroller to function as a web server using Wi-Fi.

  • Temperature Data Access: Learn how to access real-time temperature data via a web browser or mobile device.

  • Arduino Code Overview: Get insights into the Arduino code structure for the project, including configuration settings and client request handling.

  • Board and COM Port Selection: Step-by-step instructions on selecting the ESP32 board and COM port in the Arduino IDE.

  • Practical Demonstration: Watch a live demonstration showcasing the system in action, from code uploading to accessing temperature data remotely.

Video

Video 52: CheerLights Global Sync with LCD

Learn how to synchronize LED colors across multiple devices using the Cheer Lights project, integrated with an ESP32 microcontroller and an LCD screen for real-time feedback.

  • Introduction to Cheer Lights: Previous tutorials covered essential topics like RGB LED and LCD screen usage.

  • Cheer Lights with MQTT: Synchronize LED colors through MQTT subscriptions for a shared experience.

  • Integration with ESP32 and LCD Screen: Connect Cheer Lights to an ESP32 microcontroller with an LCD screen for displaying colors and connectivity status.

  • Connecting to Wi-Fi: The ESP32 connects to Wi-Fi, displaying the SSID when connected and attempting to reconnect if disconnected.

  • Interaction with Cheer Lights Group: Interact with the Cheer Lights group on Discord to change colors and participate in the shared experience.

  • Setup and Coding: Detailed instructions provided on setting up the ESP32 board, selecting the correct port, and installing necessary libraries for integrating Cheer Lights with the ESP32 and LCD screen.

Video

Video 53: Internet Clock

Learn how to build an Internet clock using ESP32 microcontroller, NTP server, and Wi-Fi connectivity, allowing for automatic time adjustment without the need for a real-time module.

  • Introduction: Discover how to create an Internet clock without requiring a real-time module.

  • ESP32 Microcontroller: Understand the role of ESP32 with Wi-Fi in automatically adjusting the time.

  • NTP Server: Learn about NTP servers and their function in synchronizing time over the internet.

  • Setting up: Follow the steps to set up the ESP32 board in Arduino IDE and select the appropriate COM port.

  • Arduino code explanation: Dive into the Arduino code for the Internet clock project, including Wi-Fi setup, NTP server configuration, and LCD screen time display.

  • Demonstration: See the Internet clock in action with customizable time format and settings.

Video

Video 54: Mastering RGB Color Mixing and IoT Control

Learn how to master RGB color mixing principles and leverage the power of ESP32 microcontrollers for IoT applications, controlling LED strips via Wi-Fi connectivity.

  • RGB Color Mixing: Understand how to create any color using combinations of red, green, and blue (RGB) with a practical demonstration using an RGB Color Picker.

  • ESP32 IoT Applications: Explore the versatility of the ESP32 microcontroller for IoT projects, focusing on LED strip control via Wi-Fi.

  • SunFounder ESP32 Camera Extension Module: Discover the features of the SunFounder ESP32 camera extension module, including built-in battery and charger for easy power-up.

  • Wiring and Code Explanation: Dive deep into the wiring setup and code structure for controlling LED strips with detailed explanations of library installations, color selection, Wi-Fi setup, and client request handling.

  • Selecting ESP32 Board and Port: Step-by-step guidance on selecting the ESP32 board and port in the Arduino IDE, along with troubleshooting tips for identifying the correct port.

  • Practical Demonstration: Witness a practical demonstration of selecting colors and controlling LED strips using the ESP32 microcontroller through a web interface on various devices like desktops, mobile phones, and tablets.

Video

For MicroPython User

This chapter is a comprehensive guide tailored specifically for users who prefer working with MicroPython. It covers various topics, including getting started with MicroPython, working with displays, generating sounds, controlling actuators, utilizing sensors, and exploring fun projects. This chapter provides MicroPython users with the necessary knowledge and resources to effectively use this kit and unleash their creativity in building exciting projects.

Here is the complete code package for the ESP32 Starter Kit. You can click on the following link to download it:

Once the download is complete, unzip the file and open the relevant example code or project files in the corresponding software. This will allow you to browse and utilize all the code and resources provided by the kit.

1. Get Started

1.1 Introduction of MicroPython

MicroPython is a software implementation of a programming language largely compatible with Python 3, written in C, that is optimized to run on a microcontroller.[3][4]

MicroPython consists of a Python compiler to bytecode and a runtime interpreter of that bytecode. The user is presented with an interactive prompt (the REPL) to execute supported commands immediately. Included are a selection of core Python libraries; MicroPython includes modules which give the programmer access to low-level hardware.

The Story Starts Here

Things changed in 2013 when Damien George launched a crowdfunding campaign (Kickstarter).

Damien was an undergraduate student at Cambridge University and an avid robotics programmer. He wanted to reduce the world of Python from a gigabyte machine to a kilobyte. His Kickstarter campaign was to support his development while he turned his proof of concept into a finished implementation.

MicroPython is supported by a diverse Pythonista community that has a keen interest in seeing the project succeed.

Apart from testing and supporting the code base, the developers provided tutorials, code libraries, and hardware porting, so Damien was able to focus on other aspects of the project.

Why MicroPython?

Although the original Kickstarter campaign released MicroPython as a development board “pyboard” with STM32F4, MicroPython supports many ARM-based product architectures. The mainline supported ports are ARM Cortex-M (many STM32 boards, TI CC3200/WiPy, Teensy boards, Nordic nRF series, SAMD21 and SAMD51), ESP8266, ESP32, 16bit PIC, Unix, Windows, Zephyr and JavaScript. Second, MicroPython allows for fast feedback. This is because you can use REPL to enter commands interactively and get responses. You can even tweak code and run it immediately instead of traversing the code-compile-upload-execute cycle.

While Python has the same advantages, for some Microcontroller boards like the ESP32, they are small, simple and have little memory to run the Python language at all. That’s why MicroPython has evolved, keeping the main Python features and adding a bunch of new ones to work with these Microcontroller boards.

Next you will learn to install MicroPython into the ESP32.

1.2 Install Thonny IDE

Before you can start to program ESP32 with MicroPython, you need an integrated development environment (IDE), here we recommend Thonny. Thonny comes with Python 3.7 built in, just one simple installer is needed and you’re ready to learn programming.

  1. You can download it by visiting the Thonny website. Once open the page, you will see a light gray box in the upper right corner, click on the link that applies to your operating system.

    _images/download_thonny.png
  2. The installers have been signed with a new certificate which hasn’t built up its reputation yet. You may need to click through your browser warning (e.g. choose “Keep” instead of “Discard” in Chrome) and Windows Defender warning (More infoRun anyway).

    _images/install_thonny1.png
  3. Next, click Next and Install to finish installing Thonny.

    _images/install_thonny6.png

1.3 Install MicroPython on the ESP32(Important)

  1. Download the MicroPython firmware for the ESP32 from the MicroPython official website and then download the latest version of the firmware.

    _images/dowload_micropython_uf2.png
  2. Connect the ESP32 WROOM 32E to your computer using a Micro USB cable.

    _images/plugin_esp32.png
  3. Click on the bottom right corner of Thonny IDE, select “MicroPython(ESP32).COMXX” from the pop-up menu, and then select “Configure interpreter”.

    _images/install_micropython1.png
  4. Click “Install or Update MicroPython” in the new pop-up window.

    _images/install_micropython2.png
  5. Select the correct port and the firmware you downloaded earlier, and click “Install”.

    _images/install_micropython3.png
  6. After a successful installation, you can close this page.

    _images/install_micropython4.png
  7. When you return to the Thonny homepage, you will see MicroPython version and ESP32-related prompts, instead of red error prompts.

    _images/install_micropython5.png

1.4 Upload the Libraries (Important)

In some projects, you will need additional libraries. So here we upload these libraries to ESP32 first, and then we can run the code directly later.

  1. Download the relevant code from the link below.

  2. Connect the ESP32 WROOM 32E to your computer using a Micro USB cable.

    _images/plugin_esp32.png
  3. Open Thonny IDE and click on the “MicroPython (ESP32).COMXX” interpreter in the bottom right corner.

    _images/sec_inter.png
  4. In the top navigation bar, click View -> Files.

    _images/th_files.png
  5. Switch the path to the folder where you downloaded the code package before, and then go to the esp32-starter-kit-main\micropython\libs folder.

    _images/th_path.png
  6. Select all the files or folders in the libs/ folder, right-click and click Upload to, it will take a while to upload.

    _images/th_upload.png
  7. Now you will see the files you just uploaded inside your drive MicroPython device.

    _images/th_done.png

1.5 Quick Guide on Thonny

Open and Run Code Directly

The code section in the projects tells you exactly which code is used, so double-click on the .py file with the serial number in the esp32-starter-kit-main\micropython\codes\ path to open it.

However, you must first download the package and upload the libraries, as described in 1.4 Upload the Libraries (Important).

  1. Open code.

    For example, 1.1_hello_led.py.

    If you double click on it, a new window will open on the right. You can open more than one code at the same time.

    _images/quick_guide1.png
  2. Plug the esp32 into your computer with a micro USB cable.

    _images/plugin_esp32.png
  3. Select correct interpreter

    Select the “MicroPython (ESP32).COMxx” interpreter.

    _images/sec_inter.png
  4. Run the code

    To run the script, click the Run current script button or press F5.

    _images/quick_guide2.png

    If the code contains any information that needs to be printed, it will appear in the Shell; otherwise, only the following information will appear.

    Click View -> Edit to open the Shell window if it doesn’t appear on your Thonny.

    MicroPython v1.19.1 on 2022-06-18; ESP32 module with ESP32
    
    Type "help()" for more information.
    
    >>> %Run -c $EDITOR_CONTENT
    
    • The first line shows the version of MicroPython, the date, and your device information.

    • The second line prompts you to enter “help()” to get some help.

    • The third line is a command from Thonny telling the MicroPython interpreter on your Pico W to run the contents of the script area - “EDITOR_CONTENT”.

    • If there is any message after the third line, it is usually a message that you tell MicroPython to print, or an error message for the code.

  5. Stop running

    _images/quick_guide3.png

    To stop the running code, click the Stop/Restart backend button. The %RUN -c $EDITOR_CONTENT command will disappear after stopping.

  6. Save or save as

    You can save changes made to the open example by pressing Ctrl+S or clicking the Save button on Thonny.

    The code can be saved as a separate file within the MicroPython drive(ESP32) by clicking on File -> Save As.

    _images/quick_guide4.png

    Select MicroPython drive.

    _images/quick_guide5.png

    Then click OK after entering the file name and extension .py. On the MicroPython drive, you will see your saved file.

    _images/quick_guide6.png

    Note

    Regardless of what name you give your code, it’s best to describe what type of code it is, and not give it a meaningless name like abc.py. When you save the code as main.py, it will run automatically when the power is turned on.

Create File and Run it

The code is shown directly in the code section. You can copy it to Thonny and run it as follows.

  1. Create a new file

    Open Thonny IDE, click New button to create a new blank file.

    _images/quick_guide7.png
  2. Copy code

    Copy the code from the project to the Thonny IDE.

    _images/quick_guide8.png
  3. Plug the esp32 into your computer with a micro USB cable.

    _images/plugin_esp32.png
  4. Select correct interpreter

    Select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

    _images/sec_inter.png
  5. Run the code

    You need click Run Current Script or simply press F5 to run it.

    _images/quick_guide9.png

    If the code contains any information that needs to be printed, it will appear in the Shell; otherwise, only the following information will appear.

    Click View -> Edit to open the Shell window if it doesn’t appear on your Thonny.

    MicroPython v1.19.1 on 2022-06-18; ESP32 module with ESP32
    
    Type "help()" for more information.
    
    >>> %Run -c $EDITOR_CONTENT
    
    • The first line shows the version of MicroPython, the date, and your device information.

    • The second line prompts you to enter “help()” to get some help.

    • The third line is a command from Thonny telling the MicroPython interpreter on your Pico W to run the contents of the script area - “EDITOR_CONTENT”.

    • If there is any message after the third line, it is usually a message that you tell MicroPython to print, or an error message for the code.

  6. Stop running

    _images/quick_guide3.png

    To stop the running code, click the Stop/Restart backend button. The %RUN -c $EDITOR_CONTENT command will disappear after stopping.

  7. Save or save as

    You can save the code by pressing Ctrl+S or clicking the Save button on Thonny. In the pop-up window, select the location where you want to save the file.

    _images/quick_guide5.png

    Then click OK or Save after entering the file name and extension .py.

    _images/quick_guide6.png

    Note

    Regardless of what name you give your code, it’s best to describe what type of code it is, and not give it a meaningless name like abc.py. When you save the code as main.py, it will run automatically when the power is turned on.

  8. Open file

    Here are two ways to open a saved code file.

    • The first method is to click the open icon on the Thonny toolbar, just like when you save a program, you will be asked if you want to open it from this computer or MicroPython device, for example, click MicroPython device and you will see a list of all the programs you have saved on the ESP32.

    • The second is to open the file preview directly by clicking View -> Files -> and then double-clicking on the corresponding .py file to open it.

1.6 (Optional) MicroPython Basic Syntax

Indentation

Indentation refers to the spaces at the beginning of a code line. Like standard Python programs, MicroPython programs usually run from top to bottom: It traverses each line in turn, runs it in the interpreter, and then continues to the next line, Just like you type them line by line in the Shell. A program that just browses the instruction list line by line is not very smart, though - so MicroPython, just like Python, has its own method to control the sequence of its program execution: indentation.

You must put at least one space before print(), otherwise an error message “Invalid syntax” will appear. It is usually recommended to standardise spaces by pressing the Tab key uniformly.

if 8 > 5:
print("Eight is greater than Five!")
>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
  File "<stdin>", line 2
SyntaxError: invalid syntax

You must use the same number of spaces in the same block of code, or Python will give you an error.

if 8 > 5:
print("Eight is greater than Five!")
        print("Eight is greater than Five")
>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
  File "<stdin>", line 2
SyntaxError: invalid syntax

Comments

The comments in the code help us understand the code, make the entire code more readable and comment out part of the code during testing, so that this part of the code does not run.

Single-line Comment

Single-line comments in MicroPython begin with #, and the following text is considered a comment until the end of the line. Comments can be placed before or after the code.

print("hello world") #This is a annotationhello world
>>> %Run -c $EDITOR_CONTENT
hello world

Comments are not necessarily text used to explain the code. You can also comment out part of the code to prevent micropython from running the code.

#print("Can't run it!")
print("hello world") #This is a annotationhello world
>>> %Run -c $EDITOR_CONTENT
hello world
Multi-line comment

If you want to comment on multiple lines, you can use multiple # signs.

#This is a comment
#written in
#more than just one line
print("Hello, World!")
>>> %Run -c $EDITOR_CONTENT
Hello, World!

Or, you can use multi-line strings instead of expected.

Since MicroPython ignores string literals that are not assigned to variables, you can add multiple lines of strings (triple quotes) to the code and put comments in them:

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")
>>> %Run -c $EDITOR_CONTENT
Hello, World!

As long as the string is not assigned to a variable, MicroPython will ignore it after reading the code and treat it as if you made a multi-line comment.

Print()

The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.

Print multiple objects:

print("Welcome!", "Enjoy yourself!")
>>> %Run -c $EDITOR_CONTENT
Welcome! Enjoy yourself!

Print tuples:

x = ("pear", "apple", "grape")
print(x)
>>> %Run -c $EDITOR_CONTENT
('pear', 'apple', 'grape')

Print two messages and specify the separator:

print("Hello", "how are you?", sep="---")
>>> %Run -c $EDITOR_CONTENT
Hello---how are you?

Variables

Variables are containers used to store data values.

Creating a variable is very simple. You only need to name it and assign it a value. You don’t need to specify the data type of the variable when assigning it, because the variable is a reference, and it accesses objects of different data types through assignment.

Naming variables must follow the following rules:

  • Variable names can only contain numbers, letters, and underscores

  • The first character of the variable name must be a letter or underscore

  • Variable names are case sensitive

Create Variable

There is no command for declaring variables in MicroPython. Variables are created when you assign a value to it for the first time. It does not need to use any specific type declaration, and you can even change the type after setting the variable.

x = 8       # x is of type int
x = "lily" # x is now of type str
print(x)
>>> %Run -c $EDITOR_CONTENT
lily
Casting

If you want to specify the data type for the variable, you can do it by casting.

x = int(5)    # y will be 5
y = str(5)    # x will be '5'
z = float(5)  # z will be 5.0
print(x,y,z)
>>> %Run -c $EDITOR_CONTENT
5 5 5.0
Get the Type

You can get the data type of a variable with the type() function.

x = 5
y = "hello"
z = 5.0
print(type(x),type(y),type(z))
>>> %Run -c $EDITOR_CONTENT
<class 'int'> <class 'str'> <class 'float'>
Single or Double Quotes?

In MicroPython, single quotes or double quotes can be used to define string variables.

x = "hello"
# is the same as
x = 'hello'
Case-Sensitive

Variable names are case-sensitive.

a = 5
A = "lily"
#A will not overwrite a
print(a, A)
>>> %Run -c $EDITOR_CONTENT
5 lily

If Else

Decision making is required when we want to execute a code only if a certain condition is satisfied.

if
if test expression:
    statement(s)

Here, the program evaluates the test expression and executes the statement only when the test expression is True.

If test expression is False, then statement(s) will not be executed.

In MicroPython, indentation means the body of the if statement. The body starts with an indentation and ends with the first unindented line.

Python interprets non-zero values ​​as “True”. None and 0 are interpreted as “False”.

if Statement Flowchart

_images/if_statement.png

Example

num = 8
if num > 0:
    print(num, "is a positive number.")
print("End with this line")
>>> %Run -c $EDITOR_CONTENT
8 is a positive number.
End with this line
if…else
if test expression:
    Body of if
else:
    Body of else

The if..else statement evaluates test expression and will execute the body of if only when the test condition is True.

If the condition is False, the body of else is executed. Indentation is used to separate the blocks.

if…else Statement Flowchart

_images/if_else.png

Example

num = -8
if num > 0:
    print(num, "is a positive number.")
else:
    print(num, "is a negative number.")
>>> %Run -c $EDITOR_CONTENT
-8 is a negative number.
if…elif…else
if test expression:
    Body of if
elif test expression:
    Body of elif
else:
    Body of else

Elif is short for else if. It allows us to check multiple expressions.

If the condition of the if is False, the condition of the next elif block is checked, and so on.

If all conditions are False, the body of else is executed.

Only one of several if…elif…else blocks is executed according to the conditions.

The if block can only have one else block. But it can have multiple elif blocks.

if…elif…else Statement Flowchart

_images/if_elif_else.png

Example

x = 10
y = 9

if x > y:
    print("x is greater than y")
elif x == y:
    print("x and y are equal")
else:
    print("x is greater than y")
>>> %Run -c $EDITOR_CONTENT
x is greater than y
Nested if

We can embed an if statement into another if statement, and then call it a nested if statement.

Example

x = 67

if x > 10:
    print("Above ten,")
    if x > 20:
        print("and also above 20!")
    else:
        print("but not above 20.")
>>> %Run -c $EDITOR_CONTENT
Above ten,
and also above 20!

While Loops

The while statement is used to execute a program in a loop, that is, to execute a program in a loop under certain conditions to handle the same task that needs to be processed repeatedly.

Its basic form is:

while test expression:
    Body of while

In the while loop, first check the test expression. Only when test expression evaluates to True, enter the body of the while. After one iteration, check the test expression again. This process continues until test expression evaluates to False.

In MicroPython, the body of the while loop is determined by indentation.

The body starts with an indentation and ends with the first unindented line.

Python interprets any non-zero value as True. None and 0 are interpreted as False.

while Loop Flowchart

_images/while_loop.png
x = 10

while x > 0:
    print(x)
    x -= 1
>>> %Run -c $EDITOR_CONTENT
10
9
8
7
6
5
4
3
2
1
Break Statement

With the break statement we can stop the loop even if the while condition is true:

x = 10

while x > 0:
    print(x)
    if x == 6:
        break
    x -= 1
>>> %Run -c $EDITOR_CONTENT
10
9
8
7
6
While Loop with Else

Like the if loop, the while loop can also have an optional else block.

If the condition in the while loop is evaluated as False, the else part is executed.

x = 10

while x > 0:
    print(x)
    x -= 1
else:
    print("Game Over")
>>> %Run -c $EDITOR_CONTENT
10
9
8
7
6
5
4
3
2
1
Game Over

For Loops

The for loop can traverse any sequence of items, such as a list or a string.

The syntax format of for loop is as follows:

for val in sequence:
    Body of for

Here, val is a variable that gets the value of the item in the sequence in each iteration.

The loop continues until we reach the last item in the sequence. Use indentation to separate the body of the for loop from the rest of the code.

Flowchart of for Loop

_images/for_loop.png
numbers = [1, 2, 3, 4]
sum = 0

for val in numbers:
    sum = sum+val

print("The sum is", sum)
>>> %Run -c $EDITOR_CONTENT
The sum is 10
The break Statement

With the break statement we can stop the loop before it has looped through all the items:

numbers = [1, 2, 3, 4]
sum = 0

for val in numbers:
    sum = sum+val
    if sum == 6:
        break
print("The sum is", sum)
>>> %Run -c $EDITOR_CONTENT
The sum is 6
The continue Statement

With the continue statement we can stop the current iteration of the loop, and continue with the next:

numbers = [1, 2, 3, 4]

for val in numbers:
    if val == 3:
        continue
    print(val)
>>> %Run -c $EDITOR_CONTENT
1
2
4
The range() function

We can use the range() function to generate a sequence of numbers. range(6) will produce numbers between 0 and 5 (6 numbers).

We can also define start, stop and step size as range(start, stop, step_size). If not provided, step_size defaults to 1.

In a sense of range, the object is “lazy” because when we create the object, it does not generate every number it “contains”. However, this is not an iterator because it supports in, len and __getitem__ operations.

This function will not store all values ​​in memory; it will be inefficient. So it will remember the start, stop, step size and generate the next number during the journey.

To force this function to output all items, we can use the function list().

print(range(6))

print(list(range(6)))

print(list(range(2, 6)))

print(list(range(2, 10, 2)))
>>> %Run -c $EDITOR_CONTENT
range(0, 6)
[0, 1, 2, 3, 4, 5]
[2, 3, 4, 5]
[2, 4, 6, 8]

We can use range() in a for loop to iterate over a sequence of numbers. It can be combined with the len() function to use the index to traverse the sequence.

fruits = ['pear', 'apple', 'grape']

for i in range(len(fruits)):
    print("I like", fruits[i])
>>> %Run -c $EDITOR_CONTENT
I like pear
I like apple
I like grape
Else in For Loop

The for loop can also have an optional else block. If the items in the sequence used for the loop are exhausted, the else part is executed.

The break keyword can be used to stop the for loop. In this case, the else part will be ignored.

Therefore, if no interruption occurs, the else part of the for loop will run.

for val in range(5):
    print(val)
else:
    print("Finished")
>>> %Run -c $EDITOR_CONTENT
0
1
2
3
4
Finished

The else block will NOT be executed if the loop is stopped by a break statement.

for val in range(5):
    if val == 2: break
    print(val)
else:
    print("Finished")
>>> %Run -c $EDITOR_CONTENT
0
1

Functions

In MicroPython, a function is a group of related statements that perform a specific task.

Functions help break our program into smaller modular blocks. As our plan becomes larger and larger, functions make it more organized and manageable.

In addition, it avoids duplication and makes the code reusable.

Create a Function
def function_name(parameters):
    """docstring"""
    statement(s)
  • A function is defined using the def keyword

  • A function name to uniquely identify the function. Function naming is the same as variable naming, and both follow the following rules.

    • Can only contain numbers, letters, and underscores.

    • The first character must be a letter or underscore.

    • Case sensitive.

  • Parameters (arguments) through which we pass values to a function. They are optional.

  • The colon (:) marks the end of the function header.

  • Optional docstring, used to describe the function of the function, we usually use triple quotes so that the docstring can be expanded to multiple lines.

  • One or more valid Micropython statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).

  • Each function needs at least one statement, but if for some reason there is a function that does not contain any statement, please put in the pass statement to avoid errors.

  • An optional return statement to return a value from the function.

Calling a Function

To call a function, add parentheses after the function name.

def my_function():
    print("Your first function")

my_function()
>>> %Run -c $EDITOR_CONTENT
Your first function
The return Statement

The return statement is used to exit a function and return to the place where it was called.

Syntax of return

return [expression_list]

The statement can contain an expression that is evaluated and returns a value. If there is no expression in the statement, or the return statement itself does not exist in the function, the function will return a None object.

def my_function():
        print("Your first function")

print(my_function())
>>> %Run -c $EDITOR_CONTENT
Your first function
None

Here, None is the return value, because the return statement is not used.

Arguments

Information can be passed to the function as arguments.

Specify arguments in parentheses after the function name. You can add as many arguments as you need, just separate them with commas.

def welcome(name, msg):
    """This is a welcome function for
    the person with the provided message"""
    print("Hello", name + ', ' + msg)

welcome("Lily", "Welcome to China!")
>>> %Run -c $EDITOR_CONTENT
Hello Lily, Welcome to China!
Number of Arguments

By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 parameters, you have to call the function with 2 arguments, not more, and not less.

def welcome(name, msg):
    """This is a welcome function for
    the person with the provided message"""
    print("Hello", name + ', ' + msg)

welcome("Lily", "Welcome to China!")

Here,the function welcome() has 2 parameters.

Since we called this function with two arguments, the function runs smoothly without any errors.

If it is called with a different number of arguments, the interpreter will display an error message.

The following is the call to this function, which contains one and one no arguments and their respective error messages.

welcome("Lily")#Only one argument
>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
TypeError: function takes 2 positional arguments but 1 were given
welcome()#No arguments
>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
TypeError: function takes 2 positional arguments but 0 were given
Default Arguments

In MicroPython, we can use the assignment operator (=) to provide a default value for the parameter.

If we call the function without argument, it uses the default value.

def welcome(name, msg = "Welcome to China!"):
    """This is a welcome function for
    the person with the provided message"""
    print("Hello", name + ', ' + msg)
welcome("Lily")
>>> %Run -c $EDITOR_CONTENT
Hello Lily, Welcome to China!

In this function, the parameter name has no default value and is required (mandatory) during the call.

On the other hand, the default value of the parameter msg is “Welcome to China!”. Therefore, it is optional during the call. If a value is provided, it will overwrite the default value.

Any number of arguments in the function can have a default value. However, once there is a default argument, all arguments on its right must also have default values.

This means that non-default arguments cannot follow default arguments.

For example, if we define the above function header as:

def welcome(name = "Lily", msg):

We will receive the following error message:

>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
SyntaxError: non-default argument follows default argument
Keyword Arguments

When we call a function with certain values, these values ​​will be assigned to arguments based on their position.

For example, in the above function welcome(), when we called it as welcome(“Lily”, “Welcome to China”), the value “Lily” gets assigned to the name and similarly “Welcome to China” to parameter msg.

MicroPython allows calling functions with keyword arguments. When we call the function in this way, the order (position) of the arguments can be changed.

# keyword arguments
welcome(name = "Lily",msg = "Welcome to China!")

# keyword arguments (out of order)
welcome(msg = "Welcome to China!",name = "Lily")

#1 positional, 1 keyword argument
welcome("Lily", msg = "Welcome to China!")

As we can see, we can mix positional arguments and keyword arguments during function calls. But we must remember that the keyword arguments must come after the positional arguments.

Having a positional argument after a keyword argument will result in an error.

For example, if the function call as follows:

welcome(name="Lily","Welcome to China!")

Will result in an error:

>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
SyntaxError: non-keyword arg after keyword arg
Arbitrary Arguments

Sometimes, if you do not know the number of arguments that will be passed to the function in advance.

In the function definition, we can add an asterisk (*) before the parameter name.

def welcome(*names):
    """This function welcomes all the person
    in the name tuple"""
    #names is a tuple with arguments
    for name in names:
        print("Welcome to China!", name)

welcome("Lily","John","Wendy")
>>> %Run -c $EDITOR_CONTENT
Welcome to China! Lily
Welcome to China! John
Welcome to China! Wendy

Here, we have called the function with multiple arguments. These arguments are packed into a tuple before being passed into the function.

Inside the function, we use a for loop to retrieve all the arguments.

Recursion

In Python, we know that a function can call other functions. It is even possible for the function to call itself. These types of construct are termed as recursive functions.

This has the benefit of meaning that you can loop through data to reach a result.

The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

def rec_func(i):
    if(i > 0):
        result = i + rec_func(i - 1)
        print(result)
    else:
        result = 0
    return result

rec_func(6)
>>> %Run -c $EDITOR_CONTENT
1
3
6
10
15
21

In this example, rec_func() is a function that we have defined to call itself (“recursion”). We use the i variable as the data, and it will decrement (-1) every time we recurse. When the condition is not greater than 0 (that is, 0), the recursion ends.

For new developers, it may take some time to determine how it works, and the best way to test it is to test and modify it.

Advantages of Recursion

  • Recursive functions make the code look clean and elegant.

  • A complex task can be broken down into simpler sub-problems using recursion.

  • Sequence generation is easier with recursion than using some nested iteration.

Disadvantages of Recursion

  • Sometimes the logic behind recursion is hard to follow through.

  • Recursive calls are expensive (inefficient) as they take up a lot of memory and time.

  • Recursive functions are hard to debug.

Data Types

Built-in Data Types

MicroPython has the following data types:

  • Text Type: str

  • Numeric Types: int, float, complex

  • Sequence Types: list, tuple, range

  • Mapping Type: dict

  • Set Types: set, frozenset

  • Boolean Type: bool

  • Binary Types: bytes, bytearray, memoryview

Getting the Data Type

You can get the data type of any object by using the type() function:

a = 6.8
print(type(a))
>>> %Run -c $EDITOR_CONTENT
<class 'float'>
Setting the Data Type

MicroPython does not need to set the data type specifically, it has been determined when you assign a value to the variable.

x = "welcome"
y = 45
z = ["apple", "banana", "cherry"]

print(type(x))
print(type(y))
print(type(z))
>>> %Run -c $EDITOR_CONTENT
<class 'str'>
<class 'int'>
<class 'list'>
>>>
Setting the Specific Data Type

If you want to specify the data type, you can use the following constructor functions:

Example

Date Type

x = int(20)

int

x = float(20.5)

float

x = complex(1j)

complex

x = str(“Hello World”)

str

x = list((“apple”, “banana”, “cherry”))

list

x = tuple((“apple”, “banana”, “cherry”))

tuple

x = range(6)

range

x = dict(name=”John”, age=36)

dict

x = set((“apple”, “banana”, “cherry”))

set

x = frozenset((“apple”, “banana”, “cherry”))

frozenset

x = bool(5)

bool

x = bytes(5)

bytes

x = bytearray(5)

bytearray

x = memoryview(bytes(5))

memoryview

You can print some of them to see the result.

a = float(20.5)
b = list(("apple", "banana", "cherry"))
c = bool(5)

print(a)
print(b)
print(c)
>>> %Run -c $EDITOR_CONTENT
20.5
['apple', 'banana', 'cherry']
True
>>>
Type Conversion

You can convert from one type to another with the int(), float(), and complex() methods: Casting in python is therefore done using constructor functions:

  • int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)

  • float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)

  • str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals

a = float("5")
b = int(3.7)
c = str(6.0)

print(a)
print(b)
print(c)

Note: You cannot convert complex numbers into another number type.

Operators

Operators are used to perform operations on variables and values.

Arithmetic Operators

You can use arithmetic operators to do some common mathematical operations.

Operator

Name

+

Addition

-

Subtraction

*

Multiplication

/

Division

%

Modulus

**

Exponentiation

//

Floor division

x = 5
y = 3

a = x + y
b = x - y
c = x * y
d = x / y
e = x % y
f = x ** y
g = x // y

print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
print(g)
>>> %Run -c $EDITOR_CONTENT
8
2
15
1.66667
2
125
1
8
2
15
>>>
Assignment operators

Assignment operators can used to assign values to variables.

Operator

Example

Same As

=

a = 6

a =6

+=

a += 6

a = a + 6

-=

a -= 6

a = a - 6

*=

a *= 6

a = a * 6

/=

a /= 6

a = a / 6

%=

a %= 6

a = a % 6

**=

a **= 6

a = a ** 6

//=

a //= 6

a = a // 6

&=

a &= 6

a = a & 6

|=

a |= 6

a = a | 6

^=

a ^= 6

a = a ^ 6

>>=

a >>= 6

a = a >> 6

<<=

a <<= 6

a = a << 6

a = 6

a *= 6
print(a)
>>> %Run test.py
36
>>>
Comparison Operators

Comparison operators are used to compare two values.

Operator

Name

==

Equal

!=

Not equal

<

Less than

>

Greater than

>=

Greater than or equal to

<=

Less than or equal to

a = 6
b = 8

print(a>b)
>>> %Run test.py
False
>>>

Return False, beause the a is less than the b.

Logical Operators

Logical operators are used to combine conditional statements.

Operator

Description

and

Returns True if both statements are true

or

Returns True if one of the statements is true

not

Reverse the result, returns False if the result is true

a = 6
print(a > 2 and a < 8)
>>> %Run -c $EDITOR_CONTENT
True
>>>
Identity Operators

Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location.

Operator

Description

is

Returns True if both variables are the same object

is not

Returns True if both variables are not the same object

a = ["hello", "welcome"]
b = ["hello", "welcome"]
c = a

print(a is c)
# returns True because z is the same object as x

print(a is b)
# returns False because x is not the same object as y, even if they have the same content

print(a == b)
# returns True because x is equal to y
>>> %Run -c $EDITOR_CONTENT
True
False
True
>>>
Membership Operators

Membership operators are used to test if a sequence is presented in an object.

Operator

Description

in

Returns True if a sequence with the specified value is present in the object

not in

Returns True if a sequence with the specified value is not present in the object

a = ["hello", "welcome", "Goodmorning"]

print("welcome" in a)
>>> %Run -c $EDITOR_CONTENT
True
>>>
Bitwise Operators

Bitwise operators are used to compare (binary) numbers.

Operator

Name

Description

&

AND

Sets each bit to 1 if both bits are 1


OR

Sets each bit to 1 if one of two bits is 1

^

XOR

Sets each bit to 1 if only one of two bits is 1

~

NOT

Inverts all the bits

<<

Zero fill left shift

Shift left by pushing zeros in from the right and let the leftmost bits fall off

>>

Signed right shift

Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off

num = 2

print(num & 1)
print(num | 1)
print(num << 1)
>>> %Run -c $EDITOR_CONTENT
0
3
4
>>>

Lists

Lists are used to store multiple items in a single variable, and are created using square brackets:

B_list = ["Blossom", "Bubbles","Buttercup"]
print(B_list)

List items are changeable, ordered, and allow duplicate values. The list items are indexed, with the first item having index [0], the second item having index [1], and so on.

C_list = ["Red", "Blue", "Green", "Blue"]
print(C_list)            # duplicate
print(C_list[0])
print(C_list[1])         # ordered
C_list[2] = "Purple"     # changeable
print(C_list)
>>> %Run -c $EDITOR_CONTENT
['Red', 'Blue', 'Green', 'Blue']
Red
Blue
['Red', 'Blue', 'Purple', 'Blue']

A list can contain different data types:

A_list = ["Banana", 255, False, 3.14]
print(A_list)
>>> %Run -c $EDITOR_CONTENT
['Banana', 255, False, 3.14]
List Length

To determine how many items are in the list, use the len() function.

A_list = ["Banana", 255, False, 3.14]
print(len(A_list))
>>> %Run -c $EDITOR_CONTENT
4
Check List items

Print the second item of the list:

A_list = ["Banana", 255, False, 3.14]
print(A_list[1])
>>> %Run -c $EDITOR_CONTENT
[255]

Print the last one item of the list:

A_list = ["Banana", 255, False, 3.14]
print(A_list[-1])
>>> %Run -c $EDITOR_CONTENT
[3.14]

Print the second, third item:

A_list = ["Banana", 255, False, 3.14]
print(A_list[1:3])
>>> %Run -c $EDITOR_CONTENT
[255, False]
Change List Items

Change the second, third item:

A_list = ["Banana", 255, False, 3.14]
A_list[1:3] = [True,"Orange"]
print(A_list)
>>> %Run -c $EDITOR_CONTENT
['Banana', True, 'Orange', 3.14]

Change the second value by replacing it with two values:

A_list = ["Banana", 255, False, 3.14]
A_list[1:2] = [True,"Orange"]
print(A_list)
>>> %Run -c $EDITOR_CONTENT
['Banana', True, 'Orange', False, 3.14]
Add List Items

Using the append() method to add an item:

C_list = ["Red", "Blue", "Green"]
C_list.append("Orange")
print(C_list)
>>> %Run -c $EDITOR_CONTENT
['Red', 'Blue', 'Green', 'Orange']

Insert an item as the second position:

C_list = ["Red", "Blue", "Green"]
C_list.insert(1, "Orange")
print(C_list)
>>> %Run -c $EDITOR_CONTENT
['Red', 'Orange', 'Blue', 'Green']
Remove List Items

The remove() method removes the specified item.

C_list = ["Red", "Blue", "Green"]
C_list.remove("Blue")
print(C_list)
>>> %Run -c $EDITOR_CONTENT
['Red', 'Green']

The pop() method removes the specified index. If you do not specify the index, the pop() method removes the last item.

A_list = ["Banana", 255, False, 3.14, True,"Orange"]
A_list.pop(1)
print(A_list)
A_list.pop()
print(A_list)
>>> %Run -c $EDITOR_CONTENT
255
['Banana', False, 3.14, True, 'Orange']
'Orange'
['Banana', False, 3.14, True]

The del keyword also removes the specified index:

C_list = ["Red", "Blue", "Green"]
del C_list[1]
print(C_list)
>>> %Run -c $EDITOR_CONTENT
['Red', 'Green']

The clear() method empties the list. The list still remains, but it has no content.

C_list = ["Red", "Blue", "Green"]
C_list.clear()
print(C_list)
>>> %Run -c $EDITOR_CONTENT
[]

2. Displays

2.1 Hello, LED!

Just as printing “Hello, world!” is the first step in learning to program, using a program to drive an LED is the traditional introduction to learning physical programming.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.1_led.png

This circuit works on a simple principle, and the current direction is shown in the figure. The LED will light up after the 220ohm current limiting resistor when pin26 outputs high level. The LED will turn off when pin26 outputs low level.

Wiring

_images/2.1_hello_led_bb.png

Run the Code

  1. Open the 2.1_hello_led.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny.

    # Import the necessary libraries
    import machine
    import time
    
    # Set up the LED on pin 26 as an output pin
    led = machine.Pin(26, machine.Pin.OUT)
    
    # Start an infinite loop
    while True:
        # Turn on the LED by setting its value to 1 (HIGH)
        led.value(1)
        # Wait for 1 second (1000 milliseconds) while the LED is on
        time.sleep(1)
    
        # Turn off the LED by setting its value to 0 (LOW)
        led.value(0)
        # Wait for 0.5 seconds (500 milliseconds) while the LED is off
        time.sleep(0.5)
    
  2. Connect the ESP32 WROOM 32E to your computer using a Micro USB cable.

    _images/plugin_esp32.png
  3. Then click on the “MicroPython (ESP32).COMXX” interpreter in the bottom right corner.

    _images/sec_inter.png
  4. Finally, click “Run Current Script” or press F5 to execute it.

    _images/quick_guide2.png
  5. After the code runs, you will see the LED blinking.

How it works?

  1. It imports two modules, machine and time. The machine module provides low-level access to the microcontroller’s hardware, while the time module provides functions for time-related operations.

    import machine
    import time
    
  2. Then set up the pin26 as an output pin using the machine.Pin() function with the machine.Pin.OUT argument.

    led = machine.Pin(26, machine.Pin.OUT)
    
  3. In the While True loop, the LED is turned on for one second by setting the value of the pin26 to 1 using led.value(1) and then set to 0(led.value(0)) to turn it off for one second, and so on in an infinite loop.

    while True:
        # Turn on the LED by setting its value to 1 (HIGH)
        led.value(1)
        # Wait for 1 second (1000 milliseconds) while the LED is on
        time.sleep(1)
    
        # Turn off the LED by setting its value to 0 (LOW)
        led.value(0)
        # Wait for 0.5 seconds (500 milliseconds) while the LED is off
        time.sleep(0.5)
    

Learn More

In this project, we used MicroPython’s machine and time module, we can find more ways to use them here.

2.2 Fading LED

In the previous project, we controlled the LED by turning it on and off using digital output. In this project, we will create a breathing effect on the LED by utilizing Pulse Width Modulation (PWM). PWM is a technique that allows us to control the brightness of an LED or the speed of a motor by varying the duty cycle of a square wave signal.

With PWM, instead of simply turning the LED on or off, we will be adjusting the amount of time the LED is on versus the amount of time it is off within each cycle. By rapidly switching the LED on and off at varying intervals, we can create the illusion of the LED gradually brightening and dimming, simulating a breathing effect.

By using the PWM capabilities of the ESP32 WROOM 32E, we can achieve smooth and precise control over the LED’s brightness. This breathing effect adds a dynamic and visually appealing element to your projects, creating an eye-catching display or ambiance.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.1_led.png

This project is the same circuit as the first project 2.1 Hello, LED!, but the signal type is different. The first project is to output digital high and low levels (0&1) directly from pin26 to make the LED light up or turn off, this project is to output PWM signal from pin26 to control the brightness of the LED.

Wiring

_images/2.1_hello_led_bb.png

Code

Note

  • Open the 2.2_fading_led.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

# Import the necessary libraries
from machine import Pin, PWM
import time

# Create a PWM object
led = PWM(Pin(26), freq=1000)

while True:
    # Gradually increase brightness
    for duty_cycle in range(0, 1024, 1):
        led.duty(duty_cycle)
        time.sleep(0.01)

    # Gradually decrease brightness
    for duty_cycle in range(1023, -1, -1):
        led.duty(duty_cycle)
        time.sleep(0.01)

The LED will gradually become brighter as the code runs.

How it works?

Overall, this code demonstrates how to use PWM signals to control the brightness of an LED.

  1. It imports two modules, machine and time. The machine module provides low-level access to the microcontroller’s hardware, while the time module provides functions for time-related operations.

    import machine
    import time
    
  2. Then initializes a PWM object for controlling the LED connected to pin 26 and sets the frequency of the PWM signal to 1000 Hz.

    led = PWM(Pin(26), freq=1000)
    
  3. Fade the LED in and out using a loop: The outer while True loop runs indefinitely. Two nested for loops are used to gradually increase and decrease the LED’s brightness. The duty cycle ranges from 0 to 1023, representing a 0% to 100% duty cycle.

    # Import the necessary libraries
    from machine import Pin, PWM
    import time
    
    # Create a PWM object
    led = PWM(Pin(26), freq=1000)
    
    while True:
        # Gradually increase brightness
        for duty_cycle in range(0, 1024, 2):
            led.duty(duty_cycle)
            time.sleep(0.01)
    
        # Gradually decrease brightness
        for duty_cycle in range(1023, -1, -2):
            led.duty(duty_cycle)
            time.sleep(0.01)
    
    • range(): Create a sequence of integers from 0 to 1023.

    • The duty cycle of the PWM signal is set to each value in the sequence using the duty() method of the PWM object.

    • time.sleep(): Pause the execution of the program for 10 milliseconds between each iteration of the loop, creating a gradual increase in brightness over time.

2.3 Colorful Light

In this project, we will delve into the fascinating world of additive color mixing using an RGB LED.

RGB LED combines three primary colors, namely Red, Green, and Blue, into a single package. These three LEDs share a common cathode pin, while each anode pin controls the intensity of the corresponding color.

By varying the electrical signal intensity applied to each anode, we can create a wide range of colors. For example, mixing high-intensity red and green light will result in yellow light, while combining blue and green light will produce cyan.

Through this project, we will explore the principles of additive color mixing and unleash our creativity by manipulating the RGB LED to display captivating and vibrant colors.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

RGB LED

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.3_rgb.png

The PWM pins pin27, pin26 and pin25 control the Red, Green and Blue pins of the RGB LED respectively, and connect the common cathode pin to GND. This allows the RGB LED to display a specific color by superimposing light on these pins with different PWM values.

Wiring

_images/rgb_pin.jpg

The RGB LED has 4 pins: the long pin is the common cathode pin, which is usually connected to GND; the left pin next to the longest pin is Red; and the two pins on the right are Green and Blue.

_images/2.3_color_light_bb.png

Code

Note

  • Open the 2.3_colorful_light.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import Pin, PWM
import time

# Define the GPIO pins for the RGB LED
RED_PIN = 27
GREEN_PIN = 26
BLUE_PIN = 25


# Set up the PWM channels
red = PWM(Pin(RED_PIN))
green = PWM(Pin(GREEN_PIN))
blue = PWM(Pin(BLUE_PIN))

# Set the PWM frequency
red.freq(1000)
green.freq(1000)
blue.freq(1000)

def set_color(r, g, b):
    red.duty(r)
    green.duty(g)
    blue.duty(b)

while True:
    # Set different colors and wait for a while
    set_color(1023, 0, 0) # Red
    time.sleep(1)
    set_color(0, 1023, 0) # Green
    time.sleep(1)
    set_color(0, 0, 1023) # Blue
    time.sleep(1)
    set_color(1023, 0, 1023) # purple
    time.sleep(1)

When the script runs, you will see the RGB LEDs display red, green, blue and purple, and so on.

Learn More

You can also set the color you want with the following code with the familiar color values of 0~255.

Note

  • Open the 2.3_colorful_light_rgb.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import Pin, PWM
import time

# Define the GPIO pins for the RGB LED
RED_PIN = 27
GREEN_PIN = 26
BLUE_PIN = 25

# Set up the PWM channels
red = PWM(Pin(RED_PIN))
green = PWM(Pin(GREEN_PIN))
blue = PWM(Pin(BLUE_PIN))

# Set the PWM frequency
red.freq(1000)
green.freq(1000)
blue.freq(1000)

# Map input values from one range to another
def interval_mapping(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

# Convert color values (0-255) to duty cycle values (0-1023)
def color_to_duty(rgb_value):
    rgb_value = int(interval_mapping(rgb_value,0,255,0,1023))
    return rgb_value

def set_color(red_value,green_value,blue_value):
    red.duty(color_to_duty(red_value))
    green.duty(color_to_duty(green_value))
    blue.duty(color_to_duty(blue_value))

while True:
    # Set different colors and wait for a while
    set_color(255, 0, 0) # Red
    time.sleep(1)
    set_color(0, 255, 0) # Green
    time.sleep(1)
    set_color(0, 0, 255) # Blue
    time.sleep(1)
    set_color(255, 0, 255) # purple
    time.sleep(1)

This code is based on the previous example, but it maps color values from 0 to 255 to a duty cycle range of 0 to 1023.

  • The interval_mapping function is a utility function that maps a value from one range to another. It takes five arguments: the input value, the minimum and maximum values of the input range, and the minimum and maximum values of the output range. It returns the input value mapped to the output range.

    def color_to_duty(rgb_value):
        rgb_value = int(interval_mapping(rgb_value,0,255,0,1023))
        return rgb_value
    
  • The color_to_duty function takes an integer RGB value (e.g. 255,0,255) and maps it to a duty cycle value suitable for the PWM pins. The input RGB value is first mapped from the range 0-255 to the range 0-1023 using the interval_mapping function. The output of interval_mapping is then returned as the duty cycle value.

    def color_to_duty(rgb_value):
        rgb_value = int(interval_mapping(rgb_value,0,255,0,1023))
        return rgb_value
    
  • The color_set function takes three integer arguments: the red, green, and blue values for the LED. These values are passed to color_to_duty to obtain the duty cycle values for the PWM pins. The duty cycle values are then set for the corresponding pins using the duty method.

    def set_color(red_value,green_value,blue_value):
        red.duty(color_to_duty(red_value))
        green.duty(color_to_duty(green_value))
        blue.duty(color_to_duty(blue_value))
    

2.4 Microchip - 74HC595

Welcome to this exciting project! In this project, we will be using the 74HC595 chip to control a flowing display of 8 LEDs.

Imagine triggering this project and witnessing a mesmerizing flow of light, as if a sparkling rainbow is jumping between the 8 LEDs. Each LED will light up one by one and quickly fade away, while the next LED continues to shine, creating a gorgeous and dynamic effect.

By cleverly utilizing the 74HC595 chip, we can control the on and off states of multiple LEDs to achieve the flowing effect. This chip has multiple output pins that can be connected in series to control the sequence of LED illumination. Moreover, thanks to the chip’s expandability, we can easily add more LEDs to the flowing display, creating even more spectacular effects.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

74HC595

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.4_74hc595_led.png
  • When MR (pin10) is high level and CE (pin13) is low level, data is input in the rising edge of SHcp and goes to the memory register through the rising edge of SHcp.

  • If the two clocks are connected together, the shift register is always one pulse earlier than the memory register.

  • There is a serial shift input pin (DS), a serial output pin (Q7’) and an asynchronous reset button (low level) in the memory register.

  • The memory register outputs a Bus with a parallel 8-bit and in three states.

  • When OE is enabled (low level), the data in memory register is output to the bus(Q0 ~ Q7).

Wiring

_images/2.4_74hc595_bb.png

Code

Note

  • Open the 2.4_microchip_74hc595.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Initialize the pins for the 74HC595 shift register
sdi = machine.Pin(25, machine.Pin.OUT)  # DS
rclk = machine.Pin(27, machine.Pin.OUT)  # STcp
srclk = machine.Pin(26, machine.Pin.OUT)  # SHcp

# Define the hc595_shift function to shift data into the 74HC595 shift register
def hc595_shift(dat):
    # Set the RCLK pin to low
    rclk.off()

    # Iterate through each bit (from 7 to 0)
    for bit in range(7, -1, -1):
        # Extract the current bit from the input data
        value = 1 & (dat >> bit)

        # Set the SRCLK pin to low
        srclk.off()

        # Set the value of the SDI pin
        sdi.value(value)

        # Clock the current bit into the shift register by setting the SRCLK pin to high
        srclk.on()

    # Latch the data into the storage register by setting the RCLK pin to high
    rclk.on()

num = 0

# Shift data into the 74HC595 to create a moving LED pattern
for i in range(16):
    if i < 8:
        num = (num << 1) + 1  # Shift left and set the least significant bit to 1
    elif i >= 8:
        num = (num & 0b01111111) << 1  # Mask the most significant bit and shift left
    hc595_shift(num)  # Shift the current value into the 74HC595
    print("{:0>8b}".format(num))  # Print the current value in binary format
    time.sleep_ms(200)  # Wait 200 milliseconds before shifting the next value

During script execution, you will see the LED light up one by one, and then turn off in the original order.

How it works?

This code is used to control an 8-bit shift register (74595), and output different binary values to the shift register, with each value displayed on an LED for a certain period of time.

  1. The code imports the machine and time modules, where the machine module is used to control hardware I/O, and the time module is used for implementing time delays and other functions.

    import machine
    import time
    
  2. Three output ports are initialized using the machine.Pin() function, corresponding to the data port (SDI), storage clock port (RCLK), and shift register clock port (SRCLK) of the shift register.

    # Initialize the pins for the 74HC595 shift register
    sdi = machine.Pin(25, machine.Pin.OUT)  # DS
    rclk = machine.Pin(27, machine.Pin.OUT)  # STcp
    srclk = machine.Pin(26, machine.Pin.OUT)  # SHcp
    
  3. A function called hc595_shift() is defined to write an 8-bit data to the shift register.

    def hc595_shift(dat):
        # Set the RCLK pin to low
        rclk.off()
    
        # Iterate through each bit (from 7 to 0)
        for bit in range(7, -1, -1):
            # Extract the current bit from the input data
            value = 1 & (dat >> bit)
    
            # Set the SRCLK pin to low
            srclk.off()
    
            # Set the value of the SDI pin
            sdi.value(value)
    
            # Clock the current bit into the shift register by setting the SRCLK pin to high
            srclk.on()
    
        # Latch the data into the storage register by setting the RCLK pin to high
        rclk.on()
    
  4. About the for loop.

    for i in range(16):
            if i < 8:
                num = (num << 1) + 1  # Shift left and set the least significant bit to 1
            elif i >= 8:
                num = (num & 0b01111111) << 1  # Mask the most significant bit and shift left
            hc595_shift(num)  # Shift the current value into the 74HC595
            print("{:0>8b}".format(num))  # Print the current value in binary format
            time.sleep_ms(200)  # Wait 200 milliseconds before shifting the next value
    
    • The variable i is used to control the output binary value. In the first 8 iterations, the value of num will be successively 00000001, 00000011, 00000111, …, 11111111, which is left-shifted by one bit and then added by 1.

    • In the 9th to 16th iterations, the highest bit of 1 is first changed to 0, and then left-shifted by one bit, resulting in the output values of 00000010, 00000100, 00001000, …, 10000000.

    • In each iteration, the value of num is passed to the hc595_shift() function to control the shift register to output the corresponding binary value.

    • At the same time as outputting the binary value, the print() function outputs the binary value as a string to the terminal.

    • After outputting the binary value, the program pauses for 200 milliseconds using the time.sleep_ms() function, so that the value on the LED remains displayed for a certain period of time.

2.5 Number Display

Welcome to this fascinating project! In this project, we will explore the enchanting world of displaying numbers from 0 to 9 on a seven-segment display.

Imagine triggering this project and witnessing a small, compact display glowing brightly with each number from 0 to 9. It’s like having a miniature screen that showcases the digits in a captivating way. By controlling the signal pins, you can effortlessly change the displayed number and create various engaging effects.

Through simple circuit connections and programming, you will learn how to interact with the seven-segment display and bring your desired numbers to life. Whether it’s a counter, a clock, or any other intriguing application, the seven-segment display will be your reliable companion, adding a touch of brilliance to your projects.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

7-segment Display

BUY

74HC595

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_2.5_74hc595_7_segment.png

Here the wiring principle is basically the same as 2.4 Microchip - 74HC595, the only difference is that Q0-Q7 are connected to the a ~ g pins of the 7 Segment Display.

Wiring

74HC595

LED Segment Display

Q0

a

Q1

b

Q2

c

Q3

d

Q4

e

Q5

f

Q6

g

Q7

dp

Wiring

_images/2.5_segment_bb.png

Code

Note

  • Open the 2.5_number_display.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Define the segment code for a common anode 7-segment display
SEGCODE = [0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f]

# Initialize the pins for the 74HC595 shift register
sdi = machine.Pin(25, machine.Pin.OUT)  # DS
rclk = machine.Pin(27, machine.Pin.OUT)  # STcp
srclk = machine.Pin(26, machine.Pin.OUT)  # SHcp

# Define the hc595_shift function to shift data into the 74HC595 shift register
def hc595_shift(dat):
    # Set the RCLK pin to low
    rclk.off()

    # Iterate through each bit (from 7 to 0)
    for bit in range(7, -1, -1):
        # Extract the current bit from the input data
        value = 1 & (dat >> bit)

        # Set the SRCLK pin to low
        srclk.off()

        # Set the value of the SDI pin
        sdi.value(value)

        # Clock the current bit into the shift register by setting the SRCLK pin to high
        srclk.on()

    # Latch the data into the storage register by setting the RCLK pin to high
    rclk.on()

# Continuously loop through the numbers 0 to 9 and display them on the 7-segment display
while True:
    for num in range(10):
        hc595_shift(SEGCODE[num])  # Shift the segment code for the current number into the 74HC595
        time.sleep_ms(500)  # Wait 500 milliseconds before displaying the next number

When the script is running, you will be able to see the LED Segment Display display 0~9 in sequence.

How it works?

In this project, we are using the hc595_shift() function to write the binary number to the shift register.

Suppose that the 7-segment Display display the number “2”. This bit pattern corresponds to the segments f, c and dp being turned off (low), while the segments a, b, d, e and g are turned on (high). This is “01011011” in binary and “0x5b” in hexadecimal notation.

Therefore, you would need to call hc595_shift(0x5b) to display the number “2” on the 7-segment display.

_images/7_segment21.png

The following table shows the hexadecimal patterns that need to be written to the shift register to display the numbers 0 to 9 on a 7-segment display.

Glyph Code

Numbers

Binary Code

Hex Code

0

00111111

0x3f

1

00000110

0x06

2

01011011

0x5b

3

01001111

0x4f

4

01100110

0x66

5

01101101

0x6d

6

01111101

0x7d

7

00000111

0x07

8

01111111

0x7f

9

01101111

0x6f

Write these codes into hc595_shift() to make the LED Segment Display display the corresponding numbers.

2.6 Display Characters

Now, we will explore the fascinating world of character display using the I2C LCD1602 module.

Through this project, we will learn how to initialize the LCD module, set the desired display parameters, and send character data to be displayed on the screen. We can showcase custom messages, display sensor readings, or create interactive menus. The possibilities are endless!

By mastering the art of character display on the I2C LCD1602, we will unlock new avenues for communication and information display in our projects. Let’s dive into this exciting journey and bring our characters to life on the LCD screen

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

I2C LCD1602

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

Usage Description

IO21

SDA

IO22

SCL

Schematic

_images/circuit_2.6_lcd.png

Wiring

_images/2.6_i2clcd1602_bb.png

Code

Note

  • Open the 2.6_liquid_crystal_display.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

  • The lcd1602.py library is used here and check if it’s uploaded to ESP32. Refer to 1.4 Upload the Libraries (Important) for a tutorial.

# Import the LCD class from the lcd1602 module
from lcd1602 import LCD

import time

# Create an instance of the LCD class and assign it to the lcd variable
lcd = LCD()
# Set the string " Hello!\n"
string = " Hello!\n"
# Display the string on the LCD screen
lcd.message(string)

time.sleep(2)
# Set the string "    Sunfounder!"
string = "    Sunfounder!"
# Display the string on the LCD screen
lcd.message(string)

time.sleep(2)
# Clear the LCD screen
lcd.clear()

After the script runs, you will be able to see two lines of text will appear on the LCD screen in turn and then disappear.

Note

If the code and wiring are correct, but the LCD still fails to display any content, you can adjust the potentiometer on the back to increase the contrast.

How it works?

In the lcd1602 library, we integrate the relevant functions of lcd1602 into the LCD class.

  1. Import lcd1602 module.

    from lcd1602 import LCD
    
  2. Declare an object of the LCD class and name it lcd.

    lcd = LCD()
    
  3. This statement will display the text on the LCD. It should be noted that the argument must be a string type. If we want to pass an integer or float, we must use the forced conversion statement str().

    lcd.message(string)
    
  4. If you call this statement multiple times, lcd will superimpose the texts. This requires the use of the following statement to clear the display.

    lcd.clear()
    

2.7 RGB LED Strip

In this project, we will delve into the mesmerizing world of driving WS2812 LED strips and bring a vibrant display of colors to life. With the ability to individually control each LED on the strip, we can create captivating lighting effects that will dazzle the senses.

Furthermore, we have included an exciting extension to this project, where we will explore the realm of randomness. By introducing random colors and implementing a flowing light effect, we can create a mesmerizing visual experience that captivates and enchants.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

WS2812 RGB 8 LEDs Strip

BUY

Schematic

_images/circuit_2.7_ws2812.png

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Note

IO33 is not available for this project.

The WS2812 LED strip is a type of LED strip that requires a precise pulse-width modulation (PWM) signal. The PWM signal has precise requirements in both time and voltage. For instance, a “0” bit for the WS2812 corresponds to a high-level pulse of about 0.4 microseconds, while a “1” bit corresponds to a high-level pulse of about 0.8 microseconds. This means the strip needs to receive high-frequency voltage changes.

However, with a 4.7K pull-up resistor and a 100nf pull-down capacitor on IO33, a simple low-pass filter is created. This type of circuit “smooths out” high-frequency signals, because the capacitor needs some time to charge and discharge when it receives voltage changes. Therefore, if the signal changes too quickly (i.e., is high-frequency), the capacitor will not be able to keep up. This results in the output signal becoming blurred and unrecognizable to the strip.

Wiring

_images/2.7_rgb_strip_bb.png

Code

Note

  • Open the 2.7_rgb_strip.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import Pin
from neopixel import NeoPixel

pin = Pin(14, Pin.OUT)   # set a pin to output to drive NeoPixels
pixels = NeoPixel(pin, 8)   # create NeoPixel driver on pin for 8 pixels

pixels[0] = [64,154,227]    # set the pixel
pixels[1] = [128,0,128]
pixels[2] = [50,150,50]
pixels[3] = [255,30,30]
pixels[4] = [0,128,255]
pixels[5] = [99,199,0]
pixels[6] = [128,128,128]
pixels[7] = [255,100,0]

pixels.write()              # write data to all pixels

Let’s select some favorite colors and display them on the RGB LED Strip!

How it works?

  1. In the neopixel module, we have integrated related functions into the NeoPixel class.

    from neopixel import NeoPixel
    
  2. Use the NeoPixel class from the neopixel module to initialize the pixels object, specifying the data pin and the number of LEDs.

    pixels = NeoPixel(pin, 8)   # create NeoPixel driver on pin for 8 pixels
    
  3. Set the color of each LED and use the write() method to send the data to the WS2812 LED to update its display.

    pixels[0] = [64,154,227]    # set the pixel
    pixels[1] = [128,0,128]
    pixels[2] = [50,150,50]
    pixels[3] = [255,30,30]
    pixels[4] = [0,128,255]
    pixels[5] = [99,199,0]
    pixels[6] = [128,128,128]
    pixels[7] = [255,100,0]
    
    pixels.write()              # write data to all pixels
    

Learn More

We can randomly generate colors and make a colorful flowing light.

Note

  • Open the 2.7_rgb_strip_random.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it. * Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import Pin
import neopixel
import time
import random

# Set the number of pixels for the running light
num_pixels = 8

# Set the data pin for the RGB LED strip
data_pin = Pin(14, Pin.OUT)

# Initialize the RGB LED strip object
pixels = neopixel.NeoPixel(data_pin, num_pixels)

# Continuously loop the running light
while True:
    for i in range(num_pixels):
        # Generate a random color for the current pixel
        color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

        # Turn on the current pixel with the random color
        pixels[i] = color

        # Update the RGB LED strip display
        pixels.write()

        # Turn off the current pixel
        pixels[i] = (0, 0, 0)

        # Wait for a period of time to control the speed of the running light
        time.sleep_ms(100)
  • In the while loop, we use a for loop to turn on each pixel of the RGB LED strip one by one.

  • First use the random.randint() function to generate a random color for the current pixel.

  • Then turn on the current pixel with the random color, use the write() method of the NeoPixel object to send the color data to the RGB LED strip to update its display

  • Finally, turn off the current pixel by setting its color to (0, 0, 0), and wait for a period of time to control the speed of the running light.

3. Sounds

3.1 Beep

This is a simple project to make an active buzzer beep quickly four times every second.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Buzzer

-

Transistor

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_3.1_buzzer.png

When the IO14 output is high, after the 1K current limiting resistor (to protect the transistor), the S8050 (NPN transistor) will conduct, so that the buzzer will sound.

The role of S8050 (NPN transistor) is to amplify the current and make the buzzer sound louder. In fact, you can also connect the buzzer directly to IO14, but you will find that the buzzer sound is smaller.

Wiring

Two types of buzzers are included in the kit. We need to use active buzzer. Turn them around, the sealed back (not the exposed PCB) is the one we want.

_images/buzzer.png

The buzzer needs to use a transistor when working, here we use S8050 (NPN Transistor).

_images/3.1_buzzer_bb.png

Code

Note

  • Open the 3.1_beep.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Create a Pin object representing pin 14 and set it to output mode
buzzer = machine.Pin(14, machine.Pin.OUT)

# Enter an infinite loop
while True:
    # Iterate over the values 0 to 3 using a for loop
    for i in range(4):
        # Turn on the buzzer by setting its value to 1
        buzzer.value(1)
        # Pause for 0.2 seconds
        time.sleep(0.2)
        # Turn off the buzzer
        buzzer.value(0)
        # Pause for 0.2 seconds
        time.sleep(0.2)
    # Pause for 1 second before restarting the for loop
    time.sleep(1)

When the script is running, the buzzer will beep quickly four times every second.

3.2 Custom Tone

We have used active buzzer in the previous project, this time we will use passive buzzer.

Like the active buzzer, the passive buzzer also uses the phenomenon of electromagnetic induction to work. The difference is that a passive buzzer does not have oscillating source, so it will not beep if DC signals are used. But this allows the passive buzzer to adjust its own oscillation frequency and can emit different notes such as “doh, re, mi, fa, sol, la, ti”.

Let the passive buzzer emit a melody!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Buzzer

-

Transistor

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_3.1_buzzer.png

When the IO14 output is high, after the 1K current limiting resistor (to protect the transistor), the S8050 (NPN transistor) will conduct, so that the buzzer will sound.

The role of S8050 (NPN transistor) is to amplify the current and make the buzzer sound louder. In fact, you can also connect the buzzer directly to IO14, but you will find that the buzzer sound is smaller.

Wiring

Two types of buzzers are included in the kit. We need to use active buzzer. Turn them around, the sealed back (not the exposed PCB) is the one we want.

_images/buzzer.png

The buzzer needs to use a transistor when working, here we use S8050 (NPN Transistor).

_images/3.1_buzzer_bb.png

Code

Note

  • Open the 3.2_custom_tone.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Define the frequencies of several musical notes in Hz
C4 = 262
D4 = 294
E4 = 330
F4 = 349
G4 = 392
A4 = 440
B4 = 494

# Create a PWM object representing pin 14 and assign it to the buzzer variable
buzzer = machine.PWM(machine.Pin(14))

# Define a tone function that takes as input a Pin object representing the buzzer, a frequency in Hz, and a duration in milliseconds
def tone(pin, frequency, duration):
    pin.freq(frequency) # Set the frequency
    pin.duty(512) # Set the duty cycle
    time.sleep_ms(duration) # Pause for the duration in milliseconds
    pin.duty(0) # Set the duty cycle to 0 to stop the tone

# Play a sequence of notes with different frequency inputs and durations
tone(buzzer, C4, 250)
time.sleep_ms(500)
tone(buzzer, D4, 250)
time.sleep_ms(500)
tone(buzzer, E4, 250)
time.sleep_ms(500)
tone(buzzer, F4, 250)
time.sleep_ms(500)
tone(buzzer, G4, 250)
time.sleep_ms(500)
tone(buzzer, A4, 250)
time.sleep_ms(500)
tone(buzzer, B4, 250)

How it works?

If the passive buzzer given a digital signal, it can only keep pushing the diaphragm without producing sound.

Therefore, we use the tone() function to generate the PWM signal to make the passive buzzer sound.

This function has three parameters:

  • pin: The pin that controls the buzzer.

  • frequency: The pitch of the buzzer is determined by the frequency, the higher the frequency, the higher the pitch.

  • Duration: The duration of the tone.

We use the duty() function to set the duty cycle to 512(about 50%). It can be other numbers, and it only needs to generate a discontinuous electrical signal to oscillate.

Learn More

We can simulate specific pitches and thus play a complete piece of music.

Note

  • Open the 3.2_custom_tone_music.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Define the GPIO pin that is connected to the buzzer
buzzer = machine.PWM(machine.Pin(14))

# Define the frequencies of the notes in Hz
C5 = 523
D5 = 587
E5 = 659
F5 = 698
G5 = 784
A5 = 880
B5 = 988

# Define the durations of the notes in milliseconds
quarter_note = 250
half_note = 300
whole_note = 1000

# Define the melody as a list of tuples (note, duration)
melody = [
    (E5, quarter_note),
    (E5, quarter_note),
    (F5, quarter_note),
    (G5, half_note),
    (G5, quarter_note),
    (F5, quarter_note),
    (E5, quarter_note),
    (D5, half_note),
    (C5, quarter_note),
    (C5, quarter_note),
    (D5, quarter_note),
    (E5, half_note),
    (E5, quarter_note),
    (D5, quarter_note),
    (D5, half_note),
    (E5, quarter_note),
    (E5, quarter_note),
    (F5, quarter_note),
    (G5, half_note),
    (G5, quarter_note),
    (F5, quarter_note),
    (E5, quarter_note),
    (D5, half_note),
    (C5, quarter_note),
    (C5, quarter_note),
    (D5, quarter_note),
    (E5, half_note),
    (D5, quarter_note),
    (C5, quarter_note),
    (C5, half_note),

]

# Define a function to play a note with the given frequency and duration
def tone(pin,frequency,duration):
    pin.freq(frequency)
    pin.duty(512)
    time.sleep_ms(duration)
    pin.duty(0)

# Play the melody
for note in melody:
    tone(buzzer, note[0], note[1])
    time.sleep_ms(50)
  • The tone function sets the frequency of the pin to the value of frequency using the freq method of the pin object.

  • It then sets the duty cycle of the pin to 512 using the duty method of the pin object.

  • This will cause the pin to produce a tone with the specified frequency and volume for the duration of duration in milliseconds using the sleep_ms method of the time module.

  • The code then plays a melody by iterating through a sequence called melody and calling the tone function for each note in the melody with the note’s frequency and duration.

  • It also inserts a short pause of 50 milliseconds between each note using the sleep_ms method of the time module.

4. Actuators

4.1 Small Fan

In this engaging project, we’ll explore how to drive a motor using the L293D.

The L293D is a versatile integrated circuit (IC) commonly used for motor control in electronics and robotics projects. It can drive two motors in both forward and reverse directions, making it a popular choice for applications requiring precise motor control.

By the end of this captivating project, you will have gained a thorough understanding of how digital signals and PWM signals can effectively be utilized to control motors. This invaluable knowledge will prove to be a solid foundation for your future endeavors in robotics and mechatronics. Buckle up and get ready to dive into the exciting world of motor control with the L293D!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

DC Motor

BUY

L293D

-

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_4.1_motor_l293d.png

Wiring

Note

Since the motor requires a relatively high current, it is necessary to first insert the battery and then slide the switch on the expansion board to the ON position to activate the battery supply.

_images/4.1_motor_l293d_bb.png

Code

Note

  • Open the 4.1_motor_turn.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Create Pin objects representing the motor control pins and set them to output mode
motor1A = machine.Pin(13, machine.Pin.OUT)
motor2A = machine.Pin(14, machine.Pin.OUT)

# Define a function to rotate the motor clockwise
def clockwise():
    motor1A.value(1)
    motor2A.value(0)

# Define a function to rotate the motor anticlockwise
def anticlockwise():
    motor1A.value(0)
    motor2A.value(1)

# Define a function to stop the motor
def stop():
    motor1A.value(0)
    motor2A.value(0)

# Enter an infinite loop

try:
    while True:
        clockwise() # Rotate the motor clockwise
        time.sleep(1) # Pause for 1 second
        anticlockwise() # Rotate the motor anticlockwise
        time.sleep(1)
        stop() # Stop the motor
        time.sleep(2)

except KeyboardInterrupt:
    stop()  # Stop the motor when KeyboardInterrupt is caught

During script execution, you will see the motor alternately rotating clockwise and counterclockwise every second.

Learn More

In addition to simply making the motor rotate clockwise and counterclockwise, you can also control the speed of the motor’s rotation by using pulse-width modulation (PWM) on the control pin, as shown below.

Note

  • Open the 4.1_motor_turn_pwm.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import Pin, PWM
import time

# Create PWM objects representing the motor control pins and set their frequency to 1000 Hz
motor1A = PWM(Pin(13, Pin.OUT))
motor2A = PWM(Pin(14, Pin.OUT))
motor1A.freq(500)
motor2A.freq(500)

# Enter an infinite loop
while True:
    # Rotate the motor forward by gradually increasing the power on the motor1A pin
    for power in range(0, 1023, 20):
        motor1A.duty(power)
        motor2A.duty(0)
        time.sleep(0.1)
    # Decreasing the power on the motor1A pin
    for power in range(1023, 0, -20):
        motor1A.duty(power)
        motor2A.duty(0)
        time.sleep(0.1)
    # Rotate the motor in the opposite direction by gradually increasing the power on the motor2A pin
    for power in range(0, 1023, 20):
        motor1A.duty(0)
        motor2A.duty(power)
        time.sleep(0.1)
    # Decreasing the power on the motor2A pin
    for power in range(1023, 0, -20):
        motor1A.duty(0)
        motor2A.duty(power)
        time.sleep(0.1)

Unlike the previous script, here the motor is controlled by PWM signals with a frequency of 1000 Hz, which determines the speed of the motor.

  • The code uses a while True loop to run continuously. Inside the loop, there are four for loops that control the motors in a sequence.

  • The first two for loops increase and decrease the speed of IN1 while keeping IN2 at 0 speed.

  • The next two for loops increase and decrease the speed of IN2 while keeping IN1 at 0 speed.

  • The range function in each for loop produces a string of numbers that serves as the duty cycle of the PWM signal. This is then output to IN1 or IN2 via the duty method. The duty cycle determines the percentage of time that the PWM signal is high, which in turn determines the average voltage applied to the motor, and thus the motor speed.

  • The time.sleep function is used to introduce a delay of 0.1 seconds between each step in the sequence, which allows the motor to change speed gradually, rather than jumping from one speed to another instantaneously.

4.2 Pumping

In this intriguing project, we will delve into controlling a water pump using the L293D.

In the realm of water pump control, things are a bit simpler compared to controlling other motors. The beauty of this project lies in its simplicity - there’s no need to worry about the direction of rotation. Our primary goal is to successfully activate the water pump and keep it running.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Centrifugal Pump

-

L293D

-

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_4.1_motor_l293d.png

Wiring

Note

It is recommended here to insert the battery and then slide the switch on the expansion board to the ON position to activate the battery supply.

_images/4.2_pump_l293d_bb.png

Code

Note

  • Open the 4.2_pumping.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Create Pin objects representing the motor control pins and set them to output mode
motor1A = machine.Pin(13, machine.Pin.OUT)
motor2A = machine.Pin(14, machine.Pin.OUT)

# Define a function to rotate the pump
def rotate():
    motor1A.value(1)
    motor2A.value(0)

# Define a function to stop the pump
def stop():
    motor1A.value(0)
    motor2A.value(0)

try:
    while True:
        rotate()  # Rotate the motor clockwise
        time.sleep(5)  # Pause for 5 seconds
        stop()  # Stop the motor
        time.sleep(2)

except KeyboardInterrupt:
    stop()  # Stop the motor when KeyboardInterrupt is caught

During the script execution, you will see the pump working and water coming out of the tube, then stopping for 2 seconds before starting to work again.

4.3 Swinging Servo

A Servo is a type of position-based device known for its ability to maintain specific angles and deliver precise rotation. This makes it highly desirable for control systems that demand consistent angle adjustments. It’s not surprising that Servos have found extensive use in high-end remote-controlled toys, from airplane models to submarine replicas and sophisticated remote-controlled robots.

In this intriguing adventure, we’ll challenge ourselves to manipulate the Servo in a unique way - by making it sway! This project offers a brilliant opportunity to dive deeper into the dynamics of Servos, sharpening your skills in precise control systems and offering a deeper understanding of their operation.

Are you ready to make the Servo dance to your tunes? Let’s embark on this exciting journey!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Servo

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_4.3_servo.png

Wiring

  • Orange wire is signal and connected to IO25.

  • Red wire is VCC and connected to 5V.

  • Brown wire is GND and connected to GND.

_images/4.3_swinging_servo_bb.png

Code

Note

  • Open the 4.3_swinging_servo.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Create a PWM (Pulse Width Modulation) object on Pin 25
servo = machine.PWM(machine.Pin(25))

# Set the frequency of the PWM signal to 50 Hz, common for servos
servo.freq(50)

# Define a function for interval mapping
def interval_mapping(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

# Define a function to write an angle to the servo
def servo_write(pin, angle):

    pulse_width = interval_mapping(angle, 0, 180, 0.5, 2.5) # Calculate the pulse width
    duty = int(interval_mapping(pulse_width, 0, 20, 0, 1023))     # Calculate the duty cycle
    pin.duty(duty) # Set the duty cycle of the PWM signal

# Create an infinite loop
while True:
    # Loop through angles from 0 to 180 degrees
    for angle in range(180):
        servo_write(servo, angle)
        time.sleep_ms(20)

    # Loop through angles from 180 to 0 degrees in reverse
    for angle in range(180, -1, -1):
        servo_write(servo, angle)
        time.sleep_ms(20)

When running this code, the servo will continuously sweep back and forth between 0 and 180 degrees.

How it works?

  1. Import the necessary libraries: machine for controlling the microcontroller’s hardware, and time for adding delays.

    import machine
    import time
    
  2. Create a PWM (Pulse Width Modulation) object on Pin 25 and set its frequency to 50 Hz, which is common for servo.

    # Create a PWM (Pulse Width Modulation) object on Pin 25
    servo = machine.PWM(machine.Pin(25))
    
    # Set the frequency of the PWM signal to 50 Hz, common for servos
    servo.freq(50)
    
  3. Define an interval_mapping function to map values from one range to another. This will be used to convert the angle to the appropriate pulse width and duty cycle.

    def interval_mapping(x, in_min, in_max, out_min, out_max):
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
    
  4. Define a servo_write function that takes a PWM object and an angle as inputs. It calculates the pulse width and duty cycle based on the given angle, and then sets the PWM output accordingly.

    def servo_write(pin, angle):
    
        pulse_width = interval_mapping(angle, 0, 180, 0.5, 2.5) # Calculate the pulse width
        duty = int(interval_mapping(pulse_width, 0, 20, 0, 1023))     # Calculate the duty cycle
        pin.duty(duty) # Set the duty cycle of the PWM signal
    
    • In this function, interval_mapping() is called to map the angle range 0 ~ 180 to the pulse width range 0.5 ~ 2.5ms.

    • Why is it 0.5~2.5? This is determined by the working mode of the Servo.

    • Next, convert the pulse width from period to duty.

    • Since duty() cannot have decimals when used (the value cannot be a float type), we used int() to force the duty to be converted to an int type.

  5. Create an infinite loop with two nested loops.

    while True:
        # Loop through angles from 0 to 180 degrees
        for angle in range(180):
            servo_write(servo, angle)
            time.sleep_ms(20)
    
        # Loop through angles from 180 to 0 degrees in reverse
        for angle in range(180, -1, -1):
            servo_write(servo, angle)
            time.sleep_ms(20)
    
    • The first nested loop iterates through angles from 0 to 180 degrees, and the second nested loop iterates through angles from 180 to 0 degrees in reverse.

    • In each iteration, the servo_write function is called with the current angle, and a delay of 20 milliseconds is added.

5. Sensors

5.1 Reading Button Value

In this interactive project, we’ll venture into the realm of button controls and LED manipulation.

The concept is straightforward yet effective. We’ll be reading the state of a button. When the button is pressed down, it registers a high voltage level, or ‘high state’. This action will then trigger an LED to light up.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Button

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO14, IO25, I35, I34, I39, I36, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

  • Conditional Usage Pins (Input)

    The following pins have built-in pull-up or pull-down resistors, so external resistors are not required when using them as input pins:

    Conditional Usage Pins

    Description

    IO13, IO15, IO2, IO4

    Pulling up with a 47K resistor defaults the value to high.

    IO27, IO26, IO33

    Pulling up with a 4.7K resistor defaults the value to high.

    IO32

    Pulling down with a 1K resistor defaults the value to low.

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.1_button.png

To ensure proper functionality, connect one side of the button pin to 3.3V and the other side to IO14. When the button is pressed, IO14 will be set to high, causing the LED to light up. When the button is released, IO14 will return to its suspended state, which may be either high or low. To ensure a stable low level when the button is not pressed, IO14 should be connected to GND through a 10K pull-down resistor.

Wiring

_images/5.1_button_bb.png

Note

A four-pin button is designed in an H shape. When the button is not pressed, the left and right pins are disconnected, and current cannot flow between them. However, when the button is pressed, the left and right pins are connected, creating a pathway for current to flow.

Code

Note

  • Open the 5.1_read_button_value.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

button = machine.Pin(14, machine.Pin.IN) # Button pin
led = machine.Pin(26, machine.Pin.OUT) # LED pin


while True:
    # If the button is pressed by reading its value
    if button.value() == 1:
        # Turn on the LED by setting its value to 1
        led.value(1)
#         time.sleep(0.5)
    else:
        # Turn off the LED
        led.value(0)

During script execution, the LED lights up when you press the button and goes out when you release it.

5.2 Tilt It!

The tilt switch is a simple yet effective 2-pin device that contains a metal ball in its center. When the switch is in an upright position, the two pins are electrically connected, allowing current to flow through. However, when the switch is tilted or tilted at a certain angle, the metal ball moves and breaks the electrical connection between the pins.

In this project, we will utilize the tilt switch to control the illumination of an LED. By positioning the switch in a way that triggers the tilt action, we can toggle the LED on and off based on the switch’s orientation.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Tilt Switch

-

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO14, IO25, I35, I34, I39, I36, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

  • Conditional Usage Pins (Input)

    The following pins have built-in pull-up or pull-down resistors, so external resistors are not required when using them as input pins:

    Conditional Usage Pins

    Description

    IO13, IO15, IO2, IO4

    Pulling up with a 47K resistor defaults the value to high.

    IO27, IO26, IO33

    Pulling up with a 4.7K resistor defaults the value to high.

    IO32

    Pulling down with a 1K resistor defaults the value to low.

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.2_tilt.png

When the tilt switch is in an upright position, IO14 will be set to high, resulting in the LED being lit. Conversely, when the tilt switch is tilted, IO14 will be set to low, causing the LED to turn off.

The purpose of the 10K resistor is to maintain a stable low state for IO14 when the tilt switch is in a tilted position.

Wiring

_images/5.2_tilt_switch_bb.png

Code

Note

  • Open the 5.2_tilt_switch.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

switch = machine.Pin(14, machine.Pin.IN) # Tilt switch pin
led = machine.Pin(26, machine.Pin.OUT) # LED pin

while True:
    # Check if the switch is tilted by reading its value
    if switch.value() == 1:
        # Turn on the LED by setting its value to 1
        led.value(1)
    else:
        # Turn off the LED
        led.value(0)

When the script is running, the LED will be turned on when the switch is upright, and turned off when the switch is tilted.

5.3 Detect the Obstacle

This module is commonly installed on the car and robot to judge the existence of the obstacles ahead. Also it is widely used in hand held device, water faucet and so on.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Obstacle Avoidance Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO13, IO14, IO27, IO26, IO25, IO33, I35, I34, I39, I36, IO4, IO18, IO19, IO21, IO22, IO23

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.3_avoid.png

When the obstacle avoidance module does not detect any obstacles, IO14 returns a high level. However, when it detects an obstacle, it returns a low level. You can adjust the blue potentiometer to modify the detection distance of this module.

Wiring

_images/5.3_avoid_bb.png

Code

Note

  • Open the 5.3_avoid.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

ir_avoid = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP) # avoid module pin

while True:

    # Print values of the obstacle avoidance module
    print(ir_avoid.value())
    time.sleep(0.1)

While the program is running, if the IR obstacle avoidance module detects an obstacle in front of it, the value “0” will be shown on the Serial Monitor, otherwise, the value “1” will be shown.

5.4 Detect the Line

The line-tracking module is used to detect the presence of black areas on the ground, such as black lines taped with electrical tape.

Its emitter emits appropriate infrared light into the ground, which is relatively absorbed and weakly reflected by black surfaces. The opposite is true for white surfaces. If reflected light is detected, the ground is currently indicated as white. If it is not detected, it is indicated as black.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Line Tracking Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO13, IO14, IO27, IO26, IO25, IO33, I35, I34, I39, I36, IO4, IO18, IO19, IO21, IO22, IO23

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.4_line.png

When the line tracking module detects a black line, IO14 returns a high level. On the other hand, when it detects a white line, IO14 returns a low level. You can adjust the blue potentiometer to modify the sensitivity of this module’s detection.

Wiring

_images/5.4_line_bb.png

Code

Note

  • Open the 5.4_detect_the_line.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Create a pin object named greyscale, set pin number 14 as input
line = machine.Pin(14, machine.Pin.IN)


while True:
    # Check if the value is 1 (black)
    if line.value() == 1:
        # Print "black"
        print("black")
        time.sleep(0.5)
    # If the value is not 1 (it's 0, which means white)
    else :
        # Print "white"
        print("white")
        time.sleep(0.5)

When the line tracking module detects there is black line, there appears “black” on the Shell; otherwise, “white” is displayed.

5.5 Detect Human Movement

Passive infrared sensor (PIR sensor) is a common sensor that can measure infrared (IR) light emitted by objects in its field of view. Simply put, it will receive infrared radiation emitted from the body, thereby detecting the movement of people and other animals. More specifically, it tells the main control board that someone has entered your room.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

PIR Motion Sensor Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO13, IO14, IO27, IO26, IO25, IO33, I35, I34, I39, I36, IO4, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Note

IO32 cannot be used as input pin in this project because it is internally connected to a 1K pull-down resistor, which sets its default value to 0.

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.5_pir.png

When the PIR module detects motion, IO14 will go high, and the LED will be lit. Otherwise, when no motion is detected, IO14 will be low, and the LED will turn off.

Note

The PIR module has two potentiometers: one adjusts sensitivity, the other adjusts detection distance. To make the PIR module work better, you need to turn both of them counterclockwise to the end.

_images/PIR_TTE.png

Wiring

_images/5.5_pir_bb.png

Code

Note

  • Open the 5.5_detect_human_movement.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Define pins
PIR_PIN = 14    # PIR sensor
LED_PIN = 26    # LED

# Initialize the PIR sensor pin as an input pin
pir_sensor = machine.Pin(PIR_PIN, machine.Pin.IN, machine.Pin.PULL_DOWN)
# Initialize the LED pin as an output pin
led = machine.Pin(LED_PIN, machine.Pin.OUT)

# Global flag to indicate motion detected
motion_detected_flag = False

# Function to handle the interrupt
def motion_detected(pin):
    global motion_detected_flag
    print("Motion detected!")
    motion_detected_flag = True

# Attach the interrupt to the PIR sensor pin
pir_sensor.irq(trigger=machine.Pin.IRQ_RISING, handler=motion_detected)

# Main loop
while True:
    if motion_detected_flag:
        led.value(1)  # Turn on the LED
        time.sleep(5)  # Keep the LED on for 5 seconds
        led.value(0)  # Turn off the LED
        motion_detected_flag = False

When the script is running, the LED will light up for 5 seconds and then go off when the PIR module detects someone passing.

Note

The PIR module has two potentiometers: one adjusts sensitivity, the other adjusts detection distance. To make the PIR module work better, you need to turn both of them counterclockwise to the end.

_images/PIR_TTE.png

How it work?

This code sets up a simple motion detection system using a PIR sensor and an LED. When motion is detected, the LED will turn on for 5 seconds.

Here’s a breakdown of the code:

  1. Define the interrupt handler function that will be executed when motion is detected:

    def motion_detected(pin):
        global motion_detected_flag
        print("Motion detected!")
        motion_detected_flag = True
    
  2. Attach the interrupt to the PIR sensor pin, with the trigger set to “rising” (i.e., when the pin goes from low to high voltage):

    pir_sensor.irq(trigger=machine.Pin.IRQ_RISING, handler=motion_detected)
    

    This sets up an interrupt on the pir_sensor pin, which is connected to the PIR motion sensor.

    Here’s a detailed explanation of the parameters:

    • trigger=machine.Pin.IRQ_RISING: This parameter sets the trigger condition for the interrupt. In this case, the interrupt will be triggered on a rising edge. A rising edge is when the voltage on the pin changes from a low state (0V) to a high state (typically 3.3V or 5V, depending on your hardware). For a PIR motion sensor, when motion is detected, the output pin usually goes from low to high, making the rising edge an appropriate trigger condition.

    • handler=motion_detected: This parameter specifies the function that will be executed when the interrupt is triggered. In this case, the motion_detected function is provided as the interrupt handler. This function will be called automatically when the interrupt condition (rising edge) is detected on the pir_sensor pin.

    So, this line of code configures the PIR sensor to call the motion_detected function whenever motion is detected by the sensor, due to the output pin going from a low to a high state.

  3. In the main loop, if the motion_detected_flag is set to True, the LED will be turned on for 5 seconds and then turned off. The flag is then reset to False to wait for the next motion event.

    while True:
        if motion_detected_flag:
            led.value(1)  # Turn on the LED
            time.sleep(5)  # Keep the LED on for 5 seconds
            led.value(0)  # Turn off the LED
            motion_detected_flag = False
    

5.6 Two Kinds of Transistors

This kit is equipped with two types of transistors, S8550 and S8050, the former is PNP and the latter is NPN. They look very similar, and we need to check carefully to see their labels. When a High level signal goes through an NPN transistor, it is energized. But a PNP one needs a Low level signal to manage it. Both types of transistor are frequently used for contactless switches, just like in this experiment.

Let’s use LED and button to understand how to use transistor!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Button

BUY

Transistor

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO14, IO25, I35, I34, I39, I36, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

  • Conditional Usage Pins (Input)

    The following pins have built-in pull-up or pull-down resistors, so external resistors are not required when using them as input pins:

    Conditional Usage Pins

    Description

    IO13, IO15, IO2, IO4

    Pulling up with a 47K resistor defaults the value to high.

    IO27, IO26, IO33

    Pulling up with a 4.7K resistor defaults the value to high.

    IO32

    Pulling down with a 1K resistor defaults the value to low.

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Way to connect NPN (S8050) transistor

_images/circuit_5.6_S8050.png

In this circuit, when the button is pressed, IO14 is high.

By programming IO26 to output high, after a 1k current limiting resistor (to protect the transistor), the S8050 (NPN transistor) is allowed to conduct, thus allowing the LED to light up.

_images/5.6_s8050_bb.png

Way to connect PNP(S8550) transistor

_images/circuit_5.6_S8550.png

In this circuit, IO14 is low by the default and will change to high when the button is pressed.

By programming IO26 to output low, after a 1k current limiting resistor (to protect the transistor), the S8550 (PNP transistor) is allowed to conduct, thus allowing the LED to light up.

The only difference you will notice between this circuit and the previous one is that in the previous circuit the cathode of the LED is connected to the collector of the S8050 (NPN transistor), while this one is connected to the emitter of the S8550 (PNP transistor).

_images/5.6_s8550_bb.png

Code

Note

  • Open the 5.6_transistor.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine

button = machine.Pin(14, machine.Pin.IN)   # Button
led = machine.Pin(26, machine.Pin.OUT)  # LED

# Start an infinite loop
while True:
    # Read the current value of the 'button' object (0 or 1) and store it in the 'button_status' variable
    button_status = button.value()
    # If the button is pressed (value is 1)
    if button_status == 1:
        led.value(1) # Turn the LED on
    # If the button is not pressed (value is 0)
    else:
        led.value(0)            # turn the LED off

Two types of transistors can be controlled using the same code. When we press the button, the ESP32 will send a high-level signal to the transistor; when we release it, it will send a low-level signal.

  • The circuit using the S8050 (NPN transistor) will light up when the button is pressed, indicating that it is in a high-level conduction state;

  • The circuit using the S8550 (PNP transistor) will light up when the button is released, indicating that it is in a low-level conduction state.

5.7 Feel the Light

The photoresistor is a commonly used device for analog inputs, similar to a potentiometer. Its resistance value changes based on the intensity of the light it receives. When exposed to strong light, the resistance of the photoresistor decreases, and as the light intensity decreases, the resistance increases.

By reading the value of the photoresistor, we can gather information about the ambient light conditions. This information can be used for tasks such as controlling the brightness of an LED, adjusting the sensitivity of a sensor, or implementing light-dependent actions in a project.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Photoresistor

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO14, IO25, I35, I34, I39, I36

  • Strapping Pins

    The following pins are strapping pins, which affect the startup process of the ESP32 during power on or reset. However, once the ESP32 is booted up successfully, they can be used as regular pins.

    Strapping Pins

    IO0, IO12

Schematic

_images/circuit_5.7_photoresistor.png

As the light intensity increases, the resistance of the light-dependent resistor (LDR) decreases, resulting in a decrease in the value read on I35.

Wiring

_images/5.7_photoresistor_bb.png

Code

Note

  • Open the 5.7_feel_the_light.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import ADC,Pin
import time

# create an ADC object acting on a pin
photoresistor = ADC(Pin(35, Pin.IN))

# Configure the ADC attenuation to 11dB for full range
photoresistor.atten(photoresistor.ATTN_11DB)

while True:

    # read a raw analog value in the range 0-4095
    value = photoresistor.read()
    print(value)
    time.sleep(0.05)

After the program runs, the Shell prints out the photoresistor values. You can shine a flashlight on it or cover it up with your hand to see how the value will change.

  • atten(photoresistor.ATTN_11DB): Configure the ADC attenuation to 11dB for full range.

    To read voltages above the reference voltage, apply input attenuation with the atten keyword argument.

    Valid values (and approximate linear measurement ranges) are:

    • ADC.ATTN_0DB: No attenuation (100mV - 950mV)

    • ADC.ATTN_2_5DB: 2.5dB attenuation (100mV - 1250mV)

    • ADC.ATTN_6DB: 6dB attenuation (150mV - 1750mV)

    • ADC.ATTN_11DB: 11dB attenuation (150mV - 2450mV)

  • machine.ADC - MicroPython Docs

5.8 Turn the Knob

A potentiometer is a three-terminal device that is commonly used to adjust the resistance in a circuit. It features a knob or a sliding lever that can be used to vary the resistance value of the potentiometer. In this project, we will utilize it to control the brightness of an LED, similar to a desk lamp in our daily life. By adjusting the position of the potentiometer, we can change the resistance in the circuit, thereby regulating the current flowing through the LED and adjusting its brightness accordingly. This allows us to create a customizable and adjustable lighting experience, similar to that of a desk lamp.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Potentiometer

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO14, IO25, I35, I34, I39, I36

  • Strapping Pins

    The following pins are strapping pins, which affect the startup process of the ESP32 during power on or reset. However, once the ESP32 is booted up successfully, they can be used as regular pins.

    Strapping Pins

    IO0, IO12

Schematic

_images/circuit_5.8_potentiometer.png

When you rotate the potentiometer, the value of I35 will change. By programming, you can use the value of I35 to control the brightness of the LED. Therefore, as you rotate the potentiometer, the brightness of the LED will also change accordingly.

Wiring

_images/5.8_potentiometer_bb.png

Code

Note

  • Open the 5.8_turn_the_knob.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import ADC, Pin, PWM
import time

pot = ADC(Pin(35, Pin.IN)) # create an ADC object acting on a pin

# Configure the ADC attenuation to 11dB for full range
pot.atten(pot.ATTN_11DB)

# Create a PWM object
led = PWM(Pin(26), freq=1000)

while True:
    # Read a raw analog value in the range of 0-4095
    value = pot.read()

    # Scale the value to the range of 0-1023 for ESP32 PWM duty cycle
    pwm_value = int(value * 1023 / 4095)

    # Update the LED brightness based on the potentiometer value
    led.duty(pwm_value)

    # Read the voltage in microvolts and convert it to volts
    voltage = pot.read_uv() / 1000000

    # Print the raw value and the voltage
    print(f"value: {value}, Voltage: {voltage}V")

    # Wait for 0.5 seconds before taking the next reading
    time.sleep(0.5)

With this script run, the LED brightness changes as the potentiometer is rotated, while the analog value and voltage at this point are displayed in the Shell.

5.9 Measure Soil Moisture

This capacitive soil moisture sensor is different from most of the resistive sensors on the market, using the principle of capacitive induction to detect soil moisture.

By visually reading the values from the soil moisture sensor, we can gather information about the moisture level in the soil. This information is useful for various applications, such as automatic irrigation systems, plant health monitoring, or environmental sensing projects.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Soil Moisture Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO14, IO25, I35, I34, I39, I36

  • Strapping Pins

    The following pins are strapping pins, which affect the startup process of the ESP32 during power on or reset. However, once the ESP32 is booted up successfully, they can be used as regular pins.

    Strapping Pins

    IO0, IO12

Schematic

_images/circuit_5.9_soil_moisture.png

By inserting the module into the soil and watering it, the value read on I35 will decrease.

Wiring

_images/5.9_moisture_bb.png

Code

Note

  • Open the 5.9_moisture.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import ADC,Pin
import time

# create an ADC object acting on a pin
moisture = ADC(Pin(35, Pin.IN))

# Configure the ADC attenuation to 11dB for full range
moisture.atten(moisture.ATTN_11DB)

while True:

    # read a raw analog value in the range 0-4095
    value = moisture.read()
    print(value)
    time.sleep(0.05)

When the script runs, you will see the soil moisture value in the Shell.

By inserting the module into the soil and watering it, the value of the soil moisture sensor will become smaller.

5.10 Temperature Sensing

A thermistor is a temperature sensor that exhibits a strong dependence on temperature, and it can be classified into two types: Negative Temperature Coefficient (NTC) and Positive Temperature Coefficient (PTC). The resistance of an NTC thermistor decreases with increasing temperature, while the resistance of a PTC thermistor increases with increasing temperature.

In this project, we will be using an NTC thermistor. By connecting the NTC thermistor to an analog input pin of the ESP32 microcontroller, we can measure its resistance, which is directly proportional to the temperature.

By incorporating the NTC thermistor and performing the necessary calculations, we can accurately measure the temperature and display it on the I2C LCD1602 module. This project enables real-time temperature monitoring and provides a visual interface for temperature display.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Thermistor

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO14, IO25, I35, I34, I39, I36

  • Strapping Pins

    The following pins are strapping pins, which affect the startup process of the ESP32 during power on or reset. However, once the ESP32 is booted up successfully, they can be used as regular pins.

    Strapping Pins

    IO0, IO12

Schematic

_images/circuit_5.10_thermistor.png

When the temperature rises, the resistance of the thermistor decreases, causing the value read on I35 to decrease. Additionally, by using a formula, you can convert the analog value into temperature and then print it out.

Wiring

_images/5.10_thermistor_bb.png

Note

  • The thermistor is black and marked 103.

  • The color ring of the 10K ohm resistor is red, black, black, red and brown.

Code

Note

  • Open the 5.10_thermistor.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

# Import the necessary libraries
from machine import ADC, Pin
import time
import math

# Define the beta value of the thermistor, typically provided in the datasheet
beta = 3950

# Create an ADC object (thermistor)
thermistor = ADC(Pin(35, Pin.IN))

# Set the attenuation
thermistor.atten(thermistor.ATTN_11DB)

# Start an infinite loop to continuously monitor the temperature
while True:
    # Read the voltage in microvolts and convert it to volts
    Vr = thermistor.read_uv() / 1000000

    # Calculate the resistance of the thermistor based on the measured voltage
    Rt = 10000 * Vr / (3.3 - Vr)

    # Use the beta parameter and resistance value to calculate the temperature in Kelvin
    temp = 1 / (((math.log(Rt / 10000)) / beta) + (1 / (273.15 + 25)))

    # Convert to Celsius
    Cel = temp - 273.15

    # Convert to Fahrenheit
    Fah = Cel * 1.8 + 32

    # Print the temperature values in both Celsius and Fahrenheit
    print('Celsius: %.2f C  Fahrenheit: %.2f F' % (Cel, Fah))
    time.sleep(0.5)

When the code is run, the Shell will print out the Celsius and Fahrenheit temperatures.

How it works?

Each thermistor has a normal resistance. Here it is 10k ohm, which is measured under 25 degree Celsius.

When the temperature gets higher, the resistance of the thermistor decreases. Then the voltage data is converted to digital quantities by the A/D adapter.

The temperature in Celsius or Fahrenheit is output via programming.

Here is the relation between the resistance and temperature:

RT =RN expB(1/TK - 1/TN)

  • RT is the resistance of the NTC thermistor when the temperature is TK.

  • RN is the resistance of the NTC thermistor under the rated temperature TN. Here, the numerical value of RN is 10k.

  • TK is a Kelvin temperature and the unit is K. Here, the numerical value of TK is 373.15 + degree Celsius.

  • TN is a rated Kelvin temperature; the unit is K too. Here, the numerical value of TN is 373.15+25.

  • And B(beta), the material constant of NTC thermistor, is also called heat sensitivity index with a numerical value 4950.

  • exp is the abbreviation of exponential, and the base number e is a natural number and equals 2.7 approximately.

Convert this formula TK=1/(ln(RT/RN)/B+1/TN) to get Kelvin temperature that minus 273.15 equals degree Celsius.

This relation is an empirical formula. It is accurate only when the temperature and resistance are within the effective range.

Learn More

You can also display the calculated Celsius and Fahrenheit temperatures on the I2C LCD1602.

_images/5.10_thermistor_lcd_bb.png

Note

  • Open the 5.10_thermistor_lcd.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

  • Here you need to use the library called lcd1602.py, please check if it has been uploaded to ESP32, for a detailed tutorial refer to 1.4 Upload the Libraries (Important).

# Import the necessary libraries
from machine import ADC, Pin
from lcd1602 import LCD
import time
import math

# Define the beta value of the thermistor, typically provided in the datasheet
beta = 3950

# Create an ADC object (thermistor)
thermistor = ADC(Pin(35, Pin.IN))

# Set the attenuation
thermistor.atten(thermistor.ATTN_11DB)

lcd = LCD()

# Start an infinite loop to continuously monitor the temperature
while True:
    # Read the voltage in microvolts and convert it to volts
    Vr = thermistor.read_uv() / 1000000

    # Calculate the resistance of the thermistor based on the measured voltage
    Rt = 10000 * Vr / (3.3 - Vr)

    # Use the beta parameter and resistance value to calculate the temperature in Kelvin
    temp = 1 / (((math.log(Rt / 10000)) / beta) + (1 / (273.15 + 25)))

    # Convert to Celsius
    Cel = temp - 273.15

    # Convert to Fahrenheit
    Fah = Cel * 1.8 + 32

    # Print the temperature values in both Celsius and Fahrenheit
    print('Celsius: %.2f C  Fahrenheit: %.2f F' % (Cel, Fah))

    # Clear the LCD screen
    lcd.clear()

    # Display the temperature values in both Celsius and Fahrenheit
    lcd.message('Cel: %.2f \xDFC \n' % Cel)
    lcd.message('Fah: %.2f \xDFF' % Fah)
    time.sleep(1)

5.11 Toggle the Joystick

If you play a lot of video games, then you should be very familiar with the Joystick. It is usually used to move the character around, rotate the screen, etc.

The principle behind Joystick’s ability to allow the computer to read our actions is very simple. It can be thought of as consisting of two potentiometers that are perpendicular to each other. These two potentiometers measure the analog value of the joystick vertically and horizontally, resulting in a value (x,y) in a planar right-angle coordinate system.

The joystick of this kit also has a digital input, which is activated when the joystick is pressed.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Joystick Module

BUY

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Analog Input

    IO14, IO25, I35, I34, I39, I36

    For Digital Input

    IO13, IO14, IO27, IO26, IO25, IO33, IO4, IO18, IO19, IO21, IO22, IO23

  • Strapping Pins (Input)

    Strapping pins are a special set of pins that are used to determine specific boot modes during device startup (i.e., power-on reset).

    Strapping Pins

    IO5, IO0, IO2, IO12, IO15

    Generally, it is not recommended to use them as input pins. If you wish to use these pins, consider the potential impact on the booting process. For more details, please refer to the Strapping Pins section.

Schematic

_images/circuit_5.11_joystick.png

The SW (Z-axis) pin is connected to IO33, which has a built-in 4.7K pull-up resistor. Therefore, when the SW button is not pressed, it will output a high level. When the button is pressed, it will output a low level.

I34 and I35 will change their values as you manipulate the joystick. The range of values is from 0 to 4095.

Wiring

_images/5.11_joystick_bb.png

Code

Note

  • Open the 5.11_joystick.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import ADC,Pin
import time

xAxis = ADC(Pin(34, Pin.IN)) # create an ADC object acting on a pin
xAxis.atten(xAxis.ATTN_11DB)
yAxis = ADC(Pin(35, Pin.IN)) # create an ADC object acting on a pin
yAxis.atten(yAxis.ATTN_11DB)
button = Pin(33, Pin.IN, Pin.PULL_UP)

while True:
    xValue = xAxis.read()  # read a raw analog value in the range 0-4095
    yValue = yAxis.read()  # read a raw analog value in the range 0-4095
    btnValue = button.value()
    print(f"X:{xValue}, Y:{yValue}, Button:{btnValue}")
    time.sleep(0.1)

When the program runs, the Shell prints out the x, y, and button values of joystick.

X:1921, Y:1775, Button:0
X:1921, Y:1775, Button:0
X:1923, Y:1775, Button:0
X:1924, Y:1776, Button:0
X:1926, Y:1777, Button:0
X:1925, Y:1776, Button:0
X:1924, Y:1776, Button:0
  • The x-axis and y-axis values are analog values that vary from 0 to 4095.

  • The button is a digital value with a status of 1(release) or 0(press).

    _images/joystick_direction.png

5.12 Measuring Distance

The ultrasonic module is used for distance measurement or object detection. In this project, we will program the module to obtain obstacle distances. By sending ultrasonic pulses and measuring the time it takes for them to bounce back, we can calculate distances. This enables us to implement distance-based actions or obstacle avoidance behaviors.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Ultrasonic Module

BUY

Available Pins

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    For Input

    IO13, IO14, IO27, IO26, IO25, IO33, IO32, I35, I34, I39, I36, IO4, IO18, IO19, IO21, IO22, IO23

    For Output

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO32, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_5.12_ultrasonic.png

The ESP32 sends a set of square wave signals to the Trig pin of the ultrasonic sensor every 10 seconds. This prompts the ultrasonic sensor to emit a 40kHz ultrasound signal outward. If there is an obstacle in front, the ultrasound waves will be reflected back.

By recording the time it takes from sending to receiving the signal, dividing it by 2, and multiplying it by the speed of light, you can determine the distance to the obstacle.

Wiring

_images/5.12_ultrasonic_bb.png

Code

Note

  • Open the 5.12_ultrasonic.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time

# Define the trigger and echo pins for the distance sensor
TRIG = machine.Pin(26, machine.Pin.OUT)
ECHO = machine.Pin(25, machine.Pin.IN)

# Calculate the distance using the ultrasonic sensor
def distance():
    # Ensure trigger is off initially
    TRIG.off()
    time.sleep_us(2)  # Wait for 2 microseconds

    # Send a 10-microsecond pulse to the trigger pin
    TRIG.on()
    time.sleep_us(10)
    TRIG.off()

    # Wait for the echo pin to go high
    while not ECHO.value():
        pass

    # Record the time when the echo pin goes high
    time1 = time.ticks_us()

    # Wait for the echo pin to go low
    while ECHO.value():
        pass

    # Record the time when the echo pin goes low
    time2 = time.ticks_us()

    # Calculate the time difference between the two recorded times
    during = time.ticks_diff(time2, time1)

    # Calculate and return the distance (in cm) using the speed of sound (340 m/s)
    return during * 340 / 2 / 10000

# Continuously measure and print the distance
while True:
    dis = distance()
    print('Distance: %.2f' % dis)
    time.sleep_ms(300)  # Wait for 300 milliseconds before repeating

Once the program is running, the Shell will print out the distance of the ultrasonic sensor from the obstacle ahead.

5.13 Temperature - Humidity

The DHT11 is a temperature and humidity sensor commonly used for environmental measurements. It is a digital sensor that communicates with a microcontroller to provide temperature and humidity readings.

In this project, we will be reading the DHT11 sensor and printing out the temperature and humidity values it detects.

By reading the data provided by the sensor, we can obtain the current temperature and humidity values in the environment. These values can be used for real-time monitoring of environmental conditions, weather observations, indoor climate control, humidity reports, and more.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

DHT11 Humiture Sensor

BUY

  • Available Pins

    Here is a list of available pins on the ESP32 board for this project.

    Available Pins

    IO13, IO12, IO14, IO27, IO26, IO25, IO33, IO15, IO2, IO0, IO4, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_5.13_dht11.png

Wiring

_images/5.13_dht11_bb.png

Code

Note

  • Open the 5.13_dht11.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import dht
import machine
import time

# Initialize the DHT11 sensor and connect it to pin 14
sensor = dht.DHT11(machine.Pin(14))

# Loop indefinitely to continuously measure temperature and humidity
while True:
    try:
        # Measure temperature and humidity
        sensor.measure()

        # Get temperature and humidity values
        temp = sensor.temperature()
        humi = sensor.humidity()

        # Print temperature and humidity
        print("Temperature: {}, Humidity: {}".format(temp, humi))

        # Wait for 1 second between measurements
        time.sleep(1)
    except Exception as e:
        print("Error: ", e)
        time.sleep(1)

When the code is running, you will see the Shell continuously print out the temperature and humidity, and as the program runs steadily, these two values will become more and more accurate.

Learn More

You can also display the temperature and humidity on the I2C LCD1602.

_images/5.13_dht11_lcd_bb.png

Note

  • Open the 5.13_dht11_lcd.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

  • Here you need to use the library called lcd1602.py, please check if it has been uploaded to ESP32, for a detailed tutorial refer to 1.4 Upload the Libraries (Important).

import dht
import machine
import time
from lcd1602 import LCD

# Initialize the DHT11 sensor and connect it to pin 14
sensor = dht.DHT11(machine.Pin(14))

# Initialize the LCD1602 display
lcd = LCD()

# Loop to measure temperature and humidity
while True:
    try:
        # Measure temperature and humidity
        sensor.measure()

        # Get temperature and humidity values
        temp = sensor.temperature()
        humi = sensor.humidity()

        # Print temperature and humidity
        print("Temperature: {}, Humidity: {}".format(temp, humi))

        # Clear the LCD display
        lcd.clear()

        # Display temperature and humidity on the LCD1602 screen
        lcd.write(0, 0, "Temp: {}\xDFC".format(temp))
        lcd.write(0, 1, "Humi: {}%".format(humi))

        # Wait for 2 seconds before measuring again
        time.sleep(2)

    except Exception as e:
        print("Error: ", e)
        time.sleep(2)

5.14 IR Remote Control

An infrared receiver is a component that receives infrared signals and can independently detect and output signals compatible with TTL level. It is similar in size to a regular plastic-packaged transistor and is commonly used in various applications such as infrared remote control and infrared transmission.

In this project, we will use an infrared receiver to detect signals from a remote control. When a button on the remote control is pressed and the infrared receiver receives the corresponding signal, it can decode the signal to determine which button was pressed. By decoding the received signal, we can identify the specific key or command associated with it.

The infrared receiver allows us to incorporate remote control functionality into our project, enabling us to interact with and control devices using infrared signals.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

IR Receiver

BUY

Available Pins

Here is a list of available pins on the ESP32 board for this project.

Available Pins

IO13, IO12, IO14, IO27, IO26, IO25, IO15, IO0, IO5, IO18, IO19, IO21, IO22, IO23

Schematic

_images/circuit_5.14_receiver.png

When you press a button on the remote control, the infrared receiver detects the signal, and you can use an infrared library to decode it. This decoding process allows you to obtain the key value associated with the button press.

Wiring

_images/5.14_ir_receiver_bb.png

Code

Note

  • Open the 5.14_ir_receiver.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

  • Here, you need to utilize the libraries found in the ir_rx folder. Please ensure they have been uploaded to the ESP32. For a comprehensive tutorial, refer to 1.4 Upload the Libraries (Important).

import time
from machine import Pin, freq
from ir_rx.print_error import print_error
from ir_rx.nec import NEC_8

pin_ir = Pin(14, Pin.IN) # IR receiver

# Decode the received data and return the corresponding key name
def decodeKeyValue(data):
    if data == 0x16:
        return "0"
    if data == 0x0C:
        return "1"
    if data == 0x18:
        return "2"
    if data == 0x5E:
        return "3"
    if data == 0x08:
        return "4"
    if data == 0x1C:
        return "5"
    if data == 0x5A:
        return "6"
    if data == 0x42:
        return "7"
    if data == 0x52:
        return "8"
    if data == 0x4A:
        return "9"
    if data == 0x09:
        return "+"
    if data == 0x15:
        return "-"
    if data == 0x7:
        return "EQ"
    if data == 0x0D:
        return "U/SD"
    if data == 0x19:
        return "CYCLE"
    if data == 0x44:
        return "PLAY/PAUSE"
    if data == 0x43:
        return "FORWARD"
    if data == 0x40:
        return "BACKWARD"
    if data == 0x45:
        return "POWER"
    if data == 0x47:
        return "MUTE"
    if data == 0x46:
        return "MODE"
    return "ERROR"

# User callback
def callback(data, addr, ctrl):
    if data < 0:  # NEC protocol sends repeat codes.
        pass
    else:
        print(decodeKeyValue(data))


ir = NEC_8(pin_ir, callback) # Instantiate the NEC_8 receiver

# Show debug information
ir.error_function(print_error)

# keep the script running until interrupted by a keyboard interrupt (Ctrl+C)
try:
    while True:
        pass
except KeyboardInterrupt:
    ir.close()  # Close the receiver

When the program is running, press the key on the remote control, the value and name of the key will appear in the Shell.

Note

The new remote control features a plastic tab at the end to insulate the battery inside. To power up the remote when using it, simply remove this plastic piece.

How it works?

  1. While this program may appear somewhat complex at first glance, it actually accomplishes the fundamental functions of the IR receiver using just a few lines of code.

    import time
    from machine import Pin, freq
    from ir_rx.nec import NEC_8
    
    pin_ir = Pin(14, Pin.IN) # IR receiver
    
    # User callback
    def callback(data, addr, ctrl):
        if data < 0:  # NEC protocol sends repeat codes.
            pass
        else:
            print(decodeKeyValue(data))
    
    ir = NEC_8(pin_ir, callback)  # Instantiate receiver
    
    • In this code, an ir object is instantiated, allowing it to read the signals captured by the IR receiver at any given moment.

    • The resulting information is then stored in the data variable within the callback function.

    • If the IR receiver receives duplicate values (e.g., when a button is pressed and held down), the data will be less than 0, and this data needs to be filtered out.

    • Otherwise, the data would be a usable value, albeit in an unreadable code. The decodeKeyValue(data) function is then utilized to decode it into a more comprehensible format.

      def decodeKeyValue(data):
          if data == 0x16:
              return "0"
          if data == 0x0C:
              return "1"
          if data == 0x18:
              return "2"
          if data == 0x5E:
          ...
      
  2. Next, we incorporate several debug functions into the program. While these functions are essential, they are not directly related to the desired outcome we aim to achieve.

    from ir_rx.print_error import print_error
    
    ir.error_function(print_error) # Show debug information
    
  3. Lastly, we use an empty loop for the main program and implement a try-except structure to ensure the program exits with the ir object properly terminated.

    try:
        while True:
            pass
    except KeyboardInterrupt:
        ir.close()
    

6. Funny Projects

6.1 Fruit Piano

Have you ever wanted to play the piano but couldn’t afford one? Or maybe you just want to have some fun with diy a fruit piano? Well, this project is for you!

With just a few touch sensors on the ESP32 board, you can now play your favorite tunes and enjoy the experience of playing the piano without breaking the bank.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Buzzer

BUY

Transistor

BUY

About the Touch Pins

The ESP32 microcontroller has built-in touch sensor functionality, which allows you to use certain pins on the board as touch-sensitive inputs. The touch sensor works by measuring changes in capacitance on the touch pins, which are caused by the electrical properties of the human body.

Here are some key features of the touch sensor on the ESP32:

  • Number of touch pins

    The ESP32 has up to 10 touch pins, depending on the specific board. The touch pins are typically labeled with a “T” followed by a number.

    • GPIO4: TOUCH0

    • GPIO0:TOUCH1

    • GPIO2: TOUCH2

    • GPIO15: TOUCH3

    • GPIO13: TOUCH4

    • GPIO12: TOUCH5

    • GPIO14: TOUCH6

    • GPIO27: TOUCH7

    • GPIO33: TOUCH8

    • GPIO32: TOUCH9

    Note

    The GPIO0 and GPIO2 pins are used for bootstrapping and flashing firmware to the ESP32, respectively. These pins are also connected to the onboard LED and button. Therefore, it is generally not recommended to use these pins for other purposes, as it could interfere with the normal operation of the board.

  • Sensitivity

    The touch sensor on the ESP32 is very sensitive and can detect even small changes in capacitance. The sensitivity can be adjusted using software settings.

  • ESD Protection

    The touch pins on the ESP32 have built-in ESD (Electrostatic Discharge) protection, which helps to prevent damage to the board from static electricity.

  • Multitouch

    The touch sensor on the ESP32 supports multitouch, which means that you can detect multiple touch events simultaneously.

Schematic

_images/circuit_6.1_fruit_piano.png

The idea behind this project is to use touch sensors to detect when a user touches a specific pin. Each touch pin is associated with a specific note, and when the user touches a pin, the corresponding note is played on the passive buzzer. The result is a simple and affordable way to enjoy the experience of playing the piano.

Wiring

_images/6.1_fruit_piano_bb.png

In this project, you need to remove the ESP32 WROOM 32E from the expansion board and then insert it into the breadboard. This is because some pins on the expansion board are connected to resistors, which will affect the capacitance of the pins.

Code

Note

  • Open the 6.1_fruit_piano.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import Pin, PWM, TouchPad
import time

# Define the touch pins and their corresponding notes
touch_pins = [4, 15, 13, 12, 14, 27, 33, 32]  # Use valid touch-capable pins
notes = [262, 294, 330, 349, 392, 440, 494, 523]

# Initialize the touch sensors
touch_sensors = [TouchPad(Pin(pin)) for pin in touch_pins]

# Initialize the buzzer
buzzer = PWM(Pin(25), duty=0)

# Function to play a tone
def play_tone(frequency, duration):
    buzzer.freq(frequency)
    buzzer.duty(512)
    time.sleep_ms(duration)
    buzzer.duty(0)

touch_threshold = 200

# Main loop to check for touch inputs and play the corresponding note
while True:
    for i, touch_sensor in enumerate(touch_sensors):
        value = touch_sensor.read()
        print(i,value)
        if value < touch_threshold:
            play_tone(notes[i], 100)
            time.sleep_ms(50)
        time.sleep(0.01)

You can connect fruits to these ESP32 pins: 4, 15, 13, 12, 14, 27, 33, 32.

When the script runs, touching these fruits will play the notes C, D, E, F, G, A, B and C5.

Note

Touch_threshold needs to be adjusted based on the conductivity of different fruits.

You can run the script first to see the values printed by the shell.

0 884
1 801
2 856
3 964
4 991
5 989
6 1072
7 1058

After touching the fruits on pins 12, 14, and 27, the printed values are as follows. Therefore, I set the touch_threshold to 200, which means that when a value less than 200 is detected, it is considered to be touched, and the buzzer will emit different notes.

0 882
1 810
2 799
3 109
4 122
5 156
6 1068
7 1055

6.2 Flowing Light

Have you ever wanted to add some fun and interactive element to your living space? This project involves creating a running light using WS2812 LED strip and a obstacle avoidance module. The running light changes direction when an obstacle is detected, making it an exciting addition to your home or office decor.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Obstacle Avoidance Module

BUY

WS2812 RGB 8 LEDs Strip

BUY

Schematic Diagram

_images/circuit_6.2_flowing_led.png

The WS2812 LED strip is composed of a series of individual LEDs that can be programmed to display different colors and patterns. In this project, the strip is set up to display a running light that moves in a particular direction and changes direction when an obstacle is detected by the obstacle avoidance module.

Wiring

_images/6.2_flowing_light_bb.png

Code

Note

  • Open the 6.2_flowing_led.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import Pin
import neopixel
import time
import random

# Set the number of pixels for the running light
num_pixels = 8

# Set the data pin for the RGB LED strip
data_pin = Pin(14, Pin.OUT)

# Initialize the RGB LED strip object
pixels = neopixel.NeoPixel(data_pin, num_pixels)

# Initialize the avoid sensor
avoid = Pin(25, Pin.IN)

# Initialize the direction variable
direction_forward = True

# Initialize the reverse direction flag
reverse_direction = False

# Continuously loop the running light
while True:

# Read the input from the infrared sensor
avoid_value = avoid.value()

# Generate a random color for the current pixel
color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

# If no obstacle is detected
if avoid_value:
      for i in range(num_pixels):

            # Turn on the current pixel with the random color
            pixels[i] = color

            # Update the RGB LED strip display
            pixels.write()

            # Turn off the current pixel
            pixels[i] = (0, 0, 0)
            time.sleep_ms(100)

# If detects an obstacle, change the direction of the LED strip
else:
      for i in range(num_pixels-1, -1, -1):

            pixels[i] = color
            pixels.write()
            pixels[i] = (0, 0, 0)
            time.sleep_ms(100)

LEDs on the RGB Strip light up one by one when the script runs. As soon as an object is placed in front of the obstacle avoidance module, the LEDs on the RGB Strip light up one by one in the opposite direction.

6.3 Light Theremin

Theremin is an electronic musical instrument that does not require physical contact. Based on the position of the player’s hand, it produces different tones.

Its controlling section is usually made up of two metal antennas that sense the position of the thereminist’s hands and control oscillators with one hand and volume with the other. The electric signals from the theremin are amplified and sent to a loudspeaker.

We cannot reproduce the same instrument through ESP32, but we can use photoresistor and passive buzzer to achieve similar gameplay.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Photoresistor

BUY

Buzzer

BUY

Transistor

BUY

Schematic

_images/circuit_6.3_light_theremin.png

Before starting the project, calibrate the range of light intensity by waving your hand over the photoresistor. The LED connected to IO26 is used as an indicator during the calibration process. When the LED is lit, it signifies the start of calibration, and when it is turned off, it indicates the end of calibration.

As you wave your hand over the photoresistor, the value of the photoresistor will change accordingly. Utilize this change to control the buzzer and play different musical notes. Each variation in the photoresistor’s value can be mapped to a specific musical note, allowing the buzzer to produce a melody as you wave your hand over the photoresistor.

Wiring

_images/6.3_theremin_bb.png

Code

Note

  • Open the 6.3_light_theremin.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import Pin, PWM, ADC
import time

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

# Initialize light sensor
sensor = ADC(Pin(35))
sensor.atten(ADC.ATTN_11DB)

# Initialize buzzer
buzzer = PWM(Pin(13), freq=440, duty=0)

light_low=4095
light_high=0

# Map the interval of input values to output values
def interval_mapping(x, in_min, in_max, out_min, out_max):
    return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min

# Create a tone using the specified pin, frequency, and duration
def tone(pin,frequency,duration):
    pin.freq(frequency)
    pin.duty(512)
    time.sleep_ms(duration)
    pin.duty(0)

# Calibrate the photoresistor's maximum and minimum values in 5 seconds.
timer_init_start = time.ticks_ms()
led.value(1) # turn on the LED
while time.ticks_diff(time.ticks_ms(), timer_init_start)<5000:
    light_value = sensor.read()
    if light_value > light_high:
        light_high = light_value
    if light_value < light_low:
        light_low = light_value
led.value(0) # turn off the LED

# Play the tones based on the light values
while True:
    light_value  = sensor.read()
    pitch = int(interval_mapping(light_value,light_low,light_high,50,6000))
    if pitch > 50 :
        tone(buzzer,pitch,20)
    time.sleep_ms(10)

Upon starting the program, the LED turns on, providing us with a five-second window to calibrate the photoresistor’s detection range.

Calibration is a crucial step as it accounts for various lighting conditions that we may encounter while using the device, such as varying light intensities during different times of the day. Additionally, the calibration process takes into account the distance between our hands and the photoresistor, which determines the playable range of the instrument.

Once the calibration period is over, the LED turns off, indicating that we can now play the instrument by waving our hands over the photoresistor. This setup enables us to create music by adjusting the height of our hands, providing an interactive and enjoyable experience.

6.4 Reversing Aid

Imagine this: You’re in your car, about to reverse into a tight parking spot. With our project, you will have an ultrasonic module mounted on the rear of your vehicle, acting as a digital eye. As you engage the reverse gear, the module springs to life, emitting ultrasonic pulses that bounce off obstacles behind you.

The magic happens when these pulses return to the module. It swiftly calculates the distance between your car and the objects, transforming this data into real-time visual feedback displayed on a vibrant LCD screen. You’ll witness dynamic, color-coded indicators depicting the proximity of obstacles, ensuring you have a crystal-clear understanding of the surrounding environment.

But we didn’t stop there. To immerse you further into this driving experience, we incorporated a lively buzzer. As your car inches closer to an obstacle, the buzzer’s tempo intensifies, creating an auditory symphony of warnings. It’s like having a personal orchestra guiding you through the complexities of reverse parking.

This innovative project combines cutting-edge technology with an interactive user interface, making your reversing experience safe and stress-free. With the ultrasonic module, LCD display, and lively buzzer working harmoniously, you’ll feel empowered and confident while maneuvering in tight spaces, leaving you free to focus on the joy of driving.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Ultrasonic Module

BUY

Buzzer

-

Transistor

BUY

I2C LCD1602

BUY

Schematic

_images/circuit_6.4_reversing_aid.png

The ultrasonic sensor in the project emits high-frequency sound waves and measures the time it takes for the waves to bounce back after hitting an object. By analyzing this data, the distance between the sensor and the object can be calculated. To provide a warning when the object is too close, a buzzer is used to produce an audible signal. Additionally, the measured distance is displayed on an LCD screen for easy visualization.

Wiring

_images/6.4_aid_ultrasonic_bb.png

Code

Note

  • Open the 6.4_reversing_aid.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

# Import required libraries
from machine import Pin
import time
from lcd1602 import LCD
import _thread

# Initialize the buzzer
buzzer = Pin(14, Pin.OUT)

# Initialize the ultrasonic module
TRIG = Pin(26, Pin.OUT)
ECHO = Pin(25, Pin.IN)

# Initialize the LCD1602 display
lcd = LCD()

dis = 100

# Calculate the distance
def distance():
    # Ensure trigger is off initially
    TRIG.off()
    time.sleep_us(2)  # Wait for 2 microseconds

    # Send a 10-microsecond pulse to the trigger pin
    TRIG.on()
    time.sleep_us(10)
    TRIG.off()

    # Wait for the echo pin to go high
    while not ECHO.value():
        pass

    # Record the time when the echo pin goes high
    time1 = time.ticks_us()

    # Wait for the echo pin to go low
    while ECHO.value():
        pass

    # Record the time when the echo pin goes low
    time2 = time.ticks_us()

    # Calculate the time difference between the two recorded times
    during = time.ticks_diff(time2, time1)

    # Calculate and return the distance (in cm) using the speed of sound (340 m/s)
    return during * 340 / 2 / 10000

# Thread to continuously update the ultrasonic sensor reading
def ultrasonic_thread():
    global dis
    while True:
        dis = distance()

        # Clear the LCD screen
        lcd.clear()

        # Display the distance
        lcd.write(0, 0, 'Dis: %.2f cm' % dis)
        time.sleep(0.5)

# Start the ultrasonic sensor reading thread
_thread.start_new_thread(ultrasonic_thread, ())

# Beep function for the buzzer
def beep():
    buzzer.value(1)
    time.sleep(0.1)
    buzzer.value(0)
    time.sleep(0.1)

# Initialize the intervals variable
intervals = 10000000
previousMills = time.ticks_ms()
time.sleep(1)

# Main loop
while True:
    # Update intervals based on distance
    if dis < 0 and dis > 500:
        pass
    elif dis <= 10:
        intervals = 300
    elif dis <= 20:
        intervals = 500
    elif dis <= 50:
        intervals = 1000
    else:
        intervals = 2000

    # Print the distance if it's not -1
    if dis != -1:
        print('Distance: %.2f' % dis)
    time.sleep_ms(100)

    # Check if it's time to beep
    currentMills = time.ticks_ms()
    if time.ticks_diff(currentMills, previousMills) >= intervals:
        beep()
        previousMills = currentMills
  • When the script is running, the ultrasonic module will continuously detect the distance of obstacles in front of it, and display the distance on the Shell and I2C LCD1602.

  • As the obstacle gets closer, the beeping frequency of the buzzer will become more rapid.

  • The ultrasonic_thread() function runs in a separate thread so that it can update the distance measurement continuously without blocking the main loop.

Note

If the code and wiring are correct, but the LCD still fails to display any content, you can adjust the potentiometer on the back to increase the contrast.

6.5 Color Gradient

Are you ready to experience a world of color? This project will take you on a magical journey where you can control an LED strip and achieve smooth color transitions. Whether you’re looking to add some color to your home decor or seeking a fun programming project, this project has got you covered. Let’s dive into this colorful world together!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Potentiometer

BUY

WS2812 RGB 8 LEDs Strip

BUY

Schematic

_images/circuit_6.5_color_gradient.png

This project uses an LED strip and a potentiometer to create a color mixing effect. The potentiometer is used to adjust the hue value of the LED, which is then converted into RGB values using a color conversion function. The RGB values are then used to update the color of the LED.

Wiring

_images/6.5_color_strip_bb.png

Code

Note

  • Open the 6.5_color_gradient.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import Pin, ADC, PWM
import neopixel
import time

NUM_LEDS = 8  # Number of LEDs in the strip
PIN_NUM = 26  # LED strip
POT_PIN = 14  # Potentiometer

# Initialize the potentiometer
potentiometer = ADC(Pin(POT_PIN))
potentiometer.atten(ADC.ATTN_11DB)

# Initialize the NeoPixel LED strip
np = neopixel.NeoPixel(Pin(PIN_NUM), NUM_LEDS)

# Function to convert HSL color space to RGB color space
def hsl_to_rgb(h, s, l):
    # Helper function to convert hue to RGB
    def hue_to_rgb(p, q, t):
        if t < 0:
            t += 1
        if t > 1:
            t -= 1
        if t < 1/6:
            return p + (q - p) * 6 * t
        if t < 1/2:
            return q
        if t < 2/3:
            return p + (q - p) * (2/3 - t) * 6
        return p

    if s == 0:
        r = g = b = l
    else:
        q = l * (1 + s) if l < 0.5 else l + s - l * s
        p = 2 * l - q
        r = hue_to_rgb(p, q, h + 1/3)
        g = hue_to_rgb(p, q, h)
        b = hue_to_rgb(p, q, h - 1/3)

    return (int(r * 255), int(g * 255), int(b * 255))

# Function to set the color of all LEDs in the strip
def set_color(np, color):
    for i in range(NUM_LEDS):
        np[i] = color
    np.write()

# Main loop
while True:
    # Read the potentiometer value and normalize it to the range [0, 1]
    pot_value = potentiometer.read() / 4095.0
    hue = pot_value  # Set hue value based on the potentiometer's position
    saturation = 1  # Set saturation to 1 (fully saturated)
    lightness = 0.5  # Set lightness to 0.5 (halfway between black and white)

    # Convert the HSL color to RGB
    current_color = hsl_to_rgb(hue, saturation, lightness)

    # Set the LED strip color based on the converted RGB value
    set_color(np, current_color)

    # Sleep for a short period to allow for smooth transitions
    time.sleep(0.1)

As the code runs, slowly rotate the potentiometer and you will see the color of the RGB Strip fade from red to purple.

6.6 Digital Dice

This project builds upon the 2.5 Number Display project by adding a button to control the digit displayed on the seven-segment display.

When the button is pressed, the 7-segment display scrolls through the numbers 1-6, and when the button is released, it displays a random number.

This cycle continues each time the button is pressed.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

74HC595

BUY

7-segment Display

BUY

Button

BUY

Schematic

_images/circuit_6.6_electronic_dice.png

This project builds upon the 2.5 Number Display project by adding a button to control the digit displayed on the seven-segment display.

The button is directly connected to IO13 without an external pull-up or pull-down resistor because IO13 has an internal pull-up resistor of 47K, eliminating the need for an additional external resistor.

Wiring

_images/6.6_DICE_bb.png

Code

Note

  • Open the 6.6_digital_dice.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

import machine
import time
import random

# Define the segment code for a common anode 7-segment display
SEGCODE = [0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07, 0x7f, 0x6f]

# Initialize the pins for the 74HC595 shift register
sdi = machine.Pin(25, machine.Pin.OUT)  # DS
rclk = machine.Pin(27, machine.Pin.OUT)  # STcp
srclk = machine.Pin(26, machine.Pin.OUT)  # SHcp

button = machine.Pin(13, machine.Pin.IN) # Button pin

# Define the hc595_shift function to shift data into the 74HC595 shift register
def hc595_shift(dat):
    # Set the RCLK pin to low
    rclk.off()

    # Iterate through each bit (from 7 to 0)
    for bit in range(7, -1, -1):
        # Extract the current bit from the input data
        value = 1 & (dat >> bit)

        # Set the SRCLK pin to low
        srclk.off()

        # Set the value of the SDI pin
        sdi.value(value)

        # Clock the current bit into the shift register by setting the SRCLK pin to high
        srclk.on()

    # Latch the data into the storage register by setting the RCLK pin to high
    rclk.on()

# Initialize the random seed
random.seed(time.ticks_us())


num = 1
button_state = False

# Define the button callback function to toggle the button state
def button_callback(pin):
    global button_state
    button_state = not button_state

# Attach the button callback function to the falling edge of the button pin
button.irq(trigger=machine.Pin.IRQ_FALLING, handler=button_callback)

# Continuously display the current digit on the 7-segment display, scrolling if button is not pressed
while True:

    # Display the current digit on the 7-segment display
    hc595_shift(SEGCODE[num])

    # If the button is pressed and button state is True
    if button_state:
        pass

    # If the button is pressed again and button state is False, generate a new random digit
    if not button_state:
        num = random.randint(1, 6)
        time.sleep_ms(10) # Adjust this value to control the display refresh rate

While the program is running, pressing the button will make the 7-segment display scroll and randomly display a number between 1 and 6.

Upon pressing the button again, the 7-segment display will stop and reveal a specific number. Press the button once more, and the 7-segment display will resume scrolling through the digits.

6.7 Guess Number

Are you feeling lucky? Want to test your intuition and see if you can guess the right number? Then look no further than the Guess Number game!

With this project, you can play a fun and exciting game of chance.

Using an IR remote control, players input numbers between 0 and 99 to try and guess the randomly generated lucky point number. The system displays the player’s input number on an LCD screen, along with upper and lower limit tips to help guide the player towards the right answer. With every guess, players get closer to the lucky point number, until finally, someone hits the jackpot and wins the game!

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

IR Receiver

BUY

I2C LCD1602

BUY

Schematic

_images/circuit_6.7_guess_number.png

Wiring

_images/6.7_guess_receiver_bb.png

Code

Note

  • Open the 6.7_game_guess_number.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

  • The lcd1602.py and ir_rx libraries are used here and check if it’s uploaded to ESP32. Refer to 1.4 Upload the Libraries (Important) for a tutorial.

from lcd1602 import LCD
import machine
import time
import urandom
from machine import Pin
from ir_rx.print_error import print_error
from ir_rx.nec import NEC_8

# IR receiver configuration
pin_ir = Pin(14, Pin.IN)

# Initialize the guessing game variables
lower = 0
upper = 99
pointValue = int(urandom.uniform(lower, upper))
count = 0

# Initialize the LCD1602 display
lcd = LCD()

# Initialize a new random value for the game
def init_new_value():
    global pointValue, upper, lower, count
    pointValue = int(urandom.uniform(lower, upper))
    print(pointValue)
    upper = 99
    lower = 0
    count = 0
    return False

# Display messages on the LCD based on the game state
def lcd_show(result):
    global count
    lcd.clear()
    if result == True:
        string = "GAME OVER!\n"
        string += "Point is " + str(pointValue)
    else:
        string = "Enter number: " + str(count) + "\n"
        string += str(lower) + " < Point < " + str(upper)
    lcd.message(string)
    return

# Process the entered number and update the game state
def number_processing():
    global upper, count, lower
    if count > pointValue:
        if count < upper:
            upper = count
    elif count < pointValue:
        if count > lower:
            lower = count
    elif count == pointValue:
        return True
    count = 0
    return False

# Process the key inputs from the IR remote control
def process_key(key):
    global count, lower, upper, pointValue, result
    if key == "Power":
        init_new_value()
        lcd_show(False)
    elif key == "+":
        result = number_processing()
        lcd_show(result)
        if result:
            time.sleep(5)
            init_new_value()
            lcd_show(False)
        else:
            lcd_show(False)
    elif key.isdigit():
        count = count * 10 + int(key) if count * 10 + int(key) <= 99 else count
        lcd_show(False)

# Decode the received data and return the corresponding key name
def decodeKeyValue(data):
    if data == 0x16:
        return "0"
    if data == 0x0C:
        return "1"
    if data == 0x18:
        return "2"
    if data == 0x5E:
        return "3"
    if data == 0x08:
        return "4"
    if data == 0x1C:
        return "5"
    if data == 0x5A:
        return "6"
    if data == 0x42:
        return "7"
    if data == 0x52:
        return "8"
    if data == 0x4A:
        return "9"
    if data == 0x09:
        return "+"
    if data == 0x15:
        return "-"
    if data == 0x7:
        return "EQ"
    if data == 0x0D:
        return "U/SD"
    if data == 0x19:
        return "CYCLE"
    if data == 0x44:
        return "PLAY/PAUSE"
    if data == 0x43:
        return "FORWARD"
    if data == 0x40:
        return "BACKWARD"
    if data == 0x45:
        return "POWER"
    if data == 0x47:
        return "MUTE"
    if data == 0x46:
        return "MODE"
    return "ERROR"

def callback(data, addr, ctrl):
    if data < 0:
        pass
    else:
        key = decodeKeyValue(data)
        if key != "ERROR":
            process_key(key)

# Initialize the IR receiver object with the callback function
ir = NEC_8(pin_ir, callback)

# ir.error_function(print_error)

# Initialize the game with a new random value
init_new_value()

# Show the initial game state on the LCD
lcd_show(False)

try:
    while True:
        pass
except KeyboardInterrupt:
    ir.close()
  • When the code runs, a secret number is produced but not displayed on the LCD, and what you need to do is to guess it.

  • Press the number you guessed on the remote control, then press the + key to confirm.

  • Simultaneously, the range shown on the I2C LCD1602 will decrease, and you must press the appropriate number based on this new range.

  • If you got the lucky number luckily or unluckily, there will appear GAME OVER!.

Note

If the code and wiring are correct, but the LCD still fails to display any content, you can adjust the potentiometer on the back to increase the contrast.

How it works?

The following is a detailed analysis of part of the code.

  1. Initialize the guessing game variables.

    lower = 0
    upper = 99
    pointValue = int(urandom.uniform(lower, upper))
    count = 0
    
    • lower and upper bounds for the secret number.

    • The secret number (pointValue) randomly generated between lower and upper bounds.

    • The user’s current guess (count).

  2. This function resets the guessing game values and generates a new secret number.

    def init_new_value():
        global pointValue, upper, lower, count
        pointValue = int(urandom.uniform(lower, upper))
        print(pointValue)
        upper = 99
        lower = 0
        count = 0
        return False
    
  3. This function displays the current game status on the LCD screen.

    def lcd_show(result):
        global count
        lcd.clear()
        if result == True:
            string = "GAME OVER!\n"
            string += "Point is " + str(pointValue)
        else:
            string = "Enter number: " + str(count) + "\n"
            string += str(lower) + " < Point < " + str(upper)
        lcd.message(string)
        return
    
    • If the game is over (result=True), it shows GAME OVER! and the secret number.

    • Otherwise, it shows the current guess (count) and the current guessing range (lower to upper)

  4. This function processes the user’s current guess (count) and updates the guessing range.

    def number_processing():
        global upper, count, lower
        if count > pointValue:
            if count < upper:
                upper = count
        elif count < pointValue:
            if count > lower:
                lower = count
        elif count == pointValue:
            return True
        count = 0
        return False
    
    • If the current guess (count) is higher than the secret number, the upper bound is updated.

    • If the current guess (count) is lower than the secret number, the lower bound is updated.

    • If the current guess (count) is equal to the secret number, the function returns True (game over).

  5. This function processes the key press events received from the IR remote.

    def process_key(key):
        global count, lower, upper, pointValue, result
        if key == "Power":
            init_new_value()
            lcd_show(False)
        elif key == "+":
            result = number_processing()
            lcd_show(result)
            if result:
                time.sleep(5)
                init_new_value()
                lcd_show(False)
            else:
                lcd_show(False)
        elif key.isdigit():
            count = count * 10 + int(key) if count * 10 + int(key) <= 99 else count
            lcd_show(False)
    
    • If the Power key is pressed, the game is reset.

    • If the + key is pressed, the current guess (count) is processed and the game status is updated.

    • If a digit key is pressed, the current guess (count) is updated with the new digit.

  6. This callback function is triggered when the IR receiver receives

    def callback(data, addr, ctrl):
        if data < 0:
            pass
        else:
            key = decodeKeyValue(data)
            if key != "ERROR":
                process_key(key)
    

6.8 Plant Monitor

Welcome to the Plant Monitor project!

In this project, we will be using an ESP32 board to create a system that helps us take care of our plants. With this system, we can monitor the temperature, humidity, soil moisture, and light levels of our plants, and ensure that they are getting the care and attention they need to thrive.

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

DHT11 Humiture Sensor

BUY

I2C LCD1602

BUY

Centrifugal Pump

-

L293D

-

Button

BUY

Photoresistor

BUY

Soil Moisture Module

BUY

Schematic

_images/circuit_6.8_plant_monitor_l293d.png

The system uses a DHT11 sensor to measure the temperature and humidity levels of the surrounding environment. Meanwhile, a soil moisture module is used to measure the moisture level of the soil and a photoresistor is used to measure the light level. The readings from these sensors are displayed on an LCD screen, and a water pump can be controlled using a button to water the plant when needed.

IO32 has an internal pull-down resistor of 1K, and by default, it is at a low logic level. When the button is pressed, it establishes a connection to VCC (high voltage), resulting in a high logic level on IO32.

Wiring

Note

It is recommended here to insert the battery and then slide the switch on the expansion board to the ON position to activate the battery supply.

_images/6.8_plant_monitor_l293d_bb.png

Code

Note

  • Open the 6.8_plant_monitor.py file located in the esp32-starter-kit-main\micropython\codes path, or copy and paste the code into Thonny. Then, click “Run Current Script” or press F5 to execute it.

  • Make sure to select the “MicroPython (ESP32).COMxx” interpreter in the bottom right corner.

from machine import ADC, Pin
import time
import dht
from lcd1602 import LCD

# DHT11
dht11 = dht.DHT11(Pin(13))

# Soil moisture
moisture_pin = ADC(Pin(14))
moisture_pin.atten(ADC.ATTN_11DB)

# Photoresistor
photoresistor = ADC(Pin(35))
photoresistor.atten(ADC.ATTN_11DB)

# Button and pump
button = Pin(32, Pin.IN)

motor1A = Pin(27, Pin.OUT)
motor2A = Pin(26, Pin.OUT)

# I2C LCD1602 setup
lcd = LCD()

# Rotate the pump
def rotate():
motor1A.value(1)
motor2A.value(0)

# Stop the pump
def stop():
motor1A.value(0)
motor2A.value(0)

button_state = False

# Define the button callback function to toggle the button state
def button_callback(pin):
global button_state
button_state = not button_state

# Attach the button callback function to the rising edge of the button pin
button.irq(trigger=Pin.IRQ_RISING, handler=button_callback)

page = 0
temp = 0
humi = 0

try:
while True:

      # If the button is pressed and button state is True
      if button_state:
            print("rotate")
            rotate()

      # If the button is pressed again and button state is False
      if not button_state:
            print("stop")
            stop()
      time.sleep(2)

      # Clear the LCD display
      lcd.clear()

      # Toggle the value of the page variable between 0 and 1
      page=(page+1)%2

      # When page is 1, display temperature and humidity on the LCD1602
      if page is 1:
            try:
            # Measure temperature and humidity
            dht11.measure()

            # Get temperature and humidity values
            temp = dht11.temperature()
            humi = dht11.humidity()
            except Exception as e:
            print("Error: ", e)

            # Display temperature and humidity
            lcd.write(0, 0, "Temp: {}\xDFC".format(temp))
            lcd.write(0, 1, "Humi: {}%".format(humi))

      # If page is 0, display the soil moisture and light
      else:
            light = photoresistor.read()
            moisture = moisture_pin.read()

            # Clear the LCD display
            lcd.clear()

            # Display the value of soil moisture and light
            lcd.write(0, 0, f"Moisture: {moisture}")
            lcd.write(0, 1, f"Light: {light}")

except KeyboardInterrupt:
# Stop the motor when KeyboardInterrupt is caught
stop()
  • When the code is running, the I2C LCD1602 alternately displays temperature and humidity, as well as soil moisture and light intensity analog values, with a 2-second interval.

  • Press the button to start the water pump, and press it again to stop the water pump.

Note

If the code and wiring are correct, but the LCD still fails to display any content, you can adjust the potentiometer on the back to increase the contrast.

Play with Scratch

Besides programming on the Arduino IDE or Thonny IDE, we can also use graphical programming.

Here we recommend programming with Scratch, but the official Scratch is currently only compatible with Raspberry Pi, so we have partnered with a company, STEMPedia, who has developed a Scratch 3 based graphical programming software for many boards - PictoBlox.

_images/1_pictoblox.png

It keeps the basic functions of Scratch 3, but also adds control boards, such as Arduino Uno, Mega, Nano, ESP32, Microbit and STEAMPedia homemade main boards, which can use external sensors, robots to control the sprites on the stage, with strong hardware interaction capabilities.

In addition, it has AI and machine learning, even if you do not have much programming foundation, you can learn and use these popular and high-tech.

Just drag and drop the Scratch coding blocks and make cool games, animations, interactive projects, and even control robots the way you want!

Now let’s start the journey of discovery!

1. Get Started

1.1 Install PictoBlox

Click this link:https://thestempedia.com/product/pictoblox/download-pictoblox/,choose the appropriate Operating System (Windows, macOS, Linux) and follow the steps to install.

_images/download.png

1.2 Interface Introduction

_images/pictoblox_interface.jpg

Sprites

A sprite is an object, or a character, that performs different actions in a project. It understands and obeys the commands given to it. Each sprite has specific costumes and sounds that you can also customize.

Stage

The stage is the area where the sprite performs actions in backdrops according to your program.

Backdrops

Backdrops are used to decorate the stage. You can choose a backdrop from PictoBlox, draw one yourself or upload an image from your computer.

Script Area

A script is a program or a code in PictoBlox/Scratch lingo. It is a set of “blocks” arranged in a specific order to perform a task or a series of tasks. You can write multiple scripts, all of which can run simultaneously. You can only write scripts in the script area in the center of the screen.

Blocks

Blocks are like pieces of a puzzle that are used to write programs by simply stacking them together in the script area. Using blocks to write code can make programming easier and reduce the probability of errors.

Block Palette

The block palettes are located in the left area and are named by their functions, such as motion, sound and control. Each palette has different blocks, for example, the blocks in the Motion palette will control the movement of the sprites, and the blocks in the Control palette will control the work of the script based on specific conditions.

There are other kinds of block palettes that can be loaded from the Add Extension button located at the bottom left.

Modes

Unlike Scratch, PictoBlox has two modes:

  • Stage Mode: In this mode, you can write scripts for the sprite and boards to interact with sprites in real-time. If you disconnect the board with Pictoblox, you cannot interact anymore.

  • Upload Mode: This mode allows you to write scripts and upload it to the board so that you can use even when it is not connected to your computer, for example, you need to upload a script for making moving robots.

For more information, please refer to: https://thestempedia.com/tutorials/getting-started-pictoblox

1.3 Quick Guide on PictoBlox

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

Now let’s learn how to use PictoBlox in two modes.

Also build a simple circuit to make this LED blink in 2 different modes.

_images/1_hello_led_bb.png

Stage Mode

1. Connect to ESP32 Board

Connect your ESP32 board to the computer with a USB cable, usually the computer will automatically recognize your board and finally assign a COM port.

_images/plugin_esp32.png

Open PictoBlox, the Python programming interface will open by default. And we need to switch to the Blocks interface.

_images/0_choose_blocks.png

Then you will see the top right corner for mode switching. The default is Stage mode, where Tobi is standing on the stage.

_images/1_stage_upload.png

Click Board in the upper right navigation bar to select the board.

_images/1_board.png

For example, choose ESP32.

_images/1_choose_uno.png

A connection window will then pop up for you to select the port to connect to, and return to the home page when the connection is complete. If you break the connection during use, you can also click Connect to reconnect.

_images/1_connect.png

At the same time, ESP32 related palettes, such as ESP32, Actuators, etc., will appear in the Block Palette.

_images/1_arduino_uno.png

2. Upload Firmware

Since we’re going to work in the Stage mode, we must upload the firmware to the board. It will ensure real-time communication between the board and the computer. Uploading the firmware it is a one-time process. To do so, click on the Upload Firmware button.

After waiting for a while, the upload success message will appear.

Note

If you are using this board in PictoBlox for the first time, or if this board was previously uploaded with the Arduino IDE. Then you need to tap Upload Firmware before you can use it.

_images/1_firmware.png

3. Programming

  • Open and run the script directly

Of course, you can open the scripts directly to run them, but please download them from github first.

You can click on File in the top right corner and then choose Open.

_images/0_open.png

Choose Open from Computer.

_images/0_dic.png

Then go to the path of esp32-starter-kit-main\scratch, and open 1. Stage Mode.sb3. Please ensure that you have downloaded the required code from github.

_images/0_stage.png

Click directly on the script to run it, some projects are click on the green flag or click on the sprite.

_images/1_more.png
  • Program step by step

You can also write the script step by step by following these steps.

Click on the ESP32 palette.

_images/1_arduino_uno.png

The LED is controlled by the digital pin 26 (only 2 states, HIGH or LOW), so drag the [set digital pin out as] block to the script area.

Since the default state of the LED is lit, now set pin 23 to LOW and click on this block and you will see the LED go off.

  • [set digital pin out as]: Set the digital pin to (HIGH/LOW) level.

_images/1_digital.png

In order to see the effect of continuous blinking LED, you need to use the [Wait 1 seconds] and [forever] blocks in the Control palette. Click on these blocks after writing, there is a yellow halo means it is running.

  • [Wait 1 seconds]: from the Control palette, used to set the time interval between 2 blocks.

  • [forever]: from the Control palette, allows the script to keep running unless manually paused.

_images/1_more.png

Upload Mode

1. Connect to ESP32 Board

Connect your ESP32 board to the computer with a USB cable, usually the computer will automatically recognize your board and finally assign a COM port.

_images/plugin_esp32.png

Open PictoBlox and click Board in the top right navigation bar to select the board.

_images/1_board.png

For example, choose ESP32.

_images/1_choose_uno.png

A connection window will then pop up for you to select the port to connect to, and return to the home page when the connection is complete. If you break the connection during use, you can also click Connect to reconnect.

_images/1_connect.png

At the same time, ESP32 related palettes, such as ESP32, Actuators, etc., will appear in the Block Palette.

_images/1_upload_uno.png

After selecting Upload mode, the stage will switch to the original code area.

_images/1_upload.png

2. Programming

  • Open and run the script directly

You can click on File in the top right corner.

_images/0_open.png

Choose Open from Computer.

_images/0_dic.png

Then go to the path of esp32-starter-kit-main\scratch, and open 1. Upload Mode.sb3. Please ensure that you have downloaded the required code from github.

_images/0_upload.png

Finally, click the Upload Code button.

_images/1_upload_code.png
  • Program step by step

You can also write the script step by step by following these steps.

Click on the ESP32 palette.

_images/1_upload_uno.png

Drag [when ESP32 starts up] to the script area, which is required for every script.

_images/1_uno_starts.png

The LED is controlled by the digital pin26 (only 2 states HIGH or LOW), so drag the [set digital pin out as] block to the script area.

Since the default state of the LED is lit, now set pin26 to LOW and click on this block and you will see the LED go off.

  • [set digital pin out as]: Set the digital pin to (HIGH/LOW) level.

_images/1_upload_digital.png

At this point you will see the code appear on the right side, if you want to edit this code, then you can turn Edit mode on.

_images/1_upload1.png

In order to see the effect of continuous blinking LED, you need to use the [Wait 1 seconds] and [forever] blocks in the Control palette. Click on these blocks after writing, there is a yellow halo means it is running.

  • [Wait 1 seconds]: from the Control palette, used to set the time interval between 2 blocks.

  • [forever]: from the Control palette, allows the script to keep running unless the power is off.

_images/1_upload_more.png

Finally, click the Upload Code button.

_images/1_upload_code.png

2. Projects

The following projects are written in order of programming difficulty, it is recommended to read these books in order.

In each project, there are very detailed steps to teach you how to build the circuit and how to program it step by step to achieve the final result.

Of course, you can also open the script directly to run it, but you need to make sure you have downloaded the relevant material from github.

Once the download is complete, unzip it. Refer to Stage Mode to run individual scripts directly.

But the 2.8 Read Temperature and Humidity is used the Upload Mode.

2.1 Table Lamp

Here, we connect an LED on the breadboard and have the sprite control the blinking of this LED.

When the Button sprite on the stage is clicked, the LED will blink 5 times and then stop.

_images/2_button.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

You Will Learn

  • Breadboard, LEDs and Resistors

  • Building a circuit on a breadboard

  • Delete and select sprites

  • Switching costumes

  • Set a limited number of repeat loops

Build the Circuit

Follow the diagram below to build the circuit on the breadboard.

Since the anode of the LED (the longer pin) is connected to pin26 through a 220Ω resistor, and the cathode of the LED is connected to GND, you can light up the LED by giving pin 9 a high level.

_images/1_hello_led_bb.png

Programming

The whole programming is divided into 3 parts, the first part is to select the desired sprite, the second part is to switch the costume for the sprite to make it look clickable, and the third part is to make the LED blink.

1. Select Button3 sprite

Delete the existing Tobi sprite by using the Delete button in the upper right corner, and select a sprite again.

_images/2_tobi.png

Here, we select the Button3 sprite.

_images/2_button3.png

Click on Costumes in the top right corner and you will see that the Button3 sprite has 2 costumes, we set button3-a to be released and button3-b to be pressed.

_images/2_button3_2.png

2. Switching costumes.

When the sprite is clicked (Events palette), it switches to costume for button3-b (looks palette).

_images/2_switch.png

3. Make the LED blink 5 times

Use the [Repeat] block to make the LED blink 5 times (High-> LOW cycle) and finally switch the costume back to button3-a.

  • [Repeat 10]: limited number of repeat loops, you can set the number of repeats yourself, from the Control palette.

_images/2_led_on_off.png

2.2 Breathing LED

Now use another method to control the brightness of the LED. Unlike the previous project, here the brightness of the LED is made to slowly diminish until it disappears.

When the sprite on the stage is clicked, the brightness of the LED slowly increases and then goes out instantly.

_images/3_ap.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

LED

BUY

You Will Learn

  • Set the output value of the PWM pin

  • Create variables

  • Change the brightness of the sprite

Build the Circuit

This project uses the same circuit as the previous project 2.1 Table Lamp, but instead of using HIGH/LOW to make the LEDs light up or turn off, this project uses the PWM - Wikipedia signal to slowly light up or dim down the LED.

The PWM signal range is 0-255, on the ESP32 board, 2, 5, 12~15, 18, 19, 21, 22, 25, 26 and 27 can output PWM signal.

_images/1_hello_led_bb.png

Programming

1. Select a sprite

Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter button3 in the search box, and then click to add it.

_images/3_sprite.png

2. Creating a variable.

Create a variable called pwm to store the value of the pwm change.

Click on the Variables palette and select Make a Variable.

_images/3_ap_va.png

Enter the name of the variable, it can be any name, but it is recommended to describe its function. The data type is number and For all sprites.

_images/3_ap_pwm.png

Once created, you will see pwm inside the Variables palette and in the checked state, which means this variable will appear on the stage. You can try unchecking it to see if pwm is still present on the stage.

_images/3_ap_0.png

3. Set the initial state

When the button3 sprite is clicked, switch the costume to button-b (clicked state), and set the initial value of the variable pwm to 0.

  • [set pwm to 0]: from Variables palette, used to set the value of the variable.

_images/3_ap_brightness.png

4. Make the LED brighter and brighter

Since the range of pwm is 255, so by [repeat] block, the variable pwm is accumulated to 255 by 5, and then put into [set PWM pin] block, so you can see the LED slowly light up.

  • [change pwm by 5]: from Variables palette, let the variable change a specific number each time. It can be a positive or negative number, positive is increasing each time, negative is decreasing each time, for example, here the variable pwm is increased by 5 each time.

  • [set PWM pin]: from the ESP32 palette, used to set the output value of the pwm pin.

_images/3_ap_1.png

Finally, switch the costume of button3 back to button-a and make the PWM pin value 0, so that the LED will light up slowly and then turn off again.

_images/3_ap_2.png

2.3 Colorful Balls

In this project, we will make the RGB LEDs display different colors.

Clicking on different colored balls on the stage area will cause the RGB LED to light up in different colors.

_images/4_color.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

RGB LED

BUY

You Will Learn

  • The principle of RGB LED

  • Copy sprites and select different costumes

  • Three primary colors superimposed

Build the Circuit

An RGB LED packages three LEDs of red, green, and blue into a transparent or semitransparent plastic shell. It can display various colors by changing the input voltage of the three pins and superimpose them, which, according to statistics, can create 16,777,216 different colors.

_images/4_rgb.png _images/3_color_ball_bb.png

Programming

1. Select sprite

Delete the default sprite, then choose the Ball sprite.

_images/4_ball.png

And duplicate it 5 times.

_images/4_duplicate_ball.png

Choose different costumes for these 5 Ball sprites and move them to the corresponding positions.

Note

Ball3 sprite costume color needs to be manually changed to red.

_images/4_rgb1.png

2. Make RGB LEDs light up in the appropriate color

Before understanding the code, we need to understand the RGB color model.

The RGB color model is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors.

Additive color mixing: adding red to green yields yellow; adding green to blue yields cyan; adding blue to red yields magenta; adding all three primary colors together yields white.

_images/4_rgb_addition.png

So the code to make the RGB LED light yellow is as follows.

_images/4_yellow.png

When the Ball sprite (yellow ball) is clicked, we set pin 27 high (red LED on), pin 26 high (green LED on) and pin 25 low (blue LED off) so that the RGB LED will light yellow.

You can write codes to other sprites in the same way to make the RGB LEDs light up in the corresponding colors.

3. Ball2 sprite (light blue)

_images/4_blue.png

4. Ball3 sprite (red)

_images/4_red.png

5. Ball4 sprite (green)

_images/4_green.png

6. Ball5 sprite (purple)

_images/4_purple.png

2.4 Moving Mouse

Today we are going to make a mouse toy controlled by a potentiometer.

When the green flag is clicked, the mouse on the stage moves forward, and when you rotate the potentiometer, the mouse will change the direction of movement.

_images/6_mouse.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Potentiometer

BUY

You Will Learn

  • Potentiometer principle

  • Read analog pin and ranges

  • Mapping one range to another

  • Moving and changing the direction of sprite

Build the Circuit

The potentiometer is a resistive element with 3 terminals, the 2 side pins are connected to 5V and GND, and the middle pin is connected to pin35. After conversion by the ADC converter of the ESP32, the value range is 0-4095.

_images/5_moving_mouse_bb.png

Programming

1. Choose a sprite

Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter mouse in the search box, and then click to add it.

_images/6_sprite.png

2. Creating a variable.

Create a variable called value to store the value of the potentiometer read.

Once created, you will see value appear inside the Variables palette and in the checked state, which means this variable will appear on the stage.

_images/6_value.png

3. Read the value of pin35

Store the value of pin35 read into the variable value.

  • [set my variable to 0]: Set the value of the variable.

  • [read analog pin ()]: Read the value of pins in the range of 0-4095.

_images/6_read_a0.png

To be able to read all the way through, you need to use the [forever] block. Click on this script to run it, rotate the potentiometer in both directions, and you will see that the value range is 0-1023.

_images/6_1023.png

4. Move the sprite

Use the [move steps] block to move the sprite, run the script and you will see the sprite move from the middle to the right.

_images/6_move.png

5. Changing the sprite’s direction

Now change the direction of the sprite’s movement by the value of pin35. Since the value of pin35 ranges from 0-4095, but the sprite’s rotation direction is -180~180, a [map] block needs to be used.

Also add [when green flag clicked] at the beginning to start the script.

  • [point in direction]: Set the steering angle of the sprite, from Motion palette.

  • [map from to]: Map a range to another range.

_images/6_direction.png

2.5 Doorbell

Here, we will use the button and the bell on the stage to make a doorbell.

After the green flag is clicked, you can press the button and the bell on the stage will make a sound.

_images/7_doorbell.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Button

BUY

You Will Learn

  • How the button work

  • Reading digital pin and ranges

  • Creating a conditional loop

  • Adding a backdrop

  • Playing sound

Build the Circuit

The button is a 4-pin device, since the pin 1 is connected to pin 2, and pin 3 to pin 4, when the button is pressed, the 4 pins are connected, thus closing the circuit.

_images/5_buttonc.png

Build the circuit according to the following diagram.

  • Connect one of the pins on the left side of the button to pin14, which is connected to a pull-down resistor and a 0.1uF (104) capacitor (to eliminate jitter and output a stable level when the button is working).

  • Connect the other end of the resistor and capacitor to GND, and one of the pins on the right side of the button to 5V.

_images/6_doorbel_bb.png

Programming

1. Add a Backdrop

Click the Choose a Backdrop button in the lower right corner.

_images/7_backdrop.png

Choose Bedroom 1.

_images/7_bedroom2.png

2. Select the sprite

Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter bell in the search box, and then click to add it.

_images/7_sprite.png

Then select the bell sprite on the stage and move it to the right position.

_images/7_doorbell.png

3. Press the button and the bell makes a sound

Use [if then] to make a conditional statement that when the value of the pin14 read is equal to 1 (the key is pressed), the sound xylo1 will be played.

  • [read status of digital pin]: This block is from the ESP32 palette and used to read the value of a digital pin, the result is 0 or 1.

  • [if then]: This block is a control block and from Control palette. If its boolean condition is true, the blocks held inside it will run, and then the script involved will continue. If the condition is false, the scripts inside the block will be ignored. The condition is only checked once; if the condition turns to false while the script inside the block is running, it will keep running until it has finished.

  • [play sound until done]: This block is from the Sound palette, used to play specific sounds.

_images/7_bell.png

2.6 Low Temperature Alarm

In this project, we will make a low temperature alarm system, when the temperature is below the threshold, the Snowflake sprite will appear on the stage.

_images/9_tem.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Thermistor

BUY

You Will Learn

  • Thermistor working principle

  • Multivariable and Subtractive Operations

Build the Circuit

A thermistor is a type of resistor whose resistance is strongly dependent on temperature, more so than in standard resistors, and there are two types of resistors, PTC (resistance increases as temperature increases) and PTC (resistance decreases as temperature increases).

Build the circuit according to the following diagram.

One end of the thermistor is connected to GND, the other end is connected to pin35, and a 10K resistor is connected in series to 5V.

The NTC thermistor is used here, so when the temperature rises, the resistance of the thermistor decreases, the voltage division of pin35 decreases, and the value obtained from pin35 decreases, and vice versa increases.

_images/7_low_temp_bb.png

Programming

1. Select a sprite

Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter Snowflake in the search box, and then click to add it.

_images/9_snow.png

2. Create 2 variables

Create two variables, before and current, to store the value of pin35 in different cases.

_images/9_va.png

3. Read the value of pin35

When the green flag is clicked, the value of pin35 is read and stored in the variable before.

_images/9_before.png

4. Read the value of pin35 again

In [forever], read the value of pin35 again and store it in the variable current.

_images/9_current.png

5. Determining temperature changes

Using the [if else] block, determine if the current value of pin35 is 200 greater than before, which represents a decrease in temperature. At this point let Snowflake sprite show, otherwise hide.

  • [-] & [>]: subtraction and comparison operators from Operators platette.

_images/9_show.png

2.7 Light Alarm Clock

In life, there are various kinds of time alarm clocks. Now let’s make a light-controlled alarm clock. When morning comes, the brightness of light increases and this light-controlled alarm clock will remind you that it’s time to get up.

_images/10_clock.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Photoresistor

BUY

You Will Learn

  • Photoresistor working principle

  • Stopping sound playback and stopping scripts from running

Build the Circuit

A photoresistor or photocell is a light-controlled variable resistor. The resistance of a photoresistor decreases with increasing incident light intensity.

Build the circuit according to the following diagram.

Connect one end of the photoresistor to 5V, the other end to pin35, and connect a 10K resistor in series with GND at this end.

So when the light intensity increases, the resistance of a photoresistor decreases, the voltage division of the 10K resistor increases, and the value obtained by pin35 becomes larger.

_images/8_light_alarm_bb.png

Programming

1. Select a sprite

Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, enter bell in the search box, and then click to add it.

_images/10_sprite.png

2. Read the value of pin35

Create two variables before and current. When green flag is clicked, read the value of pin35 and store it in variable before as a reference value. In [forever], read the value of pin35 again, store it in the variable current.

_images/10_reada0.png

3. Make a sound

When the value of current pin35 is greater than the previous 50, which represents the current light intensity is greater than the threshold, then let the sprite make a sound.

_images/10_sound.png

4. Turning the sprite

Use [turn block] to make the bell sprite turn left and right to achieve the alarm effect.

_images/10_turn.png

5. stop all

Stops the alarm when it has been ringing for a while.

_images/10_stop.png

2.8 Read Temperature and Humidity

Previous projects have been using stage mode, but some functions are only available in upload mode, such as serial communication function. In this project, we will print the temperature and humidity of the DHT11 using the Serial Monitor in Upload Mode.

_images/11_serial.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

DHT11 Humiture Sensor

BUY

You Will Learn

  • Get the temperature and humidity from the DHT11 module

  • Serial Monitor for Upload Mode

  • Add extension

Build the Circuit

The digital temperature and humidity sensor DHT11 is a composite sensor that contains a calibrated digital signal output of temperature and humidity.

Now build the circuit according to the following diagram.

_images/9_dht11_bb.png

Programming

1. Adding Extensions

Switch to Upload mode, click the Add Extension button in the bottom left corner, then select Communication to add it, and it will appear at the end of the palette area.

_images/11_addcom.png

2. Initializing the ESP32 and Serial Monitor

In Upload mode, start ESP32 and then set the serial port baud rate.

  • [when ESP32 Starts up]: In Upload mode, start ESP32.

  • [set serial baud rate to]: From the Communications palette, used to set the baud rate of serial port 0, default is 115200. If you are using Mega2560, then you can choose to set baud rate in serial port 0~2.

_images/11_init.png

3. Read temperature and humidity

Create 2 variables tem and humi to store the temperature and humidity respectively, the code will appear on the right side while you drag and drop the block.

_images/11_readtem.png

4. Print them on the Serial Monitor

Write the read temperature and humidity to the Serial Monitor. To avoid transferring too fast and causing PictoBlox to jam, use the [wait seconds] block, to add some time interval for the next print.

_images/11_writeserial.png

5. Uploading code

Unlike the Stage mode, the code in Upload mode needs to be uploaded to the ESP32 board using the Upload Code button to see the effect. This also allows you to unplug the USB cable and still have the program running.

_images/11_upload.png

6. Turn on the serial monitor

Now open the Serial Monitor to see the temperature and humidity.

_images/11_serial.png

2.9 Rotating Fan

In this project, we will make a spinning star sprite and fan.

Clicking on the left and right arrow sprites on the stage will control the clockwise and counterclockwise rotation of the motor and star sprite, click on the star sprite to stop the rotation.

_images/13_fan.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

DC Motor

BUY

L293D

-

You Will Learn

  • Motor working principle

  • Broadcast function

  • Stop other script in sprite block

Build the Circuit

_images/10_rotaing_fan_bb.png

Programming

The effect we want to achieve is to use 2 arrow sprites to control the clockwise and counterclockwise rotation of the motor and the star sprite respectively, clicking on the star sprite will stop the motor from rotating.

1. Add sprites

Delete the default sprite, then select the Star sprite and the Arrow1 sprite, and copy Arrow1 once.

_images/13_star.png

In the Costumes option, change the Arrow1 sprite to a different direction costume.

_images/13_star1.png

Adjust the size and position of the sprite appropriately.

_images/13_star2.png

2. Left arrow sprite

When this sprite is clicked, it broadcasts a message - turn, then sets digital pin12 to low and pin14 to high, and sets the variable flag to 1. If you click the left arrow sprite, you will find that the motor turns counterclockwise, if your turn is clockwise, then you swap the positions of pin12 and pin14.

There are 2 points to note here.

  • [broadcast]: from the Events palette, used to broadcast a message to the other sprites, when the other sprites receive this message, it will perform a specific event. For example, here is turn, when the star sprite receives this message, it executes the rotation script.

  • variable flag: The direction of rotation of the star sprite is determined by the value of flag. So when you create the flag variable, you need to make it apply to all sprites.

_images/13_left.png

3. right-arrow sprite

When this sprite is clicked, broadcast a message turn, then set digital pin12 high and pin14 low to make the motor turn clockwise and set the flag variable to 0.

_images/13_right.png

4. star sprite

There are 2 events included here.

  • When the star sprite receives the broadcasted message turn, it determines the value of flag; if flag is 1, it turns 10 degrees to the left, otherwise it reverses. Since it is in [FOREVER], it will keep turning.

  • When this sprite is clicked, set both pins of the motor to high to make it stop rotating and stop the other scripts in this sprite.

_images/13_broadcast.png

2.10 Light Sensitive Ball

In this project, we use Photoresistor to make the ball on the stage fly upwards. Place your hand on top of the photoresistor to control the light intensity it receives. The closer your hand is to the photoresistor, the smaller its value and the higher the ball flies on the stage, otherwise it will fall. When the ball touches the string, it makes a nice sound as well as a twinkling starlight.

_images/18_ball.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Photoresistor

BUY

You Will Learn

  • Fill the sprite with colors

  • Touch between the sprites

Build the Circuit

A photoresistor or photocell is a light-controlled variable resistor. The resistance of a photoresistor decreases with increasing incident light intensity.

Build the circuit according to the following diagram.

Connect one end of the photoresistor to 5V, the other end to pin35, and connect a 10K resistor in series with GND at this end.

So when the light intensity increases, the resistance of a photoresistor decreases, the voltage division of the 10K resistor increases, and the value obtained by pin35 becomes larger.

_images/8_light_alarm_bb.png

Programming

The effect we want to get is that the closer your hand is to the photoresistor, the ball sprite on the stage keeps going up, otherwise it will fall on the bowl sprite. If it touches the Line sprite while walking up or falling down, it will make a musical sound and emit star sprites in all directions.

1. Select sprite and backdrop

Delete the default sprite, select the Ball, Bowl and Star sprite.

_images/18_ball1.png

Move the Bowl sprite to the bottom center of the stage and enlarge its size.

_images/18_ball3.png

Because we need to move it upwards, so set direction of Ball sprite to 0.

_images/18_ball4.png

Set the size and direction of the Star sprite to 180 because we need it to fall down, or you can change it to another angle.

_images/18_ball12.png

Now add the Stars backdrop.

_images/18_ball2.png

2. Draw a Line sprite

Add a Line sprite.

_images/18_ball7.png

Go to the Costumes page of the Line sprite, reduce the width of the red line on the canvas slightly, then copy it 5 times and align the lines.

_images/18_ball8.png

Now fill the lines with different colors. First choose a color you like, then click on the Fill tool and move the mouse over the line to fill it with color.

_images/18_ball9.png

Follow the same method to change the color of the other lines.

_images/18_ball10.png

3. Scripting the Ball sprite

Set the initial position of the Ball sprite, then when the light value is less than 1500 (it can be any other value, depending on your current environment.), let the Ball move up.

You can make the variable light_value show up on the stage to observe the change of light intensity at any time.

_images/18_ball5.png

Otherwise, the Ball sprite will fall and limit its Y coordinate to a minimum of -100. This can be modified to make it look like it is falling on the Bowl sprite.

_images/18_ball6.png

When the Line sprite is hit, the current Y coordinate is saved to the variable ball_coor and a Bling message is broadcast.

_images/18_ball11.png

4. Scripting the Star sprite

When the script starts, first hide the Star sprite. When the Bling message is received, clone the Star sprite.

_images/18_ball13.png

When the Star sprite appears as a clone, play the sound effect and set its coordinates to be in sync with the Ball sprite.

_images/18_ball14.png

Create the effect of the Star sprite appearing, and adjust it as needed.

_images/18_ball15.png

2.11 GAME - Shooting

Have you seen those shooting games on TV? The closer a contestant shoots a bullet on the target to the bullseye, the higher his score.

Today we are also doing a shooting game in Scratch. In the game, let the Crosshair shoot as far as possible to the bullseye to get a higher score.

Click on the green flag to start. Use the Obstacle Avoidance module to shoot an bullet.

_images/14_shooting.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Obstacle Avoidance Module

BUY

You Will Learn

  • How the Obstacle Avoidance module works and the angle range

  • Paint different sprites

  • Touch colors

Build the Circuit

The obstacle avoidance module is a distance-adjustable infrared proximity sensor whose output is normally high and low when an obstacle is detected.

Now build the circuit according to the diagram below.

_images/12_shooting_bb.png

Programming

1. Paint the Crosshair sprite

Delete the default sprite, select the Sprite button and click Paint, a blank sprite Sprite1 will appear and name it Crosshair.

_images/14_shooting0.png

Go to the Crosshair sprite’s Costumes page. Click on the Circle tool, remove the fill color, and set the color and width of the outline.

_images/14_shooting02.png

Now draw a circle with the Circle tool. After drawing, you can click to the Select tool and move the circle so that the original point is aligned with the center of the canvas.

_images/14_shooting03.png

Using the Line tool, draw a cross inside the circle.

_images/14_shooting033.png

Paint the Target sprite

Create a new sprite called Target sprite.

_images/14_shooting01.png

Go to the Costumes page of the Target sprite, click on the Circle tool, select a fill color and remove the Outline and paint a large circle.

_images/14_shooting05.png

Use the same method to draw additional circles, each with a different color, and you can use the Forward or Backbard tool to change the position of the overlapping circles. Note that you also need to select the tool to move the circles, so that the origin of all the circles and the center of the canvas are aligned.

_images/14_shooting04.png

3. Add a backdrop

Add a suitable background which preferably does not have too many colors and does not match the colors in the Target sprite. Here I have chosen Wall1 backdrop.

_images/14_shooting06.png

4. Script the Crosshair sprite

Set the random position and size of the Crosshair sprite, and let it move randomly.

_images/14_shooting4.png

When a hand is placed in front of the obstacle avoidance module, it will output a low level as a transmit signal.

_images/14_shooting5.png

When the shooting message is received, the sprite stops moving and slowly shrinks, thus simulating the effect of a bullet being shot.

_images/14_shooting6.png

Use the [Touch color ()] block to determine the position of the shot.

_images/14_shooting7.png

When the shot is inside the yellow circle, 10 is reported.

_images/14_shooting8.png

Use the same method to determine the position of the bullet shot, if it is not set on the Target sprite, it means it is out of the circle.

_images/14_shooting9.png

2.12 GAME - Inflating the Balloon

Here, we will play a game of ballooning.

After clicking the green flag, the balloon will become bigger and bigger. If the balloon is too big, it will be blown up; if the balloon is too small, it will fall down; you need to judge when to press the button to make it fly upwards.

_images/13_balloon0.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Button

BUY

You Will Learn

  • Paint costume for the sprite

Build the Circuit

The button is a 4-pin device, since the pin 1 is connected to pin 2, and pin 3 to pin 4, when the button is pressed, the 4 pins are connected, thus closing the circuit.

_images/5_buttonc.png

Build the circuit according to the following diagram.

  • Connect one of the pins on the left side of the button to pin14, which is connected to a pull-down resistor and a 0.1uF (104) capacitor (to eliminate jitter and output a stable level when the button is working).

  • Connect the other end of the resistor and capacitor to GND, and one of the pins on the right side of the button to 5V.

_images/6_doorbel_bb.png

Programming

1. Add a sprite and a backdrop

Delete the default sprite, click the Choose a Sprite button in the lower right corner of the sprite area, then select the Balloon1 sprite.

_images/13_balloon1.png

Add a Boardwalk backdrop via the Choose a backdrop button, or other backbackdrops you like.

_images/13_balloon2.png

2. Paint a costume for the Balloon1 sprite

Now let’s draw an exploding effect costume for the balloon sprite.

Go to the Costumes page for the Balloon1 sprite, click the Choose a Costume button in the bottom left corner, and select Paint to bring up a blank Costume.

_images/13_balloon7.png

Select a color and then use the Brush tool to draw a pattern.

_images/13_balloon3.png

Select a color again, click the Fill tool, and move the mouse inside the pattern to fill it with a color.

_images/13_balloon4.png

Finally, write the text BOOM, so that an explosion effect costume is complete.

_images/13_balloon5.png

3. Scripting the Balloon sprite

Set the initial position and size of the Balloon1 sprite.

_images/13_balloon6.png

Then let the Balloon sprite slowly get bigger.

_images/13_balloon8.png

When the button is pressed (value is 1), the size of the Balloon1 sprite stops getting bigger.

  • When the size is less than 90, it will fall (y coordinate decreases).

  • When the size is bigger than 90 and smaller than 120, it will fly to the sky (y coordinate increases).

_images/13_balloon9.png

If the button has not been pressed, the balloon slowly gets bigger and when the size is bigger than 120, it will explode (switch to the explode effect costume).

_images/13_balloon10.png

2.13 GAME - Star-Crossed

In the next projects, we will play some fun mini-games in PictoBlox.

Here we use Joystick module to play a Star-Crossed game.

After the script is run, stars will appear randomly on the stage, you need to use Joystick to control Rocketship to avoid the stars, if you touch it, the game will be over.

_images/16_rocket.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Joystick Module

BUY

You Will Learn

  • How Joystick module works

  • Set the x and y coordinates of the sprite

Build the Circuit

A joystick is an input device consisting of a stick that pivots on a base and reports its angle or direction to the device it is controlling. Joysticks are often used to control video games and robots.

In order to communicate a full range of motion to the computer, a joystick needs to measure the stick’s position on two axes - the X-axis (left to right) and the Y-axis (up and down).

The motion coordinates of the joystick are shown in the following figure.

Note

  • The x coordinate is from left to right, the range is 0-4095.

  • y coordinate is from top to bottom, range is 0-4095.

_images/16_joystick.png

Now build the circuit according to the following diagram.

_images/14_star_crossed_bb.png

Programming

The whole script is to achieve the effect that when the green flag is clicked, the Stars sprite moves in a curve on the stage and you need to use the joystick to move the Rocketship, so that it will not be touched by the Star sprite.

1. Add sprites and backdrops

Delete the default sprite, and use the Choose a Sprite button to add the Rocketship sprite and the Star sprite. Note that the Rocket sprite size is set to 50%.

_images/16_sprite.png

Now add the Stars backdrop by Choose a Backdrop.

_images/16_sprite1.png

2. Scripting for Rocketship

The Rocketship sprite is to achieve the effect that it will appear at a random position and then be controlled by the joystick to move it up, down, left, and right.

The workflow is as follows.

  • When the green flag is clicked, have the sprite go to a random location and create 2 variables x and y, which store the values read from pin33 (VRX of Joystick) and pin35 (VRY of Joystick), respectively. You can let the script run, toggling the joystick up and down, left and right, to see the range of values for x and y.

_images/16_roc2.png
  • The value of pin33 is in the range 0-4095 (the middle is about 1800). Use x-1800>200 to determine if Joystick is toggling to the right, and if so, make the x coordinate of the sprite +30 (to move the sprite to the right).

_images/16_roc3.png
  • If the Joystick is toggled to the left, let the x coordinate of the sprite be -30 (let the sprite move to the left).

_images/16_roc4.png
  • Since the Joystick’s y coordinate is from up (0) to down (4095), and the sprite’s y coordinate is from down to up. So in order to move the Joystick upwards and the sprite upwards, the y-coordinate must be -30 in the script.

_images/16_roc5.png
  • If the joystick is flicked down, the y-coordinate of the sprite is +30.

_images/16_roc6.png

3. Scripting for Star

The effect to be achieved by the Star sprite is to appear at a random location, and if it hits Rocketship, the script stops running and the game ends.

  • When the green flag is clicked and the sprite goes to a random location, the [turn degrees] block is to make the Star sprite move forward with a bit of an angle change so you can see that it is moving in a curve and if on edge, bounce.

_images/16_star1.png
  • If the sprite touches the Rocketship sprite while it’s moving, stop the script from running.

_images/16_star2.png

2.14 GAME - Eat Apple

In this project, we play a game that uses button to control Beetle to eat apple.

When the green flag is clicked, press the button and Beetle will rotate, press the button again and Beetle stops running and goes forward at that angle. You need to control the angle of Beetle so that it moves forward without touching the black line on the map until it eats the apple. If it touches the black line, the game is over.

_images/14_apple.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Button

BUY

Build the Circuit

The button is a 4-pin device, since the pin 1 is connected to pin 2, and pin 3 to pin 4, when the button is pressed, the 4 pins are connected, thus closing the circuit.

_images/5_buttonc.png

Build the circuit according to the following diagram.

  • Connect one of the pins on the left side of the button to pin14, which is connected to a pull-down resistor and a 0.1uF (104) capacitor (to eliminate jitter and output a stable level when the button is working).

  • Connect the other end of the resistor and capacitor to GND, and one of the pins on the right side of the button to 5V.

_images/6_doorbel_bb.png

Programming

The effect we want to achieve is to use the button to control the direction of the Beetle sprite to move forward and eat the apple without touching the black line on the Maze backdrop, which will switch the backdrop when eaten.

Now add the relevant backdrops and sprites.

1. Adding backdrops and sprites

Add a Maze backdrop via the Choose a backdrop button.

_images/14_backdrop.png

Delete the default sprite, then select the Beetle sprite.

_images/14_sprite.png

Place the Beetle sprite at the entrance of the Maze backdrop, remembering the x,y coordinate values at this point, and resize the sprite to 40%.

_images/14_sprite1.png

2. Draw a backdrop

Now it’s time to simply draw a backdrop with the WIN! character appearing on it.

First click on the backdrop thumbnail to go to the Backdrops page and click on the blank backdrop1.

_images/14_paint_back.png

Now start drawing, you can refer to the picture below to draw, or you can draw a backdrop on your own, as long as the expression is winning.

  • Using the Circle tool, draw an ellipse with the color set to red and no outline.

  • Then use the Text tool, write the character "WIN!", set the character color to black, and adjust the size and position of the character.

  • Name the backdrop as Win.

_images/14_win.png

3. Scripting for the backdrop

The backdrop needs to be switched to Maze every time the game starts.

_images/14_switchback.png

4. Writing scripts for the sprite Beetle

Now write a script for the sprite Beetle to be able to move forward and turn direction under the control of a button. The workflow is as follows.

  • When the green flag is clicked, set the Beetle angle to 90, and the position to (-134, -134), or replace it with the coordinate value of your own placed position. Create the variable flag and set the initial value to -1.

_images/14_bee1.png

Next, in the [forever] block, four [if] blocks are used to determine various possible scenarios.

  • If the button is 1 (pressed), use the [mod] block to toggle the value of the variable flag between 0 and 1 (alternating between 0 for this press and 1 for the next press).

_images/14_bee2.png
  • If flag=0 (this button press), let the Beetle sprite turn clockwise. Then determine if flag is equal to 1 (button pressed again), the Beetle sprite moves forward. Otherwise, it keeps turning clockwise.

_images/14_bee3.png
  • If the Beetle sprite touches black (the black line on the Maze backdrop), the game ends and the script stops running.

Note

You need to click on the color area in the [Touch color] block, and then select the eyedropper tool to pick up the color of the black line on the stage. If you choose a black arbitrarily, this [Touch color] block will not work.

_images/14_bee5.png
  • If Beetle touches red (Also use the straw tool to pick up the red color of the apple), the backdrop will be switched to Win, which means the game succeeds and stops the script from running.

_images/14_bee4.png

2.15 GAME - Flappy Parrot

Here we use the ultrasonic module to play a flappy parrot game.

After the script runs, the green bamboo will slowly move from the right to the left at a random height. Now place your hand on top of the ultrasonic module, if the distance between your hand and the ultrasonic module is less than 10, the parrot will fly upwards, otherwise it will fall downwards. You need to control the distance between your hand and the ultrasonic module so that the Parrot can avoid the green bamboo (Paddle), if it touches it, the game is over.

_images/15_parrot.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Ultrasonic Module

BUY

Build the Circuit

An ultrasonic sensor module is an instrument that measures the distance to an object using ultrasonic sound waves. It has two probes. One is to send ultrasonic waves and the other is to receive the waves and transform the time of sending and receiving into a distance, thus detecting the distance between the device and an obstacle.

Now build the circuit according to the following diagram.

_images/16_flappy_parrot_bb.png

Programming

The effect we want to achieve is to use the ultrasonic module to control the flight height of the sprite Parrot, while avoiding the Paddle sprite.

1. Add a sprite

Delete the default sprite, and use the Choose a Sprite button to add the Parrot sprite. Set its size to 50%, and move its position to the left center.

_images/15_sprite.png

Now add the Paddle sprite, set its size to 150%, set its angle to 180, and move its initial position to the top right corner.

_images/15_sprite1.png

Go to the Costumes page of the Paddle sprite and remove the Outline.

_images/15_sprite2.png

2. Scripting for the Parrot Sprite

Now script the Parrot sprite, which is in flight and the flight altitude is determined by the detection distance of the ultrasonic module.

  • When the green flag is clicked, switch the costume every 0.2s so that it is always in flight.

_images/15_parr1.png
  • Read the value of the ultrasonic module and store it in the variable distance after rounding it with the [round] block.

_images/15_parr2.png
  • If the ultrasonic detection distance is less than 10cm, let the y coordinate increase by 50, the Parrot sprite will fly upwards. Otherwise, the y-coordinate value is decreased by 40, Parrot will fall down.

_images/15_parr3.png
  • If the Parrot sprite touches the Paddle sprite, the game ends and the script stops running.

_images/15_parr4.png

3. Scripting for the Paddle sprite

Now write the script for the Paddle sprite, which needs to appear randomly on the stage.

  • Hide the sprite Paddle when the green flag is clicked, and clone itself at the same time. The [create clone of] block is a control block and a stack block. It creates a clone of the sprite in the argument. It can also clone the sprite it is running in, creating clones of clones, recursively.

_images/15_padd.png
  • When Paddle is presented as a clone, its position is 220 (rightmost) for the x-coordinate and its y-coordinate at (-125 to 125) random (height random).

_images/15_padd1.png
  • Use the [repeat] block to make its x coordinate value slowly decrease, so you can see the clone of the Paddle sprite slowly move from the right to the left until it disappears.

_images/15_padd2.png
  • Re-clone a new Paddle sprite and delete the previous clone.

_images/15_padd3.png

2.16 GAME - Breakout Clone

Here we use the potentiometer to play a Breakout Clone game.

After clicking the green flag, you need to use the potentiometer to control the paddle on the stage to catch the ball so that it can go up and hit the bricks, all the bricks disappear then the game is won, if you don’t catch the ball, the game is lost.

_images/17_brick.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Potentiometer

BUY

Build the Circuit

The potentiometer is a resistive element with 3 terminals, the 2 side pins are connected to 5V and GND, and the middle pin is connected to pin35. After the conversion by the ADC converter of the esp32 board, the value range is 0-4095.

_images/5_moving_mouse_bb.png

Programming

There are 3 sprites on the stage.

1. Paddle sprite

The effect to be achieved by the Paddle is that the initial position is in the middle of the bottom of the stage, and it is controlled by a potentiometer to move it to the left or to the right.

  • Delete the default sprite, use the Choose a Sprite button to add the Paddle sprite, and set its x and y to (0, -140).

    _images/17_padd1.png
  • Go to the Costumes page, remove the Outline and change its color to dark gray.

    _images/17_padd3.png
  • Now script the Paddle sprite to set its initial position to (0, -140) when the green flag is clicked, and read the value of pin35 (potentiometer) into the variable a0. Since the Paddle sprite moves from left to right on the stage at x-coordinates -195~195, you need to use the [map] block to map the variable a0 range 0~4095 to -195~195.

    _images/17_padd2.png
  • Now you can rotate the potentiometer to see if the Paddle can move left and right on the stage.

2. Ball sprite

The effect of the ball sprite is that it moves around the stage and bounces when it touches the edge; it bounces down if it touches the block above the stage; it bounces up if it touches the Paddle sprite during its fall; if it doesn’t, the script stops running and the game ends.

  • Add Ball sprite.

    _images/17_ball1.png
  • When the green flag is clicked, set the angle of the Ball sprite to 45° and set the initial position to (0, -120).

    _images/17_ball2.png
  • Now let the Ball sprite move around the stage and bounce when it touches the edge, and you can click on the green flag to see the effect.

    _images/17_ball3.png
  • When the Ball sprite touches the Paddle sprite, do a reflection. The easy way to do this is to let the angle be directly inverted, but then you’ll find that the path of the ball is completely fixed, which is too boring. Therefore, we use the center of the two sprites to calculate and make the ball bounce in the opposite direction of the center of the baffle.

    _images/17_ball4.png _images/17_ball6.png
  • When the Ball sprite falls to the edge of the stage, the script stops running and the game ends.

    _images/17_ball5.png

3. Block1 sprite

The Block1 sprite is to appear with the effect of cloning 4x8 of itself above the stage in a random color, and deleting a clone if it is touched by the Ball sprite.

The Block1 sprite is not available in the PictoBlox library, you need to draw it yourself or modify it with an existing sprite. Here we are going to modify it with the Button3 sprite.

  • After adding the Button3 sprite, go to the Costumes page. Now delete button-a first, then reduce both the width and height of button-b, and change the sprite name to Block1, as shown in the following image.

    Note

    • For the width of Block1, you can probably simulate it on the screen to see if you can put down 8 in a row, if not, then reduce the width appropriately.

    • In the process of shrinking the Block1 sprite, you need to keep the center point in the middle of the sprite.

    _images/17_bri2.png
  • Now create 2 variables first, block to store the number of blocks and roll to store the number of rows.

    _images/17_bri3.png
  • We need to make a clone of the Block1 sprite, so that it displays from left to right, top to bottom, one by one, 4x8 in total, with random colors.

    _images/17_bri4.png
  • After the script is written, click on the green flag and look at the display on the stage, if it is too compact or too small, you can change the size.

    _images/17_bri5.png
  • Now write the trigger event. If the cloned Block1 sprite touches the Ball sprite, delete the clone and broadcast the message crush.

    _images/17_bri6.png
  • Back to the Ball sprite, when the broadcast crush is received (the Ball sprite touches the clone of Block1 sprite), the Ball is popped from the opposite direction.

    _images/17_ball7.png

2.17 GAME - Fishing

Here, we play a fishing game with a button.

When the script is running, the fish swim left and right on the stage, you need to press the button when the fish is almost close to the hook (it is recommended to press it for a longer time) to catch the fish, and the number of fish caught will be recorded automatically.

_images/18_fish.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Resistor

BUY

Button

BUY

Build the Circuit

The button is a 4-pin device, since the pin 1 is connected to pin 2, and pin 3 to pin 4, when the button is pressed, the 4 pins are connected, thus closing the circuit.

_images/5_buttonc.png

Build the circuit according to the following diagram.

  • Connect one of the pins on the left side of the button to pin14, which is connected to a pull-down resistor and a 0.1uF (104) capacitor (to eliminate jitter and output a stable level when the button is working).

  • Connect the other end of the resistor and capacitor to GND, and one of the pins on the right side of the button to 5V.

_images/6_doorbel_bb.png

Programming

We need to select an Underwater backdrop first, then add a Fish sprite and let it swim back and forth on the stage. Then draw a Fishhook sprite and control it by a button to start fishing. When the Fish sprite touches the Fishhook sprite in the hooked state (turns red), it will be hooked.

1. Adding a backdrop

Use the Choose a Backdrop button to add an Underwater backdrop.

_images/18_under.png

2. Fishhook sprite

The Fishhook sprite usually stays underwater in the yellow state; when the button is pressed, it is in the fishing state (red) and moves above the stage.

There is no Fishhook sprite in Pictoblox, we can modify the Glow-J sprite to look like a fishhook.

  • Add the Glow-J sprite via Choose a Sprite.

_images/18_hook.png
  • Now go to the Costumes page of the Glow-J sprite, select Cyan’s fill in the screen and remove it. Then change the J color to red and also reduce its width. The most important point to note is that you need to have the top of it just at the center point.

_images/18_hook1.png
  • Use the Line tool to draw a line as long as possible from the center point up (line out of the stage). Now that the sprite is drawn, set the sprite name to Fishhook and move it to the right position.

_images/18_hook2.png
  • When the green flag is clicked, set the sprite’s color effect to 30 (yellow), and set its initial position.

_images/18_hook3.png
  • If the button is pressed, set the color effect to 0 (red, start fishing state), wait for 0.1 and then move the Fishhook sprite to the top of the stage. Release the button and let the Fishhook return to its initial position.

_images/18_hook4.png

3. Fish sprite

The effect to be achieved by the Fish sprite is to move left and right on the stage, and when it encounters a Fishhook sprite in the fishing state, it shrinks and moves to a specific position and then disappears, and then clones a new fish sprite again.

  • Now add the fish sprite and adjust its size and position.

_images/18_fish1.png
  • Create a variable score to store the number of fish caught, hide this sprite and clone it.

_images/18_fish2.png
  • Show the clone of the fish sprite, switch its costume and finally set the initial position.

_images/18_fish3.png
  • Make the fish sprite’s clone move left and right and bounce back when it touches the edge.

_images/18_fish4.png
  • The fish sprite (of the clone) will not react when it passes the Fishhook sprite; when it touches the Fishhook sprite in the fishing state (turns red), it will be caught, at which point the score (variable score) +1, and it will also show a score animation (shrinks 40%, quickly moves to the position of the scoreboard and disappears). At the same time, a new fish is created (a new fish sprite clone) and the game continues.

Note

You need to click on the color area in the [Touch color] block, and then select the eyedropper tool to pick up the red color of the Fishhook sprite on the stage. If you choose a color arbitrarily, this [Touch color] block will not work.

_images/18_fish5.png

2.18 GAME - Don’t Tap on The White Tile

I’m sure many of you have played this game on your cell phones. This game is played by tapping on randomly appearing black to add points, the speed will get faster and faster, tap on white blocks or miss black blocks game over.

Now we use PictoBlox to replicate it.

Insert two IR obstacle avoidance modules vertically on the breadboard, when your hand is placed above one of the IR modules, a blink dot will appear on the stage, representing a tap was made.

If the tap to the black block, the score plus 1, touch the white block, the score minus 1.

You need to decide whether to place your hand on top of the IR module on the left or on top of the IR module on the right, depending on the position of the black block on the stage.

_images/21_tile.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Breadboard

BUY

Jumper Wires

BUY

Obstacle Avoidance Module

BUY

Build the Circuit

The obstacle avoidance module is a distance-adjustable infrared proximity sensor whose output is normally high and low when an obstacle is detected.

Now build the circuit according to the diagram below.

_images/19_tap_tile_bb.png

Programming

Here we need to have 3 sprites, Tile , Left IR and Right IR.

  • Tile sprite: used to achieve the effect of alternating black and white tiles downward, in the cell phone this game is generally 4 columns, here we only do two columns.

  • Left IR sprite: used to achieve the click effect, when the left IR module senses your hand, it will send a message - left to Left IR sprite, let it start working. If it touches the black tile on the stage, the score will be increased by 1, otherwise the score will be decreased by 1.

  • Right IR sprite: The function is basically the same as Left IR, except that it receives Right information.

1. Paint a Tile sprite.

Delete the default sprite, mouse over the Add Sprite icon, select Paint and a blank sprite will appear and name it Tile.

_images/21_tile1.png

Go to the Costumes page and use the Rectangle tool to draw a rectangle.

_images/21_tile2.png

Select the rectangle and click Copy -> Paste to make an identical rectangle, then move the two rectangles to a flush position.

_images/21_tile01.png

Select one of the rectangles and choose a fill color of black.

_images/21_tile02.png

Now select both rectangles and move them so that their center points match the center of the canvas.

_images/21_tile0.png

Duplicate costume1, alternating the fill colors of the two rectangles. For example, the fill color of costume1 is white on the left and black on the right, and the fill color of costume2 is black on the left and white on the right.

_images/21_tile3.png

2. Scripting the Tile sprite

Now go back to the Blocks page and set the initial position of the Tile sprite so that it is at the top of the stage.

_images/21_tile4.png

Create a variable -blocks and give it an initial value to determine the number of times the Tile sprite will appear. Use the [repeat until] block to make the variable blocks gradually decrease until blocks is 0. During this time, have the sprite Tile randomly switch its costume.

After clicking on the green flag, you will see the Tile sprite on the stage quickly switch costumes.

_images/21_tile5.png

Create clones of the Tile sprite while the variable blocks is decreasing, and stop the script from running when blocks is 0. Two [wait () seconds] blocks are used here, the first to limit the interval between Tile’s clones and the second is to let the variable blocks decrease to 0 without stopping the program immediately, giving the last tile sprite enough time to move.

_images/21_tile6.png

Now script the clone of the Tile sprite to move down slowly and delete it when it reaches the bottom of the stage. The change in the y coordinate affects the drop speed, the larger the value, the faster the drop speed.

_images/21_tile7.png

Hide the body and show the clone.

_images/21_tile8.png

3. Read the values of the 2 IR modules

In the backdrop, read the values of the 2 IR modules and make the corresponding actions.

  • If the left IR obstacle avoidance module senses your hand, broadcast a message - left.

  • If the left IR avoidance module senses your hand, broadcast a message - right.

_images/21_tile9.png

4. Left IR sprite

Again, mouse over the Add sprite icon and select Paint to create a new sprite called Left IR.

_images/21_tile10.png

Go to the Costumes page of the Left IR sprite, select the fill color (any color out of black and white) and draw a circle.

_images/21_tile11.png

Now start scripting the Left IR sprite. When the message - left is received (the IR receiver module on the left detects an obstacle), then determine if the black block of the Tile sprite is touched, and if it is, let the variable count add 1, otherwise subtract 1.

_images/21_tile12.png

Note

You need to make the Tile sprite appear on the stage, and then absorb the color of the black block in the Tile sprite.

_images/21_tile13.png

Now let’s do the sensing effect (zoom in and out) for Left IR.

_images/21_tile14.png

Make the Left IR sprite hide when the green flag is clicked, show when the message - left is received, and finally hide again.

_images/21_tile15.png

5. Right IR sprite

Copy the Left IR sprite and rename it to Right IR.

_images/21_tile16.png

Then change the receive message to - right.

_images/21_tile17.png

Now all the scripting is done and you can click on the green flag to run the script.

2.19 GAME - Protect Your Heart

In this project, let’s make a game that tests reaction speed.

In the stage, there is a heart protected in a rectangular box, and there are arrows flying towards this heart from any position on the stage. The color of the arrow will alternate between black and white at random and the arrow will fly faster and faster.

If the color of the rectangular box and the arrow color are the same, the arrow is blocked outside and level is added 1; if the color of both is not the same, the arrow will shoot through the heart and the game is over.

Here the color of the rectangle box is controlled by the Line Tracking module. When the module is placed on a black surface (a surface that is reflective), the color of the rectangle box is black, otherwise it is white.

So you need to decide whether to put the Line Tracking module on a white surface or a black surface according to the arrow color.

_images/22_heart.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Line Tracking Module

BUY

Build the Circuit

This is a digital Line Tracking module, when a black line is detected, it outputs 1; when a white line is detected, it outputs a value of 0. In addition, you can adjust its sensing distance through the potentiometer on the module.

Now build the circuit according to the diagram below.

_images/20_protect_heart_bb.png

Note

Before starting the project, you need to adjust the sensitivity of the module.

Wiring according to the above diagram, then power up the R3 board (either directly into the USB cable or the 9V battery button cable), without uploading the code.

Now stick a black electrical tape on the desktop, put the Line Track module at a height of 2cm from the desktop.

With the sensor facing down, observe the signal LED on the module to make sure it lights up on the white table and goes off on the black tape.

If not, you need to adjust the potentiometer on the module, so that it can do the above effect.

Programming

Here we need to create 3 sprites, Heart, Square Box and Arrow1.

  • Heart: stops in the middle of the stage, if touched by Arrow1 sprite, the game is over.

  • Square Box: There are two types of costumes, black and white, and will switch costumes according to the value of Line Tracking module.

  • Arrow: flies towards the middle of the stage from any position in black/white; if its color matches the color of the Square Box sprite, it is blocked and re-flies towards the middle of the stage from a random position; if its color does not match the color of the Square Box sprite, it passes through the Heart sprite and the game is over.

1. Add Square Box sprite

Since the Arrow1 and Square Box sprite both have white costumes, in order for them to be displayed on the stage, now fill the background with a color that can be any color except black, white, and red.

  • Click on Backdrop1 to go to its Backdrops page.

  • Select the color you want to fill.

  • Use the Rectangle tool to draw a rectangle the same size as the drawing board.

_images/22_heart0.png

Delete the default sprite, use the Choose a Sprite button to add the Square Box sprite, and set its x and y to (0, 0).

_images/22_heart1.png

Go to the Square Box sprite’s Costumes page and set the black and white costumes.

  • Click the selection tool

  • Select the rectangle on the canvas

  • Select the fill color as black

  • and name the costume Black

_images/22_heart2.png

Select the second costume, set the fill color to white, name it White, and delete the rest of the costume.

_images/22_heart3.png

2. Add Heart sprite

Also add a Heart sprite, set its position to (0, 0), and shrink its size so that it appears to be located inside the Square Box.

_images/22_heart5.png

On the Costumes page, adjust the heart purple costume so that it appears to be broken.

_images/22_heart6.png

3. Add Arrow1 sprite

Add an Arrow1 sprite.

_images/22_heart7.png

On the Costumes page, keep and copy the rightward facing costume and set its color to black and white.

_images/22_heart8.png

4. Scripting for Square Box sprite

Go back to the Blocks page and script Square Box sprite.

  • So when the value of the digital pin 2 (Line Following module) is 1 (black line detected), then switch the costume to Black.

  • Otherwise toggle the costume to White.

_images/22_heart4.png

5. Scripting for Heart sprite

Heart sprite is protected inside Square Box, and by default is a red costume. When the Arrow1 sprite is touched, the game ends.

_images/22_heart9.png

6. Scripting for Arrow1 sprite

Make the Arrow1 sprite hide and create a clone when the green flag is clicked.

_images/22_heart10.png

Create an [init] block to initialize the Arrow1 sprite’s position, orientation and color.

It appears at a random location, and if the distance between it and the Heart sprite is less than 200, it moves outward until the distance is greater than 200.

_images/22_heart11.png

Set its direction to face the Heart sprite.

_images/22_heart12.png

Make its color alternate randomly between black/white.

  • Variable color is 0, toggle costume to White.

  • Variable color is 1, toggles the outfit to Black.

_images/22_heart14.png

Now let it start moving, it will move faster as the value of the variable level increases.

_images/22_heart13.png

Now set its collision effect with the Square Box sprite.

  • If the Arrow1 sprite and the Square Box sprite have the same color (which will be modified according to the value of the Line Track module), either black or white, a new clone is created and the game continues.

  • If their colors do not match, the Arrow1 sprite continues to move and the game ends when it hits the Heart sprite.

_images/22_heart15.png

Note

The two [touch color()] blocks need to pick up the black/white costumes of Square Box separately.

_images/22_heart16.png

2.20 GAME - Kill Dragon

Here, we use the joystick to play a game of dragon killing.

When clicking on green, the dragon will float up and down on the right side and blow fire intermittently. You need to use the joystick to control the movement of the magic wand and launch star attacks at the dragon, while avoiding the flames it shoots, and finally defeat it.

_images/19_dragon.png

Required Components

In this project, we need the following components.

It’s definitely convenient to buy a whole kit, here’s the link:

Name

ITEMS IN THIS KIT

LINK

ESP32 Starter Kit

320+

ESP32 Starter Kit

You can also buy them separately from the links below.

COMPONENT INTRODUCTION

PURCHASE LINK

ESP32 WROOM 32E

BUY

ESP32 Camera Extension

-

Jumper Wires

BUY

Joystick Module

BUY

Build the Circuit

A joystick is an input device consisting of a stick that pivots on a base and reports its angle or direction to the device it is controlling. Joysticks are often used to control video games and robots.

In order to communicate a full range of motion to the computer, a joystick needs to measure the stick’s position on two axes - the X-axis (left to right) and the Y-axis (up and down).

The motion coordinates of the joystick are shown in the following figure.

Note

  • The x coordinate is from left to right, the range is 0-1023.

  • y coordinate is from top to bottom, range is 0-1023.

_images/16_joystick.png

Now build the circuit according to the following diagram.

_images/14_star_crossed_bb.png

Programming

1. Dragon

Woods backdrop added via the Choose a Backdrop button.

_images/19_dragon01.png
  • Delete the default sprite and add the Dragon sprite.

_images/19_dragon0.png
  • Go to the Costumes page and flip the dragon-b and dragon-c horizontally.

_images/19_dragon1.png
  • Set the size to 50%.

_images/19_dragon3.png
  • Now create a variable - dragon to record the dragon’s life points, and set the initial value to 50.

_images/19_dragon2.png
  • Next, switch the sprite costume to dragon-b and have the Dragon sprite up and down in a range.

_images/19_dragon4.png
  • Add a Lightning sprite as the fire blown by the Dragon sprite. You need to rotate it 90° clockwise in the Costumes page, this is to make the Lightning sprite move in the right direction.

Note

When adjusting the Lightning sprite’s costume, you may move it off-center, which must be avoided! The center point must be right in the middle of the sprite!

_images/19_lightning1.png
  • Then adjust the dragon-c costume of the Dragon sprite so that its center point should be at the tail of the fire. This will make the positions of the Dragon sprite and the Lightning sprite correct, and prevent Lightning from launching from the dragon’s feet.

_images/19_dragon5.png
  • Correspondingly, dragon-b needs to make the head of the dragon coincide with the center point.

_images/19_dragon5.png
  • Adjust the size and orientation of the Lightning sprite to make the image look more harmonious.

_images/19_lightning3.png
  • Now script the Lightning sprite. This is easy, just have it follow the Dragon sprite all the time. At this point, click on the green flag and you will see Dragon moving around with lightning in its mouth.

_images/19_lightning4.png
  • Back to the Dragon sprite, now have it blow out fire, being careful not to let the fire in its mouth shoot out, but to create a clone for the Lightning sprite.

_images/19_dragon6.png
  • Click on the Lightning sprite and let the Lightning clone shoot out at a random angle, it will bounce off the wall and disappear after a certain amount of time.

_images/19_lightning5.png
  • In the Lightning sprite, hide its body and show the clone.

_images/19_lightning6.png

Now the dragon can move up and down and blow out fire.

2.Wand

  • Create a Wand sprite and rotate its direction to 180 to point to the right.

_images/19_wand1.png
  • Now create a variable hp to record its life value, initially set to 3. Then read the Joystick’s value, which is used to control the wand’s movement.

_images/19_wand2.png
  • The dragon has lightning, and the wand that crushes it has its “magic bullet”! Create a Star sprite, resize it, and script it to always follow the Wand sprite, and limit the number of stars to three.

_images/19_star2.png
  • Make the Wand sprite shoot stars automatically. The Wand sprite shoots stars the same way the dragon blows fire – by creating clones.

_images/19_wand3.png
  • Go back to the Star sprite and script its clone to spin and shoot to the right, disappear after going beyond the stage and restoring the number of stars. Same as Lightning sprite, hide the body and show the clone.

_images/19_star3.png

Now we have a wand that shoots star bullets.

3. Fight!

The wand and the dragon are currently still at odds with each other, and we’re going to make them fight. The dragon is strong, and the wand is the brave man who crusades against the dragon. The interaction between them consists of the following parts.

  1. if the wand touches the dragon, it will be knocked back and lose life points.

  2. if lightning strikes the wand, the wand will lose life points.

  3. if the star bullet hits the dragon, the dragon will lose life points.

Once that’s sorted out, let’s move on to changing the scripts for each sprite.

  • If the Wand hits the Dragon, it will be knocked back and lose life points.

_images/19_wand4.png
  • If Lightning (a Lightning sprite clone) hits the Wand sprite, it will make a pop sound and disappear, and the Wand will lose life points.

_images/19_lightning7.png
  • If a Star (clone of the Star sprite) hits the Dragon, it will emit a collect sound and disappear, while restoring the Star count, and the Dragon will lose life points.

_images/19_star4.png

4. stage

The battle between the Wand and the Dragon will eventually be divided into winners and losers, which we represent with the stage.

  • Add Blue Sky backgdrop, and write the character “WIN!” on it to represent that the dragon has been defeated and the dawn has come.

_images/19_sky0.png
  • And modify the blank backdrop as follows, to represent that the game has failed and everything will be in darkness.

_images/19_night.png
  • Now write a script to switch these backgdrops, when the green flag is clicked, switch to Woods backgdrop; if the dragon’s life point is less than 1 , then the game succeeds and switch the backdrop to Blue Sky; if the life value point of the Wand is less than 1, then switch to Night backdrop and the game fails.

_images/19_sky1.png

Learn about the Components in Your Kit

After opening the package, please check whether the quantity of components is compliance with product description and whether all components are in good condition.

_images/components_list.jpg

Below is the introduction to each component, which contains the operating principle of the component and the corresponding projects.

Control Board

ESP32 WROOM 32E

The ESP32 WROOM-32E is a versatile and powerful module built around Espressif’s ESP32 chipset. It offers dual-core processing, integrated Wi-Fi and Bluetooth connectivity, and boasts a wide range of peripheral interfaces. Known for its low-power consumption, the module is ideal for IoT applications, enabling smart connectivity and robust performance in compact form factors.

_images/esp32_wroom_32e.jpg

Key features include:

  • Processing Power: It’s equipped with a dual-core Xtensa® 32-bit LX6 microprocessor, offering scalability and flexibility.

  • Wireless Capabilities: With integrated 2.4 GHz Wi-Fi and dual-mode Bluetooth, it’s perfectly suited for applications demanding stable wireless communication.

  • Memory & Storage: It comes with ample SRAM and high-performance flash storage, catering to user programs and data storage needs.

  • GPIO: Offering up to 38 GPIO pins, it supports a variety of external devices and sensors.

  • Low Power Consumption: Multiple power-saving modes are available, making it ideal for battery-powered or energy-efficient scenarios.

  • Security: Integrated encryption and security features ensure user data and privacy are well-protected.

  • Versatility: From simple household appliances to complex industrial machinery, the WROOM-32E delivers consistent, efficient performance.

In summary, the ESP32 WROOM-32E not only offers robust processing capabilities and diverse connectivity options but also boasts an array of features making it a preferred choice in the IoT and smart device sectors.

Pinout Diagram

The ESP32 has some pin usage limitations due to various functionalities sharing certain pins. When designing a project, it’s a good practice to carefully plan the pin usage and cross-check for potential conflicts to ensure proper functioning and avoid issues.

_images/esp32_pinout.jpg

Here are some of the key restrictions and considerations:

  • ADC1 and ADC2: ADC2 cannot be used when WiFi or Bluetooth is active. However, ADC1 can be used without any restrictions.

  • Bootstrapping Pins: GPIO0, GPIO2, GPIO5, GPIO12, and GPIO15 are used for bootstrapping during the boot process. Care should be taken not to connect external components that could interfere with the boot process on these pins.

  • JTAG Pins: GPIO12, GPIO13, GPIO14, and GPIO15 can be used as JTAG pins for debugging purposes. If JTAG debugging is not required, these pins can be used as regular GPIOs.

  • Touch Pins: Some pins support touch functionalities. These pins should be used carefully if you intend to use them for touch sensing.

  • Power Pins: Some pins are reserved for power-related functions and should be used accordingly. For example, avoid drawing excessive current from power supply pins like 3V3 and GND.

  • Input-only Pins: Some pins are input-only and should not be used as outputs.

Strapping Pins

ESP32 has five strapping pins:

Strapping Pins

Description

IO5

Defaults to pull-up, the voltage level of IO5 and IO15 affects the Timing of SDIO Slave.

IO0

Defaults to pull-up, if pulled low, it enters download mode.

IO2

Defaults to pull-down, IO0 and IO2 will make ESP32 enter download mode.

IO12(MTDI)

Defaults to pull-down, if pulled high, ESP32 will fail to boot up normally.

IO15(MTDO)

Defaults to pull-up, if pulled low, debug log will not be visible. Additionally, the voltage level of IO5 and IO15 affects the Timing of SDIO Slave.

Software can read the values of these five bits from register “GPIO_STRAPPING”. During the chip’s system reset release (power-on-reset, RTC watchdog reset and brownout reset), the latches of the strapping pins sample the voltage level as strapping bits of “0” or “1”, and hold these bits until the chip is powered down or shut down. The strapping bits configure the device’s boot mode, the operating voltage of VDD_SDIO and other initial system settings.

Each strapping pin is connected to its internal pull-up/pull-down during the chip reset. Consequently, if a strapping pin is unconnected or the connected external circuit is high-impedance, the internal weak pull-up/pull-down will determine the default input level of the strapping pins.

To change the strapping bit values, users can apply the external pull-down/pull-up resistances, or use the host MCU’s GPIOs to control the voltage level of these pins when powering on ESP32.

After reset release, the strapping pins work as normal-function pins. Refer to following table for a detailed boot-mode configuration by strapping pins.

_images/esp32_strapping.png
  • FE: falling-edge, RE: rising-edge

  • Firmware can configure register bits to change the settings of “Voltage of Internal LDO (VDD_SDIO)” and “Timing of SDIO Slave”, after booting.

  • The module integrates a 3.3 V SPI flash, so the pin MTDI cannot be set to 1 when the module is powered up.

ESP32 Camera Extension

We have designed an expansion board that enables you to fully utilize the camera and SD card functionalities of the ESP32 WROOM 32E. By combining the OV2640 camera, Micro SD, and ESP32 WROOM 32E, you get an all-in-one expansion board.

The board provides two types of GPIO headers - one with female headers, perfect for quick prototyping projects. The other type features screw terminals, ensuring stable wire connections and making it suitable for IoT projects.

Additionally, you can power your project using a single 3.7V 18650 battery. If the battery runs low, you can conveniently charge it by simply plugging in a 5V Micro USB cable. This makes it a great tool for outdoor projects and remote applications.

_images/esp32_camera_extension.jpg

Interface Introduction

_images/esp32_camera_extension_pinout.jpg
  • Power Switch
    • Controls the battery’s power supply, toggling it on and off.

  • Charging Port
    • Upon connecting a 5V Micro USB cable, the battery can be charged.

  • Battery Port
    • Features a PH2.0-2P interface, compatible with 3.7V 18650 lithium batterry.

    • Provides power to both the ESP32 WROOM 32E and ESP32 Camera Extension.

  • ESP32 Pin Headers
    • Intended for the ESP32 WROOM 32E module. Pay close attention to its orientation; ensure both Micro USB ports face the same side to avoid incorrect placement.

  • GPIO Headers
    • Female Headers: Used to connect various components to the ESP32, perfect for quick prototyping projects.

    • Screw Terminal: 3.5mm pitch 14pin screw terminal, ensuring stable wire connections and making it suitable for IoT projects.

  • Indicator Lights
    • PWR: Lights up when the battery is powered or when a Micro USB is directly plugged into the ESP32.

    • CHG: Illuminates upon connecting a Micro USB to the board’s charging port, signifying charging onset. It will turn off once the battery is fully charged.

  • Micro SD Connector
    • Spring-loaded slot for the easy insertion and ejection of Micro SD card.

  • 24-pin 0.5mm FFC / FPC connector
    • Designed for the OV2640 camera, making it suitable for various vision-related projects.

ESP32 Camera Extension Pinout

The ESP32 WROOM 32E’s pinout diagram can be found in Pinout Diagram.

However, when the ESP32 WROOM 32E is inserted into the extension board, some of its pins may also be used to drive the Micro SD card or a camera.

Consequently, pull-up or pull-down resistors have be added to these pins. If you’re using these pins as inputs, it’s crucial to account for these resistors as they can affect input levels.

Here’s the pinout table for the right-side pins:

_images/esp32_extension_pinout1.jpg

Here’s the pinout table for the left-side pins:

_images/esp32_extension_pinout2.jpg

Note

There are some specific constraints:

  • IO33 is connected to a 4.7K pull-up resistor and a filtering capacitor, which prevents it from driving the WS2812 RGB Strip.

Interface Insertion Guide

Upload Code

When you need to upload code to the ESP32 WROOM 32E, connect it to your computer using a Micro USB cable.

_images/plugin_esp32.png

Inserting the Micro SD Card

Gently push in the Micro SD card to secure it in place. Pushing it again will eject it.

_images/insert_sd.png

Attaching the Camera

When connecting the camera, ensure the black stripe of the FPC cable is facing upwards and is fully inserted into the connector.

Battery Power and Charging

Carefully insert the battery cable into the battery port, avoiding applying too much force to prevent pushing up the battery terminal. If the terminal is pushed up, it’s okay as long as the pins are not broken; you can simply press it back into position.

_images/plugin_battery.png

If the battery is drained, plug in a 5V Micro USB to charge it.

_images/battery_charge.png

Basic

Breadboard

What is a “solderless” breadboard?

_images/breadboard.png

A breadboard is a rectangular plastic board with many small holes in it. These small holes allow you to easily insert electronic components to build circuits. Technically speaking, these breadboards are known as solderless breadboards because they do not require soldering to make connections.

Features

  • Size: 163 x 54 x 8 mm

  • 830 tie points breadboards: 630 tie-point ic-circuit area plus 2x100 tie-point distribution strips providing 4 power rails.

  • Wire size: Suitable for 20-29 AWG wires.

  • Material: ABS Plastic Panel, Tin Plated Phosphor Bronze Contact Sheet.

  • Voltage / Current: 300V/3-5A.

  • With Self-Adhesive Tape on the Back

What is in the breadboard?

_images/breadboard_internal.png

The inside of the breadboard is made up of rows of small metal clips. When you insert the leads of a component into the holes of the breadboard, one of the clips catches it. Some breadboards are actually made of clear plastic, so you can see the clips inside.

What do the letters and numbers on a breadboard mean?

_images/breadboard_internal2.png

Most breadboards have some numbers, letters and plus and minus signs on them. Although the labels will vary from breadboard to breadboard, the function is basically the same. These labels allow you to find the corresponding holes more quickly when building your circuit.

The row numbers and column letters help you to precisely locate the holes on the breadboard, for example, hole “C12” is where column C intersects row 12.

What do the colored lines and plus and minus signs mean?

_images/breadboard_internal3.png

The sides of the breadboard are usually distinguished by red and blue (or other colors), as well as plus and minus signs, and are usually used to connect to the power supply, known as the power bus.

When building a circuit, it is common to connect the negative terminal to the blue (-) column and the positive terminal to the red (+) column.

How are the holes connected?

_images/breadboard_internal4.png

As shown in the diagram, each set of five holes in the middle section, columns A-E or F-J, is electrically connected. This means, for example, that hole A1 is electrically connected to holes B1, C1, D1 and E1.

It is not connected to hole A2 because that hole is in a different row with a separate set of metal clips. It is also not connected to holes F1, G1, H1, I1 or J1 because they are located in the other “half” of the breadboard - the clips are not connected across the middle gap.

Unlike the middle section, which is grouped by five holes, the buses on sides are electrically connected separately. For example, the column marked blue (-) is electrically connected as a whole, and the column marked red (+) is also electrically connected.

Which electronic parts are compatible with breadboards?

_images/breadboard_pins.jpg

Many electronic components have long metal legs called leads. Almost all components with leads will work with a breadboard. Components such as resistors, capacitors, switches, diodes, etc. can be inserted in any of the rows, but ICs need to be arranged across the middle gap.

Resistor

_images/resistor.png

Resistor is an electronic element that can limit the branch current. A fixed resistor is a kind of resistor whose resistance cannot be changed, while that of a potentiometer or a variable resistor can be adjusted.

Two generally used circuit symbols for resistor. Normally, the resistance is marked on it. So if you see these symbols in a circuit, it stands for a resistor.

_images/resistor_symbol.png

Ω is the unit of resistance and the larger units include KΩ, MΩ, etc. Their relationship can be shown as follows: 1 MΩ=1000 KΩ, 1 KΩ = 1000 Ω. Normally, the value of resistance is marked on it.

When using a resistor, we need to know its resistance first. Here are two methods: you can observe the bands on the resistor, or use a multimeter to measure the resistance. You are recommended to use the first method as it is more convenient and faster.

_images/resistance_card.jpg

As shown in the card, each color stands for a number.

Black

Brown

Red

Orange

Yellow

Green

Blue

Violet

Grey

White

Gold

Silver

0

1

2

3

4

5

6

7

8

9

0.1

0.01

The 4- and 5-band resistors are frequently used, on which there are 4 and 5 chromatic bands.

Normally, when you get a resistor, you may find it hard to decide which end to start for reading the color. The tip is that the gap between the 4th and 5th band will be comparatively larger.

Therefore, you can observe the gap between the two chromatic bands at one end of the resistor; if it’s larger than any other band gaps, then you can read from the opposite side.

Let’s see how to read the resistance value of a 5-band resistor as shown below.

_images/220ohm.jpg

So for this resistor, the resistance should be read from left to right. The value should be in this format: 1st Band 2nd Band 3rd Band x 10^Multiplier (Ω) and the permissible error is ±Tolerance%. So the resistance value of this resistor is 2(red) 2(red) 0(black) x 10^0(black) Ω = 220 Ω, and the permissible error is ± 1% (brown).

You can learn more about resistor from Wiki: Resistor - Wikipedia.

Capacitor

_images/103_capacitor.png _images/10uf_cap.png

Capacitor, refers to the amount of charge storage under a given potential difference, denoted as C, and the international unit is farad (F). Generally speaking, electric charges move under force in an electric field. When there is a medium between conductors, the movement of electric charges is hindered and the electric charges accumulate on the conductors, resulting in accumulation of electric charges.

The amount of stored electric charges is called capacitance. Because capacitors are one of the most widely used electronic components in electronic equipment, they are widely used in direct current isolation, coupling, bypass, filtering, tuning loops, energy conversion, and control circuits. Capacitors are divided into electrolytic capacitors, solid capacitors, etc.

According to material characteristics, capacitors can be divided into: aluminum electrolytic capacitors, film capacitors, tantalum capacitors, ceramic capacitors, super capacitors, etc.

In this kit, ceramic capacitors and electrolytic capacitors are used.

There are 103 or 104 label on the ceramic capacitors, which represent the capacitance value, 103=10x10^3pF, 104=10x10^4pF

Unit Conversion

1F=10^3mF=10^6uF=10^9nF=10^12pF

Jumper Wires

Wires that connect two terminals are called jumper wires. There are various kinds of jumper wires. Here we focus on those used in breadboard. Among others, they are used to transfer electrical signals from anywhere on the breadboard to the input/output pins of a microcontroller.

Jump wires are fitted by inserting their “end connectors” into the slots provided in the breadboard, beneath whose surface there are a few sets of parallel plates that connect the slots in groups of rows or columns depending on the area. The “end connectors” are inserted into the breadboard, without soldering, in the particular slots that need to be connected in the specific prototype.

There are three types of jumper wire: Female-to-Female, Male-to-Male, and Male-to-Female. The reason we call it Male-to-Female is because it has the outstanding tip in one end as well as a sunk female end. Male-to-Male means both side are male and Female-to-Female means both ends are female.

_images/image414.png

More than one type of them may be used in a project. The color of the jump wires is different but it doesn’t mean their function is different accordingly; it’s just designed so to better identify the connection between each circuit.

Transistor

_images/npn_pnp.png

Transistor is a semiconductor device that controls current by current. It functions by amplifying weak signal to larger amplitude signal and is also used for non-contact switch.

A transistor is a three-layer structure composed of P-type and N-type semiconductors. They form the three regions internally. The thinner in the middle is the base region; the other two are both N-type or P-type ones - the smaller region with intense majority carriers is the emitter region, when the other one is the collector region. This composition enables the transistor to be an amplifier. From these three regions, three poles are generated respectively, which are base (b), emitter (e), and collector (c). They form two P-N junctions, namely, the emitter junction and collection junction. The direction of the arrow in the transistor circuit symbol indicates that of the emitter junction.

Based on the semiconductor type, transistors can be divided into two groups, the NPN and PNP ones. From the abbreviation, we can tell that the former is made of two N-type semiconductors and one P-type and that the latter is the opposite. See the figure below.

Note

s8550 is PNP transistor and the s8050 is the NPN one, They look very similar, and we need to check carefully to see their labels.

_images/transistor_symbol.png

When a High level signal goes through an NPN transistor, it is energized. But a PNP one needs a Low level signal to manage it. Both types of transistor are frequently used for contactless switches, just like in this experiment.

Put the label side facing us and the pins facing down. The pins from left to right are emitter(e), base(b), and collector(c).

_images/ebc.png

Note

  • The base is the gate controller device for the larger electrical supply.

  • In the NPN transistor, the collector is the larger electrical supply and the emitter is the outlet for that supply, the PNP transistor is just the opposite.

Example

Chip

74HC595

_images/74HC595.png

Do you ever find yourself wanting to control a lot of LEDs, or just need more I/O pins to control buttons, sensors, and servos all at once? Well, you can connect a few sensors to Arduino pins, but you will soon start to run out of pins on the Arduino.

The solution is to use “shift registers”. Shift registers allow you to expand the number of I/O pins you can use from the Arduino (or any microcontroller). The 74HC595 shift register is one of the most famous.

The 74HC595 basically controls eight independent output pins and uses only three input pins. If you need more than eight additional I/O lines, you can easily cascade any number of shift registers and create a large number of I/O lines. All this is done by so-called shifting.

Features

  • 8-Bit serial-in, parallel-out shift

  • Wide operating voltage range of 2 V to 6 V

  • High-current 3-state outputs can drive up to 15LSTTL loads

  • Low power consumption, 80-µA max ICC

  • Typical tPD = 14 ns

  • ±6-mA output drive at 5 V

  • Low input current of 1 µA max

  • Shift register has direct clear

Pins of 74HC595 and their functions:

_images/74hc595_pin.png
  • Q0-Q7: 8-bit parallel data output pins, able to control 8 LEDs or 8 pins of 7-segment display directly.

  • Q7’: Series output pin, connected to DS of another 74HC595 to connect multiple 74HC595s in series

  • MR: Reset pin, active at low level;

  • SHcp: Time sequence input of shift register. On the rising edge, the data in shift register moves successively one bit, i.e. data in Q1 moves to Q2, and so forth. While on the falling edge, the data in shift register remain unchanged.

  • STcp: Time sequence input of storage register. On the rising edge, data in the shift register moves into memory register.

  • CE: Output enable pin, active at low level.

  • DS: Serial data input pin

  • VCC: Positive supply voltage.

  • GND: Ground.

Functional Diagram

_images/74hc595_functional_diagram.png

Working Principle

When MR (pin10) is high level and OE (pin13) is low level, data is input in the rising edge of SHcp and goes to the memory register through the rising edge of STcp.

  • Shift Register

    • Suppose, we want to input the binary data 1110 1110 into the shift register of the 74hc595.

    • The data is input from bit 0 of the shift register.

    • Whenever the shift register clock is a rising edge, the bits in the shift register are shifted one step. For example, bit 7 accepts the previous value in bit 6, bit 6 gets the value of bit 5, etc.

_images/74hc595_shift.png
  • Storage Register

    • When the storage register is in the rising edge state, the data of the shift register will be transferred to the storage register.

    • The storage register is directly connected to the 8 output pins, Q0 ~ Q7 will be able to receive a byte of data.

    • The so-called storage register means that the data can exist in this register and will not disappear with one output.

    • The data will remain valid and unchanged as long as the 74HC595 is powered on continuously.

    • When new data comes, the data in the storage register will be overwritten and updated.

_images/74hc595_storage.png

Example

L293D

L293D is a 4-channel motor driver integrated by chip with high voltage and high current. It’s designed to connect to standard DTL, TTL logic level, and drive inductive loads (such as relay coils, DC, Stepper Motors) and power switching transistors etc. DC Motors are devices that turn DC electrical energy into mechanical energy. They are widely used in electrical drive for their superior speed regulation performance.

See the figure of pins below. L293D has two pins (Vcc1 and Vcc2) for power supply. Vcc2 is used to supply power for the motor, while Vcc1 to supply for the chip. Since a small-sized DC motor is used here, connect both pins to +5V.

_images/l293d111.png

The following is the internal structure of L293D. Pin EN is an enable pin and only works with high level; A stands for input and Y for output. You can see the relationship among them at the right bottom. When pin EN is High level, if A is High, Y outputs high level; if A is Low, Y outputs Low level. When pin EN is Low level, the L293D does not work.

_images/l293d334.png

Example

Display

LED

What’s LED?

_images/led_pin.jpg _images/led_polarity.jpg

LEDs are very common electronic devices that can be used to decorate your room during the festival, and you can also use them as indicators for various things, such as whether the power to your home appliances is on or off. They come in dozens of different shapes and sizes, and the most common are LEDs with through hole LEDs, which generally have long leads and can be plugged into a breadboard.

The full name of LED is light-emitting diode, so it has the characteristics of a diode, where current flows in one direction, from the anode (positive) to the cathode (negative).

Here are the electrical symbols for LEDs.

_images/led_symbol.png

Various sizes and colors

_images/led_color.png

Red, yellow, blue, green, and white are the most common LED colors, and the light emitted is usually the same color as the appearance.

We rarely use LEDs that are transparent or matte in appearance, but the light emitted may be a color other than white.

LEDs come in four sizes: 3mm, 5mm, 8mm and 10mm, with 5mm being the most common size.

_images/led_type.jpg

Below is the LED size of 5mm in mm.

_images/led_size.png

Forward Voltage

The Forward Voltage is a very important parameter to know when using LEDs, as it determines how much power you use and how large the current limiting resistor should be.

The Forward Voltage is the voltage that the LED needs to use when it lights up. For most red, yellow, orange and light green LEDs, they generally use a voltage between 1.9V and 2.1V.

_images/led_voltage.jpg

According to Ohm’s law, the current through this circuit decreases as the resistance increases, which causes the LED to dim.

I = (Vp-Vl)/R

To get the LEDs to light up safely and with the right brightness, how much resistance should we use in the circuit?

For 99% of 5mm LEDs, the recommended current is 20mA, as you can see from the Conditions column of its data sheet.

_images/led_datasheet.png

Now convert the above formula as shown below.

R = (Vp-Vl)/I

If Vp is 5V, Vl (Forward Voltage) is 2V, and I is 20mA, then R is 150Ω.

So we can make the LED brighter by reducing the resistance of the resistor, but it is not recommended to go below 150Ω (this resistance may not be very accurate, because different suppliers provide LEDs have differences).

Below are the forward voltages and wavelengths of different color LEDs that you can use as reference.

LED Color

Forward Voltage

Wavelength

Red

1.8V ~ 2.1V

620 ~ 625

Yellow

1.9V ~ 2.2V

580 ~ 590

Green

1.9V ~ 2.2V

520 ~ 530

Blue

3.0V ~ 3.2V

460 ~ 465

White

3.0V ~ 3.2V

8000 ~ 9000

Example

RGB LED

_images/rgb_led.png

RGB LEDs emit light in various colors. An RGB LED packages three LEDs of red, green, and blue into a transparent or semitransparent plastic shell. It can display various colors by changing the input voltage of the three pins and superimpose them, which, according to statistics, can create 16,777,216 different colors.

Features

  • Color: Tri-Color (Red/Green/Blue)

  • Common Cathode

  • 5mm Clear Round Lens

  • Forward Voltage: Red: DC 2.0 - 2.2V; Blue&Green: DC 3.0 - 3.2V (IF=20mA)

  • 0.06 Watts DIP RGB LED

  • Luminance Brighter Up To +20%

  • Viewing Angle: 30°

Common Anode and Common Cathode

RGB LEDs can be categorized into common anode and common cathode ones.

  • In a common cathode RGB LED, all three LEDs share a negative connection (cathode).

  • In a common anode RGB LED, the three LEDs share a positive connection (anode).

_images/rgb_cc_ca.jpg

Note

We use the common cathode one.

RGB LED Pins

An RGB LED has 4 pins: the longest one is GND; the others are Red, Green and Blue. Place the RGB LEDs as shown, so that the longest lead is second from the left. Then the pin numbers of the RGB LEDs should be Red, GND, Green and Blue.

_images/rgb_pin.jpg

You can also use the multimeter to select Diode Test mode, and then connect as shown below to measure the color of each pin.

_images/rgb_test.png

Mix colors

To generate additional colors, you can combine the three colors at different intensities. To adjust the intensity of each LED, you can use a PWM signal.

Because the LEDs are so close to each other, our eyes see the result of the color combination rather than the three colors individually.

Check out the table below to see how the colors are combined. It will give you an idea of how the color mixing chart works and how different colors are produced.

_images/rgb_mix.png

Example

7-segment Display

_images/7_segment.png

A 7-segment display is an 8-shaped component which packages 7 LEDs. Each LED is called a segment - when energized, one segment forms part of a numeral to be displayed.

  • Each of the LEDs in the display is given a positional segment with one of its connection pins led out from the rectangular plastic package.

  • These LED pins are labeled from “a” through to “g” representing each individual LED.

  • The other LED pins are connected together forming a common pin.

  • So by forward biasing the appropriate pins of the LED segments in a particular order, some segments will brighten and others stay dim, thus showing the corresponding character on the display.

Features

  • Size: 19 x 12.7 x 13.8mm(LxWxH, include the pin)

  • Screen: 0.56’’

  • Color: red

  • Common Cathode

  • Forward Voltage: 1.8V

  • 10 pins

  • Pitch: standard 0.1” (2.54mm)

Common Cathode (CC) or Common Anode (CA)

There are two types of pin connection: Common Cathode (CC) and Common Anode (CA). As the name suggests, a CC display has all the cathodes of the 7 LEDs connected when a CA display has all the anodes of the 7 segments connected.

  • Common Cathode 7-Segment Display

_images/segment_cathode.png
  • Common Anode 7-Segment Display

_images/segment_anode.png

How to Know CC or CA?

Usually there will be label on the side of the 7-segment display, xxxAx or xxxBx. Generally speaking xxxAx stands for common cathode and xxxBx stands for common anode.

_images/7_segment.png _images/7_segment_bs.png

You can also use a multimeter to check the 7-segment display if there is no label. Set the multimeter to diode test mode and connect the black lead to the middle pin of the 7-segment display, and the red lead to any other pin except the middle one. The 7-segment display is common cathode if a segment lights up.

You swap the red and black meter heads if there is no segment lit. When a segment is lit, it indicates a common anode.

components/img/7_segment_test.JPG

Display Codes

To help you get to know how 7-segment displays(Common Cathode) display Numbers, we have drawn the following table. Numbers are the number 0-F displayed on the 7-segment display; (DP) GFEDCBA refers to the corresponding LED set to 0 or 1.

_images/segment_code.png

For example, 01011011 means that DP, F and C are set to 0, while others are set to 1. Therefore, the number 2 is displayed on the 7-segment display.

_images/7segment_2.png

Example

I2C LCD1602

_images/i2c_lcd1602.png
  • GND: Ground

  • VCC: Voltage supply, 5V.

  • SDA: Serial data line. Connect to VCC through a pullup resistor.

  • SCL: Serial clock line. Connect to VCC through a pullup resistor.

As we all know, though LCD and some other displays greatly enrich the man-machine interaction, they share a common weakness. When they are connected to a controller, multiple IOs will be occupied of the controller which has no so many outer ports. Also it restricts other functions of the controller.

Therefore, LCD1602 with an I2C module is developed to solve the problem. The I2C module has a built-in PCF8574 I2C chip that converts I2C serial data to parallel data for the LCD display.

I2C Address

The default address is basically 0x27, in a few cases it may be 0x3F.

Taking the default address of 0x27 as an example, the device address can be modified by shorting the A0/A1/A2 pads; in the default state, A0/A1/A2 is 1, and if the pad is shorted, A0/A1/A2 is 0.

_images/i2c_address.jpg

Backlight/Contrast

Backlight can be enabled by jumper cap, unplugg the jumper cap to disable the backlight. The blue potentiometer on the back is used to adjust the contrast (the ratio of brightness between the brightest white and the darkest black).

_images/back_lcd1602.jpg
  • Shorting Cap: Backlight can be enabled by this cap,unplugg this cap to disable the backlight.

  • Potentiometer: It is used to adjust the contrast (the clarity of the displayed text), which is increased in the clockwise direction and decreased in the counterclockwise direction.

Example

WS2812 RGB 8 LEDs Strip

_images/ws2812b.png

The WS2812 RGB 8 LEDs Strip is composed of 8 RGB LEDs. Only one pin is required to control all the LEDs. Each RGB LED has a WS2812 chip, which can be controlled independently. It can realize 256-level brightness display and complete true color display of 16,777,216 colors. At the same time, the pixel contains an intelligent digital interface data latch signal shaping amplifier drive circuit, and a signal shaping circuit is built in to effectively ensure the color height of the pixel point light Consistent.

It is flexible, can be docked, bent, and cut at will, and the back is equipped with adhesive tape, which can be fixed on the uneven surface at will, and can be installed in a narrow space.

Features

  • Work Voltage: DC5V

  • IC: One IC drives one RGB LED

  • Consumption: 0.3w each LED

  • Working Temperature: -15-50

  • Color: Full color RGB

  • RGB Type:5050RGB(Built-in IC WS2812B)

  • Light Strip Thickness: 2mm

  • Each LED can be controlled individually

WS2812B Introdction

WS2812B is a intelligent control LED light source that the control circuit and RGB chip are integrated in a package of 5050 components. It internal include intelligent digital port data latch and signal reshaping ampli fication drive circuit. Also include a precision internal oscillator and a 12V voltage programmable constant curr e-nt control part, effectively ensuring the pixel point light color height consistent.

The data transfer protocol use single NZR communication mode. After the pixel power-on reset, the DIN port receive data from controller, the first pixel collect initial 24bit data then sent to the internal data latch, the other data which reshaping by the internal signal reshaping amplification circuit sent to the next cascade pixel through the DO port. After transmission for each pixel,the signal to reduce 24bit. pixel adopt auto resha -ping transmit technology, making the pixel cascade number is not limited the signal transmission, only depend on the speed of signal transmission.

LED with low driving voltage, environmental protection and energy saving, high brightness, scattering angl e is large, good consistency, low power, long life and other advantages. The control chip integrated in LED above becoming more simple circuit, small volume, convenient installation.

Example

Sound

Buzzer

_images/buzzer.png

As a type of electronic buzzer with an integrated structure, buzzers, which are supplied by DC power, are widely used in computers, printers, photocopiers, alarms, electronic toys, automotive electronic devices, telephones, timers and other electronic products or voice devices.

Buzzers can be categorized as active and passive ones (see the following picture). Turn the buzzer so that its pins are facing up, and the buzzer with a green circuit board is a passive buzzer, while the one enclosed with a black tape is an active one.

The difference between an active buzzer and a passive buzzer:

An active buzzer has a built-in oscillating source, so it will make sounds when electrified. But a passive buzzer does not have such source, so it will not beep if DC signals are used; instead, you need to use square waves whose frequency is between 2K and 5K to drive it. The active buzzer is often more expensive than the passive one because of multiple built-in oscillating circuits.

The following is the electrical symbol of a buzzer. It has two pins with positive and negative poles. With a + in the surface represents the anode and the other is the cathode.

_images/buzzer_symbol.png

You can check the pins of the buzzer, the longer one is the anode and the shorter one is the cathode. Please don’t mix them up when connecting, otherwise the buzzer will not make sound.

Buzzer - Wikipedia

Example

Audio Module and Speaker

Audio Amplifier Module

_images/audio_module.jpg

Audio Amplifier Module contains a HXJ8002 audio power amplifier chip. This chip is a power amplifier with low power supply, that can provide 3W average audio power for a 3Ω BTL load with low harmonic distortion (under 10% threshold distortion at 1KHz) from a 5V DC power supply. This chip can amplify audio signals without any coupling capacitors or bootstrap capacitors.

The module can be supplied by a 2.0V up to 5.5V DC with 10mA operating current (0.6uA for typical standby current) power source and produce a powerful amplified sound into a 3Ω, 4Ω, or 8Ω impedance speaker. This module has an improved pop and clicks circuitry for reducing significantly the transition nose at the powering on and off moment. Tiny size besides high efficiency and low power supplying make it applicable in widely portable and battery-powered projects and microcontrollers.

  • IC: HXJ8002

  • Input Voltage: 2V ~ 5.5V

  • Standby Mode Current: 0.6uA (typical value)

  • Output Power: 3W (3Ω load) , 2.5W (4Ω load) , 1.5W (8Ω load)

  • Output Speaker Impedance: 3Ω, 4Ω, 8Ω

  • Size: 19.8mm x 14.2mm

Speaker

_images/speaker_pic.png
  • Size: 20x30x7mm

  • Impedance:8ohm

  • Rate Input Power: 1.5W

  • Max Input Power: 2.0W

  • Wire Length: 10cm

_images/2030_speaker.png

The size chart is as follows:

Example

Driver

DC Motor

_images/image114.jpeg

This is a 3V DC motor. When you give a high level and a low level to each of the 2 terminals, it will rotate.

  • Length: 25mm

  • Diameter: 21mm

  • Shaft Diameter: 2mm

  • Shaft Length: 8mm

  • Voltage: 3-6V

  • Current: 0.35-0.4A

  • Speed at 3V: 19000 RPM (Rotations Per Minute)

  • Weight: Approximately 14g (for one unit)

Direct current (DC) motor is a continuous actuator that converts electrical energy into mechanical energy. DC motors make rotary pumps, fans, compressors, impellers, and other devices work by producing continuous angular rotation.

A DC motor consists of two parts, the fixed part of the motor called the stator and the internal part of the motor called the rotor (or armature of a DC motor) that rotates to produce motion. The key to generating motion is to position the armature within the magnetic field of the permanent magnet (whose field extends from the north pole to the south pole). The interaction of the magnetic field and the moving charged particles (the current-carrying wire generates the magnetic field) produces the torque that rotates the armature.

_images/motor_sche.png

Current flows from the positive terminal of the battery through the circuit, through the copper brushes to the commutator, and then to the armature. But because of the two gaps in the commutator, this flow reverses halfway through each complete rotation.

This continuous reversal essentially converts the DC power from the battery to AC, allowing the armature to experience torque in the right direction at the right time to maintain rotation.

_images/motor_rotate.gif

Example

Servo

_images/servo.png

A servo is generally composed of the following parts: case, shaft, gear system, potentiometer, DC motor, and embedded board.

It works like this: The microcontroller sends out PWM signals to the servo, and then the embedded board in the servo receives the signals through the signal pin and controls the motor inside to turn. As a result, the motor drives the gear system and then motivates the shaft after deceleration. The shaft and potentiometer of the servo are connected together. When the shaft rotates, it drives the potentiometer, so the potentiometer outputs a voltage signal to the embedded board. Then the board determines the direction and speed of rotation based on the current position, so it can stop exactly at the right position as defined and hold there.

_images/servo_internal.png

The angle is determined by the duration of a pulse that is applied to the control wire. This is called Pulse width Modulation. The servo expects to see a pulse every 20 ms. The length of the pulse will determine how far the motor turns. For example, a 1.5ms pulse will make the motor turn to the 90 degree position (neutral position). When a pulse is sent to a servo that is less than 1.5 ms, the servo rotates to a position and holds its output shaft some number of degrees counterclockwise from the neutral point. When the pulse is wider than 1.5 ms the opposite occurs. The minimal width and the maximum width of pulse that will command the servo to turn to a valid position are functions of each servo. Generally the minimum pulse will be about 0.5 ms wide and the maximum pulse will be 2.5 ms wide.

_images/servo_duty.png

Example

Centrifugal Pump

_images/pump.png

The centrifugal pump converts rotational kinetic energy into hydrodynamic energy to transport fluid. The rotation energy comes from the electric motor. The fluid enters the pump impeller along or near the rotating shaft, is accelerated by the impeller, flows radially outward into the diffuser or volute chamber, and then flows out from there.

Common uses of centrifugal pumps include water, sewage, agricultural, petroleum, and petrochemical pumping.

Features
  • Voltage Scope: DC 3 ~ 4.5V

  • Operating Current: 120 ~ 180mA

  • Power: 0.36 ~ 0.91W

  • Max Water Head: 0.35 ~ 0.55M

  • Max Flow Rate: 80 ~ 100 L/H

  • Continuous Working Life: 100 hours

  • Water Fing Grade: IP68

  • Driving Mode: DC, Magnetic Driving

  • Material: Engineering Plastic

  • Outlet Outside Diameter: 7.8 mm

  • Outlet Inside Diameter: 6.5 mm

  • It is a submersible pump and should be used that way. It tends to heat too much that there’s a risk of overheating if you turn it on unsubmerged.

Example

Controller

Button

_images/button.png

Buttons are a common component used to control electronic devices. They are usually used as switches to connect or break circuits. Although buttons come in a variety of sizes and shapes, the one used here is a 6mm mini-button as shown in the following pictures. Pin 1 is connected to pin 2 and pin 3 to pin 4. So you just need to connect either of pin 1 and pin 2 to pin 3 or pin 4.

The following is the internal structure of a button. The symbol on the right below is usually used to represent a button in circuits.

_images/button_symbol.png

Since the pin 1 is connected to pin 2, and pin 3 to pin 4, when the button is pressed, the 4 pins are connected, thus closing the circuit.

_images/button2.jpg

Example

Tilt Switch

_images/tilt_switch.png

The tilt switch used here is a ball one with a metal ball inside. It is used to detect inclinations of a small angle.

The principle is very simple. When the switch is tilted in a certain angle, the ball inside rolls down and touches the two contacts connected to the pins outside, thus triggering circuits. Otherwise the ball will stay away from the contacts, thus breaking the circuits.

_images/tilt_symbol.png

Example

Potentiometer

_images/potentiometer.png

Potentiometer is also a resistance component with 3 terminals and its resistance value can be adjusted according to some regular variation.

Potentiometers come in various shapes, sizes, and values, but they all have the following things in common:

  • They have three terminals (or connection points).

  • They have a knob, screw, or slider that can be moved to vary the resistance between the middle terminal and either one of the outer terminals.

  • The resistance between the middle terminal and either one of the outer terminals varies from 0 Ω to the maximum resistance of the pot as the knob, screw, or slider is moved.

Here is the circuit symbol of potentiometer.

_images/potentiometer_symbol.png

The functions of the potentiometer in the circuit are as follows:

  1. Serving as a voltage divider

    Potentiometer is a continuously adjustable resistor. When you adjust the shaft or sliding handle of the potentiometer, the movable contact will slide on the resistor. At this point, a voltage can be output depending on the voltage applied onto the potentiometer and the angle the movable arm has rotated to or the travel it has made.

  2. Serving as a rheostat

    When the potentiometer is used as a rheostat, connect the middle pin and one of the other 2 pins in the circuit. Thus you can get a smoothly and continuously changed resistance value within the travel of the moving contact.

  3. Serving as a current controller

    When the potentiometer acts as a current controller, the sliding contact terminal must be connected as one of the output terminals.

If you want to know more about potentiometer, refer to: Potentiometer - Wikipedia

Example

Joystick Module

_images/joystick_pic.png
  • GND: Ground.

  • +5V: Power supply, accepts 3.3V to 5V.

  • VRX: Analog output corresponding to the joystick’s horizontal (X-axis) position.

  • VRY: Analog output corresponding to the joystick’s vertical (Y-axis) position.

  • SW: Button switch output, activated when the joystick is pressed down. For proper operation, an external pull-up resistor is required. With the resistor in place, the SW pin outputs a high level when idle and goes low when the joystick is pressed.

The basic idea of a joystick is to translate the movement of a stick into electronic information that a computer can process.

In order to communicate a full range of motion to the computer, a joystick needs to measure the stick’s position on two axes - the X-axis (left to right) and the Y-axis (up and down). Just as in basic geometry, the X-Y coordinates pinpoint the stick’s position exactly.

To determine the location of the stick, the joystick control system simply monitors the position of each shaft. The conventional analog joystick design does this with two potentiometers, or variable resistors.

The joystick also has a digital input that is actuated when the joystick is pressed down.

_images/joystick318.png

Example

IR Receiver

IR Receiver

_images/ir_receiver_sl838.png
  • OUT: Signal output

  • GND: GND

  • VCC: power supply, 3.3v~5V

SL838 infrared-receiver is a component which receives infrared signals and can independently receive infrared rays and output signals compatible with TTL level. It is similar with a normal plastic-packaged transistor in size and is suitable for all kinds of infrared remote control and infrared transmission.

Infrared, or IR, communication is a popular, low-cost, easy-to-use wireless communication technology. Infrared light has a slightly longer wavelength than visible light, so it is imperceptible to the human eye - ideal for wireless communication. A common modulation scheme for infrared communication is 38KHz modulation.

  • Can be used for remote control

  • Wide operating voltage: 2.7~5V

  • Internal filter for PCM frequency

  • TTL and CMOS compatibility

  • Strong anti-interference ability

  • Compliant RoHS

Remote Control

_images/image186.jpeg

This is a Mini thin infrared wireless remote control with 21 function buttons and a transmitting distance of up to 8 meters, which is suitable for operating a wide range of devices in a kid’s room.

  • Size: 85x39x6mm

  • Remote control range: 8-10m

  • Battery: 3V button type lithium manganese battery

  • Infrared carrier frequency: 38KHz

  • Surface paste material: 0.125mm PET

  • Effective life: more than 20,000 times

Example

Sensor

Photoresistor

_images/photoresistor.png

A photoresistor or photocell is a light-controlled variable resistor. The resistance of a photoresistor decreases with increasing incident light intensity; in other words, it exhibits photo conductivity.

A photoresistor can be applied in light-sensitive detector circuits and light-activated and dark-activated switching circuits acting as a resistance semiconductor. In the dark, a photoresistor can have a resistance as high as several megaohms (MΩ), while in the light, a photoresistor can have a resistance as low as a few hundred ohms.

Here is the electronic symbol of photoresistor.

_images/photoresistor_symbol.png

Example

Thermistor

_images/thermistor.png

A thermistor is a type of resistor whose resistance is strongly dependent on temperature, more so than in standard resistors. The word is a combination of thermal and resistor. Thermistors are widely used as inrush current limiters, temperature sensors (negative temperature coefficient or NTC type typically), self-resetting overcurrent protectors, and self-regulating heating elements (positive temperature coefficient or PTC type typically).

Here is the electronic symbol of thermistor.

_images/thermistor_symbol.png

Thermistors are of two opposite fundamental types:

  • With NTC thermistors, resistance decreases as temperature rises usually due to an increase in conduction electrons bumped up by thermal agitation from valency band. An NTC is commonly used as a temperature sensor, or in series with a circuit as an inrush current limiter.

  • With PTC thermistors, resistance increases as temperature rises usually due to increased thermal lattice agitations particularly those of impurities and imperfections. PTC thermistors are commonly installed in series with a circuit, and used to protect against overcurrent conditions, as resettable fuses.

In this kit we use an NTC one. Each thermistor has a normal resistance. Here it is 10k ohm, which is measured under 25 degree Celsius.

Here is the relation between the resistance and temperature:

RT = RN * expB(1/TK - 1/TN)

  • RT is the resistance of the NTC thermistor when the temperature is TK.

  • RN is the resistance of the NTC thermistor under the rated temperature TN. Here, the numerical value of RN is 10k.

  • TK is a Kelvin temperature and the unit is K. Here, the numerical value of TK is 273.15 + degree Celsius.

  • TN is a rated Kelvin temperature; the unit is K too. Here, the numerical value of TN is 273.15+25.

  • And B(beta), the material constant of NTC thermistor, is also called heat sensitivity index with a numerical value 3950.

  • exp is the abbreviation of exponential, and the base number e is a natural number and equals 2.7 approximately.

Convert this formula TK=1/(ln(RT/RN)/B+1/TN) to get Kelvin temperature that minus 273.15 equals degree Celsius.

This relation is an empirical formula. It is accurate only when the temperature and resistance are within the effective range.

Example

DHT11 Humiture Sensor

The digital temperature and humidity sensor DHT11 is a composite sensor that contains a calibrated digital signal output of temperature and humidity. The technology of a dedicated digital modules collection and the temperature and humidity sensing technology are applied to ensure that the product has high reliability and excellent long-term stability.

The sensor includes a resistive sense of wet component and an NTC temperature measurement device, and is connected with a high-performance 8-bit microcontroller.

Only three pins are available for use: VCC, GND, and DATA. The communication process begins with the DATA line sending start signals to DHT11, and DHT11 receives the signals and returns an answer signal. Then the host receives the answer signal and begins to receive 40-bit humiture data (8-bit humidity integer + 8-bit humidity decimal + 8-bit temperature integer + 8-bit temperature decimal + 8-bit checksum).

_images/dht11.png

Features

  1. Humidity measurement range: 20 - 90%RH

  2. Temperature measurement range: 0 - 60℃

  3. Output digital signals indicating temperature and humidity

  4. Working voltage:DC 5V; PCB size: 2.0 x 2.0 cm

  5. Humidity measurement accuracy: ±5%RH

  6. Temperature measurement accuracy: ±2℃

Example

PIR Motion Sensor Module

_images/pir_pic.png

The PIR sensor detects infrared heat radiation that can be used to detect the presence of organisms that emit infrared heat radiation.

The PIR sensor is split into two slots that are connected to a differential amplifier. Whenever a stationary object is in front of the sensor, the two slots receive the same amount of radiation and the output is zero. Whenever a moving object is in front of the sensor, one of the slots receives more radiation than the other , which makes the output fluctuate high or low. This change in output voltage is a result of detection of motion.

_images/PIR_working_principle.jpg

After the sensing module is wired, there is a one-minute initialization. During the initialization, module will output for 0~3 times at intervals. Then the module will be in the standby mode. Please keep the interference of light source and other sources away from the surface of the module so as to avoid the misoperation caused by the interfering signal. Even you’d better use the module without too much wind, because the wind can also interfere with the sensor.

_images/pir_back1.png

Distance Adjustment

Turning the knob of the distance adjustment potentiometer clockwise, the range of sensing distance increases, and the maximum sensing distance range is about 0-7 meters. If turn it anticlockwise, the range of sensing distance is reduced, and the minimum sensing distance range is about 0-3 meters.

Delay adjustment

Rotate the knob of the delay adjustment potentiometer clockwise, you can also see the sensing delay increasing. The maximum of the sensing delay can reach up to 300s. On the contrary, if rotate it anticlockwise, you can shorten the delay with a minimum of 5s.

Two Trigger Modes

Choosing different modes by using the jumper cap.

  • H: Repeatable trigger mode, after sensing the human body, the module outputs high level. During the subsequent delay period, if somebody enters the sensing range, the output will keep being the high level.

  • L: Non-repeatable trigger mode, outputs high level when it senses the human body. After the delay, the output will change from high level into low level automatically.

Example

Line Tracking Module

_images/line_track.png
  • S: Usually low level, high level when the black line is detected.

  • V+:Power supply, 3.3v~5V

  • G: Ground

This is a 1-channel Line Tracking module which, as the name suggests, tracks black lines on a white background or white lines against a black background.

_images/tcrt5000.jpg

The module uses a TCRT500 infrared sensor, which consists of an infrared LED (blue) and a photosensitive triplet (black).

  • The blue infrared LED, when powered on, emits infrared light that is invisible to the human eye.

  • The black phototransistor, which is used to receive infrared light, has an internal resistor whose resistance varies with the infrared light received; the more infrared light received, the lower its resistance decreases and vice versa.

There is a LM393 comparator on the module, which is used to compare the voltage of the phototransistor with the set voltage (adjusted by potentiometer), if it is greater than the set voltage, the output is 1; otherwise the output is 0.

Therefore, when the infrared emitter tube shines on a black surface, because the black will absorb light, the photosensitive transistor receives less infrared light, its resistance will increase (voltage increase), after LM393 comparator, the output high level.

Similarly, when it shines on a white surface, the reflected light will become more and the resistance of the photosensitive transistor will decrease (voltage decreases); therefore, the comparator outputs a low level and the indicator LED lights up.

Features

  • Using infrared emission sensor TCRT5000

  • Detection distance: 1-8mm, focal length of 2.5mm

  • Comparator output signal clean, good waveform, driving capacity greater than 15mA

  • Using potentiometer for sensitivity adjustment

  • Operating voltage: 3.3V-5V

  • Digital output: 0 (white) and 1 (black)

  • Uses wide voltage LM393 comparator.

  • Size: 42mmx10mm

Example

Soil Moisture Module

_images/soil_mositure.png
  • GND: Ground

  • VCC: Power supply, 3.3v~5V

  • AOUT: Outputs the soil moisture value, the wetter the soil, the smaller its value.

This capacitive soil moisture sensor is different from most of the resistive sensors on the market, using the principle of capacitive induction to detect soil moisture. It avoids the problem that resistive sensors are highly susceptible to corrosion and greatly extends its working life.

It is made of corrosion-resistant materials and has an excellent service life. Insert it into the soil around plants and monitor real-time soil moisture data. The module includes an on-board voltage regulator that allows it to operate over a voltage range of 3.3 ~ 5.5 V. It is ideal for low-voltage microcontrollers with 3.3 V and 5 V supplies.

The hardware schematic of the capacitive soil moisture sensor is shown below.

_images/solid_schematic.png

There is a fixed frequency oscillator, which is built with a 555 timer IC. The generated square wave is then fed to the sensor like a capacitor. However, for the square wave signal, the capacitor has a certain reactance or, for the sake of argument, a resistor with a pure ohmic resistor (10k resistor on pin 3) to form a voltage divider.

The higher the soil moisture, the higher the capacitance of the sensor. As a result, the square wave has less reactance, which reduces the voltage on the signal line, and the smaller the value of the analog input through the microcontroller.

Specification

  • Operating Voltage: 3.3 ~ 5.5 VDC

  • Output Voltage: 0 ~ 3.0VDC

  • Operating Current: 5mA

  • Interface: PH2.0-3P

  • Dimensions: 3.86 x 0.905 inches (L x W)

  • Weight: 15g

Example

Obstacle Avoidance Module

_images/IR_Obstacle.png
  • VCC: Power supply, 3.3 ~ 5V DC.

  • GND: Ground

  • OUT: Signal pin, usually high level, and low level when an obstacle is detected.

The IR obstacle avoidance module has strong adaptability to environmental light, it has a pair of infrared transmitting and receiving tubes.

The transmitting tube emits infrared frequency, when the detection direction encounters an obstacle, the infrared radiation is received by the receiving tube, after the comparator circuit processing, the indicator will light up and output low level signal.

The detection distance can be adjusted by potentiometer, the effective distance range 2-30cm.

_images/IR_module.png

Example

Ultrasonic Module

_images/ultrasonic_pic.png
  • TRIG: Trigger Pulse Input

  • ECHO: Echo Pulse Output

  • GND: Ground

  • VCC: 5V Supply

This is the HC-SR04 ultrasonic distance sensor, providing non-contact measurement from 2 cm to 400 cm with a range accuracy of up to 3 mm. Included on the module is an ultrasonic transmitter, a receiver and a control circuit.

You only need to connect 4 pins: VCC (power), Trig (trigger), Echo (receive) and GND (ground) to make it easy to use for your measurement projects.

Features

  • Working Voltage: DC5V

  • Working Current: 16mA

  • Working Frequency: 40Hz

  • Max Range: 500cm

  • Min Range: 2cm

  • Trigger Input Signal: 10uS TTL pulse

  • Echo Output Signal: Input TTL lever signal and the range in proportion

  • Connector: XH2.54-4P

  • Dimension: 46x20.5x15 mm

Principle

The basic principles are as follows:

  • Using IO trigger for at least 10us high level signal.

  • The module sends an 8 cycle burst of ultrasound at 40 kHz and detects whether a pulse signal is received.

  • Echo will output a high level if a signal is returned; the duration of the high level is the time from emission to return.

  • Distance = (high level time x velocity of sound (340M/S)) / 2

_images/ultrasonic_prin.jpg

Formula:

  • us / 58 = centimeters distance

  • us / 148 = inch distance

  • distance = high level time x velocity (340M/S) / 2

Note

This module should not be connected under power up, if necessary, let the module’s GND be connected first. Otherwise, it will affect the work of the module.

The area of the object to be measured should be at least 0.5 square meters and as flat as possible. Otherwise, it will affect results.

Example

FAQ

How to use Blynk on mobile device?

Note

As datastreams can only be created in Blynk on the web, you will need to reference different projects to create datastreams on the web, then follow the tutorial below to create widgets in Blynk on your mobile device.

  1. Open Google Play or APP Store on your mobile device and search for “Blynk IoT” (not Blynk(legacy)) to download.

  2. After opening the APP, login in, this account should be the same as the account used on the web client.

  3. Then go to Dashboard (if you don’t have one, create one) and you will see that the Dashboard for mobile and web are independent of each other.

    _images/APP_1.jpg
  4. Click Edit Icon.

  5. Click on the blank area.

  6. Choose the same widget as on the web page, such as select a Joystick widget.

    _images/APP_2.jpg
  7. Now you will see a Joystick widget appear in the blank area, click on it.

  8. Joystick Settings will appear, select the Xvalue and Yvalue datastreams you just set in the web page. Note that each widget corresponds to a different datastream in each project.

  9. Go back to the Dashboard page and you can operate the Joystick when you want.

    _images/APP_3.jpg

How to format the SD card?

The steps to ensure your SD card is formatted correctly may vary depending on your operating system. Here are simple steps on how to format an SD card in Windows, MacOS, and Linux:

Windows

  1. Insert your SD card into the computer, then open “My Computer” or “This PC.” Right-click on your SD card and select “Format.”

    _images/sd_format_win1.png
  2. In the file system drop-down menu, select the desired file system (usually choose FAT32, or for SD cards larger than 32GB, you may need to choose exFAT). Check “Quick Format” and then click “Start”.

    _images/sd_format_win2.png

MacOS

  1. Insert your SD card into the computer. Open the “Disk Utility” application (can be found in the “Utilities” folder).

    _images/sd_format_mac1.png
  2. Select your SD card from the list on the left and then click “Erase”.

    _images/sd_format_mac2.png
  3. From the format drop-down menu, choose your desired file system (usually choose MS-DOS (FAT) for FAT32, or ExFAT for SD cards larger than 32GB) and then click “Erase”.

    _images/sd_format_mac3.png
  4. Finally, wait for the formatting to complete.

    _images/sd_format_mac3.png

Linux

  • First, insert your SD card and then open a terminal.

  • Type lsblk and find your SD card’s name in the device list (e.g., it may be sdb).

  • Use the umount command to unmount the SD card, like sudo umount /dev/sdb*.

  • Use the mkfs command to format the SD card. For example, sudo mkfs.vfat /dev/sdb1 will format the SD card to a FAT32 file system (for SD cards larger than 32GB, you might need to use mkfs.exfat).

Before formatting your SD card, make sure to back up any important data on the SD card, as the formatting operation will erase all files on the SD card.

Always displaying “Unknown COMxx”?

When plugging the ESP32 into the computer, the Arduino IDE often displays Unknown COMxx. Why does this happen?

_images/unknown_device.png

This is because the USB driver for ESP32 is different from the regular Arduino Boards. The Arduino IDE can’t automatically recognize this board.

In such a scenario, you need to manually select the correct board by following these steps:

  1. Click on “Select the other board and port”.

    _images/unknown_select.png
  2. In the search, type “esp32 dev module”, then select the board that appears. Afterward, select the correct port and click OK.

    _images/unknown_board.png
  3. Now, you should be able to see your board and port in this quick view window.

    _images/unknown_correct.png

Thank You

Thanks to the evaluators who evaluated our products, the veterans who provided suggestions for the tutorial, and the users who have been following and supporting us. Your valuable suggestions to us are our motivation to provide better products!

Particular Thanks

  • Len Davisson

  • Kalen Daniel

  • Juan Delacosta

Now, could you spare a little time to fill out this questionnaire?

Note

After submitting the questionnaire, please go back to the top to view the results.