2021年12月31日 星期五

ESP32 Web Server with Slider & MQTT : Control LED Brightness (PWM)

 ESP32 Web Server with Slider & MQTT  : Control LED Brightness (PWM)









// Import required libraries

#include <WiFi.h>

#include <AsyncTCP.h>

#include <ESPAsyncWebServer.h>

//================MQTT=====================

#include <PubSubClient.h>  //MQTT


// Replace with your network credentials

//const char* ssid = "REPLACE_WITH_YOUR_SSID";

//const char* password = "REPLACE_WITH_YOUR_PASSWORD";

const char* ssid     = "TOTOLINK_A3002MU";

const char* password = "24063173";


//================MQTT=====================

const char* mqtt_server = "broker.mqtt-dashboard.com" ; //MQTT


// Set web server port number to 80

const int output = 2;


String sliderValue = "0";


// setting PWM properties

const int freq = 5000;

const int ledChannel = 0;

const int resolution = 8;


const char* PARAM_INPUT = "value";


// Create AsyncWebServer object on port 80

AsyncWebServer server(80);


//================MQTT=====================

WiFiClient espClient;

PubSubClient client(espClient);

long lastMsg = 0;

char msg[50];


//======================================================

const char index_html[] PROGMEM = R"rawliteral(

<!DOCTYPE HTML><html>

<head>

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <title>ESP Web Server</title>

  <style>

    html {font-family: Arial; display: inline-block; text-align: center;}

    h2 {font-size: 2.3rem;}

    p {font-size: 1.9rem;}

    body {max-width: 400px; margin:0px auto; padding-bottom: 25px;}

    .slider { -webkit-appearance: none; margin: 14px; width: 360px; height: 25px; background: #FFD65C;

      outline: none; -webkit-transition: .2s; transition: opacity .2s;}

    .slider::-webkit-slider-thumb {-webkit-appearance: none; appearance: none; width: 35px; height: 35px; background: #003249; cursor: pointer;}

    .slider::-moz-range-thumb { width: 35px; height: 35px; background: #003249; cursor: pointer; } 

  </style>

</head>

<body>

  <h2>ESP Web Server</h2>

  <p><span id="textSliderValue">%SLIDERVALUE%</span></p>

  <p><input type="range" onchange="updateSliderPWM(this)" id="pwmSlider" min="0" max="255" value="%SLIDERVALUE%" step="1" class="slider"></p>

<script>

function updateSliderPWM(element) {

  var sliderValue = document.getElementById("pwmSlider").value;

  document.getElementById("textSliderValue").innerHTML = sliderValue;

  console.log(sliderValue);

  var xhr = new XMLHttpRequest();

  xhr.open("GET", "/slider?value="+sliderValue, true);

  xhr.send();

}

</script>

</body>

</html>

)rawliteral";


//======================================================

// Replaces placeholder with button section in your web page

String processor(const String& var){

  //Serial.println(var);

  if (var == "SLIDERVALUE"){

    return sliderValue;

  }

  return String();

}



//================MQTT=====================

void callback(char* topic, byte* message, unsigned int length) {

  Serial.print("Message arrived on topic: ");

  Serial.print(topic);

  Serial.print(". Message: ");

  String messageTemp;

  

  for (int i = 0; i < length; i++) {

    Serial.print((char)message[i]);

    messageTemp += (char)message[i];

  }

  Serial.println();


  // Feel free to add more if statements to control more GPIOs with MQTT


  // If a message is received on the topic esp32/output, you check if the message is either "on" or "off". 

  // Changes the output state according to the message

  if (String(topic) == "alex9ufo/esp32/slider/input") {

    Serial.print("Changing output to ");

    

    sliderValue = messageTemp;

    ledcWrite(ledChannel, sliderValue.toInt());

    }


    loop_mqtt();

 }

//================MQTT=====================


void reconnect() {

  // Loop until we're reconnected

  while (!client.connected()) {

    Serial.print("Attempting MQTT connection...");

    // Attempt to connect

    if (client.connect("ESP32Client")) {

      Serial.println("connected");

      // Subscribe

      client.subscribe("alex9ufo/esp32/slider/input");

    } else {

      Serial.print("failed, rc=");

      Serial.print(client.state());

      Serial.println(" try again in 5 seconds");

      // Wait 5 seconds before retrying

      delay(5000);

    }

  }

}

//================MQTT===================== 

void loop_mqtt(){

  if (!client.connected()) {

    reconnect();

  }

  client.loop();

  long now = millis();

  if (now - lastMsg > 5000) {

    lastMsg = now;

  }  

}

   

//=========================================


void setup(){

  // Serial port for debugging purposes

  Serial.begin(115200);

  

  // configure LED PWM functionalitites

  ledcSetup(ledChannel, freq, resolution);

  

  // attach the channel to the GPIO to be controlled

  ledcAttachPin(output, ledChannel);

  

  ledcWrite(ledChannel, sliderValue.toInt());


  // Connect to Wi-Fi

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {

    delay(1000);

    Serial.println("Connecting to WiFi..");

  }


  // Print ESP Local IP Address

  Serial.println(WiFi.localIP());


  // Route for root / web page

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){

    request->send_P(200, "text/html", index_html, processor);

  });


  // Send a GET request to <ESP_IP>/slider?value=<inputMessage>

  server.on("/slider", HTTP_GET, [] (AsyncWebServerRequest *request) {

    String inputMessage;

    // GET input1 value on <ESP_IP>/slider?value=<inputMessage>

    if (request->hasParam(PARAM_INPUT)) {

      inputMessage = request->getParam(PARAM_INPUT)->value();

      sliderValue = inputMessage;

      ledcWrite(ledChannel, sliderValue.toInt());

    }

    else {

      inputMessage = "No message sent";

    }

    Serial.println(inputMessage);

    request->send(200, "text/plain", "OK");

  });

  

  // Start server

  server.begin();


    

  //================MQTT===================== 

  client.setServer(mqtt_server, 1883);

  client.setCallback(callback);

}

  

void loop() {

  loop_mqtt();

}




[{"id":"b3e673b9a2a27073","type":"ui_slider","z":"9459afd070c7170a","name":"","label":"slider","tooltip":"","group":"fc89dc38.347898","order":34,"width":"16","height":"6","passthru":true,"outs":"end","topic":"topic","topicType":"msg","min":0,"max":"255","step":1,"className":"","x":290,"y":100,"wires":[["5c189735a713b0b4"]]},{"id":"5c189735a713b0b4","type":"mqtt out","z":"9459afd070c7170a","name":"","topic":"alex9ufo/esp32/slider/input","qos":"1","retain":"","respTopic":"","contentType":"","userProps":"","correl":"","expiry":"","broker":"3d43a51a.c133a2","x":540,"y":100,"wires":[]},{"id":"fc89dc38.347898","type":"ui_group","name":"LED show","tab":"ec4c23e9246d7836","order":1,"disp":true,"width":16,"collapse":false,"className":""},{"id":"3d43a51a.c133a2","type":"mqtt-broker","name":"broker.mqtt-dashboard.com","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"protocolVersion":"4","keepalive":"60","cleansession":true,"birthTopic":"","birthQos":"0","birthRetain":"false","birthPayload":"","birthMsg":{},"closeTopic":"","closePayload":"","closeMsg":{},"willTopic":"","willQos":"0","willRetain":"false","willPayload":"","willMsg":{},"sessionExpiry":""},{"id":"ec4c23e9246d7836","type":"ui_tab","name":"Home","icon":"dashboard","disabled":false,"hidden":false}]

沒有留言:

張貼留言

WOKWI LED + MQTT Node-Red SQLite

WOKWI LED + MQTT Node-Red SQLite const char *mqtt_broker = "broker.mqtt-dashboard.com" ; const char *topic1 = "alex9ufo/e...