| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118 |
- #include <ESP8266WiFi.h>
- #include <WiFiClient.h>
- #include <ESP8266WebServer.h>
- #include <ESP8266mDNS.h>
- #include <SimpleTimer.h>
- MDNSResponder mdns;
- // Replace with your network credentials
- const char* ssid = "hazard18";
- const char* password = "pu1f0xylu1";
- // Host
- const char* host = "dweet.io";
- SimpleTimer timer;
- ESP8266WebServer server(80);
- // Pin
- #define LIGHTSENSOR A0
- String webPage = "";
- int gpio2_pin = 2;
- boolean done = false;
- void setup(void){
- webPage += "<h1>ESP8266 Web Server</h1><p>Socket #1 <a href=\"socket1On\"><button>ON</button></a> <a href=\"socket1Off\"><button>OFF</button></a></p>";
- webPage += "<p>Socket #2 <a href=\"socket2On\"><button>ON</button></a> <a href=\"socket2Off\"><button>OFF</button></a></p>";
- // prepare timer
- timer.setInterval(5000, reportLightIntensity);
-
-
-
- Serial.begin(115200);
- delay(100);
-
- WiFi.begin(ssid, password);
- Serial.println("Connecting...");
- // Wait for connection
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("");
- Serial.print("Connected to ");
- Serial.println(ssid);
- Serial.print("IP address: ");
- Serial.println(WiFi.localIP());
-
- if (mdns.begin("esp8266", WiFi.localIP())) {
- Serial.println("MDNS responder started");
- }
- // preparing GPIOs
- pinMode(gpio2_pin, OUTPUT);
- digitalWrite(gpio2_pin, LOW);
- delay(1000);
- server.on("/", [](){
- server.send(200, "text/html", webPage);
- });
- server.on("/socket2On", [](){
- server.send(200, "text/html", webPage);
- digitalWrite(gpio2_pin, HIGH);
- delay(1000);
- });
- server.on("/socket2Off", [](){
- server.send(200, "text/html", webPage);
- digitalWrite(gpio2_pin, LOW);
- delay(1000);
- });
- server.begin();
- Serial.println("HTTP server started");
- }
- void reportLightIntensity(){
- // Use WiFiClient class to create TCP connections
- WiFiClient client;
- const int httpPort = 80;
- if (!client.connect(host, httpPort)) {
- Serial.println("connection failed");
- return;
- }
- int h = (unsigned int) analogRead(LIGHTSENSOR);
- Serial.println("a0 val: " + String(h));
-
- // This will send the request to the server
- client.print(String("GET /dweet/for/esp1881?light_intensity=") + String(h) + " HTTP/1.1\r\n" +
- "Host: " + host + "\r\n" +
- "Connection: close\r\n\r\n");
- delay(10);
-
- // Read all the lines of the reply from server and print them to Serial
- while(client.available()){
- String line = client.readStringUntil('\r');
- Serial.print(line);
- }
-
- Serial.println();
- Serial.println("closing connection");
-
- }
-
- void loop(void){
-
- server.handleClient();
- timer.run();
- }
|