Sabtu, 14 Juni 2025

Mengontrol NodeMCU ESP8266 menggunakan webserver atau hosting (seperti hosting berbasis PHP/MySQL atau layanan cloud)

 

1. Konsep Kerja

  • NodeMCU mengakses skrip PHP di hosting/server untuk membaca/mengupdate status saklar.

  • Database (MySQL/Firebase) menyimpan status ON/OFF.

  • Antarmuka web (HTML/JS) digunakan untuk kontrol dari browser.


2. Alat & Komponen yang Dibutuhkan

✅ NodeMCU ESP8266
✅ Relay module
✅ Koneksi internet (WiFi)
✅ Hosting/web server (misal: 000webhost, InfinityFree, atau VPS)
✅ Database (MySQL atau Firebase)


3. Setup Database & Hosting

A. Jika Menggunakan MySQL (PHP + MySQL)

  1. Buat database di hosting (misal: db_switch).

  2. Buat tabel:

    sql

    CREATE TABLE `tb_switch` (
      `id` INT AUTO_INCREMENT PRIMARY KEY,
      `status` INT(1) DEFAULT 0
    );
  3. Masukkan data awal:

    sql

    INSERT INTO `tb_switch` (`status`) VALUES (0);

B. Buat Skrip PHP untuk API

Buat file api.php di hosting:

php

<?php
header('Content-Type: application/json');

// Koneksi database
$host = "localhost";
$user = "username_db";
$pass = "password_db";
$db   = "db_switch";
$conn = new mysqli($host, $user, $pass, $db);

// Ambil data dari GET/POST
$action = $_GET['action'];

if ($action == "get") {
    $result = $conn->query("SELECT status FROM tb_switch WHERE id=1");
    $row = $result->fetch_assoc();
    echo json_encode(["status" => $row['status']]);
} 
else if ($action == "set") {
    $status = $_GET['status'];
    $conn->query("UPDATE tb_switch SET status=$status WHERE id=1");
    echo json_encode(["success" => true]);
}
?>

4. Program NodeMCU (HTTP Request ke Server)

cpp

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

const char* ssid = "WIFI_SSID";
const char* password = "WIFI_PASSWORD";
const char* serverUrl = "http://yourwebsite.com/api.php";

const int relayPin = D1;  // GPIO5

void setup() {
  Serial.begin(115200);
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, LOW);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
}

void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    
    // Ambil status dari server
    http.begin(serverUrl + String("?action=get"));
    int httpCode = http.GET();
    
    if (httpCode == 200) {
      String payload = http.getString();
      int status = payload.substring(12,13).toInt(); // Ambil nilai "status"
      digitalWrite(relayPin, status ? HIGH : LOW);
    }
    http.end();
    
    delay(1000);  // Update setiap 1 detik
  }
}

5. Buat Antarmuka Web untuk Kontrol

Buat file index.html di hosting:

html

<!DOCTYPE html>
<html>
<head>
    <title>Kontrol Saklar Online</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h1>Saklar NodeMCU</h1>
    <button id="btn-on">ON</button>
    <button id="btn-off">OFF</button>

    <script>
        $("#btn-on").click(function() {
            $.get("api.php?action=set&status=1", function(data) {
                alert("Saklar ON");
            });
        });

        $("#btn-off").click(function() {
            $.get("api.php?action=set&status=0", function(data) {
                alert("Saklar OFF");
            });
        });
    </script>
</body>
</html>

6. Cara Kerja Sistem

  1. NodeMCU melakukan HTTP GET ke api.php?action=get untuk memeriksa status relay.

  2. Website mengirim perintah api.php?action=set&status=1/0 untuk mengubah status.

  3. Database menyimpan status terakhir.

  4. Relay menyala/mati sesuai perintah.


7. Kelebihan Solusi Ini

✔ Bisa diakses dari mana saja via browser.
✔ Tidak perlu app khusus (cukup pakai HTML/JS).
✔ Bisa dipasang di hosting gratis (000webhost, InfinityFree).
✔ Bisa dikembangkan untuk multi-device.


8. Catatan Penting

  • Pastikan hosting mendukung PHP & MySQL.

  • Jika pakai Firebase, ganti api.php dengan Firebase Realtime DB.

  • Untuk keamanan, tambahkan password di API.

Dengan ini, Anda bisa membuat saklar ON/OFF NodeMCU online via website!

Tidak ada komentar:

Posting Komentar

Cara Mengkonversi File Python (.py) ke Executable (.exe) di Linux

  Berikut adalah panduan lengkap untuk mengkonversi script Python ke file .exe yang bisa dijalankan di Windows, meskipun Anda menggunakan Li...