Beruflich Dokumente
Kultur Dokumente
CURITIBA
2014
II
Orientador:
Prof. Dr. James Alexandre Baraniuk
CURITIBA
2014
III
TERMO DE APROVAÇÃO
ANDRÉ OSTI SAKAGUCHI
DEDICATÓRIA
AGRADECIMENTOS
Albert Einstein
VII
RESUMO
ABSTRACT
Home automation is one of the promising technologies that have been growing
considerably in the world. Quality of life, comfort, security are some of the benefits that
people can have after moving to a smart home. With an intelligent and programmable
system, the equipment of a home shall be controlled and monitored locally or remotely
in an automatically way.
This work focuses on the development and construction of a system of control and
monitoring of houses using open hardware and different types of communication
between the system components, such as: RS485, radio frequency of 433MHz and
2.4GHz, Bluetooth, infrared and ethernet. Through a supervisory the user can make
the total supervision and control of the system.
LISTA DE ILUSTRAÇÕES
LISTA DE TABELAS
SUMÁRIO
RESUMO.......................................................................................................... VII
ABSTRACT ..................................................................................................... VIII
LISTA DE ILUSTRAÇÕES ................................................................................. 1
LISTA DE TABELAS .......................................................................................... 3
LISTA DAS SIGLAS ........................................................................................... 4
SUMÁRIO........................................................................................................... 5
1.1 CONTEXTUALIZAÇÃO ................................................................................ 7
1.2 OBJETIVOS ................................................................................................. 8
1.3 JUSTIFICATIVA ........................................................................................... 8
1.4 DIFERENCIAL EM RELAÇÃO A OUTROS PROJETOS ............................. 9
1.5 ESTRUTURA DA MONOGRAFIA .............................................................. 10
2 AUTOMAÇÃO RESIDENCIAL ...................................................................... 11
3 IMPLEMENTAÇÃO DO PROJETO ............................................................... 14
3.1 EQUIPAMENTOS ...................................................................................... 15
3.1.1 Atuadores ................................................................................................ 16
3.1.2 Sensores ................................................................................................. 18
3.2 MICROCONTROLADOR............................................................................ 21
3.2.1 ATmega328 ............................................................................................. 23
3.2.2 ATtiny85 .................................................................................................. 24
3.3 FONTE DE ALIMENTAÇÃO....................................................................... 25
3.4 CENTRAL................................................................................................... 25
3.5 MÓDULO.................................................................................................... 26
3.6 COMUNICAÇÃO ........................................................................................ 27
3.6.1 RS485 ..................................................................................................... 27
3.6.2 RÁDIO FREQUENCIA............................................................................. 29
3.6.3 Bluetooth ................................................................................................. 32
3.6.4 Ethernet ................................................................................................... 33
3.6.5 INFRAVERMELHO ................................................................................. 35
3.6.6 SUPERVISÓRIO ..................................................................................... 37
3.7.1 Introdução ............................................................................................... 39
3.7.2 Programação do supervisório web .......................................................... 43
6
1 INTRODUÇÃO
1.1 CONTEXTUALIZAÇÃO
1.2 OBJETIVOS
1.3 JUSTIFICATIVA
2 AUTOMAÇÃO RESIDENCIAL
rede elétrica, par trançado, cabo coaxial, infravermelhos, rádio frequência e fibra
óptica.
O ZigBee é um protocolo que diferente do X-10, envia e recebe os dados sem
o uso de fios a frequências de 868 MHz, 915 MHz e também de 2,4 GHz. Os
equipamentos são flexíveis, de fácil instalação e econômicos no ponto de vista de
consumo de energia.
DALI (Digital Addressable Lighting Interface) é um protocolo de comunicação
utilizado para o controle unicamente de iluminação. É constituído de um cabo de dois
fios com fluxo de informação bidirecional (Teixeira, 2011). A norma IEC 60929
especifica o padrão internacional onde independente dos fabricantes dos produtos, o
protocolo assegura a intercambialidade e a interoperabilidade dos dispositivos. O
protocolo DALI não pode ser usado para controle de outros sistemas que não sejam
de iluminação porém, é eficaz para a seleção de informações como por exemplo a
ocorrência de um defeito em uma luminária, fazendo-se útil o seu interfaceamento
com sistemas automáticos em edifícios quando são necessários relatórios de
supervisão remota e emissão de ordens de serviço. Cada unidade que se deseja
controlar com o uso deste protocolo recebe um endereço, assim é possível se
comunicar com cada componente.
3 IMPLEMENTAÇÃO DO PROJETO
O sistema que este trabalho propõe terá por finalidade a integração de todos
os dispositivos necessários para se realizar o gerenciamento e controle de um
domicílio.
Cada ambiente de uma casa possuirá um módulo controlado por ATmega328
ou Attiny85 a fim de fazer o controle de lâmpadas, televisões, cortinas, entre outros.
Além dos módulos acoplados em cada ambiente, também é necessário acoplar uma
central que será capaz de armazenar todos os dados do sistema.
Para realizar a integração entre todos os dispositivos optou-se por estudar
diferentes tipos de comunicação tais como: padrão serial RS485, ondas de rádio
frequência, bluetooth ,protocolo ethernet e raios infra-vermelho. Com esta diversidade
de comunicações o sistema é preparado para as diferentes situações nos domicílios.
Por exemplo o controle de portão, luminárias, aquecimento de piscina, ou seja,
equipamentos que estão em um ambiente externo, sem conexão com o interior da
residência.
Cada módulo terá a possibilidade de se comunicar com outro módulo e
também com a central.
A central estará conectada à internet através da comunicação ethernet com a
finalidade de, através de um supervisório, ter a possibilidade de controlar e monitorar
toda a residência, podendo o usuário interferir nos equipamentos de sua residência
mesmo não estando próximo a ela. Para realização desta operação, a central também
se comunicará com os módulos de forma ativa, ou seja, enviando comandos.
Além do uso do supervisório o usuário poderá fazer o controle de sua
residência através de um controle remoto que emita raios infra-vermelho e também
através de um celular, tablet com o uso do bluetooth.
3.1 EQUIPAMENTOS
fará o processamento das medições feitas pelos sensores e também realizará ações
por meio dos atuadores.
3.1.1 Atuadores
3.1.1.1 Relé
FIGURA 4 - RELÉ
FONTE: ELECTRONICA-PT (2014).
3.1.2 Sensores
3.2 MICROCONTROLADOR
3.2.1 ATmega328
FIGURA 10 - ATMEGA328-PU
FONTE: O AUTOR (2014).
3.2.2 ATtiny85
3.4 CENTRAL
3.5 MÓDULO
3.6 COMUNICAÇÃO
3.6.1 RS485
FIGURA 13 - MAX485
FONTE: O AUTOR (2014).
Este nome é uma padronização criada pelo comitê Electronic Industries Association
onde o objetivo era de padronizar uma interface comum de comunicação de dados
entre vários componentes. Mais informações sobre o MAX485 podem ser vistas no
anexo B.
A comunicação RS485 é feita pela diferença entre as tensões que as linhas
transmitem, resultando em 1 ou 0. Pode ser feita a comunicação half-duplex e full-
duplex. A comunicação half-duplex é um método de envio de dados onde eles
trafegam somente em um sentido por vez, assim, a capacidade total da linha pode ser
usada. Por outro lado, a comunicação full-duplex é um método de envio de dados
simultâneo, ou seja, os dados podem ser enviados e recebidos ao mesmo tempo. Para
o projeto será utilizado a comunicação half-duple.
Existem 4 terminais (DE, RE, GND e VCC) no módulo MAX485 e um borne
de saída (A, B). Os terminais VCC e GND são a alimentação de 5Vcc e o terra
respectivamente, para transmissão é necessário alimentar com 5Vcc os terminais DE
e RE e com o GND nos terminais RE e DE do receptor.
Para realização da comunicação entre os diversos módulos e a central foi
usada a biblioteca VirtualWire.h. Esta biblioteca tem por finalidade o envio de
pequenas mensagens, sem endereçamento utilizando modulação ASK, ou seja, o
sinal digital a ser transmitido é variado em função da alteração da amplitude da onda
portadora. Esta onda portadora é comutada entre dois valores, usualmente ligado e
desligado, 1 ou 0 . O uso da modulação ASK serve como sincronização entre o
transmissor e o receptor.
O comando utilizado para envio dos dados após definida a mensagem a ser
entregue é:
vw_send((uint8_t *)msg, strlen(msg));
A leitura da mensagem que foi entregue é feita através de armazenamento
dos dados (&buflen) em um vetor de tamanho variável conforme a mensagem. Para
programação é necessário que o vetor de armazenamento dos dados esteja em uma
função condicionante SE, está função irá analisar se existe alguma mensagem
recebida. Caso exista esta mensagem o microcontrolador será capaz de informar cada
dado desta mensagem que foi armazenada em um vetor:
if (vw_get_message(buf, &buflen))
{
mensagem = &buflen;
29
𝜆 = 0,69284𝑚 (3.3)
0,69284
𝐴𝑛𝑡𝑒𝑛𝑎 = (3.5)
4
FIGURA 15 - NRF24L01
FONTE: O AUTOR (2014).
32
3.6.3 Bluetooth
Neste sistema será criado uma aplicação para dispositivos móveis com
sistema operacional Android. Este aplicativo será o responsável por utilizar a
tecnologia de transmissão bluetooth para enviar dados, por exemplo do celular para o
módulo acoplado ao microcontrolador. O microcontrolador irá fazer o tratamento dos
comandos recebidos pelo celular. O dispositivo bluetooth receptor recebe os dados e
envia via serial ao microcontrolador. O Apêndice H mostra como foi feito o aplicativo.
3.6.4 Ethernet
3.6.5 INFRAVERMELHO
FIGURA 17 - SENSOR IR
FONTE: O AUTOR (2014).
3.6.6 SUPERVISÓRIO
Para realização desta autenticação foi utilizado uma biblioteca pronta em php
chamada Page Password Protect 2.13.
Após feito este processo, uma página será aberta conforme Figura 19.
3.7 PROGRAMAÇÃO
3.7.1 Introdução
FIGURA 21 – ESQUEMÁTICO 1
FONTE: O AUTOR (2014).
41
FIGURA 22 – ESQUEMÁTICO 2
FONTE: O AUTOR (2014).
FIGURA 23 – ESQUEMÁTICO 3
FONTE: O AUTOR (2014).
42
A central analisa a mensagem que foi recebida e envia para o módulo, este
também analisa a mensagem e acende as lâmpadas. Após o acendimento o módulo
retorna a central o novo estado do sistema, assim a central sempre saberá o estado
de cada módulo que representa cada ambiente.
FIGURA 24 – ESQUEMÁTICO 4
FONTE: O AUTOR (2014).
Este processo irá acontecer enquanto o sistema estiver ligado. Caso o usuário
realiza um comando via bluetooth ou infravermelho o comando será sempre enviado
a central para ela estar sempre atualizada em relação ao sistema todo.
Com a definição do endereçamento de cada mensagem, para a comunicação
ocorrer corretamente foram utilizadas bibliotecas prontas, ou seja, foi usado um
conjunto de funções pré-escritas por outros programadores. A Tabela 3 exemplifica
as bibliotecas utilizadas.
TABELA 3 – BIBLIOTECAS
Dispositivo HARDWARE BIBLIOTECA
RF433 RF 433MHz VirtualWire
RS485 MAX485 VirtualWire
RF2,4Ghz nRF24L01 NRF24
SUPERVISÓRIO/Ethernet W5100 SPI, servidor
XAMPP(apache)
BLUETOOTH BLUETOOTH O autor
INFRAVERMELHO TSOP4838 IRremote
FONTE: O AUTOR, 2014.
43
A função cliente.read() faz a leitura pelo módulo ethernet do que for enviado
pelo supervisório e assim é armazenado em uma string chamada “msg”.
Após o armazenamento o microcontrolador passa a analisar cada caracteree
desta mensagem em sequência.
45
Por exemplo:
if (msg[6]=='#') // analisa se o último caractere é o #
{
if (msg[5]=='A') client.write(Luz1);
if (msg[5]=='L')
{
if (msg[4]=='1')
{
// Caso L#, ele copia os bytes anteriores p/ a
// string 'Luz' e cada byte representa um
// dispositivo, onde '1'=ON e '0'=OFF
Luz1[0]=msg[1];
Luz1[1]=msg[2];
Luz1[2]=msg[3];
if (Luz1[0]=='1') comando1(); else comando2();
if (Luz1[1]=='1') comando3(); else comando4();
if (Luz1[2]=='1') comando5(); else comando6();
}
}
{
digitalWrite(saida1,1);
}
4 PROTÓTIPO
FIGURA 25 – CENTRAL
FONTE: O AUTOR (2014).
TABELA 5 – SIMBOLOGIA CENTRAL
Número Componente
1 Cabo ethernet com conexão RJ45
2 Ethernet shild acoplado a um Arduino
3 Módulo RF433Mhz
4 nRF24L01
5 MAX485 para comunicação RS485
FONTE: O AUTOR, 2014.
Após feita a montagem da central, montou-se os módulos conforme a figura 26.
FIGURA 26 – MÓDULO
FONTE: O AUTOR (2014).
49
9 - VirtualWire http://www.airspayce.com/mikem/arduin
o/VirtualWire/
10 - IRremote http://arcfn.com
11 - RF24 http://maniacbug.github.io/RF24/
12 Attiny85 - http://imall.iteadstudio.com/im13061500
3.html
13 Relé, resistores, - Loja de matérias eletrônicos
diodos,
transistores
14 Bluetooth - http://imall.iteadstudio.com/im12072300
9.html
15 - Bluetooth Apêndice D
FONTE: O AUTOR, 2014.
55
5 CONCLUSÃO
REFERÊNCIAS
<html>
<php>
<?php include("password_protect.php"); ?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.ccs" />
<title>
Início - Automação Residencial
</title>
<style type="text/css">
<!--
#logoApDiv {
position:absolute;
width:900px;
height:175px;
z-index:1;
top: 20px;
left: 50%; /*posição em relação à parte esquerda*/
margin-left: -450px;
border:1px;
background-color: #FFFFFF;
//background:url(gradial.png);
}
#menuApDiv {
position:absolute;
width:250px;
height:100%;
z-index:2;
top: 195px;
left: 50%; /*posição em relação à parte esquerda */
margin-left: -450px;
border:1px;
background-color: #FFFFFF;
}
#ContApDiv {
position:absolute;
width:650px;
z-index:3;
left: 50%; /*posição em relação à parte esquerda */
margin-left: -200px;
top: 195px;
background-color: #FFFFFF;
}
#SiteApDiv {
position:absolute;
width:900px;
62
}
-->
</style>
</head>
<body SCROLL="YES" background="back.jpg" >
<font face="Arial, Helvetica, sans-serif">
<div id="logoApDiv"><a href="/teste/home.php"><img src="logo.jpg" alt="Andre Osti"
/></a>
</div>
<div id="SiteApDiv">
<table border="0px" width="900px" bgcolor="#FFFFFF"><!-- Tabela de layout -->
<tr>
<!-- Menu -->
<td width="200px" valign="top">
<table width="200" class="bordasimples">
<tr>
<td align="left" bgcolor="#FFFFFF" class="navlink"><a href="/teste/home.php">
Residência</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente1.php">Ambiente
1</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente2.php">Ambiente
2</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente3.php">Ambiente
3</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente4.php">Ambiente
4</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class\="navlink"><a href="ambiente5.php">Ambiente
5</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente6.php">Ambiente
6</a></td>
</tr>
63
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente7.php">Ambiente
7</a></td>
</tr>
</table>
</td>
<!-- conteudo -->
<td width="700px">
<table>
<tr>
<td>
</td>
</tr>
</table><h1>Residência</h1>
<font size='2'><h2>Escolha o Ambiente em que deseja supervisionar:</h2></font>
<center>
<table>
<img src='planta.png' width='600' >
</table>
</center>
</td>
</tr>
</table>
<hr />
<center><font face="Arial, Helvetica, sans-serif">2014 - 2014 © <b>André
Osti</b></font></center>
</div>
</font>
</body>
</html>
64
<html>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<php>
<?php include("password_protect.php"); ?>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.ccs" />
<title>
Início - Automação Residencial
</title>
<style type="text/css">
<!--
#logoApDiv {
position:absolute;
width:900px;
height:175px;
z-index:1;
top: 20px;
left: 50%; /*posição em relação à parte esquerda*/
margin-left: -450px;
border:1px;
background-color: #FFFFFF;
//background:url(gradial.png);
}
#menuApDiv {
position:absolute;
width:250px;
height:100%;
z-index:2;
top: 195px;
left: 50%; /*posição em relação à parte esquerda */
margin-left: -450px;
border:1px;
background-color: #FFFFFF;
}
#ContApDiv {
position:absolute;
width:650px;
z-index:3;
left: 50%; /*posição em relação à parte esquerda */
margin-left: -200px;
top: 195px;
background-color: #FFFFFF;
}
#SiteApDiv {
position:absolute;
65
width:900px;
/* height -> none */
top:195px;
z-index:2;
left: 50%; /*posição em relação à parte esquerda */
margin-left: -450px;
}
}
-->
</style>
</head>
<body SCROLL="YES" background="back.jpg" >
<font face="Arial, Helvetica, sans-serif">
<div id="logoApDiv"><a href="/teste/home.php"><img src="logo.jpg" alt="Andre Osti"
/></a>
</div>
<div id="SiteApDiv">
<table border="0px" width="900px" bgcolor="#FFFFFF"><!-- Tabela de layout -->
<tr>
<!-- Menu -->
<td width="200px" valign="top">
<table width="200" class="bordasimples">
<tr>
<td align="left" bgcolor="#FFFFFF" class="navlink"><a href="/teste/home.php">
Residência</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente1.php">Ambiente
1</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente2.php">Ambiente
2</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente3.php">Ambiente
3</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente4.php">Ambiente
4</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente5.php">Ambiente
5</a></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente6.php">Ambiente
6</a></td>
66
</tr>
<tr>
<td bgcolor="#FFFFFF" class="navlink"><a href="ambiente7.php">Ambiente
7</a></td>
</tr>
</table>
</td>
<!-- conteudo -->
<td width="700px">
<table>
<tr>
<td>
</td>
</tr>
</table><h2>Ambiente 1 - HALL</h2>
<center>
<img src='ambiente1.png'>
<?php
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
// Se conecta ao IP e Porta:
socket_connect($sock,"192.168.0.99", 8080);
// Executa a ação correspondente ao botão apertado.
if(isset($_POST['bits'])) {
$msg = $_POST['bits'];
if(isset($_POST['Lampada1'])){ if($msg[0]=='1') { $msg[0]='0'; } else { $msg[0]='1'; }}
if(isset($_POST['Lampada2'])){ if($msg[1]=='1') { $msg[1]='0'; } else { $msg[1]='1'; }}
if(isset($_POST['Lampada3'])){ if($msg[2]=='1') { $msg[2]='0'; } else { $msg[2]='1'; }}
socket_write($sock,$msg,strlen($msg));
}
socket_write($sock,'A#',2); //Requisita o status do sistema.
// Espera e lê o status e define a cor dos botões de acordo.
$status = socket_read($sock,6);
if (($status[4]=='L')&&($status[5]=='#')&&($status[3]=='1')) {
if ($status[0]=='0') $img1 = 'lamp_off.png';
else $img1 = 'lamp_on.png';
if ($status[1]=='0') $img2 = 'lamp_off.png';
else $img2 = 'lamp_on.png';
if ($status[2]=='0') $img3 = 'lamp_off.png';
else $img3 = 'lamp_on.png';
echo "<form method =\"post\" action=\"ambiente1.php\">";
echo "<input type=\"hidden\" name=\"bits\" value=\"$status\">";
echo "<img src='$img1'>";
echo "<img src='$img2'>";
echo "<img src='$img3'></br>";
echo "<button style=\"margin-right:1px;width:90;font: bold 12px Arial\" type =
\"Submit\" Name = \"Lampada1\">Lâmpada 1</button>";
echo "<button style=\"margin-right:1px;width:90;font: bold 12px Arial\" type =
\"Submit\" Name = \"Lampada2\">Lâmpada 2</button>";
echo "<button style=\"margin-right:1px;width:90;font: bold 12px Arial\" type =
\"Submit\" Name = \"Lampada3\">Lâmpada 3</button>";
67
#include <SPI.h>
#include <Ethernet.h>
#include <VirtualWire.h>
void setup()
{
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
Serial.begin(9600);
dht.begin();
vw_set_tx_pin(9); // Define o pino do transmissor,o 9
vw_set_rx_pin(8); // Define o pino receptor,o 8
vw_set_ptt_pin(7);
vw_setup(2000); // Bits per sec
}
69
{
char *msg = "021";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando9()
{
char *msg = "022";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando10()
{
char *msg = "023";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando11()
{
char *msg = "024";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando12()
{
char *msg = "025";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando13()
{
char *msg = "030";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando14()
{
char *msg = "031";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando15()
{
71
}
void comando37()
{
char *msg = "070";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando38()
{
char *msg = "071";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando39()
{
char *msg = "072";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando40()
{
char *msg = "073";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando41()
{
char *msg = "074";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void comando42()
{
char *msg = "075";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx(); // Wait until the whole message is gone
}
void loop()
{
{
// guarda o caracter na string 'msg'
msg[1]=msg[2]; msg[2]=msg[3]; msg[3]=msg[4]; msg[4]=msg[5];
msg[5]=msg[6];
msg[6] = client.read();
if (msg[6]=='#')
{
if (msg[5]=='A') client.write(Luz1); //se for solicitado envia estado do
ambiente
if (msg[5]=='B') client.write(Luz2);
if (msg[5]=='C') client.write(Luz3);
if (msg[5]=='D') client.write(Luz4);
if (msg[5]=='E') client.write(Luz5);
if (msg[5]=='F') client.write(Luz6);
if (msg[5]=='G') client.write(Luz7);
if (msg[4]=='2')
{
Luz2[0]=msg[1];
Luz2[1]=msg[2];
Luz2[2]=msg[3];
if (Luz2[0]=='1') comando7(); else comando8();
if (Luz2[1]=='1') comando9(); else comando10();
if (Luz2[2]=='1') comando11(); else comando12();
}
if (msg[4]=='3')
{
Luz3[0]=msg[1];
Luz3[1]=msg[2];
Luz3[2]=msg[3];
if (Luz3[0]=='1') comando13(); else comando14();
if (Luz3[1]=='1') comando15(); else comando16();
if (Luz3[2]=='1') comando17(); else comando18();
}
if (msg[4]=='4')
{
Luz4[0]=msg[1];
Luz4[1]=msg[2];
Luz4[2]=msg[3];
if (Luz4[0]=='1') comando19(); else comando20();
if (Luz4[1]=='1') comando21(); else comando22();
if (Luz4[2]=='1') comando23(); else comando24();
}
if (msg[4]=='5')
{
Luz5[0]=msg[1];
Luz5[1]=msg[2];
Luz5[2]=msg[3];
if (Luz5[0]=='1') comando25(); else comando26();
if (Luz5[1]=='1') comando27(); else comando28();
if (Luz5[2]=='1') comando29(); else comando30();
}
if (msg[4]=='6')
{
77
Luz6[0]=msg[1];
Luz6[1]=msg[2];
Luz6[2]=msg[3];
if (Luz6[0]=='1') comando31(); else comando32();
if (Luz6[1]=='1') comando33(); else comando34();
if (Luz6[2]=='1') comando35(); else comando36();
}
if (msg[4]=='7')
{
Luz7[0]=msg[1];
Luz7[1]=msg[2];
Luz7[2]=msg[3];
if (Luz7[0]=='1') comando37(); else comando38();
if (Luz7[1]=='1') comando39(); else comando40();
if (Luz7[2]=='1') comando41(); else comando42();
}
}
}
}
}
78
void loop()
{
digitalWrite(3,HIGH);
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
}
if((buf[0] == '0')&&(buf[1] == '1')&&(buf[2] == '3'))
{
digitalWrite(A1,0);
char *msg = "0001L#";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if((buf[0] == '0') && (buf[1] == '1')&&(buf[2] == '4'))
{
digitalWrite(A2,1);
char *msg = "0011L#";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if((buf[0] == '0')&&(buf[1] == '1')&&(buf[2] == '5'))
{
digitalWrite(A2,0);
char *msg = "0001L#";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
delay(50);
}
if(c == 'b')
{
digitalWrite(A1,0);
char *msg = "0001L#";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'C')
{
digitalWrite(A2,1);
char *msg = "0011L#";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'c')
{
digitalWrite(A2,0);
char *msg = "0001L#";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'D')
{
char *msg = "020";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'd')
{
char *msg = "021";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'E')
{
char *msg = "022";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'e')
{
char *msg = "023";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'F')
{
char *msg = "024";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
81
}
if(c == 'f')
{
char *msg = "025";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'G')
{
char *msg = "030";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'g')
{
char *msg = "031";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'H')
{
char *msg = "032";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'h')
{
char *msg = "033";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'I')
{
char *msg = "034";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
if(c == 'i')
{
char *msg = "035";
vw_send((uint8_t *)msg, strlen(msg));
vw_wait_tx();
}
delay(50);
}
82
#include <VirtualWire.h>
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // iniciando o receptor de infravermelho
Serial.println("setup");
pinMode (A0, OUTPUT); //define os pinos de saída
pinMode (A1, OUTPUT);
pinMode (A2, OUTPUT);
void loop()
{
uint8_t buf[VW_MAX_MESSAGE_LEN];
uint8_t buflen = VW_MAX_MESSAGE_LEN;
if (vw_get_message(buf, &buflen)) //se receber mensagem da central ou dos
módulos via RF433 ou RS485
{
int i;
Serial.print("Got: ");
for (i = 0; i < buflen; i++)
{
Serial.print(char(buf[i]));
}
Serial.println("");
if((buf[0] == '0') && (buf[1] == '2')&&(buf[2] == '0'))
{
digitalWrite(A0,1);
}
if((buf[0] == '0')&&(buf[1] == '2')&&(buf[2] == '1'))
{
digitalWrite(A0,0);
}
if((buf[0] == '0') && (buf[1] == '2')&&(buf[2] == '2'))
{
digitalWrite(A1,1);
}
if((buf[0] == '0')&&(buf[1] == '2')&&(buf[2] == '3'))
{
digitalWrite(A1,0);
84
}
if((buf[0] == '0') && (buf[1] == '2')&&(buf[2] == '4'))
{
digitalWrite(A2,1);
}
if((buf[0] == '0')&&(buf[1] == '2')&&(buf[2] == '5'))
{
digitalWrite(A2,0);
}
delay(50);
}
}
85
ANEXO A – DHT22
ANEXO B – MAX485
ANEXO C – nrf24l01
Caractereísticas do nRF24L01
a) Radio
Worldwide 2.4GHz ISM band operation
126 RF channels
Common RX and TX pins
GFSK modulation
1 and 2Mbps air data rate
1MHz non-overlapping channel spacing at 1Mbps
2MHz non-overlapping channel spacing at 2Mbps
b) Transmiter
Programmable output power: 0, -6, -12 or -18dBm
11.3mA at 0dBm output power
c) Receiver
Integrated channel filters
12.3mA at 2Mbps
-82dBm sensitivity at 2Mbps
-85dBm sensitivity at 1Mbps
Programmable LNA gain
d) RF Synthesizer
Fully integrated synthesizer
No external loop filer, VCO varactor diode or resonator
Accepts low cost ±60ppm 16MHz crystal
e) Enhanced ShockBurst
1 to 32 bytes dynamic payload length
Automatic packet handling
Auto packet transaction handling
6 data pipe MultiCeiver™ for 1:6 star networks
f) Power Managment
Integrated voltage regulator
1.9 to 3.6V supply range
Idle modes with fast start-up times for advanced power management
22uA Standby-I mode, 900nA power down mode
Max 1.5ms start-up from power down mode
Max 130us start-up from standby-I mod