Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- #define input 5
- #define output 4
- //Notwendige Daten zum Verbinden
- char* ssid = your_ssid;
- char* password = your_password;
- char* mqttServer = your_mqttserver;
- int mqttPort = 1883;
- char* mqttUser = your_User;
- char* mqttPassword = your_password;
- char* topic = your_status_detection_topic;
- WiFiClient espClient;
- PubSubClient client(espClient);
- int inputState;
- int lastState;
- char message[50];
- void setup_wifi() {
- delay(10);
- // We start by connecting to a WiFi network
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- randomSeed(micros());
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- for (int i = 0; i < length; i++) {
- Serial.print((char)payload[i]);
- }
- Serial.println();
- digitalWrite(output, HIGH);
- delay(500);
- digitalWrite(output, LOW);
- }
- void reconnect() {
- // Loop until we're reconnected
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- if (client.connect("ESP32Client", mqttUser, mqttPassword)) {
- Serial.println("connected");
- // Once connected, publish an announcement...
- client.subscribe("pc/power");
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- // Wait 5 seconds before retrying
- delay(5000);
- }
- }
- }
- void setup() {
- pinMode(BUILTIN_LED, OUTPUT);
- pinMode(input, INPUT);
- pinMode(output, OUTPUT);
- Serial.begin(115200);
- setup_wifi();
- client.setServer(mqttServer, 1883);
- client.setCallback(callback);
- }
- void loop() {
- if (!client.connected()) {
- reconnect();
- }
- client.loop();
- inputState = digitalRead(input);
- if (inputState != lastState ) {
- if (inputState == 1) {
- client.publish(topic, "ON");
- Serial.println("posted");
- Serial.println(WiFi.status());
- Serial.println(client.connected());
- } else {
- client.publish(topic, "OFF");
- Serial.println("posted");
- Serial.println(WiFi.status());
- Serial.println(client.connected());
- }
- }
- lastState = inputState;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement