Управление платой ESP8266 через интернет с хостинга

В сети много примеров для подключения веб интерфейса на ESP8266, но очень мало примеров работы с хостингом.

Этот скетч покажет как достучатся к сайту и получить данные с него. Схема примерно выглядит как на рисунке.

Ну а дальше полет вашей фантазии, это может быть часть умного дома или просто вывод на сенсор данных с сайта.

#include <ESP8266WiFi.h>

#ifndef STASSID
#define STASSID "namewifi"//имя вашего WiFi
#define STAPSK  "passwifi"//Пароль вашего WiFi
#endif

const char* ssid     = STASSID;
const char* password = STAPSK;

const char* host = "host.ru"; //адрес домена скрипта
const uint16_t port = 80;

void setup() {
  Serial.begin(115200);
  pinMode (13, OUTPUT);
  digitalWrite(13, LOW);
  delay(100);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  /* Explicitly set the ESP8266 to be a WiFi-client, otherwise, it by default,
     would try to act as both a client and an access-point and could cause
     network-issues with your other WiFi-devices on your WiFi-network. */
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  Serial.print("connecting to ");
  Serial.print(host);
  Serial.print(':');
  Serial.println(port);
  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  if (!client.connect(host, port)) {
    Serial.println("connection failed");
    delay(5000);
    return;
  }
  // This will send a string to the server
  Serial.println("sending data to server");
  
  if (client.connected()) {
    client.print("POST /getdata.php?data=");
    client.print("1");
    client.println(" HTTP/1.1");
    client.println("Host: host.ru");
    client.println(""); //mandatory blank line
  } 
  else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  // wait for data to be available
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      delay(60000);
      return;
    }
  }
  // Прочитайте все строки ответа с сервера и распечатайте их в Serial
  Serial.println("receiving from remote server");
  // not testing 'client.connected()' since we do not need to send data here
 while (client.connected()) {
      String line = client.readStringUntil('\n');
      if (line.startsWith("pin13:1")) {
        Serial.println("esp8266 - Pin13 = 1");
        //digitalWrite (13, HIGH);
      } else if(line.startsWith("pin13:0")){
        Serial.println("esp8266 - Pin13 = 0");
        //digitalWrite(13, LOW);
      }
      
      //Serial.println(line); //выведет все линии со скрипта
  }
  Serial.println("closing connection");// Close the connection
  client.stop();

  delay(10000); // execute once every 10 sekund, don't flood remote service
}

 

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest
0 комментариев
Межтекстовые Отзывы
Посмотреть все комментарии
× iOs app

To install this Web App in your iPhone/iPad press iOs sourse and then Add to Home Screen.