Advertisement
Guest User

ThingSpeak-ArduinoExample-Wifi

a guest
Nov 8th, 2015
156
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.93 KB | None | 0 0
  1.  #include <WiFi.h>
  2.  #include <SPI.h>
  3.  
  4. char thingSpeakAddress[] = "api.thingspeak.com";
  5. String writeAPIKey = "[chave_de_escrita]";
  6. const int updateThingSpeakInterval = 17 * 1000;
  7.  
  8. char ssid[] = "[nome_da_rede]";
  9. char pass[] = "[senha_da_rede]";
  10.  
  11. int status = WL_IDLE_STATUS;
  12. WiFiClient client;
  13. String stringVal = "";
  14.  
  15. long lastConnectionTime = 0;
  16. boolean lastConnected = false;
  17. int failedCounter = 0;
  18.  
  19. void setup() {
  20.   Serial.begin(115200);
  21.  
  22.   while (status != WL_CONNECTED) {
  23.     Serial.print("Conectando...");
  24.     status = WiFi.begin(ssid, pass);
  25.     delay(5000);
  26.   }
  27.  
  28.   Serial.println("Conexão realizada com sucesso!");
  29. }
  30.  
  31. void loop() {
  32.  
  33.   while (client.available()) {
  34.     char c = client.read();
  35.     Serial.print(c);
  36.   }
  37.  
  38.   if (!client.connected() && lastConnected ) {
  39.     Serial.println("...disconnected");
  40.     Serial.println();
  41.     client.stop();
  42.   }
  43.  
  44.   if(!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))
  45.     updateThingSpeak("field1=teste");
  46.   lastConnected = client.connected();
  47. }
  48.  
  49. void updateThingSpeak(String  tsdata) {
  50.   if (client.connect(thingSpeakAddress, 80)) {        
  51.     client.print("POST /update HTTP/1.1\n");
  52.     client.print("Host: api.thingspeak.com\n");
  53.     client.print("Connection: close\n");
  54.     client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\n");
  55.     client.print("Content-Type: application/x-www-form-urlencoded\n");
  56.     client.print("Content-Length: ");
  57.     client.print(tsdata.length());
  58.     client.print("\n\n");
  59.     client.print(tsdata);
  60.     lastConnectionTime = millis();
  61.      
  62.     if (client.connected()) {
  63.       Serial.println("Conectando ao ThingSpeak...");
  64.       Serial.println();
  65.       failedCounter = 0;
  66.     } else {
  67.       failedCounter++;
  68.       Serial.println("Connexão ao ThingSpeak falhou ("+String(failedCounter, DEC)+")");  
  69.       Serial.println();
  70.     }
  71.    
  72.     lastConnectionTime = millis();
  73.   }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement