|
|
@ -0,0 +1,14 @@
|
|||
const int analogInPin = 12; // The photoresistor mimics the input pin
|
||||
int Lightvalue = 0; // Defining variables
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600); // Initialize the serial port baud rate
|
||||
pinMode(analogInPin,INPUT);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
Lightvalue = analogRead(analogInPin); // Read the value of light sensitivity
|
||||
Serial.print("Lightvalue = "); // Print the value of light sensitivity through the serial port
|
||||
Serial.println(Lightvalue);
|
||||
delay(200);
|
||||
}
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
# 10. Photoresistor
|
||||
|
||||
## 10.1 Overview
|
||||
In this section , you will learn how to use a light intensity detection module also called a photoresistor. The photoresistor
|
||||
detects the ambient light intensity and prints it to the serial monitor.
|
||||
|
||||
## 10.2 Working principle
|
||||
|
||||
### 10.2.1 Photoresistor
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/10.lesson_photoresistor.png" width="150" height="150"/>
|
||||
|
||||
Aphotoresistor is a resistor made by utilizing the photoelectric effect of semiconductors. The resistance value changes with
|
||||
the intensity of incident light. It is also called a photodetector. When the incident light is strong, the resistance decreases.
|
||||
Whenthe incident light is weak, the resistance increases. . There is another type where the resistance decreases when the
|
||||
incident light is weak and when the incident light is strong, the resistance increases. According to this characteristic,
|
||||
photoresistors with different shapes and irradiation areas can be manufactured.
|
||||
Working principle: Since the carriers generated by illumination participate in conduction and drift under the action of the
|
||||
external electric field, the electrons rush to the positive electrode of the power supply and the holes rush to the negative
|
||||
electrode of the power supply, thus causing the resistance of the photoresistor to drop rapidly. Photoresistors are generally
|
||||
|
||||
used for light measurement, light control and photoelectric conversion .
|
||||
|
||||
## 10.3 Connection lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/10.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 10.4 Upload code program
|
||||
|
||||
### 10.4.1 Connect the main control board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 10.4.2 Open the program file (path: 2_ESP32_S3_PLUS \ Lesson_10_Photoresistor )
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board, and wait for the program
|
||||
upload to be completed .
|
||||
After the program is uploaded, open the IDE serial port monitor and you can see the printed output light intensity value.
|
||||
Under normal lighting, the value is a maximum of 4095
|
||||
The detection value is <300 when covering the photoresistor with objects.
|
||||
|
||||
## 10.5 Code analysis
|
||||
|
||||
The variable Lightvalue that defines the analog input pin analogInPin of the photoresistor detection module and the light
|
||||
intensity value.
|
||||
|
||||
```cpp
|
||||
const int analogInPin = 12; // The photoresistor mimics the input pin
|
||||
int Lightvalue = 0; // Defining variables
|
||||
```
|
||||
|
||||
Set the photosensitive detection module pin as input, baud rate 9600
|
||||
|
||||
```cpp
|
||||
void setup() {
|
||||
Serial.begin(9600); // Initialize the serial port baud rate
|
||||
pinMode(analogInPin,INPUT);
|
||||
}
|
||||
```
|
||||
|
||||
The loop function first obtains the simulation value of the light detection module, saves it to a variable and prints it to the
|
||||
serial monitor.
|
||||
|
||||
```cpp
|
||||
void loop() {
|
||||
Lightvalue = analogRead(analogInPin); // Read the value of light sensitivity
|
||||
Serial.print("Lightvalue = "); // Print the value of light sensitivity through the serial port
|
||||
Serial.println(Lightvalue);
|
||||
delay(200);
|
||||
}
|
||||
|
||||
```
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
#include <Wire.h>
|
||||
#include <Adafruit_GFX.h>
|
||||
#include <Adafruit_SSD1306.h>
|
||||
|
||||
#define SCREEN_WIDTH 128 // Define the screen width to be 128 pixels
|
||||
#define SCREEN_HEIGHT 64 // Define the screen height to be 64 pixels
|
||||
#define OLED_RESET -1 // Define the OLED reset pin to -1 (or -1 if the reset function is not used)
|
||||
// Create an Adafruit_SSD1306 object that controls the OLED screen, specifying the screen width, height, I2C bus object, and reset pin
|
||||
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
|
||||
|
||||
#define Echo 18 // Define the ultrasonic Echo pin
|
||||
#define Trig 17 // Define the ultrasonic Trig pin
|
||||
int Udistance = 0; // Define the ultrasonic distance variable
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
pinMode(Echo, INPUT); // Define the pin operation mode as the input
|
||||
pinMode(Trig, OUTPUT); // Define the pin operation mode as output
|
||||
Wire.begin(5,4); // The initial I2C bus SDA pin is set to 5 and the SCL pin is set to 4
|
||||
|
||||
// Initializing the screen
|
||||
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
|
||||
Serial.println(F("SSD1306 initialization failed"));
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
}
|
||||
|
||||
void loop() {
|
||||
Udistance = GetDistance(); // Obtaining ultrasonic distance
|
||||
display.clearDisplay(); // Clear the screen buffer
|
||||
// Display ultrasonic distance
|
||||
display.setTextSize(2);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.setCursor(16, 8);
|
||||
display.println("Distance");
|
||||
display.setCursor(32, 40);
|
||||
display.print(Udistance);
|
||||
display.print(" cm");
|
||||
display.display();
|
||||
//delay(200); // Delay the next read for a while to adjust the update rate
|
||||
Serial.print("Distance = ");
|
||||
Serial.println(Udistance);
|
||||
}
|
||||
|
||||
float GetDistance() // Get ultrasonic sensor values
|
||||
{
|
||||
float distance;
|
||||
digitalWrite(Trig, LOW); // Sending a low level to the Trig triggers ranging
|
||||
delayMicroseconds(2);
|
||||
digitalWrite(Trig, HIGH);
|
||||
delayMicroseconds(10);
|
||||
digitalWrite(Trig, LOW);
|
||||
distance = pulseIn(Echo, HIGH) / 58.00; // Output distance conversion
|
||||
// delay(10);
|
||||
return distance;
|
||||
}
|
||||
|
|
@ -0,0 +1,167 @@
|
|||
# 11. Ultrasonic ranging
|
||||
|
||||
## 11.1 Overview
|
||||
|
||||
In this section you will learn how to use the Ultrasonic Module. The ultrasonic sensor is used to measure distance and the
|
||||
value is displayed on the OLED screen in real time.
|
||||
|
||||
## 11.2 Working principle
|
||||
|
||||
### 11.2.1 Ultrasonic sensor
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/11.lesson_ultrasonic.png" width="300" height="100"/>
|
||||
|
||||
Sound waves are produced by vibrations and can travel at different speeds in different media. Ultrasonic waves have the
|
||||
advantages of strong directivity, slow energy loss, and long propagation distance in media, and are often used for distance
|
||||
measurement. For example, distance meters, liquid level measuring instruments, etc. can all be realized through ultrasonic
|
||||
waves.
|
||||
|
||||
|||
|
||||
|----|----|
|
||||
|Electrical parameters|HC-SR04 Ultrasonic module|
|
||||
|Working voltage|DC-5V|
|
||||
|Working current|15mA|
|
||||
|Working frequency|40KHz|
|
||||
|Maximum range|4m|
|
||||
|Minimum range|2cm|
|
||||
|Measuring angle|15°|
|
||||
|Input trigger signal|10 USTTLpulse|
|
||||
|Output echo signal|Output TTL level signal, proportional to the range|
|
||||
|||
|
||||
|
||||
Ultrasonic ranging is a non-contact detection method , especially used in airborne ranging. Because the wave speed in the
|
||||
air is slow, the echo signal contained along the direction of structural information propagation is easy to detect and has very
|
||||
high resolution, so it The accuracy is higher than other methods; the ultrasonic sensor has the characteristics of simple
|
||||
structure, small size, and reliable signal processing. The use of ultrasonic detection is often faster, more convenient, simpler
|
||||
to calculate, easier to achieve real-time control, and can meet industrial practical requirements in terms of measurement
|
||||
accuracy.
|
||||
|
||||
There are many methods of ultrasonic ranging. The principle of this system in ultrasonic measurement is: the trigger signal
|
||||
input terminal ( TRIG ) will input a high-level signal of more than 10 microseconds.After receiving the signal, the
|
||||
ultrasonic transmitter will automatically send 8 A 40Hz square wave.At the same time, the timer will start. When the sensor
|
||||
receives the echo, it stops timing and outputs the echo signal. Detect the ultrasonic wave from the ultrasonic transmitter, the
|
||||
transmission time through the gas medium to the receiver , multiply this time by the speed of sound in the gas, and get the
|
||||
distance of sound propagation. That is, the ultrasonic transmitter emits ultrasonic waves in a certain direction, and the MCU
|
||||
starts timing at the same time. The ultrasonic waves are launched in the air and return immediately when encountering
|
||||
obstacles on the way. The ultrasonic receiver stops timing immediately after receiving the reflected waves.
|
||||
Trecorded by the timer , the distance ( s ) from the launch point to the obstacle can be calculated .
|
||||
|
||||
**Formula: S = VT/2**
|
||||
|
||||
Four factors limit the maximum measurable distance of an ultrasound system: the amplitude of the ultrasound wave, the
|
||||
texture of the reflector, the angle between the reflected and incident sound waves, and the sensitivity of the receiving
|
||||
transducer. The ability of the receiving transducer to directly receive the acoustic pulse will determine the minimum
|
||||
measurable distance.
|
||||
|
||||
### 11.2.2 OLED
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/11.lesson_oled.png" width="150" height="150"/>
|
||||
|
||||
1. Resolution: 128*64
|
||||
2. Super wide viewing angle: greater than 160
|
||||
3. Communication method: IIC
|
||||
4. Working voltage: 3.3V~5V
|
||||
|
||||
## 11.3 Connection lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/11.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 11.4 Upload code program
|
||||
|
||||
### 11.4.1 Connect the main control board to the computer with a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 11.4.2 Open the program file ( path : 2_ESP32_S3_PLUS \ Lesson_11_Ultrasonic_ranging_OLED_display )
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board, and wait for the program
|
||||
upload to be completed .
|
||||
After the program is uploaded, use an object to block the ultrasonic wave and see the measured distance value ( when the
|
||||
screen does not display correctly, you need to check the SCL/SDAwiring, or press the motherboard reset button to reset the
|
||||
program ).
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/11.lesson_oled_output.png" width="200" height="200"/>
|
||||
|
||||
## 11.5 Code analysis
|
||||
|
||||
Declare the required libraries. If the corresponding libraries are not added, please go back to the installation libraryto see how to add the libraries.
|
||||
|
||||
```cpp
|
||||
#include <Wire.h>
|
||||
#include <Adafruit_GFX.h>
|
||||
#include <Adafruit_SSD1306.h>
|
||||
```
|
||||
|
||||
Define the pixel parameters of the OLED screen and instantiate a screen object display
|
||||
|
||||
```cpp
|
||||
#define SCREEN_WIDTH 128 // Define the screen width to be 128 pixels
|
||||
#define SCREEN_HEIGHT 64 // Define the screen height to be 64 pixels
|
||||
#define OLED_RESET -1 // Define the OLED reset pin to -1 (or -1 if the reset function is not used)
|
||||
// Create an Adafruit_SSD1306 object that controls the OLED screen, specifying the screen width, height, I2C bus object, and reset pin
|
||||
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
|
||||
```
|
||||
|
||||
Define ultrasonic sensor pins and distance variables
|
||||
|
||||
```cpp
|
||||
#define Echo 18 // Define the ultrasonic Echo pin
|
||||
#define Trig 17 // Define the ultrasonic Trig pin
|
||||
int Udistance = 0; // Define the ultrasonic distance variable
|
||||
```
|
||||
|
||||
Set the ultrasonic pin Echo as input, Trig as output, initialize IIC bus and initialization screen, baud rate 9600
|
||||
|
||||
```cpp
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
pinMode(Echo, INPUT); // Define the pin operation mode as the input
|
||||
pinMode(Trig, OUTPUT); // Define the pin operation mode as output
|
||||
Wire.begin(5,4); // The initial I2C bus SDA pin is set to 5 and the SCL pin is set to 4
|
||||
|
||||
// Initializing the screen
|
||||
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
|
||||
Serial.println(F("SSD1306 initialization failed"));
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Ultrasonic acquisition distance function
|
||||
```cpp
|
||||
float GetDistance() // Get ultrasonic sensor values
|
||||
{
|
||||
float distance;
|
||||
digitalWrite(Trig, LOW); // Sending a low level to the Trig triggers ranging
|
||||
delayMicroseconds(2);
|
||||
digitalWrite(Trig, HIGH);
|
||||
delayMicroseconds(10);
|
||||
digitalWrite(Trig, LOW);
|
||||
distance = pulseIn(Echo, HIGH) / 58.00; // Output distance conversion
|
||||
// delay(10);
|
||||
return distance;
|
||||
}
|
||||
```
|
||||
|
||||
The loop function first obtains the distance value of the ultrasonic detection module and saves it to the variable Udistance.
|
||||
The value is output to the screen display through the display method of the screen object.
|
||||
|
||||
```cpp
|
||||
void loop() {
|
||||
Udistance = GetDistance(); // Obtaining ultrasonic distance
|
||||
display.clearDisplay(); // Clear the screen buffer
|
||||
// Display ultrasonic distance
|
||||
display.setTextSize(2);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.setCursor(16, 8);
|
||||
display.println("Distance");
|
||||
display.setCursor(32, 40);
|
||||
display.print(Udistance);
|
||||
display.print(" cm");
|
||||
display.display();
|
||||
//delay(200); // Delay the next read for a while to adjust the update rate
|
||||
Serial.print("Distance = ");
|
||||
Serial.println(Udistance);
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
#include <Wire.h>
|
||||
#include <Adafruit_GFX.h>
|
||||
#include <Adafruit_SSD1306.h>
|
||||
#include <DHT.h>
|
||||
|
||||
#define SCREEN_WIDTH 128 // Define the screen width to be 128 pixels
|
||||
#define SCREEN_HEIGHT 64 // Define the screen height to be 64 pixels
|
||||
#define OLED_RESET -1 // Define the OLED reset pin to -1 (or -1 if the reset function is not used)
|
||||
// Create an Adafruit_SSD1306 object that controls the OLED screen, specifying the screen width, height, I2C bus object, and reset pin
|
||||
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
|
||||
|
||||
#define DHTPIN 19 // The DHT11 sensor is connected to digital pin 4 of the Arduino
|
||||
#define DHTTYPE DHT11 // The DHT11 sensor was used
|
||||
DHT dht(DHTPIN, DHTTYPE); // Create DHT objects for connecting DHT sensors, specifying sensor pins and sensor models
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
Wire.begin(5,4); // The initial I2C bus SDA pin is set to 5 and the SCL pin is set to 4
|
||||
|
||||
// Initializing the screen
|
||||
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
|
||||
Serial.println(F("SSD1306 initialization failed"));
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
display.clearDisplay(); // Clear the screen buffer
|
||||
dht.begin(); // Initialize the DHT11 sensor
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Read the temperature and humidity data
|
||||
int humidity = dht.readHumidity();
|
||||
int temperature = dht.readTemperature();
|
||||
display.clearDisplay(); // Clear the screen buffer
|
||||
// Display temperature and humidity data
|
||||
display.setTextSize(1);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.setCursor(16, 20);
|
||||
display.print("Temperature: ");
|
||||
display.println(temperature);
|
||||
display.setCursor(16, 40);
|
||||
display.print("Humidity: ");
|
||||
display.print(humidity);
|
||||
display.println("%");
|
||||
display.display();
|
||||
delay(2000);
|
||||
}
|
||||
|
|
@ -0,0 +1,116 @@
|
|||
# 12. DHT11 temperature and humidity sensor
|
||||
|
||||
## 12.1. Overview
|
||||
In this tutorial, we will learn how to use the DHT11 temperature and humidity sensor. It's accurate enough for most projects
|
||||
where you need to detect humidity and temperature readings. Again, we will use a library specifically designed for these
|
||||
sensors, which will keep our code short and easy to write.
|
||||
|
||||
## 12.2. Working principle
|
||||
|
||||
### 12.2.1. DHT11 temperature and humidity sensor
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/12.lesson_dht11.png" width="100" height="150"/>
|
||||
|
||||
- **humidity:**
|
||||
- **Resolution:** 16Bit
|
||||
- **Resolution:** ±1% RH
|
||||
- **Accuracy:** ±5% RH at 25℃
|
||||
- **Interchangeability:** Interchangeable
|
||||
- **Response time:** 6S under 1/e(63%) 25℃, 1m/s air condition
|
||||
- **Hysteresis:** <±0.3% RH
|
||||
- **Long-term stability:** <±0.5% RH/year
|
||||
|
||||
**temperature:**
|
||||
|
||||
|||||
|
||||
|----|----|----|----|
|
||||
|**Resolution**|±2℃|**Lag**|<±0.3% RH|
|
||||
|**Repeatability**|±0.2℃|**Response time**|10S at 1/e (63%) condition|
|
||||
|**Interchangeability**|Interchangeable||||
|
||||
|||||
|
||||
|
||||
## 12.3 Connection lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/12.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 12.4 Upload code program
|
||||
|
||||
### 12.4.1 Connect the main control board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 12.4.2 Open the program file (path: 2_ESP32_S3_PLUS\ Lesson _ 12_DHT11_OLED_display )
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board, and wait for the program
|
||||
upload to be completed .
|
||||
After the program is uploaded, you will see the temperature and humidity values ( when the screen does not display
|
||||
correctly, you need to check the SCL/SDAwiring, or press the motherboard reset button to reset the program ).
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/12.lesson_oled_output.png" width="200" height="200"/>
|
||||
|
||||
### 12.5 Code analysis
|
||||
Declare the required library files. If the corresponding library is not added, please go back to the installation library
|
||||
to see
|
||||
how to add the library.
|
||||
|
||||
```cpp
|
||||
#include <Wire.h>
|
||||
#include <Adafruit_GFX.h>
|
||||
#include <Adafruit_SSD1306.h>
|
||||
#include <DHT.h>
|
||||
```
|
||||
|
||||
Define the pixel parameters of the OLED screen and instantiate a screen object display
|
||||
```cpp
|
||||
#define SCREEN_WIDTH 128 // Define the screen width to be 128 pixels
|
||||
#define SCREEN_HEIGHT 64 // Define the screen height to be 64 pixels
|
||||
#define OLED_RESET -1 // Define the OLED reset pin to -1 (or -1 if the reset function is not used)
|
||||
// Create an Adafruit_SSD1306 object that controls the OLED screen, specifying the screen width, height, I2C bus object, and reset pin
|
||||
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
|
||||
```
|
||||
|
||||
Define DHT11 sensor pins and instantiate DHT objects as dht
|
||||
```cpp
|
||||
#define DHTPIN 19 // The DHT11 sensor is connected to digital pin 4 of the Arduino
|
||||
#define DHTTYPE DHT11 // The DHT11 sensor was used
|
||||
DHT dht(DHTPIN, DHTTYPE); // Create DHT objects for connecting DHT sensors, specifying sensor pins and sensor models
|
||||
```
|
||||
|
||||
Set up the initialization bus, OLED screen and DHT11
|
||||
```cpp
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
Wire.begin(5,4); // The initial I2C bus SDA pin is set to 5 and the SCL pin is set to 4
|
||||
|
||||
// Initializing the screen
|
||||
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
|
||||
Serial.println(F("SSD1306 initialization failed"));
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
display.clearDisplay(); // Clear the screen buffer
|
||||
dht.begin(); // Initialize the DHT11 sensor
|
||||
}
|
||||
```
|
||||
|
||||
Read the temperature and humidity values in the loop function, save them to variables, and then display them on the OLED screen.
|
||||
```cpp
|
||||
void loop() {
|
||||
// Read the temperature and humidity data
|
||||
int humidity = dht.readHumidity();
|
||||
int temperature = dht.readTemperature();
|
||||
display.clearDisplay(); // Clear the screen buffer
|
||||
// Display temperature and humidity data
|
||||
display.setTextSize(1);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.setCursor(16, 20);
|
||||
display.print("Temperature: ");
|
||||
display.println(temperature);
|
||||
display.setCursor(16, 40);
|
||||
display.print("Humidity: ");
|
||||
display.print(humidity);
|
||||
display.println("%");
|
||||
display.display();
|
||||
delay(2000);
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
/* esp32 by espressif system 라이브러리 필요 v 2.0.17 빌드 가능
|
||||
Irecv 이슈
|
||||
*/
|
||||
|
||||
#include <IRremoteESP8266.h>
|
||||
#include <IRrecv.h>
|
||||
#include <IRutils.h>
|
||||
#include <FastLED.h>
|
||||
|
||||
#define LED_PIN 6 // Define the WS2812B RGB lamp pin
|
||||
#define NUM_LEDS 12 // Define the number of beads
|
||||
#define BRIGHTNESS 5 // Defining the brightness of the light
|
||||
#define FRAMES_PER_SECOND 120 // Defines frames per second
|
||||
CRGB leds[NUM_LEDS]; // WS2812B LED
|
||||
static uint8_t hue = 0; // Sets the value of the color
|
||||
int Color = 1; // A variable that defines the color pattern of the light
|
||||
|
||||
//const int IR_RECEIVE_PIN = 8; // Infrared receiver connected to GPI8 pin
|
||||
const int IR_RECEIVE_PIN = 20;
|
||||
IRrecv irReceiver(IR_RECEIVE_PIN);
|
||||
decode_results results;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
irReceiver.enableIRIn(); // Enable infrared receiver function
|
||||
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS); // The LED on the LED strip is added to the controller using the FastLED library
|
||||
FastLED.setBrightness(BRIGHTNESS); // Set the light brightness
|
||||
|
||||
}
|
||||
|
||||
void loop() {
|
||||
if (irReceiver.decode(&results)) { // If you receive an infrared signal
|
||||
Serial.println(results.value, HEX); // Print the numerical value of the infrared signal
|
||||
|
||||
if (results.value == 0xFF30CF) {
|
||||
Color = 1; // If key 1 is pressed, the color mode is red
|
||||
}else if(results.value == 0xFF18E7){
|
||||
Color = 2; // If key 1 is pressed, the color mode is green
|
||||
}else if(results.value == 0xFF7A85){
|
||||
Color = 3; // If key 1 is pressed, the color mode is blue
|
||||
}
|
||||
irReceiver.resume(); // Continue to receive the next signal
|
||||
}
|
||||
|
||||
for (int i = 0; i < NUM_LEDS; i++) {
|
||||
if (Color == 1) {
|
||||
leds[i] = CHSV(hue, 255, 255); //set it to red
|
||||
} else if (Color == 2) {
|
||||
leds[i] = CHSV(hue + 85, 255, 255); // set it to green
|
||||
} else if (Color == 3) {
|
||||
leds[i] = CHSV(hue + 170, 255, 255); // set it to blue
|
||||
}
|
||||
FastLED.show(); // Displays the color of the LED
|
||||
FastLED.delay(2 / FRAMES_PER_SECOND); // Delay to control the frame rate
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
# 13. Infrared remote control RGB
|
||||
|
||||
## 13.1 Overview
|
||||
In this section , you will learn how to use an IR remote control with an IR receiver . Complete a project to switch RGB light
|
||||
colors via infrared remote control.
|
||||
|
||||
## 13.2 Working principle
|
||||
The universal infrared remote control system consists of two parts: sending and receiving. The sending part is composed of
|
||||
infrared remote control, and the receiving part is composed of infrared receiving tube. The signal sent by the infrared remote
|
||||
control is a series of binary pulse codes. In order to avoid interference from other infrared signals during wireless
|
||||
transmission, it is generally necessary to modulate at a given carrier frequency and then transmit through an infrared
|
||||
emitting phototransistor. The infrared receiving tube filters out other noise waves, receives only the signal of a given
|
||||
frequency, and restores it to a demodulated binary pulse code. The built-in receiving tube converts the light signal sent by
|
||||
the infrared light-emitting diode, amplifies the signal through the amplifier in the IC, and restores the original code sent by
|
||||
the remote control through automatic gain control, band-pass filtering, demodulation, and wave formation, and outputs the
|
||||
signal through the infrared receiving module Pins identify the circuits that enter an appliance.
|
||||
The encoding scheme that matches the infrared remote control protocol is: NEC protocol. Next, let us understand what the
|
||||
NECprotocol is.
|
||||
|
||||
(1) 8 address bits, 8 sequence bits address bits and sequence bits are transmitted twice to ensure reliability
|
||||
(3) Pulse position modulation
|
||||
(4) The carrier frequency is 38 kHz
|
||||
(5) The time for each bit is 1.125 ms or 2.25 ms
|
||||
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/13.lesson_ir_receiver.png" width="150" height="150"/>
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/13.lesson_ir_transmiter.png" width="200" height="400"/>
|
||||
|
||||
## 13.3 Connection lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/13.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 13.4 Upload code program
|
||||
|
||||
### 13.4.1 Connect the main control board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 13.4.2 Open the program file ( Path : 2_ESP32_S3_PLUS \ Lesson_13_Infrared_change_RGB )
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board, and wait for the program
|
||||
upload to be completed .
|
||||
|
||||
After the program is uploaded, point the infrared remote control at the infrared receiver and press the number keys 1/2/3 to
|
||||
control the WS2812 to switch lights of different colors.
|
||||
|
||||
## 13.5 Code analysis
|
||||
|
||||
Declare the required library files. If the corresponding library is not added, please go back to the installation library
|
||||
to see
|
||||
how to add the library.
|
||||
|
||||
```cpp
|
||||
/* esp32 by espressif system 라이브러리 필요 v2.0.17 빌드 가능
|
||||
Irecv 이슈
|
||||
*/
|
||||
|
||||
#include <IRremoteESP8266.h>
|
||||
#include <IRrecv.h>
|
||||
#include <IRutils.h>
|
||||
#include <FastLED.h>
|
||||
```
|
||||
|
||||
Define ws2812 pins, number of lamp beads, brightness and other parameters and variables hue, Color
|
||||
|
||||
```cpp
|
||||
#define LED_PIN 6 // Define the WS2812B RGB lamp pin
|
||||
#define NUM_LEDS 12 // Define the number of beads
|
||||
#define BRIGHTNESS 5 // Defining the brightness of the light
|
||||
#define FRAMES_PER_SECOND 120 // Defines frames per second
|
||||
CRGB leds[NUM_LEDS]; // WS2812B LED
|
||||
static uint8_t hue = 0; // Sets the value of the color
|
||||
int Color = 1; // A variable that defines the color pattern of the light
|
||||
```
|
||||
|
||||
Define the infrared receiver pin as 8, instantiate the infrared receiver object as irReceiver, and receive the infrared
|
||||
information object pointer results.
|
||||
|
||||
```cpp
|
||||
//const int IR_RECEIVE_PIN = 8; // Infrared receiver connected to GPI8 pin
|
||||
const int IR_RECEIVE_PIN = 20;
|
||||
IRrecv irReceiver(IR_RECEIVE_PIN);
|
||||
decode_results results;
|
||||
```
|
||||
|
||||
Initialize the infrared receiver and ws2812, set the baud rate to 9600
|
||||
|
||||
```cpp
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
irReceiver.enableIRIn(); // Enable infrared receiver function
|
||||
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS); // The LED on the LED strip is added to the controller using the FastLED library
|
||||
FastLED.setBrightness(BRIGHTNESS); // Set the light brightness
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
The loop function determines whether an infrared signal is received, and compares the received infrared signal code with
|
||||
the three instruction code values to obtain three color modes.
|
||||
|
||||
```cpp
|
||||
void loop() {
|
||||
if (irReceiver.decode(&results)) { // If you receive an infrared signal
|
||||
Serial.println(results.value, HEX); // Print the numerical value of the infrared signal
|
||||
|
||||
if (results.value == 0xFF30CF) {
|
||||
Color = 1; // If key 1 is pressed, the color mode is red
|
||||
}else if(results.value == 0xFF18E7){
|
||||
Color = 2; // If key 1 is pressed, the color mode is green
|
||||
}else if(results.value == 0xFF7A85){
|
||||
Color = 3; // If key 1 is pressed, the color mode is blue
|
||||
}
|
||||
irReceiver.resume(); // Continue to receive the next signal
|
||||
}
|
||||
```
|
||||
|
||||
Three color modes are obtained according to the received infrared encoding information, and the corresponding color can be
|
||||
obtained by judging the value of the color mode variable Color. Let ws2812 display this color again.
|
||||
|
||||
|
||||
```cpp
|
||||
|
||||
for (int i = 0; i < NUM_LEDS; i++) {
|
||||
if (Color == 1) {
|
||||
leds[i] = CHSV(hue, 255, 255); //set it to red
|
||||
} else if (Color == 2) {
|
||||
leds[i] = CHSV(hue + 85, 255, 255); // set it to green
|
||||
} else if (Color == 3) {
|
||||
leds[i] = CHSV(hue + 170, 255, 255); // set it to blue
|
||||
}
|
||||
FastLED.show(); // Displays the color of the LED
|
||||
FastLED.delay(2 / FRAMES_PER_SECOND); // Delay to control the frame rate
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
/* esp32 by espressif system 라이브러리 필요 v 2.0.17 빌드 가능 */
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
const char *ssid = "mkHome_2.4Ghz"; // Enter the WiFi account to which your ESP32 will connect
|
||||
const char *password = "mk800130"; //Set WiFi password
|
||||
|
||||
const int greenLEDPin = 13; // Green LED control pin
|
||||
const int yellowLEDPin = 11; // Yellow LED control pin
|
||||
const int redLEDPin = 10; // Red LED control pin
|
||||
|
||||
int greenLEDState = LOW; // Green LED initial state (off)
|
||||
int yellowLEDState = LOW; // Yellow LED initial state (off)
|
||||
int redLEDState = LOW; // Red LED initial state (off)
|
||||
|
||||
// Create an AsyncWebServer object
|
||||
AsyncWebServer server(80);
|
||||
|
||||
// Generates the HTML code for the web page
|
||||
const char index_html[] PROGMEM = R"rawliteral(
|
||||
<!DOCTYPE HTML><html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
|
||||
<style>
|
||||
html {
|
||||
font-family: Arial;
|
||||
display: inline-block;
|
||||
margin: 0px auto;
|
||||
text-align: center;
|
||||
}
|
||||
h2 { font-size: 3.0rem; }
|
||||
p { font-size: 3.0rem; }
|
||||
.units { font-size: 1.2rem; }
|
||||
.dht-labels{
|
||||
font-size: 1.5rem;
|
||||
vertical-align:middle;
|
||||
padding-bottom: 15px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>ESP32 LED Control</h2>
|
||||
<p>
|
||||
<i id="greenLED" class="fas fa-lightbulb" style="color:#808080;" onclick="toggleLED('green');"></i>
|
||||
<span class="dht-labels" id="ledText1">LED Off</span>
|
||||
</p>
|
||||
<p>
|
||||
<i id="yellowLED" class="fas fa-lightbulb" style="color:#808080;" onclick="toggleLED('yellow');"></i>
|
||||
<span class="dht-labels" id="ledText2">LED Off</span>
|
||||
</p>
|
||||
<p>
|
||||
<i id="redLED" class="fas fa-lightbulb" style="color:#808080;" onclick="toggleLED('red');"></i>
|
||||
<span class="dht-labels" id="ledText3">LED Off</span>
|
||||
</p>
|
||||
</body>
|
||||
<script>
|
||||
function toggleLED(color) {
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.open("GET", "/toggle?color=" + color, true);
|
||||
xhttp.send();
|
||||
}
|
||||
|
||||
function updateIcon(led, color) {
|
||||
var icon = document.getElementById(led);
|
||||
icon.style.color = color;
|
||||
}
|
||||
|
||||
setInterval(function() {
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.onreadystatechange = function() {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
var ledState = JSON.parse(this.responseText);
|
||||
updateIcon("greenLED", ledState.greenColor);
|
||||
document.getElementById("ledText1").innerHTML = ledState.greenText;
|
||||
updateIcon("yellowLED", ledState.yellowColor);
|
||||
document.getElementById("ledText2").innerHTML = ledState.yellowText;
|
||||
updateIcon("redLED", ledState.redColor);
|
||||
document.getElementById("ledText3").innerHTML = ledState.redText;
|
||||
}
|
||||
};
|
||||
xhttp.open("GET", "/ledstate", true);
|
||||
xhttp.send();
|
||||
}, 1000);
|
||||
</script>
|
||||
</html>
|
||||
)rawliteral";
|
||||
|
||||
String getLEDState() {
|
||||
String json;
|
||||
json += "{\"greenColor\":\"" + String(greenLEDState == HIGH ? "#66CC33" : "#808080") + "\",";
|
||||
json += "\"yellowColor\":\"" + String(yellowLEDState == HIGH ? "#FFCC33" : "#808080") + "\",";
|
||||
json += "\"redColor\":\"" + String(redLEDState == HIGH ? "#FF0000" : "#808080") + "\",";
|
||||
json += "\"greenText\":\"" + String(greenLEDState == HIGH ? "LED ON" : "LED OFF") + "\",";
|
||||
json += "\"yellowText\":\"" + String(yellowLEDState == HIGH ? "LED ON" : "LED OFF") + "\",";
|
||||
json += "\"redText\":\"" + String(redLEDState == HIGH ? "LED ON" : "LED OFF") + "\"}";
|
||||
return json;
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600); // Set the serial port baud rate
|
||||
|
||||
//Set the pin output mode
|
||||
pinMode(greenLEDPin, OUTPUT);
|
||||
pinMode(yellowLEDPin, OUTPUT);
|
||||
pinMode(redLEDPin, OUTPUT);
|
||||
|
||||
//Set the state of the LED
|
||||
digitalWrite(greenLEDPin, greenLEDState);
|
||||
digitalWrite(yellowLEDPin, yellowLEDState);
|
||||
digitalWrite(redLEDPin, redLEDState);
|
||||
|
||||
// Setting up WiFi connection
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.println("WiFi Setting");
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(1000);
|
||||
Serial.println(".");
|
||||
}
|
||||
// Printing IP addresses
|
||||
Serial.println(WiFi.localIP());
|
||||
|
||||
// Set up the request handler function
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send_P(200, "text/html", index_html);
|
||||
});
|
||||
server.on("/toggle", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
String color = request->getParam("color")->value();
|
||||
if (color == "green") {
|
||||
greenLEDState = !greenLEDState;
|
||||
digitalWrite(greenLEDPin, greenLEDState);
|
||||
} else if (color == "yellow") {
|
||||
yellowLEDState = !yellowLEDState;
|
||||
digitalWrite(yellowLEDPin, yellowLEDState);
|
||||
} else if (color == "red") {
|
||||
redLEDState = !redLEDState;
|
||||
digitalWrite(redLEDPin, redLEDState);
|
||||
}
|
||||
request->send(200, "application/json", getLEDState());
|
||||
});
|
||||
server.on("/ledstate", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send(200, "application/json", getLEDState());
|
||||
});
|
||||
|
||||
// Starting the server
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// AsyncWebServer
|
||||
}
|
||||
|
|
@ -0,0 +1,143 @@
|
|||
# 14. Webswitch control LED
|
||||
|
||||
## 14.1 Overview
|
||||
This section focuses on learning the WiFi function of ESP32S3 and controlling the LED on the web page.
|
||||
|
||||
## 14.2 Working principle
|
||||
|
||||
Connect to a WiFi hotspot with smooth network through ESP32, and then use other devices such as computers or mobile
|
||||
phones to connect to the same WiFi. Enter the IP in the browser address bar to open the web interface created by ESP32,
|
||||
and control it through the web page containing the LED switch. LED.
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="800" height="200"/>
|
||||
|
||||
## 14.3 Connection lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/14.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 14.4 Upload code program
|
||||
|
||||
### 14.4.1 Connect the main control board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 14.4.2 Open the program file (path: 2_ESP32_S3_PLUS \ Lesson_14_Web_key_controls_LED )
|
||||
|
||||
Modify the WiFi account and password to which ESP32 is connected in the code. (This WiFi can be the router WiFi at home
|
||||
or the WiFi transmitted by the mobile hotspot, but make sure it is 2.4G and not 5G)
|
||||
|
||||
```cpp
|
||||
const char *ssid = "xxxxxxx"; // Enter the WiFi account to which your ESP32 will connect
|
||||
const char *password = "xxxxxxx"; //Set WiFi password
|
||||
```
|
||||
|
||||
Then select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board, and wait for the program
|
||||
upload to be completed .
|
||||
After the program upload is completed, open the serial monitor to view the IP address.
|
||||
Here the IP is 192.168.8.1, but everyone will get a different IP.
|
||||
Connect to the same WiFi with your mobile phone, then open the browser, enter the IP address above and enter the page.
|
||||
Click the icon to control the corresponding LED switch.
|
||||
|
||||
## 14.5 Code analysis
|
||||
|
||||
Declare the required libraries primarily for creating web services and handling asynchronous event-driven models
|
||||
|
||||
```cpp
|
||||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
```
|
||||
|
||||
Initialize the WiFi to be connected to ESP32, set the three LED pins and the initial state is off
|
||||
|
||||
```cpp
|
||||
const char *ssid = "xxxxxxx"; // Enter the WiFi account to which your ESP32 will connect
|
||||
const char *password = "xxxxxxx"; //Set WiFi password
|
||||
|
||||
const int greenLEDPin = 13; // Green LED control pin
|
||||
const int yellowLEDPin = 11; // Yellow LED control pin
|
||||
const int redLEDPin = 10; // Red LED control pin
|
||||
|
||||
int greenLEDState = LOW; // Green LED initial state (off)
|
||||
int yellowLEDState = LOW; // Yellow LED initial state (off)
|
||||
int redLEDState = LOW; // Red LED initial state (off)
|
||||
```
|
||||
|
||||
Create AsyncWebServer object
|
||||
|
||||
```cpp
|
||||
// Create an AsyncWebServer object
|
||||
AsyncWebServer server(80);
|
||||
```
|
||||
|
||||
Generate the HTMLcode of the web page , in which the web page icon is obtained from an external link, so the connected
|
||||
WiFi must be a valid WiFi to obtain the icon normally.
|
||||
|
||||
```cpp
|
||||
// Generates the HTML code for the web page
|
||||
const char index_html[] PROGMEM = R"rawliteral(
|
||||
<!DOCTYPE HTML><html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
|
||||
<style>
|
||||
html {
|
||||
font-family: Arial;
|
||||
display: inline-block;
|
||||
margin: 0px auto;
|
||||
text-align: center;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
```
|
||||
|
||||
The GetLEDState function implements web page update operations. When the icon is clicked, it updates the icon status
|
||||
accordingly and issues instructions to the ESP32.
|
||||
|
||||
```cpp
|
||||
String getLEDState() {
|
||||
String json;
|
||||
json += "{\"greenColor\":\"" + String(greenLEDState == HIGH ? "#66CC33" : "#808080") + "\",";
|
||||
json += "\"yellowColor\":\"" + String(yellowLEDState == HIGH ? "#FFCC33" : "#808080") + "\",";
|
||||
json += "\"redColor\":\"" + String(redLEDState == HIGH ? "#FF0000" : "#808080") + "\",";
|
||||
json += "\"greenText\":\"" + String(greenLEDState == HIGH ? "LED ON" : "LED OFF") + "\",";
|
||||
json += "\"yellowText\":\"" + String(yellowLEDState == HIGH ? "LED ON" : "LED OFF") + "\",";
|
||||
json += "\"redText\":\"" + String(redLEDState == HIGH ? "LED ON" : "LED OFF") + "\"}";
|
||||
return json;
|
||||
}
|
||||
```
|
||||
Set the request processing function in the step
|
||||
```cpp
|
||||
// Set up the request handler function
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send_P(200, "text/html", index_html);
|
||||
});
|
||||
server.on("/toggle", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
String color = request->getParam("color")->value();
|
||||
if (color == "green") {
|
||||
greenLEDState = !greenLEDState;
|
||||
digitalWrite(greenLEDPin, greenLEDState);
|
||||
} else if (color == "yellow") {
|
||||
yellowLEDState = !yellowLEDState;
|
||||
digitalWrite(yellowLEDPin, yellowLEDState);
|
||||
} else if (color == "red") {
|
||||
redLEDState = !redLEDState;
|
||||
digitalWrite(redLEDPin, redLEDState);
|
||||
}
|
||||
request->send(200, "application/json", getLEDState());
|
||||
});
|
||||
server.on("/ledstate", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send(200, "application/json", getLEDState());
|
||||
});
|
||||
|
||||
```
|
||||
|
||||
Finally start the server
|
||||
|
||||
```cpp
|
||||
// Starting the server
|
||||
server.begin();
|
||||
```
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <ESP32PWM.h>
|
||||
|
||||
const char *ssid = "mkHome_2.4Ghz"; // Set up WiFi account
|
||||
const char *password = "mk800130"; // Set WiFi password
|
||||
|
||||
#define GREEN_LED_PIN 13 // Define the green LED control pin
|
||||
#define YELLOW_LED_PIN 11 // Define the yellow LED control pin
|
||||
#define RED_LED_PIN 10 // Define the red LED control pin
|
||||
|
||||
AsyncWebServer server(80); // Create an AsyncWebServer object
|
||||
|
||||
// A function to handle the root path
|
||||
void handleRoot(AsyncWebServerRequest *request) {
|
||||
request->send(200, "text/html", getIndexHtml());
|
||||
}
|
||||
|
||||
// A function to handle slider requests
|
||||
void handleSlider(AsyncWebServerRequest *request) {
|
||||
|
||||
if (request->hasParam("red")) {
|
||||
int redValue = request->getParam("red")->value().toInt();
|
||||
ledcWrite(0, redValue); // Set the red LED brightness
|
||||
}
|
||||
if (request->hasParam("yellow")) {
|
||||
int yellowValue = request->getParam("yellow")->value().toInt();
|
||||
ledcWrite(1, yellowValue); // Set the yellow LED brightness
|
||||
}
|
||||
if (request->hasParam("green")) {
|
||||
int greenValue = request->getParam("green")->value().toInt();
|
||||
ledcWrite(2, greenValue); // Set the green LED brightness
|
||||
}
|
||||
request->send(200, "text/plain", "OK");
|
||||
}
|
||||
|
||||
// Generates the HTML code for the web page
|
||||
String getIndexHtml() {
|
||||
String html = "<!DOCTYPE html>";
|
||||
html += "<html><head><title>ESP32 Web controls LED</title>";
|
||||
html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
|
||||
html += "<link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.2/css/all.css'>";
|
||||
html += "<style>";
|
||||
html += "input[type=range] { width: 80%; }";
|
||||
html += ".led-icon { font-size: 24px; margin-right: 10px; }";
|
||||
html += "</style>";
|
||||
html += "</head><body style='text-align:center;'>";
|
||||
html += "<h2>ESP32 Web Control</h2>";
|
||||
|
||||
html += "<p><i class='fas fa-lightbulb led-icon' style='color:#66CC33;'></i> Green:</p>";
|
||||
html += "<input type='range' min='0' max='255' value='0' id='green' onchange='changeSlider(this.value, \"green\")' style='background-color: green;'><br>";
|
||||
|
||||
html += "<p><i class='fas fa-lightbulb led-icon' style='color:#FFCC33;'></i> Yellow:</p>";
|
||||
html += "<input type='range' min='0' max='255' value='0' id='yellow' onchange='changeSlider(this.value, \"yellow\")' style='background-color: yellow;'><br>";
|
||||
|
||||
html += "<p><i class='fas fa-lightbulb led-icon' style='color:#FF0000;'></i> Red:</p>";
|
||||
html += "<input type='range' min='0' max='255' value='0' id='red' onchange='changeSlider(this.value, \"red\")' style='background-color: red;'><br>";
|
||||
|
||||
html += "<script>";
|
||||
html += "function changeSlider(value, led) { var xhttp = new XMLHttpRequest(); xhttp.open('GET', '/slider?' + led + '=' + value, true); xhttp.send(); }";
|
||||
html += "</script></body></html>";
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600); // Set serial port baud rate 9600
|
||||
|
||||
ledcSetup(0, 5000, 8); // 8-bit resolution, 5000Hz frequency
|
||||
ledcSetup(1, 5000, 8);
|
||||
ledcSetup(2, 5000, 8);
|
||||
|
||||
ledcAttachPin(RED_LED_PIN, 0); // Red LED
|
||||
ledcAttachPin(YELLOW_LED_PIN, 1); // Yellow LED
|
||||
ledcAttachPin(GREEN_LED_PIN, 2); // Green LED
|
||||
|
||||
// Setting up WiFi connection
|
||||
WiFi.begin(ssid, password);
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(1000);
|
||||
Serial.println("Connecting to WiFi...");
|
||||
}
|
||||
Serial.println("Connected to the WiFi network");
|
||||
Serial.print("IP Address: ");
|
||||
Serial.println(WiFi.localIP()); // Printing IP addresses
|
||||
|
||||
// Set up the request handler function
|
||||
server.on("/", HTTP_GET, handleRoot);
|
||||
server.on("/slider", HTTP_GET, handleSlider);
|
||||
server.begin();// Starting the server
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// AsyncWebServer
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
#
|
||||
|
|
@ -0,0 +1,92 @@
|
|||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <FastLED.h>
|
||||
|
||||
const char *ssid = "mkHome_2.4Ghz"; //设置WiFi账号 Set up WiFi account
|
||||
const char *password = "mk800130"; //设置WiFi密码 Set WiFi password
|
||||
|
||||
#define LED_PIN 6 // WS2812B连接的引脚 The pin for WS2812B connection
|
||||
#define NUM_LEDS 12 // WS2812B上的灯数量 Number of lights on WS2812B
|
||||
|
||||
CRGB leds[NUM_LEDS]; // 创建RGB灯数组 Create an array of RGB lights
|
||||
|
||||
// 创建 AsyncWebServer 对象 Create an AsyncWebServer object
|
||||
AsyncWebServer server(80);
|
||||
|
||||
// 处理根路径的函数 A function to handle the root path
|
||||
void handleRoot(AsyncWebServerRequest *request) {
|
||||
request->send(200, "text/html", getIndexHtml());
|
||||
}
|
||||
|
||||
// 处理颜色控制请求的函数 A function that handles requests for color control
|
||||
void handleColor(AsyncWebServerRequest *request) {
|
||||
// 读取参数值 Reading parameter values
|
||||
if (request->hasParam("red") && request->hasParam("green") && request->hasParam("blue")) {
|
||||
int red = request->getParam("red")->value().toInt();
|
||||
int green = request->getParam("green")->value().toInt();
|
||||
int blue = request->getParam("blue")->value().toInt();
|
||||
|
||||
// 设置ws2812颜色 Set the ws2812 color
|
||||
for (int i = 0; i < NUM_LEDS; i++) {
|
||||
leds[i] = CRGB(red, green, blue);
|
||||
}
|
||||
FastLED.show();// 更新ws2812颜色 Update ws2812 color
|
||||
}
|
||||
request->send(200, "text/plain", "OK");
|
||||
}
|
||||
|
||||
// 生成网页的 HTML 代码 Generates the HTML code for the web page
|
||||
String getIndexHtml() {
|
||||
String html = "<!DOCTYPE html>";
|
||||
html += "<html><head><title>ESP32 Web controls WS2812B LED</title>";
|
||||
html += "<meta name='viewport' content='width=device-width, initial-scale=1'>";
|
||||
html += "<link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.2/css/all.css'>";
|
||||
html += "</head><body style='text-align:center;'>";
|
||||
html += "<h2>ESP32 Web Control</h2>";
|
||||
|
||||
html += "<p><i class='fas fa-circle' style='color:red;'></i> Red:</p>";
|
||||
html += "<input type='range' min='0' max='255' value='0' id='red' onchange='changeColor()' style='width: 80%;'><br>";
|
||||
|
||||
html += "<p><i class='fas fa-circle' style='color:green;'></i> Green:</p>";
|
||||
html += "<input type='range' min='0' max='255' value='0' id='green' onchange='changeColor()' style='width: 80%;'><br>";
|
||||
|
||||
html += "<p><i class='fas fa-circle' style='color:blue;'></i> Blue:</p>";
|
||||
html += "<input type='range' min='0' max='255' value='0' id='blue' onchange='changeColor()' style='width: 80%;'><br>";
|
||||
|
||||
html += "<script>function changeColor() {var red = document.getElementById('red').value;";
|
||||
html += "var green = document.getElementById('green').value;";
|
||||
html += "var blue = document.getElementById('blue').value;";
|
||||
html += "var xhttp = new XMLHttpRequest();";
|
||||
html += "xhttp.open('GET', '/color?red='+red+'&green='+green+'&blue='+blue, true);";
|
||||
html += "xhttp.send();}</script>";
|
||||
html += "</body></html>";
|
||||
return html;
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600); // 设置串口波特率 Set the serial port baud rate
|
||||
FastLED.addLeds<WS2812B, LED_PIN, GRB>(leds, NUM_LEDS); // 初始化ws2812灯条 Initialize the ws2812 light bar
|
||||
|
||||
// 设置 WiFi 连接 setting up WiFi connection
|
||||
WiFi.begin(ssid, password);
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(1000);
|
||||
Serial.println("Connecting to WiFi...");
|
||||
}
|
||||
Serial.println("Connected to the WiFi network");
|
||||
Serial.print("IP Address: ");
|
||||
Serial.println(WiFi.localIP()); //打印IP地址
|
||||
|
||||
// 设置请求处理函数 Set up the request handler function
|
||||
server.on("/", HTTP_GET, handleRoot);
|
||||
server.on("/color", HTTP_GET, handleColor);
|
||||
|
||||
// 启动服务器 Starting the server
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// 处理异步事件
|
||||
// AsyncWebServer 使用了事件驱动模型,所以不需要在循环中处理
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
#
|
||||
|
|
@ -0,0 +1,151 @@
|
|||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <Adafruit_Sensor.h>
|
||||
#include <DHT.h>
|
||||
|
||||
const char *ssid = "XXXXXX"; //设置WiFi账号 Set up WiFi account
|
||||
const char *password = "XXXXXXXX"; //设置WiFi密码 Set WiFi password
|
||||
|
||||
#define DHTPIN 19 // 19引脚连接到DHT传感器 The 19 pins are connected to the DHT sensor
|
||||
#define DHTTYPE DHT11 // 定义传感器类型为DHT11 The sensor type is defined as DHT11
|
||||
DHT dht(DHTPIN, DHTTYPE); // 创建一个DHT对象,使用指定的引脚和传感器类型 Creates a DHT object with the specified pin and sensor types
|
||||
// 创建 AsyncWebServer 对象
|
||||
AsyncWebServer server(80);
|
||||
|
||||
float t = 0.0; // 定义一个浮点型变量t,用于存储温度值 Define a floating-point variable t to store the temperature
|
||||
float h = 0.0; // 定义一个浮点型变量h,用于存储湿度值 Define a floating point variable h to store the humidity value
|
||||
unsigned long previousMillis = 0; // 将存储上次DHT更新的时间 The time of the last DHT update is stored
|
||||
const long interval = 10000; // 每10秒更新DHT读数 The DHT readings are updated every 10 seconds
|
||||
|
||||
// 生成网页的 HTML 代码 Generates the HTML code for the web page
|
||||
const char index_html[] PROGMEM = R"rawliteral(
|
||||
<!DOCTYPE HTML><html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
|
||||
<style>
|
||||
html {
|
||||
font-family: Arial;
|
||||
display: inline-block;
|
||||
margin: 0px auto;
|
||||
text-align: center;
|
||||
}
|
||||
h2 { font-size: 3.0rem; }
|
||||
p { font-size: 3.0rem; }
|
||||
.units { font-size: 1.2rem; }
|
||||
.dht-labels{
|
||||
font-size: 1.5rem;
|
||||
vertical-align:middle;
|
||||
padding-bottom: 15px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>ESP32 DHT Server</h2>
|
||||
<p>
|
||||
<i class="fas fa-thermometer-half" style="color:#059e8a;"></i>
|
||||
<span class="dht-labels">Temperature</span>
|
||||
<span id="temperature">%TEMPERATURE%</span>
|
||||
<sup class="units">°C</sup>
|
||||
</p>
|
||||
<p>
|
||||
<i class="fas fa-tint" style="color:#00add6;"></i>
|
||||
<span class="dht-labels">Humidity</span>
|
||||
<span id="humidity">%HUMIDITY%</span>
|
||||
<sup class="units">%</sup>
|
||||
</p>
|
||||
</body>
|
||||
<script>
|
||||
setInterval(function ( ) {
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.onreadystatechange = function() {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
document.getElementById("temperature").innerHTML = this.responseText;
|
||||
}
|
||||
};
|
||||
xhttp.open("GET", "/temperature", true);
|
||||
xhttp.send();
|
||||
}, 10000 ) ;
|
||||
|
||||
setInterval(function ( ) {
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.onreadystatechange = function() {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
document.getElementById("humidity").innerHTML = this.responseText;
|
||||
}
|
||||
};
|
||||
xhttp.open("GET", "/humidity", true);
|
||||
xhttp.send();
|
||||
}, 10000 ) ;
|
||||
</script>
|
||||
</html>)rawliteral";
|
||||
|
||||
String processor(const String &var) {
|
||||
if (var == "TEMPERATURE") { // 如果请求的变量是"TEMPERATURE" If the request variable is "TEMPERATURE"
|
||||
return String(t); // 返回当前温度值的字符串形式 Returns the current temperature as a string
|
||||
} else if (var == "HUMIDITY") { // 如果请求的变量是"HUMIDITY" If the requested variable is "HUMIDITY"
|
||||
return String(h); // 返回当前湿度值的字符串形式 Returns the current humidity value as a string
|
||||
}
|
||||
return String(); // 如果请求的变量不是"TEMPERATURE"或"HUMIDITY",则返回空字符串 If the requested variable is not "TEMPERATURE" or "HUMIDITY", an empty string is returned
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
dht.begin(); // 初始化DHT11 Initialize DHT11
|
||||
|
||||
// 设置 WiFi 连接 Setting up WiFi connection
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.println("Connecting to WiFi");
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(1000);
|
||||
Serial.println(".");
|
||||
}
|
||||
|
||||
Serial.println(WiFi.localIP()); //打印IP地址 Printing IP addresses
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send_P(200, "text/html", index_html, processor);
|
||||
});
|
||||
server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
float newT = dht.readTemperature();
|
||||
if (isnan(newT)) {
|
||||
request->send(500, "text/plain", "Failed to read temperature from DHT sensor!");
|
||||
} else {
|
||||
request->send_P(200, "text/plain", String(newT).c_str());
|
||||
}
|
||||
});
|
||||
server.on("/humidity", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
float newH = dht.readHumidity();
|
||||
if (isnan(newH)) {
|
||||
request->send(500, "text/plain", "Failed to read humidity from DHT sensor!");
|
||||
} else {
|
||||
request->send_P(200, "text/plain", String(newH).c_str());
|
||||
}
|
||||
});
|
||||
|
||||
// 启动服务器
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
unsigned long currentMillis = millis(); //获取当前的毫秒数,用于记录当前时间。 Gets the current number of milliseconds, which is used to record the current time.
|
||||
if (currentMillis - previousMillis >= interval) { //检查是否已经到达了指定的时间间隔,如果是则执行下面的代码。 Check to see if the specified interval has been reached, and if so execute the following code:
|
||||
previousMillis = currentMillis; //更新上一次执行的时间,以便下一次判断时间间隔。 Update the time of the last execution so that the next time interval is determined.
|
||||
float newT = dht.readTemperature(); //读取温度传感器的数据,并将读取到的值存储在newT变量中。 The data of the temperature sensor is read and the value read is stored in the newT variable.
|
||||
if (isnan(newT)) { //检查读取的温度值是否为非数字(NaN),如果是则输出错误信息。 Check if the temperature is not a number (NaN) and print an error if it is.
|
||||
Serial.println("Failed to read temperature from DHT sensor!");
|
||||
} else {
|
||||
t = newT; //将读取到的温度值赋给t变量 Assign the temperature to the t variable
|
||||
Serial.println(t); //打印输出温度 Print output temperature
|
||||
}
|
||||
float newH = dht.readHumidity(); //读取湿度传感器的数据,并将读取到的值存储在newH变量中 Read the humidity sensor data and store the read value in the newH variable
|
||||
if (isnan(newH)) { //检查读取的湿度值是否为非数字(NaN),如果是则输出错误信息 Check if the humidity value is not a NaN and print an error if it is
|
||||
Serial.println("Failed to read humidity from DHT sensor!");
|
||||
} else {
|
||||
h = newH; //将读取到的湿度值赋给h变量 The read humidity value is assigned to the h variable
|
||||
Serial.println(h); //打印输出湿度 Print output humidity
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
#
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
const char *ssid = "XXXXXX"; //设置WiFi账号 Set up WiFi account
|
||||
const char *password = "XXXXXXXX"; //设置WiFi密码 Set WiFi password
|
||||
const int buzzerPin = 21; // 21引脚连接到有源蜂鸣器 The 21 pins are connected to the active buzzer
|
||||
bool isBuzzerOn = false; // 跟踪蜂鸣器的状态 Track the state of the buzzer
|
||||
AsyncWebServer server(80); // 创建 AsyncWebServer 对象
|
||||
|
||||
// 生成网页的 HTML 代码 Generate HTML code for the web page
|
||||
const char index_html[] PROGMEM = R"rawliteral(
|
||||
<!DOCTYPE HTML><html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
|
||||
<style>
|
||||
html {
|
||||
font-family: Arial;
|
||||
display: inline-block;
|
||||
margin: 0px auto;
|
||||
text-align: center;
|
||||
}
|
||||
h2 { font-size: 3.0rem; }
|
||||
p { font-size: 3.0rem; }
|
||||
.units { font-size: 1.2rem; }
|
||||
.dht-labels{
|
||||
font-size: 1.5rem;
|
||||
vertical-align:middle;
|
||||
padding-bottom: 15px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>ESP32 Buzzer Control</h2>
|
||||
<p>
|
||||
<i id="buzzerIcon" class="fas fa-volume-mute" style="color:#059e8a; cursor: pointer;"></i>
|
||||
<span class="dht-labels">Buzzer Control</span>
|
||||
</p>
|
||||
</body>
|
||||
<script>
|
||||
document.getElementById("buzzerIcon").addEventListener("click", function() {
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.onreadystatechange = function() {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
if (document.getElementById("buzzerIcon").classList.contains("fa-volume-up")) {
|
||||
document.getElementById("buzzerIcon").classList.remove("fa-volume-up");
|
||||
document.getElementById("buzzerIcon").classList.add("fa-volume-mute");
|
||||
} else {
|
||||
document.getElementById("buzzerIcon").classList.remove("fa-volume-mute");
|
||||
document.getElementById("buzzerIcon").classList.add("fa-volume-up");
|
||||
}
|
||||
}
|
||||
};
|
||||
xhttp.open("GET", "/toggleBuzzer", true);
|
||||
xhttp.send();
|
||||
});
|
||||
</script>
|
||||
</html>)rawliteral";
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
pinMode(buzzerPin, OUTPUT); // 设置引脚工作模式为输出 Set the pin operation mode to output
|
||||
digitalWrite(buzzerPin, LOW); // 蜂鸣器初始设置关闭 The initial setting of the buzzer is off
|
||||
|
||||
// 设置 WiFi 连接 Setting up WiFi connection
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.println("Connecting to WiFi");
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(1000);
|
||||
Serial.println(".");
|
||||
}
|
||||
|
||||
Serial.println(WiFi.localIP()); //打印IP地址 Printing IP addresses
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send_P(200, "text/html", index_html);
|
||||
});
|
||||
|
||||
server.on("/toggleBuzzer", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
if (isBuzzerOn) {
|
||||
digitalWrite(buzzerPin, LOW); // 关闭蜂鸣器 Turn off the buzzer
|
||||
isBuzzerOn = false;
|
||||
} else {
|
||||
digitalWrite(buzzerPin, HIGH); // 打开蜂鸣器 Turn on the buzzer
|
||||
isBuzzerOn = true;
|
||||
}
|
||||
request->send(200, "text/plain", "Buzzer toggled");
|
||||
});
|
||||
|
||||
//启用服务器 Enabling the server
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
//在这里添加任何需要持续运行的额外代码
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
#
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
|
||||
const char *ssid = "XXXXXX"; // 设置WiFi账号 Set up WiFi account
|
||||
const char *password = "XXXXXXXX"; // 设置WiFi密码 Set WiFi password
|
||||
const int ledPin = 13; // LED控制引脚 LED control pin
|
||||
const int ldrPin = 12; // 光敏电阻连接的引脚 Photoresistor connected pin
|
||||
int threshold = 4095 * 0.7; // 如果sensorValue小于70%的阈值 If sensorValue is less than the 70% threshold
|
||||
AsyncWebServer server(80); // 创建AsyncWebServer对象 Create an AsyncWebServer object
|
||||
|
||||
// 生成网页的HTML代码 Generates the HTML code for the web page
|
||||
const char index_html[] PROGMEM = R"rawliteral(
|
||||
<!DOCTYPE HTML><html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
|
||||
<style>
|
||||
html {
|
||||
font-family: Arial;
|
||||
display: inline-block;
|
||||
margin: 0px auto;
|
||||
text-align: center;
|
||||
}
|
||||
h2 { font-size: 3.0rem; }
|
||||
p { font-size: 3.0rem; }
|
||||
.units { font-size: 1.2rem; }
|
||||
.dht-labels{
|
||||
font-size: 1.5rem;
|
||||
vertical-align:middle;
|
||||
padding-bottom: 15px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>ESP32 Light Control</h2>
|
||||
<p>
|
||||
<i id="ledIcon" class="fas fa-lightbulb" style="color:#808080;"></i>
|
||||
<span class="dht-labels" id="ledText">LED OFF</span>
|
||||
</p>
|
||||
<p>
|
||||
<i id="ldrIcon" class="fas fa-sun" style="color:#FFD700;"></i>
|
||||
<span class="dht-labels">Brightness</span>
|
||||
<span id="brightness">%BRIGHTNESS%</span>
|
||||
<sup class="units">%</sup>
|
||||
</p>
|
||||
<p style="font-size: 1rem;">When the light intensity is below 70%, the LED will be turned on.</p>
|
||||
</body>
|
||||
<script>
|
||||
setInterval(function ( ) {
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.onreadystatechange = function() {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
var brightness = parseInt(this.responseText);
|
||||
document.getElementById("brightness").innerHTML = brightness;
|
||||
if (brightness < 70) {
|
||||
document.getElementById("ledIcon").style.color = "#059e8a"; // 设置为彩色
|
||||
document.getElementById("ledText").innerHTML = "LED ON";
|
||||
digitalWrite(ledPin, HIGH);
|
||||
} else {
|
||||
document.getElementById("ledIcon").style.color = "#808080"; // 设置为灰色
|
||||
document.getElementById("ledText").innerHTML = "LED OFF";
|
||||
digitalWrite(ledPin, LOW);
|
||||
}
|
||||
}
|
||||
};
|
||||
xhttp.open("GET", "/brightness", true);
|
||||
xhttp.send();
|
||||
}, 1000);
|
||||
</script>
|
||||
</html>
|
||||
)rawliteral";
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
pinMode(ledPin, OUTPUT); // 定义引脚工作模式 Define the pin operation mode
|
||||
digitalWrite(ledPin, LOW); // 确保LED初始状态为关闭 Ensure that the LED is initially off
|
||||
pinMode(ldrPin, INPUT); // 设置光敏电阻引脚为输入模式 Set the photoresistor pin to input mode
|
||||
|
||||
// 设置 WiFi 连接 Setting up WiFi connection
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.println("Connecting to WiFi");
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(1000);
|
||||
Serial.println(".");
|
||||
}
|
||||
|
||||
Serial.println(WiFi.localIP()); //打印IP地址 Printing IP addresses
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send_P(200, "text/html", index_html);
|
||||
});
|
||||
|
||||
server.on("/brightness", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
int sensorValue = analogRead(ldrPin); // 读取光敏电阻的值(0-4095之间) Read photoresistor values (0-4095)
|
||||
int brightnessPercentage = map(sensorValue, 0, 4095, 0, 100); // 将值映射到百分比范围(0-100) Map values to a percentage range (0-100)
|
||||
String brightnessString = String(brightnessPercentage); // 将百分比转换为字符串 Convert percentages to strings
|
||||
request->send(200, "text/plain", brightnessString); // 发送亮度百分比到客户端 Send the brightness percentage to the client
|
||||
|
||||
if (sensorValue < threshold) { //如果检测到亮度低于70% If the brightness is detected below 70%
|
||||
digitalWrite(ledPin, HIGH); //点亮LED灯 Light up the LED
|
||||
} else { //否则 otherwise
|
||||
digitalWrite(ledPin, LOW); //熄灭LED灯 Turn off the LED lights
|
||||
}
|
||||
});
|
||||
|
||||
//启用服务器
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
#
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <ESP32Servo.h>
|
||||
#include <Wire.h>
|
||||
#include <Adafruit_GFX.h>
|
||||
#include <Adafruit_SSD1306.h>
|
||||
|
||||
#define SCREEN_WIDTH 128 // 定义屏幕宽度为128像素 Define the screen width to be 128 pixels
|
||||
#define SCREEN_HEIGHT 64 // 定义屏幕高度为64像素 Define the screen height to be 64 pixels
|
||||
#define OLED_RESET -1 // 定义 OLED 复位引脚为-1(如果不使用复位功能,则设置为-1) Define the OLED reset pin to -1 (or -1 if the reset function is not used)
|
||||
// 创建 Adafruit_SSD1306 对象,用于控制 OLED 屏幕,指定屏幕宽度、高度、I2C 总线对象和复位引脚
|
||||
// Create an Adafruit_SSD1306 object that controls the OLED screen, specifying the screen width, height, I2C bus object, and reset pin
|
||||
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
|
||||
|
||||
const char *ssid = "XXXXXX"; // 设置WiFi账号 Set up WiFi account
|
||||
const char *password = "XXXXXXXX"; // 设置WiFi密码 Set WiFi password
|
||||
const int servoPin = 9; // 舵机控制引脚 Servo control pin
|
||||
Servo servo; // 实例化舵机对象 Instantiate the steering gear object
|
||||
AsyncWebServer server(80); // 创建 AsyncWebServer 对象
|
||||
|
||||
// 生成网页的 HTML 代码 Generates the HTML code for the web page
|
||||
const char index_html[] PROGMEM = R"rawliteral(
|
||||
<!DOCTYPE HTML><html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
|
||||
<style>
|
||||
html {
|
||||
font-family: Arial;
|
||||
display: inline-block;
|
||||
margin: 0px auto;
|
||||
text-align: center;
|
||||
}
|
||||
h2 { font-size: 3.0rem; }
|
||||
p { font-size: 3.0rem; }
|
||||
.units { font-size: 1.2rem; }
|
||||
.dht-labels{
|
||||
font-size: 1.5rem;
|
||||
vertical-align:middle;
|
||||
padding-bottom: 15px;
|
||||
}
|
||||
.slider {
|
||||
width: 80%;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>ESP32 Servo Control</h2>
|
||||
<p>
|
||||
<i id="servoIcon" class="fas fa-compass" style="color:#70a3ff;"></i>
|
||||
<span class="dht-labels" id="servoText">Servo Angle: 90</span>
|
||||
</p>
|
||||
<p>
|
||||
<input type="range" min="0" max="180" value="90" class="slider" id="servoSlider">
|
||||
</p>
|
||||
</body>
|
||||
<script>
|
||||
document.getElementById("servoSlider").addEventListener("input", function() {
|
||||
var angle = this.value;
|
||||
document.getElementById("servoText").innerHTML = "Servo Angle: " + angle;
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.open("GET", "/servo?angle=" + angle, true);
|
||||
xhttp.send();
|
||||
});
|
||||
</script>
|
||||
</html>
|
||||
)rawliteral";
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
Wire.begin(5, 4); //初始化 I2C 总线 SDA引脚设置为5,SCL引脚设置为4 The initial I2C bus SDA pin is set to 5 and the SCL pin is set to 4
|
||||
|
||||
// 初始化屏幕
|
||||
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
|
||||
Serial.println(F("SSD1306 initialization failed"));
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
|
||||
display.clearDisplay();
|
||||
// 初始化显示舵机角度 Initialize display steering Angle
|
||||
display.setTextSize(2);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.setCursor(0, 8);
|
||||
display.println("SG90 Angle");
|
||||
display.setCursor(32, 40);
|
||||
display.print("0");
|
||||
display.display();
|
||||
|
||||
servo.attach(servoPin); //关联舵机引脚 Associate servo pin
|
||||
// 设置 WiFi 连接
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.println("Connecting to WiFi");
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(1000);
|
||||
Serial.println(".");
|
||||
}
|
||||
Serial.println(WiFi.localIP()); //打印IP地址
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send_P(200, "text/html", index_html);
|
||||
});
|
||||
|
||||
server.on("/servo", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
if (request->hasParam("angle")) {
|
||||
int angle = request->getParam("angle")->value().toInt();
|
||||
servo.write(angle);
|
||||
display.clearDisplay();
|
||||
|
||||
// 显示舵机角度 Display steering Angle
|
||||
display.setTextSize(2);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.setCursor(0, 8);
|
||||
display.println("SG90 Angle");
|
||||
display.setCursor(32, 40);
|
||||
display.print(angle);
|
||||
display.display();
|
||||
request->send(200, "text/plain", "OK");
|
||||
} else {
|
||||
request->send(400, "text/plain", "Missing angle parameter");
|
||||
}
|
||||
});
|
||||
|
||||
//启用服务器
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
#
|
||||
|
|
@ -0,0 +1,159 @@
|
|||
#include <Arduino.h>
|
||||
#include <WiFi.h>
|
||||
#include <AsyncTCP.h>
|
||||
#include <ESPAsyncWebServer.h>
|
||||
#include <Wire.h>
|
||||
#include <Adafruit_GFX.h>
|
||||
#include <Adafruit_SSD1306.h>
|
||||
|
||||
#define SCREEN_WIDTH 128 // 定义屏幕宽度为128像素 Define the screen width to be 128 pixels
|
||||
#define SCREEN_HEIGHT 64 // 定义屏幕高度为64像素 Define the screen height to be 64 pixels
|
||||
#define OLED_RESET -1 // 定义 OLED 复位引脚为-1(如果不使用复位功能,则设置为-1) Define the OLED reset pin to -1 (or -1 if the reset function is not used)
|
||||
// 创建 Adafruit_SSD1306 对象,用于控制 OLED 屏幕,指定屏幕宽度、高度、I2C 总线对象和复位引脚
|
||||
// Create an Adafruit_SSD1306 object that controls the OLED screen, specifying the screen width, height, I2C bus object, and reset pin
|
||||
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
|
||||
|
||||
|
||||
const char *ssid = "ZHIYI"; // 设置WiFi账号 Set up WiFi account
|
||||
const char *password = "zy12345678"; // 设置WiFi密码 Set WiFi password
|
||||
const int Trig = 17; // 超声波传感器的触发引脚 Trigger pin of ultrasonic sensor
|
||||
const int Echo = 18; // 超声波传感器的回声引脚 The echo pin of the ultrasonic sensor
|
||||
// 创建 AsyncWebServer 对象
|
||||
AsyncWebServer server(80);
|
||||
|
||||
// 生成网页的 HTML 代码 Generates the HTML code for the web page
|
||||
const char index_html[] PROGMEM = R"rawliteral(
|
||||
<!DOCTYPE HTML><html>
|
||||
<head>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
|
||||
<style>
|
||||
html {
|
||||
font-family: Arial;
|
||||
display: inline-block;
|
||||
margin: 0px auto;
|
||||
text-align: center;
|
||||
}
|
||||
h2 { font-size: 3.0rem; }
|
||||
p { font-size: 3.0rem; }
|
||||
.units { font-size: 1.2rem; }
|
||||
.dht-labels{
|
||||
font-size: 1.5rem;
|
||||
vertical-align:middle;
|
||||
padding-bottom: 15px;
|
||||
}
|
||||
.slider {
|
||||
width: 80%;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h2>ESP32 Ultrasonic</h2>
|
||||
<p>
|
||||
<i id="ultrasonicIcon" class="fas fa-ruler-vertical" style="color:#70a3ff;"></i>
|
||||
<span class="dht-labels" id="ultrasonicText">Distance: -- cm</span>
|
||||
</p>
|
||||
</body>
|
||||
<script>
|
||||
setInterval(function ( ) {
|
||||
var xhttp = new XMLHttpRequest();
|
||||
xhttp.onreadystatechange = function() {
|
||||
if (this.readyState == 4 && this.status == 200) {
|
||||
var distance = parseInt(this.responseText);
|
||||
if (distance != -1) {
|
||||
document.getElementById("ultrasonicText").innerHTML = "Distance: " + distance + " cm";
|
||||
} else {
|
||||
document.getElementById("ultrasonicText").innerHTML = "Distance: Error";
|
||||
}
|
||||
}
|
||||
};
|
||||
xhttp.open("GET", "/ultrasonic", true);
|
||||
xhttp.send();
|
||||
}, 1000);
|
||||
</script>
|
||||
</html>
|
||||
)rawliteral";
|
||||
|
||||
float GetDistance() //获取超声波传感器数值 Get ultrasonic sensor values
|
||||
{
|
||||
float distance;
|
||||
//发送一个低短脉冲到Trig触发测距
|
||||
digitalWrite(Trig, LOW); //发送一个低电平到Trig
|
||||
delayMicroseconds(2);
|
||||
digitalWrite(Trig, HIGH);
|
||||
delayMicroseconds(10);
|
||||
digitalWrite(Trig, LOW);
|
||||
distance = pulseIn(Echo, HIGH) / 58.00;
|
||||
//Serial.print("Distance = ");
|
||||
//Serial.println(distance); //串行输出距离转换成厘米
|
||||
delay(10);
|
||||
return distance;
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
pinMode(Trig, OUTPUT); //定义引脚工作模式为输入 Define the pin operation mode as the input
|
||||
pinMode(Echo, INPUT); //定义引脚工作模式为输出 Define the pin operation mode as output
|
||||
Wire.begin(5, 4); //初始化 I2C 总线 SDA引脚设置为5,SCL引脚设置为4 The initial I2C bus SDA pin is set to 5 and the SCL pin is set to 4
|
||||
|
||||
// 初始化屏幕 Initializing the screen
|
||||
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
|
||||
Serial.println(F("SSD1306 initialization failed"));
|
||||
for (;;)
|
||||
;
|
||||
}
|
||||
|
||||
// 清空屏幕缓冲区 Clear the screen buffer
|
||||
display.clearDisplay();
|
||||
|
||||
// 显示超声波距离 Display ultrasonic distance
|
||||
display.setTextSize(2);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.setCursor(16, 8);
|
||||
display.println("Distance");
|
||||
display.setCursor(16, 40);
|
||||
display.print("0");
|
||||
display.print(" cm");
|
||||
display.display();
|
||||
|
||||
// 设置 WiFi 连接 Setting up WiFi connection
|
||||
WiFi.begin(ssid, password);
|
||||
Serial.println("Connecting to WiFi");
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(1000);
|
||||
Serial.println(".");
|
||||
}
|
||||
|
||||
Serial.println(WiFi.localIP()); //打印IP地址
|
||||
|
||||
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
request->send_P(200, "text/html", index_html);
|
||||
});
|
||||
|
||||
server.on("/ultrasonic", HTTP_GET, [](AsyncWebServerRequest *request) {
|
||||
float distance = GetDistance();
|
||||
if (distance >= 400 || distance <= 2) {
|
||||
distance = -1; // 超出范围或错误值
|
||||
}
|
||||
request->send(200, "text/plain", String(distance));
|
||||
|
||||
// 清空屏幕缓冲区
|
||||
display.clearDisplay();
|
||||
|
||||
// 显示超声波距离
|
||||
display.setTextSize(2);
|
||||
display.setTextColor(SSD1306_WHITE);
|
||||
display.setCursor(16, 8);
|
||||
display.println("Distance");
|
||||
display.setCursor(16, 40);
|
||||
display.print(distance);
|
||||
display.print(" cm");
|
||||
display.display();
|
||||
});
|
||||
|
||||
//启用服务器
|
||||
server.begin();
|
||||
}
|
||||
|
||||
void loop() {
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
#
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
#define LED 13 // Define the LED lamp output pin
|
||||
|
||||
void setup() {
|
||||
pinMode(LED, OUTPUT); // Define the operation mode of the pin
|
||||
digitalWrite(LED, LOW); // Output low level
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Because the negative electrode of the LED lamp is already connected to the GND,
|
||||
// it only needs to output a high level to run and light the LED lamp
|
||||
digitalWrite(LED, HIGH);
|
||||
}
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
# 2. Light up the LED
|
||||
|
||||
## 2.1.Overview
|
||||
|
||||
This section mainly focuses on understanding the characteristics of the main control board and expansion board, learning
|
||||
how to burn code and lighting the green LED on the expansion board through the program.
|
||||
|
||||
## 2.2.Control board resources
|
||||
|
||||
### 2.2.1.ESP32-S3-PLUS main control board
|
||||
* All I/O ports provided by the main control board support PWM;
|
||||
* Some I/O second functions also support SPI/IIC/clock output and other functions;
|
||||
* Tpye-C input voltage is 5V;
|
||||
* DCinput voltage 7V~9V
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/ESP32S3-Pinout.jpg" width="100%" height="100%"/>
|
||||
|
||||
### 2.2.2 Expansion board
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/expansion_board.png" width="800" height="600"/>
|
||||
|
||||
## 2.3.Connect the line
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/2.lesson_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 2.4. Upload code program
|
||||
|
||||
### 2.4.1. Connect the main control board to the computer with a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="800" height="600"/>
|
||||
|
||||
### 2.4.2. Open the " 2_ESP32_S3_PLUS \Lesson_2_Light_up_the_LED" code file
|
||||
|
||||
Select the board type as ESP32S3 Dev Module. When plugging in the USB, a new COM number will be displayed. Select it.
|
||||
|
||||
Here it is COM(x), but the actual COM number will be different for everyone.
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/arduino_program_run.png" width="800" height="600"/>
|
||||
|
||||
Click "Upload" to start compiling and uploading the program to the main control board.
|
||||
Waiting for the program to upload;
|
||||
|
||||
After the program upload is completed , you can see that the green light of LED2 is on.
|
||||
|
||||
## 2.5. Code analysis
|
||||
this " sketch " code consists of comments. These are not actual program instructions; instead, they simply explain how to
|
||||
make the program work. They are there for your ease of reading . Everything between " /* " and " */ " at the top of the
|
||||
sketch is a block comment that explains the purpose of the sketch.
|
||||
Single-line comments begin with "//" and everything up to the end of the line is considered a comment.
|
||||
|
||||
The first part of the code is:
|
||||
|
||||
```cpp
|
||||
#define LED 13 // Define the LED lamp output pin
|
||||
|
||||
void setup() {
|
||||
pinMode(LED, OUTPUT); // Define the operation mode of the pin
|
||||
digitalWrite(LED, LOW); // Output low level
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
* Every sketch requires a "set" function , which is a "void setup()" function, this is executed when the reset button is
|
||||
pressed.
|
||||
* It is executed whenever the board resets for any reason, such as first power-up or after uploading a sketch.
|
||||
* The next step is to name the pin and set the output. Here, set " LED " as the output port, and digitalWrite(LED,LOW)
|
||||
controls the pin to output a low level, which is to turn off.
|
||||
*The sketch must also have a " loop " function. Unlike the "Set " function, which only runs once , after a reset, the "Loop "
|
||||
function will start again immediately after completing the command run.
|
||||
|
||||
```cpp
|
||||
void loop() {
|
||||
// Because the negative electrode of the LED lamp is already connected to the GND,
|
||||
// it only needs to output a high level to run and light the LED lamp
|
||||
digitalWrite(LED, HIGH);
|
||||
}
|
||||
```
|
||||
|
||||
Inside the loop function, the command turns on the LED ( high )
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
//2025.07.04
|
||||
//#define button 46 문제있어서 gpio 13으로 바꿈
|
||||
#define LED 13
|
||||
#define button 8
|
||||
|
||||
int key_ok = 0; //Define the data variables needed for the project
|
||||
int LED_en = 0;
|
||||
|
||||
void setup() {
|
||||
pinMode(button, INPUT); //Define the operation mode of the pin
|
||||
pinMode(LED, OUTPUT);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Determine if a button has been pressed and read the button level
|
||||
if (digitalRead(button)) {
|
||||
if (key_ok) // Determine if the button is pressed
|
||||
{
|
||||
key_ok = 0;
|
||||
if (LED_en) LED_en = 0; // Determines whether the last flag bit is established
|
||||
else LED_en = 1;
|
||||
}
|
||||
} else {
|
||||
delay(20);
|
||||
if (!digitalRead(button)) key_ok = 1;
|
||||
}
|
||||
|
||||
// When the key is pressed, the level of the LED light output pin is reversed
|
||||
if (LED_en) digitalWrite(LED, HIGH);
|
||||
else digitalWrite(LED, LOW);
|
||||
}
|
||||
|
|
@ -0,0 +1,83 @@
|
|||
# 3. Button control LED
|
||||
|
||||
## 3.1.Overview
|
||||
This section focuses on learning how to use buttons to control LEDs to implement the delay control function.
|
||||
|
||||
## 3.2. Working principle
|
||||
The key signal pin S has a pull-up resistor by default, so it is high level and changes to low level when the key is pressed. At
|
||||
this time, the input of pin 46 of the main control board is low level. By judging the pin status as a condition, the LED pin
|
||||
level is flipped, thereby controlling the LED to turn on and off.
|
||||
|
||||
### 3.2.1.LED
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/3_lession_traffic_light.png" width="200" height="80"/>
|
||||
|
||||
LED(Light Emitting Diode), which converts electrical energy into light energy, also has one-way conductivity and a
|
||||
reverse breakdown voltage of about 5v. Its forward volt-ampere characteristic curve is very steep. In the development board,
|
||||
the negative electrodes of the LEDs are all common to the ground. When the signal pin is set to high level , the LED is on,
|
||||
and when it is set to low level , the LED is turned off.
|
||||
|
||||
## 3.3.Connect the lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/3.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 3.4.Upload code
|
||||
|
||||
### 3.4.1. Connect the main control board to the computer with a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 3.4.2. Open the program file (path: 2_ESP32_S3_PLUS \ Lesson_3_Button_control_LED )
|
||||
|
||||
Also select the board type as ESP32S3 Dev Module, and select the COM number that is newly displayed when the USB is
|
||||
|
||||
plugged in. In this case, it is COM29, but the actual COM number will be different for everyone.
|
||||
Click "Upload" to start compiling and uploading the program to the main control board.
|
||||
Wait for the program upload to complete .
|
||||
|
||||
Press the button to light up LED2, press it again to turn off LED2 , and repeat the above effect.
|
||||
|
||||
## 3.5. Code analysis
|
||||
First define the led pin , button pin and define two variables
|
||||
|
||||
```cpp
|
||||
#define LED 13
|
||||
#define button 8
|
||||
|
||||
int key_ok = 0; //Define the data variables needed for the project
|
||||
int LED_en = 0;
|
||||
```
|
||||
|
||||
Set the button pin as input and the LED pin as output
|
||||
|
||||
```cpp
|
||||
void setup() {
|
||||
pinMode(button, INPUT); //Define the operation mode of the pin
|
||||
pinMode(LED, OUTPUT);
|
||||
}
|
||||
```
|
||||
|
||||
Obtain the button status within the loop structure, use the if...else... statement to determine whether the button is pressed or
|
||||
released, implement the debounce function for the button status variable key_ok, and reverse the LED_en state when the
|
||||
button is released, thus affecting the LED Write high and low levels to make the LED turn on or off.
|
||||
|
||||
```cpp
|
||||
void loop() {
|
||||
// Determine if a button has been pressed and read the button level
|
||||
if (digitalRead(button)) {
|
||||
if (key_ok) // Determine if the button is pressed
|
||||
{
|
||||
key_ok = 0;
|
||||
if (LED_en) LED_en = 0; // Determines whether the last flag bit is established
|
||||
else LED_en = 1;
|
||||
}
|
||||
} else {
|
||||
delay(20);
|
||||
if (!digitalRead(button)) key_ok = 1;
|
||||
}
|
||||
|
||||
// When the key is pressed, the level of the LED light output pin is reversed
|
||||
if (LED_en) digitalWrite(LED, HIGH);
|
||||
else digitalWrite(LED, LOW);
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
#define Buzzer 21 // Define the active buzzer pin
|
||||
void setup() {
|
||||
pinMode(Buzzer, OUTPUT); // Define the pin as the output working mode
|
||||
}
|
||||
|
||||
void loop() {
|
||||
digitalWrite(Buzzer, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(Buzzer, LOW);
|
||||
delay(500);
|
||||
}
|
||||
|
|
@ -0,0 +1,54 @@
|
|||
# 4. Active buzzer
|
||||
|
||||
## 4.1.Overview
|
||||
The electronic buzzer is DC powered and equipped with an integrated circuit. They are widely used in computers, printers,
|
||||
copiers, alarms, electronic toys, automotive electronic equipment, telephones, timers and other electronic products for voice
|
||||
equipment. Buzzers can be divided into active buzzers and passive buzzers. Turn the two buzzer pins upward. The one with
|
||||
the green circuit board is the passive buzzer, and the other one sealed with black tape is the active buzzer. In this section you
|
||||
will learn how to use an active buzzer to generate a sound that sounds for half a second and then stops for half a second.
|
||||
|
||||
## 4.2. Working principle
|
||||
|
||||
### 4.2.1. Active buzzer
|
||||
An active buzzer has an internal oscillation source, and it can sound as long as it is given a high level. Use the delay
|
||||
function to make the buzzer sound regularly
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/4.lesson_buzzer.png" width="150" height="100"/>
|
||||
|
||||
## 4.3.Connect lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/4.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 4.4.Upload code
|
||||
|
||||
### 4.4.1. Connect the main control board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 4.4.2. Open the program file (path: 2_ESP32_S3_PLUS\ Lesson_4_active_buzzer )
|
||||
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board.
|
||||
|
||||
## 4.5. Code analysis
|
||||
|
||||
Define the buzzer pin and set the buzzer as an output
|
||||
|
||||
```cpp
|
||||
#define Buzzer 21 // Define the active buzzer pin
|
||||
void setup() {
|
||||
pinMode(Buzzer, OUTPUT); // Define the pin as the output working mode
|
||||
}
|
||||
```
|
||||
|
||||
The buzzer pin is at a high level for 500 milliseconds and then at a low level for 500 milliseconds to achieve a "beep" sound
|
||||
effect at intervals.
|
||||
|
||||
```cpp
|
||||
void loop() {
|
||||
digitalWrite(Buzzer, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(Buzzer, LOW);
|
||||
delay(500);
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
#define Green 13 // Define the green light pin
|
||||
#define Yellow 11 // Define the yellow light pin
|
||||
#define red 10 // Define the red light pin
|
||||
|
||||
void setup() {
|
||||
// Define the pin as the output working mode
|
||||
pinMode(Green, OUTPUT);
|
||||
pinMode(Yellow, OUTPUT);
|
||||
pinMode(red, OUTPUT);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
digitalWrite(Green, HIGH); // Turn on the green light
|
||||
digitalWrite(Yellow, LOW); // Put out the yellow light
|
||||
digitalWrite(red, LOW); // Turn off the red light
|
||||
delay(5000); // Turn on the green light for five seconds
|
||||
|
||||
// The green light flashes every 500 milliseconds
|
||||
digitalWrite(Green, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(Green, LOW);
|
||||
delay(500);
|
||||
digitalWrite(Green, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(Green, LOW);
|
||||
delay(500);
|
||||
digitalWrite(Green, HIGH);
|
||||
delay(500);
|
||||
|
||||
// The yellow light is on for 1 second
|
||||
digitalWrite(Green, LOW);
|
||||
digitalWrite(Yellow, HIGH);
|
||||
digitalWrite(red, LOW);
|
||||
delay(1200);
|
||||
|
||||
// The red light stays on for 5 seconds
|
||||
digitalWrite(Green, LOW);
|
||||
digitalWrite(Yellow, LOW);
|
||||
digitalWrite(red, HIGH);
|
||||
delay(5000);
|
||||
|
||||
// The red light flashes every 500 milliseconds
|
||||
digitalWrite(red, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(red, LOW);
|
||||
delay(500);
|
||||
digitalWrite(red, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(red, LOW);
|
||||
delay(500);
|
||||
digitalWrite(red, HIGH);
|
||||
delay(500);
|
||||
}
|
||||
|
|
@ -0,0 +1,110 @@
|
|||
# 5. Traffic lights
|
||||
|
||||
## 5.1 Overview
|
||||
In this section, you will learn to light multiple LEDs and control the green, yellow, and red lights to light up at intervals
|
||||
through a delay function to achieve the effect of a traffic light.
|
||||
|
||||
## 5.2. Working principle
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/3_lession_traffic_light.png" width="200" height="80"/>
|
||||
|
||||
There are three colors of traffic lights, green light, yellow light and red light. The pins connected to the main control board
|
||||
are 13/11/10. By controlling the high level of the three pins, the corresponding lights can be lit. A single light cycle is as
|
||||
follows: first let the green light be on for a period of time, which means that the traffic is in a passable state, then flash a
|
||||
reminder before the green light ends and switch to the yellow light, then switch to the yellow light, and wait for a short
|
||||
period of time before switching to the yellow light. Switch to red light. The red light also waits for a period of time,
|
||||
indicating that traffic is prohibited from passing, and flashes as a reminder before the red light ends and is ready to switch to
|
||||
the green light.
|
||||
So the single-cycle process is roughly as follows:
|
||||
Leave the green light on for five seconds , the green light flashing every 500 milliseconds, the yellow light on for 1 second,
|
||||
|
||||
|
||||
the red light on for 5 seconds, the red light flashing every 500 milliseconds, and so on.
|
||||
|
||||
## 5.3 Connection lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/5.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 5.4 Upload code
|
||||
|
||||
### 5.4.1 Connect the main control board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 5.4.2 Open the program file (path: 2_ESP32_S3_PLUS\ Lesson_5_Traffic_light )
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board.
|
||||
|
||||
## 5.5 Code analysis
|
||||
|
||||
Define three LED pins
|
||||
|
||||
```cpp
|
||||
#define Green 13 // Define the green light pin
|
||||
#define Yellow 11 // Define the yellow light pin
|
||||
#define red 10 // Define the red light pin
|
||||
```
|
||||
|
||||
Set pin as output
|
||||
|
||||
```cpp
|
||||
void setup() {
|
||||
// Define the pin as the output working mode
|
||||
pinMode(Green, OUTPUT);
|
||||
pinMode(Yellow, OUTPUT);
|
||||
pinMode(red, OUTPUT);
|
||||
}
|
||||
```
|
||||
|
||||
The loop function executes a single light cycle.
|
||||
|
||||
The red light first lights up for 5 seconds and then flashes every 500 milliseconds.
|
||||
```cpp
|
||||
void loop() {
|
||||
digitalWrite(Green, HIGH); // Turn on the green light
|
||||
digitalWrite(Yellow, LOW); // Put out the yellow light
|
||||
digitalWrite(red, LOW); // Turn off the red light
|
||||
delay(5000); // Turn on the green light for five seconds
|
||||
|
||||
// The green light flashes every 500 milliseconds
|
||||
digitalWrite(Green, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(Green, LOW);
|
||||
delay(500);
|
||||
digitalWrite(Green, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(Green, LOW);
|
||||
delay(500);
|
||||
digitalWrite(Green, HIGH);
|
||||
delay(500);
|
||||
```
|
||||
Yellow light on for 1 second
|
||||
```cpp
|
||||
// The yellow light is on for 1 second
|
||||
digitalWrite(Green, LOW);
|
||||
digitalWrite(Yellow, HIGH);
|
||||
digitalWrite(red, LOW);
|
||||
delay(1200);
|
||||
```
|
||||
|
||||
Finally, the red light turns on for 5 seconds and then flashes every 500 milliseconds
|
||||
```cpp
|
||||
// The red light stays on for 5 seconds
|
||||
digitalWrite(Green, LOW);
|
||||
digitalWrite(Yellow, LOW);
|
||||
digitalWrite(red, HIGH);
|
||||
delay(5000);
|
||||
|
||||
// The red light flashes every 500 milliseconds
|
||||
digitalWrite(red, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(red, LOW);
|
||||
delay(500);
|
||||
digitalWrite(red, HIGH);
|
||||
delay(500);
|
||||
digitalWrite(red, LOW);
|
||||
delay(500);
|
||||
digitalWrite(red, HIGH);
|
||||
delay(500);
|
||||
```
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
#define Green 13 // Define the green light pin
|
||||
#define Yellow 11 // Define the yellow light pin
|
||||
#define red 10 // Define the red light pin
|
||||
|
||||
void setup() {
|
||||
// Define the pin as the output working mode
|
||||
pinMode(Green, OUTPUT);
|
||||
pinMode(Yellow, OUTPUT);
|
||||
pinMode(red, OUTPUT);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
|
||||
digitalWrite(Green, HIGH); // Turn on the green light
|
||||
digitalWrite(Yellow, LOW); // Turn off the yellow light
|
||||
digitalWrite(red, LOW); // Turn off the red light
|
||||
delay(200); // Turn on the green light for 200 millisecond
|
||||
|
||||
digitalWrite(Green, LOW); // Turn on the green light
|
||||
digitalWrite(Yellow, HIGH); // Put out the yellow light
|
||||
digitalWrite(red, LOW); // Turn off the red light
|
||||
delay(200); // Turn on the green light for 200 millisecond
|
||||
|
||||
digitalWrite(Green, LOW); // Turn off the green light
|
||||
digitalWrite(Yellow, LOW); // Turn off the yellow light
|
||||
digitalWrite(red, HIGH); // Turn on the red light
|
||||
delay(200); // Turn on the green light for 200 millisecond
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
# 6. Flowing water lamp
|
||||
|
||||
## 6.1.Overview
|
||||
In this section, you will learn how to use three LED lights to achieve a running water effect.
|
||||
|
||||
## 6.2. Working principle
|
||||
As in the previous section "Traffic Light Project", the LED on/off is controlled by controlling the high/low level of the three
|
||||
LED light pins. After setting the waiting time for on and off, you can see the lighting process of the three LEDs one by one,
|
||||
simulating the effect of running water lamps.
|
||||
|
||||
## 6.3 Connection lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/5.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 6.4 Upload code
|
||||
|
||||
### 6.4.1 Connect the main control board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 6.4.2 Open the program file (path: 2_ESP32_S3_PLUS\ Lesson_6_Flow_light )
|
||||
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board.
|
||||
|
||||
## 6.5 Code analysis
|
||||
|
||||
Define three LED pins and operating modes
|
||||
|
||||
```cpp
|
||||
#define Green 13 // Define the green light pin
|
||||
#define Yellow 11 // Define the yellow light pin
|
||||
#define red 10 // Define the red light pin
|
||||
|
||||
void setup() {
|
||||
// Define the pin as the output working mode
|
||||
pinMode(Green, OUTPUT);
|
||||
pinMode(Yellow, OUTPUT);
|
||||
pinMode(red, OUTPUT);
|
||||
}
|
||||
```
|
||||
|
||||
Within the loop function, each LED light is lit individually at intervals of 200 milliseconds
|
||||
|
||||
```cpp
|
||||
void loop() {
|
||||
|
||||
digitalWrite(Green, HIGH); // Turn on the green light
|
||||
digitalWrite(Yellow, LOW); // Turn off the yellow light
|
||||
digitalWrite(red, LOW); // Turn off the red light
|
||||
delay(200); // Turn on the green light for 200 millisecond
|
||||
|
||||
digitalWrite(Green, LOW); // Turn on the green light
|
||||
digitalWrite(Yellow, HIGH); // Put out the yellow light
|
||||
digitalWrite(red, LOW); // Turn off the red light
|
||||
delay(200); // Turn on the green light for 200 millisecond
|
||||
|
||||
digitalWrite(Green, LOW); // Turn off the green light
|
||||
digitalWrite(Yellow, LOW); // Turn off the yellow light
|
||||
digitalWrite(red, HIGH); // Turn on the red light
|
||||
delay(200); // Turn on the green light for 200 millisecond
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
#include <FastLED.h> // FastLED Declare the FastLED library
|
||||
|
||||
#define LED_PIN 6 // Define the WS2812 RGB lamp pin
|
||||
#define NUM_LEDS 12 // Define the number of beads
|
||||
#define BRIGHTNESS 64 // Set the light level from 0 to 255, with the higher the light
|
||||
|
||||
CRGB leds[NUM_LEDS]; //An array of CRGB type with length NUM_LEDS is instantiated to control the WS2812B LED strip
|
||||
|
||||
void setup() {
|
||||
FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS); // Use the NEOPIXEL type
|
||||
FastLED.setBrightness(BRIGHTNESS); // Initialize the light level
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Light the leds one by one to show green
|
||||
for (int i = 0; i < NUM_LEDS; i++) {
|
||||
fill_solid(leds, NUM_LEDS, CRGB::Black); // Turn off all leds
|
||||
leds[i] = CRGB::Green; // Light only the current LED
|
||||
FastLED.show();
|
||||
delay(100);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
# 7. WS2812B
|
||||
|
||||
## 7.1. Overview
|
||||
This section focuses on understanding ws2812 and learning how to declare a library and instantiate objects through the
|
||||
library to light up RGB lights one by one in turn. We will use a library designed specifically for these sensors, which will
|
||||
keep our code short and easy to write.
|
||||
|
||||
## 7.2. Working principle
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/7_lession_ws2812b.png" width="150" height="150"/>
|
||||
|
||||
WS2812B is an intelligent externally controlled LED light source that integrates control circuit and light-emitting circuit. Its
|
||||
appearance is the same as a 5050LED lamp bead, and each component is a pixel. There is an intelligent digital interface data
|
||||
latch signal shaping amplification drive circuit, a high-precision internal oscillator and a 12V high-voltage programmable
|
||||
fixed current control part inside the pixel, which effectively ensures that the pixel light color is highly consistent.
|
||||
The data protocol adopts single-line zero return code communication method. After the pixel is powered on and reset, the
|
||||
DIN client receives the data from the controller and first sends out the 24-bit data. After extracting the first pixel, it is sent to
|
||||
the pixel data latch. The remaining data is shaped and amplified by the internal shaping processing circuit. . It starts to be
|
||||
|
||||
forwarded to the next cascade pixel through the DO output port. After each pixel is transmitted, the signal is reduced by 24
|
||||
bits.The pixels adopt automatic shaping and forwarding technology, so that the number of cascades of pixels is not limited
|
||||
by signal transmission, but only limited by the signal transmission speed requirements.
|
||||
|
||||
## 7.3.Connect the lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/7.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 7.4.Upload code
|
||||
|
||||
### 7.4.1. Connect the main control board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 7.4.2 Open the program file (path: 2_ESP32_S3_PLUS\ Lesson_7_WS2812B )
|
||||
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board.
|
||||
|
||||
## 7.5. Code analysis
|
||||
|
||||
Declare the FastLED library, define the ws2812 pin as 6, the number of lamp beads as 12 and the brightness value as 64.
|
||||
|
||||
```cpp
|
||||
#include <FastLED.h> // FastLED Declare the FastLED library
|
||||
|
||||
#define LED_PIN 6 // Define the WS2812 RGB lamp pin
|
||||
#define NUM_LEDS 12 // Define the number of beads
|
||||
#define BRIGHTNESS 64 // Set the light level from 0 to 255, with the higher the light
|
||||
```
|
||||
|
||||
Instantiate ws2812 as LEDs, set the NEOPIXEL type and initialize the light brightness.
|
||||
|
||||
```cpp
|
||||
|
||||
CRGB leds[NUM_LEDS]; //An array of CRGB type with length NUM_LEDS is instantiated to control the WS2812B LED strip
|
||||
|
||||
void setup() {
|
||||
FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS); // Use the NEOPIXEL type
|
||||
FastLED.setBrightness(BRIGHTNESS); // Initialize the light level
|
||||
}
|
||||
```
|
||||
|
||||
The loop function lights up the LEDs one by one and displays green
|
||||
|
||||
```cpp
|
||||
void loop() {
|
||||
// Light the leds one by one to show green
|
||||
for (int i = 0; i < NUM_LEDS; i++) {
|
||||
fill_solid(leds, NUM_LEDS, CRGB::Black); // Turn off all leds
|
||||
leds[i] = CRGB::Green; // Light only the current LED
|
||||
FastLED.show();
|
||||
delay(100);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
#include <FastLED.h>
|
||||
|
||||
#define LED_PIN 6 // Define the WS2812 RGB lamp pin
|
||||
#define NUM_LEDS 12 // Define the number of beads
|
||||
#define BRIGHTNESS 64 // Set the light level from 0 to 255, with the higher the light
|
||||
CRGB leds[NUM_LEDS]; //An array of CRGB type with length NUM_LEDS is instantiated to control the WS2812B LED strip
|
||||
|
||||
void setup() {
|
||||
FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS); // Use the NEOPIXEL type
|
||||
FastLED.setBrightness(BRIGHTNESS); // Initialize the light level
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Gradients display different colors
|
||||
for (int hue = 0; hue < 255; hue++) {
|
||||
fill_rainbow(leds, NUM_LEDS, hue, 8);
|
||||
FastLED.show();
|
||||
delay(20);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
# 8. Gradient RGB
|
||||
|
||||
## 8.1. Overview
|
||||
In this section , you will learn the control of WS2812 in an advanced way to achieve the effect of RGB light gradient .
|
||||
|
||||
## 8.2. Working principle
|
||||
Use the library function fill_rainbow(leds, NUM_LEDS, hue, 8); to change the gradient display of RGB lights.
|
||||
|
||||
## 8.3 Connection lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/7.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 8.4. Upload code program
|
||||
|
||||
### 8.4.1. Connect the main control board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 8.4.2 Open the program file (path: 2_ESP32_S3_PLUS\Lesson_8_Gradient_RGB_light)
|
||||
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board, and wait for the program
|
||||
|
||||
upload to be completed .
|
||||
|
||||
## 8.5 Code analysis
|
||||
The declaration library, pin definition and setting part of the code are consistent with the previous section, and then use the
|
||||
fill_rainbow function in the loop function to implement the rainbow color gradient.
|
||||
|
||||
```cpp
|
||||
void loop() {
|
||||
// Gradients display different colors
|
||||
for (int hue = 0; hue < 255; hue++) {
|
||||
fill_rainbow(leds, NUM_LEDS, hue, 8);
|
||||
FastLED.show();
|
||||
delay(20);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
#include <ESP32Servo.h>
|
||||
#define SERVO_PIN 9 // Connect the servo signal line to A0 of UNOR4 MINIMA
|
||||
Servo myServo; // Instantiate a steering gear object
|
||||
|
||||
void setup() {
|
||||
pinMode(SERVO_PIN, OUTPUT); // Set the servo connected pin to output mode
|
||||
myServo.attach(SERVO_PIN); // Set the steering gear object
|
||||
}
|
||||
|
||||
void loop() {
|
||||
// Let the steering gear turn from 180 to 0 degrees
|
||||
for (int angle = 180; angle >= 0; angle--) {
|
||||
myServo.write(angle);
|
||||
delay(10);
|
||||
}
|
||||
|
||||
// Let the steering gear turn from 0 to 180 degrees
|
||||
for (int angle = 0; angle <= 180; angle++) {
|
||||
myServo.write(angle);
|
||||
delay(10);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,71 @@
|
|||
# 9.Servo control
|
||||
|
||||
## 9.1. Overview
|
||||
In this section, you will learn how to drive the servo to achieve 0~180° rotation.
|
||||
|
||||
## 9.2 Working principle
|
||||
|
||||
### 9.2.1. Steering gear
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/9.lesson_servo.png" width="150" height="150"/>
|
||||
|
||||
The steering gear ( servo motor ) control pulse signal period is a 20MS pulse width modulation signal (PWM), the pulse
|
||||
width is from 0.5ms to 2.5ms, and the corresponding steering position changes linearly from 0 to 180 degrees.
|
||||
There is a reference circuit inside the steering gear, which generates a pulse signal with a period of 20ms and a width of
|
||||
1.5ms. There is a comparator that compares the external signal with the reference signal to determine the direction and size,
|
||||
thereby generating a motor rotation signal.
|
||||
|
||||
## 9.3 Connection lines
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/9.lession_connect_line.png" width="800" height="600"/>
|
||||
|
||||
## 9.4 Upload code program
|
||||
|
||||
### 9.4.1 Connect the main control SD board to the computer using a USB cable
|
||||
|
||||
<img src="https://mkpark.iptime.org:10443/esp32S3_tscinbuny_tutorial/images/upload_code_program.png" width="600" height="200"/>
|
||||
|
||||
### 9.4.2 Open the program file (path: 2_ESP32_S3_PLUS\Lesson_9_Steering_gear_control)
|
||||
Also select the board type as ESP32S3 Dev Module and select the COM number newly displayed when the USB is plugged
|
||||
in . Then click "Upload" to start compiling and uploading the program to the main control board, and wait for the program
|
||||
upload to be completed .
|
||||
|
||||
## 9.5 Code analysis
|
||||
|
||||
Declare the servo library Servo, define the servo pin A0 and instantiate the servo object myServo.
|
||||
|
||||
```cpp
|
||||
#include <ESP32Servo.h>
|
||||
|
||||
#define SERVO_PIN 9 // Connect the servo signal line to A0 of UNOR4 MINIMA
|
||||
Servo myServo; // Instantiate a steering gear object
|
||||
```
|
||||
|
||||
Set the servo pin to output mode and initialize the servo.
|
||||
|
||||
```cpp
|
||||
|
||||
void setup() {
|
||||
pinMode(SERVO_PIN, OUTPUT); // Set the servo connected pin to output mode
|
||||
myServo.attach(SERVO_PIN); // Set the steering gear object
|
||||
}
|
||||
```
|
||||
|
||||
Let the servo rotate back and forth between 0~180° in the loop function.
|
||||
|
||||
```cpp
|
||||
|
||||
void loop() {
|
||||
// Let the steering gear turn from 180 to 0 degrees
|
||||
for (int angle = 180; angle >= 0; angle--) {
|
||||
myServo.write(angle);
|
||||
delay(10);
|
||||
}
|
||||
|
||||
// Let the steering gear turn from 0 to 180 degrees
|
||||
for (int angle = 0; angle <= 180; angle++) {
|
||||
myServo.write(angle);
|
||||
delay(10);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
After Width: | Height: | Size: 379 KiB |
|
After Width: | Height: | Size: 7.7 KiB |
|
After Width: | Height: | Size: 485 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 42 KiB |
|
After Width: | Height: | Size: 256 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 113 KiB |
|
After Width: | Height: | Size: 437 KiB |
|
After Width: | Height: | Size: 29 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 442 KiB |
|
After Width: | Height: | Size: 195 KiB |
|
After Width: | Height: | Size: 437 KiB |
|
After Width: | Height: | Size: 419 KiB |
|
After Width: | Height: | Size: 24 KiB |
|
After Width: | Height: | Size: 434 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 398 KiB |
|
After Width: | Height: | Size: 320 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 470 KiB |
|
After Width: | Height: | Size: 22 KiB |
|
After Width: | Height: | Size: 2.2 MiB |
|
After Width: | Height: | Size: 266 KiB |
|
After Width: | Height: | Size: 468 KiB |
|
After Width: | Height: | Size: 130 KiB |