1、环境搭建
(1)官网下载:Arduino - Home
(2)配置首选项
资源下载,点击下载
文件——>首选项——>开发管理地址
添加开发板地址:https://arduino.me/packages/esp32.json
下载社区打包的esp32安装包,直接运行,程序会自动解压到相应位置。
重启Arduino
配置工具和选择芯片
usb驱动安装(点击安装即可)
链接: https://pan.baidu.com/s/1sQGQ3WuVXw92RiqmRMDfJA?pwd=sd1p 提取码: sd1p
2、GPIO_OUTPUT模式
步骤:
1、设置GPIO模式
2、设置GPIO电平
案例:点亮、延时、熄灭、延时
#define led 4;//定义端口4
void setup() {
pinMode(led, OUTPUT);//设置GPIO模式
}
void loop() {
digitalWrite(led, HIGH); //给端口高电平
delay(1000); //延时
digitalWrite(led, LOW); //给端口低电平
delay(1000);
}
3、串口调试函数
(1)print() 不换行
(2)println() 换行
(3)printf() 格式化、不换行
案例:分别使用(1)、(2)、(3)
void setup() {
int x=2024,y=7,z=18;//定义三个整型并赋值
Serial.begin(115200);//初始化串口,设置波特率为115200
Serial.print("hello");
Serial.println("wzf");
Serial.printf("%d-%d-%d",x,y,z);
}
void loop() {
}
输出
4、串口读数据
read() 读取一个字节
readString() 读取字符串
available() 判断串口是否有数据,返回int型数据长度
案例:读取串口一个字节数据
void setup() {
Serial.begin(115200); //初始化串口,设置波特率为115200
}
void loop() {
int lenth = Serial.available();//保存串口数据长度
if (lenth > 0) {
char data=Serial.read();//读取串口数据
data--;//将数据减一
Serial.println(String(data));//打印数据并换行
}
}
案例:读取串口数据到字符串
//定义一个读取字符串函数
void read_String() {
int length = Serial.available();
if (length > 0) {
String data = Serial.readString(); //读取串口数据
Serial.println(data); //打印数据并换行
}
}
void setup() {
Serial.begin(115200); //初始化串口,设置波特率为115200
}
void loop() {
read_String();
delay(10);// 添加一个小延迟可以帮助避免在连续发送大量数据时完全占用CPU
}
案例:读取串口数据到字符数组
//定义一个读取数据到数组的函数
void read_Arr() {
int length = Serial.available();
if (length > 0) {
char data[64];
Serial.read(data, length); //读取串口数据(data:缓存位置 length:存储长度)
Serial.println(String(data)); //打印数据并换行
}
}
void setup() {
Serial.begin(115200); //初始化串口,设置波特率为115200
}
void loop() {
read_Arr();
delay(10); // 添加一个小延迟可以帮助避免在连续发送大量数据时完全占用CPU
}
5、串口写数据
write() 写入数据
案例:写数据并输出
void setup() {
Serial.begin(115200); //初始化串口,设置波特率为115200
Serial.write(98);//输出以Ascll码输出
Serial.println();//输出一个换行
Serial.print(98);//原样输出
}
void loop() {
}
6、按键控制
arduino的引脚模式有三种:
- INPUT——输入模式
- OUTPUT——输出模式
- INPUT_PULLUP——输入上拉模式
digitalRead() 读取引脚电平状态(参数为引脚号)
案例:按键按下控制其他引脚输出(按键:2 输出:4)
#define KEY 2 //定义2号引脚为按键
#define OUT 4 //定义1号引脚为输出
//按键扫描函数
void Scan_Key() {
if (digitalRead(KEY) == LOW) {
delay(10); //按键消抖处理
if (digitalRead(KEY) == LOW) {
digitalWrite(OUT, HIGH);//设置输出引脚为高电平
Serial.println("成功进入");
while (digitalRead(KEY) == LOW)
;
Serial.println("成功退出");
digitalWrite(OUT, LOW);//设置输出引脚为低电平
}
}
}
void setup() {
Serial.begin(115200);
pinMode(OUT, OUTPUT); //设置引脚4为输出模式
pinMode(KEY, INPUT_PULLUP); //设置引脚2为输入上拉模式
}
void loop() {
Scan_Key();
}
7、PWM输出控制
ledcSetup (通道,频率、精度)
ledcAttachPin (goio引脚,通道号)
ledcWrite (通道,占空比)
案例:控制引脚4从低电平到高电平,再从高电平到低电平
#define LED 4
void setup() {
//初始化通道并设置频率和精度2^10=1024
ledcSetup(1, 1000, 10);
//绑定输出引脚和通道
ledcAttachPin(LED, 1);
}
void loop() {
for (int duty = 0; duty < 1023; duty++) {
//设置占空比
ledcWrite(1, duty);
delay(5);
}
for (int duty = 1023; duty >= 0; duty--) {
ledcWrite(1, duty);
delay(5);
}
}
8、定时器
硬件定时器
hw_timer_t * =timerBegin(定时器序号,预分屏系数,是否向上计数) esp32c3 80Mhz
timerAttachInterrupt(定时器对象(结构体指针),回调函数,是否边缘触发)
timerAlarmWrite(定时器对象,计数值,是否自动加载)
timerAlarmEnable(定时器对象)
timerAlarmDisable(定时器对象)
案例:定时1s使引脚2电平反转
#define LED 2
void Time()
{
digitalWrite(LED, !digitalRead(LED));
}
void setup() {
//初始化定时器
hw_timer_t *time0 = timerBegin(0,80,true);//80Mhz/80=1Mhz(1us)
//绑定回调函数
timerAttachInterrupt(time0,Time,true);
//设置定时器每隔1秒(1,000,000微秒)触发一次中断
timerAlarmWrite(time0,1000000,true);
//启动定时器
timerAlarmEnable(time0);
pinMode(LED, OUTPUT);
}
void loop() {
}
软件定时器
setTimeout(定时器回调函数,定时时间ms) 单次运行的定时任务
setInterval(定时器回调函数,定时时间ms) 周期运行的定时任务
cancel(定时器编号) 停止定时器的定时任务
cancelAll(true) 停止所有定时任务
changeDelay(定时器编号,新的定时时间ms) 改变定时任务的执行周期
案例:定时2s使引脚2电平反转,翻转5次后又重新设置为3s
首先安装AsyncTimer库
#include "AsyncTimer.h"
#define LED 2
AsyncTimer T;//定义一个定时器
int TimerID =0;//定时器编号
int i=0;//记录执行次数
//定时器回调函数,无传参
void Timer()
{
digitalWrite(LED, !digitalRead(LED));
i++;
}
void setup() {
//创建周期性定时任务
TimerID = T.setInterval(Timer,2000);//返回任务编号
pinMode(LED, OUTPUT);
}
void loop() {
T.handle();//开启定时器
if(i>5)
{
T.changeDelay(TimerID,3000);
}
}
9、外部中断
attachInterrupt(中断信号输入引脚,中断服务程序地址,中断触发类型)
中断触发类型:HIGH LOW RISING FALLING上升沿 CHANGE改变
volatile 关键字
案例:按键4控制LED2电平翻转
#define LED 2
#define KEY 4
volatile int i = 0; //标志0:led灭 1:led亮
//中断服务函数
IRAM_ATTR void Interrupt() {
i = (i == 0) ? 1 : 0;
}
void setup() {
pinMode(LED, OUTPUT);
pinMode(KEY, INPUT_PULLUP); //输入上拉模式
attachInterrupt(digitalPinToInterrupt(KEY), Interrupt, FALLING);
}
void loop() {
if (i == 0) {
digitalWrite(LED, LOW);
} else {
digitalWrite(LED, HIGH);
}
}
10、模数转换
analogReadResolution(精度) 更改精度值,一般是12不用改
analogRead(引脚) 模数转换,读取引脚
analogWrite(引脚,对应电压) 数模转换,写入引脚
电压:电压值= 测量值*(3.3 / 2^精度 -1)
案例:串口输出模数转换结果,输出33引脚的电压值
#define INPUT 33
void setup() {
Serial.begin(115200);
}
void loop() {
int values = analogRead(INPUT);
float volt = values *(3.3/4095);
Serial.printf("转换值为:%d\n电压为:%2f V",values,volt);
Serial.println();
delay(3000);
}
11、OLED显示屏
关键是取字模软件的使用
http://链接: https://pan.baidu.com/s/1oWOY4U06IwpFtkfgz9aUAg?pwd=ic6u 提取码: ic6u
加载库:Adafruit_SSD1306
clearDisplay(); 清屏
display(); 显示
setTextColor(INVERSE); 设置颜色
setTextSize(); 设置字体大小
print("hello worle!"); 输出字符串
drawBitmap(x坐标、y坐标、文字数据、文字宽、文字高、颜色)
OLED显示字符串
案例:oled屏显示hello world
#include "Adafruit_SSD1306.h"
#define SCL 22
#define SDA 21
//定义i2c对象
TwoWire i2c = TwoWire(0);
//定义显示屏对象(长、宽、i2c对象)
Adafruit_SSD1306 oled = Adafruit_SSD1306(128, 64, &i2c);
void Init_Oled() {
//初始化i2c对象(数据线、信号线、波特率)
i2c.begin(SDA, SCL, 400000);
//初始化显示屏对象(vcc供电、通讯地址)
oled.begin(SSD1306_SWITCHCAPVCC, 0x3c);
//设置显示字体大小
oled.setTextSize(3);
//设置显示字体颜色
oled.setTextColor(INVERSE);
}
void setup() {
Init_Oled(); //初始化
oled.clearDisplay(); //清屏
oled.print("hello \n worle!"); //写入hello world
oled.display(); //显示
}
void loop() {
}
OLED显示中文
案例:oled屏显示“你好”
#include "Adafruit_SSD1306.h"
#define SCL 22
#define SDA 21
//定义i2c对象
TwoWire i2c = TwoWire(0);
//定义显示屏对象(长、宽、i2c对象)
Adafruit_SSD1306 oled = Adafruit_SSD1306(128, 64, &i2c);
//新建字库
const unsigned char ZiKu[][32] {
{ 0x08, 0x80, 0x08, 0x80, 0x08, 0x80, 0x11, 0xFE, 0x11, 0x02, 0x32, 0x04, 0x34, 0x20, 0x50, 0x20,
0x91, 0x28, 0x11, 0x24, 0x12, 0x24, 0x12, 0x22, 0x14, 0x22, 0x10, 0x20, 0x10, 0xA0, 0x10, 0x40 }, /*"你",0*/
{ 0x10, 0x00, 0x10, 0xFC, 0x10, 0x04, 0x10, 0x08, 0xFC, 0x10, 0x24, 0x20, 0x24, 0x20, 0x25, 0xFE,
0x24, 0x20, 0x48, 0x20, 0x28, 0x20, 0x10, 0x20, 0x28, 0x20, 0x44, 0x20, 0x84, 0xA0, 0x00, 0x40 }, /*"好",1*/
{ 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00, 0x10, 0x00,
0x10, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00 }, /*"!",2*/
};
void Init_Oled() {
//初始化i2c对象(数据线、信号线、波特率)
i2c.begin(SDA, SCL, 400000);
//初始化显示屏对象(vcc供电、通讯地址)
oled.begin(SSD1306_SWITCHCAPVCC, 0x3c);
//设置显示字体大小
oled.setTextSize(1);
//设置显示字体颜色
oled.setTextColor(INVERSE);
}
void setup() {
Init_Oled(); //初始化
oled.clearDisplay(); //清屏
oled.drawBitmap(25,5,ZiKu[0],16,16,1);//你
oled.drawBitmap(43,5,ZiKu[1],16,16,1);//好
oled.drawBitmap(61,5,ZiKu[2],16,16,1);//!
oled.display(); //显示
}
void loop() {
}
OLED显示图片
案例:显示图片
#include "Adafruit_SSD1306.h"
#define SCL 22
#define SDA 21
//定义i2c对象
TwoWire i2c = TwoWire(0);
//定义显示屏对象(长、宽、i2c对象)
Adafruit_SSD1306 oled = Adafruit_SSD1306(128, 64, &i2c);
//新建图片字库
const unsigned char Img[] {
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0xF8,0x00,0x00,0x00,0x1F,0xFF,0xF8,0x00,
0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0xF8,0x00,0x00,0x00,0x1F,0xFF,0xF8,0x00,
0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0xF8,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,
0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0xF8,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,
0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0xF8,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,
0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0xF8,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,
0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0xF8,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,
0x00,0x00,0x00,0x00,0x00,0x1D,0xFF,0xFF,0xF0,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,
0x00,0x00,0x1F,0x00,0x00,0x1F,0xFF,0xF0,0x00,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,
0x00,0x00,0x1F,0x00,0x00,0x1F,0xFF,0xF0,0x00,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,
0x00,0x03,0xFF,0x00,0x01,0xFF,0xF0,0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0x80,
0x00,0x03,0xFF,0x00,0x01,0xFF,0xF0,0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0x80,
0x00,0x3F,0xF0,0x00,0x1F,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xF8,0x00,
0x00,0x3F,0xF0,0x00,0x1F,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xF8,0x00,
0x00,0x3F,0xF0,0x00,0x1F,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x3F,0xF0,0x00,0x1F,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x03,0xFF,0x00,0x01,0xFF,0xF0,0x00,0x1F,0xF0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x03,0xFF,0x00,0x01,0xFF,0xF0,0x00,0x1F,0xF0,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x03,0xFF,0x00,0x01,0xFF,0xF0,0x01,0xFF,0xFF,0x80,0x01,0xFF,0x80,0x00,0x00,0x00,
0x03,0xFF,0x00,0x01,0xFF,0xF0,0x01,0xFF,0xFF,0x80,0x01,0xFF,0x80,0x00,0x00,0x00,
0x03,0xFF,0x00,0x01,0xFF,0xF0,0x1F,0xFF,0xFF,0x80,0x1F,0xFF,0xF8,0x00,0x00,0x00,
0x03,0xFF,0x00,0x01,0xFF,0xF0,0x1F,0xFF,0xFF,0x80,0x1F,0xFF,0xF8,0x00,0x00,0x00,
0x03,0xFF,0x00,0x01,0xFF,0xF0,0x1F,0xFF,0xFF,0x80,0x1F,0xFF,0xFF,0x81,0xF8,0x00,
0x03,0xFF,0x00,0x01,0xFF,0xF0,0x1F,0xFF,0xFF,0x00,0x1F,0xFF,0xFF,0x81,0xF8,0x00,
0x03,0xFF,0xF0,0x01,0xFF,0xFF,0x1F,0xFF,0xF8,0x00,0x1F,0xFF,0xFF,0x81,0xF8,0x00,
0x03,0xFF,0xF0,0x01,0xFF,0xFF,0x1F,0xFF,0xF8,0x00,0x1F,0xFF,0xFF,0x81,0xF8,0x00,
0x03,0xFF,0x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xFF,0x80,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0xFF,0xFF,0x9F,0xFF,0xFF,0x80,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0xFF,0x9F,0xFF,0xF8,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0xFF,0x9F,0xFF,0xF8,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x01,0xFF,0xFF,0xFF,0x80,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1F,0xFF,0xFF,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
void Init_Oled() {
//初始化i2c对象(数据线、信号线、波特率)
i2c.begin(SDA, SCL, 400000);
//初始化显示屏对象(vcc供电、通讯地址)
oled.begin(SSD1306_SWITCHCAPVCC, 0x3c);
//设置显示字体大小
oled.setTextSize(1);
//设置显示字体颜色
oled.setTextColor(INVERSE);
}
void setup() {
Init_Oled(); //初始化
oled.clearDisplay(); //清屏
oled.drawBitmap(0,0,Img,128,64,1);
oled.display(); //显示
}
void loop() {
}
12、DHT11温湿度传感器使用
加载库:DHT sensor library
DHT dht11=DHT(DHT11_PIN,DHT22);//创建传感器对象 (引脚,传感器类型)
dht11.readTemperature(); 温度读取函数
dht11.readHumidity(); 湿度读取函数
案例:串口打印温湿度,传感器输入引脚为33
#include <DHT.h>
#define DHT11_PIN 33
//创建传感器对象
DHT dht11=DHT(DHT11_PIN,DHT22);
//温湿度显示函数
void Show_tAndh()
{
float t = dht11.readTemperature();
float h = dht11.readHumidity();
Serial.printf("温度:%.2f ^C 湿度:%.2f ^%",t,h);
Serial.println();
delay(2000);
}
void setup() {
//温湿度初始化
dht11.begin();
//串口初始化
Serial.begin(115200);
}
void loop() {
Show_tAndh();
}
13、HCSR04超声波传感器使用
加载库:HCSR04
//定义传感器对象
UltraSonicDistanceSensor distanceSensor(4,2);//4:接收引脚 2:发送引脚
distanceSensor.measureDistanceCm(); //距离读取函数
案例:测量传感器距离cm,4为接收引脚,2为发送引脚
#include <HCSR04.h>
//定义传感器对象
UltraSonicDistanceSensor distanceSensor(4,2);//4:接收引脚 2:发送引脚
void setup() {
//串口初始化
Serial.begin(115200);
}
void loop() {
float distance = distanceSensor.measureDistanceCm();
Serial.printf("距离:%.2fcm",distance);
Serial.println();
delay(1000);
}
14、SG90舵机使用
红:5v
黄:PWM
棕:GND
方法一:使用PWM信号控制舵机轴的位置
PWM信号的频率为50Hz (周期20ms)
脉宽为 0.5ms~2.5ms
0.5ms 0度
1ms 45度
1.5ms 90度
2ms 135度
2.5ms 180度
ledcSetup (通道,频率、精度)
ledcAttachPin (goio引脚,通道号)
ledcWrite (通道,占空比) ------>0度占空比:0.5 / 20 = x / 1023
案例:实现舵机0度到180度旋转
void setup() {
ledcSetup(1, 50, 10);
ledcAttachPin(4, 1);
}
void loop() {
ledcWrite(1,25);//0度
delay(2000);
ledcWrite(1,127);//180度
delay(2000);
}
方法二:使用舵机库
加载库:ESP32Servo
ESP32PWM::allocateTimer(1); //为舵机分配一个定时器 参数为个数
servo.setPeriodHertz(50); //设置舵机的周期为50HZ
servo.attach(4,500,2500); //参数4为引脚 设置舵机的最小脉冲宽度为500us 最大脉冲宽度为2500us
servo.write(pos);//设置舵机角度
案例:舵机从0度到180度,再从180到0度
#include <ESP32Servo.h>
Servo servo;//创建舵机对象
int pos = 0 ;//定义角度全局变量
void setup() {
ESP32PWM::allocateTimer(1); //为舵机分配一个定时器 参数为个数
servo.setPeriodHertz(50); //设置舵机的周期为50HZ
servo.attach(4,500,2500); //参数4为引脚 设置舵机的最小脉冲宽度为500us 最大脉冲宽度为2500us
}
void loop() {
for(pos = 0 ;pos <= 180;pos ++)
{
servo.write(pos);//设置舵机角度
delay(15);
}
for(pos = 180 ;pos >= 0;pos --)
{
servo.write(pos);
delay(15);
}
}
15、WIFI的使用
WIFI的AP模式
如:路由器,可以创建一个无线网络,让其他设备连接
WiFi.mode(WIFI_AP); //设置WiFi模式为AP模式
WiFi.softAP(ssid,password); //创建WiFi接入点
Serial.println(WiFi.softAPIP()); //获取AP的IP地址
Serial.println(WiFi.softAPmacAddress());// // 获取AP的MAC地址
WiFi.softAPdisconnect(true); //关闭WiFi
WiFi.softAPgetStationNum(); //获取WiFi连接数量
案例:连接一个名为esp32的wifi,密码为00000000
#include <WiFi.h>
#define LED 12
char *ssid = "esp32"; //WiFi名称
char *password = "00000000";//WiFi密码
int connect_num = 0;//WiFi接入设备数量
void setup(){
pinMode(LED, OUTPUT);
Serial.begin(115200);
WiFi.mode(WIFI_AP);//设置WiFi模式为AP模式
WiFi.softAP(ssid,password);//创建WiFi接入点
digitalWrite(LED, HIGH);
Serial.println("WiFi接入点创建成功!");
Serial.printf("WiFi名称:%s\r\n",WiFi.softAPSSID());
Serial.print("softAP的IP地址为:");
Serial.println(WiFi.softAPIP());
Serial.print("softAP的MAC地址为:");
Serial.println(WiFi.softAPmacAddress());
}
void loop(){
delay(30000);
connect_num = WiFi.softAPgetStationNum();
if(connect_num == 0){
WiFi.softAPdisconnect(true);//关闭WiFi
Serial.println("30秒没有设备连接,WiFi已经关闭!!!");
digitalWrite(LED,LOW);
}
else{
Serial.printf("当前连接设备数:%d 台 \r\n",connect_num);
}
}
WIFI的STA模式
特点:不可以让其他设备连接,只可以连接其他设备
WiFi.SSID(); //获取当前连接的WiFi网络名称
WiFi.RSSI(); //获取WiFi信号强度
WiFi.mode(WIFI_STA); //设置WiFi模式为STA模式
Scan_Useful_WiFi(); //扫描可用WiFi
WiFi.begin(); //连接WiFi
案例:连接一个wifi,获取B站粉丝数
#include <WiFi.h>
#include "HTTPClient.h"
#include "ArduinoJson.h"
char *ssid = "高会"; //WiFi名称
char *password = "15126067576";//WiFi密码
/*获取哔哩哔哩粉丝数量*/
void getFuns()
{
HTTPClient http;
http.begin("https://api.bilibili.com/x/relation/stat?vmid=692254175");
int httpCode = http.GET();
DynamicJsonDocument doc(1024);
if(httpCode > 0)
{
String payload = http.getString();
deserializeJson(doc,payload);
int follower = doc["data"]["follower"].as<int>();
String mid = doc["data"]["mid"].as<String>();
Serial.println("uid:"+mid);
Serial.printf("粉丝数量:%d 个\r\n",follower);
}
http.end();
}
/*扫描可用WiFi*/
void Scan_Useful_WiFi()
{
int num = WiFi.scanNetworks();
Serial.printf("扫描到 %d 个可用WiFi\r\n",num);
for(int i = 0;i < num ; i++)
{
Serial.print(WiFi.SSID(i));//获取当前连接的WiFi网络名称
Serial.printf("[%d] \r\n",WiFi.RSSI(i));//获取WiFi信号强度
}
}
void setup(){
Serial.begin(115200);
WiFi.mode(WIFI_STA);//设置WiFi模式为STA模式
Scan_Useful_WiFi();//扫描可以WiFi
WiFi.begin(ssid,password);//连接WiFi
Serial.printf("开始连接WiFi:%s",ssid);
while(WiFi.status() != WL_CONNECTED)//判断WiFi是否已经连接
{
Serial.print(".");
delay(200);
}
Serial.println();
Serial.println("WiFi连接成功!");
Serial.print("IP地址:");
Serial.println(WiFi.localIP());
Serial.print("网关:");
Serial.println(WiFi.gatewayIP());
Serial.print("子网掩码:");
Serial.println(WiFi.subnetMask());
Serial.print("DNS服务器:");
Serial.println(WiFi.dnsIP());
getFuns();//获取哔哩哔哩粉丝数量
}
void loop(){
}
16、json格式解析
加载库:ArduinoJson
HTTPClient http;//定义http客户端对象
http.begin("http://quan.suning.com/getSysTime.do");//发起http请求
http.GET();//获取http状态码,服务器响应正常为200
http.getString();//获取接口返回json格式数据
DynamicJsonDocument doc(1024);//将json数据解析为一个可操作对象
deserializeJson(doc,payload);//将payloas数据转化为可操作数据
案例:获取B站粉丝数和当前时间
#include <WiFi.h>
#include "HTTPClient.h"
#include "ArduinoJson.h"
char *ssid = "高会"; //WiFi名称
char *password = "15126067576";//WiFi密码
void getFuns();//获取哔哩哔哩粉丝和关注
void getCurrentTime();//获取当前时间
void connect_WiFi();//连接WiFi
void setup(){
Serial.begin(115200);//初始化串口
connect_WiFi();//连接WiFi
getCurrentTime();//获取当前时间
getFuns();//获取哔哩哔哩粉丝数量
}
void loop(){
}
/*获取哔哩哔哩粉丝数量*/
void getFuns()
{
HTTPClient http;
http.begin("https://api.bilibili.com/x/relation/stat?vmid=692254175");
/*
{
"code": 0,
"message": "0",
"ttl": 1,
"data": {
"mid": 692254175,
"following": 18,
"whisper": 0,
"black": 0,
"follower": 9
}
}
*/
int httpCode = http.GET();
DynamicJsonDocument doc(1024);
if(httpCode > 0)
{
String payload = http.getString();
deserializeJson(doc,payload);
int follower = doc["data"]["follower"].as<int>();
String mid = doc["data"]["mid"].as<String>();
Serial.println("uid:"+mid);
Serial.printf("粉丝数量:%d 个\r\n",follower);
}
http.end();
}
/*扫描可用WiFi*/
void Scan_Useful_WiFi()
{
int num = WiFi.scanNetworks();
Serial.printf("扫描到 %d 个可用WiFi\r\n",num);
for(int i = 0;i < num ; i++)
{
Serial.print(WiFi.SSID(i));//获取当前连接的WiFi网络名称
Serial.printf("[%d] \r\n",WiFi.RSSI(i));//获取WiFi信号强度
}
}
/*连接WiFi*/
void connect_WiFi()
{
WiFi.mode(WIFI_STA);//设置WiFi模式为STA模式
Scan_Useful_WiFi();//扫描可用WiFi
WiFi.begin(ssid,password);//连接WiFi
Serial.printf("开始连接WiFi:%s",ssid);
while(WiFi.status() != WL_CONNECTED)//判断WiFi是否已经连接
{
Serial.print(".");
delay(200);
}
}
/*获取当前时间*/
void getCurrentTime()
{
HTTPClient http;//定义http客户端对象
http.begin("http://quan.suning.com/getSysTime.do");//发起http请求
/*
{"sysTime2":"2024-08-27 22:44:07","sysTime1":"20240827224407"}
*/
int httpCode = http.GET();//获取http状态码
DynamicJsonDocument doc(1024);//将json数据解析为一个可操作对象
if(httpCode == 200)//服务器响应正常为200
{
String payload = http.getString();//获取接口返回json格式数据
deserializeJson(doc,payload);
String time = doc["sysTime2"].as<String>();
Serial.print("当前时间:");
Serial.println(time);
}
http.end();
}
17、MQTT
加载库:PubSubClient
//WIFI 连接库和MQTT客户端
#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include <DallasTemperature.h>
#include "DHTesp.h" //引入DHTesp头文件,为下面调用函数做准备。
// WiFi 账号密码
const char *ssid = "TEST"; // Wifi 账号
const char *password = "12345678"; // wifi 密码
// MQTT Broker 服务端连接
const char *mqtt_broker = "esp.icce.top";//mqtt服务器地址
const char *topic_subscribe = "ESP32PI/DRIVER";//主题
const char *topic_publish = "ESP32PI/SENSOR";//主题
const char *mqtt_username = "esp32test2";
const char *mqtt_password = "test123";
const int mqtt_port = 1883;//端口
//客户端变量
WiFiClient espClient;
PubSubClient client(espClient);
//引脚绑定
#define MQ2PIN 32
#define LIGHTSENSORPIN 34 //Ambient light sensor reading
#define FANPIN 26
#define LIGHTPIN 25
#define DHTPIN 33
DHTesp dhtSensor; //定义一个DHT传感器
const int DHT22_PIN = DHTPIN; //定义一个整形变量,目的是使用GPIO-32来接收来自传感器的数据
int curtain_state=0;
void setup() {
analogReadResolution(12);
pinMode(LIGHTSENSORPIN, INPUT);
pinMode(MQ2PIN, INPUT);
dhtSensor.setup(DHT22_PIN, DHTesp::DHT22);//把DHT11与gpio第32号数字引脚关联。
//软串口波特率
Serial.begin(115200);
pinMode(FANPIN,OUTPUT);
digitalWrite(FANPIN,HIGH);
pinMode(LIGHTPIN,OUTPUT);
digitalWrite(LIGHTPIN,HIGH);
// connecting to a WiFi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(2000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker 连接服务端
client.setServer(mqtt_broker, mqtt_port);
client.setCallback(callback);//回调
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());//返回连接状态
delay(2000);
}
}
// publish and subscribe
client.subscribe(topic_subscribe);
}
// The callback for when a PUBLISH message is received from the server.
void callback(const char* topic, byte* payload, unsigned int length) {
Serial.println("On message....");
char json[length + 1];
strncpy (json, (char*)payload, length);
json[length] = '\0';
Serial.print("Topic: ");
Serial.println(topic);
Serial.print("Message: ");
Serial.println(json);
StaticJsonBuffer<200> jsonBuffer;
JsonObject& data = jsonBuffer.parseObject((char*)json);
if (!data.success())
{
Serial.println("parseObject() failed");
return;
}
// Check request method
String state_light= String((const char*)data["LIGHT"]);
String state_fan=String((const char*)data["FAN"]);
String state_curtain=String((const char*)data["CURTAIN"]);
Serial.println(state_light);
if(state_light=="ON"){
Serial.println("light on");
digitalWrite(LIGHTPIN,LOW);
}
else if(state_light=="OFF"){
Serial.println("light off");
digitalWrite(LIGHTPIN,HIGH);
}
if(state_fan=="ON"){
Serial.println("fan on");
digitalWrite(FANPIN,LOW);
}
else if(state_fan=="OFF"){
Serial.println("fan off");
digitalWrite(FANPIN,HIGH);
}
if(state_curtain=="ON"){
Serial.println("curtain on");
curtain_state=1;
}
else if(state_curtain=="OFF"){
Serial.println("curtain off");
curtain_state=0;
}
}
void loop() {
if ( !client.connected() ) {
reconnect();
}
client.publish(topic_publish, public_messages().c_str());
delay(200);
client.loop();//循环
}
//发布消息
String public_messages() {
TempAndHumidity dhtdata = dhtSensor.getTempAndHumidity();//接受来自传感器的温度湿度数据,存入data变量
static int flag=0;
static int progress=0;
static int time_int=0;
// Prepare gpios JSON payload string
StaticJsonBuffer<256> jsonBuffer;
JsonObject& data = jsonBuffer.createObject();
if(time_int==5){
time_int=0;
data["TEMPERATURE"] = String(dhtdata.temperature,1);//℃
data["HUMIDITY"] = String(dhtdata.humidity,1);//℃
data["LIGHT_INTENSITY"] = String(analogRead(LIGHTSENSORPIN)/4096.0*1000.0,1); //Read light level
data["SMOKE"] = String(analogRead(MQ2PIN)/4096.0*10000,2);
}else
time_int+=1;
//步进电机圈数
if(curtain_state==0&&progress!=0){
progress-=1;
}
if(curtain_state==1&&progress!=10){
progress+=1;
}
data["CURATIN_PROGRESS"] = String(progress*10);
char payload[256];
data.printTo(payload, sizeof(payload));
String strPayload = String(payload);
Serial.print("publish message: ");
Serial.println(strPayload);
return strPayload;
}
void reconnect() {
// Loop until we're reconnected
while(!client.connected()) {
String client_id = "esp32-client";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
Serial.println("Public emqx mqtt broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());//返回连接状态
delay(1000);
}
}
client.subscribe(topic_subscribe);
}