// Water Softener Salt Level Monitor #include "Adafruit_VL53L0X.h" Adafruit_VL53L0X lox = Adafruit_VL53L0X(); #include // Network information. #define WIFI_NAME "Your ssid" #define PASSWORD "Your password" IPAddress ip(192,168,1,150); // Choose your ip address IPAddress gateway(192,168,1,254); // Your gateway IPAddress subnet(255,255,255,0); IPAddress dns(192,168,1,254); // Same as your gateway // Hardware information. #define TIMEOUT 5000 // Timeout for server response. // ThingSpeak information. #define THING_SPEAK_ADDRESS "api.thingspeak.com" String writeAPIKey="Your API key"; // Change this to the write API key for your channel. WiFiClient client; // Put your setup code here, to run once: void setup() { Serial.begin( 74880 ); // You may need to adjust the speed depending on your hardware. lox.begin(); connectWifi(); } void loop() { HTTPPost(); delay( 1000 ); Serial.println( "Goodnight for an hour "); ESP.deepSleep( 4200000000ULL ); // unsigned 32 bit integer in microseconds delay(100); // If you disable sleep mode, add delay so you don't post to ThingSpeak too often. // delay( 20000 ); } // Connect to the local Wi-Fi network int connectWifi() { WiFi.mode(WIFI_STA); WiFi.persistent(false); // Turn off confusing helful features WiFi.setAutoConnect(false); WiFi.setAutoReconnect(false); WiFi.config(ip, gateway, subnet, dns); WiFi.begin( WIFI_NAME , PASSWORD ); delay(1000); // Optimise for minimum value to connect } // This function builds the data string for posting to ThingSpeak int HTTPPost(){ VL53L0X_RangingMeasurementData_t measure; lox.rangingTest(&measure, false); if (client.connect( THING_SPEAK_ADDRESS , 80 )){ // Build the postData string. String postData= "api_key=" + writeAPIKey ; postData += "&field1="; postData += String(measure.RangeMilliMeter); postData += "&field2="; postData += String(WiFi.RSSI()); // POST data via HTTP. Serial.println( "Connecting to ThingSpeak for update..." ); Serial.println(); client.println( "POST /update HTTP/1.1" ); client.println( "Host: api.thingspeak.com" ); client.println( "Connection: close" ); client.println( "Content-Type: application/x-www-form-urlencoded" ); client.println( "Content-Length: " + String( postData.length() ) ); client.println(); client.println( postData ); Serial.println( postData ); String answer=getResponse(); Serial.println( answer ); Serial.println(WiFi.RSSI()); Serial.println(measure.RangeMilliMeter); } else { Serial.println ( "Connection Failed" ); } } // Collect the response and build it into a string. String getResponse(){ String response; long startTime = millis(); delay( 200 ); while ( client.available() < 1 && (( millis() - startTime ) < TIMEOUT ) ){ delay( 5 ); } if( client.available() > 0 ){ // Get response from server. char charIn; do { charIn = client.read(); // Read a char from the buffer. response += charIn; // Append the char to the string response. } while ( client.available() > 0 ); } client.stop(); return response; }