Tutorial, Pendidikan, Media Pembelajaran, Ilmu Pengetahuan.

Tuesday, October 22, 2024

Belajar IoT-005- edit teks LCD 16x2 IoT via browser dengan protokol MQTT

 Pada proyek Iot Kali ini, kita akan membuat projet dengan menggunakan LCD 16x2 yang tulisannya bisa dirubah via Browser, dan bisa diganti tulisannya secara jarak jauh. Dengan membuat ini, kita bisa membuat Pager (heheh.... yang kelahiran 80an pasti kenal apa itu Pager).dengan esp 8266+LCD 16x32.

langkah pertama rangkaian LCD 16x2 dengan esp 8266 seperti gambar berikut.


Kemudian buatlah file html, yang berfungsi sebagai dashboard, untuk mengirim teks ke LCD 16x2

berikut kode HTML nya :

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Data Sensor</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <!-- Label "Terhubung" -->
  <div class="status">
    <p id="status">Terputus</p>
  </div>

      <!-- Card baru untuk mengirim teks ke LCD -->
       <p>======</p>
     
    <div class="card">
      <h2>Kirim Teks ke LCD</h2>
      <input type="text" id="lcd-text" placeholder="Masukkan teks"/>
      <button id="send-btn" onclick="sendLCD()">Kirim</button>
    </div>
  </div>

</body>

<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
    <script>
        const clientId = Math.random().toString(16).substr(2, 8);
        const host = 'wss://broker.emqx.io:8084/mqtt';

        const options = {
          keepalive: 30,
          clientId: clientId,
          protocolId: 'MQTT',
          protocolVersion: 4,
          clean: true,
          reconnectPeriod: 1000,
          connectTimeout: 30 * 1000
        }

        console.log("Menghubungkan ke Broker");
        const client = mqtt.connect(host, options);

        client.on('connect', () => {
          console.log('Terhubung ke broker:' + clientId)
          client.subscribe('rokhmad.com/#', { qos: 1 })
          document.getElementById("status").innerHTML = "Terhubung";
        })

        client.on('message', (topic, message, packet) => {
       
          if(topic === "rokhmad.com/lcd"){
            document.getElementById("lcd-text").value = message;
          }        
           
        })

       
        function sendLCD(){
          var valueLCD = document.getElementById("lcd-text").value;
          client.publish("rokhmad.com/lcd", valueLCD, {qos: 1, retain: true});
        }
    </script>
</html>


kemudian kode HTML tersebut jika dijalankan di browser maka hasilnya sebagai berikut :



Ketika kita klik tombol kirim, jika kita cek di aplikasi MQTTX maka akan tampil sebagai berikut (BELUM TAHU APA ITU MQTT ?? KUNJUNGI Postingan saya disini : https://www.rokhmad.com/2024/10/belajar-iot-001-mengenal-komunikasi.html)

MQTT dengan topic : rokhmad.com/lcd
pesan yang dikirim : mardiyatun makan


kemudian pesan yang masuk di MQTT, akan dipanggil oleh esp8266 dengan menggunakan sketch :


#include <ESP8266WiFi.h>
#include <PubSubClient.h>

//////////////////
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 16, 2);
//atau 0x3F
// WiFi settings
const char *ssid = "R.MEETING";             // Replace with your WiFi name
const char *password = "smktwosra123";    // Replace with your WiFi password

// MQTT Broker settings
const char *mqtt_broker = "broker.emqx.io";  // EMQX broker endpoint
const char *mqtt_topic = "rokhmad.com/#";     // MQTT topic
const char *mqtt_username = "emqx";  // MQTT username for authentication
const char *mqtt_password = "public";  // MQTT password for authentication
const int mqtt_port = 1883;  // MQTT port (TCP)

WiFiClient espClient;
PubSubClient mqtt_client(espClient);
void connectToWiFi();
void connectToMQTTBroker();
void mqttCallback(char *topic, byte *payload, unsigned int length);

void setup() {
  lcd.init();
  // Turn on the blacklight and print a message.
  lcd.backlight();
  Serial.begin(115200);
  connectToWiFi();
  mqtt_client.setServer(mqtt_broker, mqtt_port);
  mqtt_client.setCallback(mqttCallback);
  connectToMQTTBroker();
}

void connectToWiFi() {
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nConnected to the WiFi network");
}

void connectToMQTTBroker() {
  while (!mqtt_client.connected()) {
    String client_id = "esp8266-client-" + String(WiFi.macAddress());
    Serial.printf("Connecting to MQTT Broker as %s.....\n", client_id.c_str());
    if (mqtt_client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
      Serial.println("Connected to MQTT broker");
      mqtt_client.subscribe(mqtt_topic);
      // Publish message upon successful connection
    } else {
      Serial.print("Failed to connect to MQTT broker, rc=");
      Serial.print(mqtt_client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void mqttCallback(char *topic, byte *payload, unsigned int length) {
  Serial.print("Message received on topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  String message;
  for (int i = 0; i < length; i++) {
    message += (char) payload[i];  // Convert *byte to string
  }
 if (String (topic) == "rokhmad.com/lcd") {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("---twosra IoT---");
    lcd.setCursor(0, 1);
    lcd.print(message);
  }
  Serial.println(message);
  Serial.println();
  Serial.println("-----------------------");
}
void loop() {
  if (!mqtt_client.connected()) {
    connectToMQTTBroker();
  }
  mqtt_client.loop();
}


Akhirnya dan hasilnya seperti berikut ini :







Share:

0 comments:

About me

About me
Tentang Saya

www.rokhmad.com

Blog edukasi Tutorial, Pendidikan, Media Pembelajaran, Ilmu Pengetahuan.

toko Online

SKETCH JWSD ESP

VIDEO PERAKITAN JWSD WIFI

Unduh Library Project jws 1000m

kumpulan sketch JWSD 1000 M

kumpulan sketch JWSD 1000 M
kumpulan sketch JWSD 1000 M

Kumpulan Sketch JWSD

JWSD 2 Panel Full Bluetooth

JWSD 2 Panel Full Bluetooth
JWSD 2 Panel Bluetooth

JWSD 3 panel Bluetooth

JWSD 3 panel Bluetooth
JWSD 3 panel Bluetooth

Sketch JWS 4 Panel, Bluetooth Kontrolled

Sketch JWS 4 Panel, Bluetooth Kontrolled
JWSD- 2019 NEW ! !

Sketch Jam Sholat 1 Panel

Sketch Jam Sholat 1 Panel
Jam sholat 1 Panel

Sketch Jam Sholat 2 Panel

Sketch Jam Sholat 2 Panel
Jam dua panel

Sketch Jam Sholat 3 Panel

Sketch Jam Sholat 3 Panel
Sketch Jam Sholat 3 Panel

Sketch Jam Sholat 5 Panel

Sketch Jam Sholat 5 Panel
Jam Sholat 5 Panel

Toko Kami

Daftar isi

Blog Archive

Tryout UNBK

e-learning

e-learning
Belajar mudah, dimana saja

my Edmodo

Buku Digital

Buku Tamu

Komentar Terkini

Live Traffic

Donasi

Donasi
Donasi

Total Pengunjung