Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //#include <ThingSpeak.h>
- #include <ESP8266WiFi.h>
- //////////////////////////////
- const int trigPin = 12;
- const int echoPin = 14;
- //define sound velocity in cm/uS
- #define SOUND_VELOCITY 0.034
- #define CM_TO_INCH 0.393701
- long duration;
- float distanceCm;
- float distanceInch;
- //////////////////////////////
- //Wifi config
- const char* ssid = "Fatimah"; //Input here your network SSID(name)
- const char* pass = "123456789";
- //ThingSpeak config
- //unsigned long myChannelNumber = 2168066; //Input here your channel number
- //const char * myWriteAPIKey = "Y86LIUY1H210Q8FK"; // Paste here your ThingSpeak Write API Key
- const char* host = "maker.ifttt.com";
- const int buzzer = D7;
- const int ledPin = D8;
- int safetyDistance = 30;
- void setup() {
- WiFi.begin(ssid, pass);
- pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
- pinMode(echoPin, INPUT); // Sets the echoPin as an Input
- pinMode(buzzer, OUTPUT);
- pinMode(ledPin, OUTPUT);
- Serial.begin(9600); // Starts the serial communication
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- getDistanceAndShow();
- }
- void loop() {
- getDistanceAndShow();
- WiFiClient client;
- const int httpPort = 80;
- if (!client.connect(host, httpPort)) {
- Serial.println("connection failed");
- return;
- }
- safetyDistance = distanceCm;
- if (safetyDistance <= 10) {
- digitalWrite(buzzer, HIGH);
- digitalWrite(ledPin, HIGH);
- String url = "/trigger/Alert/with/key/krVWdWa8GJn8-Q9yAbqKNirgfQqaYxM68vd3eJQLUuK";
- Serial.print("Requesting URL: ");
- Serial.println(url);
- client.print(String("GET ") + url + " HTTP/1.1\r\n" +
- "Host: " + host + "\r\n" +
- "Connection: close\r\n\r\n");
- }
- else {
- digitalWrite(buzzer, LOW);
- digitalWrite(ledPin, LOW);
- }
- /*
- int x = ThingSpeak.writeField(myChannelNumber, 1, distance, myWriteAPIKey);
- if(x == 200){
- Serial.println("Channel update successful.");
- }
- else{
- Serial.println("Problem updating channel. HTTP error code " + String(x));
- }*/
- }
- void getDistanceAndShow() {
- // Clears the trigPin
- digitalWrite(trigPin, LOW);
- delayMicroseconds(2);
- // Sets the trigPin on HIGH state for 10 micro seconds
- digitalWrite(trigPin, HIGH);
- delayMicroseconds(10);
- digitalWrite(trigPin, LOW);
- // Reads the echoPin, returns the sound wave travel time in microseconds
- duration = pulseIn(echoPin, HIGH);
- // Calculate the distance
- distanceCm = duration * SOUND_VELOCITY / 2;
- // Convert to inches
- distanceInch = distanceCm * CM_TO_INCH;
- // Prints the distance on the Serial Monitor
- Serial.print("Distance (cm): ");
- Serial.println(distanceCm);
- delay(1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement