Ethernet Shield enviando dados para web



Neste post estou usando o ethernet shield do arduino para enviar as leituras de temperatura de um sensor LM35 para o site  ThingSpeak e exibir estas leituras em forma de gráfico no blog. O site ThingSpeak permite que o usuário envie diversos tipos de dados e acesse estes dados de diversas formas com uma api para inclusão em outros meios como web, twitter ou o que mais você quiser.

No exemplo abaixo estou enviando estas leituras para um pequeno gráfico que pode ser visto em todas as páginas deste blog, esta mesma idéia pode ser usada para enviar outros tipos de leituras e existem ainda formas de fazer com que esta função tenha duas vias para controlar equipamentos e fazer automação doméstica.

Na imagem acima o sensor está conectado na porta analógica 0 e alimentado por 5V a partir da própria placa Ethernet. As leituras analógicas são convertidas para apresentar a temperatura em graus centígrados antes do envio.

(imagem estática de exemplo)

O código para exibição no blog é simples e pode ser encontrado no endereço https://www.thingspeak.com/channels/261 que é o endereço do canal destes dados no site ThingSpeak.

----------------------------------------------------------------------------------------------------


/*

 ThingSpeak Client to Update Channel Feeds
 
 The ThingSpeak Client sketch is designed for the Arduino + Ethernet Shield.
 This sketch updates a channel feed with an analog input reading via the
 ThingSpeak API (http://community.thingspeak.com/documentation/)
 using HTTP POST.
 
 Getting Started with ThingSpeak:
 
    * Sign Up for New User Account - https://www.thingspeak.com/users/new
    * Create a New Channel by selecting Channels and then Create New Channel
    * Enter the Write API Key in this sketch under "ThingSpeak Settings"
 
 Created: January 25, 2011 by Hans Scharler (http://www.iamshadowlord.com)
 
 Additional Credits: Example sketches from Tom Igoe and David A. Mellis
 
*/

#include <SPI.h>
#include <Ethernet.h>

int pin = 0; // analog pin
int tempc = 0,tempf=0; // temperature variables
int samples[8]; // variables to make a better precision
int maxi = -100,mini = 100; // to start max/min temperature
int i;

// Local Network Settings
byte mac[]     = { 0xD4, 0x28, 0xB2, 0xFF, 0xA0, 0xA1 }; // Must be unique on local network
byte ip[]      = { 192, 168,   1,  13 };                // Must be unique on local network
byte gateway[] = { 192, 168,   1,   1 };
byte subnet[]  = { 255, 255, 255,   0 };

// ThingSpeak Settings
byte server[]  = { 184, 106, 153, 149 }; // IP Address for the ThingSpeak API
String writeAPIKey = "sua chave vai aqui";    // Write API Key for a ThingSpeak Channel
const int updateInterval = 10000;        // Time interval in milliseconds to update ThingSpeak   
Client client(server, 80);

// Variable Setup
long lastConnectionTime = 0; 
boolean lastConnected = false;
int resetCounter = 0;

void setup()
{
  Ethernet.begin(mac, ip, gateway, subnet);
  Serial.begin(9600);
  delay(1000);
}

void loop()
{
  
  tempc = ( 5.0 * analogRead(pin) * 100.0) / 1024.0;

  String analogPin0 = String(tempc);
  
  // Print Update Response to Serial Monitor
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }
  
  // Disconnect from ThingSpeak
  if (!client.connected() && lastConnected)
  {
    Serial.println();
    Serial.println("...disconnected.");
    Serial.println();
    
    client.stop();
  }
  
  // Update ThingSpeak
  if(!client.connected() && (millis() - lastConnectionTime > updateInterval))
  {
    updateThingSpeak("field1="+analogPin0);
  }
  
  lastConnected = client.connected();
}

void updateThingSpeak(String tsData)
{
  if (client.connect())
  { 
    Serial.println("Connected to ThingSpeak...");
    Serial.println();
        
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: "+writeAPIKey+"\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);
    
    lastConnectionTime = millis();
    
    resetCounter = 0;
    
  }
  else
  {
    Serial.println("Connection Failed.");   
    Serial.println();
    
    resetCounter++;
    
    if (resetCounter >=5 ) {resetEthernetShield();}

    lastConnectionTime = millis(); 
  }
}

void resetEthernetShield()
{
  Serial.println("Resetting Ethernet Shield.");   
  Serial.println();
  
  client.stop();
  delay(1000);
  
  Ethernet.begin(mac, ip, gateway, subnet);
  delay(1000);
}

----------------------------------------------------------------------------

Internet of Things

LUX com arduino GPRS shield e sensor LDR.

/*
Graph: Feed 38642, Datastream lux
*/

Laboratórios, Lojas e Produtos

Blogs, Comunidades e Revistas