Name der Bibliothek | Bibliotheksfunktion | Herunterladen |
---|---|---|
NewPing |
Bibliothek für AVR-Mikrocontroller (ATmega) Arduino Uno / Nano / Mega. Es ermöglicht Messungen mit Ultraschall-Distanzsensoren US-02X, IOE-SR0X, HC-SR0X, HY-SRF0X, JSN-SR0XT, DYP-ME007. |
Herunterladen |
NewPingESP8266 |
Bibliothek für ESP8266- und ESP32-Mikrocontroller. Es ermöglicht Messungen mit Ultraschall-Distanzsensoren US-02X, IOE-SR0X, HC-SR0X, HY-SRF0X, JSN-SR0XT, DYP-ME007. |
Herunterladen |
Ethernet2 |
Bibliothek für AVR-Mikrocontroller (ATmega) Arduino Uno / Nano / Mega. Es ermöglicht die Kommunikation mit dem Ethernet-Modul Wiznet W5200 bis W5500 über die SPI-Schnittstelle. |
Herunterladen |
Ethernet3 |
Bibliothek für AVR-Mikrocontroller (ATmega) Arduino Uno / Nano / Mega. Es ermöglicht die Kommunikation mit dem Ethernet-Modul Wiznet W5500 V2 - USR-ES1 über die SPI-Schnittstelle. |
Herunterladen |
/*|-----------------------------------------------------------------------------------|*/ /*|Projekt: Hladinomer - HTTP - Compact - HC-SR04 / JSN-SR04T / HY-SRF05 |*/ /*|Arduino + Ethernet (W5100 / W5500, ENC28J60), ESP8266 (NodeMCU), ESP32 (DevKit) |*/ /*|Autor: Martin Chlebovec (martinius96) |*/ /*|E-mail: martinius96@gmail.com |*/ /*|Info k projektu (schéma): https://martinius96.github.io/hladinomer-studna-scripty/ |*/ /*|Testovacie webove rozhranie: http://arduino.clanweb.eu/studna_s_prekladom/ |*/ /*|Knižnice NewPing, ESP8266NewPing a Ethernet2 je dostupná v Github repozitári: |*/ /*|https://github.com/martinius96/hladinomer-studna-scripty/ - stihnuť a rozbaliť |*/ /*|Obsah priečinka /src/ nakopírovať do C:/Users/User/Dokumenty/Arduino/libraries/ |*/ /*|Na toto webove rozhranie posiela mikrokontroler data |*/ /*|Na zaklade zvolenej platformy v Arduino IDE sa vykona kompilacia podla direktiv |*/ /*|Licencia pouzitia: MIT |*/ /*|Revízia: 24. Jun 2022 |*/ /*|-----------------------------------------------------------------------------------|*/ const char* host = "arduino.clanweb.eu"; //adresa webservera (doména) na ktorú sa odosielajú dáta String url = "/studna_s_prekladom/data.php"; //URL adresa //Pre testovacie webove rozhranie sa data odosielaju na: arduino.clanweb.eu/studna_s_prekladom/data.php (HTTP POST ONLY) #define maxVzdialenost 450 unsigned long timer2 = 0; #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) //HLAVICKOVE SUBORY PRE ARDUINO A ETHERNET SHIELD + watchdog #include <avr\wdt.h> #include <SPI.h>#include <Ethernet.h> //Ethernet shield Wiznet W5100 - zakomentovat ak sa nepouziva //#include <Ethernet2.h> //Ethernet modul Wiznet W5500 - zakomentovat ak sa nepouziva //#include <Ethernet3.h> //Ethernet modul WIZ850io / USR-ES1 (Wiznet W5500 V2) - zakomentovat ak sa nepouziva //#include <UIPEthernet.h> //Ethernet modul ENC28J60 - zakomentovat ak sa nepouziva
#include <NewPing.h> #define pinTrigger 5 #define pinEcho 6 NewPing sonar(pinTrigger, pinEcho, maxVzdialenost); byte mac[] = { 0xAA, 0xBB, 0xCA, 0xDC, 0xEE, 0xDE }; //IPAddress ip(192, 168, 0, 2); //IPAddress dnServer(192, 168, 0, 1); //IPAddress gateway(192, 168, 0, 1); //IPAddress subnet(255, 255, 255, 0); EthernetClient client; #endif #if defined(ESP32) || defined(ESP8266) #include <NewPingESP8266.h>const char * ssid = "WIFI_MENO_SIETE"; //MENO WiFi SIETE const char * password = "WIFI_HESLO_SIETE"; //HESLO WiFi SIETE
#endif #if defined(ESP8266) #include <ESP8266WiFi.h> #define pinTrigger 5 //D1 #define pinEcho 4 //D2 NewPingESP8266 sonar(pinTrigger, pinEcho, maxVzdialenost); #endif #if defined(ESP32) #include <WiFi.h> #include "esp_system.h" #define pinTrigger 22 //D22 #define pinEcho 23 //D23 NewPingESP8266 sonar(pinTrigger, pinEcho, maxVzdialenost); const int wdtTimeout = 30000; //time in ms to trigger the watchdog hw_timer_t *timer = NULL; void IRAM_ATTR resetModule() { ets_printf("reboot\n"); esp_restart(); } #endif #if defined(ESP32) || defined(ESP8266) WiFiClient client; #endif void setup() { Serial.begin(115200); #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) if (Ethernet.begin(mac) == 0) { Serial.println(F("Konfigurujem Ethernet adapter")); Ethernet.begin(mac); // pre DHCP //Ethernet.begin(mac, ip); //pre staticku IPv4 //Ethernet.begin(mac, ip, dns); //pre staticku IPv4 //Ethernet.begin(mac, ip, dns, gateway); //pre staticku IPv4 //Ethernet.begin(mac, ip, dns, gateway, subnet); //pre staticku IPv4 //IBA PRE Ethernet3.h !!! POZOR --> INY BEGIN ORDER PARAMETROV.... : //Ethernet.begin(mac, ip, subnet, gateway, dns); } Serial.print(F("Priradena IP: ")); Serial.println(Ethernet.localIP()); wdt_enable(WDTO_8S); //watchdog on 8 sec trigger #elif defined(ESP32) || defined(ESP8266) WiFi.begin(ssid, password); //pripoj sa na wifi siet s heslom while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(F(".")); } Serial.println(""); Serial.println(F("Wifi pripojene s IP:")); Serial.println(WiFi.localIP()); #endif #if defined(ESP8266) ESP.wdtEnable(30000); //30s SW watchdog #elif defined(ESP32) timer = timerBegin(0, 80, true); //timer 0, div 80 timerAttachInterrupt(timer, &resetModule, true); //attach callback timerAlarmWrite(timer, wdtTimeout * 1000, false); //set time in us timerAlarmEnable(timer); //enable interrupt #endif } void loop() { #if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) wdt_reset(); //Feed watchdog #endif #if defined(ESP32) || defined(ESP8266) yield(); if (WiFi.status() != WL_CONNECTED) { WiFi.begin(ssid, password); //pripoj sa na wifi siet s heslom } while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print(F(".")); } #endif #if defined(ESP8266) ESP.wdtFeed(); //feed watchdog #endif #if defined(ESP32) timerWrite(timer, 0); //reset timer (feed watchdog) #endif if ((millis() - timer2) >= 300000 || timer2 == 0) { timer2 = millis(); int vzdialenost = sonar.ping_cm(); delay(50); if (vzdialenost > 0) { vzdialenost = 0; for (int i = 0; i < 10; i++) { vzdialenost += sonar.ping_cm(); delay(50); } vzdialenost = vzdialenost / 10; Serial.print(F("Vzdialenost medzi senzorom a predmetom je: ")); Serial.print(vzdialenost); Serial.println(F(" cm.")); client.stop(); String data = "hodnota=" + String(vzdialenost) + "&token=123456789"; if (client.connect(host, 80)) { client.println("POST " + url + " HTTP/1.0"); client.println("Host: " + (String)host); client.println(F("User-Agent: MCU")); client.println(F("Connection: close")); client.println(F("Content-Type: application/x-www-form-urlencoded;")); client.print(F("Content-Length: ")); client.println(data.length()); client.println(); client.println(data); Serial.println(F("Data uspesne odoslane na web")); while (client.connected()) { String line = client.readStringUntil('\n'); if (line == "\r") { break; } } String line = client.readStringUntil('\n'); } else { Serial.println(F("Pripojenie zlyhalo...")); delay(500); timer2 = 0; //vynulujeme timer, znovu nameriame a vykoname request } client.stop(); } else { Serial.println(F("Vzdialenost medzi predmetom a senzorom je mimo rozsah.")); delay(500); client.stop(); timer2 = 0; //vynulujeme timer, znovu nameriame a vykoname request } } }
/*|-----------------------------------------------------------------------------------|*/ /*|Projekt: Hladinomer - HTTP - OTA - HC-SR04 / JSN-SR04T / HY-SRF05 |*/ /*|ESP8266 (NodeMCU, Wemos D1 Mini, Generic), ESP32 (DevKit, Generic) |*/ /*|Autor: Martin Chlebovec (martinius96) |*/ /*|E-mail: martinius96@gmail.com |*/ /*|Info k projektu (schéma): https://martinius96.github.io/hladinomer-studna-scripty/ |*/ /*|Testovacie webove rozhranie: http://arduino.clanweb.eu/studna_s_prekladom/ |*/ /*|Knižnica ESP8266NewPing je dostupná v Github repozitári: |*/ /*|https://github.com/martinius96/hladinomer-studna-scripty/ - stihnuť a rozbaliť |*/ /*|Obsah priečinka /src/ nakopírovať do C:/Users/User/Dokumenty/Arduino/libraries/ |*/ /*|Na toto webove rozhranie posiela mikrokontroler data |*/ /*|Na zaklade zvolenej platformy v Arduino IDE sa vykona kompilacia podla direktiv |*/ /*|Licencia pouzitia: MIT |*/ /*|Revízia: 26. Februar 2021 |*/ /*|-----------------------------------------------------------------------------------|*/ #include <WiFiUdp.h> #include <ArduinoOTA.h> #include <NewPingESP8266.h>const char * ssid = "WIFI_MENO_SIETE"; //MENO WiFi SIETE const char * password = "WIFI_HESLO_SIETE"; //HESLO WiFi SIETE
const char* host = "arduino.clanweb.eu"; //adresa webservera (doména) na ktorú sa odosielajú dáta String url = "/studna_s_prekladom/data.php"; //URL adresa - cesta pod domenou k cieľovemu .php súboru, ktorý realizuje zápis //Pre testovacie webove rozhranie sa data odosielaju na: arduino.clanweb.eu/studna_s_prekladom/data.php (HTTP POST ONLY) unsigned long timer2 = 0; #if defined(ESP32) #include <WiFi.h> #include <ESPmDNS.h> #include "esp_system.h" #define pinTrigger 22 #define pinEcho 23 #define maxVzdialenost 450 NewPingESP8266 sonar(pinTrigger, pinEcho, maxVzdialenost); const int wdtTimeout = 30000; //time in ms to trigger the watchdog hw_timer_t *timer = NULL; void IRAM_ATTR resetModule() { ets_printf("reboot\n"); esp_restart(); } #elif defined(ESP8266) #include <ESP8266WiFi.h> #include <ESP8266mDNS.h> #include <ArduinoOTA.h> #include <NewPingESP8266.h> #define pinTrigger 5 //D1 #define pinEcho 4 //D2 #define maxVzdialenost 450 NewPingESP8266 sonar(pinTrigger, pinEcho, maxVzdialenost); #endif WiFiClient client; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); //pripoj sa na wifi siet s heslom while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } ArduinoOTA.onStart([]() { Serial.println(F("Start")); }); ArduinoOTA.onEnd([]() { Serial.println(F("\nEnd")); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); }); ArduinoOTA.begin(); Serial.println(F("")); Serial.println(F("Wifi pripojene s IP:")); Serial.println(WiFi.localIP()); #if defined(ESP32) timer = timerBegin(0, 80, true); //timer 0, div 80 timerAttachInterrupt(timer, &resetModule, true); //attach callback timerAlarmWrite(timer, wdtTimeout * 1000, false); //set time in us timerAlarmEnable(timer); //enable interrupt #elif defined(ESP8266) ESP.wdtEnable(30000); #endif } void loop() { if (WiFi.status() != WL_CONNECTED) { WiFi.begin(ssid, password); //pripoj sa na wifi siet s heslom } while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } #if defined(ESP32) timerWrite(timer, 0); //reset timer (feed watchdog) #elif defined(ESP8266) ESP.wdtFeed(); #endif ArduinoOTA.handle(); yield(); if ((millis() - timer2) >= 300000 || timer2 == 0) { timer2 = millis(); int vzdialenost = sonar.ping_cm(); delay(50); if (vzdialenost > 0) { vzdialenost = 0; for (int i = 0; i < 10; i++) { vzdialenost += sonar.ping_cm(); delay(50); } vzdialenost = vzdialenost / 10; Serial.print(F("Vzdialenost medzi senzorom a predmetom je: ")); Serial.print(vzdialenost); Serial.println(F(" cm.")); String data = "hodnota=" + String(vzdialenost) + "&token=123456789"; if (client.connect(host, 80)) { client.println("POST " + url + " HTTP/1.0"); client.println("Host: " + (String)host); client.println(F("User-Agent: ESP")); client.println(F("Connection: close")); client.println(F("Content-Type: application/x-www-form-urlencoded;")); client.print(F("Content-Length: ")); client.println(data.length()); client.println(); client.println(data); Serial.println(F("Data uspesne odoslane na web")); while (client.connected()) { String line = client.readStringUntil('\n'); if (line == "\r") { break; } } String line = client.readStringUntil('\n'); } else { Serial.println(F("Pripojenie zlyhalo...")); delay(500); timer2 = 0; //reset pocitadla, vykoname opakovany request } } else { Serial.println(F("Vzdialenost medzi predmetom a senzorom je mimo rozsah.")); delay(500); timer2 = 0; //reset pocitadla, vykoname opakovany request } client.stop(); } }
/*|-----------------------------------------------------------------------------------|*/ /*|Projekt: Hladinomer - HTTP - ULP - DEEP SLEEP - HC-SR04 / JSN-SR04T / HY-SRF05 |*/ /*|ESP8266 (NodeMCU, Wemos D1 Mini, Generic), ESP32 (DevKit, Generic) |*/ /*|Autor: Martin Chlebovec (martinius96) |*/ /*|E-mail: martinius96@gmail.com |*/ /*|Info k projektu (schéma): https://martinius96.github.io/hladinomer-studna-scripty/ |*/ /*|Testovacie webove rozhranie: http://arduino.clanweb.eu/studna_s_prekladom/ |*/ /*|Knižnica ESP8266NewPing je dostupná v Github repozitári: |*/ /*|https://github.com/martinius96/hladinomer-studna-scripty/ - stihnuť a rozbaliť |*/ /*|Obsah priečinka /src/ nakopírovať do C:/Users/User/Dokumenty/Arduino/libraries/ |*/ /*|Na toto webove rozhranie posiela mikrokontroler data |*/ /*|Na zaklade zvolenej platformy v Arduino IDE sa vykona kompilacia podla direktiv |*/ /*|Licencia pouzitia: MIT |*/ /*|Revízia: 26. Februar 2021 |*/ /*|-----------------------------------------------------------------------------------|*/const char * ssid = "WIFI_MENO_SIETE"; //MENO WiFi SIETE const char * password = "WIFI_HESLO_SIETE"; //HESLO WiFi SIETE
const char* host = "arduino.clanweb.eu"; //adresa webservera (doména) na ktorú sa odosielajú dáta String url = "/studna_s_prekladom/data.php"; //URL adresa - cesta pod domenou k cieľovemu .php súboru, ktorý realizuje zápis //Pre testovacie webove rozhranie sa data odosielaju na: arduino.clanweb.eu/studna_s_prekladom/data.php (HTTP POST ONLY) #include <NewPingESP8266.h> #if defined(ESP32) #define uS_TO_S_FACTOR 1000000 /* Conversion factor for micro seconds to seconds */ #define TIME_TO_SLEEP 300 /* Time ESP32 will go to sleep (in seconds) */ #include <WiFi.h> #define pinTrigger 22 #define pinEcho 23 #define maxVzdialenost 450 #elif defined(ESP8266) #include <ESP8266WiFi.h> #define pinTrigger 5 //D1 #define pinEcho 4 //D2 #define maxVzdialenost 450 #endif NewPingESP8266 sonar(pinTrigger, pinEcho, maxVzdialenost); WiFiClient client; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); //pripoj sa na wifi siet s heslom while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print(F(".")); } Serial.println(F("")); Serial.println(F("Wifi pripojene s IP:")); Serial.println(WiFi.localIP()); int vzdialenost = sonar.ping_cm(); delay(50); if (vzdialenost > 0) { vzdialenost = 0; for (int i = 0; i < 10; i++) { vzdialenost += sonar.ping_cm(); delay(50); } vzdialenost = vzdialenost / 10; Serial.print(F("Vzdialenost medzi senzorom a predmetom je: ")); Serial.print(vzdialenost); Serial.println(F(" cm.")); String data = "hodnota=" + String(vzdialenost) + "&token=123456789"; client.stop(); if (client.connect(host, 80)) { client.println("POST " + url + " HTTP/1.0"); client.println("Host: " + (String)host); client.println(F("User-Agent: ESP")); client.println(F("Connection: close")); client.println(F("Content-Type: application/x-www-form-urlencoded;")); client.print(F("Content-Length: ")); client.println(data.length()); client.println(); client.println(data); Serial.println(F("Data uspesne odoslane na web")); while (client.connected()) { String line = client.readStringUntil('\n'); if (line == "\r") { break; } } String line = client.readStringUntil('\n'); } else { Serial.println(F("Pripojenie zlyhalo...")); } } else { Serial.println(F("Vzdialenost medzi predmetom a senzorom je mimo rozsah.")); } client.stop(); #if defined(ESP32) esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR); Serial.println("Setup ESP32 to sleep for every " + String(TIME_TO_SLEEP) + " Seconds"); esp_deep_sleep_start(); #elif defined(ESP8266) Serial.println(F("Entering deep sleep mode for 300 seconds")); ESP.deepSleep(300e6); #endif } void loop() { }
/*|----------------------------------------------------------------------------|*/ /*|Project: Ultrasonic water level monitor - HC-SR04 / JSN-SR04T / HY-SRF05... |*/ /*|ESP32 (DevKit, Generic) + PHY Ethernet LAN8720 / TLK110, RMII interface |*/ /*|Author: Martin Chlebovec (martinius96) |*/ /*|E-mail: martinius96@gmail.com |*/ /*|Buy me a coffee at: paypal.me/chlebovec |*/ /*|Project info: https://martinius96.github.io/hladinomer-studna-scripty/en |*/ /*|Test web interface: http://arduino.clanweb.eu/studna_s_prekladom/?lang=en |*/ /*|Revision: 8. September 2022 |*/ /*|----------------------------------------------------------------------------|*/ #include <ETH.h> #include <NewPingESP8266.h> const char* host = "arduino.clanweb.eu"; //webhost String url = "/studna_s_prekladom/data.php"; //URL address to target PHP file boolean eth_state = false; #define pinTrigger 4 //CONNECT TO TRIGGER PIN OF ULTRASONIC SENSOR #define pinEcho 5 //CONNECT TO ECHO PIN OF ULTRASONIC SENSOR #define maxVzdialenost 450 NewPingESP8266 sonar(pinTrigger, pinEcho, maxVzdialenost); /* ETH_CLOCK_GPIO0_IN - default: external clock from crystal oscillator ETH_CLOCK_GPIO0_OUT - 50MHz clock from internal APLL output on GPIO0 - possibly an inverter is needed for LAN8720 ETH_CLOCK_GPIO16_OUT - 50MHz clock from internal APLL output on GPIO16 - possibly an inverter is needed for LAN8720 ETH_CLOCK_GPIO17_OUT - 50MHz clock from internal APLL inverted output on GPIO17 - tested with LAN8720 */ #ifdef ETH_CLK_MODE #undef ETH_CLK_MODE #endif #define ETH_CLK_MODE ETH_CLOCK_GPIO17_OUT // Pin# of the enable signal for the external crystal oscillator (-1 to disable for internal APLL source) #define ETH_POWER_PIN -1 // Type of the Ethernet PHY (LAN8720 or TLK110) #define ETH_TYPE ETH_PHY_LAN8720 // I²C-address of Ethernet PHY (0 or 1 for LAN8720, 31 for TLK110) #define ETH_ADDR 1 // Pin# of the I²C clock signal for the Ethernet PHY, DONT USE THIS PIN FOR ultrasonic sensor in this sketch #define ETH_MDC_PIN 23 // Pin# of the I²C IO signal for the Ethernet PHY #define ETH_MDIO_PIN 18 TaskHandle_t Task1; //ULTRASONIC MEASUREMENT TaskHandle_t Task2; //PHY ETHERNET HTTP SOCKET QueueHandle_t q = NULL; WiFiClient client; static void Task1code( void * parameter); static void Task2code( void * parameter); void WiFiEvent(WiFiEvent_t event); void setup() { Serial.begin(115200); WiFi.onEvent(WiFiEvent); ETH.begin(ETH_ADDR, ETH_POWER_PIN, ETH_MDC_PIN, ETH_MDIO_PIN, ETH_TYPE, ETH_CLK_MODE); delay(5000); q = xQueueCreate(20, sizeof(int)); if (q != NULL) { Serial.println(F("Queue FIFO buffer is created")); vTaskDelay(1000 / portTICK_PERIOD_MS); //wait for a second xTaskCreatePinnedToCore( Task1code, /* Task function. */ "Task1", /* name of task. */ 10000, /* Stack size of task */ NULL, /* parameter of the task */ 1, /* priority of the task */ &Task1, /* Task handle to keep track of created task */ 1); /* pin task to core 1 */ Serial.println(F("Ultrasonic measurement task started")); xTaskCreatePinnedToCore( Task2code, /* Task function. */ "Task2", /* name of task. */ 10000, /* Stack size of task */ NULL, /* parameter of the task */ 1, /* priority of the task */ &Task2, /* Task handle to keep track of created task */ 0); /* pin task to core 0 */ Serial.println(F("HTTP Socket task started")); } else { Serial.println(F("Queue creation failed")); } } void loop() { yield(); } static void Task1code( void * parameter) { if (q == NULL) { Serial.println(F("Queue in Measurement task is not ready")); return; } while (1) { int distance = sonar.ping_cm(); delay(50); Serial.print(F("Test measurement: ")); Serial.print(distance); Serial.println(F(" cm")); if (distance > 0) { distance = 0; for (int i = 0; i < 10; i++) { distance += sonar.ping_cm(); delay(50); } distance = distance / 10; Serial.print(F("Distance to water level is: ")); Serial.print(distance); Serial.println(F(" cm.")); xQueueSend(q, (void *)&distance, (TickType_t )0); //add the measurement value to Queue for (int countdown = 300; countdown >= 0; countdown--) { Serial.print(F("Next measurement in: ")); Serial.print(countdown); Serial.println(F(" seconds")); vTaskDelay(1000 / portTICK_PERIOD_MS); } } } } static void Task2code( void * parameter) { int distance; if (q == NULL) { Serial.println(F("Queue in HTTP socket task is not ready")); return; } while (1) { xQueuePeek(q, &distance, portMAX_DELAY); //read measurement value from Queue and run code below, if no value, WAIT.... String data = "hodnota=" + String(distance) + "&token=123456789"; client.stop(); while (eth_state != true) { vTaskDelay(1 / portTICK_PERIOD_MS); } if (client.connect(host, 80)) { Serial.println(F("Connected to server successfully")); client.println("POST " + url + " HTTP/1.0"); client.println("Host: " + (String)host); client.println(F("User-Agent: ESP")); client.println(F("Connection: close")); client.println(F("Content-Type: application/x-www-form-urlencoded;")); client.print(F("Content-Length: ")); client.println(data.length()); client.println(); client.println(data); Serial.println(F("Datas were sent to server successfully")); xQueueReset(q); //EMPTY QUEUE, IF REQUEST WAS SUCCESSFUL, OTHERWISE RUN REQUEST AGAIN while (client.connected()) { String line = client.readStringUntil('\n'); if (line == "\r") { break; } } String line = client.readStringUntil('\n'); } else { Serial.println(F("Connection to webserver was NOT successful")); } yield(); client.stop(); } } void WiFiEvent(WiFiEvent_t event) { switch (event) { case ARDUINO_EVENT_ETH_START: eth_state = false; Serial.println("ETH Started"); //set eth hostname here ETH.setHostname("esp32-ethernet"); break; case ARDUINO_EVENT_ETH_CONNECTED: eth_state = false; Serial.println("ETH Connected"); break; case ARDUINO_EVENT_ETH_GOT_IP: eth_state = true; Serial.print("ETH MAC: "); Serial.print(ETH.macAddress()); Serial.print(", IPv4: "); Serial.print(ETH.localIP()); if (ETH.fullDuplex()) { Serial.print(", FULL_DUPLEX"); } Serial.print(", "); Serial.print(ETH.linkSpeed()); Serial.println("Mbps"); break; case ARDUINO_EVENT_ETH_DISCONNECTED: eth_state = false; Serial.println("ETH Disconnected"); break; case ARDUINO_EVENT_ETH_STOP: eth_state = false; Serial.println("ETH Stopped"); break; default: break; } }
/*|-----------------------------------------------------------------------------------|*/ /*|Projekt: Hladinomer - HTTP - HC-SR04 / JSN-SR04T / HY-SRF05 |*/ /*|ESP32 (DevKit, Generic) - ESP-IDF v4.2 (4.0 compatible) |*/ /*|Autor: Martin Chlebovec (martinius96) |*/ /*|E-mail: martinius96@gmail.com |*/ /*|Info k projektu (schéma): https://martinius96.github.io/hladinomer-studna-scripty/ |*/ /*|Testovacie webove rozhranie: http://arduino.clanweb.eu/studna_s_prekladom/ |*/ /*|Revízia: 4. Jun 2021 |*/ /*|-----------------------------------------------------------------------------------|*/ //Header files, full project: https://github.com/martinius96/hladinomer-studna-scripty/tree/master/examples/Hladinomer/HTTP/ESP-IDF #include <string.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "esp_system.h" #include "esp_wifi.h" #include "esp_event.h" #include "esp_log.h" #include "nvs_flash.h" #include "protocol_examples_common.h" #include "lwip/err.h" #include "lwip/sockets.h" #include "lwip/sys.h" #include "lwip/netdb.h" #include "lwip/dns.h" #include "ultrasonic.h" #include "driver/dac.h" /* Constants that aren't configurable in menuconfig */ #define MAX_DISTANCE_CM 450 // 5m max #define GPIO_TRIGGER 22 #define GPIO_ECHO 23 // Webserver #define WEB_SERVER "arduino.clanweb.eu" #define WEB_PORT "80" static const char *TAG = "http_request"; static const char *TAG2 = "ultrasonic_measurement"; QueueHandle_t q=NULL; static void ultrasonic(void *pvParamters) { ultrasonic_sensor_t sensor = { .trigger_pin = GPIO_TRIGGER, .echo_pin = GPIO_ECHO }; ultrasonic_init(&sensor); uint32_t distance = 0; if(q == NULL){ printf("Queue is not ready \n"); return; } while (true) { uint32_t avg_distance = 0; int index_loop = 1; while(index_loop<=10){ esp_err_t res = ultrasonic_measure_cm(&sensor, MAX_DISTANCE_CM, &distance); if (res != ESP_OK) { printf("Error: "); switch (res) { case ESP_ERR_ULTRASONIC_PING: printf("Cannot ping (device is in invalid state)\n"); break; case ESP_ERR_ULTRASONIC_PING_TIMEOUT: printf("Ping timeout (no device found)\n"); break; case ESP_ERR_ULTRASONIC_ECHO_TIMEOUT: printf("Echo timeout (i.e. distance too big)\n"); break; default: printf("%d\n", res); } } else { printf("Measurement %d: %d cm\n", index_loop, distance); avg_distance += distance; index_loop++; } } avg_distance = avg_distance / 10; distance = avg_distance; xQueueSend(q,(void *)&distance,(TickType_t )0); // add the counter value to the queue for(int countdown = 300; countdown >= 0; countdown--) { ESP_LOGI(TAG2, "%d... ", countdown); vTaskDelay(1000 / portTICK_PERIOD_MS); } } } static void http_get_task(void *pvParameters) { const struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_STREAM, }; struct addrinfo *res; struct in_addr *addr; int s, r; char recv_buf[64]; uint32_t distance; if(q == NULL){ printf("Queue is not ready \n"); return; } while(1) { xQueueReceive(q,&distance,portMAX_DELAY); char REQUEST [1000]; char values [250]; sprintf(values, "hodnota=%d&token=123456789", distance); sprintf (REQUEST, "POST /studna_s_prekladom/data.php HTTP/1.0\r\nHost: "WEB_SERVER"\r\nUser-Agent: ESP32\r\nConnection: close\r\nContent-Type: application/x-www-form-urlencoded;\r\nContent-Length:%d\r\n\r\n%s\r\n",strlen(values),values); int err = getaddrinfo(WEB_SERVER, WEB_PORT, &hints, &res); if(err != 0 || res == NULL) { ESP_LOGE(TAG, "DNS lookup failed err=%d res=%p", err, res); vTaskDelay(1000 / portTICK_PERIOD_MS); continue; } /* Code to print the resolved IP. Note: inet_ntoa is non-reentrant, look at ipaddr_ntoa_r for "real" code */ addr = &((struct sockaddr_in *)res->ai_addr)->sin_addr; ESP_LOGI(TAG, "DNS lookup succeeded. IP=%s", inet_ntoa(*addr)); s = socket(res->ai_family, res->ai_socktype, 0); if(s < 0) { ESP_LOGE(TAG, "... Failed to allocate socket."); freeaddrinfo(res); vTaskDelay(1000 / portTICK_PERIOD_MS); continue; } ESP_LOGI(TAG, "... allocated socket"); if(connect(s, res->ai_addr, res->ai_addrlen) != 0) { ESP_LOGE(TAG, "... socket connect failed errno=%d", errno); close(s); freeaddrinfo(res); vTaskDelay(4000 / portTICK_PERIOD_MS); continue; } ESP_LOGI(TAG, "... connected"); freeaddrinfo(res); if (write(s, REQUEST, strlen(REQUEST)) < 0) { ESP_LOGE(TAG, "... socket send failed"); close(s); vTaskDelay(4000 / portTICK_PERIOD_MS); continue; } ESP_LOGI(TAG, "... socket send success"); struct timeval receiving_timeout; receiving_timeout.tv_sec = 5; receiving_timeout.tv_usec = 0; if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &receiving_timeout, sizeof(receiving_timeout)) < 0) { ESP_LOGE(TAG, "... failed to set socket receiving timeout"); close(s); vTaskDelay(4000 / portTICK_PERIOD_MS); continue; } ESP_LOGI(TAG, "... set socket receiving timeout success"); /* Read HTTP response */ do { bzero(recv_buf, sizeof(recv_buf)); r = read(s, recv_buf, sizeof(recv_buf)-1); for(int i = 0; i < r; i++) { putchar(recv_buf[i]); } } while(r > 0); ESP_LOGI(TAG, "... done reading from socket. Last read return=%d errno=%d.", r, errno); close(s); ESP_LOGI(TAG, "Starting again!"); } } void app_main(void) { ESP_ERROR_CHECK( nvs_flash_init() ); ESP_ERROR_CHECK(esp_netif_init()); ESP_ERROR_CHECK(esp_event_loop_create_default()); /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. * Read "Establishing Wi-Fi or Ethernet Connection" section in * examples/protocols/README.md for more information about this function. */ ESP_ERROR_CHECK(example_connect()); q=xQueueCreate(20,sizeof(unsigned long)); if(q != NULL){ printf("Queue is created\n"); vTaskDelay(1000/portTICK_PERIOD_MS); //wait for a second xTaskCreate(&ultrasonic, "ultrasonic", 2048, NULL, 5, NULL); printf("producer task started\n"); xTaskCreate(&http_get_task, "http_get_task", 4096, NULL, 5, NULL); printf("consumer task started\n"); }else{ printf("Queue creation failed"); } }