moty
Published

IoT with ESP8266

Remotely switch things and read data using ESP8266 Arduino and your website.

IntermediateFull instructions provided3,893
IoT with ESP8266

Things used in this project

Story

Read more

Schematics

wifi_iot

Code

iot_wifi

C/C++
// Simple IoT using ESP8266 and your website
// for more inf see moty22.co.uk

#include <SoftwareSerial.h>
SoftwareSerial wifi(6, 5);      // RX, TX for ESP8266

  
  int analog=0, i=0;
  String msg, host, d1;
 
const int str_len = 100;
char str_data[str_len]; 
const char end_c = '*', start_c = '%'; //marking the data part of the website reply
  
void setup()
{
  
  pinMode(7,OUTPUT);
  pinMode(3,INPUT_PULLUP);
  wifi.begin(9600); //software serial
  Serial.begin(9600);
 // wifi.listen();
  
  wifi.println("AT+RST"); //reset wifi
  delay(2000);
  wifi.println("AT+CWMODE=1");  //station mode
  delay(1000);
   //connect to AP, ADD YOUR ROUTER SSID and PASSWORD
  wifi.println("AT+CWJAP=\"SSID\",\"PASSWORD\"");
  delay(10000);
  
}
 
void loop()
{
    ++i;
    if(i=2000){ 
    analog = analogRead(A0);
    if(digitalRead(3)) {d1 = "OFF";} else {d1 = "ON";}

      //GET request of a website page a31.php 
    msg = "GET /a31.php?v1=" + String(highByte(analog)) + "&v2=" + String(lowByte(analog)) + "&v3=" + d1 + " HTTP/1.1";
    host = "HOST: moty22.co.uk";  //change to your website address
    
    wifi.println("AT+CIPSTART=\"TCP\",\"moty22.co.uk\",80");  //change to your website address
    delay(1000);
    wifi.println("AT+CIPSEND=" + String(msg.length() + host.length() + 6));
    delay(1000);
    
    wifi.println(msg);
    wifi.println(host);
    wifi.println("");
    i=0;
    }
      //get reply from website
    get_str();
    Serial.println(str_data);
    if(find(str_data,"output=ON")){digitalWrite(7, HIGH); Serial.println("output=ON");} 
    if(find(str_data,"output=OFF")){digitalWrite(7, LOW); Serial.println("output=OFF");}
    delay(10000);
    
}

boolean find(String string, String toFind){
  if(string.indexOf(toFind)>=0) return true;
    
  return false;
}

void get_str(){
  int i = 0;
  bool begin_str=0;
    
  char c = read_c();
  while(c != end_c){
    if(i >= str_len) break;
    if(c == start_c) { begin_str=1;}  
    if (begin_str) {
      str_data[i] = c; 
      i++;
    }
    c = read_c();
    
  }
  str_data[i] = '\0';
}

char read_c(){
  while(!wifi.available());
  return wifi.read();
}

Credits

moty

moty

12 projects • 63 followers

Comments