Keyestudio ESP32 Sensor Kit Guide
Keyestudio ESP32 Sensor Kit Guide
1. Description ..............................................................................................................................................................4
2. Kit ...............................................................................................................................................................................5
www.keyestudio.com
keyestudio
Project 11: Photo Interrupter ....................................................................................................................... 59
www.keyestudio.com
keyestudio
Project 33: Rotary Encoder ......................................................................................................................... 163
www.keyestudio.com
keyestudio
Project 54: Smoke Alarm .............................................................................................................................264
1. Description
Dupont wires.
The 42 sensors and modules are fully compatible with the ESP32
Expansion Board. You only need to stack the ESP32 mainboard onto the
www.keyestudio.com
keyestudio
ESP32 Expansion Board, and hook up them with Dupont wires, which is
C), schematic diagrams, wiring methods and test code are included.
2. Kit
ESP32mainboard)
Keyestudio Common
2 1
Cathode RGB Module
www.keyestudio.com
keyestudio
4 Keyestudio Active Buzzer 1
Keyestudio Button
6 1
Module
Keyestudio Obstacle
9 1
Avoidance Sensor
www.keyestudio.com
keyestudio
Keyestudio NTC-MF52AT
11 1
Thermistor
12 Keyestudio Photoresistor 1
Keyestudio
14 1
Rotary Potentiometer
15 Keyestudio IR Receiver 1
Keyestudio Rotary
17 1
Encoder Module
Keyestudio Joystick
18 1
Module
www.keyestudio.com
keyestudio
Keyestudio HT16K33 8X8
19 1
Dot Matrix Module
Keyestudio TM1650
20 1
4-Digit Tube Display
Keyestudio Thin-film
21 1
Pressure Sensor
Keyestudio SR01
23 1
Ultrasonic Sensor
24 9G 90° Servo 1
Keyestudio Capacitive
25 1
Sensor
Keyestudio Photo
26 1
Interrupter
www.keyestudio.com
keyestudio
27 Keyestudio Hall Sensor 1
Keyestudio XHT11
31 Temperature and 1
Humidity Sensor
Keyestudio 18B20
32 1
Temperature Sensor
www.keyestudio.com
keyestudio
34 Fan 1
Keyestudio Collision
39 1
Sensor
Keyestudio Alcohol
40 1
Sensor
www.keyestudio.com
keyestudio
Kyestudio
41 LCD_128X32_DOT 1
Module
5-Channel AD Button
42 1
Module
DXL345 Acceleration
43 1
Module
Keyestudio ESP32
44 1
Development Board
Keyestudio ESP32-IO
45 1
Expansion Board
Keyestudio IR Remote
46 1
Control
47 USB Cable 1
www.keyestudio.com
keyestudio
48 F-F Dupont Wire 1
49 White Card 1
51 Battery Holder 1
www.keyestudio.com
keyestudio
When we get the kit, we can see that there are 42 sensors/modules in the
the ESP32 mainboard and the ESP32 Expansion Board using wirings. Then
run the corresponding test code to test the function of each sensor
the kits.
www.keyestudio.com
keyestudio
Note : When connecting the module/sensor wirings in the projects, the
more, do not misconnect the power supply and signal pin, otherwise
modules/sensors.
1. Overview
For ESP32 beginners, we will start with some simple things. In this project,
project.
2. Components
3. Wiring Diagram:
www.keyestudio.com
keyestudio
computer.
4. Test Code
//*************************************************************************************
/*
* Filename : Hello World
* Description : Enter the letter R,and the serial port displays"Hello World".
* Auther :http//www.keyestudio.com
*/
char val;// defines variable "val"
void setup()
{
Serial.begin(9600);// sets baudrate to 9600
}
void loop()
{
if (Serial.available() > 0) {
val=Serial.read();// reads symbols assigns to "val"
if(val=='R')// checks input for the letter "R"
{ // if so,
Serial.println("Hello World!");// shows “Hello World !”.
}
}
}
//*************************************************************************************
www.keyestudio.com
keyestudio
www.keyestudio.com
keyestudio
Note:For macOS users, if the upload fails, set the baud rate to 115200
before clicking .
www.keyestudio.com
keyestudio
www.keyestudio.com
keyestudio
Note: If the uploading code fails, you can press and hold the Boot button
on the ESP32 after clicking and release the Boot button after the
appears. , as shown
below:
www.keyestudio.com
keyestudio
5. Test Result
www.keyestudio.com
keyestudio
click ,set the baud rate to 9600,enter the letter“R”,click“Send”,
1. Overview
control. If you want to light up the LED, you just need to make a certain
www.keyestudio.com
keyestudio
In the project, we will control the high and low level of the signal end S
2. Working Principle
The left one is wrong wiring-up diagram. Why? Theoretically, when the S
terminal outputs high levels, the LED will receive the voltage and light up.
LED brighten.
The right one is correct wiring-up diagram. GND and VCC are powered up.
When the S terminal is a high level, the triode Q1 will be connected and
LED will light up(note: current passes through LED and R3 to reach GND
by VCC not IO ports). Conversely, when the S terminal is a low level, the
3. Components
www.keyestudio.com
keyestudio
Keyestudio
ESP32 3P Micro
ESP32
Purple LED
Expansion Dupont USB
Board*1
Module*1
Board*1 Wire*1 Cable*1
4. Wiring Diagram
5. Test Code
www.keyestudio.com
keyestudio
//*************************************************************************************
/*
* Filename : Blink
* Description : led Flashing 1 s
* Auther : http://www.keyestudio.com
*/
int ledPin = 0; //Define LED pin connection to GPIO0
void setup() {
pinMode(ledPin, OUTPUT);//Set mode to output
}
void loop() {
digitalWrite(ledPin, HIGH); //Output high level, turn on led
delay(1000);//Delay 1000 ms
digitalWrite(ledPin, LOW); //Output low level,turn off led
delay(1000);//Delay 1000 ms
}
//*************************************************************************************
6. Code Explanation
3. Setup() executes once, while loop() executes all the time. Delay
www.keyestudio.com
keyestudio
Firstly, we connect the module signal to ledPIN, namely GP0, and set it to
a high level to light the LEDs on the module. Then delay 1000 ms,
controlling the LEDs on the module light up for 1s and off for 1s to
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,we will see that the LED in the circuit will
flash alternately.
Note: If the uploading code fails, you can press and hold the Boot button
on the ESP32 after clicking and release the Boot button after the
appears. , as shown
below:
www.keyestudio.com
keyestudio
Project 3: Traffic Lights Module
1. Overview
In this lesson, we will learn how to control multiple LED lights and
In this kit, we will use the traffic light module to simulate the traffic light.
2. Working Principle
we only need to control three separated LEDs. Output high levels to the
www.keyestudio.com
keyestudio
3. Components
Keyestudio
ESP32 5P Micro
ESP32 DIY Traffic
Expansion Dupont USB
Board*1 Lights
Board*1 Wire*1 Cable*1
Module*1
4. Wiring Diagram
www.keyestudio.com
keyestudio
5. Test Code
//*************************************************************************************
/*
* Filename : Traffic_Light
* Description : Simulated traffic lights
* Auther : http://www.keyestudio.com
*/
int redPin = 15; //Red LED connected to GPIO15
int yellowPin = 2; //Yellow LED connected to GPIO2
int greenPin = 0; //Green LED connected to GPIO0
void setup() {
//LED interfaces are set to output mode
pinMode(greenPin, OUTPUT);
pinMode(yellowPin, OUTPUT);
pinMode(redPin, OUTPUT);
}
void loop() {
www.keyestudio.com
keyestudio
digitalWrite(greenPin, HIGH); //Lighting green LED
delay(5000); //Delay for 5 seconds
digitalWrite(greenPin, LOW); //Turn off green LEDS
for (int i = 1; i <= 3; i = i + 1) { //run three times
digitalWrite(yellowPin, HIGH); //Lighting yellow LED
delay(500); //Delay for 0.5 seconds
digitalWrite(yellowPin, LOW); //Turn off yellow LED
delay(500); //Delay for 0.5 seconds
}
digitalWrite(redPin, HIGH); //Lighting red LED
delay(5000); //Delay5s
digitalWrite(redPin, LOW); //Turn off red LED
}
//*************************************************************************************
6. Code Explanation
each time. When i<0, exit the for() loop and execute 256 times
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,we will see that the green LED will be on for
5s then off, the yellow LED will flash for 3s then go off and the red one
will be on for 5s then off, the three LED modules will simulate the
www.keyestudio.com
keyestudio
1. Description
Lasers are widely used to cut, weld, surface treat, and more on specific
materials. The energy of the laser is very high. The toy laser pointer may
cause glare to the human eye, and it may cause retinal damage for a long
time. my country also prohibits the use of laser to illuminate the aircraft.
2. Working Principle
The laser head sensor module is mainly composed of a laser head with a
can see the circuit schematic diagram of this module which is very similar
to the LED we have learned. They are all driven by triodes. A high-level
www.keyestudio.com
keyestudio
digital signal is directly input at the signal end, then the sensor will start
3. Components
www.keyestudio.com
keyestudio
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : Laser sensor
* Description : Laser light flashing
* Auther : http://www.keyestudio.com
*/
int laserPin = 0; //Define the laser pin as GPIO 0
void setup() {
pinMode(laserPin, OUTPUT);//Define laser pin as output mode
}
void loop() {
digitalWrite(laserPin, HIGH); //Open the laser
delay(2000); //Delay 2 seconds
digitalWrite(laserPin, LOW); //Shut down the laser
delay(2000); //Delay 2 seconds
}
//*************************************************************************************
www.keyestudio.com
keyestudio
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,we will see that the laser module will emit
red laser signals for 2 seconds and stop emitting signals for 2 seconds on
a cycle.
1. Overview
www.keyestudio.com
keyestudio
lung breathing in and out. So how to control LED’s brightness? We need
2. Components
ESP32 Keyestudio
ESP32 3P Dupont MicroUSB
Expansion Purple LED
Board*1 Wire*1 Cable*1
Board*1 Module*1
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************
/*
* Filename : Breathing Led
* Description : Make led light fade in and out, just like breathing.
* Auther : http//www.keyestudio.com
*/
#define PIN_LED 0 //define the led pin
#define CHN 0 //define the pwm channel
#define FRQ 1000 //define the pwm frequency
#define PWM_BIT 8 //define the pwm precision
void setup() {
ledcSetup(CHN, FRQ, PWM_BIT); //setup pwm channel
ledcAttachPin(PIN_LED, CHN); //attach the led pin to pwm channel
}
void loop() {
for (int i = 0; i < 255; i++) { //make light fade in
ledcWrite(CHN, i);
delay(10);
}
for (int i = 255; i > -1; i--) { //make light fade out
ledcWrite(CHN, i);
delay(10);
}
}
//*************************************************************************************
5.Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,we will see that the LED on the module
www.keyestudio.com
keyestudio
Project 6: RGB Module
1. Overview
foggy common cathode LED. We connect the RGB module to the PWM
port of MCU and the other pin to GND(for common anode RGB, the rest
Digital control is used to generate square waves with different duty cycles
(a signal that constantly switches between high and low levels) to control
the analog output.In general, the input voltages of ports are 0V and 5V.
www.keyestudio.com
keyestudio
cannot change resistors constantly. For this reason, we resort to PWM.
For Arduino digital port voltage outputs, there are only LOW and HIGH
You can define LOW as“0”and HIGH as“1’, and let the Arduino output five
This process can be likened to showing a movie. The movie we watch are
2. Working Principle
www.keyestudio.com
keyestudio
For our experiment, we will control the RGB module to display different
3. Components
Keyestudio
ESP32 Common
ESP32 4P Dupont Micro USB
Expansion Cathode
Board*1 Wire*1 Cable*1
Board*1 RGB
Module *1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************
/*
* Filename : RGB LED
* Description : Use RGBLED to show random color.
* Auther : http//www.keyestudio.com
*/
int ledPins[] = {0, 2, 15}; //define red, green, blue led pins
const byte chns[] = {0, 1, 2}; //define the pwm channels
int red, green, blue;
void setup() {
for (int i = 0; i < 3; i++) { //setup the pwm channels,1KHz,8bit
ledcSetup(chns[i], 1000, 8);
ledcAttachPin(ledPins[i], chns[i]);
}
}
void loop() {
red = random(0, 256);
www.keyestudio.com
keyestudio
green = random(0, 256);
blue = random(0, 256);
setColor(red, green, blue);
delay(200);
}
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,we will see that the RGB LED on the module
1. Overview
www.keyestudio.com
keyestudio
In this kit, there is a Keyestudio single-channel button module, which
mainly uses a tact switch and comes with a yellow button cap.
will read the high level (3.3V) and low level (0V).
reading the high and low level of the S terminal on the sensor.
2. Working Principle
The button module has four pins. The pin 1 is connected to the pin 3 and
the pin 2 is linked with the pin 4. When the button is not pressed, they are
disconnected. Yet, when the button is pressed, they are connected. If the
www.keyestudio.com
keyestudio
3. Components
ESP32 Keyestudio 3P
ESP32 Micro USB
Expansion DIY Button Dupont
Board*1 Cable*1
Board*1 Module*1 Wire*1
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : button
* Description : Read key value
www.keyestudio.com
keyestudio
* Auther : http://www.keyestudio.com
*/
int val = 0; //Useto store key values
int button = 15; //The pin of the button is connected to GP15
void setup() {
Serial.begin(9600); //Start the serial port monitor and set baud rate to 9600
pinMode(button, INPUT); //Set key pin to input mode
}
void loop() {
val = digitalRead(button); //Read the value of the key and assign it to the variable val
Serial.print(val); //Print it on the serial port
if (val == 0) { //Press the key to read the low level and print the press related information
Serial.print(" ");
Serial.println("Press the botton");
delay(100);
}
6. Code Explanation
and INPUT.
rate to 9600.
www.keyestudio.com
keyestudio
3. digitalRead(button): read the digital level of the button(HIGH or LOW).
If this pin is not connected to pins, the digitalRead() will return HIGH or
LOW.
4. if..else..:if the logic behind () is true, execute the code of (); otherwise
5. If the button is pressed, the signal end is low level, GP15 is low level
and Val is 0. Then the monitor will show the corresponding value and
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600. The serial monitor will display the corresponding data and
characters. When the button is pressed, val is 0, the monitor will show
“Press the button”;when the button is released, val is 1,the monitor will
www.keyestudio.com
keyestudio
1. Description
button, and its function is to replace the traditional button with a variable
www.keyestudio.com
keyestudio
area button. When we power on, the sensor needs about 0.5 seconds to
stabilize.
Do not touch the keys during this time period. At this time, all functions
2. Working Principle
When our fingers touch the module, the signal S outputs high levels, the
red LED on the module flashes. We can determine if the button is pressed
3. Required Components
www.keyestudio.com
keyestudio
Keyestudio
ESP32
ESP32 DIY 3P Dupont Micro USB
Expansion
Board*1 Capacitive Wire*1 Cable*1
Board*1
Module*1
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : Touch sensor
* Description : Reading touch value
* Auther : http://www.keyestudio.com
*/
int val = 0;
int touch = 15; //The key of PIN
www.keyestudio.com
keyestudio
void setup() {
Serial.begin(9600);//Baud rate is 9600
pinMode(touch, INPUT);//Setting input mode
}
void loop() {
val = digitalRead(touch);//Read the value of the key
Serial.print(val);//Print out key values
if (val == 1) {//Press for high level
Serial.print(" ");
Serial.println("Press the button");
delay(100);
}
else {//Release to low level
Serial.print(" ");
Serial.println("Loosen the button");
delay(100);
}
}
//*************************************************************************************
6. Code Explanation
When we touch the sensor, the Shell monitor will show “ Pressed the
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600.
The serial monitor will display the corresponding data and characters.
when the button is pressed, the red LED lights up and val is 1. Then the
www.keyestudio.com
keyestudio
shell shows “Pressed the button!”; if the button is released, the red LED
1. Overview
www.keyestudio.com
keyestudio
determine whether there is an obstacle by reading the high and low level
2. Working Principle
NE555 circuit provides IR signals with frequency to the emitter TX, then
When the receiver RX meets the weak signals reflected back, the
receiving pin will output high levels, which indicates the obstacle is far
away. On the contrary, it the reflected signals are stronger, low levels will
www.keyestudio.com
keyestudio
3. Components
Keyestudio
ESP32 DIY
ESP32 3P Dupont Micro USB
Expansion Obstacle
Board*1 Wire*1 Cable*1
Board*1 Avoidance
Sensor*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//*************************************************************************************
/*
* Filename : obstacle avoidance sensor
* Description : Reading the obstacle avoidance value
* Auther : http://www.keyestudio.com
*/
int val = 0;
void setup() {
Serial.begin(9600);//Set baud rate to 9600
pinMode(15, INPUT);//Set pin GP15 to input mode
}
void loop() {
val = digitalRead(15);//Read digital level
Serial.print(val);//Print the level signal read
if (val == 0) {//Obstruction detected
Serial.print(" ");
Serial.println("There are obstacles");
delay(100);
www.keyestudio.com
keyestudio
}
else {//No obstructions detected
Serial.print(" ");
Serial.println("All going well");
delay(100);
}
}
//*************************************************************************************
6. Code Explanation
Note:
Upload the test code and wire up according to the connection diagram.
distance.
the frequency will increase. Make the S LED at the critical point of ON and
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600.
www.keyestudio.com
keyestudio
The serial monitor will display the corresponding data and characters.
When the sensor detects the obstacle, the val is 0, the monitor will show
“There are obstacles”; if the obstacle is not detected, the val is 1,“All
www.keyestudio.com
keyestudio
Project 10: Line Tracking Sensor
1. Description
tracking sensor which mainly uses a TCRT5000 reflective black and white
In the experiment, we judge the color (black and white) of the object
detected by the sensor by reading the high and low levels of the S
terminal on the module; and display the test results on the shell.
2. Working Principle
high levels; when white object is detected, the signal terminal is low level;
www.keyestudio.com
keyestudio
its detection height is 0-3cm. We can adjust the sensitivity by rotating the
sensitivity is best when the red LED on the sensor is at the critical point
3. Required Components
Keyestudio
Sensor*1
www.keyestudio.com
keyestudio
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : line tracking
* Description : Reading the tracking sensor value
* Auther : http://www.keyestudio.com
*/
int val = 0;
void setup() {
Serial.begin(9600);//Set baud rate to 9600
pinMode(15, INPUT);//Sets sensor pin to input mode
}
void loop() {
val = digitalRead(15);//Read the digital level output by the patrol sensor
Serial.print(val);//Serial port print value
if (val == 0) {//White val is 0 detected
Serial.print(" ");
Serial.println("White");
www.keyestudio.com
keyestudio
delay(100);
}
else {//Black val is 1 detected
Serial.print(" ");
Serial.println("Black");
delay(100);
}
}
//*************************************************************************************
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600.
The serial monitor will display the corresponding data and characters.
when the sensor doesn’t detect an object or detects a black object, the
val is 1, and the monitor will display "1 Black" ; when a white object (can
reflect light) is detected, the val is 0, and the monitor will display "0
White" ;
www.keyestudio.com
keyestudio
1. Description
www.keyestudio.com
keyestudio
2. Working Principle
When the paper is put in the slot, C is connected with VCC and the signal
end S of the sensor are high levels; then the red LED will be off. Otherwise,
3. Required Components
Keyestudio
ESP32 Expansion 3P Dupont Micro USB
ESP32 Board*1 DIY Photo
Board*1 Wire*1 Cable*1
Interrupter*1
www.keyestudio.com
keyestudio
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : Photo_Interrupt
* Description : Light snap sensor counting
* Auther : http://www.keyestudio.com
*/
int PushCounter = 0; //The count variable is assigned an initial value of 0
int State = 0; //Store the current state of the sensor output
int lastState = 0; //Stores the state of the last sensor output
void setup() {
Serial.begin(9600);//Set the baud rate to 9600
pinMode(15, INPUT);//Set the light snap sensor pin to input mode
}
void loop() {
State = digitalRead(15);//Read current state
www.keyestudio.com
keyestudio
if (State != lastState) {//If the state is different from the last read
if (State == 1) {//block the light
PushCounter = PushCounter + 1;//Count + 1
Serial.println(PushCounter);//Print count
}
}
lastState = State;//Update state
}
//*************************************************************************************
6. Code Explanation
Logic setting:
Set PushCounter to 0
Set lastState to 0
Set PushCounter to
lastState is 0 , State
when an object PushCounter+1
turns into 1; lastState
enters the slot print the value of
turns into 1
PushCounter
leaves the slot are not equal,lastState Don’t print the value of
www.keyestudio.com
keyestudio
through this slot are not equal,lastState print the value of
lastState is 1 , State
When the PushCounter doesn ’ t
turns into 0,two data
object leaves change;Don’t print the
are not equal lastState
this slot again PushCounter value
turns into 0
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600.
The serial monitor will display the PushCounter data. Every time when the
object passes through the slot of the sensor, the PushCounter data will
www.keyestudio.com
keyestudio
1. Overview
www.keyestudio.com
keyestudio
In this kit, there is a Keyestudio tilt sensor. The tilt switch can output
is a ball inside. When the switch is higher than the horizontal level, the
switch is turned on, and when it is lower than the horizontal level, the
switch is turned off. This tilt module can be used for tilt detection, alarm
or other detection.
2. Working Principle
The working principle is pretty simple. When pin 1 and 2 of the ball
switch P1 are connected, the signal S is low level and the red LED will light
up; when they are disconnected, the pin will be pulled up by the 4.7K R1
3. Components
www.keyestudio.com
keyestudio
ESP32 Keyestudio
ESP32 3P Dupont Micro USB
Expansion Tilt
Board*1 Wire*1 Cable*1
Board*1 Sensor*1
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : Tilt switch
www.keyestudio.com
keyestudio
* Description : Reading the tilt sensor value
* Auther :http://www.keyestudio.com
*/
int val; //Store the level value output by the tilt sensor
void setup() {
Serial.begin(9600);
pinMode(15, INPUT); //Connect the pin of the tilt sensor to GP15 and set GP15 to the input mode
}
void loop() {
val = digitalRead(15); //Read module level signal
Serial.println(val); //Newline print
delay(100); //Delay for 100 ms
}
//*************************************************************************************
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600. Make the tilt module incline to one side, the red LED on the
module will be off and the monitor will display“1”. In contrast, if you
make it incline the other side, the red LED will light up and the monitor
will display“0”.
www.keyestudio.com
keyestudio
1. Description
The collision sensor uses a tact switch. This sensor is often used as a limit
www.keyestudio.com
keyestudio
shrapnel is pressed down by reading the high and low levels of the S
terminal on the module; and, we display the test results in the shell.
2. Working Principle
It mainly uses a tact switch. When the shrapnel of the tact switch is
pressed, 2 and 3 are connected, the signal terminal S is low level, and the
red LED on the module lights up; when the touch switch is not pressed, 2
and 3 are not connected, and 3 is pulled up to a high level by the 4.7K
resistor R1, that is, the sensor signal terminal S is a high level, and the
3. Components Required
www.keyestudio.com
keyestudio
ESP32 Keyestudio
ESP32 3P Dupont Micro USB
Expansion Collision
Board*1 Wire*1 Cable*1
Board*1 Sensor*1
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : collision sensor
* Description : Reading the value of the collision sensor
* Auther : http://www.keyestudio.com
*/
int val = 0;
void setup() {
Serial.begin(9600);//Set baud rate to 9600
pinMode(15, INPUT);//Set collision sensor pin 15 to input mode
www.keyestudio.com
keyestudio
}
void loop() {
val = digitalRead(15);//Read the value of the collision sensor
Serial.print(val);//Newline print
if (val == 0) {//Collision val is 0
Serial.print(" ");
Serial.println("The end of his!");
delay(100);
}
else {// No collision val is 1
Serial.print(" ");
Serial.println("All going well");
delay(100);
}
}
//*************************************************************************************
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600. The serial monitor will display the corresponding data and
characters.
In the experiment, when the shrapnel on the sensor is pressed down, val
is 0, the red LED of the module is on, and "0 The end of his!" is printed;
when the shrapnel is released, the val is 1, the red LED of the module is
off, and "1 All going well" is printed. !" character, as shown below.
www.keyestudio.com
keyestudio
1.Description
In this kit, there is a Hall sensor which mainly adopts a A3144 linear Hall
www.keyestudio.com
keyestudio
voltage generator, a differential amplifier, a Schmitt trigger, a
In the experiment, we use the Hall sensor to detect the magnetic field
2. Working Principle
When the sensor detects no magnetic field or a north pole magnetic field,
the signal terminal will be high level; when it senses a south pole
magnetic field, the signal terminal will be low levels. The stronger the
3. Required Components
www.keyestudio.com
keyestudio
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : Hall magnetic
* Description : Reading the value of hall magnetic sensor
* Auther : http://www.keyestudio.com
*/
int val = 0;
int hallPin = 15; //Hall sensor pin is connected to GPIO15
void setup() {
Serial.begin(9600);//Set baud rate to 9600
pinMode(hallPin, INPUT);//Set pin to input mode
}
void loop() {
val = digitalRead(hallPin);//Read the level value of hall sensor
Serial.print(val);//Print val
www.keyestudio.com
keyestudio
if (val == 0) {//There is a South Pole magnetic field
Serial.println(" The magnetic field at the South Pole!");
}
else {//If not
Serial.println(" Just be all normal!");
}
}
//*************************************************************************************
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600. when the sensor detects no magnetic fields or the north
pole magnetic field, the monitor l will show“1 Just be all normal!”and
the LED on the sensor will be off; When it detects the south pole
magnetic field,“0 The magnetic field at the South Pole!”and the LED on
www.keyestudio.com
keyestudio
Project 15: Reed Switch Module
1. Overview
In this kit, there is a Keyestudio reed switch module, which mainly uses a
The reed switch is the abbreviation of the dry reed switch. It is a passive
It has the advantages of simple structure, small size and easy control.
Its shell is a sealed glass tube with two iron elastic reed electric plates.
near the module by reading the high and low level of the S terminal on
www.keyestudio.com
keyestudio
2. Working Principle
In normal conditions, the glass tube in the two reeds made of special
tube, in the role of the magnetic field lines, the pipe within the two reeds
are magnetized to attract each other in contact, the reed will suck
communication.
flexibility and separate, the line is disconnected. The sensor uses this
3. Components
www.keyestudio.com
keyestudio
Keyestudio DIY
ESP32 Expansion Reed Switch 3P Dupont Micro USB
ESP32 Board*1
Board*1 Module*1 Wire*1 Cable*1
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : Reed Switch
* Description : Read the value of the reed sensor
* Auther : http://www.keyestudio.com
www.keyestudio.com
keyestudio
*/
int val = 0;
int reedPin = 15; //Define dry reed module signal pin connected to GPIO15
void setup() {
Serial.begin(9600);//Set baud rate to 9600
pinMode(reedPin, INPUT);//Set mode to input
}
void loop() {
val = digitalRead(reedPin);//Read digital level
Serial.print(val);//Serial port shows up
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600. The serial monitor will display the corresponding data and
characters.
When the sensor detects a magnetic field, val is 0 and the red LED of the
magnetic field is detected, val is 1, and the LED on the module goes out,
www.keyestudio.com
keyestudio
"1 There is no magnetic field" will be shown, as shown below.
1. Overview
In this kit, there is a Keyestudio PIR motion sensor, which mainly uses an
www.keyestudio.com
keyestudio
based on pyroelectric effect, which can detect infrared rays emitted by
humans or animals, and the Fresnel lens can make the sensor's detection
reading the high and low levels of the S terminal on the module. The
2. Working Principle
the sensor outputs low level. At this time, the LED on the module will light
up and the MOS tube Q1 will be connected and the signal terminal S will
sensor outputs a high level. Then LED on the module will go off, the MOS
tube Q1 is disconnected and the signal terminal S will detect high levels.
www.keyestudio.com
keyestudio
3. Required Components
Keyestudio DIY
ESP32 Expansion 3P Dupont Micro USB
ESP32 Board*1 PIR Motion
Board*1 Wire*1 Cable*1
Sensor*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//*************************************************************************************
/*
* Filename : PIR motion
* Description : Reading the value of the human body infrared sensor
* Auther : http://www.keyestudio.com
*/
int val = 0;
int pirPin = 15; //The pin of PIR motion sensor is defined as GPIO15
void setup() {
Serial.begin(9600); //Set baud rate to 9600
pinMode(pirPin, INPUT); //Set the sensor to input mode
}
void loop() {
val = digitalRead(pirPin); //Read the sensor value
Serial.print(val);//Print val value
if (val == 1) {//There is movement nearby, output high level
Serial.print(" ");
Serial.println("Some body is in this area!");
www.keyestudio.com
keyestudio
delay(100);
}
else {//If no movement nearby, output low level
Serial.print(" ");
Serial.println("No one!");
delay(100);
}
}
//*************************************************************************************
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,open the serial monitor and set the baud
rate to 9600. The serial monitor will display the corresponding data and
characters.
When the sensor detects someone nearby, value is 1, the LED will go off
and the monitor will show“1 Somebody is in this area!”. In contrast, the
www.keyestudio.com
keyestudio
1. Overview
experiment, we control the active buzzer to emit sounds. Since it has its
www.keyestudio.com
keyestudio
own oscillating circuit, the buzzer will automatically sound if given large
voltage.
2. Working Principle
R2 and another port is linked with a NPN triode Q1. So, if this triode Q1 is
level, the triode Q1 will be connected.If the base electrode is pulled down
When we output a high level from the IO port to the triode, the buzzer
will emit sounds; if outputting low levels, the buzzer won’t emit sounds.
3. Components
www.keyestudio.com
keyestudio
Keyestudio
ESP32 Expansion 3P Dupont Micro USB
ESP32 Board*1 Active
Board*1 Wire*1 Cable*1
Buzzer*1
4. Connection Diagram
5. Test Code
//*************************************************************************************
/*
* Filename : Active buzzer
* Description : An active buzzer produces sound
* Auther : http://www.keyestudio.com
*/
www.keyestudio.com
keyestudio
int buzzer = 15; //Define buzzer receiver pin GPIO15
void setup() {
pinMode(buzzer, OUTPUT);//Set the output mode
}
void loop() {
digitalWrite(buzzer, HIGH); //sound production
delay(1000);
digitalWrite(buzzer, LOW); //Stop the sound
delay(1000);
}
//*************************************************************************************
6. Code Explanation
In the experiment, we set the pin to GPIO15. When setting to high, the
active buzzer will beep; when setting to low, the active buzzer will stop
emitting sounds.
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. The active buzzer will emit sound for 1
www.keyestudio.com
keyestudio
Project 18: 8002b Audio Power Amplifier
1. Overview
In this kit, there is a Keyestudio 8002b audio power amplifier. The main
The main function of this module is: it can amplify the output audio
2. Working Principle
In fact, it is similar to a passive buzzer. The active buzzer has its own
www.keyestudio.com
keyestudio
oscillation source.Yet, the passive buzzer does not have internal
different frequencies.
3. Components
Keyestudio
ESP32 Expansion 8002b Audio 3P Dupont Micro USB
ESP32 Board*1
Board*1 Power Wire*1 Cable*1
Amplifier*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************
/*
* Filename : Passive Buzzer
* Description : Passive Buzzer sounds the alarm.
* Auther : http//www.keyestudio.com
*/
#define LEDC_CHANNEL_0 0
#define LEDC_TIMER_13_BIT 13
#define BUZZER_PIN 15
www.keyestudio.com
keyestudio
//Create a musical melody list, Super Mario
int melody[] = {330, 330, 330, 262, 330, 392, 196, 262, 196, 165, 220, 247, 233, 220, 196, 330, 392, 440,
349, 392, 330, 262, 294, 247, 262, 196, 165, 220, 247, 233, 220, 196, 330, 392,440, 349, 392, 330, 262,
294, 247, 392, 370, 330, 311, 330, 208, 220, 262, 220, 262,
294, 392, 370, 330, 311, 330, 523, 523, 523, 392, 370, 330, 311, 330, 208, 220, 262,220, 262, 294, 311,
294, 262, 262, 262, 262, 262, 294, 330, 262, 220, 196, 262, 262,262, 262, 294, 330, 262, 262, 262, 262,
294, 330, 262, 220, 196};
int noteDurations[] =
{8,4,4,8,4,2,2,3,3,3,4,4,8,4,8,8,8,4,8,4,3,8,8,3,3,3,3,4,4,8,4,8,8,8,4,8,4,3,8,8,2,8,8,8,4,4,8,8,4,8,8
,3,8,8,8,4,4,4,8,2,8,8,8,4,4,8,8,4,8,8,3,3,3,1,8,4,4,8,4,8,4,8,2,8,4,4,8,4,1,8,4,4,8,4,8,4,8,2};
void setup() {
pinMode(BUZZER_PIN, OUTPUT); // Set the buzzer to output mode
}
void loop() {
{
noteDuration = 800/noteDurations[i];
ledcAttachPin(BUZZER_PIN, LEDC_CHANNEL_0);
ledcWrite(LEDC_CHANNEL_0, 50);
6. Test Result
www.keyestudio.com
keyestudio
Connect the wires according to the experimental wiring diagram, compile
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on,then the power amplifier module will emit
1. Description
The 130 motor driver module is compatible with servo motors, which has
H-bridge driver chip for DC motor solutions. In addition, this chip has low
www.keyestudio.com
keyestudio
outputting the voltage directions of the two signal terminals IN+ and IN-
2. Working Principle
The chip is used to help drive the motor. We can’t drive it with a triode
the motor rotate. Just apply voltage to both ends of the motor. The
the rated voltage, the higher the voltage, the faster the motor rotates; on
the contrary, the lower the voltage, the slower the motor rotates, or even
unable to rotate.
So we can use the PWM port to control the speed of the motor. We
haven't learned PWM here, so we use the high and low levels to control
3. Required Components
www.keyestudio.com
keyestudio
Note: the motor is separated with its fan, you need to assemble it first.
4. Connection Diagram
Board
G G
V 5V
IN+ IO15
IN- IO4
www.keyestudio.com
keyestudio
5. Test Code
//*************************************************************************************
/*
* Filename : 130DC Fan motor
* Description : Motor positive and negative rotation
* Auther : http://www.keyestudio.com
*/
//Define two pins interfaces of the motor, respectively 15 and 4
int INA = 15; //INA corresponds to IN+
int INB = 4; //INB corresponds to IN-
void setup() {
//Set the motor pins as output
pinMode(INA, OUTPUT);
pinMode(INB, OUTPUT);
}
void loop() {
//Turn counterclockwise
digitalWrite(INA, HIGH);
digitalWrite(INB, LOW);
delay(2000);
//stop
digitalWrite(INA, LOW);
digitalWrite(INB, LOW);
delay(1000);
//clockwise rotation
www.keyestudio.com
keyestudio
digitalWrite(INA, LOW);
digitalWrite(INB, HIGH);
delay(2000);
//stop
digitalWrite(INA, LOW);
digitalWrite(INB, LOW);
delay(1000);
}
//*************************************************************************************
6. Code Explanation
Set pins to GPIO4、GPIO15, when the pin GPIO4 outputs low levels and
the pin GPIO15 outputs high levels, the motor will rotate
counterclockwise; when both pins are set to low, the motor stops
rotating.
7. Test Result
power on. Switch the DIP switch ON the ESP32 expansion board to the
ON end, after powering on, compile and upload the code to the ESP32.
seconds, stop for 1 second and clockwise for 2 seconds and stop for 1
www.keyestudio.com
keyestudio
Project 20: Potentiometer
1. Overview
The digital IO ports can read the voltage value between 0 and 3.3V and
the module only outputs high levels. However, the analog sensor can
read the voltage value through 16 ADC analog ports on the ESP32 board.
2. Working Principle
www.keyestudio.com
keyestudio
ADC : The more bits an ADC has, the denser the partitioning of the
www.keyestudio.com
keyestudio
he output voltage value.
ADC on ESP32:
signals. GPIO pin serial numbers and analog pin definitions are shown
below:
ADC0 GPIO 36
ADC3 GPIO 39
ADC4 GPIO 32
ADC5 GPIO33
ADC6 GPIO34
ADC7 GPIO 35
ADC10 GPIO 4
ADC11 GPIO0
ADC12 GPIO2
ADC13 GPIO15
ADC14 GPIO13
ADC15 GPIO 12
ADC16 GPIO 14
www.keyestudio.com
keyestudio
ADC17 GPIO27
ADC18 GPIO25
ADC19 GPIO26
DAC on ESP32:
DAC1 GPIO25
DAC2 GPIO26
3. Components
Keyestudio
ESP32 Expansion 3P Dupont Micro USB
ESP32 Board*1 Rotary
Board*1 Wire*1 Cable*1
Potentiometer*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : Rotary_potentiometer
* Description : Read the basic usage of ADC,DAC and Voltage
* Auther : http//www.keyestudio.com
*/
#define PIN_ANALOG_IN 34 //the pin of the Potentiometer
void setup() {
Serial.begin(9600);
}
www.keyestudio.com
keyestudio
delay(200);
}
//**********************************************************************************
6. Code Explanation
2. analogRead(pin): read the value of the specified analog pin. The ESP32
contains a multi-channel, 12-bit converter. This means that it will map the
integer value between 0 and 4095. For example, this will produce a
3. The map() function converts this 12-bit DAC value to an 8-bit DAC
value.
5. The serial monitor displays the values of adcVal, dacVal, voltage, the
baud rate must be set before display (we default to 9600,which can be
changed).
7. Test Result
mpile and upload the code to the ESP32. After uploading successfull
www.keyestudio.com
keyestudio
y,we will use a USB cable to power on, open the serial monitor an
d set the baud rate to 9600. The serial monitor will display the pot
entiometer's ADC value, DAC value and voltage value. Rotate the po
www.keyestudio.com
keyestudio
Project 21: Steam Sensor
1. Description
(digital) input module, also called rain, rain sensor. It can be used to
amount of rain, convert it into digital signal (DO) and analog signal (AO)
output, and is widely used in Arduino robot kits, raindrops, rain sensors,
and can be used for various It can monitor various weather conditions,
and convert it into digital signal and AO output, and can also be used for
www.keyestudio.com
keyestudio
analog port of the ESP32 development board, sense the change of the
analog value, and display the corresponding analog value on the shell.
2. Working Principle
printed parallel lines on the circuit board. The more water there is, the
more wires will be connected, and the conductive contact area increases.
The voltage output by pin 2 will gradually increase. The larger the analog
It can also detect steam in the air. Two position holes are used to install
www.keyestudio.com
keyestudio
3. Required Components
4. Connection Diagram
5. Test Code
//**********************************************************************************
/*
* Filename : Steam sensor
* Description : Read the basic usage of ADC,DAC and Voltage
* Auther : http//www.keyestudio.com
*/
www.keyestudio.com
keyestudio
#define PIN_ANALOG_IN 34 //the pin of the Steam sensor
void setup() {
Serial.begin(9600);
}
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on, open the serial monitor and set the baud
rate to 9600. The serial monitor will display the steam sensor’s ADC
value, DAC value and voltage value. When a few drops of water are
placed in the sensor sensing area, the values will change. The more water
volume, the greater the output voltage value , ADC value and the DAC
value .
www.keyestudio.com
keyestudio
1. Overview
In this kit, there is a Keyestudio DIY electronic block and a sound sensor.
www.keyestudio.com
keyestudio
level in the current environment with it. The louder the sound, the larger
the ADC, DAC and the voltage value, and the “shell”window will display
2. Working Principle
build the circuit with the LM386 chip and amplify the sound through the
3. Components
www.keyestudio.com
keyestudio
4. Connection Diagram
5. Test Code
www.keyestudio.com
keyestudio
//**********************************************************************************
/*
* Filename : MicroPhone
* Description : Read the basic usage of ADC,DAC and Voltage
* Auther : http//www.keyestudio.com
*/
#define PIN_ANALOG_IN 34 //the pin of the Sound Sensor
void setup() {
Serial.begin(9600);
}
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on, open the serial monitor and set the baud
rate to 9600. The serial monitor will display the sound sensor’s ADC
value, DAC value and voltage value. Rotate the potentiometer clockwise
and speak at the MIC. Then you can see the analog value get larger, as
shown below:
www.keyestudio.com
keyestudio
1. Description
www.keyestudio.com
keyestudio
In this kit, there is a photoresistor consists of photosensitive resistance
elements. Its resistance changes with the light intensity. Also, it converts
the change of the analog value, and display the corresponding analog
2. Working Principle
www.keyestudio.com
keyestudio
3. Components
4. Connection Diagram
5. Test Code
www.keyestudio.com
keyestudio
//**********************************************************************************
/*
* Filename : Photoresistance
* Description : Read the basic usage of ADC,DAC and Voltage
* Auther : http//www.keyestudio.com
*/
#define PIN_ANALOG_IN 34 //the pin of the Photoresistance
void setup() {
Serial.begin(9600);
}
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on, open the serial monitor and set the baud
rate to 9600. The serial monitor will display the photoresistor’s ADC value,
DAC value and voltage value. When the light intensity gets stronger, the
www.keyestudio.com
keyestudio
www.keyestudio.com
keyestudio
Project 24: NTC-MF52AT Thermistor
1. Overview
its signal terminal to the analog port of the ESP32 mainboard and read
www.keyestudio.com
keyestudio
analog value.
2. Working Principle
3. Components
www.keyestudio.com
keyestudio
Keyestudio
ESP32 Expansion 3P Dupont
ESP32 Board*1 NTC-MF52AT Micro USB Cable*1
Board*1 Wire*1
Thermistor*1
4. Connection Diagram
5. Test Code
//**********************************************************************************
/*
* Filename : Temperature sensor
* Description : Making a thermometer by thermistor.
* Auther : http//www.keyestudio.com
*/
#define PIN_ANALOG_IN 34
void setup() {
www.keyestudio.com
keyestudio
Serial.begin(9600);
}
void loop() {
int adcValue = analogRead(PIN_ANALOG_IN); //read ADC pin
double voltage = (float)adcValue / 4095.0 * 3.3; // calculate voltage
double Rt = (3.3 - voltage) / voltage * 10; //calculate resistance value of thermistor
double tempK = 1 / (1 / (273.15 + 25) + log(Rt / 4.7) / 3950.0); //calculate temperature (Kelvin)
double tempC = tempK - 273.15; //calculate temperature (Celsius)
Serial.printf("ADC value : %d,\tVoltage : %.2fV, \tTemperature : %.2fC\n", adcValue, voltage, tempC);
delay(1000);
}
//**********************************************************************************
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on, open the serial monitor and set the baud
rate to 9600. The serial monitor will display the thermistor’s ADC value,
www.keyestudio.com
keyestudio
Project 25: Thin-film Pressure Sensor
1. Overview
pressure-sensitive functions.
signal on the S end of the module. The smaller the ADC value, DAC value
and voltage value, the greater the pressure; and the displayed results will
www.keyestudio.com
keyestudio
2. Working Principle
sensor will vary. We convert the pressure signals detected by the sensor
into the electric signals through a circuit. Then we can obtain the
3. Components
Keyestudio
ESP32 Expansion Thin-film 3P Dupont Micro USB
ESP32 Board*1
Board*1 Pressure Wire*1 Cable*1
Sensor*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : Film pressure sensor
* Description : Read the basic usage of ADC,DAC and Voltage
* Auther : http//www.keyestudio.com
*/
#define PIN_ANALOG_IN 34 //the pin of the Film pressure sensor
void setup() {
www.keyestudio.com
keyestudio
Serial.begin(9600);
}
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on, open the serial monitor and set the baud
rate to 9600. The serial monitor will display the thin-film’s ADC value,
DAC value and voltage value, when the thin-film is pressed by fingers, the
www.keyestudio.com
keyestudio
1. Description
In daily life, it is often seen that a fire broke out without any precaution. It
www.keyestudio.com
keyestudio
will cause great economic and human loss. So how can we avoid this
situation? Right, install a flame sensor and a speaker in those places that
easily break out a fire. When the flame sensor detects a fire, the speaker
will alarm people quickly to put out the fire.
So in this project, you will learn how to use a flame sensor and an active
buzzer module to simulate the fire alarm system.
2. Working Principle
This flame sensor can be used to detect fire or other light sources with
wavelength stands at 700nm ~ 1000nm. Its detection angle is about 60°.
You can rotate the potentiometer on the sensor to control its sensitivity.
Adjust the potentiometer to make the LED at the critical point between
on and off state. The sensitivity is the best.
From the below figure, power up. When detecting fire, the digital pin
outputs low levels, the red LED2 will light up first, the digital signal
terminal D0 outputs a low level, and the red LED1 will light up. The
stronger the external infrared light, the smaller the value; the weaker the
www.keyestudio.com
keyestudio
3. Required Components
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : Flame sensor
* Description : Read the basic usage of Digital,ADC,DAC and Voltage
* Auther : http//www.keyestudio.com
*/
//Flame sensor two pins 13, 34, respectively
#define PIN_ANALOG_IN 34
int digitalPin = 13;
//The following two variables hold the digital signal and adc values respectively
int analogVal = 0;
int adcVal = 0;
void setup() {
Serial.begin(9600);
pinMode(digitalPin, INPUT); //Digital pin 13 is set to input mode
}
www.keyestudio.com
keyestudio
//In loop(),the digitalRead()function is used to obtain the digital value,
//the analogRead() function is used to obtain the ADC value.
//and then the map() function is used to convert the value into an 8-bit precision DAC value.
//The input and output voltage are calculated according to the previous formula,
//and the information is finally printed out.
void loop() {
int digitalVal = digitalRead(digitalPin); //Read digital signal;
int adcVal = analogRead(PIN_ANALOG_IN);
int dacVal = map(adcVal, 0, 4095, 0, 255);
double voltage = adcVal / 4095.0 * 3.3;
Serial.printf("digitalVal: %d, \t ADC Val: %d, \t DAC Val: %d, \t Voltage: %.2fV\n",digitalVal, adcVal,
dacVal, voltage);
delay(200);
}
//**********************************************************************************
6. Code Explanation
Two pins we use are defined as GPIO13 and GPIO34 according to the
respectively.
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Rotating the potentiometer on the sensor,
we can adjust the red LED bright and not bright critical point. The red
LED2 on the sensor module is lit, while the red LED1 is not. Open the
monitor and set baud rate to 9600. The "Shell" window will display the
digital value, ADC value, DAC value and voltage value of the flame sensor.
www.keyestudio.com
keyestudio
When fire is detected, the LED1 will be on. the digital value will change
from 1 to 0, and the analog value will become smaller, as shown below.
www.keyestudio.com
keyestudio
Project 27: MQ-2 Gas Sensor
1. Description
This analog gas sensor - MQ2 is used in gas leakage detecting equipment
alcohol, Hydrogen and smoke. It has high sensitivity and quick response.
In the experiment, we read the analog value at the A0 port and the D0
www.keyestudio.com
keyestudio
2. Working Principle
The greater the concentration of smoke, the greater the conductivity, the
lower the output resistance, the greater the output analog signal.
gas through the potentiometer, and output the digital value at D0. When
the measured gas content exceeds the critical point, the D0 terminal
outputs a low level; when the measured gas content does not exceed the
www.keyestudio.com
keyestudio
3. Required Components
keyestudio
ESP32 Expansion 4P Dupont Micro USB
ESP32 Board*1 DIY Analog
Board*1 Wire*1 Cable*1
Gas Sensor*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : MQ2
* Description : Read the basic usage of Digital, ADC,DAC and Voltage
* Auther : http//www.keyestudio.com
*/
//MQ_2 two pins 13, 34, respectively
#define PIN_ANALOG_IN 34
int digitalPin = 13;
//The following two variables hold the digital signal and adc values respectively
int analogVal = 0;
int adcVal = 0;
void setup() {
Serial.begin(9600);
pinMode(digitalPin, INPUT); //Digital pin 13 is set to input mode
}
www.keyestudio.com
keyestudio
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Rotating the potentiometer on the sensor,
we can adjust the red LED bright and not bright critical point. Open the
monitor , set baud rate to 9600 and display the corresponding data and
characters. When the sensor detects the smoke or combustible gas, the
red LED lights up and the digital value changes from 1 to 0, the ADC
www.keyestudio.com
keyestudio
1. Description
In this kit, there is a MQ-3 alcohol sensor, which uses the gas-sensing
material is tin dioxide (SnO2) which has a low conductivity in clean air.
located, the conductivity of the sensor increases with the increase of the
www.keyestudio.com
keyestudio
In the experiment, we read the analog value at the A0 end of the sensor
and the digital value at the D0 end to judge the content of alcohol vapor
2. Working Principle
of the ambient gas. When in use, A0 terminal reads the analog value
chip (comparator), we can adjust and measure the alcohol vapor alarm
threshold through the potentiometer, and output the digital value at D0.
When the measured alcohol vapor content exceeds the critical point, the
content does not exceed the critical point, the D0 terminal outputs a high
level.
www.keyestudio.com
keyestudio
3. Components Required
keyestudio
ESP32 Expansion 4P Dupont
ESP32 Board*1 Alcohol Micro USB Cable*1
Board*1 Wire*1
Sensor*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : MQ3
* Description : Read the basic usage of Digital, ADC,DAC and Voltage
* Auther : http//www.keyestudio.com
*/
//MQ_3 two pins 13, 34, respectively
#define PIN_ANALOG_IN 34
int digitalPin = 13;
//The following two variables hold the digital signal and adc values respectively
int analogVal = 0;
int adcVal = 0;
void setup() {
Serial.begin(9600);
pinMode(digitalPin, INPUT); //Digital pin 13 is set to input mode
www.keyestudio.com
keyestudio
}
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Rotating the potentiometer on the sensor,
we can adjust the yellow and green LED bright and not bright critical
point. Open the monitor, set baud rate to 9600 and display the
corresponding data and characters. When the sensor detects the alcohol
gas, the yellow and green LED lights up and the digital value changes
from 1 to 0, the ADC value, DAC value and voltage value decrease, as
www.keyestudio.com
keyestudio
shown below.
1. Description
www.keyestudio.com
keyestudio
When we talked about analog and digital sensors earlier, we talked about
the single-channel key module. When we press the key, it outputs a low
level, and when we release the key, it outputs a high level. We can only
read these two digital signals. In fact, the key module ADC acquisition
can also be performed. In this kit, a DIY electronic building block five-way
We can judge which key is pressed through the analog value. In the
2. Working Principle
Let’s look at the schematic diagram, when we do not press the key, the
OUT of S output to the signal end is pulled down by R1. At this time, we read
the low level 0V. When we press the key SW1, the OUT of the output to the
signal end S is directly connected to the VCC. At this time, we read the high level
3.3V(the figure is marked as a 12-bit ADC(0~4095) and VCC is 5V. The principle
is the same. Here we have VCC of 3.3V and ADC mapped to 12 bits), which is an
Next,when we press the key SW2, the OUT terminal voltage of the signal we
When we press the key SW3, the OUT terminal voltage of the signal we read is
www.keyestudio.com
keyestudio
the voltage between R2+R3 and R1, namely VCC*R1/(R3+R2+R1), which is
When we press the key SW4, the OUT terminal voltage of the signal we read is
Similarly, when we press the key SW5, the OUT terminal voltage of the signal
about 844.
www.keyestudio.com
keyestudio
3. Components Required
keyestudio
ESP32 Expansion 5-Channel AD 3P Dupont
ESP32 Board*1 Micro USB Cable*1
Board*1 Button Wire*1
Module*1
4. Connection Diagram
5.Test Code
www.keyestudio.com
keyestudio
//**********************************************************************************
/*
* Filename : Five AD Keys
* Description : Read the value of Five AD Keys
* Auther : http//www.keyestudio.com
*/
int val = 0;
int ADkey = 34; //Define five AD keys connected to GPIO36
void setup() {
Serial.begin(9600); //Set baud rate to 9600
}
void loop() {
val = analogRead(ADkey); //Read the simulated value of the AD key and assign it to the variable val
Serial.print(val); //A newline prints the variable val
if (val <= 500) { //Val is less than or equal to 500 when no button is pressed
Serial.println(" no key is pressed");
} else if (val <= 1000) { //When key 5 is pressed,val is between 500 and 1000
Serial.println(" SW5 is pressed");
} else if (val <= 2000) { //When pressed,val is between 1000 and 2000
Serial.println(" SW4 is pressed");
} else if (val <= 3000) { //When pressed,val is between 2000 and 3000
Serial.println(" SW3 is pressed");
} else if (val <= 4000) { //When key 2 is pressed,val is between 3000 and 4000
Serial.println(" SW2 is pressed");
} else { //When key 1 is pressed,val is greater than 4000
Serial.println(" SW1 is pressed");
}
}
//**********************************************************************************
6. Code Explanation
We assign the read analog value to the variable val, and the serial
When the analog value is in the range of 500 and 1000, the button SW5 is
pressed; when the analog value is in the 1000 and 2000, the button SW4
www.keyestudio.com
keyestudio
is pressed; when the analog value is between 2000 and 3000, the button
SW3 is pressed; when the analog value is between 3000 and 4000, the
button SW2 is pressed. When the analog value is above 4000, we judge
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set baud rate
to 9600; when the button is pressed, the serial monitor prints out the
www.keyestudio.com
keyestudio
Project 30: Joystick Module
1. Overview
kit, which mainly uses PS2 joysticks. When controlling it, we need to
connect the X and Y ports of the module to the analog port of the
GND of the MCU. We can read the high and low levels of two analog
values and one digital port) to determine the working status of the
In the experiment, two analog values(x axis and y axis) will be shown on
the Shell.
www.keyestudio.com
keyestudio
2. Working Principle
button is not pressed and the module is pulled down by R1, low levels
will be output ; on the contrary, when the button is pressed, VCC will be
3. Components
www.keyestudio.com
keyestudio
ESP32 Keyestudio
ESP32 5P Dupont Micro USB
Expansion Joystick
Board*1 Wire*1 Cable*1
Board*1 Module*1
4. Connection Diagram
5. Test Code
//**********************************************************************************
/*
* Filename : Joystick
www.keyestudio.com
keyestudio
* Description : Read data from Rocker.
* Auther : http//www.keyestudio.com
*/
int xyzPins[] = {34, 35, 13}; //x,y,z pins
void setup() {
Serial.begin(9600);
pinMode(xyzPins[0], INPUT); //x axis.
pinMode(xyzPins[1], INPUT); //y axis.
pinMode(xyzPins[2], INPUT_PULLUP); //z axis is a button.
}
6. Code Explanation
GPIO34, the y pin is set to GPIO35 and the pin of the joystick is set to
GPIO13.
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set baud rate
to 9600;
www.keyestudio.com
keyestudio
The serial monitor will show the corresponding value. Moving the joystick
or pressing it will change the analog and digital values in the serial
monitor .
www.keyestudio.com
keyestudio
Project 31: Relay Module
1. Overview
2. Working Principle
Input Voltage:3.3V-5V
www.keyestudio.com
keyestudio
It can let the MCU control board drive 3A load, such as an LED lamp belt,
3. Components Required
Keyestudio
ESP32 Expansion 3P Dupont Micro USB
ESP32 Board*1 Relay
Board*1 Wire*1 Cable*1
Module*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : Relay
* Description : Relay turn on and off.
* Auther : http//www.keyestudio.com
*/
#define Relay 15 // defines digital 15
void setup()
{
pinMode(Relay, OUTPUT); // sets "Relay" to "output"
}
void loop()
{
digitalWrite(Relay, HIGH); // turns on the relay
delay(1000); //delays 1 seconds
digitalWrite(Relay, LOW); // turns off the relay
delay(1000); // delays 1 seconds
}
www.keyestudio.com
keyestudio
//**********************************************************************************
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. The relay will cycle on and off, on for 1
second, off for 1 second. At the same time, you can hear the sound of the
relay on and off as well as see the change of the indicator light on the
relay .
1. Overview
In previous lessons, we learned about the plug-in RGB module and used
www.keyestudio.com
keyestudio
There is a Keyestudio 6812 RGB module whose the driving principle is
different from the plug-in RGB module. It can only control with one pin.
the control circuit and the light-emitting circuit. Each LED element is the
same as a 5050 LED lamp bead, and each component is a pixel. There are
2. Working Principle
From the schematic diagram, we can see that these four pixel lighting
beads are all connected in series. In fact, no matter how many they are,
we can use a pin to control a light and let it display any color. The pixel
constant current control part, which effectively ensures the color of the
method. After the pixel is powered up and reset, the S terminal receives
the data transmitted from the controller. The first 24bit data sent is
extracted by the first pixel and sent to the data latch of the pixel.
www.keyestudio.com
keyestudio
3. Components
Keyestudio
ESP32 Expansion 3P Dupont
ESP32 Board*1 6812 RGB Micro USB Cable*1
Board*1 Wire*1
Module*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : sk6812 RGB LED
* Description : turn on sk6812 RGB LED
* Auther : http//www.keyestudio.com
*/
#include <Adafruit_NeoPixel.h>
#define PIN 15
www.keyestudio.com
keyestudio
// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel. Avoid connecting
// on a live circuit...if you must, connect GND first.
void setup() {
strip.begin();
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
// Some example procedures showing how to display to the pixels:
colorWipe(strip.Color(255, 0, 0), 50); // Red
colorWipe(strip.Color(0, 255, 0), 50); // Green
colorWipe(strip.Color(0, 0, 255), 50); // Blue
// Send a theater pixel chase in...
theaterChase(strip.Color(127, 127, 127), 50); // White
theaterChase(strip.Color(127, 0, 0), 50); // Red
theaterChase(strip.Color( 0, 0, 127), 50); // Blue
rainbow(20);
rainbowCycle(20);
theaterChaseRainbow(50);
}
www.keyestudio.com
keyestudio
delay(wait);
}
}
delay(wait);
www.keyestudio.com
keyestudio
delay(wait);
7. Test Code
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Then we can see the four RGB LEDs show
www.keyestudio.com
keyestudio
Project 33: Rotary Encoder
1. Overview
and so on.
the set data is up 1; and when the middle button is pressed, the value will
www.keyestudio.com
keyestudio
be show in the serial monitor.
2. Working Principle
c signal, and then converts this signal into a counting pulse, and the numb
ses output during clockwise and reverse rotation. There is no limit to coun
t rotation. It resets to the initial state, that is, starts counting from 0.
3. Components
www.keyestudio.com
keyestudio
Keyestudio
ESP32 Expansion 5P Dupont Micro USB
ESP32 Board*1 Rotary
Board*1 Wire*1 Cable*1
Encoder*1
4. Connection Diagram
5. Test Code
//**********************************************************************************
/*
* Filename : Encoder
* Description : Rotary encoder module counting.
* Auther : http//www.keyestudio.com
*/
//Interfacing Rotary Encoder with Arduino
//Encoder Switch -> pin 27
www.keyestudio.com
keyestudio
//Encoder DT -> pin 14
//Encoder CLK -> pin 12
int Previous_Output;
int Encoder_Count;
void setup() {
Serial.begin(9600);
void loop() {
//aVal = digitalRead(pinA);
if (digitalRead(Encoder_DT) != Previous_Output)
{
if (digitalRead(Encoder_CLK) != Previous_Output)
{
Encoder_Count ++;
Serial.println(Encoder_Count);
}
else
{
Encoder_Count--;
Serial.println(Encoder_Count);
}
}
Previous_Output = digitalRead(Encoder_DT);
if (digitalRead(Encoder_Switch) == 0)
{
delay(5);
www.keyestudio.com
keyestudio
if (digitalRead(Encoder_Switch) == 0) {
Serial.println("Switch pressed");
while (digitalRead(Encoder_Switch) == 0);
}
}
}
//**********************************************************************************
6. Code Explanation
This code is set well in the library file. When CLK descends, read the
voltage of DAT, when DAT is a HIGH level, the value of the rotary encoder
is added by 1; when DAT is a LOW level, the value of the rotary encoder is
cut down 1.
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set baud rate
to 9600;
Rotate the knob on the rotary encoder clockwise, the displayed data will
decrease; on the contrary, in anticlockwise way, the data will rise. Equally,
www.keyestudio.com
keyestudio
1. Overview
www.keyestudio.com
keyestudio
Servo motor is a position control rotary actuator. It mainly consists of a
In general, servo has three lines in brown, red and orange. The brown
wire is grounded, the red one is a positive pole line and the orange one is
a signal line.
2. Working Principle
corresponds the rotation angle from 0 ° to 180 ° . But note that for
different brand motors, the same signal may have different rotation
angles.
www.keyestudio.com
keyestudio
3. Components
www.keyestudio.com
keyestudio
ESP32 Expansion
ESP32 Board*1 Servo*1 Micro USB Cable*1
Board*1
4. Connection Diagram
5. Test Code 1
//**********************************************************************
/*
* Filename : Servo_1
* Description : Steering gear rotation Angle 0-90-180, repeatly
www.keyestudio.com
keyestudio
* Auther : http//www.keyestudio.com
*/
int servoPin = 4;//steering gear PIN
void setup() {
pinMode(servoPin, OUTPUT);//steering pin is set to output
}
void loop() {
servopulse(servoPin, 0);//Rotate it to zero degrees
delay(1000);//delay 1S
servopulse(servoPin, 90);//Rotate it to 90 degrees
delay(1000);
servopulse(servoPin, 180);//Rotate it to 180 degrees
delay(1000);
}
6. Code Explanation 1
toLow, toHigh are the upper limit and lower limit we map. For example,
map(myangle, 0, 180, 500, 2500) means that an angle value myangle (0°
We use the function servopulse() to make the servo move. We also make
www.keyestudio.com
keyestudio
the servo rotate 0°, 90°and 180°cyclically.
7. Test Result 1
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on, the servo will rotate 0 ° , 90 ° and 180 °
cyclically.
8. Test Code 2
//**********************************************************************
/*
* Filename : Servo Sweep
* Description : Control the servo motor for sweeping
* Auther : http//www.keyestudio.com
*/
#include <ESP32Servo.h>
void setup() {
myservo.setPeriodHertz(50); // standard 50 hz servo
myservo.attach(servoPin, 500, 2500); // attaches the servo on servoPin to the servo object
}
void loop() {
for (posVal = 0; posVal <= 180; posVal += 1) { // goes from 0 degrees to 180 degrees
// in steps of 1 degree
myservo.write(posVal); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
www.keyestudio.com
keyestudio
for (posVal = 180; posVal >= 0; posVal -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(posVal); // tell servo to go to position in variable 'pos'
delay(15); // waits 15ms for the servo to reach the position
}
}
//********************************************************************************
9. Code Explanation 2
myservo. write (pos) is the rotation angle to POS. myservo. read () reads
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on, the servo will rotate from 0° to 180° by
www.keyestudio.com
keyestudio
Project 35: Ultrasonic Sensor
Bats and some marine animals are able to use high frequencies of s
waves from the larynx through the mouth or nose and use the sou
www.keyestudio.com
keyestudio
pplications in medicine, military, industry and agriculture.
1. Overview
In this kit, there is a keyes HC-SR04 ultrasonic sensor, which can detect
obstacles in front and the detailed distance between the sensor and the
obstacle. Its principle is the same as that of bat flying. It can emit the
hit an obstacle and come back immediately. The distance between the
sensor and the obstacle can be calculated by the time gap of emitting
In the experiment, we use the sensor to detect the distance between the
2. Working Principle
shown below; when the ultrasonic emitter emits the ultrasonic waves
towards certain direction, the counter will count. The ultrasonic waves
travel and reflect back once encountering the obstacle. Then the counter
will stop counting when the receiver receives the ultrasonic waves
coming back.
The ultrasonic wave is also sound wave, and its speed of sound V is
www.keyestudio.com
keyestudio
to time t, we can calculate the distance s from the emitting spot to the
obstacle.
s=340t/2.
1. First pull down the TRIG, and then trigger it with at least 10us high level
signal;
return.
level, the duration time of high level is actually the time from emission to
reception of ultrasonic.
www.keyestudio.com
keyestudio
3. Components
keyestudio
ESP32 Expansion SR01 4P Dupont
ESP32 Board*1 Micro USB Cable*1
Board*1 Ultrasonic Wire*1
Sensor*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : Ultrasonic
* Description : Use the ultrasonic module to measure the distance.
* Auther : http//www.keyestudio.com
*/
const int TrigPin = 13; // define TrigPin
const int EchoPin = 14; // define EchoPin.
int duration = 0; // Define the initial value of the duration to be 0
int distance = 0;//Define the initial value of the distance to be 0
void setup()
{
pinMode(TrigPin , OUTPUT); // set trigPin to output mode
pinMode(EchoPin , INPUT); // set echoPin to input mode
Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results.
}
void loop()
{
// make trigPin output high level lasting for 10μs to triger HC_SR04
digitalWrite(TrigPin , HIGH);
delayMicroseconds(10);
www.keyestudio.com
keyestudio
digitalWrite(TrigPin , LOW);
// Wait HC-SR04 returning to the high level and measure out this waitting time
duration = pulseIn(EchoPin , HIGH);
// calculate the distance according to the time
distance = (duration/2) / 28.5 ;
Serial.print("Distance: ");
Serial.print(distance); //Serial port print distance value
Serial.println("cm");
delay(300); // Wait 100ms between pings (about 20 pings/sec).
}
//**********************************************************************************
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set baud rate
to 9600.
The serial monitor will print the distance between the ultrasonic sensor
www.keyestudio.com
keyestudio
1. Overview
www.keyestudio.com
keyestudio
Infrared remote control is currently the most widely used means of
small volume, low power consumption, strong function and low cost.
and other small electrical devices have also used the infrared remote
control.
Its transmitting circuit is the use of infrared light emitting diode to emit
sensor. The infrared receiving sensor mainly uses the VS1838B infrared
and the output is a digital signal. It can receive 38KHz modulated remote
control signal.
www.keyestudio.com
keyestudio
2. Working Principle
between 30khz and 60khz, and most of them use a square wave of 38kHz
and a duty ratio of 1/3. A 4.7K pull-up resistor R3 is added to the signal
3. Components
Keyestudio
ESP32
ESP32 DIY 3P Dupont Micro USB Remote
Expansion
Board*11 IR Wire*1 Cable*1 Control*1
Board*1
Receiver*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : IR Receiver
* Description : Decode the infrared remote control and print it out through the serial port.
* Auther : http//www.keyestudio.com
*/
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>
void setup() {
Serial.begin(9600); // Initialize the serial port and set the baud rate to 9600
irrecv.enableIRIn(); // Start the receiver
Serial.print("IRrecvDemo is now running and waiting for IR message on Pin ");
www.keyestudio.com
keyestudio
Serial.println(recvPin); //print the infrared receiving pin
}
void loop() {
if (irrecv.decode(&results)) { // Waiting for decoding
serialPrintUint64(results.value, HEX);// Print out the decoded results
Serial.println("");
irrecv.resume(); // Release the IRremote. Receive the next value
}
delay(1000);
}
//**********************************************************************************
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set baud rate
to 9600; Find the infrared remote control, pull out the insulating sheet,
and press the button at the receiving head of the infrared receiving
sensor. After receiving the signal, the LED on the infrared receiving
www.keyestudio.com
keyestudio
Write down the key code value associated with the infrared remote with
www.keyestudio.com
keyestudio
Project 37: DS18B20 Temperature Sensor
1. Description
xim. The MCU can communicate with the DS18B20 through 1-Wire
2. Working Principle
www.keyestudio.com
keyestudio
The hardware interface of the 1-Wire bus is very simple, just connect the
complex timing operations in the library, and you can use the library
functions directly.
This can save up to 12-bit temperature vale. In the register, save in code
A total of 2 bytes, LSB is the low byte, MSB is the high byte, where MSb is
www.keyestudio.com
keyestudio
the high byte of the byte, LSb is the low byte of the byte. As you can see,
bit, is expressed. Among them, S represents the sign bit, and the lower 11
bits are all powers of 2, which are used to represent the final temperature.
0.0625.
3. Required Components
Keyestudio DIY
ESP32 Expansion 18B20 3P Dupont
ESP32 Board*1 Micro USB Cable*1
Board*1 Temperature Wire*1
Sensor*1
4. Required Components
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : ds18b20
* Description : Read the temperature of ds18B20
* Auther : http//www.keyestudio.com
*/
#include <DS18B20.h>
//ds18b20 pin to 15
DS18B20 ds18b20(15);
void setup() {
Serial.begin(9600);
}
void loop() {
double temp = ds18b20.GetTemp();//Read the temperature
temp *= 0.0625;//The conversion accuracy is 0.0625/LSB
www.keyestudio.com
keyestudio
Serial.print("Temperature: ");
Serial.print(temp);
Serial.println("C");
delay(1000);
}
//**********************************************************************************
6. Code Explanation
1. We set the pin to GPIO15 and obtain the temperature in the unit
of ℃.
2. Set a double decimal variable to temp, and assign the measured result
to temp.
3. The serial monitor displays the temp value, and the baud rate needs to
changed).
4. We add the unit behind the data. If the unit is directly set to °C, the
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set baud rate
www.keyestudio.com
keyestudio
environment, as shown below.
www.keyestudio.com
keyestudio
Project 38: XHT11 Temperature and Humidity Sensor
1. Description
humidity.
www.keyestudio.com
keyestudio
It includes a resistive element and a NTC temperature measuring device.
2. Working Principle
microcomputer and XHT11 adopts the single bus data format. The
communication time is about 4ms. The data is divided into fractional part
out. Data format: 8bit humidity integer data + 8bit humidity decimal data
checksum
www.keyestudio.com
keyestudio
3. Required Components
Keyestudio
XHT11
ESP32 Expansion Temperature and 3P Dupont
ESP32Board*1 Micro USB Cable*1
Board*1 Humidity Sensor Wire*1
(compatible
with DHT11)*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : xht11
* Description : Read the temperature and humidity values of XHT11.
* Auther : http//www.keyestudio.com
*/
#include "xht11.h"
//gpio15
xht11 xht(15);
unsigned char dht[4] = {0, 0, 0, 0};//Only the first 32 bits of data are received, not the parity bits
void setup() {
Serial.begin(9600);//Start the serial port monitor and set baud rate to 9600
}
void loop() {
if (xht.receive(dht)) { //Returns true when checked correctly
Serial.print("RH:");
Serial.print(dht[0]); //The integral part of humidity, DHT [1] is the fractional part
Serial.print("% ");
Serial.print("Temp:");
Serial.print(dht[2]); //The integral part of temperature, DHT [3] is the fractional part
Serial.println("C");
} else { //Read error
Serial.println("sensor error");
}
delay(1000); //It takes 1000ms to wait for the device to read
}
//**********************************************************************************
6. Code Explanation
1. We set the pin to GPIO15, and store the detected temperature and
3. We add units behind the data. If the temperature unit is directly set
www.keyestudio.com
keyestudio
to °C, the test results may be wrong, so we directly replace °C with C; the
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set baud rate
to 9600; The monitor will display the temperature and humidity data of
www.keyestudio.com
keyestudio
Project 39: DS1307 Clock Module
1. Overview
This module mainly uses the real-time clock chip DS1307, which is t
he I2C bus interface chip that has second, minute, hour, day, month,
and won‘t’ affected by the CPU main crystal oscillator and capacitan
error is generally less than 10 s. The chip also has a clock protectio
clock in case of power failure of main power supply and other bad
www.keyestudio.com
keyestudio
environment.
In the experiment, we use the DS1307 clock module to obtain the system
2. Working Principle
Serial real-time clock records year, month, day, hour, minute, second and
VBAT:X2:+3V input;
SDA:serial data;
www.keyestudio.com
keyestudio
SCL:serial clock;
3. Components
Keyestudio
ESP32 Expansion 4P Dupont
ESP32 Board*1 DS1307 Clock Micro USB Cable*1
Board*1 Wire*1
Module*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : DS1307 Real Time Clock
* Description : Read the year/month/day/hour/minute/second/week of DS1307 clock module
* Auther : http//www.keyestudio.com
*/
#include <Wire.h>
#include "RtcDS1307.h" //DS1307 clock module library
RtcDS1307<TwoWire> Rtc(Wire);//i2cport
void setup(){
Serial.begin(57600);//Set baud rate to 57600
Rtc.Begin();
Rtc.SetIsRunning(true);
www.keyestudio.com
keyestudio
Rtc.SetDateTime(RtcDateTime(__DATE__, __TIME__));
}
void loop(){
// Print year/month/day/hour/minute/second/week
Serial.print(Rtc.GetDateTime().Year());
Serial.print("/");
Serial.print(Rtc.GetDateTime().Month());
Serial.print("/");
Serial.print(Rtc.GetDateTime().Day());
Serial.print(" ");
Serial.print(Rtc.GetDateTime().Hour());
Serial.print(":");
Serial.print(Rtc.GetDateTime().Minute());
Serial.print(":");
Serial.print(Rtc.GetDateTime().Second());
Serial.print(" ");
Serial.println(Rtc.GetDateTime().DayOfWeek());
delay(1000);//Delay 1 second
}
//**********************************************************************************
6. Code Explanation
Rtc.SetDateTime();set time
Rtc.GetDateTime().Day()return date
www.keyestudio.com
keyestudio
Rtc.GetDateTime().Hour()return hour
Rtc.GetDateTime().Minute()return minute
Rtc.GetDateTime().Second()return second
7. Test Result
ach the DS1307 sensor to a battery, compile and upload the code t
o power on. Open the serial monitor and set baud rate to 9600. W
e can see the displayed year, month, day, hour, minute, second and
week on the serial monitor, and set the time and date to refresh ev
www.keyestudio.com
keyestudio
1. Overview
www.keyestudio.com
keyestudio
In this kit, there is a DIY electronic building block ADXL345 acceleration
sensor module, which uses the ADXL345BCCZ chip. The chip is a small,
thin, low-power 3-axis accelerometer with a high resolution (13 bits) and
sensor.
2. Working Principle
The sensor can measure static acceleration due to gravity in tilt detection
Angle changes of
www.keyestudio.com
keyestudio
3. Components Required
Keyestudio
ESP32 Expansion ADXL345 4P Dupont
ESP32 Board*1 Micro USB Cable*1
Board*1 Acceleration Wire*1
Module*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : ADXL345
* Description : Read the X/Y/Z value of ADXL345
* Auther : http//www.keyestudio.com
*/
#include "adxl345_io.h"
//The port is sda-->21,scl-->22
adxl345 adxl345(21, 22);
void setup() {
Serial.begin(57600);//Start serial port monitoring and set baud rate to 57600
adxl345.Init();
}
www.keyestudio.com
keyestudio
void loop() {
adxl345.readXYZ(&out_X, &out_Y, &out_Z);
Serial.print(out_X);
Serial.print("g ");
Serial.print(out_Y);
Serial.print("g ");
Serial.print(out_Z);
Serial.println("g");
delay(100);
}
//**********************************************************************************
6. Code Explanation
Set 3 decimal variables out_X out_Y out_Z, and assign the measured
result to out_X out_Y out_Z. The serial monitor displays the value of out_X
out_Y out_Z, and the baud rate needs to be set before displaying (our
Get the acceleration value of the X axis and return it to the variables
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set baud rate
www.keyestudio.com
keyestudio
to 9600.
The serial monitor displays the value corresponding to the sensor, the
www.keyestudio.com
keyestudio
Project 41: TM1650 4-Digit Tube Display
1. Overview
4-digit digital tube, and its driver chip is TM1650. When using it, we only
4-bitdigit tube, which greatly saves the IO port resources of the control
board.
TM1650 is a special circuit for LED (light emitting diode display) drive
control. It integrates MCU input and output control digital interface, data
circuits.
www.keyestudio.com
keyestudio
TM1650 has stable performance, reliable quality and strong
anti-interference ability.
24 hours.
(note that this data transmission protocol is not a standard I2C protocol).
The chip can drive the digital tube and save MCU pin resources through
2. Working Principle
TM1650 adopts IIC treaty, which uses DIO and CLK buses.
Data command setting: 0x48 means that we light up the digital tube,
www.keyestudio.com
keyestudio
3. Components
Keyestudio
ESP32 Expansion TM16504-Digit 4P Dupont Micro USB
ESP32 Board*1
Board*1 Segment Wire*1 Cable*1
Display*1
www.keyestudio.com
keyestudio
4. Connection Diagram
5. Test Code
//**********************************************************************************
/*
* Filename : TM1650 Four digital tube
* Description : TM1650 Four Digital Tube shows 0-9999
* Auther : http//www.keyestudio.com
*/
#include "TM1650.h"
#define CLK 22 //pins definitions for TM1650 and can be changed to other ports
#define DIO 21
TM1650 DigitalTube(CLK,DIO);
void setup(){
DigitalTube.setBrightness(); //set brightness, 0---7, default : 2
www.keyestudio.com
keyestudio
DigitalTube.displayOnOFF(); //display on or off, 0=display off, 1=display on, default : 1
for(char b=1;b<5;b++){
DigitalTube.clearBit(b); //DigitalTube.clearBit(0 to 3); Clear bit display.
}
// DigitalTube.displayDot(1,true); //Bit0 display dot. Use before displayBit().
DigitalTube.displayBit(1,0); //DigitalTube.Display(bit,number); bit=0---3 number=0---9
}
void loop(){
for(int num=0; num<10000; num++){
displayFloatNum(num);
delay(100);
}
}
www.keyestudio.com
keyestudio
DigitalTube.clearBit(3);
DigitalTube.displayBit(4, dat%100/10);
}
//**********************************************************************************
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. The 4-digit tube display will show integer
from 0 to 99999, add 1 for each 10ms. Increase to 9999 then start from 0.
www.keyestudio.com
keyestudio
Project 42: HT16K33_8X8 Dot Matrix Module
1. Overview
light-emitting diode is placed at the intersection of the row line and the
column line. When the corresponding row is set to 1 level, and a certain
2. Working Principle
As the schematic diagram shown, to light up the LED at the first row and
column, we only need to set C1 to high level and R1 to low level. To turn
on LEDs at the first row, we set R1 to low level and C1-C8 to high level.
www.keyestudio.com
keyestudio
16 IO ports are needed, which will highly waste the MCU resources.
8*8 dot matrix, which greatly saves the resources of the single-chip
microcomputer.
There are three DIP switches on the module, all of which are set to I2C
A0 A1 A2 A0 A1 A2 A0 A1 A2
(1) (2) (3) (1) (2) (3) (1) (2) (3)
0 0 0 1 0 0 0 1 0
(OFF) (OFF) (OFF) (ON) (OFF) (OFF) (OFF) (ON) (OFF)
OX70 OX71 OX72
A0 A1 A2 A0 A1 A2 A0 A1 A2
(1) (2) (3) (1) (2) (3) (1) (2) (3)
1 1 0 0 0 1 1 0 1
(ON) (ON) (OFF) (OFF) (OFF) (ON) (ON) (OFF) (ON)
OX73 OX74 OX75
A0 A1 A2 A0 A1 A2
(1) (2) (3) (1) (2) (3)
www.keyestudio.com
keyestudio
0 1 1 1 1 1
(OFF) (ON) (ON) (ON) (ON) (ON)
OX76 OX77
3. Components
Keyestudio
ESP32 Expansion HT16K33_ 4P Dupont Micro USB
ESP32 Board*1
Board*1 8X8 Dot Wire*1 Cable*1
Matrix*1
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : 8×8 Dot-matrix Display
* Description : 8x8 LED dot matrix display“Heart” pattern.
* Auther : http//www.keyestudio.com
*/
#include "HT16K33_Lib_For_ESP32.h"
#define SDA 21
#define SCL 22
//The brightness values can be set from 1 to 15, with 1 darkest and 15 brightest
#define A 15
www.keyestudio.com
keyestudio
byte result[8][8];
byte test1[8] = {0x00,0x42,0x41,0x09,0x09,0x41,0x42,0x00};
void setup()
{
matrix.init(0x70, SDA, SCL);//Initialize matrix
matrix.showLedMatrix(test1,0,0);
matrix.show();
}
void loop()
{
for (int i = 0; i <= 7; i++)
{
matrix.setBrightness(i);
delay(100);
}
for (int i = 7; i > 0; i--)
{
matrix.setBrightness(i);
delay(100);
}
}
//**********************************************************************************
6. Code Explanation
The pattern in our code is an array of byte data type, which is shown in
into binary, and fill in the 8*8 form below to make it clear. 1 means on, 0
0 0 0 0 0 0 0 0
0 1 1 0 0 1 1 0
www.keyestudio.com
keyestudio
0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0
0 0 0 0 0 0 0 0
0 1 0 0 0 0 1 0
0 0 1 1 1 1 0 0
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Then the dot matrix displays a
“ smile ”pattern.
www.keyestudio.com
keyestudio
Project 43: LCD_128X32_DOT Module
1. Description
This is a 128*32 pixel LCD module, which uses IIC communication mode
and ST7567A driver chip . At the same time, the code contains all the
English letters and common symbols of the library that can be directly
called. When used, we can also set English letters and symbols to display
different text sizes in our code. To make it easy to set up the pattern
specific pattern into control code and then copy it directly into the test
www.keyestudio.com
keyestudio
English words, common symbols and numbers.
2. Working Principle
call the library function, if interested, you can also go to understand the
3. Components
Keyestudio
ESP32 Expansion 4P Dupont Micro USB
ESP32 Board*1 LCD_128X32_DO
Board*1 Wire*1 Cable*1
T Module*1
www.keyestudio.com
keyestudio
4. Connection Diagram
5. Test Code
//**********************************************************************************
/*
* Filename : lcd128*32
* Description : Lcd128 *32 Displays character strings
* Auther : http//www.keyestudio.com
*/
#include "lcd128_32_io.h"
void setup() {
lcd.Init(); //initialize
lcd.Clear(); //cls
}
www.keyestudio.com
keyestudio
void loop() {
lcd.Cursor(0, 7); //Set display position
lcd.Display("KEYES"); //Setting the display
lcd.Cursor(1, 0);
lcd.Display("ABCDEFGHIJKLMNOPQR");
lcd.Cursor(2, 0);
lcd.Display("123456789+-*/<>=$@");
lcd.Cursor(3, 0);
lcd.Display("%^&(){}:;'|?,.~\\[]");
}
//**********************************************************************************
6. Code Explanation
1. .Init() initializes the display screen; .Clear() clears the display; .Cursor()
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. The first line of the 128X32LCD module
and the third line shows "123456789+-*/<> =$@", the fourth line
www.keyestudio.com
keyestudio
Project 44: RFID Module
1. Description
original chip to design card reading circuit, easy to use and low cost,
so on.
www.keyestudio.com
keyestudio
strings. For example, we read the data of the IC card below: 0xED、0xF7、
2. Working Principle
is a sensing device, and this device does not contain a battery. It only
contains tiny integrated circuit chips and media for storing data and
antennas for receiving and transmitting signals. To read the data in the
tag, first put it into the reading range of the card reader. The reader will
electricity according to Lenz's law, the RFID tag will supply power,
www.keyestudio.com
keyestudio
3. Components Required
4. Connection Diagram
www.keyestudio.com
keyestudio
5. Test Code
//**********************************************************************************
/*
* Filename : RFID
* Description : RFID reader UID
* Auther : http//www.keyestudio.com
*/
#include <Wire.h>
#include "MFRC522_I2C.h"
// IIC pins default to GPIO21 and GPIO22 of ESP32
// 0x28 is the i2c address of SDA, if doesn't match,please check your address with i2c.
MFRC522 mfrc522(0x28); // create MFRC522.
void setup() {
Serial.begin(115200); // initialize and PC's serial communication
Wire.begin(); // initialize I2C
www.keyestudio.com
keyestudio
mfrc522.PCD_Init(); // initialize MFRC522
ShowReaderDetails(); // dispaly PCD - MFRC522 read carder
Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
}
void loop() {
//
if ( ! mfrc522.PICC_IsNewCardPresent() || ! mfrc522.PICC_ReadCardSerial() ) {
delay(50);
return;
}
// save UID
Serial.print(F("Card UID:"));
for (byte i = 0; i < mfrc522.uid.size; i++) {
Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.println();
}
void ShowReaderDetails() {
// attain the MFRC522 software
byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
Serial.print(F("MFRC522 Software Version: 0x"));
Serial.print(v, HEX);
if (v == 0x91)
Serial.print(F(" = v1.0"));
else if (v == 0x92)
Serial.print(F(" = v2.0"));
else
Serial.print(F(" (unknown)"));
Serial.println("");
// when returning to 0x00 or 0xFF, may fail to transmit communication signals
if ((v == 0x00) || (v == 0xFF)) {
Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
}
}
//**********************************************************************************
www.keyestudio.com
keyestudio
6. Code Explanation
the IIC
7. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set baud rate
to 115200. When we make the IC card close to the RFID module, the
Note: Different RFID-RC522 door cards and key chains have diverse
www.keyestudio.com
keyestudio
values.
5. Comprehensive Experiments
www.keyestudio.com
keyestudio
1. Overview
LED. When the button is pressed and low levels are output, the LED will
light up; when the button is released, the LED will go off. Then we can
2. Components
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************
/*
* Filename : button_control_LED
* Description : Make a table lamp.
* Auther : http//www.keyestudio.com
*/
#define PIN_LED 4
#define PIN_BUTTON 15
bool ledState = false;
void setup() {
// initialize digital pin PIN_LED as an output.
pinMode(PIN_LED, OUTPUT);
pinMode(PIN_BUTTON, INPUT);
}
www.keyestudio.com
keyestudio
reverseGPIO(PIN_LED);
}
while (digitalRead(PIN_BUTTON) == LOW);
}
}
5. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. When the button is pressed, the LED will
1. Overview
www.keyestudio.com
keyestudio
In the previous experiment, we control an output module though an
input module. In this lesson, we will make an experiment that the active
2. Components
Keyestudio
ESP32 Keyestudio
ESP32 Obstacle 3P Dupont Micro USB
Expansion Active
Board*1 Avoidance Wire*2 Cable*1
Board*1 Buzzer*1
Sensor*1
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************************
/*
* Filename : Avoiding alarm
* Description : Obstacle avoidance sensor controls the buzzer
* Auther : http//www.keyestudio.com
*/
int item = 0;
void setup() {
pinMode(15, INPUT); //Obstacle avoidance sensor is connected to GPIO15 and set to input mode
pinMode(4, OUTPUT); //The buzzer is connected to GPIO4 and set to output mode
}
void loop() {
item = digitalRead(15);//Read the level value output by the obstacle avoidance sensor
if (item == 0) {//Obstruction detected
digitalWrite(4, HIGH);//The buzzer sounded
} else {//No obstacles detected
digitalWrite(4, LOW);//The buzzer is off
}
delay(100);//Delay 100ms
}
//**********************************************************************************
5. Code Explanation
The value is 0 when pressing the button, So, we can determine the key
HIGH).
6. Test Result
www.keyestudio.com
keyestudio
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. If the obstacle is detected, the active buzzer
1. Description
2. Required Components
www.keyestudio.com
keyestudio
Keyestudio DIY
ESP32 Expansion Keyestudio DIY Active
ESP32 Board*1 PIR Motion
Board*1 Buzzer*1
Sensor*1
Keyestudio
Purple LED
3P Dupont Wire*3 Micro USB Cable*1
Module*1
3. Connection Diagram
4. Test Code
//**********************************************************************************
www.keyestudio.com
keyestudio
/*
* Filename : PIR alarm
* Description : PIR control buzzer
* Auther : http//www.keyestudio.com
*/
int item = 0;
void setup() {
pinMode(15, INPUT); //PIR motion sensor is connected to GPIO15 and set as the input mode
pinMode(4, OUTPUT);//The active buzzer is connected to GPIO4 and set to output mode
pinMode(22, OUTPUT);//LED is connected to GPIO22 and set to output mode
}
void loop() {
item = digitalRead(15);//Read digital level signal output by infrared pyrorelease sensor
if (item == 1) { //Movement detected
digitalWrite(4, HIGH); //Turn on the buzzer
digitalWrite(22, HIGH); //Turn on the LED
delay(200);//Delay 200ms
digitalWrite(4, LOW); //Turn off the buzzer
digitalWrite(22, LOW); //Turn off the LED
delay(200);//Delay 200ms
} else { //No detection
digitalWrite(4, LOW); //Turn off the buzzer
digitalWrite(22, LOW); //Turn off the LED
}
}
//**********************************************************************************
5. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. If the sensor detects people moving, the
buzzer will emit an alarm , and the LED will flash continuously.
www.keyestudio.com
keyestudio
Project 48: Extinguishing Robot
1. Description
will automatically sense the fire and start the fan. In this project we will
learn how to build a very simple robot using ESP32, (detecting flames
with a flame sensor, blowing out candles with a fan) can teach us basic
concepts about robotics. Once you understand the basics below, you can
2. Components Required
www.keyestudio.com
keyestudio
ESP32 Expansion
ESP32 Board*1 130 Motor*1 Flame Sensor*1
Board*1
Battery(privode for
yourself)*6
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************************
/*
* Filename : Fire-fighting robot
* Description : Flame sensor controls the 130 fan module
* Auther : http//www.keyestudio.com
*/
int item = 0;
void setup() {
Serial.begin(9600);
pinMode(15, OUTPUT);//INA corresponds to IN+, and sets GPIO15 to output mode
pinMode(4, OUTPUT);//INB corresponds to IN-, and sets GPIO4 to output mode
}
void loop() {
item = analogRead(34);//The flame sensor is connected to GPIO34, and read the simulated value to Item
Serial.println(item);//Serial port display analog value
if (item < 3000) {//Less than 3000
digitalWrite(15, LOW);//Turn on the fan
digitalWrite(4, HIGH);
} else {//Otherwise, turn off the fan.
digitalWrite(15, LOW);
digitalWrite(4, LOW);
}
delay(100);
}
//**********************************************************************************
5. Code Explanation
In the code, we set the threshold value to 3000. When the ADC value
detected by the flame sensor is lower than the threshold value, the fan
will be automatically turned on; otherwise, it will be turned off. For the
www.keyestudio.com
keyestudio
6. Test Result
the DIP switch on the ESP32 expansion board to the ON end and power
up, compile and upload the code to the ESP32. After uploading
successfully, open the serial monitor and set baud rate to 9600, then the
ADC value of the flame will be printed. When this value is less than 3000,
the fan will work to blow out the fire, otherwise, it will be turned off.
www.keyestudio.com
keyestudio
Project 49: Rotary Encoder control RGB
1. Introduction
In this lesson, we will control the LED on the RGB module to show
get the remainders. The remainder is 0 and the LED will become red. The
remainder is 1, the LED will become green. The remainder is 2, the LED
2. Components
www.keyestudio.com
keyestudio
Keyestudio Keyestudio
ESP32 Expansion
ESP32Board*1 Common Cathode Rotary Encoder
Board*1
RGB Module*1 Module*1
Micro USB
5P Dupont Wire*1 4P Dupont Wire*1
Cable*1
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************************
/*
* Filename : Encoder control RGB
* Description : Rotary encoder controls RGB to present different effects
* Auther : http//www.keyestudio.com
*/
//Interfacing Rotary Encoder with Arduino
//Encoder Switch -> pin 27
//Encoder DT -> pin 14
//Encoder CLK -> pin 12
int Encoder_DT = 14;
int Encoder_CLK = 12;
int Encoder_Switch = 27;
int Previous_Output;
int Encoder_Count;
int ledPins[] = {0, 2, 15}; //define red, green, blue led pins
const byte chns[] = {0, 1, 2}; //define the pwm channels
int red, green, blue;
int val;
void setup() {
Serial.begin(9600);
void loop() {
//aVal = digitalRead(pinA);
if (digitalRead(Encoder_DT) != Previous_Output)
www.keyestudio.com
keyestudio
{
if (digitalRead(Encoder_CLK) != Previous_Output)
{
Encoder_Count ++;
Serial.print(Encoder_Count);
Serial.print(" ");
val = Encoder_Count % 3;
Serial.println(val);
}
else
{
Encoder_Count--;
Serial.print(Encoder_Count);
Serial.print(" ");
val = Encoder_Count % 3;
Serial.println(val);
}
}
Previous_Output = digitalRead(Encoder_DT);
if (digitalRead(Encoder_Switch) == 0)
{
delay(5);
if (digitalRead(Encoder_Switch) == 0) {
Serial.println("Switch pressed");
while (digitalRead(Encoder_Switch) == 0);
}
}
if (val == 0) {
//RED(255, 0, 0)
ledcWrite(chns[0], 255 );
ledcWrite(chns[1], 0);
ledcWrite(chns[2], 0);
} else if (val == 1) {
//GREEN(0, 255, 0)
ledcWrite(chns[0], 0);
ledcWrite(chns[1], 255);
ledcWrite(chns[2], 0);
} else {
//BLUE(0, 0, 255)
ledcWrite(chns[0], 0);
ledcWrite(chns[1], 0);
www.keyestudio.com
keyestudio
ledcWrite(chns[2], 255);
}
}
//**********************************************************************************
5. Code Explanation
remainders.
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set the baud
rate to 9600, then rotate the knob of the rotary encoder to display the
www.keyestudio.com
keyestudio
1. Introduction
www.keyestudio.com
keyestudio
by controlling the brightness of LED through an adjustable potentiometer.
After the code is set successfully, we can control the brightness of the
2. Required Components
Keyestudio
ESP32 Keyestudio
ESP32 Rotary 3P Dupont Micro USB
Expansion Purple
Board*1 Potentiomete Wire*2 Cable*1
Board*1 LED*1
r*1
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************************
/*
* Filename : adjust the light
* Description : Controlling the brightness of LED by potentiometer.
* Auther : http//www.keyestudio.com
*/
#define PIN_ANALOG_IN 34 //the pin of the potentiometer
#define PIN_LED 15 // the pin of the LED
#define CHAN 0
void setup() {
ledcSetup(CHAN, 1000, 12);
ledcAttachPin(PIN_LED, CHAN);
}
void loop() {
int adcVal = analogRead(PIN_ANALOG_IN); //read adc
int pwmVal = adcVal; // adcVal re-map to pwmVal
ledcWrite(CHAN, pwmVal); // set the pulse width.
delay(10);
}
//**********************************************************************************
www.keyestudio.com
keyestudio
5. Code Explanation
In the experiment, the mapping function maps adcVal from the range of
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Rotating the potentiometer on the module
1. Description
www.keyestudio.com
keyestudio
In life, we can see all kinds of smart products, such as smart home. Smart
homes include smart curtains, smart windows, smart TVs, smart lights,
and then achieve the effect of closing and opening the window by a
servo.
2. Required Components
Keyestudio
ESP32 Expansion 3P Dupont Micro USB
ESP32 Board*1 Steam Servo*1
Board*1 Wire*1 Cable*1
Sensor*1
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************************
/*
* Filename : smart window
* Description : Water drop sensor controls steering gear rotation.
* Auther : http//www.keyestudio.com
*/
#include <ESP32Servo.h>//Import the steering gear library file
int adcVal = 0;//A variable that holds the ADC value output by the droplet sensor
int servoPin = 15; // Define the servo pin
Servo myservo;//Defines an instance of the steering gear class
void setup(){
Serial.begin(9600);
pinMode(PIN_ADC, INPUT);
myservo.setPeriodHertz(50); // standard 50 hz servo
myservo.attach(servoPin, 500, 2500); // attaches the servo on servoPin to the servo object
}
www.keyestudio.com
keyestudio
void loop(){
adcVal = analogRead(PIN_ADC);//The droplet sensor is connected to the analog port GP34
Serial.println(adcVal);
if (adcVal > 2000) {//The simulated value is greater than 2000
myservo.write(0);//close the window
delay(500);//Give the steering gear time to turn
} else {// no rain
myservo.write(180);//open the window
delay(500);//Delay 500ms
}
}
//**********************************************************************************
5. Code Explanation
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. When the sensor detects a certain amount
windows.
www.keyestudio.com
keyestudio
Project 52: Sound Activated Light
1. Introduction
In this lesson, we will make a smart sound activated light using a sound
sensor and an LED module. When we make a sound, the light will
automatically turn on; when there is no sound, the light will automatically
with a sound sensor, and this sensor converts the intensity of external
threshold is exceeded, the light will go out, and when it is not exceeded,
www.keyestudio.com
keyestudio
the light will go out.
2. Components
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************************
/*
* Filename : sound-controlled lights
* Description : Sound sensor controls LED on and off
* Auther : http//www.keyestudio.com
*/
int ledPin = 15;//LED is connected to GP15
int microPin = 34;//Sound sensor is connected to GPIO34
void setup() {
Serial.begin(9600);//Set baud rate to 9600
pinMode(ledPin, OUTPUT);//LED is the output mode
}
void loop() {
int val = analogRead(microPin);//Read analog value
Serial.print(val);// Serial port print
if(val > 600){//exceed the threshold value
digitalWrite(ledPin, HIGH);//Lighting LED 3s,and print the corresponding information
Serial.println(" led on");
delay(3000);
}else{//otherwise
digitalWrite(ledPin, LOW);//Turn off the LED and print the corresponding information
Serial.println(" led off");
}
delay(100);
}
//**********************************************************************************
5. Code Explanation
We set the ADC threshold value to 600. If more than 600, LED will be on
6. Test Result
www.keyestudio.com
keyestudio
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set the baud
rate to 9600, then the corresponding volume ADC value will be displayed.
When the analog value of sound is greater than 600, the LED on the LED
1. Description
In this experiment, we will make a fire alarm system. Just use a flame
www.keyestudio.com
keyestudio
sensor to control an active buzzer to emit sounds.
2. Required Components
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************************
/*
* Filename : Flame Alarm
* Description : Controlling the buzzer by flame sensor.
* Auther : http//www.keyestudio.com
*/
int item = 0;
void setup() {
Serial.begin(9600);
pinMode(4, INPUT);//Flame sensor digital pin is connected to GPIO4
pinMode(15, OUTPUT);//Buzzer pin is connected to GPIO15
}
void loop() {
item = digitalRead(4);//Read the digital level output by the flame sensor
Serial.println(item);//Newline print level signal
if (item == 0) {//Flame detected
digitalWrite(15, HIGH);//Turn on the buzzer
} else {//Otherwise, turn off the buzzer
digitalWrite(15, LOW);
}
www.keyestudio.com
keyestudio
delay(100);//Delay 100ms
}
//**********************************************************************************
5. Code Explanation
This flame sensor uses an analog pin and a digital pin. When a flame is
detected, the digital pin outputs a low level. In this experiment we will use
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. When the sensor detects the flame, the
external active buzzer will emit sounds, otherwise the active buzzer will
www.keyestudio.com
keyestudio
Project 54: Smoke Alarm
1. Description
2. Required Components
www.keyestudio.com
keyestudio
Keyestudio
Keyestudio Active
ESP32 Board*1 ESP32 Expansion Board*1 TM16504-Digit
Buzzer*1
Segment Module*1
keyestudio Analog
3P Dupont Wire*2 4P Dupont Wire*1 Micro USB Cable*1
Gas Senso*1
3. Connection Diagram
4. Test Code
www.keyestudio.com
keyestudio
//**********************************************************************************
/*
* Filename : smoke alarm
* Description : MQ2 controls a buzzer and a four-digit analog smoke tester
* Auther : http//www.keyestudio.com
*/
#include "TM1650.h" //Import the TM1650 library file
int adcVal = 0; //display ADC value
//the interfaces are GPIO21 and GPIO22
#define DIO 21
#define CLK 22
TM1650 DigitalTube(CLK,DIO);
void setup() {
DigitalTube.setBrightness(); //set brightness, 0---7, default : 2
DigitalTube.displayOnOFF(); //display on or off, 0=display off, 1=display on, default : 1
for(char b=1;b<5;b++){
DigitalTube.clearBit(b); //DigitalTube.clearBit(0 to 3); Clear bit display.
}
// DigitalTube.displayDot(1,true); //Bit0 display dot. Use before displayBit().
DigitalTube.displayBit(1,0); //DigitalTube.Display(bit,number); bit=0---3 number=0---9
pinMode(15, OUTPUT);//the buzzer is connected to GPIO15
}
void loop() {
adcVal = analogRead(34);//Read the ADC values of MQ2
displayFloatNum(adcVal);;//Four digit tube display adcVal values
if (adcVal > 1000) {//ADC value is greater than 1000
digitalWrite(15, HIGH); // buzzer alarming
} else {//or else
digitalWrite(15, LOW); //Turn off the buzzer
}
delay(100);//delay 100ms
}
www.keyestudio.com
keyestudio
DigitalTube.displayBit(3, dat%1000/100);
DigitalTube.displayBit(4, dat%100/10);
return;
}
if(dat%10000/1000 != 0){
DigitalTube.clearBit(1);
DigitalTube.displayBit(2, dat%10000/1000);
DigitalTube.displayBit(3, dat%1000/100);
DigitalTube.displayBit(4, dat%100/10);
return;
}
if(dat%1000/100 != 0){
DigitalTube.clearBit(1);
DigitalTube.clearBit(2);
DigitalTube.displayBit(3, dat%1000/100);
DigitalTube.displayBit(4, dat%100/10);
return;
}
DigitalTube.clearBit(1);
DigitalTube.clearBit(2);
DigitalTube.clearBit(3);
DigitalTube.displayBit(4, dat%100/10);
}
//**********************************************************************************
6. Code Explanation
Define an integer variable val to store the analog value of the smoke
sensor, and then we display the analog value in the four-digit digital tube,
and then set a threshold, and when the threshold is reached, the buzzer
will sound.
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
www.keyestudio.com
keyestudio
use a USB cable to power on. When the concentration of combustible gas
exceeds the standard, the active buzzer module will give an alarm, and
1. Description
combine the active buzzer, the MQ-3 alcohol sensor, and a four-digit
digital tube to test the alcohol concentration through the alcohol sensor.
Then, the concentration to control the active buzzer alarm and the
www.keyestudio.com
keyestudio
2. Components Required
Keyestudio DIY
ESP32 Board*1 ESP32 Expansion Board*1 Active Buzzer*1 TM1650 4-Digit
Tube Display*1
keyestudio Alcohol
3P Dupont Wire*2 4P Dupont Wire*1 Micro USB Cable*1
Sensor*1
3. Connection Diagram
4. Test Code
www.keyestudio.com
keyestudio
//**********************************************************************************
/*
* Filename : breathalyzer
* Description : MQ3 controls a buzzer and a four-digit tube to simulate a breathalyzer.
* Auther : http//www.keyestudio.com
*/
#include "TM1650.h" //Import the TM1650 library file
int adcVal = 0; //display ADC value
//the interfaces are GPIO21 and GPIO22
#define DIO 21
#define CLK 22
TM1650 DigitalTube(CLK,DIO);
void setup() {
DigitalTube.setBrightness(); //set brightness, 0---7, default : 2
DigitalTube.displayOnOFF(); //display on or off, 0=display off, 1=display on, default : 1
for(char b=1;b<5;b++){
DigitalTube.clearBit(b); //DigitalTube.clearBit(0 to 3); Clear bit display.
}
// DigitalTube.displayDot(1,true); //Bit0 display dot. Use before displayBit().
DigitalTube.displayBit(1,0); //DigitalTube.Display(bit,number); bit=0---3 number=0---9
pinMode(15, OUTPUT);//the buzzer is connected to GPIO15
}
void loop() {
adcVal = analogRead(34);//Read the ADC values of MQ3
displayFloatNum(adcVal);//Four digit tube display adcVal values
if (adcVal > 1000) {//ADC value is greater than 1000
digitalWrite(15, HIGH); // buzzer alarming
} else {//or else
digitalWrite(15, LOW); //Turn off the buzzer
}
delay(100);//delay 100ms
}
www.keyestudio.com
keyestudio
DigitalTube.displayBit(3, dat%1000/100);
DigitalTube.displayBit(4, dat%100/10);
return;
}
if(dat%10000/1000 != 0){
DigitalTube.clearBit(1);
DigitalTube.displayBit(2, dat%10000/1000);
DigitalTube.displayBit(3, dat%1000/100);
DigitalTube.displayBit(4, dat%100/10);
return;
}
if(dat%1000/100 != 0){
DigitalTube.clearBit(1);
DigitalTube.clearBit(2);
DigitalTube.displayBit(3, dat%1000/100);
DigitalTube.displayBit(4, dat%100/10);
return;
}
DigitalTube.clearBit(1);
DigitalTube.clearBit(2);
DigitalTube.clearBit(3);
DigitalTube.displayBit(4, dat%100/10);
}
//**********************************************************************************
5. Code Explanation
Define an integer variable val to store the ADC value of the alcohol
sensor, then we display the analog value in the four-digit display module
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
www.keyestudio.com
keyestudio
use a USB cable to power on. When different alcohol concentrations are
detected, the active buzzer module will alarm, and the four-digit digital
1. Description
We know that bats use echoes to determine the direction and the
location of their preys. In real life, sonar is used to detect sounds in the
rate of sound waves in the water is much smaller, so sound waves are
www.keyestudio.com
keyestudio
2. Required Components
Keyestudio DIY
4P Dupont 3P Dupont Micro USB
TM1650 4-Digit
Wire*3 Wire*1 Cable*1
Tube Display*1
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************************
/*
* Filename : Ultrasonic radar
* Description : Ultrasonic control four digit tube, buzzer and RGB analog ultrasonic radar.
* Auther : http//www.keyestudio.com
*/
#include "TM1650.h" //Import the TM1650 library file
//the interfaces are GPIO21 and GPIO22
#define DIO 21
#define CLK 22
TM1650 DigitalTube(CLK,DIO);
int ledPins[] = {0, 2, 15}; //define red, green, blue led pins
const byte chns[] = {0, 1, 2}; //define the pwm channels
www.keyestudio.com
keyestudio
delayMicroseconds(2);
// The sensor is triggered by a high pulse of 10 microseconds or more
digitalWrite(TrigPin, HIGH);
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
// Read the signal from the sensor: a high level pulse,
//Its duration is the time (in microseconds) from sending the ping command to receiving the echo from
the object。
float distance = pulseIn(EchoPin, HIGH) / 58.00; //Convert to distance
delay(10);
return distance;
}
void setup() {
DigitalTube.setBrightness(); //set brightness, 0---7, default : 2
DigitalTube.displayOnOFF(); //display on or off, 0=display off, 1=display on, default : 1
for(char b=1;b<5;b++){
DigitalTube.clearBit(b); //DigitalTube.clearBit(0 to 3); Clear bit display.
}
// DigitalTube.displayDot(1,true); //Bit0 display dot. Use before displayBit().
DigitalTube.displayBit(1,0); //DigitalTube.Display(bit,number); bit=0---3 number=0---9
pinMode(TrigPin, OUTPUT);//Sets the Trig pin as output
pinMode(EchoPin, INPUT); //Set the Echo pin as input
ledcSetup(3, 1000, 8);//setup the pwm channels,1KHz,8bit
ledcAttachPin(18, 3);
for (int i = 0; i < 3; i++) { //setup the pwm channels,1KHz,8bit
ledcSetup(chns[i], 1000, 8);
ledcAttachPin(ledPins[i], chns[i]);
}
}
void loop() {
distance = checkdistance(); //Ultrasonic ranging
displayFloatNum(distance); //Nixie tube shows distance
if (distance <= 10) {
ledcWrite(3, 100);
delay(100);
ledcWrite(3, 0);
ledcWrite(chns[0], 255); //Common cathode LED, high level to turn on the led.
ledcWrite(chns[1], 0);
ledcWrite(chns[2], 0);
www.keyestudio.com
keyestudio
ledcWrite(3, 200);
delay(200);
ledcWrite(3, 150);
ledcWrite(chns[0], 0);
ledcWrite(chns[1], 255);
ledcWrite(chns[2], 0);
} else {
ledcWrite(3, 0);
ledcWrite(chns[0], 0);
ledcWrite(chns[1], 0);
ledcWrite(chns[2], 255);
}
}
www.keyestudio.com
keyestudio
DigitalTube.displayBit(4, dat%100/10);
}
//**********************************************************************************
5. Code Explanation
range.
6. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. When the ultrasonic sensor detects
sound, the RGB will show different colors, and the measured distances
www.keyestudio.com
keyestudio
Project 57: IR Remote Control
1. Introduction
adjust the brightness of a light through PWM, and how to use the
button value, thus you can adjust the brightness. Control the LED to turn
www.keyestudio.com
keyestudio
on or turn off is in the same way. If we want to use the same button to
control the LED to turn on or turn off, we can achieve it through the code.
2. Components
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************************
/*
* Filename : IR Control LED
* Description : Remote controls LED on and off
* Auther : http//www.keyestudio.com
*/
#include <Arduino.h>
#include <IRremoteESP8266.h>
#include <IRrecv.h>
#include <IRutils.h>
void setup() {
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
pinMode(led, OUTPUT);
}
////////////////////
www.keyestudio.com
keyestudio
void loop() {
if(irrecv.decode(&results)) { // Waiting for decoding
serialPrintUint64(results.value, HEX);// Print out the decoded results
Serial.print("");
handleControl(results.value); // Handle the commands from remote control
irrecv.resume(); // Receive the next value
}
}
void handleControl(unsigned long value) {
if (value == 0xFF6897) // Receive the number '1'
{
digitalWrite(led, HIGH);//turn on LED
Serial.println(" led on");
}
else if (value == 0xFF9867) // Receive the number '2'
{
digitalWrite(led, LOW);//turn off LED
Serial.println(" led off");
}
}
//**********************************************************************************
5. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set the baud
rate to 9600. Press the button 1 of the remote, which will be displayed on
the monitor, and the LED will be on. Similarly, press the button 2 , the LED
will be off.
www.keyestudio.com
keyestudio
1. Description
www.keyestudio.com
keyestudio
cooling device in this experiment. When the ambient temperature is
higher than a certain value, the motor is turned on, thereby reducing the
2. Required Components
Keyestudio
keyestudio 130
ESP32 Board*1 ESP32 Expansion Board*1 TM1650 4-Digit
Motor*1
Segment Display*1
Keyestudio 18B20
3P Dupont Wire*1 4P Dupont Wire*2 Micro USB Cable*1
Temperature Sensor*1
Battery(provide for
Battery Holder*1
yourself)*6
www.keyestudio.com
keyestudio
3. Connection Diagram
4. Test Code
//**********************************************************************************
/*
* Filename : heat abstractor
* Description : DS18B20 controls a four digit tube and a motor that simulates Heat Abstractor
* Auther : http//www.keyestudio.com
*/
www.keyestudio.com
keyestudio
#include <DS18B20.h>
#include "TM1650.h" //Import the TM1650 library file
//The two ports are GP21 and GP22
#define DIO 21
#define CLK 22
TM1650 DigitalTube(CLK,DIO);
//ds18b20 pin to 13
DS18B20 ds18b20(13);
void setup() {
Serial.begin(9600);
DigitalTube.setBrightness(); //set brightness, 0---7, default : 2
DigitalTube.displayOnOFF(); //display on or off, 0=display off, 1=display on, default : 1
for(char b=1;b<5;b++){
DigitalTube.clearBit(b); //DigitalTube.clearBit(0 to 3); Clear bit display.
}
// DigitalTube.displayDot(1,true); //Bit0 display dot. Use before displayBit().
DigitalTube.displayBit(1,0); //DigitalTube.Display(bit,number); bit=0---3 number=0---9
//Motor is connected to 15 4
pinMode(15, OUTPUT);
pinMode(4, OUTPUT);
}
void loop() {
double temp = ds18b20.GetTemp();//Read the temperature
temp *= 0.0625;//The conversion accuracy is 0.0625/LSB
Serial.println(temp);
displayFloatNum(temp);//4- digit tube display temperature value
if (temp > 25) {//When the temperature exceeds 25 degrees Celsius, turn on the fan
digitalWrite(15, LOW);
digitalWrite(4, HIGH);
} else {//Otherwise, turn off the fan.
digitalWrite(15, LOW);
digitalWrite(4, LOW);
}
delay(100);
}
www.keyestudio.com
keyestudio
if(dat/10000 != 0){
DigitalTube.displayBit(1, dat%100000/10000);
DigitalTube.displayBit(2, dat%10000/1000);
DigitalTube.displayBit(3, dat%1000/100);
DigitalTube.displayBit(4, dat%100/10);
return;
}
if(dat%10000/1000 != 0){
DigitalTube.clearBit(1);
DigitalTube.displayBit(2, dat%10000/1000);
DigitalTube.displayBit(3, dat%1000/100);
DigitalTube.displayBit(4, dat%100/10);
return;
}
if(dat%1000/100 != 0){
DigitalTube.clearBit(1);
DigitalTube.clearBit(2);
DigitalTube.displayBit(3, dat%1000/100);
DigitalTube.displayBit(4, dat%100/10);
return;
}
DigitalTube.clearBit(1);
DigitalTube.clearBit(2);
DigitalTube.clearBit(3);
DigitalTube.displayBit(4, dat%100/10);
}
//**********************************************************************************
5. Code Explanation
The setting of variables and the storage of detection values are the same
control the rotation of the motor when the threshold is exceeded, and
www.keyestudio.com
keyestudio
6. Test Result
power on. Switch the DIP switch on the ESP32 expansion board to the ON
end, compile and upload the code to the ESP32. After uploading
below. If this value exceeds the value we set, the fan will rotate to
dissipate heat.
1. Description
In this project, we use the RFID522 card swiping module and the servo to
www.keyestudio.com
keyestudio
simple.We use RFID522 swipe card module, an IC card or key card to
unlock.
2. Required Components
Keyestudio RFID
Servo*1 4P Dupont Wire*1 Micro USB Cable*1
Module*1
3. Connection Diagram
www.keyestudio.com
keyestudio
4. Test Code
values.You can substitute your own IC cards and keys values for the
in the program
code with your own IC cards and keys values read by the
RFID-MFRC522 module.
//*************************************************************************************
/*
* Filename : Intelligent_access_control
www.keyestudio.com
keyestudio
* Description : RFID controlled steering gear simulated door opening
* Auther : http//www.keyestudio.com
*/
#include <Wire.h>
#include "MFRC522_I2C.h"
// IIC pins default to GPIO21 and GPIO22 of ESP32
// 0x28 is the i2c address of SDA, if doesn't match,please check your address with i2c.
MFRC522 mfrc522(0x28); // create MFRC522.
#include <ESP32Servo.h>
Servo myservo; // create servo object to control a servo
int servoPin = 15; // Servo motor pin
void setup() {
Serial.begin(9600);
Wire.begin();
mfrc522.PCD_Init();
ShowReaderDetails(); // dispaly PCD - MFRC522 read carder
Serial.println(F("Scan PICC to see UID, type, and data blocks..."));
void loop() {
if ( ! mfrc522.PICC_IsNewCardPresent() || ! mfrc522.PICC_ReadCardSerial() ) {
delay(50);
return;
}
// save UID
rfid_str = ""; //String emptying
Serial.print(F("Card UID:"));
for (byte i = 0; i < mfrc522.uid.size; i++) {
rfid_str = rfid_str + String(mfrc522.uid.uidByte[i], HEX); //Convert to string
//Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
//Serial.print(mfrc522.uid.uidByte[i], HEX);
www.keyestudio.com
keyestudio
}
Serial.println(rfid_str);
void ShowReaderDetails() {
// attain the MFRC522 software
byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
Serial.print(F("MFRC522 Software Version: 0x"));
Serial.print(v, HEX);
if (v == 0x91)
Serial.print(F(" = v1.0"));
else if (v == 0x92)
Serial.print(F(" = v2.0"));
else
Serial.print(F(" (unknown)"));
Serial.println("");
// when returning to 0x00 or 0xFF, may fail to transmit communication signals
if ((v == 0x00) || (v == 0xFF)) {
Serial.println(F("WARNING: Communication failure, is the MFRC522 properly connected?"));
}
}
//*************************************************************************************
5. Code Explanation
In the previous experiment, our card swipe module has tested the
6. Test Result
www.keyestudio.com
keyestudio
Connect the wires according to the experimental wiring diagram, compile
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. Open the serial monitor and set the baud
rate to 9600. When we use the IC card or blue key to swipe the card, the
monitor displays the card and the key information and “open the door”
,
Project 60:Bluetooth
This chapter mainly introduces how to use the bluetooth of ESP32 for
www.keyestudio.com
keyestudio
conventional bluetooth, and experiment 60.2 is bluetooth control LED.
1. Components
terminal for a study. If you haven’t install it, please click the installation:
https://www.appsapk.com/serial-bluetooth-terminal/ .
2. Component Knowledge
into two types, namely low power bluetooth (BLE) and classic bluetooth.
www.keyestudio.com
keyestudio
There are two modes for simple data transfer: master mode and slave
mode.
Master Mode: In this mode, work is done on the master device and can
request in the main mode, information such as the address and pairing
password of other bluetooth devices are required. Once paired, you can
Slave Mode: A bluetooth module in the slave mode can only accept
requests. After being connected to a host device, it can send and receive
data through the host device. Bluetooth devices can interact with each
other, when they interact, the bluetooth device in the main mode searches
data. For example, when a mobile phone exchanges data with ESP32, the
mobile phone is usually in master mode and the ESP32 is in slave mode.
www.keyestudio.com
keyestudio
3. Wiring Diagram
We can use a USB cable to connect ESP32 mainboard to the USB port on
a computer.
4. Test Code
//**********************************************************************************
/*
* Filename : Classic Bluetooth--SerialToSerialBT
* Description : ESP32 communicates with the phone by bluetooth and print phone's data via a serial port
* Auther : http//www.keyestudio.com
*/
#include "BluetoothSerial.h"
BluetoothSerial SerialBT;
String buffer;
void setup() {
Serial.begin(115200);
www.keyestudio.com
keyestudio
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.println("\nThe device started, now you can pair it with bluetooth!");
}
void loop() {
if (Serial.available()) {
SerialBT.write(Serial.read());
}
if (SerialBT.available()) {
Serial.write(SerialBT.read());
}
delay(20);
}
//**********************************************************************************
5. Test Result
Compile and upload the code to the ESP32. After uploading successfully,
we will use a USB cable to power on. Open the serial monitor and set the
baud rate to 115200. When you see the serial prints the character, as
shown below, it means that the ESP32's bluetooth is waiting for connect
ion with a phone. (If open the serial monitor and set the baud rate to
115200, the information is not displayed, please press the RESET button
of the ESP32)
www.keyestudio.com
keyestudio
Ensure that your mobile phone bluetooth is enabled and the bluetooth
“ESP32 test”.
www.keyestudio.com
keyestudio
www.keyestudio.com
keyestudio
Open the software APP and click the left side of the terminal, select
"Devices".
www.keyestudio.com
keyestudio
Data can be transferred between your phone and a computer via ESP32
now.
Send “Hello!”, When the computer receives it, which will reply with "Hi!".
www.keyestudio.com
keyestudio
www.keyestudio.com
keyestudio
1. Components
2. Wiring Diagram
www.keyestudio.com
keyestudio
3. Test Code
//**********************************************************************************
/*
* Filename : Bluetooth Control LED
* Description : The phone controls esp32's led via bluetooth.
When the phone sends "LED_on," ESP32's LED lights turn on.
When the phone sends "LED_off," ESP32's LED lights turn off.
* Auther : http//www.keyestudio.com
*/
#include "BluetoothSerial.h"
#include "string.h"
#define LED 15
BluetoothSerial SerialBT;
char buffer[20];
static int count = 0;
void setup() {
pinMode(LED, OUTPUT);
SerialBT.begin("ESP32test"); //Bluetooth device name
Serial.begin(115200);
Serial.println("\nThe device started, now you can pair it with bluetooth!");
}
void loop() {
while(SerialBT.available())
{
buffer[count] = SerialBT.read();
count++;
}
if(count>0){
Serial.print(buffer);
if(strncmp(buffer,"led_on",6)==0){
digitalWrite(LED,HIGH);
}
if(strncmp(buffer,"led_off",7)==0){
digitalWrite(LED,LOW);
}
count=0;
memset(buffer,0,20);
}
}
//**********************************************************************************
www.keyestudio.com
keyestudio
4. Test Result
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. The APP operation is the same as the
project 60.1. To make the external LED on and off, simply change the
sending content to "led_on" and "led_off". Moving the APP to send data:
www.keyestudio.com
keyestudio
LED Circumstance
www.keyestudio.com
keyestudio
www.keyestudio.com
keyestudio
Note: If the sent content is not "led-on 'or" led-off ", the status of the
LED will not change. If the LED is on, it remains on when irrelevant
1. Description
ESP32 has three different WiFi modes: Station mode, AP mode and
www.keyestudio.com
keyestudio
with WiFi running mode before using, otherwise the WiFi cannot be used.
In this project, we are going to learn the WiFi Station mode of the ESP32.
2. Components
3. Wiring Diagram
4. Component Knowledge
Station mode:
When setting Station mode, the ESP32 is taken as a WiFi client. It can
the router via a WiFi connection. As shown in the figure below, the PC
and the router have been connected. If the ESP32 wants to communicate
www.keyestudio.com
keyestudio
with the PC, the PC and the router need to be connected.
5. Test Code
Since WiFi names and passwords vary from place to place, thereby users
need to enter the correct WiFi names and passwords in the box shown
www.keyestudio.com
keyestudio
//**********************************************************************************
/*
* Filename : WiFi Station
* Description : Connect to your router using ESP32
* Auther : http//www.keyestudio.com
*/
#include <WiFi.h> //Include the WiFi Library header file of ESP32.
void setup(){
Serial.begin(115200);
delay(2000);
Serial.println("Setup start");
www.keyestudio.com
keyestudio
WiFi.begin(ssid_Router, password_Router);//Set ESP32 in Station mode and connect it to your router.
Serial.println(String("Connecting to ")+ssid_Router);
//Check whether ESP32 has connected to router successfully every 0.5s.
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("\nConnected, IP address: ");
Serial.println(WiFi.localIP());//Serial monitor prints out the IP address assigned to ESP32.
Serial.println("Setup End");
}
void loop() {
}
//**********************************************************************************
6. Test Result
After entering the correct WiFi names and passwords, compile and
upload the code to the ESP32. After uploading successfully,we will use a
USB cable to power on. Open the serial monitor and set the baud rate to
monitor prints out the IP address, then monitor will display as follows: (If
open the serial monitor and set the baud rate to 115200, the information
www.keyestudio.com
keyestudio
1. Description
In this project, we are going to learn the WiFi AP mode of the ESP32.
2. Components
3. Wiring Diagram
www.keyestudio.com
keyestudio
4. Component Knowledge
AP Mode:
ESP32.
www.keyestudio.com
keyestudio
5. Test Code
Before running the code, you can make any changes to the ESP32 AP
//**********************************************************************************
/*
* Filename : WiFi AP
* Description : Set ESP32 to open an access point
* Auther : http//www.keyestudio.com
*/
#include <WiFi.h> //Include the WiFi Library header file of ESP32.
www.keyestudio.com
keyestudio
const char *ssid_AP = "ESP32_WiFi"; //Enter the router name
const char *password_AP = "12345678"; //Enter the router password
void setup(){
Serial.begin(115200);
delay(2000);
Serial.println("Setting soft-AP configuration ... ");
WiFi.disconnect();
WiFi.mode(WIFI_AP);
Serial.println(WiFi.softAPConfig(local_IP, gateway, subnet) ? "Ready" : "Failed!");
Serial.println("Setting soft-AP ... ");
boolean result = WiFi.softAP(ssid_AP, password_AP);
if(result){
Serial.println("Ready");
Serial.println(String("Soft-AP IP address = ") + WiFi.softAPIP().toString());
Serial.println(String("MAC address = ") + WiFi.softAPmacAddress().c_str());
}else{
Serial.println("Failed!");
}
Serial.println("Setup End");
}
void loop() {
}
//**********************************************************************************
6. Test Result
Compile and upload the code to the ESP32. After uploading successfully,
we will use a USB cable to power on. Open the serial monitor and set the
baud rate to 115200, then monitor will display as follows: (If open the
serial monitor and set the baud rate to 115200, the information is not
www.keyestudio.com
keyestudio
displayed, please press the RESET button of the ESP32)
the WiFi scanning function of the mobile phone, you can see the ssid_AP
www.keyestudio.com
keyestudio
1. Description
In this project, we are going to learn the AP+Station mode of the ESP32.
2. Components
3. Wiring Diagram
www.keyestudio.com
keyestudio
4. Component Knowledge
AP+Station mode:
In addition to the AP mode and the Station mode, AP+Station mode can
be used at the same time. Turn on the Station mode of the ESP32,
5. Test Code
www.keyestudio.com
keyestudio
//**********************************************************************************
/*
* Filename : WiFi AP+Station
* Description : ESP32 connects to the user's router, turning on an access point
* Auther : http//www.keyestudio.com
*/
#include <WiFi.h>
void setup(){
Serial.begin(115200);
www.keyestudio.com
keyestudio
Serial.println("Setting soft-AP configuration ... ");
WiFi.disconnect();
WiFi.mode(WIFI_AP);
Serial.println("Setting soft-AP ... ");
boolean result = WiFi.softAP(ssid_AP, password_AP);
if(result){
Serial.println("Ready");
Serial.println(String("Soft-AP IP address = ") + WiFi.softAPIP().toString());
Serial.println(String("MAC address = ") + WiFi.softAPmacAddress().c_str());
}else{
Serial.println("Failed!");
}
void loop() {
}
//**********************************************************************************
6. Test Result
Ensure that the code in the program has been modified correctly,
compile and upload the code to the ESP32. After uploading successfully,
we will use a USB cable to power on. Open the serial monitor and set the
baud rate to 115200, then monitor will display as follows: (If open the
serial monitor and set the baud rate to 115200, the information is not
www.keyestudio.com
keyestudio
displayed, please press the RESET button of the ESP32)
Open the WiFi scanning function of the mobile phone, you can see the
ssid_AP.
www.keyestudio.com
keyestudio
1. Introduction
different functions.
www.keyestudio.com
keyestudio
2. Components Required
Keyestudi
Keyestudio DIY Keyestudio
ESP32 Expansion Keyestudio Obstacle
ESP32 Board*1 Purple LED Rotary
Board*1 Button Module*1 Avoidanc
Module*1 Potentiometer*1
Sensor*1
Keyestudio
Keyestudio Keyestudio XHT11 Keyestudi
Keyestudio
Keyestudio DIY HC-SR04 DIYCommon Temperature ADXL345
Line Tracking
Joystick Module*1 Ultrasonic Cathode RGB and Humidity Accelerati
Sensor*1
sensor *1 Module *1 Sensor Sensor*1
*1
MicroUSB
3PDupont Wire*6 4PDupont Wire*3 5PDupont Wire*1
Cable*1
3. Wiring Diagram
www.keyestudio.com
keyestudio
4. Test Code
//**********************************************************************
/*
* Filename : Comprehensive experiment
* Description : Multiple sensors/modules work together
* Auther : http//www.keyestudio.com
*/
#include "xht11.h"
#include "adxl345_io.h"
//ADXL345 sda-->21,scl-->22
adxl345 adxl345(21, 22);
www.keyestudio.com
keyestudio
//xht11 to gpio15
xht11 xht(15);
void counter() {
delay(10);
ir_flag = 0;
www.keyestudio.com
keyestudio
if (!digitalRead(button)) {
PushCounter++;
}
}
void setup() {
Serial.begin(9600);//Set baud rate to 9600
pinMode(KEY, INPUT);//Button of remote sensing module
ledcSetup(CHAN, 1000, 12);
ledcAttachPin(PIN_LED, CHAN);
pinMode(button, INPUT);//The key module
attachInterrupt(digitalPinToInterrupt(button), counter, FALLING); //External interrupt 0, falling edge
fired
pinMode(Avoid, INPUT);//Obstacle avoidance sensor
pinMode(Trig, OUTPUT);//Ultrasonic module
pinMode(Echo, INPUT);
adxl345.Init();
for (int i = 0; i < 3; i++) { //setup the pwm channels,1KHz,8bit
ledcSetup(chns[i], 1000, 8);
ledcAttachPin(ledPins[i], chns[i]);
delay(1000);
}
}
void loop() {
yushu = PushCounter % 8;
if (yushu == 0) { //The remainder is 0
yushu_0(); //rgb displays
} else if (yushu == 1) { //The remainder is 1
yushu_1(); //Displays the high and low levels read by the tracking sensor
} else if (yushu == 2) { //The remainder is 2
yushu_2(); //Display temperature and humidity value
} else if (yushu == 3) { //The remainder is 3
yushu_3(); //Displays the rocker value
}else if (yushu == 4) { //The remainder is 4
yushu_4(); //Display potentiometer ADC value and potentiometer control LED
} else if (yushu == 5) { //The remainder is 5
yushu_5(); //Obstacle avoidance sensor detects obstacles
} else if (yushu == 6) { //The remainder is 6
yushu_6(); //Shows the distance detected by ultrasound
} else if (yushu == 7) { //The remainder is 7
yushu_7(); //ADXL345 triaxial acceleration value
}
www.keyestudio.com
keyestudio
}
//RGB
void yushu_0() {
red = random(0, 256);
green = random(0, 256);
blue = random(0, 256);
setColor(red, green, blue);
delay(200);
}
void setColor(byte r, byte g, byte b) {
ledcWrite(chns[0], 255 - r); //Common anode LED, low level to turn on the led.
ledcWrite(chns[1], 255 - g);
ledcWrite(chns[2], 255 - b);
}
void yushu_1() {
int val = digitalRead(TrackingPin);//Read the digital level output by the tracking sensor
Serial.print(val);//Serial port print value
if (val == 0) {//White val is 0 detected
Serial.print(" ");
Serial.println("White");
delay(100);
}
else {//Black val is 1 detected
Serial.print(" ");
Serial.println("Black");
delay(100);
}
}
void yushu_2() {
if (xht.receive(dht)) { //Returns true when checked correctly
Serial.print("RH:");
Serial.print(dht[0]); //The integral part of humidity, DHT [1] is the fractional part
Serial.print("% ");
Serial.print("Temp:");
Serial.print(dht[2]); //The integral part of temperature, DHT [3] is the fractional part
Serial.println("C");
} else { //read error
Serial.println("sensor error");
}
delay(1200);
www.keyestudio.com
keyestudio
}
void yushu_3() {
int x = analogRead(X);
int y = analogRead(Y);
int key = digitalRead(KEY);
Serial.print("X:");
Serial.print(x);
Serial.print(" Y:");
Serial.print(y);
Serial.print(" KEY:");
Serial.println(key);
delay(100);
}
void yushu_4() {
int adcVal = analogRead(resPin); //read adc
Serial.println(adcVal);
int pwmVal = adcVal; // adcVal re-map to pwmVal
ledcWrite(CHAN, pwmVal); // set the pulse width.
delay(10);
}
void yushu_5() {
int val = digitalRead(Avoid);
if (val == 0) {//Obstruction detected
Serial.println("There are obstacles");
}
else {//No obstructions detected
Serial.println("All going well");
}
delay(100);
}
void yushu_6() {
float distance = checkdistance();
Serial.print("distance:");
Serial.print(distance);
Serial.println("cm");
delay(100);
}
void yushu_7() {
www.keyestudio.com
keyestudio
adxl345.readXYZ(&out_X, &out_Y, &out_Z);
Serial.print(out_X);
Serial.print("g ");
Serial.print(out_Y);
Serial.print("g ");
Serial.print(out_Z);
Serial.println("g");
delay(100);
}
float checkdistance() {
digitalWrite(Trig, LOW);
delayMicroseconds(2);
digitalWrite(Trig, HIGH);
delayMicroseconds(10);
digitalWrite(Trig, LOW);
float distance = pulseIn(Echo, HIGH) / 58.00;
delay(10);
return distance;
}
//*************************************************************************************
5. Code Explanation
1. Calculate how many times the button is pressed, divide it by 8, and get
the wiring, and then change the experimental function in the code.
6. Test Result
www.keyestudio.com
keyestudio
and upload the code to the ESP32. After uploading successfully,we will
use a USB cable to power on. At the beginning, the number of the button
is 0 and remainder is 0. Open the monitor and set baud rate to 9600.
Press the button, the RGB stops flashing, press once, the remainder is 1.
objects by a line tracking sensor. If the sensor does not detect an object
or detects a black object, val is 1, and the serial monitor displays the
and the serial monitor displays the character "0 White", the serial monitor
Press a key twice, the time of pressing buttons is 2 and the remainder is 2.
www.keyestudio.com
keyestudio
Press a key again, the time of pressing buttons is 3 and the remainder is 3.
below;
Press the key for the fourth time, the remainder is 4. Then the
potentiometer can adjust the PWM value at the GPI05 port to control LED
www.keyestudio.com
keyestudio
Press the key for the fifth time, the remainder is 5. Then the ultrasonic
Press the key for the sixth time, the remainder is 6. Then the ultrasonic
www.keyestudio.com
keyestudio
Press the key for seventh time and the remainder is 7. The monitor will
Press the key for eighth time and the remainder is 0. Then the RGB will
flash. If you press keys incessantly, remainders will change in a loop way.
So does functions.
www.keyestudio.com
keyestudio
Project 65: WiFi smart home
1. Description
In the previous experiment, we have learned the WiFi Station mode, WiFi
AP mode and WiFi AP+Station mode of the ESP32. In this project, We will
2. Components
Keyestudio
XHT11
Temperature and Keyestudio HC-SR04 Smart Phone/PC*1
3P Dupont*2 4P Dupont*2
Humidity Sensor Ultrasonic Sensor*1
(compatible
DHT11)*1
www.keyestudio.com
keyestudio
3. Wiring Diagram
www.keyestudio.com
keyestudio
4. Install APP
Now transfer the keyes wifi.apk file in the Android APP installation
package to the Android phone or PC, click the keyes wifi.apk file to enter
the installation page, click "ALLOW" key, and then click "INSTALL" button.
www.keyestudio.com
keyestudio
www.keyestudio.com
keyestudio
www.keyestudio.com
keyestudio
www.keyestudio.com
keyestudio
B. Enter keyes link in the search box and click search, the download
interface appears. Click " " to download and install the APP of the
system. You can refer to the steps of Android system above for operation.
5. Test Code
//**********************************************************************************
/*
www.keyestudio.com
keyestudio
* Filename : WiFi Smart Home.
* Description : WiFi APP controls Multiple sensors/modules work to achieve the effect of WiFi smart home.
* Auther : http//www.keyestudio.com
*/
#include <Arduino.h>
#include <WiFi.h>
#include <ESPmDNS.h>
#include <WiFiClient.h>
#include "xht11.h"
//gpio15
xht11 xht(27);
unsigned char dht[4] = {0, 0, 0, 0};
#include <ESP32Servo.h>
Servo myservo;
int servoPin = 21;
#define Relay 4
#define IN1 2 //IN1 corresponds to IN+
#define IN2 15 //IN2 corresponds to IN-
#define trigPin 12
#define echoPin 13
int distance1;
String dis_str;
int ip_flag = 1;
int ultra_state = 1;
int temp_state = 1;
int humidity_state = 1;
void setup() {
Serial.begin(115200);
pinMode(Relay, OUTPUT);
myservo.setPeriodHertz(50);
myservo.attach(servoPin, 500, 2500);
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
www.keyestudio.com
keyestudio
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.begin();
Serial.println("TCP server started");
MDNS.addService("http", "tcp", 80);
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
digitalWrite(Relay, LOW);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
WiFiClient client = server.available();
if (!client) {
return;
}
while(client.connected() && !client.available()){
delay(1);
}
String req = client.readStringUntil('\r');
int addr_start = req.indexOf(' ');
int addr_end = req.indexOf(' ', addr_start + 1);
if (addr_start == -1 || addr_end == -1) {
Serial.print("Invalid request: ");
Serial.println(req);
return;
}
req = req.substring(addr_start + 1, addr_end);
item=req;
Serial.println(item);
String s;
if (req == "/")
www.keyestudio.com
keyestudio
{
IPAddress ip = WiFi.localIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n<!DOCTYPE HTML>\r\n<html>Hello from ESP32 at
";
s += ipStr;
s += "</html>\r\n\r\n";
Serial.println("Sending 200");
client.println(s);
}
else if(req == "/btn/0")
{
Serial.write('a');
client.println(F("turn on the relay"));
digitalWrite(Relay, HIGH);
}
else if(req == "/btn/1")
{
Serial.write('b');
client.println(F("turn off the relay"));
digitalWrite(Relay, LOW);
}
else if(req == "/btn/2")
{
Serial.write('c');
client.println("Bring the steering gear over 180 degrees");
myservo.write(180);
delay(200);
}
else if(req == "/btn/3")
{
Serial.write('d');
client.println("Bring the steering gear over 0 degrees");
myservo.write(0);
delay(200);
}
else if(req == "/btn/4")
{
Serial.write('e');
client.println("esp32 already turn on the fans");
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
}
www.keyestudio.com
keyestudio
else if(req == "/btn/5")
{
Serial.write('f');
client.println("esp32 already turn off the fans");
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
}
else if(req == "/btn/6")
{
Serial.write('g');
while(Serial.available() > 0)
{
unoData = Serial.readStringUntil('#');
client.println("Data");
}
while(ultra_state>0)
{
Serial.print("Distance = ");
Serial.print(checkdistance());
Serial.println("#");
Serial1.print("Distance = ");
Serial1.print(checkdistance());
Serial1.println("#");
int t_val1 = checkdistance();
client.print("Distance(cm) = ");
client.println(t_val1);
ultra_state = 0;
}
}
else if(req == "/btn/7")
{
Serial.write('h');
client.println("turn off the ultrasonic");
ultra_state = 1;
}
else if(req == "/btn/8")
{
Serial.write('i');
while(Serial.available() > 0)
{
unoData = Serial.readStringUntil('#');
client.println(unoData);
}
www.keyestudio.com
keyestudio
while(temp_state>0)
{
if (xht.receive(dht)) {
Serial.print("Temperature = ");
Serial.print(dht[2],1);
Serial.println("#");
Serial1.print("Temperature = ");
Serial1.print(dht[2],1);
Serial1.println("#");
int t_val2 = dht[2];
client.print("Temperature(℃) = ");
client.println(t_val2);
}
temp_state = 0;
}
}
else if(req == "/btn/9")
{
Serial.write('j');
client.println("turn off the temperature");
temp_state = 1;
}
else if(req == "/btn/10")
{
Serial.write('k');
while(Serial.available() > 0)
{
unoData = Serial.readStringUntil('#');
client.println(unoData);
}
while(humidity_state > 0)
{
if (xht.receive(dht)) {
Serial.print("Humidity = ");
Serial.print(dht[0],1);
Serial.println("#");
Serial1.print("Humidity = ");
Serial1.print(dht[0],1);
Serial1.println("#");
int t_val3 = dht[0];
client.print("Humidity(%) = ");
client.println(t_val3);
}
www.keyestudio.com
keyestudio
humidity_state = 0;
}
}
else if(req == "/btn/11")
{
Serial.write('l');
client.println("turn off the humidity");
humidity_state = 1;
}
//client.print(s);
client.stop();
}
int checkdistance() {
digitalWrite(12, LOW);
delayMicroseconds(2);
digitalWrite(12, HIGH);
delayMicroseconds(10);
digitalWrite(12, LOW);
int distance = pulseIn(13, HIGH) / 58;
delay(10);
return distance;
}
//**********************************************************************************
change the Wifi name and default Wifi password of the experiment
6. Test Result
www.keyestudio.com
keyestudio
After the code has been modified correctly, connect the external
power supply and power on. Switch the DIP switch ON the ESP32
expansion board to the ON end, compile and upload the code to the
button on the ESP32 mainboard with your hand after click , release it
Open the serial monitor and set baud rate to 115200, then the monitor
prints the detected WiFi IP address. (If open the serial monitor and set the
baud rate to 115200, the information is not displayed, please press the
。)
www.keyestudio.com
keyestudio
Open WiFi APP, enter the detected WIFI IP address in the text box in front
of the WIFI button (for example, the IP address detected by the serial
displayed in the text box :“Hello from ESP32 at 192.168.0.156”, then the
www.keyestudio.com
keyestudio
performed:
(1) Click button, the relay will be opened, the APP will
Click again, the relay will be closed , the APP will display
www.keyestudio.com
keyestudio
display ,the servo rotates 0°.
distance between the object and the ultrasonic sensor is 14cm ; click
www.keyestudio.com
keyestudio
(6) Click button , the temperature and humidity sensor
6. Resources
link:
https://fs.keyestudio.com/KS5003-5004
www.keyestudio.com