To get API keys register at https://thingspeak.com/ and then on its twitter app on https://thingspeak.com/apps/thingtweet
Code
//nodeMCU v1.0 (black) with Arduino IDE
//nodemcu pinout https://github.com/esp8266/Arduino/issues/584
#include <ESP8266WiFi.h>
#include <pins_arduino.h>
#define myPeriodic 15 //in sec | Thingspeak pub is 15sec
long min=0;
int PIRpin = 14;
int PIRvalue=0;
const char* server = "api.thingspeak.com";
String apiKey ="Your-api-key";
String api_key_ts="your-api-key-ts";
const char* MY_SSID = "wifi=ssid";
const char* MY_PWD = "password";
int failedCounter = 0;
long lastConnectionTime = 0;
boolean lastConnected = false;
int sent = 0;
void setup() {
pinMode(PIRpin, INPUT);
Serial.begin(115200);
connectWifi();
}
void loop() {
PIRvalue=digitalRead(PIRpin);
if (PIRvalue==HIGH){
Serial.println(String(sent)+"Motion detected ");
sendMotion(PIRvalue);
updateTwitterStatus("My thing is social @thingspeak, Motion detected, possible intruder!");
int count = myPeriodic;
while(count--)
delay(1000);}
else{
Serial.println(String(sent)+"Motion NOT detected ");
sendMotion(PIRvalue);
int count = myPeriodic;
while(count--)
delay(1000);}
}
void connectWifi()
{
Serial.print("Connecting to "+*MY_SSID);
WiFi.begin(MY_SSID, MY_PWD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("Connected");
Serial.println("");
}//end connect
void sendMotion(int PIRv)
{
WiFiClient client;
if (client.connect(server, 80)) { // use ip 184.106.153.149 or api.thingspeak.com
Serial.println("WiFi Client connected ");
String postStr = apiKey;
postStr += "&field1=";
postStr += String(PIRv);
postStr += "\r\n\r\n";
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);
delay(1000);
}//end if
sent++;
client.stop();
}//end send
void updateTwitterStatus(String tsData)
{
WiFiClient client;
if (client.connect(server, 80))
{ Serial.println("WiFi Client connected to thingSpeak ");
// Create HTTP POST Data
min =millis()/(1000);
tsData = min+tsData;
tsData = "api_key="+api_key_ts+"&status="+tsData;
client.print("POST /apps/thingtweet/1/statuses/update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(tsData.length());
client.print("\n\n");
client.print(tsData);
if (client.connected())
{
Serial.println("Connecting to ThingSpeak/thingtweet...");
Serial.println();
}
}
}
This comment has been removed by the author.
ReplyDeletethere are three fields for api keys which keys have to be used where ?
ReplyDelete