Skip to content
Permalink
Browse files
Update Lvs
  • Loading branch information
lvs committed May 12, 2024
1 parent 9a97890 commit d3b935b9599d8fc0ab1014ba8140f7c3bbe7e9aa
Showing 1 changed file with 82 additions and 1 deletion.
83 Lvs
@@ -1,3 +1,84 @@
pip install paho-mqtt

import paho.mqtt.client as mqtt

#include <SPI.h>
#include <WiFiNINA.h>
#include <PubSubClient.h>

// WiFi设置
const char* ssid = "your_ssid";
const char* password = "your_password";

// MQTT服务器设置
const char* mqtt_server = "mqtt.example.com";
const int mqtt_port = 1883;
const char* mqtt_topic = "door/window/status";

WiFiClient espClient;
PubSubClient client(espClient);

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

}

void Reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ArduinoClient")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}

void SetupWifi() {
delay(10);
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}

Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}

void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}

void loop() {
bool doorIsOpen = readDoorSensor();

if (doorIsOpen) {
char msg[50];
sprintf(msg, "OPEN");
client.publish(mqtt_topic, msg);
}


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

delay(1000);
}


bool readDoorSensor() {

return digitalRead(2) == HIGH;
}

0 comments on commit d3b935b

Please sign in to comment.