2019年8月16日 星期五

ESP8266 Multisensor Shield with Node-RED

ESP8266 Multisensor Shield with Node-RED

















===========Esp8266程式================
/*********
  Rui Santos
  Complete project details at https://randomnerdtutorials.com 
*********/

// Load libraries
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// Update these with values suitable for your network.
//const char *ssid = "PTS-2F";
//const char *pass = "PTS6662594";
const char *ssid = "74170287";
const char *pass = "24063173";
//const char *ssid = "alex9ufo";
//const char *pass = "alex9981";

// Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
const char* mqtt_server = "broker.mqtt-dashboard.com";  //ip address or hostname of the mqtt broker
// MQTT Broker IP example
//const char* mqtt_server = "192.168.1.144";

// Initializes the espClient. You should change the espClient name if you have multiple ESPs running in your home automation system
WiFiClient espClient;
PubSubClient client(espClient);

// Variable to hold the temperature reading
String temperatureString = "";
#define BUILTIN_LED  D0  // Arduino standard is GPIO13 but lolin nodeMCU is 2

// Set GPIOs for: output variable, status LED, PIR Motion Sensor, and LDR
const int output = D1  ;
const int statusLed = BUILTIN_LED ;
const int motionSensor = D2;
const int ldr = A0;
// Store the current output state
String outputState = "off";

// GPIO where the DS18B20 is connected to
const int oneWireBus = D4;         
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

// Timers - Auxiliary variables
unsigned long now = millis();
unsigned long lastMeasure = 0;
boolean startTimer = false;
unsigned long currentTime = millis();
unsigned long previousTime = 0;
//==========================================================================================
// Don't change the function below.
// This function connects your ESP8266 to your router
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, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("WiFi connected - ESP IP address: ");
  Serial.println(WiFi.localIP());
}
//==========================================================================================
// This functions is executed when some device publishes a message to a topic that your ESP8266 is subscribed to
// Change the function below to add logic to your program, so when a device publishes a message to a topic that
// your ESP8266 is subscribed you can actually do something
void callback(String topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  String messageTemp;
 
  for (int i = 0; i < length; i++) {
    Serial.print((char)message[i]);
    messageTemp += (char)message[i];
  }
  Serial.println();

  // Feel free to add more if statements to control more GPIOs with MQTT
  // If a message is received on the topic esp8266/output, you check if the message is either on or off.
  // Turns the output according to the message received
  if(topic=="alex9ufo/esp8266/output"){
    Serial.print("Changing output to ");
    if(messageTemp == "#on"){
      digitalWrite(output, LOW);
      Serial.print("#on");
    }
    else if(messageTemp == "#off"){
      digitalWrite(output, HIGH);
      Serial.print("#off");
    }
  }
  Serial.println();
}
//==========================================================================================
// This functions reconnects your ESP8266 to your MQTT broker
// Change the function below if you want to subscribe to more topics with your ESP8266
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected"); 
      // Subscribe or resubscribe to a topic
      // You can subscribe to more topics (to control more outputs)
      client.subscribe("alex9ufo/esp8266/output"); 
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
//==========================================================================================
// Checks if motion was detected and the sensors are armed. Then, starts a timer.
void detectsMovement() {
  Serial.println("MOTION DETECTED!");
  client.publish("alex9ufo/esp8266/motion", "MOTION DETECTED!");
  previousTime = millis();
  startTimer = true;
}
//==========================================================================================
void setup() {
  // Start the DS18B20 sensor
  sensors.begin();

  // Serial port for debugging purposes
  Serial.begin(115200);

  // PIR Motion Sensor mode, then set interrupt function and RISING mode
  pinMode(motionSensor, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(motionSensor), detectsMovement, RISING);
 
  // Initialize the output variable and the LED as OUTPUTs
  pinMode(output, OUTPUT);
  pinMode(statusLed, OUTPUT);
  digitalWrite(output, HIGH);
  digitalWrite(statusLed, LOW);
 
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}
//==========================================================================================
void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
 
  // Timer variable with current time
  now = millis();

  // Publishes new temperature and LDR readings every 30 seconds
  if (now - lastMeasure > 30000) {
    lastMeasure = now;
    sensors.requestTemperatures();
    // Temperature in Celsius degrees
    temperatureString = String(sensors.getTempCByIndex(0));
    // Uncomment the next line for temperature in Fahrenheit degrees
    //temperatureString = String(sensors.getTempFByIndex(0));
    // Publishes Temperature values
    client.publish("alex9ufo/esp8266/temperature", temperatureString.c_str());
    Serial.println("Temperature published");
   
    // Publishes LDR values
    client.publish("alex9ufo/esp8266/ldr", String(analogRead(ldr)).c_str());
    Serial.println("LDR values published");   
  }
  // After 10 seconds have passed since motion was detected, publishes a "No motion" message
  if ((now - previousTime > 10000) && startTimer) {
    client.publish("alex9ufo/esp8266/motion", "No motion");
    Serial.println("Motion stopped");
    startTimer = false;
  }
}
//==========================================================================================
=================Node-RED 程式====================

[{"id":"61640f10.dda39","type":"ui_switch","z":"1577f936.cf42e7","name":"","label":"Output","group":"a0157d81.02851","order":0,"width":0,"height":0,"passthru":true,"decouple":"false","topic":"","style":"","onvalue":"#on","onvalueType":"str","onicon":"","oncolor":"","offvalue":"#off","offvalueType":"str","officon":"","offcolor":"","x":110,"y":80,"wires":[["8f3f0ccd.0be1e"]]},{"id":"8f3f0ccd.0be1e","type":"mqtt out","z":"1577f936.cf42e7","name":"","topic":"alex9ufo/esp8266/output","qos":"0","retain":"true","broker":"40bf4d5e.0395f4","x":390,"y":80,"wires":[]},{"id":"ee62fc37.23c7","type":"mqtt in","z":"1577f936.cf42e7","name":"","topic":"alex9ufo/esp8266/motion","qos":"2","broker":"40bf4d5e.0395f4","x":170,"y":160,"wires":[["b45cf5.b14e9308"]]},{"id":"b45cf5.b14e9308","type":"ui_text","z":"1577f936.cf42e7","group":"a0157d81.02851","order":0,"width":0,"height":0,"name":"","label":"PIR Status:","format":"{{msg.payload}}","layout":"row-center","x":430,"y":160,"wires":[]},{"id":"d585e276.d0e5d","type":"ui_gauge","z":"1577f936.cf42e7","name":"","group":"a0157d81.02851","order":0,"width":0,"height":0,"gtype":"gage","title":"LDR","label":"Luminosity","format":"{{value}}","min":0,"max":"1023","colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","x":450,"y":240,"wires":[]},{"id":"948f9cf6.15409","type":"mqtt in","z":"1577f936.cf42e7","name":"","topic":"alex9ufo/esp8266/ldr","qos":"2","broker":"40bf4d5e.0395f4","x":150,"y":240,"wires":[["d585e276.d0e5d"]]},{"id":"6644f493.68bf4c","type":"mqtt in","z":"1577f936.cf42e7","name":"","topic":"alex9ufo/esp8266/temperature","qos":"2","broker":"40bf4d5e.0395f4","x":180,"y":320,"wires":[["44cb5724.b03ab8"]]},{"id":"44cb5724.b03ab8","type":"ui_chart","z":"1577f936.cf42e7","name":"","group":"a0157d81.02851","order":0,"width":0,"height":0,"label":"Temperature","chartType":"line","legend":"false","xformat":"HH:mm:ss","interpolate":"linear","nodata":"","dot":false,"ymin":"","ymax":"","removeOlder":1,"removeOlderPoints":"","removeOlderUnit":"3600","cutout":0,"useOneColor":false,"colors":["#1f77b4","#aec7e8","#ff7f0e","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5"],"useOldStyle":false,"x":430,"y":320,"wires":[[],[]]},{"id":"a0157d81.02851","type":"ui_group","z":"","name":"Main","tab":"8f361c82.458a5","disp":true,"width":"6","collapse":false},{"id":"40bf4d5e.0395f4","type":"mqtt-broker","broker":"broker.mqtt-dashboard.com","port":"1883","clientid":"","usetls":false,"compatmode":true,"keepalive":15,"cleansession":true,"birthQos":"0","willQos":"0"},{"id":"8f361c82.458a5","type":"ui_tab","z":"","name":"Dashboard","icon":"dashboard"}]

沒有留言:

張貼留言

113 學年度第 1 學期 RFID應用課程 Arduino程式

113 學年度第 1 學期 RFID應用課程 Arduino程式 https://www.mediafire.com/file/zr0h0p3iosq12jw/MFRC522+(2).7z/file 內含修改過後的 MFRC522 程式庫 (原程式有錯誤) //定義MFRC522...