segunda-feira, 5 de setembro de 2016

sensor de temperatura com thingspeak

Saudações povo que acompanha o meu blog. Havia prometido a um leitor que mostraria um método de fazer gráficos através do ethernet shield. Pois bem, este dia chegou e é com essa ferramenta que iremos fazer o gráfico:



Basicamente pessoal o thingspeak é um site gratuito onde através de um cadastro é gerado uma apkey e através dela nós inserimos no código do arduino e pimba. O ethernet shield manda os dados diretamente para o site e o site trata de formatá-los, deixando prontinho para leitura e interpretação.

Meu canal no thingspeak pode ser visualizado aqui

Uma vez feito o cadastro lah navegue ate a aba chaves e anote os dados de chave de escrita, que é ela que iremos trocar no codigo no campo"insira sua apkey aqui"
Um outro detalhe importante pessoal e que vocês tem que atualizar o campo "mac" conforme o mac de vocês.
Para saber o seu mac tem uma maneira simples:As ultimas IDES do arduino ja vem com a biblioteca ethernet shield instalada, então basta  ir em examples>webclient e ver o mac que esta escrito lah, veja a imagem como exemplo:
e depois anote o campo" byte mac" para depois trocar no código conforme a imagem:

Aqui pessoal irei mostrar 2 codigos: um funcionando com o uso de biblioteca, que é o caso do sensor dht11, e o outro funcionando com uma fórmula de conversão, que é o caso do sensor lm 35. Prestem atençao na string que ela é codificada após a conversão da leitura do sensor, através deste esqueleto vocês serão capazes de alterar o código as suas necessidades.


Primeiro pessoal montem conforme a imagem o lm 35:
Depois insira este código:
-----------------------------
/*
 Arduino --> ThingSpeak Channel via Ethernet
 The ThingSpeak Client sketch is designed for the Arduino and Ethernet.
 This sketch updates a channel feed with an analog input reading via the
 ThingSpeak API (https://thingspeak.com/docs)
 using HTTP POST. The Arduino uses DHCP and DNS for a simpler network setup.
 The sketch also includes a Watchdog / Reset function to make sure the
 Arduino stays connected and/or regains connectivity after a network outage.
 Use the Serial Monitor on the Arduino IDE to see verbose network feedback
 and ThingSpeak connectivity status.
 Getting Started with ThingSpeak:
   * Sign Up for New User Account - https://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"
 Arduino Requirements:
   * Arduino with Ethernet Shield or Arduino Ethernet
   * Arduino 1.0+ IDE
   
  Network Requirements:
   * Ethernet port on Router    
   * DHCP enabled on Router
   * Unique MAC Address for Arduino
 Created: October 17, 2011 by Hans Scharler (http://www.nothans.com)
 Additional Credits:
 Example sketches from Arduino team, Ethernet by Adrian McEwen
*/

#include <SPI.h>
#include <Ethernet.h>
int pin= A1;
int tempc;
// Local Network Settings
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // Insira o seu mac aqui.
// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "insira sua apkey aqui";
const int updateThingSpeakInterval = 16 * 1000;      // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)

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

// Initialize Arduino Ethernet Client
EthernetClient client;

void setup()
{
  // Start Serial for debugging on the Serial Monitor
  Serial.begin(9600);
  pinMode(pin,INPUT);
  
  // Start Ethernet on Arduino
  startEthernet();
}

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

  // Read value from Analog Input Pin 0
  String analogValue0 = 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("...disconnected");
    Serial.println();
    
    client.stop();
  }
  
  // Update ThingSpeak
  if(!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))
  {
    updateThingSpeak("field1="+analogValue0);
  }
  
  // Check if Arduino Ethernet needs to be restarted
  if (failedCounter > 3 ) {startEthernet();}
  
  lastConnected = client.connected();
}

void updateThingSpeak(String tsData)
{
  if (client.connect(thingSpeakAddress, 80))
  {         
    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();
    
    if (client.connected())
    {
      Serial.println("Connecting to ThingSpeak...");
      Serial.println();
      
      failedCounter = 0;
    }
    else
    {
      failedCounter++;
  
      Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")");   
      Serial.println();
    }
    
  }
  else
  {
    failedCounter++;
    
    Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");   
    Serial.println();
    
    lastConnectionTime = millis(); 
  }
}

void startEthernet()
{
  
  client.stop();

  Serial.println("Connecting Arduino to network...");
  Serial.println();  
  Serial.println();

  delay(1000);
  
  // Connect to network amd obtain an IP address using DHCP
  if (Ethernet.begin(mac) == 0)
  {
    Serial.println("DHCP Failed, reset Arduino to try again");
    Serial.println();
  }
  else
  {
    Serial.println("Arduino connected to network using DHCP");
    Serial.println();
    
  }
  
  delay(1000);
}
-----------------------------------
Depois de compilar navegue ate o site e veja a maravilha funcionando:)

Agora vem o código com o dht11, primeiro monte conforme a imagem:

A biblioteca foi a usada no site do filipeflop ao qual voce pode ser redirecionado clicando aqui .Depois insira o código cuidando do mac e da apkey conforme mencionado anteriormente:
--------------------------------
/*
 Arduino --> ThingSpeak Channel via Ethernet
 The ThingSpeak Client sketch is designed for the Arduino and Ethernet.
 This sketch updates a channel feed with an analog input reading via the
 ThingSpeak API (https://thingspeak.com/docs)
 using HTTP POST. The Arduino uses DHCP and DNS for a simpler network setup.
 The sketch also includes a Watchdog / Reset function to make sure the
 Arduino stays connected and/or regains connectivity after a network outage.
 Use the Serial Monitor on the Arduino IDE to see verbose network feedback
 and ThingSpeak connectivity status.
 Getting Started with ThingSpeak:
   * Sign Up for New User Account - https://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"
 Arduino Requirements:
   * Arduino with Ethernet Shield or Arduino Ethernet
   * Arduino 1.0+ IDE
   
  Network Requirements:
   * Ethernet port on Router    
   * DHCP enabled on Router
   * Unique MAC Address for Arduino
 Created: October 17, 2011 by Hans Scharler (http://www.nothans.com)
 Additional Credits:
 Example sketches from Arduino team, Ethernet by Adrian McEwen
*/
#include "DHT.h"
#include <SPI.h>
#include <Ethernet.h>
#define DHTPIN A1 // pino que estamos conectado
#define DHTTYPE DHT11 // DHT 11
DHT dht(DHTPIN, DHTTYPE);
// Local Network Settings
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // Coloque o seu mac

// ThingSpeak Settings
char thingSpeakAddress[] = "api.thingspeak.com";
String writeAPIKey = "insira sua apkey aqui";
const int updateThingSpeakInterval = 16 * 1000;      // Time interval in milliseconds to update ThingSpeak (number of seconds * 1000 = interval)

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

// Initialize Arduino Ethernet Client
EthernetClient client;


void setup()
{
  // Start Serial for debugging on the Serial Monitor
  Serial.begin(9600);
  
  // Start Ethernet on Arduino
  startEthernet();
}

void loop()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  String temp = String(h);
  String temp1 = String(t);
  // Read value from Analog Input Pin 0
  
  // 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("...disconnected");
    Serial.println();
    
    client.stop();
  }
  
  // Update ThingSpeak
  if(!client.connected() && (millis() - lastConnectionTime > updateThingSpeakInterval))
  {
    updateThingSpeak("field1="+temp+"&field2="+temp1);
  }
  
  // Check if Arduino Ethernet needs to be restarted
  if (failedCounter > 3 ) {startEthernet();}
  
  lastConnected = client.connected();
}

void updateThingSpeak(String tsData)
{
  if (client.connect(thingSpeakAddress, 80))
  {         
    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();
    
    if (client.connected())
    {
      Serial.println("Connecting to ThingSpeak...");
      Serial.println();
      
      failedCounter = 0;
    }
    else
    {
      failedCounter++;
  
      Serial.println("Connection to ThingSpeak failed ("+String(failedCounter, DEC)+")");   
      Serial.println();
    }
    
  }
  else
  {
    failedCounter++;
    
    Serial.println("Connection to ThingSpeak Failed ("+String(failedCounter, DEC)+")");   
    Serial.println();
    
    lastConnectionTime = millis(); 
  }
}

void startEthernet()
{
  
  client.stop();

  Serial.println("Connecting Arduino to network...");
  Serial.println();  
  Serial.println();

  delay(1000);
  
  // Connect to network amd obtain an IP address using DHCP
  if (Ethernet.begin(mac) == 0)
  {
    Serial.println("DHCP Failed, reset Arduino to try again");
    Serial.println();
  }
  else
  {
    Serial.println("Arduino connected to network using DHCP");
    Serial.println();
    
  }
  
  delay(1000);
}
-----------------------------------------------------------------------------------

Se tudo correr bem seus gráficos ficarão assim:

E é isso ahe pessoal, até a próxima e em breve postarei o vídeo

e como prometido eis o video:

Um comentário:

Unknown disse...

existe a possibilidade de se criar um sensor em arduino e ele demonstrar o resultado de java swing ??

obrigado!!