LusoRobótica - Robótica em Português
Sistemas específicos => Arduino / AVR => Tópico iniciado por: poliveira1978 em 12 de Agosto de 2012, 00:50
-
estou a tentar enviar dados do arduino para o raspberry e pareceu-me que usar o shield ethernet em modo cliente e um script php no raspberry poderiam funcionar.
Aqui o PHP, basicamente recebe 3 parametros na querystring e regista a informação num ficheiro de texto (quando funcionar, passa-se para mySQL):
<?php
$p1 = $_GET['p1'];
$p2 = $_GET['p2'];
$p3 = $_GET['p3'];
$timestamp = mktime();
$your_data = "Data: ".date("d/m/Y H:i:s", $timestamp). ", Temperatura: " . $p1 $
echo "OK";
$fp = fopen("/var/www/data.txt", "a");
fwrite($fp, $your_data);
fclose($fp);
?>
e aqui o código do Arduino
#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 2
#include <SPI.h>
#include <Ethernet.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,10,203);
EthernetClient client;
void setup()
{
Serial.begin(9600);
Serial.println("DHT11 TEST PROGRAM ");
Serial.print("LIBRARY VERSION: ");
Serial.println(DHT11LIB_VERSION);
if (Ethernet.begin(mac) == 0)
{
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 80))
{
Serial.println("connected");
}
}
void loop()
{
int chk = DHT11.read(DHT11PIN);
switch (chk)
{
case 0: Serial.println("OK"); break;
case -1: Serial.println("Checksum error"); break;
case -2: Serial.println("Time out error"); break;
default: Serial.println("Unknown error"); break;
}
client.print("GET /registar.php?p1=");
client.print((float)DHT11.temperature, DEC);
client.print("&p2=");
client.print((float)DHT11.humidity, DEC);
client.print("&p3=");
client.print(DHT11.dewPoint(), DEC);
client.print(" HTTP/1.0");
client.println();
/*
Serial.print("Temperatura: ");
Serial.println((float)DHT11.temperature, DEC);
Serial.print("Humidade: ");
Serial.println((float)DHT11.humidity, DEC);
Serial.print("Ponto de Orvalho: ");
Serial.print(DHT11.dewPoint(), DEC);
*/
}
O problema é que apesar de ver a informação no serial monitor, o ficheiro data.txt não é criado. quando "corro" o php directamente no browser com as respectivas querystrings o ficheiro é actualizado.
Alguém me consegue explicar onde está o erro?
Agradeço antecipadamente,
Pedro
-
O problema deve estar no arduino visto que o php funciona no PC.
Tenta copiar o exemplo do site oficial:
http://arduino.cc/en/Reference/ClientConstructor (http://arduino.cc/en/Reference/ClientConstructor)
Mudando apenas o necessário e vê se recebes o "OK" da página PHP.
Não tenho Ethernet Shield mas talvez seja preciso ler a resposta e não fazer apenas o request.
Mesmo que não seja preciso ler a resposta, nesse código, é feito um request a cada loop, devia haver um tempo de espera de alguns segundos, no mínimo, entre cada um.
-
Alterei o código do Arduino
#include <SPI.h>
#include <Ethernet.h>
#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,10,189);
EthernetClient client;
char buffer[256];
void setup()
{
Serial.begin(9600);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 80))
{
Serial.println("connected");
}
else
{
Serial.println("connection failed");
}
}
void loop()
{
int chk = DHT11.read(DHT11PIN);
Serial.print("Read sensor: ");
switch (chk)
{
case 0: Serial.println("OK"); break;
case -1: Serial.println("Checksum error"); break;
case -2: Serial.println("Time out error"); break;
default: Serial.println("Unknown error"); break;
}
Serial.println("Sending Data...");
float hum=DHT11.humidity;
float temp=DHT11.temperature;
float dew=DHT11.dewPoint();
sprintf(buffer, "GET /registar.php?hum=%2.2f&temp=%2.2f&dew=%2.2f HTTP/1.1", hum, temp, dew);
client.println(buffer);
client.println("Host: Arduino1");
client.println("Connection: close");
client.println();
client.stop();
Serial.println("Data Sent:");
Serial.print("Humidade: ");
Serial.print(hum);
Serial.println("%");
Serial.print("Temperatura: ");
Serial.print(temp);
Serial.println("*C");
Serial.print("Ponto de Orvalho: ");
Serial.print(dew);
Serial.println("*C");
delay(60000);
}
e agora aparentemente o arduino já se liga ao servidor apache, pois "aparecem" mais entradas no ficheiro de texto, mas não passa os valores, ou seja, as novas linhas ficam assim:
1344881127 - Temperatura: ? - Humidade: ? - Ponto de Orvalho: ?
o PHP agora tem este apecto:
<?php
$fields = explode("&", $_SERVER['QUERY_STRING']);
$values = array();
foreach ($fields as $field)
{
$keyval = explode("=", $field);
$values[$keyval[0]] = $keyval[1];
}
$file = fopen('/tmp/dados.txt','a+');
if ($file)
{
fwrite($file, time() . ' - Temperatura: ' . $values['temp'] . ' - Humidade: ' . $values['hum'] . ' - Ponto de Orvalho: '.$values['dew']);
fwrite($file, "\n");
fclose($file);
}
echo "dados recebidos";
?>
Acho que estou perto, mas "ainda falta um bocadinho assim..."
Agora num registo um pouco off topic, para quem precisar duma ethernet shield, deixo esta sugestão Arduino UNO + Ethernet Shield (http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=261057726939)
-
Tenta substituir isto:
sprintf(buffer, "GET /registar.php?hum=%2.2f&temp=%2.2f&dew=%2.2f HTTP/1.1", hum, temp, dew);
client.println(buffer);
Por algo como:
client.println("GET /registar.php?hum=111&temp=222&dew=333 HTTP/1.1");
Apenas para testar.
Assim já se sabe se o problema está nessa função.
-
Alterei outra vez o código do Arduino, aparentemente "montar" a querystring e enviá-la duma vez não dava grande resultado, enviando pedaços mais pequenos funciona melhor:
#include <SPI.h>
#include <Ethernet.h>
#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,10,189);
EthernetClient client;
char buffer[256];
void setup()
{
Serial.begin(9600);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 80))
{
Serial.println("connected");
}
else
{
Serial.println("connection failed");
}
}
void loop()
{
int chk = DHT11.read(DHT11PIN);
Serial.print("Read sensor: ");
switch (chk)
{
case 0: Serial.println("OK"); break;
case -1: Serial.println("Checksum error"); break;
case -2: Serial.println("Time out error"); break;
default: Serial.println("Unknown error"); break;
}
Serial.println("Sending Data...");
float hum=DHT11.humidity;
float temp=DHT11.temperature;
float dew=DHT11.dewPoint();
client.print("GET /registar.php?hum=");
client.print(hum,DEC);
client.print("&temp=");
client.print(temp,DEC);
client.print("&dew=");
client.print(dew,DEC);
client.println(" HTTP/1.1");
client.println("Host: arduino1");
client.println();
Serial.println("Data Sent:");
Serial.print("Humidade: ");
Serial.print(hum);
Serial.println("%");
Serial.print("Temperatura: ");
Serial.print(temp);
Serial.println("*C");
Serial.print("Ponto de Orvalho: ");
Serial.print(dew);
Serial.println("*C");
while(client.available())
{
char c = client.read();
Serial.print(c);
}
delay(60000);
}
O problema agora está na formatação dos valores, as linhas no ficheiro de texto ficam assim:
1344902631 - Temperatura: 28.0000000000ºC;Humidade: 32.0000000000%;Ponto de Orvalho: 9.7911558151ºC
Como assim já envia os valores vou começar a enviar para o MySQL e na própria tabela "ajusto" a formatação, vamos ver se é desta...
-
Declara hum e temp como int e não como float para não teres esses valores assim.
-
Há uma solução melhor para resolver a tal questão dos valores decimais.
Com a função round
do PHP
$valor=round(valororiginal,2); //devolve valororiginal arredondado a 2 casas decimais.
-
Mas não vale a pena fazer isso com a humidade e temperatura, porque são sempre valores inteiros.
-
o sensor dht11 dá os valores com precisão de décimas e a humidade também pode ser 10,5%, por exemplo, não?
De qualquer forma com o round do php os valores ficam mais "simples" de interpretar.
-
o sensor dht11 dá os valores com precisão de décimas e a humidade também pode ser 10,5%, por exemplo, não?
De qualquer forma com o round do php os valores ficam mais "simples" de interpretar.
Estive a ver no datasheet e o DHT11 tem resolução de 1? e a humidade deve ser a mesma coisa.
O ponto de orvalho têm casas décimais, porque não é medido, é calculado com os valores de temperatura e humidade.
-
Ok, de qualquer forma essa questão está resolvida.
Agora apareceu um problema mais estranho... o loop só é executado uma vez (quando abro o serial monitor), os dados são registados uma vez e depois... nada, até abrir outra vez o serial monitor (que provoca um reset no arduino e o faz voltar ao inicio)...
-
Não será isto:
delay(60000);
Delay de 1 minuto?
-
pensei nisso, mas não é... pois no serial monitor vejo vários "envios", mas só há um registo no servidor web...
-
Tenta substituir:
delay(60000);
Por:
delay(30000);
client.stop();
delay(30000);
E põe isto no início do loop, em vez de no setup:
Serial.println("connecting...");
if (client.connect(server, 80))
{
Serial.println("connected");
}
else
{
Serial.println("connection failed");
}
Fica assim:
#include <SPI.h>
#include <Ethernet.h>
#include <dht11.h>
dht11 DHT11;
#define DHT11PIN 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress server(192,168,10,189);
EthernetClient client;
char buffer[256];
void setup()
{
Serial.begin(9600);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
for(;;)
;
}
delay(1000);
}
void loop()
{
Serial.println("connecting...");
if (client.connect(server, 80))
{
Serial.println("connected");
}
else
{
Serial.println("connection failed");
}
int chk = DHT11.read(DHT11PIN);
Serial.print("Read sensor: ");
switch (chk)
{
case 0: Serial.println("OK"); break;
case -1: Serial.println("Checksum error"); break;
case -2: Serial.println("Time out error"); break;
default: Serial.println("Unknown error"); break;
}
Serial.println("Sending Data...");
float hum=DHT11.humidity;
float temp=DHT11.temperature;
float dew=DHT11.dewPoint();
client.print("GET /registar.php?hum=");
client.print(hum,DEC);
client.print("&temp=");
client.print(temp,DEC);
client.print("&dew=");
client.print(dew,DEC);
client.println(" HTTP/1.1");
client.println("Host: arduino1");
client.println();
Serial.println("Data Sent:");
Serial.print("Humidade: ");
Serial.print(hum);
Serial.println("%");
Serial.print("Temperatura: ");
Serial.print(temp);
Serial.println("*C");
Serial.print("Ponto de Orvalho: ");
Serial.print(dew);
Serial.println("*C");
while(client.available())
{
char c = client.read();
Serial.print(c);
}
delay(30000);
client.stop();
delay(30000);
}
Senão resultar, vê o exemplo WebClientRepeating.
-
ok, resultou... obrigado!
-
[ :)quote author=poliveira1978 link=topic=5214.msg57834#msg57834 date=1345042329]
ok, resultou... obrigado!
[/quote]
De nada.