I have a DHT11 and a soil moisture connected to an ESP32. The DHT11 and soil moisture are powered by the 3v of the ESP32 and their grounds are connected to the ground. The DHT's data pin is connected to D4 and the soil moisture's A0 pin is connected to D2 of the ESP32.
I am able to read the humidity, temperature, and soil moisture with the code below off the ESP32.
I would like to now connect to the internet so have created a function that will connect me to wifi but when I run that function, my soil moisture will return a reading of 0. When I take that function out and not run it, then the soil moisture will return a different value other than 0.
#include <Arduino.h>
#include "DHT.h"
#include <WiFi.h>
int msensor = 2;
int msvalue = 0; //moisture sensor value
DHT dht(4, DHT11);
float hRead = 0;
float tRead = 0;
#define WIFI_NETWORK "xxx"
#define WIFI_PASSWORD "xxx"
#define WIFI_TIMEOUT_MS 20000
WiFiClient client;
void setup() {
pinMode(msensor, INPUT);
dht.begin();
Serial.begin(9600);
//connectToWiFi(); //WHEN THIS FUNCTION IS ACTIVE, SOIL MOISTURE RETURNS 0
}
void loop() {
msvalue = analogRead(msensor);
hRead = dht.readHumidity();
tRead = dht.readTemperature(true);
Serial.print("soil mositure: ");
Serial.println(msvalue);
Serial.print("temp: ");
Serial.println(tRead);
Serial.print("humidity: ");
Serial.println(hRead);
delay(5000);
}
void connectToWiFi() {
Serial.print("Connecting to wifi");
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_NETWORK, WIFI_PASSWORD);
unsigned long startAttemptTime = millis();
while(WiFi.status() != WL_CONNECTED && millis() - startAttemptTime < WIFI_TIMEOUT_MS) {
Serial.print(".");
delay(100);
}
if (WiFi.status() != WL_CONNECTED) {
Serial.println("\nFailed to connect to wifi");
} else {
Serial.println("\nConnected to Wifi!");
Serial.println(WiFi.localIP());
}
}
At first I thought this was a power issue and have swapped my soil moisture to the 5v instead of 3v of the ESP32 but I still get a return value of 0. I've also tried swapping the soil moisture to the digital pin and doing a digitalRead instead of an analogRead and I still get 0.
Any ideas on why my connectToWiFi function will interefere with my soil moisture reading? Thanks