I am using the script below to create a motion sensor using a Wemos D1 and a PIR sensor.
I'm using the ESP8266 Community board manager (V2.6.3).
THE PROBLEM
When I use the Wemos D1 R1
board no motion is detected at all.
When I use any of the LOLIN(WEMOS)
motion is constantly detected even when the sensor is not connected.
I have tried multiple sensors and boards as well as double checking the wires used.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Replace with your SSID, password and MQTT broker IP address
const char* ssid = "WIFI_NETWORK";
const char* password = "WIFI_PASSWORD";
const char* mqtt_user = "MQTT_USERNAME";
const char* mqtt_password = "MQTT_PASSWORD";
const char* mqtt_server = "MQTT_IP_ADDRESS";
const char* clientID = "sonfoff/pir";
const char* topic = "sonfoff/pir";
const int inputPin = D1;
int motionState = 0;
int i = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
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 reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientID, mqtt_user, mqtt_password)) {
Serial.println("connected");
client.publish(topic, "test", true);
} 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(inputPin, INPUT);
Serial.begin(115200);
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
setup_wifi();
client.setServer(mqtt_server, 1883);
while (!client.connected()) {
reconnect();
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
motionState = digitalRead(inputPin);
if ( motionState == HIGH ) {
digitalWrite(BUILTIN_LED, HIGH);
Serial.println("Motion Detected");
client.publish(topic, "on", true);
i = 0;
}
while(motionState == LOW && i ==0){
client.publish(topic, "off", true);
Serial.println("Motion Stopped");
i++;
}
}
LOLIN
boards – jampez77 Jan 6 '20 at 8:58