0% found this document useful (0 votes)
50 views

Anexo 1.: Código HTML, CSS y PHP

The document contains code for an Arduino project that measures temperature, humidity, and other variables from sensors. It connects to a WiFi network and sends the sensor data via HTTP POST requests to a PHP script that inserts the data into a MySQL database. The PHP script then queries the database to display charts of the sensor data over time on a webpage using Highcharts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
50 views

Anexo 1.: Código HTML, CSS y PHP

The document contains code for an Arduino project that measures temperature, humidity, and other variables from sensors. It connects to a WiFi network and sends the sensor data via HTTP POST requests to a PHP script that inserts the data into a MySQL database. The PHP script then queries the database to display charts of the sensor data over time on a webpage using Highcharts.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Anexos

Anexo 1.
Código HTML, CSS y PHP.
<?php
$servername = "localhost";
//$servername = "192.168.1.42";
$username = "CAMILO";
$password = "123456";
$dbname = "invernadero";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("CONEXION RECHAZADA: " . $conn->connect_error);
}
$sql = "SELECT * from VARIABLES;";
if($result = mysqli_query($conn, $sql)) {
$rawdata = array();
$i=0;
while($row = mysqli_fetch_array($result)){
$rawdata[$i] = $row;
$i++;
}
//Adaptar el tiempo
for($i=0;$i<count($rawdata);$i++){
$time = $rawdata[$i]["FECHA"];
$date = new DateTime($time);
$rawdata[$i]["FECHA"]=$date->getTimestamp()*1000;
}
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
<HTML>
<BODY>
<meta charset="utf-8">
<meta http-equiv="refresh" content="60">
<script src="jquery.js"></script>
<!-- Importo el archivo Javascript de Highcharts directamente desde su servidor -->
<script src="highstock.js"></script>
<script src="exporting.js"></script>
<div id="container">
</div>
<script type='text/javascript'>
$(function () {
$(document).ready(function() {
Highcharts.setOptions({
global: {
useUTC: false
}
});
var chart;
$('#container').highcharts({
chart: {
type: 'spline',
animation: Highcharts.svg, // don't animate in old IE
marginRight: 10,
events: {
load: function() {
}
}
},
title: {
text: 'INVERNADERO'
},
xAxis: {
type: "datetime",
tickPixelInterval: 50
},
yAxis: {
title: {
text: 'VARIABLES METEREOLOGICAS'
},
plotLines: [{
value: 1,
width: 2,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) +'<br/>'+
Highcharts.numberFormat(this.y, 2);
}
},
legend: {
enabled: false
},
exporting: {
enabled: false}
series: [{
name: 'Temperatura 1',
data: (function() {
var data = [];
<?php
for($i = count($rawdata)-50 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["FECHA"];?>,<?php echo
$rawdata[$i]["TEMPERATURA1"];?>]);
<?php } ?>
return data;
})()
},{
name: 'Temperatura 2',
data: (function() {
var data = [];
<?php
for($i = count($rawdata)-50 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["FECHA"];?>,<?php echo
$rawdata[$i]["TEMPERATURA2"]-5;?>]);
<?php } ?>
return data;
})()
},{
name: 'Humedad 1',
data: (function() {
var data = [];
<?php
for($i = count($rawdata)-50 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["FECHA"];?>,<?php echo
$rawdata[$i]["HUMEDAD1"];?>]);
<?php } ?>
return data;
})()
},{
name: 'Humedad 2',
data: (function() {
var data = [];
<?php
for($i = count($rawdata)-50 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["FECHA"];?>,<?php echo
$rawdata[$i]["HUMEDAD2"]+10;?>]);
<?php } ?>
return data;
})()
} ,{
name: 'Humedad 3',
data: (function() {
var data = [];
<?php
for($i = count($rawdata)-50 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["FECHA"];?>,<?php echo
$rawdata[$i]["HUMEDAD3"]+20;?>]);
<?php } ?>
return data;
})()
},{
name: 'Humedad 4',
data: (function() {
var data = [];
<?php
for($i = count($rawdata)-50 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["FECHA"];?>,<?php echo
$rawdata[$i]["HUMEDAD4"]+25;?>]);
<?php } ?>
return data;
})()
},{
name: 'Humedad 5',
data: (function() {
var data = [];
<?php
for($i = count($rawdata)-50 ;$i<count($rawdata);$i++){
?>
data.push([<?php echo $rawdata[$i]["FECHA"];?>,<?php echo
$rawdata[$i]["HUMEDAD5"]+30;?>]);
<?php } ?>
return data;
})()
}

]
});
});
});
</script>
</html>
Anexo 2.
Conexión y carga de información a la base de datos.
<?php

define('DB_SERVER', 'localhost');
define('DB_USER', 'CAMILO');
define('DB_PASSWORD', '123456');
define('DB_NAME', 'invernadero');

//include('config.php');
$conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_NAME) or
die("Unable to connect to MySQL");
//0: temperature
//1: humidity
//2: pressure
//3: light

if (mysqli_real_escape_string($conn,$_POST['temperature']) ==NULL
||mysqli_real_escape_string($conn,$_POST['temp>
$temperature="NULL";
}else{
$temperature=mysqli_real_escape_string($conn,$_POST['temperature']);
}
if (mysqli_real_escape_string($conn,$_POST['humidity']) ==NULL){
$humidity="NULL";
}else{
$humidity=mysqli_real_escape_string($conn,$_POST['humidity']);
}
////////////////////////
if (mysqli_real_escape_string($conn,$_POST['temperature1']) ==NULL){
$temperature1="NULL";
}else{
$temperature1=mysqli_real_escape_string($conn,$_POST['temperature1']);
}
if (mysqli_real_escape_string($conn,$_POST['humidity1']) ==NULL){
$humidity1="NULL";
}else{
$humidity1=mysqli_real_escape_string($conn,$_POST['humidity1']);
}
//////////////////////
if (mysqli_real_escape_string($conn,$_POST['temperature2']) ==NULL){
$temperature2="NULL";
}else{
$temperature2=mysqli_real_escape_string($conn,$_POST['temperature2']);
}
if (mysqli_real_escape_string($conn,$_POST['humidity2']) ==NULL){
$humidity2="NULL";
}else{
$humidity2=mysqli_real_escape_string($conn,$_POST['humidity2']);
}
///////////////////////////////
if (mysqli_real_escape_string($conn,$_POST['humidity3']) ==NULL){
$humidity3="NULL";
}else{
$humidity3=mysqli_real_escape_string($conn,$_POST['humidity3']);
}

if (mysqli_real_escape_string($conn,$_POST['humidity4']) ==NULL){
$humidity4="NULL";
}else{
$humidity4=mysqli_real_escape_string($conn,$_POST['humidity4']);
}
////////////////////

$insertSQL = "insert into VARIABLES


(TEMPERATURA1,HUMEDAD1,TEMPERATURA2,HUMEDAD2,TEMPERATURA3,HUMED
AD3,HUMEDAD4,>
//$sql = "insert into variables (temperatura,voltaje) values ('".$temperatura."','".$voltaje."')";
mysqli_query($conn,$insertSQL) or die("INSERT Query has Failed - ".$insertSQL );

?>
Anexo 3.
Código en Arduino para el módulo ESP32 Wroom.
#include <WiFi.h>
#include <HTTPClient.h>
#include "DHT.h"
#define DHTTYPE DHT11 // DHT 11
#define DHTPIN 27
#define DHTPIN1 26
#define RETRY_LIMIT 20
#define Analogo_0 A0
#define Analogo_1 A3
#define Analogo_2 A6
DHT dht(DHTPIN,DHTTYPE);
DHT dht1(DHTPIN1,DHTTYPE);
////////////////
const char* ssid = "Tenda_76C150";
const char* password = "Wr2FaRWj";
//const char* ssid = "PIRATA";
//const char* password = "JorgitoANDRES160209";
int h2,h3,h4;

////////////////
void setup(){
dht.begin();
dht1.begin();
Serial.begin(115200);
WiFi.begin(ssid,password);
while (WiFi.status()!= WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP Address");
Serial.println(WiFi.localIP());
}

void loop(){
h2=analogRead(Analogo_1)*100/4095;
delay(2000);
h3=analogRead(Analogo_2)*100/4095;
delay(2000);
h4=analogRead(Analogo_0)*100/4095;
delay(2000);
int rtl=RETRY_LIMIT;
float h=dht.readHumidity();
float t=dht.readTemperature();
delay(500);

while (isnan(t) || isnan(h)){


Serial.println("Revisar Sensor1 - " + rtl);
h=dht.readHumidity();
t=dht.readTemperature();
delay(500);
if (--rtl <1){
ESP.restart(); // At times the DHT11 just kept returning NAN. A Restart fixed this.
}
}

float h1=dht1.readHumidity();
float t1=dht1.readTemperature();
delay(500);
while (isnan(t1) || isnan(h1)){
Serial.println("Revisar Sensor2 - " + rtl);
h1=dht1.readHumidity();
t1=dht1.readTemperature();
delay(500);
if (--rtl <1){
ESP.restart(); // At times the DHT11 just kept returning NAN. A Restart fixed this.
}
}
/////////entradas analogas///////////
/////////////Open a connection to the server
HTTPClient http;
http.begin("http://192.168.1.100/upload.php");
//http.begin("http://192.168.1.42/upload.php");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
/////////////format your POST request.
int httpResponseCode = http.POST("temperature=" + String(t)
+"&humidity=" + String(h)
+"&temperature1=" + String(t1)
+"&humidity1=" + String(h1)
+"&temperature2=" + String(t1+1.5)
+"&humidity2=" + String(h2)
+"&humidity3=" + String(h3)
+"&humidity4=" + String(h4)
);
if (httpResponseCode >0){
//check for a return code - This is more for debugging.
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
}
else{
Serial.print("Error on sending post");
Serial.println(httpResponseCode);
}
//closde the HTTP request.
http.end();

//Monitor values in console for debugging.


Serial.println("Temp = " + String(t));
Serial.println("humidity = " + String(h));
Serial.println("Temp1 = " + String(t1));
Serial.println("humidity1 = " + String(h1));
Serial.println("Temp2 = " + String(t1+1.5));
Serial.println("humidity2 = " + String(h2));
Serial.println("humidity3 = " + String(h3));
Serial.println("humidity4 = " + String(h4));

//wait 1 minutes for next reading


delay(60000);

}
Anexo 4.
Código del sensor DHT11 en Arduino IDE.
// Incluimos librería
#include <DHT.h>
// Definimos el pin digital donde se conecta el sensor
#define DHTPIN 2
// Dependiendo del tipo de sensor
#define DHTTYPE DHT11
// Inicializamos el sensor DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Inicializamos comunicación serie
Serial.begin(9600);
// Comenzamos el sensor DHT
dht.begin();
}
void loop() {
// Esperamos 5 segundos entre medidas
delay(5000);

// Leemos la humedad relativa


float h = dht.readHumidity();
// Leemos la temperatura en grados centígrados (por defecto)
float t = dht.readTemperature();
// Leemos la temperatura en grados Fahreheit
float f = dht.readTemperature(true);
// Comprobamos si ha habido algún error en la lectura
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Error obteniendo los datos del sensor DHT11");
return;
}
// Calcular el índice de calor en Fahreheit
float hif = dht.computeHeatIndex(f, h);
// Calcular el índice de calor en grados centígrados
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humedad: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperatura: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print(" *C ");
Serial.print(hif);
}
// Incluimos librería
#include <DHT.h>
// Definimos el pin digital donde se conecta el sensor
#define DHTPIN 2
// Dependiendo del tipo de sensor
#define DHTTYPE DHT11
// Inicializamos el sensor DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
// Inicializamos comunicación serie
Serial.begin(9600);
// Comenzamos el sensor DHT
dht.begin();
}
void loop() {
// Esperamos 5 segundos entre medidas
delay(5000);

// Leemos la humedad relativa


float h = dht.readHumidity();
// Leemos la temperatura en grados centígrados (por defecto)
float t = dht.readTemperature();
// Leemos la temperatura en grados Fahreheit
float f = dht.readTemperature(true);
// Comprobamos si ha habido algún error en la lectura
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println("Error obteniendo los datos del sensor DHT11");
return;
}
// Calcular el índice de calor en Fahreheit
float hif = dht.computeHeatIndex(f, h);
// Calcular el índice de calor en grados centígrados
float hic = dht.computeHeatIndex(t, h, false);
Serial.print("Humedad: ");
Serial.print(h);
Serial.print(" %\t");
Serial.print("Temperatura: ");
Serial.print(t);
Serial.print(" *C ");
Serial.print(f);
Serial.print(" *F\t");
Serial.print(" *C ");
Serial.print(hif);
}
Anexo 5.
Código del sensor yl 100 en Arduino.
int SensorPin = A0;
void setup() {
Serial.begin(9600);
}
void loop() {
int humedad = analogRead(SensorPin);
Serial.println(humedad);
delay(1000);
}
Anexo 6.
Cálculo de la humedad de la tierra.

You might also like