Difference between revisions of "WeMOS: MQTT Simple Read Write"

From OnnoWiki
Jump to navigation Jump to search
(Created page with " #include <SPI.h> #include <PubSubClient.h> #include <Ethernet.h> →‎* LightSensorMqttDemo *: #define MQTT_SERVER "192.168.0.100" // MAC Address of Arduino E...")
 
 
(3 intermediate revisions by the same user not shown)
Line 1: Line 1:
 
  #include <SPI.h>
 
  #include <SPI.h>
 
  #include <PubSubClient.h>
 
  #include <PubSubClient.h>
  #include <Ethernet.h>
+
  #include <ESP8266WiFi.h>
 
+
#include <PubSubClient.h>
 +
 
  /*
 
  /*
 
   * LightSensorMqttDemo
 
   * LightSensorMqttDemo
Line 8: Line 9:
 
   */
 
   */
 
   
 
   
  #define MQTT_SERVER "192.168.0.100"
+
  const char* ssid = "o";
   
+
const char* password =  "";
// MAC Address of Arduino Ethernet Sheild (on sticker on shield)
+
const char* mqttServer = "192.168.88.222";
byte MAC_ADDRESS[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x31, 0xB8 };
+
  const int mqttPort = 1883;
  IPAddress ip(192, 168, 0, 4);
+
  const char* mqttUser = "mqtt-spy";
  IPAddress server(192, 168, 0, 100);
+
  const char* mqttPassword = "123456";
 
   
 
   
  EthernetClient ethClient;
+
  WiFiClient espClient;
  PubSubClient client(server, 1883, callback, ethClient);
+
  PubSubClient client(espClient);
   
+
  long unsigned int mytime;
// Pin 13 is the LED output pin
 
int ledPin = 13;
 
// Analog 2 is the input pin
 
int lightPinIn = 2;
 
 
   
 
   
 
  // defines and variable for sensor/control mode
 
  // defines and variable for sensor/control mode
Line 28: Line 25:
 
  #define MODE_SENSE  2  // sensing light, LED controlled by software
 
  #define MODE_SENSE  2  // sensing light, LED controlled by software
 
  int senseMode = 0;
 
  int senseMode = 0;
 
unsigned long time;
 
 
  char message_buff[100];
 
  char message_buff[100];
 
 
  void setup()
 
  void setup()
 
  {
 
  {
 
   // initialize the digital pin as an output.
 
   // initialize the digital pin as an output.
   pinMode(ledPin, OUTPUT);
+
   pinMode(D2, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
 
    
 
    
   // init serial link for debugging
+
   Serial.begin(115200);
   Serial.begin(9600);
+
  WiFi.begin(ssid, password);
    
+
  while (WiFi.status() != WL_CONNECTED) {
   if (Ethernet.begin(MAC_ADDRESS) == 0)
+
    delay(500);
  {
+
    Serial.println("Connecting to WiFi..");
       Serial.println("Failed to configure Ethernet using DHCP");
+
  }
       return;
+
   Serial.println("Connected to the WiFi network");
 +
 
 +
  client.setServer(mqttServer, mqttPort);
 +
   client.setCallback(callback);
 +
 
 +
   while (!client.connected()) {
 +
    Serial.println("Connecting to MQTT...");
 +
 
 +
//  if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
 +
    if (client.connect("ESP8266Client" )) {
 +
       Serial.println("connected"); 
 +
      } else {
 +
      Serial.print("failed with state ");
 +
       Serial.print(client.state());
 +
      delay(2000);
 +
    }
 
   }
 
   }
  }
+
  client.publish("esp/test", "Hello from ESP8266");
 
+
  client.subscribe("esp/test");
 +
  }  
  
 
  void loop()
 
  void loop()
Line 55: Line 65:
 
       // arduino-mqtt, mqtt-spt, e10adc3949ba59abbe56e057f20f883e (123456)
 
       // arduino-mqtt, mqtt-spt, e10adc3949ba59abbe56e057f20f883e (123456)
 
       // arduino-mqtt (bisa tanpa username & password, sebagai anonymous)
 
       // arduino-mqtt (bisa tanpa username & password, sebagai anonymous)
       client.connect("arduino-mqtt");
+
       client.connect("ESP8266Client");
       client.publish("arduino/lightsensor", "I'm alive!");
+
       client.publish("esp/test", "I'm alive!");
       client.subscribe("arduino/lightsensor");
+
       client.subscribe("esp/test");
 
   }
 
   }
 
    
 
    
Line 63: Line 73:
 
     case MODE_OFF:
 
     case MODE_OFF:
 
       // light should be off
 
       // light should be off
       digitalWrite(ledPin, LOW);
+
       digitalWrite(D2, LOW);
 
       break;
 
       break;
 
     case MODE_ON:
 
     case MODE_ON:
 
       // light should be on
 
       // light should be on
       digitalWrite(ledPin, HIGH);
+
       digitalWrite(D2, HIGH);
 
       break;
 
       break;
 
     case MODE_SENSE:
 
     case MODE_SENSE:
Line 73: Line 83:
 
          
 
          
 
       // read from light sensor (photocell)
 
       // read from light sensor (photocell)
       int lightRead = analogRead(lightPinIn);
+
       int lightRead = analogRead(A0);
 
   
 
   
 
       // if there is light in the room, turn off LED
 
       // if there is light in the room, turn off LED
Line 80: Line 90:
 
       // 500 is a "magic number" for "dark"
 
       // 500 is a "magic number" for "dark"
 
       if (lightRead > 500) {
 
       if (lightRead > 500) {
         digitalWrite(ledPin, LOW);
+
         digitalWrite(D2, LOW);
 
       } else {
 
       } else {
         digitalWrite(ledPin, HIGH);
+
         digitalWrite(D2, HIGH);
 
       }
 
       }
 
        
 
        
 
       // publish light reading every 5 seconds
 
       // publish light reading every 5 seconds
       if (millis() > (time + 5000)) {
+
       if (millis() > (mytime + 5000)) {
         time = millis();
+
         mytime = millis();
 
         String pubString = "{\"report\":{\"light\": \"" + String(lightRead) + "\"}}";
 
         String pubString = "{\"report\":{\"light\": \"" + String(lightRead) + "\"}}";
 
         pubString.toCharArray(message_buff, pubString.length()+1);
 
         pubString.toCharArray(message_buff, pubString.length()+1);
 
         //Serial.println(pubString);
 
         //Serial.println(pubString);
         client.publish("arduino/lightsensor", message_buff);
+
         client.publish("esp/test", message_buff);
 
       }
 
       }
 
   }
 
   }
Line 98: Line 108:
 
   client.loop();
 
   client.loop();
 
  }   
 
  }   
+
 
 
  // handles message arrived on subscribed topic(s)
 
  // handles message arrived on subscribed topic(s)
 
  void callback(char* topic, byte* payload, unsigned int length) {
 
  void callback(char* topic, byte* payload, unsigned int length) {
 
   
 
   
   int i = 0;  
+
   int i = 0;  
 
   
 
   
   //Serial.println("Message arrived:  topic: " + String(topic));
+
   // Serial.println("Message arrived:  topic: " + String(topic));
   //Serial.println("Length: " + String(length,DEC));
+
   // Serial.println("Length: " + String(length,DEC));
 
    
 
    
 
   // create character buffer with ending null terminator (string)
 
   // create character buffer with ending null terminator (string)
Line 114: Line 124:
 
    
 
    
 
   String msgString = String(message_buff);
 
   String msgString = String(message_buff);
 
+
   
 
   //Serial.println("Payload: " + msgString);
 
   //Serial.println("Payload: " + msgString);
 
    
 
    
   if (msgString.equals("{\"command\":{\"lightmode\": \"OFF\"}}")) {
+
   if (msgString.equals("OFF")) {
 
     senseMode = MODE_OFF;
 
     senseMode = MODE_OFF;
   } else if (msgString.equals("{\"command\":{\"lightmode\": \"ON\"}}")) {
+
   } else if (msgString.equals("ON")) {
 
     senseMode = MODE_ON;
 
     senseMode = MODE_ON;
   } else if (msgString.equals("{\"command\":{\"lightmode\": \"SENSE\"}}")) {
+
   } else if (msgString.equals("SENSE")) {
 
     senseMode = MODE_SENSE;
 
     senseMode = MODE_SENSE;
 
   }
 
   }

Latest revision as of 10:13, 14 August 2020

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

/*
 * LightSensorMqttDemo
 *
 */

const char* ssid = "o";
const char* password =  "";
const char* mqttServer = "192.168.88.222";
const int mqttPort = 1883;
const char* mqttUser = "mqtt-spy";
const char* mqttPassword = "123456";

WiFiClient espClient;
PubSubClient client(espClient);
long unsigned int mytime;

// defines and variable for sensor/control mode
#define MODE_OFF    0  // not sensing light, LED off
#define MODE_ON     1  // not sensing light, LED on
#define MODE_SENSE  2  // sensing light, LED controlled by software
int senseMode = 0;
char message_buff[100];
void setup()
{
  // initialize the digital pin as an output.
  pinMode(D2, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
  
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) {
    Serial.println("Connecting to MQTT...");
 
//  if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
    if (client.connect("ESP8266Client" )) {
      Serial.println("connected");  
      } else {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
    }
  }
  client.publish("esp/test", "Hello from ESP8266");
  client.subscribe("esp/test");
} 
void loop()
{
  if (!client.connected())
  {
      // clientID, username, MD5 encoded password
      // arduino-mqtt, mqtt-spt, e10adc3949ba59abbe56e057f20f883e (123456)
      // arduino-mqtt (bisa tanpa username & password, sebagai anonymous)
      client.connect("ESP8266Client");
      client.publish("esp/test", "I'm alive!");
      client.subscribe("esp/test");
  }
  
  switch (senseMode) {
    case MODE_OFF:
      // light should be off
      digitalWrite(D2, LOW);
      break;
    case MODE_ON:
      // light should be on
      digitalWrite(D2, HIGH);
      break;
    case MODE_SENSE:
      // light is adaptive to light sensor
       
      // read from light sensor (photocell)
      int lightRead = analogRead(A0);

      // if there is light in the room, turn off LED
      // else, if it is "dark", turn it on
      // scale of light in this circit is roughly 0 - 900
      // 500 is a "magic number" for "dark"
      if (lightRead > 500) {
        digitalWrite(D2, LOW);
      } else {
        digitalWrite(D2, HIGH);
      }
      
      // publish light reading every 5 seconds
      if (millis() > (mytime + 5000)) {
        mytime = millis();
        String pubString = "{\"report\":{\"light\": \"" + String(lightRead) + "\"}}";
        pubString.toCharArray(message_buff, pubString.length()+1);
        //Serial.println(pubString);
       client.publish("esp/test", message_buff);
      }
  }
  
  // MQTT client loop processing
  client.loop();
}  
// handles message arrived on subscribed topic(s)
void callback(char* topic, byte* payload, unsigned int length) {

  int i = 0;    

  // Serial.println("Message arrived:  topic: " + String(topic));
  // Serial.println("Length: " + String(length,DEC));
  
  // create character buffer with ending null terminator (string)
  for(i=0; i<length; i++) {
    message_buff[i] = payload[i];
  }
  message_buff[i] = '\0';
  
  String msgString = String(message_buff);
   
  //Serial.println("Payload: " + msgString);
  
  if (msgString.equals("OFF")) {
    senseMode = MODE_OFF;
  } else if (msgString.equals("ON")) {
    senseMode = MODE_ON;
  } else if (msgString.equals("SENSE")) {
    senseMode = MODE_SENSE;
  }
}


Pranala Menarik