I'm using a XIAO ESP32-C3 with an Arduino capacitive soil sensor v1.2 hardwired to the A0 pin (plus VUSB and ground) to sense soil moisture content and then send it to an MQTT broker every so often.
The problem is that my controller fails to connect to Wifi. I've tried stripping the other portions of my code out and it fixes it but I'm having trouble isolating what I've done wrong that is interfering with the connection.
Below is my code.
#include <WiFi.h>
#include <PubSubClient.h>
#include "arduino_secrets.h"
// Update these with values suitable for your hardware/network.
IPAddress server(192, 168, 1, 100); // Broker IP address
const char* ssid = "NETGEAR82"; // Network SSID
const char* pass = "pastelzoo998"; // Network password
const char username[] = SECRET_USERNAME; // Broker username
const char password[] = SECRET_PASSWORD; // Broker password
// Set topics to publish to the broker
const char topic[] = "XiaoSoilSensor/Status";
const char will[] = "XiaoSoilSensor/SoilSensor";
const char topic1[] = "XiaoSoilSensor/SoilSensor";
//Set interval for sending messages (milliseconds)
const long interval = 1000;
unsigned long previousMillis = 0;
//Set up capacitive soil sensor variables
int pin_soil = A0; // Input is hardwired to A0
int soil_moisture = 0; // Sensor variable
void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
// Set up the wifi and broker class
WiFiClient wifiClient;
PubSubClient client(wifiClient);
long lastReconnectAttempt = 0;
boolean reconnect() {
if (client.connect("arduinoClient", username, password, topic, 0, 0, "0")) {
// Once connected, publish an announcement...
client.publish("XiaoSoilSensor/Status", "1");
// ... and resubscribe
// client.subscribe("inTopic");
}
return client.connected();
}
void setup() {
Serial.begin(9600);
Serial.println("Serial begin");
// Set pinmode for soil sensor
pinMode(pin_soil, INPUT);
client.setServer(server, 1883);
client.setCallback(callback);
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
// failed, retry
Serial.println("Wifi failed.");
delay(1000);
}
delay(1500);
lastReconnectAttempt = 0;
}
void loop() {
// Assigns time to check against
unsigned long currentMillis = millis();
// Check to see if the broker is connected and reconect if it isn't
if (!client.connected()) {
long now = millis();
if (now - lastReconnectAttempt > 5000) {
lastReconnectAttempt = now;
// Attempt to reconnect
if (reconnect()) {
lastReconnectAttempt = 0;
}
}
} else {
// Client connected, publish topics if the interval has passed
if (currentMillis - previousMillis >= interval) {
// Save the last time a message was sent
previousMillis = currentMillis;
// Read the sensor
soil_moisture = analogRead(pin_soil);
char buffer[33];
// Publish the reading to the broker
client.publish("XiaoSoilSensor/SoilSensor", itoa(soil_moisture, buffer, 10));
}
client.loop();
}
}