Before we get started with the Project, it is necessary to know the details of the Hardware. Slowly, we'll move ahead and get you started with ESP32 with all required instructions
The ESP32-WROOM-32 MCU Modules use the ESP32-D0WD chip at its core. This SoC features two CPU cores that can be individually controlled, and the CPU clock frequency is adjustable from 80MHz to 240MHz. The ESP32 integrates a rich set of peripherals, ranging from capacitive touch sensors, Hall sensors, SD card interface, Ethernet, high-speed SPI, UART, I2S, and I2C.
ESP32 PinoutThis is a top view of the pinouts on the ESP32. The pin labels are on the bottom of the board.
In total there are 39 GPIO pins, that can be used as input or output pins. 0V (low) and 3.3V (high). But pins 34 to 39 can be used as input only.
Using Arduino IDEIn your Arduino IDE, go to File > Preferences,
- Enter https://dl.espressif.com/dl/package_esp32_index.json into the “Additional Boards Manager URLs” field as shown in the figure below.
- Then, click the “OK” button:
- In your Arduino IDE, go to File > PreferencesEnter https://dl.espressif.com/dl/package_esp32_index.json into the “Additional Boards Manager URLs” field as shown in the figure below.Then, click the “OK” button:
- Open the Boards Manager. Go to Tools > Board > Boards Manager…
- Search for ESP32 and press the install button for the "esp32".
- Open the Boards Manager. Go to Tools > Board > Boards Manager…Search for ESP32 and press install button for the "esp32".
- Now, Go to Tools > Board:"Arduino Uno" > Select ESP32 Arduino > Select the Board you have/ Select 'ESP32 Dev Module' as default.
That's it !! You are SET and ready to start with the ESP32 Development using Arduino IDE.
From here onwards, you can use the ESP32 Dev Board similar to an Ordinary Arduino. Make sure to switch to the Correct Port which is connected to your ESP32 module.
Serial Port of ESP32/DeviceSearch and Open 'Device Manager'.
Go to 'Ports' and then Plug-In the ESP32. You'll see a new port added with 'USB Serial Device' (most cases). In my case, the port my ESP32 is connected with, to my laptop is COM9.
There are many libraries on Arduino IDE which can be found over here - https://www.arduinolibraries.info/architectures/esp32
These libraries work when it is installed in the Arduino IDE. Let us see how to do that -
In your Arduino IDE, go to Sketch > Include Library
If having a .ZIP
file which claims to be a library, select "Include .ZIP Library
" field as shown in the figure below.
Select the ZIP file, and you're good to go!!
Write simple codes that work on an Arduino IDE. Arduino helps in converting Arduino programming to be used on ESP32 for ESP-IDF with the SDK available here
Except analogRead - there are no 'A0..An pins' where n = 0, 1, 2,... in ESP module - there is another function to handle that. Separate function is present, we shall look into them in this project.
Mini Project - 1We will use the capacitive touch sensor feature of the ESP32 to make a Mini Piano. In our case, we will be using 3 pins - GPIO12, 14 and 27.
Here is the code for the same -
#define T5 12
#define T6 14
#define T7 27
int A, B, C;
const int buzzer = 32;
const int freq = 3000;
const int channel = 0;
const int res = 8;
void setup() {
ledcSetup(channel, freq, res);
ledcAttachPin(buzzer, channel);
ledcAttachPin(buzzer, channel);
pinMode(12, INPUT);
pinMode(14, INPUT);
pinMode(27, INPUT);
Serial.begin(115200);
}
void loop() {
A = touchRead(T5);
B = touchRead(T6);
C = touchRead(T7);
if (A < 30)
{
ledcWriteTone(channel, 500);
Serial.print("A: ");
Serial.println(A);
delay(500);
}
if (B < 30)
{
ledcWriteTone(channel, 1500);
Serial.print("B: ");
Serial.println(B);
delay(500);
}
if (C < 30)
{
ledcWriteTone(channel, 4000);
Serial.print("C: ");
Serial.println(C);
delay(500);
}
}
Mini Project - 2Since the ESP32 Dev Board also has a wifi chip on it. Let us try to write a simple program to test if it works.
We shall access a JSON data site(https://www.boredapi.com/api/activity or https://uselessfacts.jsph.pl/random.json?language=en) and read the data available on it, then print it on the Serial Monitor as well as the OLED screen. Here, ESP32 needs to be first connected to a WiFi network that has access to Internet.
In the code, Replace <wifi_name>
and <password>
under ssid and password with your WiFi credentials.
Below is the code for same -
#include <WiFi.h>
#include "HTTPClient.h"
#include <ArduinoJson.h>
const char* ssid = "wifi_name";
const char* password = "wifi_password";
String serverName = "https://uselessfacts.jsph.pl/random.json?language=en";
String oldTEXT="null";
void setup() {
Serial.begin(115200);
pinMode(2, OUTPUT);
//-------------------- WIFI INIT --------------------------------
WiFi.begin(ssid, password);
Serial.println("Connecting");
while(WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to WiFi network with IP Address: ");
Serial.println(WiFi.localIP());
//--------------------------------------------------------------
}
void loop() {
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
String serverPath = serverName;
// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());
// Send HTTP GET request
int httpResponseCode = http.GET();
if (httpResponseCode>0) {
//Serial.print("HTTP Response code: ");
//Serial.println(httpResponseCode);
String payload = http.getString();
StaticJsonDocument<200> doc;
deserializeJson(doc, payload);
String TEXT = doc["text"];
digitalWrite(2, HIGH);
if (TEXT != oldTEXT){
Serial.println(TEXT);
}
oldTEXT = TEXT;
digitalWrite(2, LOW);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
http.end();
delay(2000);
}
else {
Serial.println("WiFi Disconnected");
}
}
Micropython is another way to control the ESP32, but with python language. It supports the micropython, and therefore there is already a firmware that needs to be installed before getting started. https://docs.micropython.org/en/latest/esp32/quickref.html
Deploying the firmware -
Once you have the MicroPython firmware you need to load it onto your ESP32 device. There are two main steps to do this: first, you need to put your device in bootloader mode, and second, you need to copy across the firmware. The exact procedure for these steps is highly dependent on the particular board and you will need to refer to its documentation for details. (Reference - https://docs.micropython.org/en/latest/esp32/tutorial/intro.html#deploying-the-firmware)
Many creators get confused and take the easy way out. I'll show 2 ways to do this.
1. Doing the Developer Way
Download the latest firmware from https://micropython.org/download/esp32/And download the esptool.py from Github - Link to Download
Move all of them to the same folder. Then press Shift + Right Click Mouse > Select 'Open Powershell window here'
Now, make sure you have python on your PC (Windows)As per given in the website,
In the above command, /dev/ttyUSB0 is supposed to be the port we use. Therefore, go to Device Manager and check the port the Board is connected with. In my case, it was COM9. (refer here regarding finding port)
The code -
>>python esptool.py --port COM9 erase_flash
Now that the flash memory has been erased, let us insert the micropython firmware.
>>python esptool.py --chip esp32 --port COM9 write_flash -z 0x1000 esp32-20210902-v1.17.bin
That's it !! After a few minutes, the firmware will be installed, and you can get started with writing programs now.
To test we can write a quick print function to say “Hello World”. Press Enter to run the code. You will get Hello World as a response.
2. Doing the Beginner'sWay
First, you have to download Thonny from the https://thonny.org/
Then connect the ESP32 Dev Board to your computer. Then from Thonny go to Tools > Options and click on the Interpreter tab.
From the interpreter dropdown list, select MicroPython (ESP32). The port dropdown menu can be left to automatically detect or select the port. Click Ok to close.
Download the latest firmware (.bin) from https://micropython.org/download/esp32/
Now click 'Install or Update Firmware' > Select the Port > Select the firmware file > click Install
After successful installation, the MicroPython version will appear in the Python Shell.
To test we can write a quick print function to say “Hello World”. Press Enter to run the code. You will get Hello World as a response.
Mini Project - 3 - Using ThonnyWe will use the Internal Temperature sensor feature of the ESP32 to print it directly.
import esp32,time
tempF = esp32.raw_temperature()
tempC = (tempF - 32)*0.5555
while (True):
print("Current Temp of ESP32 is", tempC)
time.sleep(3)
Let us run a Program using Visual Studio instead of Thonny.
Using MicroPython - VS CodeGo through the Installation process over here - Click on the Link
Go through the Write a Python Program process - Click on the Link
Code -
from machine import Pin
import time
led = Pin(18, Pin.OUT)
led.value(0)
while True:
led.value(1)
print("On")
time.sleep(1)
led.value(0)
print("Off")
time.sleep(1)
Now, check the port the ESP32 DevBoard is connected with. Then enter the command to run the python file.
That's it !! You have done controlling ESP32 with TWO ways!!
Mini Project - 4Let us connect the ESP32 to any WiFi, and make HTTP requests. Remember, when using micropython, or prototype codes that are not plug-and-play, we need to reboot the board for the new instruction to load in.
Code -
import network
import urequests, time
import ujson
from machine import Pin
p0 = Pin(18, Pin.OUT)
p1 = Pin(22, Pin.OUT)
wlan = network.WLAN(network.STA_IF)
def do_connect():
wlan.active(True)
if not wlan.isconnected():
print('Connecting to Network...')
wlan.connect('wifi_name', 'wifi_password')
while not wlan.isconnected():
p1.off()
p1.on()
pass
p1.off()
p0.off()
time.sleep(0.2)
p0.on()
print('Connected (Local IP , Subnet, Gateway):')
print(wlan.ifconfig())
do_connect()
while wlan.isconnected():
try:
wlan.connect('wifi_name', 'wifi_password')
p0.off()
time.sleep(1)
res = urequests.get(url='https://dog-facts-api.herokuapp.com/api/v1/resources/dogs?number=1')
fact = ujson.loads(res.text)
print("Fact:",fact[0]['fact'])
#print(res.text)
p1.off()
p0.on()
time.sleep(5)
except Exception as e:
print("Error Occured")
time.sleep(5)
p0.off()
p1.on()
print(e)
You may face issues with the OS Error -202 or Error Occurred 202. To resolve that make sure the wifi credentials are correct, the wifi has internet services running, the correct website is put, and make sure to click on the Enable/Boot Button of ESP32. Comment Below for Doubts/Issues.
Resources available here - https://docs.micropython.org/en/latest/esp32/quickref.html
Now we have another way to control, that is with ESP-IDF.
Using ESP-IDFESP-IDF is Espressif's official IoT Development Framework for the ESP32, ESP32-S and ESP32-C series of SoCs. It provides a self-sufficient SDK for any generic application development on these platforms, using programming languages such as C and C++.
There are a couple of ways to get started with this. If we talk about manual, we can do the whole setup process and download it -
- Toolchain to compile code for ESP32
- Build tools - CMake and Ninja to build a full Application for ESP32
- ESP-IDF that essentially contains API (software libraries and source code) for ESP32 and scripts to operate the Toolchain
We will do it the EASY way, i.e. using VS Code Extension of ESP-IDF -
1. In the Extensions Tab of VS Code, search for 'Espressif IDF' and install the latest version (if receiving only welcome page use 1.2.0 version (stable) )
Wait for the installation to complete.
2. Now, Go to View > Command Palette > search 'ESP configure' and select 'ESP-IDF: Configure ESP-IDF extension'. This will redirect you to the ESP-IDF Setup Page to get started
Choose any from the above options - Express will install the ESP-IDF tools at the provided address. While Advanced lets the user manually input everything.
3. Next, if your configurations are similar by default, then directly click Install
4. Now, at this point the installation may take time. Nearly 1 hour, please remain patient throughout.
That's it!! Your installation of ESP-IDF and setup is complete !! Let us try with a sample program.
Search for 'ESP project' on the command palette (in View tab), and click on 'ESP-IDF: ShowExamples Project'.
From here, click on 'blink' for the Blink Example. And click 'Create Project using example blink'. Make sure, there are no gaps in the path names. For example -
❌ 'D:\Skill Development\Esp Dev\VSCode MP codes'
✔ 'D:\esp32\blink\
Next, go to folder 'main' > 'blink.c'. In which, the code is needed to be altered to see the blinking with ESP32.
#define BLINK_GPIO 18
Only change the definition of BLINK_GPIO
pin to wherever your LED is present.
Now, in the below section, you'll see Build, Flash, and Monitor buttons.
1. Click on the Build button 🏗 and wait for the process to end. This basically builds the whole program to one folder and waits to be flashed to the device.
2. Next, select the port on the left of this section. (maybe as COM6) And then Flash button ⚡
With that, the program should run well. Click on the Monitor button 💻 so that, the changes are visible virtually,
Now that we have come this far, there are a few other features as well, which you can find in the below link -
https://docs.espressif.com/projects/esp-idf/en/latest/esp32/get-started/index.html
These features were made much easier on the IDE (VS Code). You can directly access the configuration menu without entering the command idf.py menuconfig
or set the device as target using idf.py
set-target esp32
These commands are directly available on the below bar when using this extension.
The ⚙ icon is the menuconfig
command here.
That's it !! You are all set up and ready to use the IDF made by ESP.
Mini Project - 5Connect the ESP32 device to the WiFi and then receive HTTP requests. (We shall see this on Arduino in here - https://www.hackster.io/akshayansinha/webservers-on-esp32-edffef)
1. Search for 'ESP project' on the command palette (in View tab), and click on 'ESP-IDF: ShowExamples Project'.
2. Look for protocols > https_server > simple
Click on 'Create project.... ' and you have the project file READY !!
3. Next, open the Configuration Menu (menuconfig) > Then go to Example Configuration/Custom Configuration > Enter the WiFi SSID and Password.
4. Now when you flash the project, it will create a webserver on the ESP32 and when you Monitor the Output, you'll see the IP Address of the ESP32.
Mini Project - 6Connect the ESP32 device to the WiFi and then make HTTP requests. It will make similar requests as the random JSON on previous project and print the same on the output monitor.
(Let's keep this one for you guys to Complete it) 😉
--------------------------------------------------------------------------------------------------------------------
I hope you all had a Great time Learning so much about the ESP32 and its possibilities. We shall look into more of such Projects right on my Hackster Profile!
Adios.
Comments