When I run a very simple code on it, it works perfectly.
With the same wiring setup, and the same code as part of a larger program utilizing the temp sensor just before it, it seems to always read on?
Here is the simple code and the output. It detects the moition and comes on right away.
int ledPin = 13; // choose the pin for the LED
int inputPin = 4; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
void setup() {
pinMode(ledPin, OUTPUT); // declare LED as output
pinMode(inputPin, INPUT); // declare sensor as input
Serial.begin(115200);
Serial.println("Starting up");
}
void loop(){
val = digitalRead(inputPin); // read input value
Serial.println((String)"the value of val is " +val);
if (val == HIGH) // check if the input is HIGH
{
Serial.println("Motion is on");
if (pirState == LOW)
{
Serial.println("Motion detected!"); // print on output change
pirState = HIGH;
}
}
else
{
digitalWrite(ledPin, LOW); // turn LED OFF
if (pirState == HIGH)
{
Serial.println("Motion ended!"); // print on output change
pirState = LOW;
}
}
}
Here is the code that seems to give erroneous reads
void do_board_function() { // This boards function is to get and send DHT temp/humity to MQTT
Serial.println("");
Serial.println("Starting Board Functions");
//////START - TEMP + HUM//////
float readt = dht.readTemperature();
delay(2000);
float readh = dht.readHumidity();
// Check if any reads failed and exit early (to try again).
if (isnan(readt)) {
Serial.println("Failed to read from DHT sensor!");
}
else {
Serial.print("Temperature = ");
Serial.print(readt);
Serial.print(" .... ");
Serial.print("Humidity = ");
Serial.print(readh);
Serial.println();
String temp_strt = String(readt);
String hum_strt = String(readh);
temp_strt.toCharArray(temp, temp_strt.length() + 1); //packaging up the data to publish to mqtt
String temp_strh = String(readh);
hum_strt.toCharArray(hum, hum_strt.length() + 1); //packaging up the data to publish to mqtt
// String MQTTPublish = String("Temperature is" + t + "Humidity is" + h);
client.publish(Topic_DataMessagesTemp, temp);
client.publish(Topic_DataMessagesHum, hum);
//////END - TEMP + HUM//////
//New Motion Sensor code
val = digitalRead(MOTIONPIN); // read input value
Serial.println((String)"the value of val is " +val);
if (val == HIGH) // check if the input is HIGH
{
Serial.println("Motion is on");
if (pirState == LOW)
{
Serial.println("Motion detected!"); // print on output change
pirState = HIGH;
}
}
else
{
if (pirState == HIGH)
{
Serial.println("Motion ended!"); // print on output change
pirState = LOW;
}
}
I have tried to wrap the sensor in tinfoil thiking it was itnerference but I honestly have no idea....
Attached is the pictures showing the working and non working and my wiring. The motion sensor is on pin D2 and the temp sensor read put is D1..