Created
March 21, 2024 22:49
-
-
Save Ajak58a/11eb8b63c10b92aceec0bf364136592e to your computer and use it in GitHub Desktop.
Flood indicator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ThingSpeak.h" | |
#include <ESP8266WiFi.h> | |
const int trig = D1; | |
const int echo = D2; | |
#define redLed D3 | |
#define grnLed D4 | |
unsigned long channelID = REPLACE_WITH_YOUR_THINGSPEAK_CHANNEL_ID; | |
const char * write_api = "REPLACE_WITH_YOUR_THINGSPEAK_WRITE_API_KEY"; | |
char auth[] = "REPLACE_WITH_YOUR_THINGSPEAK_AUTHOR"; | |
char ssid[] = "REPLACE_WITH_YOUR_WIFI_SSID"; | |
char pass[] = "REPLACE_WITH_YOUR_WIFI_PASSWORD"; | |
unsigned long startMillis; | |
unsigned long currentMillis; | |
const unsigned long period = 10000; | |
WiFiClient client; | |
long duration; | |
int distance; | |
void setup() | |
{ | |
pinMode(trig, OUTPUT); | |
pinMode(echo, INPUT); | |
pinMode(redLed, OUTPUT); | |
pinMode(grnLed, OUTPUT); | |
digitalWrite(redLed, LOW); | |
digitalWrite(grnLed, LOW); | |
Serial.begin(9600); | |
WiFi.begin(ssid, pass); | |
while (WiFi.status() != WL_CONNECTED) | |
{ | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println("WiFi connected"); | |
Serial.println(WiFi.localIP()); | |
ThingSpeak.begin(client); | |
startMillis = millis(); //initial start time | |
} | |
void loop() | |
{ | |
digitalWrite(trig, LOW); | |
delayMicroseconds(2); | |
digitalWrite(trig, HIGH); | |
delayMicroseconds(10); | |
digitalWrite(trig, LOW); | |
duration = pulseIn(echo, HIGH); | |
distance = duration * 0.034 / 2; | |
Serial.println(distance); | |
if (distance <= 4) | |
{ | |
digitalWrite(redLed, HIGH); | |
digitalWrite(grnLed, LOW); | |
} | |
else | |
{ | |
digitalWrite(grnLed, HIGH); | |
digitalWrite(redLed, LOW); | |
} | |
currentMillis = millis(); | |
if (currentMillis - startMillis >= period) | |
{ | |
ThingSpeak.setField(1, distance); | |
ThingSpeak.writeFields(channelID, write_api); | |
startMillis = currentMillis; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment