คือผมต้องสร้าง Toggle ในแดชบอร์ดของ netpie เพื่อควบคุม led โดยตรง ผมต้องทำไงครับ

#include <WiFi.h>
#include <PubSubClient.h>

// กำหนดการเชื่อมต่อ WiFi
const char* ssid = "AAB";
const char* password = "00005555";

// กำหนดข้อมูล MQTT สำหรับ NetPie
const char* mqtt_server = "broker.netpie.io";
const int mqtt_port = 1883;
const char* mqtt_Client = "ffa71869-6288-49b1-ae5c-312666adf0bb";
const char* mqtt_username = "bVzjeZDNUkWgfWcB5VUhs6r21drcJC2X";
const char* mqtt_password = "qL3waQSSTLBGa2xgsYeYz7ELBtphSL19";

#define trig 5
#define echo 4
#define led_red 16
#define led_green 17
#define led_light 19

WiFiClient espClient;
PubSubClient client(espClient);

void reconnect() {
    while (!client.connected()) {
        Serial.print("Attempting MQTT connection...");
        
        // เชื่อมต่อ MQTT (ใช้ Username/Password ถ้าจำเป็น)
        if (client.connect(mqtt_Client, mqtt_username, mqtt_password)) {
            Serial.println("Connected!");
            
            // Subscribe topic หลังเชื่อมต่อสำเร็จ
            client.subscribe("test/topic");
        } else {
            Serial.print("Failed, rc=");
            Serial.print(client.state());
            Serial.println(" Try again in 5 seconds");
            delay(5000);
        }
    }
}

void callback(char* topic, byte* message, unsigned int length) {
    Serial.print("Message received on topic: ");
    Serial.println(topic);

    Serial.print("Message: ");
    String messageTemp;
    
    for (int i = 0; i < length; i++) {
        Serial.print((char)message);
        messageTemp += (char)message; // แปลงเป็น String
    }
    Serial.println();

    // ตัวอย่าง: ตรวจสอบข้อความที่ได้รับ
    if (messageTemp == "ON") {
        Serial.println("Turning ON the LED");
        digitalWrite(led_light, HIGH);
    } else if (messageTemp == "OFF") {
        Serial.println("Turning OFF the LED");
        digitalWrite(led_light, LOW);
    }
}


// ฟังก์ชันวัดระยะทางจากเซ็นเซอร์อัลตราโซนิก
long getDistance() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);

  long duration = pulseIn(echo, HIGH, 30000); // Timeout 30ms
  if (duration == 0) {
    Serial.println("Ultrasonic sensor timeout!");
    return -1;
  }

  long distance = (duration / 2) / 29.1;  // คำนวณระยะทาง (cm)
  return distance;
}

void setup() {
  Serial.begin(115200);
  Serial.println("Connecting to WiFi...");
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");

  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);

  pinMode(led_red, OUTPUT);
  pinMode(led_green, OUTPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  pinMode(led_light, OUTPUT);

  digitalWrite(led_light, LOW);  // เริ่มต้นให้ปิดไฟ
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  long distance = getDistance();
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // ควบคุมสถานะของ LED ตามระยะทาง
  if (distance < 10) {
    digitalWrite(led_red, HIGH);
    digitalWrite(led_green, LOW);
  } else if (distance >= 10 && distance < 20) {
    digitalWrite(led_green, HIGH);
    digitalWrite(led_red, LOW);
  } else {
    digitalWrite(led_green, LOW);
    digitalWrite(led_red, LOW);
  }

  // อ่านสถานะของ LED
  int ledRedState = digitalRead(led_red);
  int ledGreenState = digitalRead(led_green);
  int ledLightState = digitalRead(led_light);

  // ปริ้นสถานะของ LED
  Serial.print("Led red: ");
  Serial.println(ledRedState == HIGH ? "ON" : "OFF");
  Serial.print("Led green: ");
  Serial.println(ledGreenState == HIGH ? "ON" : "OFF");
  Serial.print("Led light: ");
  Serial.println(ledLightState == HIGH ? "ON" : "OFF");

  // สร้าง Payload สำหรับ Shadow
  String data = "{\"data\":{\"distance\": " + String(distance) +
               ",\"led_red\": " + String(ledRedState) +
               ",\"led_green\": " + String(ledGreenState) +
               ",\"led_light\": " + String(ledLightState) +
               "}}";

  // แปลงข้อมูล JSON เป็นข้อความ (char array)
  char msg[data.length() + 1];
  data.toCharArray(msg, data.length() + 1);

  // ส่งข้อมูลไปยัง NetPie Shadow
  if (client.publish("@shadow/data/update", msg)) {
    Serial.println("Publish Success!");
  } else {
    Serial.println("Publish Failed!");
  }

  delay(1000);  // หยุดรอ 1 วินาที
}
แสดงความคิดเห็น
โปรดศึกษาและยอมรับนโยบายข้อมูลส่วนบุคคลก่อนเริ่มใช้งาน อ่านเพิ่มเติมได้ที่นี่