ESP8266-Arduino网络编程实例-Web页面调节LED(基于PWM) Web页面调节LED(基于PWM) 本实例将演示如何通过Web页面的Slider来调节LED亮度。LED的亮度通过PWM控制。
在前面的文章中,对PWM使用做了详细的介绍,请参考:
在前面的文章中,介绍如何实现一个异步Web服务器:
在前面的文章中,介绍如何将Web页面文件储存到SPIFFS和LittleFS中:
我们将在实例中创建三个Slider来控制三个LED的亮度,控制逻辑如下:
Web页面数据通信通过WebSocket协议实现。关于WebSocket协议使用,请参考前面文章:
1、硬件准备
ESP8266 NodeMCU开发板一块
数据线一条
硬件接线如下:
2、软件准备
Arduino IDE或VSCode + PlatformIO
在前面的文章中,对如何搭建ESP8266开发环境做了详细的介绍,请参考:
ESP8266 NodeMCU的引脚介绍在前面的文章中做了详细的介绍,请参考:
3、代码实现 1)Web页面代码实现(index.html)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 <!DOCTYPE html> <html> <head> <title>ESP IOT DASHBOARD</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--<link rel="icon" type="image/png" href="favicon.png"> --> <link rel="stylesheet" type="text/css" href="/style.css"> </head> <body> <div class="topnav"> <h1>Multiple Sliders</h1> </div> <div class="content"> <div class="card-grid"> <div class="card"> <p class="card-title">Fader 1</p> <p class="switch"> <input type="range" onchange="updateSliderPWM(this)" id="slider1" min="0" max="100" step="1" value ="0" class="slider"> </p> <p class="state">Brightness: <span id="sliderValue1"></span> %</p> </div> <div class="card"> <p class="card-title"> Fader 2</p> <p class="switch"> <input type="range" onchange="updateSliderPWM(this)" id="slider2" min="0" max="100" step="1" value ="0" class="slider"> </p> <p class="state">Brightness: <span id="sliderValue2"></span> %</p> </div> <div class="card"> <p class="card-title"> Fader 3</p> <p class="switch"> <input type="range" onchange="updateSliderPWM(this)" id="slider3" min="0" max="100" step="1" value ="0" class="slider"> </p> <p class="state">Brightness: <span id="sliderValue3"></span> %</p> </div> </div> </div> <script src="script.js"></script> </body> </html>
2)Web页面样式代码实现(style.css)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 html { font-family: Arial, Helvetica, sans-serif; display: inline-block; text-align: center; } h1 { font-size: 1.8rem; color: white; } p { font-size: 1.4rem; } .topnav { overflow: hidden; background-color: #0A1128; } body { margin: 0; } .content { padding: 30px; } .card-grid { max-width: 700px; margin: 0 auto; display: grid; grid-gap: 2rem; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); } .card { background-color: white; box-shadow: 2px 2px 12px 1px rgba(140,140,140,.5); } .card-title { font-size: 1.2rem; font-weight: bold; color: #034078 } .state { font-size: 1.2rem; color:#1282A2; } .slider { -webkit-appearance: none; margin: 0 auto; width: 100%; height: 15px; border-radius: 10px; background: #FFD65C; outline: none; } .slider::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 30px; height: 30px; border-radius: 50%; background: #034078; cursor: pointer; } .slider::-moz-range-thumb { width: 30px; height: 30px; border-radius: 50% ; background: #034078; cursor: pointer; } .switch { padding-left: 5%; padding-right: 5%; }
3)Web页面控制逻辑实现(script.js)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 var gateway = `ws://${window.location.hostname}/ws`; var websocket; window.addEventListener('load', onload); function onload(event) { initWebSocket(); } function getValues(){ websocket.send("getValues"); } function initWebSocket() { console.log('Trying to open a WebSocket connection…'); websocket = new WebSocket(gateway); websocket.onopen = onOpen; websocket.onclose = onClose; websocket.onmessage = onMessage; } function onOpen(event) { console.log('Connection opened'); getValues(); } function onClose(event) { console.log('Connection closed'); setTimeout(initWebSocket, 2000); } function updateSliderPWM(element) { var sliderNumber = element.id.charAt(element.id.length-1); var sliderValue = document.getElementById(element.id).value; document.getElementById("sliderValue"+sliderNumber).innerHTML = sliderValue; console.log(sliderValue); websocket.send(sliderNumber+"s"+sliderValue.toString()); } function onMessage(event) { console.log(event.data); var myObj = JSON.parse(event.data); var keys = Object.keys(myObj); for (var i = 0; i < keys.length; i++){ var key = keys[i]; document.getElementById(key).innerHTML = myObj[key]; document.getElementById("slider"+ (i+1).toString()).value = myObj[key]; } }
页面运行逻辑如下:
4)ESP8266驱动代码实现
驱动使用到如下开源库:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 #include <Arduino.h> #include <ESP8266WiFi.h> #include <ESPAsyncTCP.h> #include <ESPAsyncWebServer.h> #include "LittleFS.h" #include <Arduino_JSON.h> const char* ssid = "*****"; const char* ssid_pwd = "****"; // Create AsyncWebServer object on port 80 AsyncWebServer server(80); // Create a WebSocket object AsyncWebSocket ws("/ws"); // Set LED GPIO const int ledPin1 = 2; const int ledPin2 = 12; const int ledPin3 = 13; String message = ""; String sliderValue1 = "0"; String sliderValue2 = "0"; String sliderValue3 = "0"; int dutyCycle1; int dutyCycle2; int dutyCycle3; //Json Variable to Hold Slider Values JSONVar sliderValues; //Get Slider Values String getSliderValues(){ sliderValues["sliderValue1"] = String(sliderValue1); sliderValues["sliderValue2"] = String(sliderValue2); sliderValues["sliderValue3"] = String(sliderValue3); String jsonString = JSON.stringify(sliderValues); return jsonString; } // Initialize LittleFS void initFS() { if (!LittleFS.begin()) { Serial.println("An error has occurred while mounting LittleFS"); } else{ Serial.println("LittleFS mounted successfully"); } } // Initialize WiFi void initWiFi() { WiFi.mode(WIFI_STA); WiFi.begin(ssid, ssid_pwd); Serial.print("Connecting to WiFi .."); while (WiFi.status() != WL_CONNECTED) { Serial.print('.'); delay(1000); } Serial.println(WiFi.localIP()); } void notifyClients(String sliderValues) { ws.textAll(sliderValues); } void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) { AwsFrameInfo *info = (AwsFrameInfo*)arg; if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) { data[len] = 0; message = (char*)data; if (message.indexOf("1s") >= 0) { sliderValue1 = message.substring(2); dutyCycle1 = map(sliderValue1.toInt(), 0, 100, 0, 1023); Serial.println(dutyCycle1); Serial.print(getSliderValues()); notifyClients(getSliderValues()); } if (message.indexOf("2s") >= 0) { sliderValue2 = message.substring(2); dutyCycle2 = map(sliderValue2.toInt(), 0, 100, 0, 1023); Serial.println(dutyCycle2); Serial.print(getSliderValues()); notifyClients(getSliderValues()); } if (message.indexOf("3s") >= 0) { sliderValue3 = message.substring(2); dutyCycle3 = map(sliderValue3.toInt(), 0, 100, 0, 1023); Serial.println(dutyCycle3); Serial.print(getSliderValues()); notifyClients(getSliderValues()); } if (strcmp((char*)data, "getValues") == 0) { notifyClients(getSliderValues()); } } } void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { switch (type) { case WS_EVT_CONNECT: Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str()); break; case WS_EVT_DISCONNECT: Serial.printf("WebSocket client #%u disconnected\n", client->id()); break; case WS_EVT_DATA: handleWebSocketMessage(arg, data, len); break; case WS_EVT_PONG: case WS_EVT_ERROR: break; } } void initWebSocket() { ws.onEvent(onEvent); server.addHandler(&ws); } void setup() { Serial.begin(115200); pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); pinMode(ledPin3, OUTPUT); initFS(); initWiFi(); initWebSocket(); // Web Server Root URL server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){ request->send(LittleFS, "/index.html", "text/html"); }); server.serveStatic("/", LittleFS, "/"); // Start server server.begin(); } void loop() { analogWrite(ledPin1, dutyCycle1); analogWrite(ledPin2, dutyCycle2); analogWrite(ledPin3, dutyCycle3); ws.cleanupClients(); }
运行结果如下:
文章来源: https://iotsmart.blog.csdn.net/article/details/127460347
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!