Construye un Termómetro Arduino con Conectividad Web y Sensor DS18B20
Componentes y materiales
| Componente | Cantidad | Notas |
|---|---|---|
| Arduino UNO | 1 | |
| PHPoC WiFi Shield para Arduino | 1 | También se puede usar PHPoC Shield |
| Sensor de temperatura Adafruit DS18B20 | 1 | |
| Resistencia 4.7k ohm (Seeed) | 1 | |
| Tubo termorretráctil | 1 |
Sobre este proyecto
Si eres principiante, puedes aprender sobre WiFi y sensores en Arduino con los tutoriales: Wifi y Arduino y Sensor de temperatura DS18B20.
He realizado un proyecto similar usando solo PHPoC aquí.
Demostración
El sistema muestra la temperatura en tiempo real en un navegador web mediante una interfaz gráfica tipo termómetro.
Flujo de datos
Arduino → PHPoC WiFi Shield → Navegador web
Arduino lee la temperatura del sensor y envía el valor al PHPoC WiFi Shield. Al recibir el dato, el shield lo transmite al navegador web vía WebSocket. Una función JavaScript visualiza la temperatura en la interfaz de usuario.
Nota: El shield PHPoC tiene un programa integrado para pasar datos de Arduino al navegador, por lo que no necesitamos preocuparnos por esa parte.
Qué necesitamos hacer
- Configurar la información WiFi para el shield PHPoC (SSID y contraseña)
- Subir la nueva interfaz web al shield PHPoC
- Escribir el código de Arduino
Configurar información WiFi para el shield PHPoC
Consulta esta instrucción.
Subir nueva interfaz web al shield PHPoC
- Descarga el código fuente PHPoC
remote_thermometer.php(en la sección de código). - Súbelo al shield PHPoC usando PHPoC Debugger según esta instrucción.
Escribir código Arduino
- Instala tres librerías: PHPoC Library for Arduino, OneWire y Dallas Temperature (ver instrucción).
- Sube el código de Arduino (en la sección de código) a la placa.
Pruebas
- Haz clic en el botón serie en el IDE de Arduino para ver la dirección IP.
- Abre el navegador web e introduce:
https://reemplaza_direccion_ip/remote_thermometer.php - Haz clic en el botón conectar y pruébalo.
El mejor kit de inicio Arduino para principiantes
Si buscas un kit Arduino, consulta El mejor kit Arduino para principiantes.
Referencias de funciones
- Serial.begin()
- Serial.println()
- delay()
- millis()
- for loop
- while loop
- if else
- loop()
- setup()
- String.toInt()
- String.substring()
- String.indexOf()
- String.remove()
- String.equals()
Código
Código Arduino
#include <OneWire.h>
#include <DallasTemperature.h>
#include "SPI.h"
#include "Phpoc.h"
// El cable de datos está conectado al puerto 8 del Arduino
OneWire oneWire(8);
DallasTemperature sensors(&oneWire);
PhpocServer server(80);
boolean alreadyConnected = false;
void setup() {
Serial.begin(9600);
while(!Serial) ;
sensors.begin();
Phpoc.begin(PF_LOG_SPI | PF_LOG_NET);
server.beginWebSocket("thermometer");
Serial.print("Dirección del servidor WebSocket: ");
Serial.println(Phpoc.localIP());
}
void loop() {
// Cuando el cliente envía el primer byte, decimos hola:
PhpocClient client = server.available();
if (client) {
sensors.requestTemperatures();
float temp = sensors.getTempCByIndex(0);
String txtMsg = String(temp) + "\r\n";
char buf[txtMsg.length()];
txtMsg.toCharArray(buf, txtMsg.length());
server.write(buf, txtMsg.length());
delay(300);
}
}
remote_thermometer.php
Este archivo proporciona la interfaz de usuario web. Sube este archivo al PHPoC WiFi Shield o PHPoC Shield según las instrucciones descritas.
<!DOCTYPE html>
<html>
<head>
<title>Arduino - PHPoC Shield - Termómetro</title>
<meta name="viewport" content="width=device-width, initial-scale=0.7, maximum-scale=0.7">
<meta charset="utf-8">
<style>
body { text-align: center; font-size: width/2pt; }
h1 { font-weight: bold; font-size: width/2pt; }
h2 { font-weight: bold; font-size: width/2pt; }
button { font-weight: bold; font-size: width/2pt; }
</style>
<script>
var canvas_width = 200, canvas_height = 450;
var ws;
var buffer = "";
function init() {
var canvas = document.getElementById("remote");
canvas.width = canvas_width;
canvas.height = canvas_height;
var ctx = canvas.getContext("2d");
ctx.translate(canvas_width/2, canvas_height - 80);
update_view(0);
}
function connect_onclick() {
if(ws == null) {
var ws_host_addr = "<?echo _SERVER("HTTP_HOST")?>";
if((navigator.platform.indexOf("Win") != -1) && (ws_host_addr.charAt(0) == "[")) {
ws_host_addr = ws_host_addr.replace(/[\[\]]/g, '');
ws_host_addr = ws_host_addr.replace(/:/g, "-");
ws_host_addr += ".ipv6-literal.net";
}
ws = new WebSocket("ws://" + ws_host_addr + "/thermometer", "text.phpoc");
document.getElementById("ws_state").innerHTML = "CONECTANDO";
ws.onopen = ws_onopen;
ws.onclose = ws_onclose;
ws.onmessage = ws_onmessage;
} else {
ws.close();
}
}
function ws_onopen() {
document.getElementById("ws_state").innerHTML = "<font color='blue'>CONECTADO</font>";
document.getElementById("bt_connect").innerHTML = "Desconectar";
ws.send("B\r\n");
update_view(0);
}
function ws_onclose() {
document.getElementById("ws_state").innerHTML = "<font color='gray'>CERRADO</font>";
document.getElementById("bt_connect").innerHTML = "Conectar";
ws.onopen = null;
ws.onclose = null;
ws.onmessage = null;
ws = null;
update_view(0);
}
function ws_onmessage(e_msg) {
e_msg = e_msg || window.event;
console.log(e_msg.data);
update_view(parseFloat(e_msg.data));
}
function update_view(temp) {
var canvas = document.getElementById("remote");
var ctx = canvas.getContext("2d");
var radius = 70;
var offset = 5;
var width = 45;
var height = 330;
ctx.clearRect(-canvas_width/2, -350, canvas_width, canvas_height);
if(ws != null) {
ctx.strokeStyle = "blue";
ctx.fillStyle = "blue";
} else {
ctx.strokeStyle = "Gray";
ctx.fillStyle = "Gray";
}
// Grados de 5 en 5
var x = -width/2;
ctx.lineWidth = 2;
for (var i = 0; i <= 100; i += 5) {
var y = -(height - radius) * i / 100 - radius - 5;
ctx.beginPath();
ctx.lineTo(x, y);
ctx.lineTo(x - 20, y);
ctx.stroke();
}
// Grados de 20 en 20
ctx.lineWidth = 5;
for (var i = 0; i <= 100; i += 20) {
var y = -(height - radius) * i / 100 - radius - 5;
ctx.beginPath();
ctx.lineTo(x, y);
ctx.lineTo(x - 25, y);
ctx.stroke();
ctx.font = "20px Georgia";
ctx.textBaseline = "middle";
ctx.textAlign = "right";
ctx.fillText(i.toString(), x - 35, y);
}
// Forma del termómetro
ctx.lineWidth = 16;
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.stroke();
ctx.beginPath();
ctx.rect(-width/2, -height, width, height);
ctx.stroke();
ctx.beginPath();
ctx.arc(0, -height, width/2, 0, 2 * Math.PI);
ctx.stroke();
ctx.fillStyle = "#e6e6ff";
ctx.beginPath();
ctx.arc(0, 0, radius, 0, 2 * Math.PI);
ctx.fill();
ctx.beginPath();
ctx.rect(-width/2, -height, width, height);
ctx.fill();
ctx.beginPath();
ctx.arc(0, -height, width/2, 0, 2 * Math.PI);
ctx.fill();
// Valor de temperatura
if(ws != null) ctx.fillStyle = "#ff1a1a";
else ctx.fillStyle = "Gray";
ctx.beginPath();
ctx.arc(0, 0, radius - offset, 0, 2 * Math.PI);
ctx.fill();
temp = Math.round(temp);
var y = (height - radius) * temp / 100.0 + radius + 5;
ctx.beginPath();
ctx.rect(-width/2 + offset, -y, width - 2*offset, y);
ctx.fill();
if(ws != null) {
ctx.fillStyle = "white";
ctx.font = "bold 34px Georgia";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.fillText(temp.toString() + "°C", 0, 0);
}
}
window.onload = init;
</script>
</head>
<body>
<p>
<h1>Arduino - Termómetro Web</h1>
</p>
<canvas id="remote"></canvas>
<h2>
<p>WebSocket: <span id="ws_state">null</span></p>
<button id="bt_connect" type="button" onclick="connect_onclick();">Conectar</button>
</h2>
</body>
</html>
Esquemáticos
- Apila el shield PHPoC WiFi o PHPoC Shield sobre Arduino
- Cablea como se muestra en la imagen
[Las imágenes del esquema se muestran en el proyecto original]
Proceso de manufactura
- El termómetro: del termoscopio de Galileo a los sensores digitales modernos
- Construye un Spybot controlado por Bluetooth con Arduino
- FlickMote: Mando IR por gestos para Smart Home
- TV‑B‑Gone DIY con Arduino: Mando universal para apagar cualquier TV
- Construye un Reloj Maestro LED Personalizado con Alarma – Visible desde 12 Metros
- Find Me: Localizador Inteligente de Objetos con Arduino y Bluetooth
- Soluciones de Alimentación Optimizadas para Proyectos Arduino
- Reproductor MP3 controlado por web con Arduino: Reproducción de audio fácil desde el navegador
- Tres en raya con Arduino, matriz LED MAX7219 y carcasa de cartón
- Construye un Robot Cuadrúpedo Inteligente con Arduino: Guía Paso a Paso
- Protege tu Arduino con desbloqueo por patrón web: configuración fácil y control remoto