This code uploads an analog value to the Things speak IOT server with the ESP8266 wifi module. Make sure to change the key to the data stream.

Dependencies:   ESP8266 mbed

main.cpp

Committer:
janhavi
Date:
2016-05-23
Revision:
0:a42b121ce25a

File content as of revision 0:a42b121ce25a:

#include "mbed.h"
#include "ESP8266.h"

Serial pc(USBTX,USBRX);
AnalogIn inputPin(A2); // temp
ESP8266 wifi(PTE0, PTE1, 115200); // baud rate for wifi
char snd[255],rcv[1000];
 
#define IP "184.106.153.149" // thingspeak.com IP Address
 
float val; // value to holed the high/low info from pir from pin D2
int cnt = 0; // counter for motion

 
/************ WiFi INTIALIZATION *********/
 
void wifi_send(void);
 
int main () {
    
pc.baud(9600);   
pc.printf("SET mode to AP\r\n");
wifi.SetMode(1);    // set ESP mode to 1
wifi.RcvReply(rcv, 1000);    //receive a response from ESP
pc.printf("%s",rcv);    //Print the response onscreen
pc.printf("Conneting to AP\r\n");
wifi.Join("Eduvance_WiFi", "eduvance");     // Your wifi username & Password 
wifi.RcvReply(rcv, 1000);    //receive a response from ESP
pc.printf("%s", rcv);    //Print the response onscreen
wait(8);  //waits for response from ESP
pc.printf("Getting IP\r\n");    //get IP addresss from the connected AP
wifi.GetIP(rcv);    //receive an IP address from the AP
pc.printf("%s", rcv);    
wait(5); // Delay 5 sec to give the pir time to get snapshut of the surrounding
pc.printf("Initializing WiFi\r\n");
while (1) {
       
   val = inputPin.read();
   pc.printf(" The Sensor is ON And I Detected = %i Till NOW\r\n",cnt);
    pc.printf("Sending WiFi information\n\r");
    wifi_send();
    cnt++;
          }
    }
 
void wifi_send(void){
   
   strcpy(snd,"AT+CIPMODE=0");//Setting WiFi into MultiChannel mode
  wifi.SendCMD(snd);
    pc.printf(snd);
  wifi.RcvReply(rcv, 3000);
  pc.printf("%s", rcv);
  
  //WIFI updates the Status to Thingspeak servers//
  strcpy(snd,"AT+CIPMUX=1");//Setting WiFi into MultiChannel mode
  wifi.SendCMD(snd);
  pc.printf(snd);
  wifi.RcvReply(rcv, 3000);
  pc.printf("%s", rcv);
  
  
  sprintf(snd,"AT+CIPSTART=4,\"TCP\",\"%s\",80",IP); //Initiate connection with THINGSPEAK server 
  wifi.SendCMD(snd);
  pc.printf(snd);
  wifi.RcvReply(rcv, 3000);
  pc.printf("%s", rcv);
 
  strcpy(snd,"AT+CIPSEND=4,46");    //Send Number of open connections,Characters to send 
  wifi.SendCMD(snd);
  pc.printf(snd);
  wifi.RcvReply(rcv, 3000);
  pc.printf("%s", rcv);
  
    
  sprintf(snd,"GET /update?key=4CDAJHYQ6JDNJC5G&field1=%2.2f\r\n",val); //Post values to thingspeak
  pc.printf("String length %3d\r\n",strlen(snd));
  pc.printf("%s",snd);
  wifi.SendCMD(snd);
  wifi.RcvReply(rcv, 3000);
  pc.printf("%s", rcv);
  
  //wifi.SendCMD("AT+CIPCLOSE"); //Close the connection to server
  //wifi.RcvReply(rcv, 3000);
  //pc.printf("%s", rcv);
}