Anda di halaman 1dari 44

Page 2 of 46

Indice
1. Introduccion
1.1. La casa Domotica
1.2. Arduino
1.2.1. Caracteristicas Generales
1.2.2. Alimentacion de Energia
1.2.3. Memoria
1.2.4. Entradas y Salidas
2. Destinatarios
3. Objetivos
3.1. Metodos
4. Aplicaciones
4.1. Encendido y Control de Sistema de Aire Acondicionado
4.2. Apertura de Puertas de Garaje y Principales de la casa
4.2.1. Material Utilizado
4.2.2. Diagrama de Circuito
4.2.3. Videos (URL)
4.3. Encendido de Semaforos dos Vias
4.3.1. Entradas Fisicas
4.3.2. Salidas Fisicas
4.3.3. Funciones Configurables
4.3.4. Temporizador
4.3.5. Bloque Texto
Page 3 of 46
5. Diagrama
5.1. Esquema del Programa
6. Conexion
6.1. Servidor Web
6.2. Habilitar SSH
6.3. Servidor Web- Apache
6.4. Servidor WebPHP
6.5. Servidor WebMySQL
6.6. Servidor WebphpMyAdmin
6.7. Servidor WebIP Dinamica
6.8. Servidor Web- FIN!
6.9. Errores
6.9.1. Reinicio de los Servicios
7. Interfaz
7.1. Jardinera
7.2. Luces
7.3. Puerta
7.4. Semaforos
7.5. Temperatura
7.6. Puerto Serial
7.7. Controles
7.8. Codigo Arduino
8. Conclusion
9. Fotografias
10. Bibliografia
Page 4 of 46
Introduccion
La casa domtica.
La domtica es un concepto que se refiere a la integracin de las distintas tecnologas en el hogar
mediante el usosimultneo de la electricidad, la electrnica, la informtica y las telecomunicaciones. Su fin
es mejorar la seguridad, el confort, la flexibilidad, las comunicaciones, el ahorro energtico, facilitar el
control integral de los sistemas para los usuarios y ofrecer nuevos servicios.
Algunos de las reas principales de la domtica son:
Automatizacin y Control - incluye el control (abrir / cerrar, on / off y regulacin) de la iluminacin,
climatizacin, persianas y toldos, puertas y ventanas, cerraduras, riego, electrodomsticos,
suministro de agua y gas etc.
Seguridad- incluye alarmas de intrusin, alarmas personales y alarmas tcnicas (incendio, humo,
agua, gas, fallo de suministro elctrico).
Telecomunicaciones- incluye transmisin de voz y datos con redes locales (LAN) para compartir
acceso de alta velocidad a Internet, recursos y el intercambio entre todos los equipos. Adems
permite disfrutar de nuevos servicios como Telefona sobre IP y Televisin digital.
Audio y video- incluye la distribucin de imgenes de video capturadas con cmaras dentro y
fuera de la casa a toda la casa y a travs de Internet. Otra parte de audio / video trata del
entretenimiento como el multi-room y el "Cine En Casa".
Con la integracin de las especficas funcionalidades de estos sistemas se puede crear servicios de "valor
aadido", como por ejemplo:
Automatizacin de eventos (apagar y encender iluminacin exterior, riego, regular temperaturas
etc.)
Escenarios tipo "Me voy de Casa" que con pulsar un botn podemos bajar todas las persianas,
apagar toda la iluminacin, armar la casa, bajar la temperatura; "Cine en Casa" que con un simple
presin de un botn bajar las persianas del saln, bajar la luz a 25%, armar la planta baja, y
encender el amplificador, el proyector y bajar lapantalla motorizada. "Cena" que regula la
iluminacin del saln y comedor, pone la msica al fondo y enciende la iluminacin de la terraza.
Avisos por telfono, SMS o email de la llegada o salida de terceros a la vivienda (hijos, asistenta,
etc.) o por el contrario, la ausencia de actividad si se queda alguien en la vivienda (nios,
ancianos, etc.) en un determinado intervalo de tiempo.
Page 5 of 46
Arduino
Arduino es una plataforma de hardware libre, basada en una placa con un microcontrolador y un entorno
dedesarrollo, diseada para facilitar el uso de la electrnica en proyectos multidisciplinares.
El hardware consiste en una placa con un microcontrolador Atmel AVR y puertos de entrada/salida.4 Los
microcontroladores ms usados son el Atmega168, Atmega328, Atmega1280, ATmega8 por su sencillez y
bajo coste que permiten el desarrollo de mltiples diseos. Por otro lado el software consiste en un entorno
de desarrollo que implementa el lenguaje de programacin Processing/Wiring y el cargador de arranque
(boot loader) que corre en la placa.
Arduino se puede utilizar para desarrollar objetos interactivos autnomos o puede ser conectado a
software del ordenador (por ejemplo: Macromedia Flash, Processing, Max/MSP, Pure Data). Las placas se
pueden montar a mano o adquirirse. El entorno de desarrollo integrado libre se puede descargar
gratuitamente.
Al ser open-hardware, tanto su diseo como su distribucin es libre. Es decir, puede utilizarse libremente
para el desarrollo de cualquier tipo de proyecto sin haber adquirido ninguna licencia.
El proyecto Arduino recibi una mencin honorfica en la categora de Comunidades Digital en el Prix Ars
Electronica de 2006.
Page 6 of 46
Caractersticas Generales
Microcontrolador ATmega328
Voltaje de Operacion 5V
Voltaje de Entrada(recomendado) 7-12V
Voltaje de Entrada (limites) 6-20V
I/O Pines Digitales 14 (de los cuales 6 pueden proporcionar una salida PWM)
Entradas Analogicas(Pines) 6
Corriente Directa por I/O Pin 40 mA
Corriente Directa 3.3V Pin 50 mA
Memoria Flash 32 KB (ATmega328) of which 0.5 KB used by bootloader
SRAM 2 KB (ATmega328)
EEPROM 1 KB (ATmega328)
Velocidad de reloj 16 MHz
Alimentacin de energa
Puede utilizarse el USB como fuente de alimentacin o puede utilizarse una fuente externa, en mi caso
utilizare el USBpor comodidad.
Memoria
El microcontrolador ATmega328 cuenta con 32KB de memoria. Adems de 2KB de SRAM y 1KB de
EEPROM (la cual puede ser utilizada como lectura o escritura con la librera EEPROM).
Entradas y Salidas
Los 14 pines con los que cuenta el Arduino UNO pueden ser utilizados como entradas o salidas utilizando
las funciones pinMode(), digitalWrite(), digitalRead(). Los pines operan a 5 volts.
Page 7 of 46
Serial: 0 (RX) y 1 (TX): Utilizados para recibir (RX) y transmitir (TX) datos en serie TTL.
Interruptores Externos 2 y 3: Se utilizan para crear una interrupcin cuando se detecta un valor bajo o
algn cambio en algn valor.
PWM pines 3, 5, 6, 9, 10 y 11: Estos pines proporcionan 8 bits de salida PWM con la funcin
analogWrite().
SPI: 10 (SS), 11 (MOSI), 12(MISO), 13 (SCK): Estos pines se utilizan para la comunicacin SPI utilizando
la librera SPI.
LED13: Un led incorporado en el Arduino que muestra cuando un valor es alto se enciende y cuando es
bajo permanece apagado.
Destinatarios
Este trabajo est planteado para que los alumnos de ingeniera se familiaricen con un nuevo concepto,
que hoy en da, puede ser desconocido para muchos, pero quiz, en un futuro, en todas las casas
hagan uso de l, como es la domtica. Para ello, introducimos los conceptos bsicos, por ejemplo:
sensores, actuadores, autmata programable, distribucin de cableado, programacin del autmata, etc.
Se desarrolla dentro de la asignatura de Micro controladores
Objetivos
Acercar a los alumnos al conocimiento de la domtica, sus posibilidades y aplicaciones.
Fomentar las instalaciones domticas en las viviendas. Creemos que los costes actuales que supone la
automatizacin de las viviendas no justifica el bajsimo uso de ellas.
Conocer los principales sensores y actuadores usados endomtica.
Trabajar en grupo favoreciendo la divisin del trabajo, la toma de decisiones y el trabajo responsable.
Medios
Este trabajo se realizo en las instalaciones de la y Hogares de los Alumnos donde se improvisaron
talleres de diversasespecialidades carpintera , electricidad, electrnica y programacin, utilizando las
aulas de Micro controladores y Ensamblador .El equipo contar con el acceso a un ordenador. Se prev
una exposicin de cinco aplicaciones sobre esta casa domtica.
Page 8 of 46
Aplicaciones
1. Encendido de luces por secciones
2. Encendido y control de sistema de Aire Acondicionado.
3. Encendido de sistemas de riego en jardinera
4. Apertura de puertas de garaje y principales de la casa
5. Encendido de semforo de 2 vas.
Encendido y control de sistema de Aire Acondicionado.
Ventilador por control de temperatura
Material:
Cantidad Nombre productos
2- Placas perforadas
2- LM317
2- C1100nF
2- R10k (termistor)
2- R15K
2- C210uF
2- VR 10k(Potonciometro)
2- Venitlador
Este circuito regula de manera automtica la velocidad del motor de un ventilador en funcin de la
temperatura.
El termistor debe estar separado del ventilador para obtener un mejor funcionamiento el cual al
incrementar sutemperatura dejara fluir mayor voltaje.
El circuito mantendr el ventilador a una velocidad baja mientras la temperatura ambiental se mantenga a
un nivel tambin bajo mientras la temperatura vaya subiendo, la velocidad del ventilador tambin subir.
Ademsdel termistor como sensor de temperatura utilizaremos el regulador de tensin LM317 el cual
soporta 1,5 A de corriente; para nuestro proyecto ms que suficiente.
El termistor es del tipo NTC el cual disminuye su resistencia al aumentar la temperatura de su superficie y
al estar conectado al pin 1 (ajuste) del regulador hace que el LM317 varie el voltaje de salida (pin 2).
Page 9 of 46
Calibracin.- Este circuito tiene la posibilidad de regular la velocidad mnima que tendr el ventilador a
temperatura ambiente la cual puede ser ajustada mediante el resistor variable VR1 (Termistor).
Para calibrar alimente el circuito con 12VDC y seguidamente ajuste VR1 hasta que el ventilador tome la
velocidad deseada.
Apertura de puertas de garaje y principales de la casa
Page 10 of 46
Material Utilizado
1. Arduino Uno
2. 2 Motores DC
3. 2 Transistores Tip110
4. 2 Resistencias 330
5. Protoboard
6. Cables Jumpers
7. Legos
Page 12 of 46
Encendido de semforo de 2 vas usando microcontrolador
Zelio soft de Schneider Electric.
Page 13 of 46
Page 14 of 46
Entradas fsicas
N. Smbolo Funcin Candado Parmetros Localizacin(L/C) Comentario
I1 Entradas DIG --- Nohayparmetros (1/1) ARRANQUE YPARO
I2 Entradas DIG --- Nohayparmetros (30/2) ENT.SIS. RIEGO
I3 Entradas DIG --- Nohayparmetros (33/2) ENT. SIST. PARA AIREACOND.
Salidas fsicas
N. Smbolo Funcin Remanencia Localizacin(L/C) Comentario
Q1 Salidas DIG No (4/6) VERDE 1
Q2 Salidas DIG No (5/6) AMARILLO1
Q3 Salidas DIG No (13/6) ROJO1
Q4 Salidas DIG No (3/6) ROJO2
Q5 Salidas DIG No (15/6) AMARILLO2
Q6 Salidas DIG No (14/6) VERDE 2
Q7 Salidas DIG No (31/6) SALIDASISTEMA RIEGO
Q8 Salidas DIG No (34/6) SALIDAPARA AIREACOND.
Funciones configurables
N. Smbolo Funcin Candado Remanencia Pa
r
me
tro
s
Localizacin(L/C) Comentario
C1 Contadores No No
Valor quesedeseaalcanzar: 5Impulsos
SalidaONcuandoel valor alcanzalapreseleccin
(5/3) (6/2) (10/6) (11/2)
(13/2) (16/3) (18/2)
(26/6)
CONT.AMARILLO1
C2 Contadores No No
Valor quesedeseaalcanzar: 5Impulsos
SalidaONcuandoel valor alcanzalapreseleccin
(15/3) (16/2) (19/6)
(22/2) (27/6)
CONT.AMARILLO2
M1 Rels auxiliares --- No
Nohayparmetros
(1/6) (4/1) (8/2) ENCLAVEDEINICIO
M2 Rels auxiliares --- No
Nohayparmetros
(3/3) (6/6) (7/3) ENCLAVEDEVERDE1,ROJO1
M3 Rels auxiliares --- No
Nohayparmetros
(12/3) (16/6) (17/3) ENCLAVEVERDE2,ROJO1
M4 Rels auxiliares --- No
Nohayparmetros
(30/6) (31/2) ENCENDIDO,APAGADO
M5 Rels auxiliares --- No
Nohayparmetros
(33/6) (34/2) ENCENDIDO,APAGADO
T1 Temporizadores No No Ver detalles ams distancia
(4/3) (6/3) (8/6)
(9/2) (22/6)
TIEMPOVERDE1,ROJO2
T2 Temporizadores No No Ver detalles ams distancia
(5/2) (9/6) (10/2)
(23/6)
INTERMITENTEAMARILLO
T3 Temporizadores No No Ver detalles ams distancia
(13/3) (18/6) (20/2)
(24/6)
TIEMPOVERDE2,ROJO1
T4 Temporizadores No No Ver detalles ams distancia
(15/2) (19/2) (20/6)
(25/6)
INTERMITENTEAMARILLO2
X1 Bloques textos --- --- Ver detalles ams distancia (2/6) (28/6) ALUMNOS YPLANTEL
X2 Bloques textos --- --- Ver detalles ams distancia (11/6) (29/6) CATEDRATICO
Page 15 of 46
Temporizador
Bloque texto
Page 16 of 46
Diagrama
Esquema del programa
Conexion:
Antes de empezar recomiendo tener instalado y configurado la versin de Debian oficial de la web de Raspberry Pi.
En la web del IEEEsb-UniOvi he escrito un artculo explicando los pasos para instalar y configurar adecuadamente el
sistema.
Servidor Web
Hay que instalar/configurar 6 tipos de programas: Acceso SSH (para administrar remotamente), Apache
(servidor), PHP (para las pginasdinmicas), MySQL (base de datos), phpMyAdmin (para administrar
fcilmente las bases de datos) y Cliente de DDNS (para mantener actualizada la IP de casa).
Para ello usar el manual publicado en: , y pondr aqu un resumen (recomiendo visitar la web original,
pues viene todo explicado paso a paso).
Habilitar SSH
Nos permitir ejecutar los comandos de la consola desde otro ordenador y de paso podremos acceder a
los ficheros del Raspberry Pi usando un cliente de sFTP (recomiendo utilizar FileZilla).
Comandosa ejecutar (en el Raspberry Pi):
Page 17 of 46
1sudoservice sshstart
Para iniciar el servicio ssh.
1sudoinsserv ssh
Para que se inicie siempre que encendamos el Raspberry Pi se pueda utilizar el SSH. Desde que
ejecutamos sto, los siguientes comandos que hay eneste manual se pueden ejecutar desde el propio
Raspberry Pi o desde otro ordenador (conectndonos al Raspberry Pi usando SSH).
Servidor WebApache
[WEB original, en ingls] Para que todo funcione se necesita instalar el propio servidor, el ms comn es
Apache. Antes de empezar hay que prepararse para que todo funcione. Primero crearemos el grupo de
usuarios para el servidor:
1
2
sudogroupadd www-data
usermod-a-G www-data www-data
Y despus actualizamos los repositorios para evitar fallos en la instalacin:
1sudoapt-get update
Llegados a este punto, y antes de empezar la instalacin tambin recomiendo actualizar los posibles
programas que tengamos sinactualizar, mediante el comando:
1sudoapt-get upgrade
Ahora ya podremos instalar el Apache:
1apt-get install apache2
Si todo ha ido bien, podremos visitar desde el navegador la pgina web de prueba, se titular It works! y
un par de frases ms. Si no funcionara nos dara un error de no encontrado. Para poder visitar la web
desde otro ordenador de nuestra habr que conocer la IP del Raspberry Pi (en la web de las instrucciones
hay capturas de pantalla ms esclarecedoras) y para saber la IP se ejecutar el comando:
1ifconfig
En el que el apartado inet add: veremos la IP (de la red eth0). Habitualmente ser algo del tipo
192.168.10.xx
NOTA: La IP 127.0.0.1 es una IP reservada que se usa para conectarse al propio ordenador o para
comprobar que funciona la Red, ms informacin en laWikipedia: Localhost.
Page 18 of 46
Accedemos con el navegador a la IP del Raspberry Pi desde nuestro ordenador: http://192.168.2.105(en
tu caso ser otra IP diferente). Si queremos aadir ms ficheros, carpetas y similar se encontrarn en el
directorio/var/www/ del Raspberry Pi. Hagamos un Hola mundo:
1sudonano /var/www/holamundo.htm
Y escribimos lo siguiente en el fichero:
1
2
3
4
5
6
7
8
9
<html>
<head>
<title>Titulo de la web</title>
</head>
<body>
<h1>Hola mundo</h1>
<p>Acabo de escribir mi primera web en mi Raspberry Pi.<br />&iquest;Mola, no?</p>
</body>
</html>
Para cerrarlo, como siempre, Control+X, nos preguntar si quieres guardar el bfer (pulsando la S, para
decir que s) y luego ENTER para guardar el fichero con el nombre que pusimos antes. Ahora si visitamos:
http://192.168.2.105/holamundo.htmveremos nuestra pgina web.
Servidor WEBPHP
[WEB original, en ingls] Con Apache se pueden mostrar pginas con HTML, pero parahacer webs de
verdad ser necesario poder ejecutar contenido dinmico, y en esto el PHP es el rey. Procedamos a su
instalacin:
1sudoapt-get install php5
Tras terminar, instalemos los dems paquetes que podramos necesitar (en la web original ponen ms
paquetes, as que pongo lo que a mi me funcion):
1
sudoapt-get install libapache2-mod-php5 libapache2-mod-perl2 php5 php5-cli php5-common php5-curl php5-dev php5-gd
php5-imap php5-ldap php5-mhash php5-mysql php5-odbc
Tras esta segunda instalacin, reiniciar (sudo reboot).
Y para comprobar que funciona, haremos la web de pruebas de PHP, que consiste en una nica funcin
(son los mismos pasos que para crear la web en html):
1sudonano /var/www/phpinfo.php
Y luego rellenar el fichero con lo siguiente:
1
2
3
<?php
phpinfo();
?>
Page 19 of 46
Si al entrar enhttp://192.168.2.105/phpinfo.php(usar la IP que corresponda) vemos una web con mucha
informacin es que todo ha funcionado correctamente.
Servidor WEB - MySQL
[WEB original, en ingls] Con Apache y PHP ya podremos hacer webs dinmicas y muy chulas, pero en
cuanto nos demos cuenta, necesitaremos una base de datos, lo ms normal es utilizar MySQL,
instalmoslo:
1sudoapt-get install mysql-server mysql-client php5-mysql
Tras la instalacin, reiniciar. Y al terminar de reiniciar iniciaremos el servidor de MySQL:
1sudoservice mysql start
Para comprobar que funciona ejecutaremos el siguiente comando (siendo CONTRASEA la contrasea
que hayamos puesto antes, ojo, que delante de nuestra contrasea hay que poner una p):
1mysql -uroot -pCONTRASEA
Si aparece mysql> en la pantalla es que todo ha funcionado. Para poder volver a ejecutar comandos de
Linux normales pulsaremos Control+C y desaparecer el mysql> para mostrar el habitual
pi@raspberrypi:~$.
Durante la instalacin preguntar por la contrasea del administrador de la base de datos, recomiendo
utilizar una contrasea segura y diferente de la que usemos en el Raspberry Pi.
Servidor WEB - phpMyAdmin
[WEB original, en ingls] Para administrar una base de datos MySQL lo ms sencillo es utilizar
phpMyAdmin, pues tiene una interfaz web con mucha ayuda y fcil de utilizar.
1sudoapt-get install libapache2-mod-auth-mysql php5-mysql phpmyadmin
Durante la instalacin nos preguntar qu tipo de servidor tenemos, seleccionaremos Apache(aparece un
* en los corchetes, se marca/desmarca con el espacio y se acepta con el ENTER). Despus preguntar si
se quiere configurar la base de datos, diremos que s. Y nos preguntar por la contrasea de MySQL (la
que pusimos antes) y a continuacin por una contrasea para phpMyAdmin (recomendable que sea
diferente, pero si es para pruebas podemos usar la misma). Al finalizar editaremos el siguiente fichero:
1sudonano /etc/php5/apache2/php.ini
El siguiente cdigo se puede escribir en cualquier sitio, pero para ser coherentes bajaremos unos dos
tercios de la web hasta encontrar la seccin Dynamic Extensions y escribiremos en una nueva lnea (es
decir, que la lnea no empiece por ;), yo lo hice justo despus del ttulo:
1extension=mysql.so
Page 20 of 46
Guardamos el fichero con los cambios efectuados y visitamos la siguiente web (usando la IP que tenga
nuestro rasPi): http://192.168.2.105/phpmyadmin/ En este punto es muy posible que no funcione,
ejecutaremos los 2 siguiente comandos:
1
2
sudoln-s/etc/phpmyadmin/apache.conf /etc/apache2/conf.d/phpmyadmin.conf
sudo/etc/init.d/apache2reload
Tras ejecutarlos actualizar en el navegador (en lugar de pulsar F5 pulsar Control+F5). Si pese a todo no
funcionase, reiniciar el Raspberry Pi.
En la web del phpMyAdmin el usuario ser root y la contrasea la que hayamos elegido cuando lo
instalamos.
Servidor WEB - IP dinmica
Con casi total seguridad en nuestra casa tendremos una IP dinmica (esto significa que cambiar de vez
en cuando). Para que nuestra webest siempre visible necesitaremos algo estable y permanente en el
tiempo. Para eso existen servicios como DynDNS No-IP, adems de crear una cuenta en esos servicios
necesitaremos instalar un programa en el Raspberry Pi que mantenga actualizada nuestra IP actual [Web
original]:
1sudoapt-get install ddclient
Durante la instalacin preguntar los datos de registro. Y si queremos ejecutar el cliente cuando
establezca unaconexin PPP, diremos que no, para que se ejecute como demonio, y ejecutaremos la
comprobacin segn las veces que reiniciemos el mdem cada da? = comprobar cada 1h. Cada mes?
= comprobar cada 6h.
Si fuese necesario volver a cambiarlos podemos utilizar el siguiente comando:
1sudodpkg-reconfigure ddclient
Servidor WEB - FIN!
Y eso es todo, ahora tendremos un servidor web completo, no podremos tener miles de visitas, pero para
hacer pruebas y publicar nuestra primera web es lo ms barato que puede existir, ya que con el coste de la
electricidad actual, tener el Raspberry Pi encendido las 24h durante todo el mes, nos costar un poco
menos de 1,10 mientras que cualquier hosting con caractersticas similares costar algo ms del doble,
entre 2 y 3 mensuales.
Adems podemos desconectar todo lo que tengamos al Raspberry Pi, pues con alimentar con un cargador
de mvil (mnimo de 700mA) y poner el cable de red ya funcionar. Como tenemos el SSH no precisamos
de ratn y teclado, ni mucho menos de una pantallaexterna.
Page 21 of 46
Errores Encontrados
Error ServerName
Al iniciarse el Raspberry Pi dar un error con el siguiente texto:
Could not reliably determine the servers fully qualified domain name, using 127.0.0.1 for ServerName
Una manera de solucionarlo esescribiendo una nueva lnea que contenga ServerName
nombre.servidordns.org en los 2 ficheros diferentes:
Una nueva lnea en el siguiente fichero:
1sudonano /etc/apache2/httpd.conf
Una lnea para cada <VirtualHost > que tengamos en:
1sudonano /etc/apache2/sites-enabled/000-default
Ser necesario reiniciar Apache para que se apliquen los cambios.
Reinicio de los Servicios
Reinicio de Apache:
1sudo/etc/init.d/apache2restart
Reinicio de MySQL:
1sudo/etc/init.d/mysql restart
Si se reemplaza restart por stop parar el servidor correspondiente (para arrancarlo sera necesario
escribir start).
Page 22 of 46
Interfaz
Jardinera
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.Estilo1 {font-family: Verdana, Arial, Helvetica, sans-serif}
.Estilo2 {font-size: 60px}
.Estilo3 {font-size: 50px}
.Estilo4 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 50px; }
-->
</style>
</head>
<body>
<div align="center">
<h1 class="Estilo1 Estilo2">Contol de Riego </h1>
<table width="688" border="2" cellpadding="3" cellspacing="2" bgcolor="#0099CC">
<tr>
<td width="320" class="Estilo4">Riego Exterior</td>
<td width="171" class="Estilo4"><div align="center"><a href="<?=$_SERVER[PHP_SELF] . "?action=on"
?>">ON</a></div></td>
<td width="161" class="Estilo4"><div align="center"><a href="<?=$_SERVER[PHP_SELF] . "?action=off"
?>">OFF</a></div></td>
</tr>
</table>
<p class="Estilo1"><span class="Estilo3"><a href="control.php">Regresar</a></span></p>
<p class="Estilo1">&nbsp;</p>
</div>
</body>
</html>
<?php
if (isset($_GET[action])) {
//Action required
//Load the serial port class
require("php_serial.class.php");
//Initialize the class
$serial = new phpSerial();
//Specify the serial port to use... in this case COM1
$serial->deviceSet("/dev/ttyACM0"); //SET THIS TO WHATEVER YOUR SERIAL DEVICE HAPPENS TO BE, YOU CAN FIND
THIS UNDER THE ARDUINO SOFTWARES MENU
//Set the serial port parameters. The documentation says 9600 8-N-1, so
Page 23 of 46
$serial->confBaudRate(9600); //Baud rate: 9600
// $serial->confParity("none"); //Parity (this is the "N" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
// $serial->confCharacterLength(8); //Character length (this is the "8" in "8-N-1") ******THIS PART OF THE CODE WAS NOT
NEEDED
// $serial->confStopBits(1); //Stop bits (this is the "1" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
//$serial->confFlowControl("none"); //******THIS PART OF THE CODE WAS NOT NEEDED
//Now we "open" the serial port so we can write to it
$serial->deviceOpen();
//Issue the appropriate command according to the Arduino source code 0=Green On, 1=Green Off, 2=Red On, 3=Red Off.
if ($_GET[action] == "on") {
//to turn the GREEN LED ON, weissue the command
$serial->sendMessage("z\r");
} else if ($_GET[action] == "off") {
//to turn the GREEN LED OFF, we issue this command
$serial->sendMessage("x\r");
}
//Were done, so close the serial port again
$serial->deviceClose();
}
?>
Luces
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.Estilo1 {font-family: Arial, Helvetica, sans-serif}
.Estilo5 {font-size: 36}
.Estilo6 {font-family: Arial, Helvetica, sans-serif; font-size: 36; }
.Estilo7 {font-size: 60px}
.Estilo9{font-family: Arial, Helvetica, sans-serif; font-size: 50px; }
.Estilo10 {font-size: 50px}
.Estilo11 {color: #000000; font-family: Arial, Helvetica, sans-serif; font-size: 50px; }
-->
</style>
</head>
<body>
<div align="center">
<h1 class="Estilo1 Estilo7">Control de Luces </h1>
<table width="699" height="590" border="2" cellpadding="3" cellspacing="2">
<tr bgcolor="#0099FF">
<td width="313" height="89" class="Estilo6"><span class="Estilo9">Sala 1 </span></td>
Page 24 of 46
<td width="172" class="Estilo5"><div align="center" class="Estilo1 Estilo10"><a href="<?=$_SERVER[PHP_SELF] .
"?action=sala1On" ?>">ON</a></div></td>
<td width="178" class="Estilo5"><div align="center" class="Estilo9"><a href="<?=$_SERVER[PHP_SELF] .
"?action=sala1Off" ?>">OFF</a></div></td>
</tr>
<tr bgcolor="#3366CC">
<td height="93" class="Estilo9">Sala 2 </td>
<td class="Estilo5"><div align="center" class="Estilo9"><a href="<?=$_SERVER[PHP_SELF] . "?action=sala2On"
?>">ON</a></div></td>
<td class="Estilo5"><div align="center" class="Estilo9"><a href="<?=$_SERVER[PHP_SELF] . "?action=sala2Off"
?>">OFF</a></div></td>
</tr>
<tr bgcolor="#0099FF">
<td height="97" class="Estilo6"><span class="Estilo9">Comedor</span></td>
<td class="Estilo5"><div align="center" class="Estilo9"><a href="<?=$_SERVER[PHP_SELF] . "?action=comedorOn"
?>">ON</a></div></td>
<td class="Estilo5"><div align="center" class="Estilo9"><a href="<?=$_SERVER[PHP_SELF] . "?action=comedorOff"
?>">OFF</a></div></td>
</tr>
<tr bgcolor="#3366CC">
<td height="93" class="Estilo9">Recamara 1</td>
<td class="Estilo5"><div align="center" class="Estilo11"><a href="<?=$_SERVER[PHP_SELF] . "?action=rec1On"
?>">ON</a></div></td>
<td class="Estilo5"><div align="center" class="Estilo11"><a href="<?=$_SERVER[PHP_SELF] . "?action=rec1Off"
?>">OFF</a></div></td>
</tr>
<tr bgcolor="#0099FF">
<td height="98" class="Estilo9">Recamara 2 </td>
<td class="Estilo5"><div align="center" class="Estilo9"><a href="<?=$_SERVER[PHP_SELF] . "?action=rec2On"
?>">ON</a></div></td>
<td class="Estilo5"><div align="center" class="Estilo9"><a href="<?=$_SERVER[PHP_SELF] . "?action=rec2Off"
?>">OFF</a></div></td>
</tr>
<tr bgcolor="#3366CC">
<td height="102" class="Estilo6"><span class="Estilo9">Bano</span></td>
<td class="Estilo5"><div align="center" class="Estilo9"><a href="<?=$_SERVER[PHP_SELF] . "?action=banoOn"
?>">ON</a></div></td>
<td class="Estilo5"><div align="center" class="Estilo9"><a href="<?=$_SERVER[PHP_SELF] . "?action=banoOff"
?>">OFF</a></div></td>
</tr>
</table>
<p class="Estilo1"><span class="Estilo7"><a href="control.php">Regresar</a></span></p>
</div>
</body>
</html>
<?php
if (isset($_GET[action])) {
//Action required
//Load the serial port class
Page 25 of 46
require("php_serial.class.php");
//Initialize the class
$serial = new phpSerial();
//Specify the serial port to use... in this case COM1
$serial->deviceSet("/dev/ttyACM0"); //SET THIS TO WHATEVER YOUR SERIAL DEVICE HAPPENS TO BE, YOU CAN FIND
THIS UNDER THE ARDUINO SOFTWARES MENU
//Set the serial port parameters. The documentation says 9600 8-N-1, so
$serial->confBaudRate(9600); //Baud rate: 9600
// $serial->confParity("none"); //Parity (this is the "N" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
// $serial->confCharacterLength(8); //Character length (this is the "8" in "8-N-1") ******THIS PART OF THE CODE WAS NOT
NEEDED
// $serial->confStopBits(1); //Stop bits (this is the "1" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
//$serial->confFlowControl("none"); //******THIS PART OF THE CODE WAS NOT NEEDED
//Now we "open" the serial port so we can write to it
$serial->deviceOpen();
//Issue the appropriate command according to the Arduino source code 0=Green On, 1=Green Off, 2=Red On, 3=Red Off.
if ($_GET[action] == "sala1On") {
//to turn the GREEN LED ON, we issue the command
$serial->sendMessage("8\r");
} else if ($_GET[action] == "sala1Off") {
//to turn the GREEN LED OFF, we issue this command
$serial->sendMessage("9\r");
}
if ($_GET[action] == "sala2On") {
//to turn the RED LED ON, we issue the command
$serial->sendMessage("0\r");
} else if ($_GET[action] == "sala2Off") {
//to turn the RED LED OFF, we issue this command
$serial->sendMessage("1\r");
}
if ($_GET[action] == "comedorOn") {
//to turn the RED LED ON, we issue the command
$serial->sendMessage("6\r");
} else if ($_GET[action] == "comedorOff") {
//to turn the RED LED OFF, we issue this command
$serial->sendMessage("7\r");
}
if ($_GET[action] == "rec1On") {
//to turn the RED LED ON, we issue the command
$serial->sendMessage("2\r");
} else if ($_GET[action] == "rec1Off") {
//to turn theRED LED OFF, we issue this command
$serial->sendMessage("3\r");
}
if ($_GET[action] == "rec2On") {
//to turn the RED LED ON, we issue the command
$serial->sendMessage("4\r");
} else if ($_GET[action] == "rec2Off") {
//to turn the RED LED OFF, we issue this command
Page 26 of 46
$serial->sendMessage("5\r");
}
if ($_GET[action] == "banoOn") {
//to turn the RED LED ON, we issue the command
$serial->sendMessage("q\r");
} else if ($_GET[action] == "banoOff") {
//to turn the RED LED OFF, we issue this command
$serial->sendMessage("w\r");
}
//Were done, so close the serial port again
$serial->deviceClose();
}
?>
Puerta
<!DOCTYPE HTMLPUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.Estilo1{font-family: Verdana, Arial, Helvetica, sans-serif}
.Estilo2 {font-size: 60px}
.Estilo3 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 60px; }
.Estilo4 {font-size: 50px}
-->
</style>
</head>
<body>
<div align="center">
<h1 class="Estilo1 Estilo2">Control de Puertas </h1>
<table width="882" border="2" cellpadding="3" cellspacing="2" bgcolor="#0099CC">
<tr>
<td width="316" height="136" class="Estilo3 Estilo4">Pricipal</td>
<td width="265" class="Estilo3"><div align="center" class="Estilo4"><a href="<?=$_SERVER[PHP_SELF] . "?action=open"
?>">CERRAR</a></div></td>
<td width="265" class="Estilo3"><div align="center" class="Estilo4"><a href="<?=$_SERVER[PHP_SELF] . "?action=close"
?>">ABRIR</a></div></td>
</tr>
</table>
<p class="Estilo1"><a href="control.php" class="Estilo4">Regresar</a></p>
</div>
</body>
</html>
<?php
Page 27 of 46
if (isset($_GET[action])) {
//Action required
//Load the serial port class
require("php_serial.class.php");
//Initialize the class
$serial = new phpSerial();
//Specify the serial port to use... in this case COM1
$serial->deviceSet("/dev/ttyACM0"); //SET THIS TO WHATEVER YOUR SERIAL DEVICE HAPPENS TO BE, YOU CAN FIND
THIS UNDER THE ARDUINO SOFTWARES MENU
//Set the serial port parameters. The documentation says 9600 8-N-1, so
$serial->confBaudRate(9600); //Baud rate: 9600
// $serial->confParity("none"); //Parity (this is the "N" in "8-N-1") ******THIS PART OF THE CODE WAS NOTNEEDED
// $serial->confCharacterLength(8); //Character length (this is the "8" in "8-N-1") ******THIS PART OF THE CODE WAS NOT
NEEDED
// $serial->confStopBits(1); //Stop bits (this is the "1" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
//$serial->confFlowControl("none"); //******THIS PART OF THE CODE WAS NOT NEEDED
//Now we "open" the serial port so we can write to it
$serial->deviceOpen();
//Issue the appropriate command according to the Arduino source code 0=Green On, 1=Green Off, 2=Red On, 3=Red Off.
if ($_GET[action] == "open") {
//to turn the GREEN LED ON, we issue the command
$serial->sendMessage("c\r");
} else if ($_GET[action] == "close") {
//to turn the GREEN LED OFF, we issue this command
$serial->sendMessage("v\r");
}
//Were done, so close the serial port again
$serial->deviceClose();
}
?>
Semaforos
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.Estilo1 {font-size: 60px}
.Estilo2 {font-size: 50px}
.Estilo3 {font-family: Verdana, Arial, Helvetica, sans-serif}
.Estilo4 {font-size: 50px; font-family: Verdana, Arial, Helvetica, sans-serif; }
-->
Page 28 of 46
</style>
</head>
<body>
<div align="center">
<h1 class="Estilo1 Estilo3">Semaforo</h1>
<p class="Estilo4"><ahref="<?=$_SERVER[PHP_SELF] . "?action=on" ?>">ON/OFF</a></p>
<p class="Estilo4">&nbsp;</p>
<p class="Estilo4">&nbsp;</p>
<p class="Estilo2"><span class="Estilo3"><a href="control.php">Regresar</a></span></p>
</div>
</body>
</html>
<?php
if (isset($_GET[action])) {
//Action required
//Load the serial port class
require("php_serial.class.php");
//Initialize the class
$serial = new phpSerial();
//Specify the serial port to use... in this case COM1
$serial->deviceSet("/dev/ttyACM0"); //SET THIS TO WHATEVER YOUR SERIAL DEVICE HAPPENS TO BE, YOU CAN FIND
THIS UNDER THE ARDUINO SOFTWARES MENU
//Set the serial port parameters. The documentation says 9600 8-N-1, so
$serial->confBaudRate(9600); //Baud rate: 9600
// $serial->confParity("none"); //Parity (this is the "N" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
// $serial->confCharacterLength(8); //Character length (this is the "8" in "8-N-1") ******THIS PART OF THE CODEWAS NOT
NEEDED
// $serial->confStopBits(1); //Stop bits (this is the "1" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
//$serial->confFlowControl("none"); //******THIS PART OF THE CODE WAS NOT NEEDED
//Now we "open" the serial port sowe can write to it
$serial->deviceOpen();
//Issue the appropriate command according to the Arduino source code 0=Green On, 1=Green Off, 2=Red On, 3=Red Off.
if ($_GET[action] == "on") {
//to turn the GREEN LED ON, we issue the command
$serial->sendMessage("a\r");
}
//Were done, so close the serial port again
$serial->deviceClose();
}
?>
Temperatura
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
Page 29 of 46
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.Estilo1 {
font-size: 60px;
font-family: Verdana, Arial, Helvetica, sans-serif;
}
.Estilo2 {font-size: 50px}
.Estilo3 {font-family: Verdana, Arial, Helvetica, sans-serif}
-->
</style>
</head>
<body>
<div align="center">
<h1 class="Estilo1">Control de temperatura</h1>
<table width="650" border="2" cellspacing="2" cellpadding="3">
<tr>
<td width="348" class="Estilo3"><span class="Estilo2">Ventilador 1 </span></td>
<td width="135" class="Estilo3"><div align="center" class="Estilo2"><a href="<?=$_SERVER[PHP_SELF] .
"?action=ven1on" ?>">ON</a></div></td>
<td width="131" class="Estilo3"><div align="center" class="Estilo2"><a href="<?=$_SERVER[PHP_SELF] .
"?action=ven1off" ?>">OFF</a></div></td>
</tr>
<tr>
<td class="Estilo3"><span class="Estilo2">Ventilardor 2 </span></td>
<td class="Estilo3"><div align="center" class="Estilo2"><a href="<?=$_SERVER[PHP_SELF] . "?action=ven2on"
?>">ON</a> </div></td>
<td class="Estilo3"><div align="center" class="Estilo2"><a href="<?=$_SERVER[PHP_SELF] . "?action=ven2off"
?>">OFF</a></div></td>
</tr>
</table>
<p class="Estilo2"><span class="Estilo3"><a href="control.php">Regresar</a></span></p>
</div>
</body>
</html>
<?php
if (isset($_GET[action])) {
//Action required
//Load the serial port class
require("php_serial.class.php");
//Initialize the class
$serial = new phpSerial();
//Specify the serial port to use... in this case COM1
$serial->deviceSet("/dev/ttyACM0"); //SET THIS TO WHATEVER YOUR SERIAL DEVICE HAPPENS TO BE, YOU CAN FIND
THIS UNDER THE ARDUINO SOFTWARES MENU
//Set the serial port parameters. The documentation says 9600 8-N-1, so
$serial->confBaudRate(9600); //Baud rate: 9600
Page 30 of 46
// $serial->confParity("none"); //Parity (this is the "N" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
// $serial->confCharacterLength(8); //Character length (this is the "8" in "8-N-1") ******THIS PART OF THE CODE WAS NOT
NEEDED
// $serial->confStopBits(1); //Stop bits (this is the "1" in "8-N-1") ******THIS PART OF THE CODE WAS NOT NEEDED
//$serial->confFlowControl("none"); //******THIS PART OF THE CODE WAS NOT NEEDED
//Now we "open" the serial port so we can write to it
$serial->deviceOpen();
//Issue the appropriate command according tothe Arduino source code 0=Green On, 1=Green Off, 2=Red On, 3=Red Off.
if ($_GET[action] == "ven1on") {
//to turn the GREEN LED ON, we issue the command
$serial->sendMessage("e\r");
} else if ($_GET[action] == "ven1off") {
//to turn the GREEN LED OFF, we issue this command
$serial->sendMessage("r\r");
}
if ($_GET[action] == "ven2on") {
//to turn the GREEN LED ON, we issue the command
$serial->sendMessage("d\r");
} else if ($_GET[action] == "ven2off") {
//to turn the GREEN LED OFF, we issue this command
$serial->sendMessage("f\r");
}
//Were done, so close the serial port again
$serial->deviceClose();
}
?>
Puerto Serial
<?php
define ("SERIAL_DEVICE_NOTSET", 0);
define ("SERIAL_DEVICE_SET", 1);
define ("SERIAL_DEVICE_OPENED", 2);
/**
* Serial port control class
* THIS PROGRAM COMES WITH ABSOLUTELY NO WARANTIES !
* USE IT AT YOUR OWN RISKS !
* Changes added by Rizwan Kassim <rizwank@uwink.com> for OSX functionality
* default serial device for osx devices is /dev/tty.serial for machines with a built in serial device
* @author Rmy Sanchez <thenux@gmail.com>
* @thanks Aurlien Derouineau for finding how to open serial ports with windows
* @thanks Alec Avedisyan for help and testing with reading
* @copyright under GPL 2 licence
* do not change this code unless you know what you are getting into. Leaving it as you have received it should work fine!
*/
class phpSerial
{
var $_device = null;
var $_windevice = null;
Page 31 of 46
var $_dHandle = null;
var $_dState = SERIAL_DEVICE_NOTSET;
var $_buffer = "";
var $_os = "";
/**
* This var says if buffer should be flushed by sendMessage (true) or manualy (false)
* @var bool
*/
var $autoflush = true;
/**
* Constructor. Perform some checks about the OS and setserial
* @return phpSerial
*/
function phpSerial ()
{
setlocale(LC_ALL, "en_US");
$sysname = php_uname();
if (substr($sysname, 0, 5) === "Linux")
{
$this->_os = "linux";
if($this->_exec("stty--version") === 0)
{
register_shutdown_function(array($this, "deviceClose"));
}
else
{
trigger_error("No stty availible, unable torun.", E_USER_ERROR);
}
}
elseif (substr($sysname, 0, 6) === "Darwin")
{
$this->_os = "osx";
// We know stty is available in Darwin.
// stty returns 1 when run from php, because "stty: stdin isnt a
// terminal"
// skip this check
// if($this->_exec("stty") === 0)
// {
register_shutdown_function(array($this, "deviceClose"));
// }
// else
// {
// trigger_error("No stty availible, unable to run.", E_USER_ERROR);
// }
}
elseif(substr($sysname, 0, 7) === "Windows")
{
$this->_os = "windows";
Page 32 of 46
register_shutdown_function(array($this, "deviceClose"));
}
else
{
trigger_error("Host OS is neither osx, linux nor windows, unable tu run.", E_USER_ERROR);
exit();
}
}
// OPEN/CLOSE DEVICE SECTION-- {START}
/**
* Device set function : used to set the device name/address.
* -> linux : use the device address, like /dev/ttyS0
* -> osx : use the device address, like /dev/tty.serial
* -> windows : use the COMxx device name, like COM1 (can also be used
* with linux)
* @param string $device the name of the device to be used
* @return bool
*/
function deviceSet ($device)
{
if ($this->_dState !== SERIAL_DEVICE_OPENED)
{
if ($this->_os === "linux")
{
if (preg_match("@^COM(\d+):?$@i", $device, $matches))
{
$device = "/dev/ttyS" . ($matches[1] - 1);
}
if ($this->_exec("stty-F " . $device) === 0)
{
$this->_device = $device;
$this->_dState = SERIAL_DEVICE_SET;
return true;
}
}
elseif ($this->_os === "osx")
{
if ($this->_exec("stty-f " . $device) === 0)
{
$this->_device = $device;
$this->_dState = SERIAL_DEVICE_SET;
return true;
}
}
elseif ($this->_os === "windows")
{
if (preg_match("@^COM(\d+):?$@i", $device, $matches) and $this->_exec(exec("mode "
. $device)) === 0)
{
Page 33 of 46
$this->_windevice = "COM" . $matches[1];
$this->_device = "\\.\com" . $matches[1];
$this->_dState = SERIAL_DEVICE_SET;
return true;
}
}
trigger_error("Specified serial port is not valid", E_USER_WARNING);
return false;
}
else
{
trigger_error("You must close your device before to set an other one", E_USER_WARNING);
return false;
}
}
/**
* Opens the device for reading and/or writing.
* @param string $mode Opening mode : same parameter as fopen()
* @return bool
*/
function deviceOpen ($mode = "r+b")
{
if ($this->_dState === SERIAL_DEVICE_OPENED)
{
trigger_error("The device is already opened", E_USER_NOTICE);
return true;
}
if ($this->_dState === SERIAL_DEVICE_NOTSET)
{
trigger_error("The device must be set before to be open", E_USER_WARNING);
return false;
}
if (!preg_match("@^[raw]\+?b?$@", $mode))
{
trigger_error("Invalid opening mode : ".$mode.". Use fopen() modes.", E_USER_WARNING);
return false;
}
$this->_dHandle = @fopen($this->_device, $mode);
if ($this->_dHandle !== false)
{
stream_set_blocking($this->_dHandle, 0);
$this->_dState = SERIAL_DEVICE_OPENED;
return true;
}
$this->_dHandle = null;
trigger_error("Unable to open the device", E_USER_WARNING);
return false;
}
/**
Page 34 of 46
* Closes the device
* @return bool
*/
function deviceClose ()
{
if ($this->_dState!== SERIAL_DEVICE_OPENED)
{
return true;
}
if (fclose($this->_dHandle))
{
$this->_dHandle = null;
$this->_dState = SERIAL_DEVICE_SET;
return true;
}
trigger_error("Unable to close the device", E_USER_ERROR);
return false;
}
// OPEN/CLOSE DEVICE SECTION-- {STOP}
// CONFIGURE SECTION-- {START}
/**
* Configure the Baud Rate
* Possible rates : 110, 150, 300, 600, 1200, 2400, 4800, 9600, 38400,
* 57600 and 115200.
* @param int $rate the rate to set the port in
* @returnbool
*/
function confBaudRate ($rate)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set the baud rate : the device is either not set or opened",
E_USER_WARNING);
return false;
}
$validBauds = array (
110 =>11,
150 => 15,
300 => 30,
600 => 60,
1200 => 12,
2400 => 24,
4800 => 48,
9600 => 96,
19200 => 19,
38400 => 38400,
57600 => 57600,
115200 => 115200
);
Page 35 of 46
if (isset($validBauds[$rate]))
{
if ($this->_os === "linux")
{
$ret = $this->_exec("stty-F " . $this->_device . " " . (int) $rate, $out);
}
if ($this->_os === "darwin")
{
$ret = $this->_exec("stty-f " . $this->_device . " " . (int) $rate, $out);
}
elseif ($this->_os === "windows")
{
$ret = $this->_exec("mode " . $this->_windevice . " BAUD=" . $validBauds[$rate], $out);
}
else return false;
if ($ret !== 0)
{
trigger_error ("Unable to set baud rate: " . $out[1], E_USER_WARNING);
return false;
}
}
}
/**
* Configure parity.
* Modes : odd, even, none
* @param string $parity one of the modes
* @return bool
*/
function confParity($parity)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set parity : the device is either not set or opened", E_USER_WARNING);
return false;
}
$args = array(
"none" => "-parenb",
"odd" => "parenb parodd",
"even" => "parenb-parodd",
);
if (!isset($args[$parity]))
{
trigger_error("Parity mode not supported", E_USER_WARNING);
return false;
}
if ($this->_os === "linux")
{
$ret = $this->_exec("stty-F " . $this->_device . " " . $args[$parity], $out);
}
Page 36 of 46
else
{
$ret = $this->_exec("mode " . $this->_windevice . " PARITY=" . $parity{0}, $out);
}
if ($ret === 0)
{
return true;
}
trigger_error("Unable to set parity : " . $out[1], E_USER_WARNING);
return false;
}
/**
* Sets the length of a character.
* @param int $int length of a character (5 <= length <= 8)
* @return bool
*/
function confCharacterLength ($int)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set length of a character : the device is either not set or opened",
E_USER_WARNING);
return false;
}
$int = (int) $int;
if ($int < 5) $int = 5;
elseif ($int > 8) $int = 8;
if ($this->_os === "linux")
{
$ret = $this->_exec("stty-F " . $this->_device . " cs" . $int, $out);
}
else
{
$ret = $this->_exec("mode " . $this->_windevice . " DATA=" . $int, $out);
}
if ($ret === 0)
{
return true;
}
trigger_error("Unable to set character length : " .$out[1], E_USER_WARNING);
return false;
}
/**
* Sets the length of stop bits.
* @param float $length the length of a stop bit. It must be either 1,
* 1.5 or 2. 1.5 is not supported under linux and on some computers.
* @return bool
*/
Page 37 of 46
function confStopBits ($length)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set the length of a stop bit : the device is either not set or opened",
E_USER_WARNING);
return false;
}
if ($length != 1 and $length != 2 and $length != 1.5 and !($length == 1.5 and $this->_os=== "linux"))
{
trigger_error("Specified stop bit length is invalid", E_USER_WARNING);
return false;
}
if ($this->_os === "linux")
{
$ret = $this->_exec("stty-F " . $this->_device . " " . (($length == 1) ? "-" : "") . "cstopb", $out);
}
else
{
$ret = $this->_exec("mode " . $this->_windevice . " STOP=" . $length, $out);
}
if ($ret === 0)
{
return true;
}
trigger_error("Unable to set stop bit length : " . $out[1], E_USER_WARNING);
return false;
}
/**
* Configures the flow control
* @param string $mode Set the flow control mode. Availible modes :
* -> "none" : no flow control
* -> "rts/cts" : use RTS/CTS handshaking
* -> "xon/xoff" : use XON/XOFF protocol
* @return bool
*/
function confFlowControl ($mode)
{
if ($this->_dState !== SERIAL_DEVICE_SET)
{
trigger_error("Unable to set flow control mode : the device is either not set or opened",
E_USER_WARNING);
return false;
}
$linuxModes = array(
"none" => "clocal -crtscts-ixon-ixoff",
"rts/cts" => "-clocal crtscts-ixon-ixoff",
Page 38 of 46
"xon/xoff" => "-clocal -crtscts ixon ixoff"
);
$windowsModes = array(
"none" => "xon=off octs=off rts=on",
"rts/cts" => "xon=off octs=on rts=hs",
"xon/xoff" => "xon=onocts=off rts=on",
);
if ($mode !== "none" and $mode !== "rts/cts" and $mode !== "xon/xoff") {
trigger_error("Invalid flow control mode specified", E_USER_ERROR);
return false;
}
if ($this->_os === "linux")
$ret = $this->_exec("stty-F " . $this->_device . " " . $linuxModes[$mode], $out);
else
$ret = $this->_exec("mode " . $this->_windevice . " " . $windowsModes[$mode], $out);
if ($ret === 0) return true;
else {
trigger_error("Unable to set flow control : " . $out[1], E_USER_ERROR);
return false;
}
}
/**
* Sets a setserial parameter (cf man setserial)
* NO MORE USEFUL !
* -> No longer supported
* -> Only use it if you need it
* @param string $param parameter name
* @param string $arg parameter value
* @return bool
*/
function setSetserialFlag ($param, $arg = "")
{
if (!$this->_ckOpened()) return false;
$return = exec ("setserial " . $this->_device . " " . $param . " " . $arg . " 2>&1");
if ($return{0} === "I")
{
trigger_error("setserial: Invalid flag", E_USER_WARNING);
return false;
}
elseif ($return{0} === "/")
{
trigger_error("setserial: Error with device file", E_USER_WARNING);
return false;
}
else
{
Page 39 of 46
return true;
}
}
// CONFIGURE SECTION-- {STOP}
// I/O SECTION-- {START}
/**
* Sends a string to the device
* @param string $str string to be sent to the device
* @param float $waitForReply time to wait for the reply (in seconds)
*/
function sendMessage ($str, $waitForReply = 0.1)
{
$this->_buffer .= $str;
if ($this->autoflush === true) $this->serialflush();
usleep((int) ($waitForReply * 1000000));
}
/**
* Reads the port until no new datas are availible, then return the content.
* @pararm int $count number of characters to be read (will stop before
* if less characters are in the buffer)
* @return string
*/
function readPort ($count = 0)
{
if ($this->_dState !== SERIAL_DEVICE_OPENED)
{
trigger_error("Device must be opened to read it", E_USER_WARNING);
return false;
}
if ($this->_os === "linux" || $this->_os === "osx")
{
// Behavior in OSX isnt to wait for new data to recover, but just grabs whats there!
// Doesnt always work perfectly for me in OSX
$content = ""; $i = 0;
if ($count !== 0)
{
do {
if ($i > $count) $content .= fread($this->_dHandle, ($count - $i));
else $content .= fread($this->_dHandle, 128);
} while (($i += 128) === strlen($content));
}
else
{
do {
$content .= fread($this->_dHandle, 128);
} while (($i += 128) === strlen($content));
}
return $content;
Page 40 of 46
}
elseif ($this->_os === "windows")
{
/* Do nothing : not implented yet */
}
trigger_error("Reading serial port is not implemented for Windows", E_USER_WARNING);
returnfalse;
}
/**
* Flushes the output buffer
* Renamed from flush for osx compat. issues
* @return bool
*/
function serialflush ()
{
if (!$this->_ckOpened()) return false;
if (fwrite($this->_dHandle, $this->_buffer) !== false)
{
$this->_buffer = "";
return true;
}
else
{
$this->_buffer = "";
trigger_error("Error while sending message", E_USER_WARNING);
return false;
}
}
// I/O SECTION-- {STOP}
// INTERNAL TOOLKIT-- {START}
function _ckOpened()
{
if ($this->_dState !== SERIAL_DEVICE_OPENED)
{
trigger_error("Device must be opened", E_USER_WARNING);
return false;
}
return true;
}
function _ckClosed()
{
if ($this->_dState !== SERIAL_DEVICE_CLOSED)
{
trigger_error("Device must be closed", E_USER_WARNING);
return false;
}
return true;
}
Page 41 of 46
function _exec($cmd, &$out = null)
{
$desc = array(
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
$proc = proc_open($cmd, $desc, $pipes);
$ret = stream_get_contents($pipes[1]);
$err = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$retVal = proc_close($proc);
if (func_num_args() == 2) $out = array($ret, $err);
return $retVal;
}
// INTERNAL TOOLKIT-- {STOP}
}
?>
Controles
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Documento sin t&iacute;tulo</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<!--
.Estilo1 {
font-family: Arial, Helvetica, sans-serif;
font-weight: bold;
}
.Estilo4 {font-family: Verdana, Arial, Helvetica, sans-serif}
.Estilo5 {font-size: 60px}
.Estilo6 {font-size: 50px}
.Estilo7 {font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 50px; }
-->
</style>
</head>
<body>
<div align="center" class="Estilo1">
<p class="Estilo5">Control de la Casa </p>
<table width="1104" border="1">
<tr bgcolor="#00FF00">
<td width="420" height="209"><div align="center" class="Estilo4 Estilo6"><a href="luces.php">Luces</a></div></td>
<td width="283"><div align="center" class="Estilo7"><a href="puerta.php">Puertas</a></div></td>
<td width="379"><div align="center" class="Estilo7"><a href="agua.php">Riego</a></div></td>
Page 42 of 46
</tr>
<tr bgcolor="#00FF00">
<td height="197"><div align="center" class="Estilo7"><a href="temp.php">Temperatura</a></div></td>
<td><div align="center" class="Estilo7"><a href="sema.php">Semaforo</a></div></td>
<td><div align="center" class="Estilo7">Percianas</div></td>
</tr>
<tr bgcolor="#00FF00">
<td height="189"><div align="center"><span class="Estilo4"><span class="Estilo4"></span></span></div></td>
<td><div align="center"><span class="Estilo4"><span class="Estilo4"><span
class="Estilo6"></span></span></span></div></td>
<td><div align="center"><span class="Estilo4"><span class="Estilo4"><span
class="Estilo6"></span></span></span></div></td>
</tr>
</table>
<p>&nbsp;</p>
</div>
</body>
</html>
CodigoArduino
#include <Servo.h>
char ms = 0;
int pin3 = 3; //sala2
int pin4 = 4; //recamara 1
int pin5 = 5; //recamara 2
int pin6 = 6; //comedor
int pin7 = 7; //sala 1
int pin8 = 8; //bano
int pin9 = 9; //semaforo
int ledPin1 = 10; //agua
int puerta = 12;
int vent1 = 13;
int vent2 = 14;
Servo myservo;
int pos = 0;
void setup()
{
Serial.begin(9600);
Page 43 of 46
pinMode(pin3,OUTPUT);
pinMode(pin4,OUTPUT);
pinMode(pin5,OUTPUT);
pinMode(pin6,OUTPUT);
pinMode(pin7,OUTPUT);
pinMode(pin8,OUTPUT);
pinMode(pin9,OUTPUT);
pinMode(ledPin1,OUTPUT);
myservo.attach(puerta);
pinMode(vent1,OUTPUT);
pinMode(vent2,OUTPUT);
}
void focos(char ms2)
{
if (ms2 == 0)
{digitalWrite(pin3,HIGH);}
if (ms2 == 1)
{digitalWrite(pin3,LOW);}
if(ms2 == 2)
{digitalWrite(pin4,HIGH);}
if(ms2 == 3)
{digitalWrite(pin4,LOW);}
if(ms2 == 4)
{digitalWrite(pin5,HIGH);}
if(ms2 == 5)
{digitalWrite(pin5,LOW);}
if(ms2 == 6)
{digitalWrite(pin6,HIGH);}
if(ms2 == 7)
{digitalWrite(pin6,LOW);}
if(ms2 == 8)
{digitalWrite(pin7,HIGH);}
if(ms2 == 9)
{digitalWrite(pin7,LOW);}
if(ms2 == q)
{digitalWrite(pin8,HIGH);}
if(ms2 == w)
{digitalWrite(pin8,LOW);}
}
void pulso(char ms3)
{
Page 44 of 46
if(ms3 == a)
{
digitalWrite(pin9,HIGH);
delay(50);
digitalWrite(pin9,LOW);
}
}
void agua(char ms4)
{
if (ms4 == e)
{
digitalWrite(ledPin1,HIGH);
}
if (ms4 == r)
{
digitalWrite(ledPin1,LOW);
}
}
void ctrl_puerta(char ms5)
{
if (ms5 == c){
for(pos=0;pos<=90;pos+=2)
{
myservo.write(pos);
}
}
if (ms5 == v){
for(pos=90;pos>=10;pos-=2)
{
myservo.write(pos);
}
}
}
void ventiladores(char ms6)
{
if (ms6 == e)
{digitalWrite(vent1,HIGH);}
if (ms6 == r)
{digitalWrite(vent1,LOW);}
if (ms6 == d)
{digitalWrite(vent2,HIGH);}
Page 45 of 46
if (ms6 == f)
{digitalWrite(vent2,LOW);}
}
void loop()
{
if (Serial.available() > 0 )
{
ms = Serial.read();
focos(ms);
pulso(ms);
agua(ms);
ctrl_puerta(ms);
ventiladores(ms);
}
}
Conclusiones

Anda mungkin juga menyukai