Arduino 开发环境对 ESP32 和 ESP8266 提供了丰富的支持,是物联网开发的绝佳选择。
这两款芯片由乐鑫( Espressif Systems )开发,功能强大且性价比高,适合从简单的物联网项目到复杂的边缘计算应用。以下是开发 ESP32/ESP8266 系列的基本步骤和关键知识点( Arduino C/C++ 编程基础需要读者自行学习,也可以在后续的项目代码中边用边学)。
从 Arduino 官方网站 下载并安装 Arduino IDE。
更多内容可见:
看不到端口的情况:
- USB 数据线有问题,或者是用的 USB 充电线。
- 带串口芯片的开发板未安装对应驱动程序,例如: Windows 下 CH340 串口驱动,可前往南京沁恒微官网 https://www.wch.cn 搜索 CH340,选择 CH341SER.EXE(适用 CH340)下载安装。
- 部分开发板 USB CDC 设置参考文章: http://www.demo1984s.com/articles/2018/10/28/1540718942344.html
ESP8266 Blink 示例
1void setup() {
2 pinMode(LED_BUILTIN, OUTPUT); // 初始化板载 LED
3}
4
5void loop() {
6 digitalWrite(LED_BUILTIN, HIGH); // 打开 LED
7 delay(1000); // 延时 1 秒
8 digitalWrite(LED_BUILTIN, LOW); // 关闭 LED
9 delay(1000);
10}
ESP32 Blink 示例
1void setup() {
2 pinMode(2, OUTPUT); // GPIO 2 通常连接到板载 LED
3}
4
5void loop() {
6 digitalWrite(2, HIGH); // 打开 LED
7 delay(1000); // 延时 1 秒
8 digitalWrite(2, LOW); // 关闭 LED
9 delay(1000);
10}
连接 Wi-Fi
1#include <WiFi.h> // ESP32
2// #include <ESP8266WiFi.h> // ESP8266
3
4const char* ssid = "你的WiFi名称";
5const char* password = "你的WiFi密码";
6
7void setup() {
8 Serial.begin(115200);
9 WiFi.begin(ssid, password);
10
11 while (WiFi.status() != WL_CONNECTED) {
12 delay(1000);
13 Serial.println("正在连接 WiFi...");
14 }
15
16 Serial.println("WiFi 已连接");
17 Serial.println(WiFi.localIP()); // 打印 IP 地址
18}
19
20void loop() {}
创建简单的 Web 服务器
1#include <WiFi.h> // ESP32
2// #include <ESP8266WiFi.h> // ESP8266
3#include <WebServer.h> // Web 服务器库
4
5const char* ssid = "你的WiFi名称";
6const char* password = "你的WiFi密码";
7
8WebServer server(80); // 在 80 端口启动服务器
9
10void handleRoot() {
11 server.send(200, "text/plain", "Hello, World!"); // 发送响应
12}
13
14void setup() {
15 Serial.begin(115200);
16 WiFi.begin(ssid, password);
17
18 while (WiFi.status() != WL_CONNECTED) {
19 delay(1000);
20 Serial.println("正在连接 WiFi...");
21 }
22
23 Serial.println("WiFi 已连接");
24 Serial.println(WiFi.localIP()); // 打印 IP 地址
25
26 server.on("/", handleRoot); // 绑定路由
27 server.begin(); // 启动服务器
28 Serial.println("Web 服务器已启动");
29}
30
31void loop() {
32 server.handleClient(); // 处理客户端请求
33}