Pessoal bom dia. Estou desenvolvendo um sistema de medição de temperatura de equipamentos que vai ajudar muito o pessoal aqui na empresa. Porém estou enfrentando diversos problemas e parecem ser erros bobos, mas não consigo resolver. Cada vez que pesquiso, modifico o código, mais embolado fica. Então resolvi criar esse post pra tentar dispor todos os problemas e vejo que várias outras pessoas também enfrentaram esse problema.

O projeto é bem simples. Por enquanto são dois sensores de temperatura, porém futuramente serão mais.

[DS18B20]-----[Arduino UNO]------serial------[PHP Computador com XAMPP]

As pessoas poderão consultar a temperatura pela web futuramente, por enquanto estou testando em um servidor local.

Seguem os códigos.

                       ARDUINO

#include <OneWire.h>
#include <DallasTemperature.h>

#define buraco 10

OneWire ourWire (buraco);
DallasTemperature sensors (&ourWire);

void setup (){
Serial.begin (9600);

sensors.begin ();
delay (500);
}
void loop(){
if (Serial.available()>0)
{
char recebido = Serial.read();
if (recebido == 't')
{

sensors.requestTemperatures ();
Serial.print ("Temperatura Datacenter: ");
Serial.println (sensors.getTempCByIndex (0));

}
}

}

                       PHP

<?php

$portAddress = "COM5";
exec("mode com5: BAUD=9600 PARITY=N data=8 stop=1 xon=off");

echo ("<h1>Temperatura Arduino</h1>");

echo ("<p>Conectando, aguarde...");
$port = fopen($portAddress, 'w+');
sleep(2);
if (!$port)
{

echo "<br/> Nao foi possivel abrir a porta $portAddress";

}
else
{
echo "<br/>CONECTADO a $portAddress";
fwrite($port, 't');
sleep(3);

echo fgets($port);

fclose($port);

}

?>

Ocasionalmente o Xampp parece parar de responder ou ocupar eternamente a porta COM, então o navegador fica muito tempo rodando e não abre a página e quando abre dá a seguinte mensagem de erro:
Warning: fopen(COM5): failed to open stream: Permission denied in C:\xampp\htdocs\teste.php on line 7

Já dei todas as permissões de todas as pastas e subpastas do Xampp e do Arduíno, mas o erro é sempre o mesmo.

Quem puder ajudar, indiretamente vai tá ajudando muita gente. 

Desde já agradeço muito a atenção e espero com esse post ajudar outros amigos que também tem esse mesmo problema.

Grande abraço!

Exibições: 823

Responder esta

Respostas a este tópico

Pode fazer com este exemplo https://www.youtube.com/watch?v=6roFRgxuyV

E ou veja este exemplo com TCP.Basta por funções de TCP ou usarum nodemcu com tcp:

https://www.youtube.com/watch?v=KGlGnWaNN0o

É pessoal tô quase fazendo mesmo com o ethernet shield. Segunda um amigo vai levar pra mim. Eu conseguindo fazer vou postar aqui o resultado, código e etc.

Pessoal, como prometido. aqui abaixo está o código para o esquema com o ethernet shield. Consegui através da mesclagem de vários códigos, então ainda tem muito lixo, mas funciona. O próximo passo que estou tentando desenvolver é que a cada sensor acrescentado não haja a necessidade de programar nada mais. Existe um exemplo assim na biblioteca do OneWire (que por sinal já está adicionado um trecho a este código, mas não funciona rs)

Quem entender um pouquinho mais e quiser ajudar. Aqui abaixo está. Espero ajudar a quem futuramente aqui nessa página parar.

 


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

byte mac[] = {
0xAB, 0xCD, 0x12, 0x34, 0xFF, 0xCA // MAC do Arduino
};
IPAddress ip(10,2,2,100); //Define o endereço IP do Arduino - Colocar no roteador com a mesma faixa de IP do computador
IPAddress gateway(10,2,2,2); //Define o gateway - Gateway do roteador para a rede interna
IPAddress subnet(255, 255, 255, 0); //Define a máscara de rede


// (porta 80 eh padrao para HTTP):
EthernetServer server(80);


OneWire ds(2); // ligar no pino digital 2 ( resistor 4.7K eh necessario)

void setup(void) {

// inicia o ethernet shield
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}

void loop(void) {
byte i;
byte present = 0;
byte type_s;
byte data[12];
byte addr[8];
float celsius;

if ( !ds.search(addr)) {
Serial.println("Nao ha mais sensores.");
Serial.println();
ds.reset_search();
delay(250);
return;
}

Serial.print("ROM =");
for( i = 0; i < 8; i++) {
Serial.write(' ');
Serial.print(addr[i], HEX);
}

if (OneWire::crc8(addr, 7) != addr[7]) {
Serial.println("CRC nao eh valido!");
return;
}
Serial.println();

// o primeiro ROM byte indica qual eh o chip
switch (addr[0]) {
case 0x10:
Serial.println(" Chip = DS18S20"); // ou anterior ao DS1820
type_s = 1;
break;
case 0x28:
Serial.println(" Chip = DS18B20");
type_s = 0;
break;
case 0x22:
Serial.println(" Chip = DS1822");
type_s = 0;
break;
default:
Serial.println("Dispositivo nao eh da familia DS18x20.");
return;
}

ds.reset();
ds.select(addr);
ds.write(0x44); // start conversion, use ds.write(0x44,1) with parasite power on at the end

delay(1000); // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.

present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad

Serial.print(" Data = ");
Serial.print(present, HEX);
Serial.print(" ");
for ( i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.print(" CRC=");
Serial.print(OneWire::crc8(data, 8), HEX);
Serial.println();

// Convert the data to actual temperature
// because the result is a 16 bit signed integer, it should
// be stored to an "int16_t" type, which is always 16 bits
// even when compiled on a 32 bit processor.
int16_t raw = (data[1] 8) | data[0];
if (type_s) {
raw = raw 3; // 9 bit resolution default
if (data[7] == 0x10) {
// "count remain" gives full 12 bit resolution
raw = (raw & 0xFFF0) + 12 - data[6];
}
} else {
byte cfg = (data[4] & 0x60);
// at lower res, the low bits are undefined, so let's zero them
if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms
else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
//// default is 12 bit resolution, 750 ms conversion time
}
celsius = (float)raw / 16.0;

Serial.print(" Temperature = ");
Serial.print(celsius);
Serial.print(" Celsius, ");


// listen for incoming clients
EthernetClient client = server.available();
if (client) {
// Serial.println("new client");
// an http request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// Serial.write(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: close"); // the connection will be closed after completion of the response
client.println("Refresh: 5"); // refresh the page automatically every 5 sec
client.println();
client.println("<!DOCTYPE HTML>");
client.println("<html>");
client.print("<p style='text-align: center;'>&nbsp;</p>");
client.print("<p style='text-align: center;'><span style='font-size: x-large;'><strong>Sistema de Monitoramento do Datacenter - JANUS</strong></span></p>");
client.print("<p style='text-align: center;'><span style='color: #0000ff;'><strong style='font-size: large;'>Área A = ");
client.println(celsius);
client.print("</strong></span><h style='text-align: center;'><span style='color: #0000ff;'><strong style='font-size: large;'><sup>o</sup>C</strong></span></h></p>");
client.print("<p style='text-align: center;'>&nbsp;</p>");
client.print("<p style='text-align: center;'>&nbsp;</p>");
client.print("<p style='text-align: center;'>&nbsp;");

// Date and Time script
client.print("<script language='javascript'>");
client.println();
client.print("<!--");
client.println();
client.print("var today = new Date()");
client.println();
client.print("document.write(today); //--> </script>");
client.print("</p>");

client.println("</html>");
break;
}
if (c == '\n') {
// you're starting a new line
currentLineIsBlank = true;
}
else if (c != '\r') {
// you've gotten a character on the current line
currentLineIsBlank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
// Serial.println("client disconnected");
}
}

CORREÇÃO: O código acima está sim lendo todos os sensores que ao arduino forem adicionados, porém, não imprime individualmente.
Ele está imprimindo um sensor a cada atualização.

Alguém tem idéia de como dispor todas as temperaturas de uma só vez?

Exemplo: Sensor A: 25Cº Sensor B: 33Cº Sensor Z: 12Cº

RSS

© 2024   Criado por Marcelo Rodrigues.   Ativado por

Badges  |  Relatar um incidente  |  Termos de serviço