ude <Ethernet.h> #include <Server.h> #include <EthernetUdp.h> #include "Dns.h" //DETERMINA IL MAC E L'IP DELLA PAGINA WEB byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED}; byte ip[] = { 10, 0, 0, 39};
//PORTA DI COMUNICAZIONE EthernetServer server(80);
//SCRIVE IL NUMERO DI PIN CORRISPONDENTE AI LED int ledPin1 = 8; int ledPin2 = 9; const int switch1Pin = 7; const int switch2Pin = 6;
//LUNGHEZZA DELLA STRINGA INVIATA String readString = String(30);
//IMPOSTA ALL'AVVIO I LED SPENTI boolean LEDON1 = false; boolean LEDON2 = false;
void setup(){ Ethernet.begin(mac, ip); pinMode(ledPin1, OUTPUT); pinMode(ledPin2, OUTPUT); pinMode(switch1Pin, INPUT); pinMode(switch2Pin, INPUT); Serial.begin(9600); }
void loop(){ EthernetClient client = server.available(); if (client) //SE ESISTE UN CLIENTE { while (client.connected()) // SE IL CLIENTE E' CONNESSO { if (client.available()) //SE E' TUTTO OK PER INIZIARE { char c = client.read(); //LEGGI I SINGOLI CARATTERI INVIATI if (readString.length() < 100) { readString += c; //CONCATENA I CARATTERI } if (c == '\n') //VEDE SE C'E' IL CARATTERE DI FINE STRINGA, PER INDIVIDUARE CHE E' FINITA { if(readString.indexOf("L1=1") > 0) //IMPOSTA UNA VARIABILE DI TIPO BOLEANA (VERO-FALSO) PER GLI STATI DEL LED { LEDON1 = true; } else if (readString.indexOf("L2=1") > 0) { LEDON2 = true; } else if(readString.indexOf("L1=0") > 0) { LEDON1 = false; } else if (readString.indexOf("L2=0") > 0) { LEDON2 = false; } //CREA LA PAGINA HTML (VERRA' AGGIORNATA AD OGNI ISTRUZIONE NUOVA) client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(); client.println("<html><head></head><body>");
//TITOLO LED 1 client.println("<br>__________________________________________________________________________________________<br>"); client.println("<h1>Mesa Titular SJC</h1>");
//OPERAZIONI DA FARE QUANDO SI CLICCA PER ATTIVARE LEDON1: if (LEDON1) { digitalWrite(ledPin1, HIGH); client.println("Status: Em Funcionamento<br>"); } else {
//OPERAZIONI DA FARE QUANDO SI CLICCA PER SPEGNERE LEDON1: digitalWrite(ledPin1, LOW ); client.println("Status: Utilizando a Mesa Reserva<br>"); }
//CREA I PULSANTI RELATIVI A LED1 client.println("<a href='?L1=0'>Desabilitar</a>"); client.println("<a href='?L1=1'>Acionar</a>"); //INSERISCE IL DIVISORE client.println("<br>__________________________________________________________________________________________<br>");
//TTOLO LED2 client.println("<h1>Mesa Reserva SJC</h1>");
//OPERAZIONI DA FARE QUANDO SI CLICCA PER ATTIVARE LEDON2: if (LEDON2) { digitalWrite(ledPin2, HIGH); digitalWrite(ledPin1, LOW ); client.println("Status: Em Funcionamento<br>"); } else {
//OPERAZIONI DA FARE QUANDO SI CLICCA PER SPEGNERE LEDON2: digitalWrite(ledPin2, LOW); client.println("Status: Desabilitado<br>"); }
//CREA I PULSANTI RELATIVI A LED2 client.println("<a href='?L2=0'>Desabilitar</a>"); client.println("<a href='?L2=1'>Acionar</a>");
//CHIUDE I TAG HTML PER LA PAGINA client.println("</body></html>");
//SI PREPARA PER UNA NUOVA ISTRUZIONE readString=""; client.println("<br>__________________________________________________________________________________________<br>"); //TERMINA LE OPERAZIONI CLIENTE client.stop(); } } } } }
E a outra é essa:
#include <SPI.h> #include <Ethernet.h> #include <EthernetUdp.h> #include "Dns.h" /********************************************************************************** ************************************FIM BIBLIOTECAS******************************** **********************************************************************************/ /********************************************************************************** ************************************ETHERNET CONFIG/FUNCTIONS********************** *********************************************************************************** se for rodar numa rede com firewall, verifique se os ip utilizado está liberado. Servidores da NTP.br a.st1.ntp.br 200.160.7.186 e 2001:12ff:0:7::186 b.st1.ntp.br 201.49.148.135 c.st1.ntp.br 200.186.125.195 d.st1.ntp.br 200.20.186.76 a.ntp.br 200.160.0.8 e 2001:12ff::8 b.ntp.br 200.189.40.8 c.ntp.br 200.192.232.8 **********************************************************************************/ byte mac[] = { 0x00, 0x00, 0xAA, 0xBB, 0xCC, 0xDD}; unsigned int localPort = 8888; // local port to listen for UDP packets IPAddress timeServer(200, 192, 232, 8); // time.nist.gov NTP server (fallback) - segunda tentativa caso a primeira de erro const int NTP_PACKET_SIZE= 48; // NTP time stamp is in the first 48 bytes of the message byte packetBuffer[ NTP_PACKET_SIZE]; // buffer to hold incoming and outgoing packets //host para a primeira tentativa const char* host = "ntp02.oal.ul.pt"; // servidor da NTP.br - ver lista acima para todos os servidores da NTP.br //const char* host = "192.168.200.254"; // servidor interno 01 - caso tenha um servidor de hora interno, pode ser configurado o nome ou ip na variavel host //const char* host = "192.168.200.253"; // servidor interno 02 EthernetUDP Udp; DNSClient Dns; IPAddress rem_add; // send an NTP request to the time server at the given address unsigned long sendNTPpacket(IPAddress& address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer,NTP_PACKET_SIZE); Udp.endPacket(); } /********************************************************************************** ************************************FIM ETHERNET CONFIG/FUNCTIONS****************** **********************************************************************************/ /********************************************************************************** ************************************UNIX TIME FUNCTIONS**************************** *********************************************************************************** localTime --> converte o unix time para ano, mes, dia semana, dia, hora, minuto e segundo função baseada na biblioteca dateTime, pois não era necessário usar toda a biblioteca. (http://playground.arduino.cc/Code/DateTime) descrição original: convert the given timep to time components this is a more compact version of the C library localtime function **********************************************************************************/ #define LEAP_YEAR(_year) ((_year%4)==0) static byte monthDays[] = {31, 28, 31, 30 , 31, 30, 31, 31, 30, 31, 30, 31}; void localTime(unsigned long *timep, byte *psec, byte *pmin, byte *phour, byte *pday, byte *pwday, byte *pmonth, byte *pyear) { unsigned long long epoch =* timep; byte year; byte month, monthLength; unsigned long days; *psec = epoch % 60; epoch /= 60; // now it is minutes *pmin = epoch % 60; epoch /= 60; // now it is hours *phour = epoch % 24; epoch /= 24; // now it is days *pwday = (epoch+4) % 7; year = 70; days = 0; while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= epoch) { year++; } *pyear=year; // *pyear is returned as years from 1900 days -= LEAP_YEAR(year) ? 366 : 365; epoch -= days; // now it is days in this year, starting at 0 for (month=0; month<12; month++) { monthLength = ( (month==1) && LEAP_YEAR(year) ) ? 29 : monthDays[month]; // month==1 -> february if (epoch >= monthLength) { epoch -= monthLength; } else { break; } } *pmonth = month; // jan is month 0 *pday = epoch+1; // day of month } /********************************************************************************** ************************************FIM UNIX TIME FUNCTIONS************************ **********************************************************************************/ /********************************************************************************** **************************************** FUNÇÕES FORMATAR DATA/HORA *************** **********************************************************************************/ String zero(int a){ if(a>=10) {return (String)a+"";} else { return "0"+(String)a;} } String diaSemana(byte dia){ String str[] = {"Domingo", "Segunda-feira", "Terça-feira", "Quarta-feira", "Quinta-feira", "Sexta-feira", "Sabado"}; return str[dia]; } /********************************************************************************** ****************************************FIIM FUNÇÕES FORMATAR DATA/HORA *********** **********************************************************************************/ /********************************************************************************** **************************************** SETUP / LOOP ***************************** **********************************************************************************/ void setup() { pinMode(4, OUTPUT); //ANTES DE INICIAR O ETHERNET, DESABILITA O SDCARD digitalWrite(4, HIGH); Serial.begin(9600); if (Ethernet.begin(mac) == 0) { Serial.println("Failed to configure Ethernet using DHCP"); } Udp.begin(localPort); Dns.begin(Ethernet.dnsServerIP() ); } void loop() { if(Dns.getHostByName(host, rem_add) == 1 ){ Serial.println("DNS resolve..."); Serial.print(host); Serial.print(" = "); Serial.println(rem_add); sendNTPpacket(rem_add); } else { Serial.println("DNS fail..."); Serial.print("time.nist.gov = "); Serial.println(timeServer); // caso a primeira tentativa não retorne um host válido sendNTPpacket(timeServer); // send an NTP packet to a time server } delay(1000); //aguarda um segundo, para receber os dados enviados. if ( Udp.parsePacket() ) { // We've received a packet, read the data from it Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer // the timestamp starts at byte 40 of the received packet and is four bytes, // or two words, long. First, esxtract the two words: unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); // combine the four bytes (two words) into a long integer // this is NTP time (seconds since Jan 1 1900): unsigned long secsSince1900 = highWord << 16 | lowWord; Serial.print("Segundos desde 1 de Jan. de 1900 = " ); Serial.println(secsSince1900); Serial.print("Unix time = "); const unsigned long seventyYears = 2208988800UL; // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: unsigned long epoch = secsSince1900 - seventyYears; //desconta 70 anos // print Unix time: Serial.println(epoch); byte ano, mes, dia, dia_semana, hora, minuto, segundo; localTime(&epoch, &segundo, &minuto, &hora, &dia, &dia_semana, &mes, &ano); //extrai data e hora do unix time Serial.print("Ano: "); Serial.println(ano+1900); Serial.print("Mes: "); Serial.println(mes+1); Serial.print("Dia da semana: "); Serial.println(dia_semana); Serial.print("Dia: "); Serial.println(dia); Serial.print("Hora: "); Serial.println(hora); Serial.print("minunto: "); Serial.println(minuto); Serial.print("segundo: "); Serial.println(segundo); String s = diaSemana(dia_semana) + ", " + zero(dia) + "/" + zero(mes+1) + "/" + (ano+1900) + " " + zero(hora) + ":" + zero(minuto) + ":" + zero(segundo); Serial.println(s); Serial.println(" "); } delay(10000); //atualiza novamente em 10 segundos }…
CK_STREAM, \SOL_TCP);// Se conecta ao IP e Porta:socket_connect($sock,"192.168.1.4",8081);// Executa a ação correspondente ao botão apertado.if(isset($_POST['bits'])) {$msg = $_POST['bits'];if(isset($_POST['Esquerda' ])){ if($msg[0] === '1') { $msg[0]='0'; } else { $msg[0]='1'; }}if(isset($_POST['Direita'])){ if($msg[1]=='1') { $msg[1]='0'; } else { $msg[1]='1'; }}socket_write($sock,$msg,strlen($msg));}
socket_write($sock,'R#',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]=='M')&&($status[5]==='#')) {if ($status[0] === '0') {$cor1 = lightcoral;} else {$cor1 = lightgreen;}
if ($status[1] == '0') {$cor2 = lightcoral;} else {$cor2 = lightgreen;}
echo "<form method =\"post\" action=\"teste.php\">";echo "<input type=\"hidden\" name=\"bits\" value=\"$status\">";echo "<button style=\"width:70; background-color: $cor1 ;font: bold 14px Arial\" type = \"Submit\" Name = \"Esquerda\">Esquerda</button></br></br>";echo "<button style=\"width:70; background-color: $cor2 ;font: bold 14px Arial\" type = \"Submit\" Name = \"Direita\">Direita</button></br></br>";
echo "</form>";}// Caso ele não receba o status corretamente, avisa erro.else { echo "Falha ao receber status do Motor"; }socket_close($sock);?></body></html>
e o do arduino é o seguinte:
include <SPI.h>#include <Ethernet.h>
//Configurações do Ethernet Shieldbyte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };byte ip[] = { 192,168,1, 4 }; // ip que o arduino assumirábyte gateway[] = { 192,168,1, 1 }; // ip do roteadorbyte subnet[] = { 255, 255, 0, 0 };
char Motor[6] = "0000M";char Direita[7] = "0000M#";char Esquerda[8] = "0000M#";int D0 = 10;int D1 = 6;EthernetServer server(8081); // Cria o servidor na porta 8081
char msg[7] = "0000M#";
void setup() {Ethernet.begin(mac, ip, gateway, subnet);server.begin();pinMode(D0,OUTPUT);pinMode(D1,OUTPUT);}
void loop() {
EthernetClient client = server.available();// SE receber um caracter...if (client) {// 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]=msg[7];msg[7]=msg[8];msg[8]=client.read();if (msg[4]=='#') {switch(msg[5]) {case 'R':// Se receber o comando 'R#' envia de volta o status dos// motores. (Que é a string 'Motor')client.write(Motor);break;case 'D':// Caso Gire para direitadigitalWrite(D0,HIGH);delay(2000);digitalWrite(D0,LOW);delay(2000);break;case 'E':// Caso gire para esquerda.digitalWrite(D1,HIGH);delay(2000);digitalWrite(D1,LOW); delay(2000); break;case 'M':Direita[0]=msg[1];//1=esquerda 0=direitaEsquerda[1]=msg[2];if (Motor[0]=='1') digitalWrite(D0,HIGH); else digitalWrite(D0,LOW);if (Motor[1]=='0') digitalWrite(D1,HIGH); else digitalWrite(D1,LOW);break;}}}}
quando mando executar a pagina PHP aparece o seguinte erro:
Warning: socket_connect(): in C:\xampp\htdocs\Motor\controle.php on line 13Warning: socket_write(): in C:\xampp\htdocs\Motor\controle.php on line 25Warning: socket_read(): in C:\xampp\htdocs\Motor\controle.php on line 28
tenho q fazer esta aplicação até quarta dia 31/04, alguem pode me socorrer? o que esta errado sou meio leigo em programação WEB…
ndo juntar os 2.
Já tentei mixar eles, mas acredito que o problema esteja na hora de atribuir o MAC e o IP.
To quebrando a cabeça nisso!
Valeu galera!
O webserver é:
/* Web_Authentication.ino - Webduino Authentication example */
/* This example assumes that you're familiar with the basics * of the Ethernet library (particularly with setting MAC and * IP addresses) and with the basics of Webduino. If you * haven't had a look at the HelloWorld example you should * probably check it out first */
/* you can change the authentication realm by defining * WEBDUINO_AUTH_REALM before including WebServer.h */#define WEBDUINO_AUTH_REALM "Weduino Authentication Example"
#include "SPI.h"#include "Ethernet.h"#include "WebServer.h"
boolean tog1 = false; //rf1 onboolean tog2 = true; //rf2 offboolean tog3 = false; //rf3 offboolean tog4 = true; //rf4 off
/* CHANGE THIS TO YOUR OWN UNIQUE VALUE. The MAC number should be * different from any other devices on your network or you'll have * problems receiving packets. */static uint8_t mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
/* CHANGE THIS TO MATCH YOUR HOST NETWORK. Most home networks are in * the 192.168.0.XXX or 192.168.1.XXX subrange. Pick an address * that's not in use and isn't going to be automatically allocated by * DHCP from your router. */static uint8_t ip[] = { 192, 168, 2, 133 };
/* This creates an instance of the webserver. By specifying a prefix * of "", all pages will be at the root of the server. */#define PREFIX ""WebServer webserver(PREFIX, 3389);
void defaultCmd(WebServer &server, WebServer::ConnectionType type, char *, bool){ server.httpSuccess(); if (type != WebServer::HEAD) { P(helloMsg) = "<h1>Hello, World!</h1><a href=\"private.html\">Private page</a>"; server.printP(helloMsg); }}
void privateCmd(WebServer &server, WebServer::ConnectionType type, char *, bool){ /* if the user has requested this page using the following credentials * username = user * password = user * display a page saying "Hello User" * * the credentials have to be concatenated with a colon like * username:password * and encoded using Base64 - this should be done outside of your Arduino * to be easy on your resources * * in other words: "dXNlcjp1c2Vy" is the Base64 representation of "user:user" * * if you need to change the username/password dynamically please search * the web for a Base64 library */ if (server.checkCredentials("dXNlcjp1c2Vy")) { server.httpSuccess(); if (type != WebServer::HEAD) { P(HTMLOPEN) = "<html>"; P(background) = "<body style=background-color:BLACK>"; //set background to BLACK P(helloMsg) = "<center><font color=’green’> <h1>MARCELO </h1></font></center>"; P(FORMOPEN) = "<form action=formLogin.html method=POST name=LED id=LED><input type=hidden name=botao id=botao value=0"; P(button1) = "<center><button name=tog1 value=1 type=submit style=font-weight:bold;color:GREEN;height:70px;width:145px>PINO 5 On</button>"; P(button2) = "<center><button name=tog2 value=2 type=submit style=font-weight:bold;color:red;height:70px;width:145px>PINO 5 Off</button>"; P(button3) = "<center><button name=tog3 value=3 type=submit style=font-weight:bold;color:GREEN;height:70px;width:145px>ABRIR PORTAOZINHO3</button>"; P(button4) = "<center><button name=tog4 value=4 type=submit style=font-weight:bold;color:red;height:70px;width:145px>ABRIR PORTAOZAO6</button>"; P(FORMCLOSE) = "</form>"; P(BODYCLOSE) = "</body>"; P(HTMLCLOSE) = "</html>"; server.printP(HTMLOPEN); server.printP(background); server.printP(helloMsg); server.printP(FORMOPEN); server.printP(button1); server.printP(button2); server.printP(button3); server.printP(button4); server.printP(FORMCLOSE); server.printP(BODYCLOSE); server.printP(HTMLCLOSE); } } else { /* send a 401 error back causing the web browser to prompt the user for credentials */ server.httpUnauthorized(); }}
void formCmd(WebServer &server, WebServer::ConnectionType type, char *url_tail, bool tail_complete){ if (server.checkCredentials("dXNlcjp1c2Vy")) { if (type == WebServer::POST) { bool repeat; char name[16], value[16]; do { repeat = server.readPOSTparam(name, 16, value, 16); /*Serial.print("name: "); Serial.println(name); Serial.print("value: "); Serial.println(value); */ if (strncmp("tog1", name, 4) == 0) { Serial.println("Botao 1 acionado"); digitalWrite(5, HIGH); tog1 = true; break; } else if (strncmp("tog2", name, 4) == 0) { Serial.println("Botao 2 acionado"); digitalWrite(5, LOW); tog1 = false; break; } else if (strncmp("tog3", name, 4) == 0) { Serial.println("Botao 3 acionado"); digitalWrite(3, HIGH); delay(1000); digitalWrite(3, LOW); tog3 = true; break; } else if (strncmp("tog4", name, 4) == 0) { Serial.println("Botao 4 acionado"); digitalWrite(6, HIGH); delay(1000); digitalWrite(6, LOW); tog4 = true; break; } } while (repeat); server.httpSeeOther(PREFIX "/private.html"); } } else { server.httpUnauthorized(); }}
void setup() { pinMode(5, OUTPUT); pinMode(3, OUTPUT); pinMode(6, OUTPUT); Serial.begin(115200); Ethernet.begin(mac, ip); webserver.setDefaultCommand(&defaultCmd); webserver.addCommand("index.html", &defaultCmd); webserver.addCommand("private.html", &privateCmd); webserver.addCommand("formLogin.html", &formCmd); webserver.begin();}
void loop(){ char buff[64]; int len = 64;
/* process incoming connections one at a time forever */ webserver.processConnection(buff, &len);}
e o NO-IP é:
// Actualizacion de la IP publica con No-IP - http://url.josematm.com/S// 2013 Josema - josematm.com #include <SPI.h>#include <Ethernet.h>#include <EEPROM.h> const char host[] = "xxxx"; //aqui vai meu usuario do no-ipconst char usuarioClave[] = "xxxxxx"; //aqui vai a senha byte mac[] = { 0xAA, 0xAB, 0xAC, 0xAD, 0xAA, 0xAB };IPAddress ipLocal(192, 168, 2, 133); char servidorIP[] = "checkip.dyndns.org";char servidorActualizacion[] = "dynupdate.no-ip.com"; IPAddress ipActual;IPAddress ipUltimaEnviada; void setup() { Serial.begin(9600); while (!Serial); // Solo para Leonardo if (Ethernet.begin(mac) == 0) { Serial.println("Error consiguiendo la IP por DHCP, intentando manualmente..."); Ethernet.begin(mac, ipLocal); } delay(1000); for (byte n = 0; n <= 3; n++) ipUltimaEnviada[n] = EEPROM.read(n); // Cargamos de EEPROM la ultima IP que se envio. Serial.print("La IP almacenada en la EEPROM es: "); Serial.println(ipUltimaEnviada);} void loop() { ipActual = compruebaIP(); if (ipActual != ipUltimaEnviada) { Serial.print("Actualizando la IP en "); Serial.print(servidorActualizacion); Serial.println("..."); if (actualizaIPDynDNS(ipActual) == true){ for (byte n = 0; n <= 3; n++) EEPROM.write(n, ipActual[n]); ipUltimaEnviada = ipActual; } } else { Serial.println("No hacemos nada, la IP no cambiado desde la ultima vez. Esperando 15 minutos..."); } delay (900000); // Y esperamos 15 minutos sentados para volver a comprobar la IP.} IPAddress compruebaIP() { EthernetClient cliente; String webIP; int desde, hasta; if (cliente.connect(servidorIP, 80)) { cliente.println("GET / HTTP/1.0"); cliente.println(); webIP = ""; } else { Serial.print(":( Conexion fallida con "); Serial.println(servidorIP); } while (cliente.connected()) { while (cliente.available()) { webIP.concat((char)cliente.read()); } } cliente.stop(); desde = webIP.indexOf("Address: ") + 9; hasta = webIP.indexOf("</body>"); return ipAIPAddress(webIP.substring(desde, hasta));} boolean actualizaIPDynDNS(IPAddress ip) { EthernetClient cliente; String webIP; if (cliente.connect(servidorActualizacion, 80)) { cliente.print("GET /nic/update?hostname="); cliente.print(host); cliente.print("&myip="); cliente.print(ip); cliente.println(" HTTP/1.0"); cliente.println("Host: dynupdate.no-ip.com"); cliente.print("Authorization: Basic "); cliente.println(usuarioClave); cliente.println("User-Agent: josematm.com - Wirduino - 0.1"); cliente.println(); } else { Serial.print(":( Conexion fallida con "); Serial.println(servidorActualizacion); return false; } while (cliente.connected()) { while (cliente.available()) { webIP.concat((char)cliente.read()); } } Serial.println(webIP); cliente.stop(); if (webIP.lastIndexOf("badauth") != -1) { Serial.println("Error de de autentificacion. Comprueba usuario y clave"); return false; } else { return true; }} IPAddress ipAIPAddress(String ipEnCadena){ IPAddress ipEnBytes; char digitoIP[4]; byte cursorDigito = 0; byte cursorIP = 0; for (byte n = 0; n < ipEnCadena.length(); n++){ if (ipEnCadena.charAt(n) != '.') { digitoIP[cursorDigito] = ipEnCadena.charAt(n); cursorDigito++; } else { digitoIP[cursorDigito +1] = '\n'; ipEnBytes[cursorIP] = atoi(digitoIP); cursorDigito = 0; memset(digitoIP, 0, sizeof(digitoIP)); cursorIP++; } } digitoIP[cursorDigito +1] = '\n'; ipEnBytes[cursorIP] = atoi(digitoIP); return ipEnBytes;}
…
, e mais abaixo o codigo html da minha página.
//É necessário instalar as seguintes bibliotecas: //Serial Relay: //https://github.com/RoboCore/SerialRelay //Para instalar a bliblioteca basta acessar o menu "Sketch > Include Library > Add .ZIP Library" na IDE do Arduino e selecionar o Arquivo SerialRelay.zip contido no mesmo ZIP deste arquivo. //Ethernet_v2 //https://github.com/RoboCore/Ethernet //Para instalar a bliblioteca basta acessar o menu "Sketch > Include Library > Add .ZIP Library" na IDE do Arduino e selecionar o Arquivo Ethernet_v2_1.6.5.zip contido no mesmo ZIP deste arquivo.
//Salve o arquivo index.htm (que veio junto com esse arquivo) em um cartão micro SD e o coloque no shield Ethernet.
#include <SPI.h> #include <SD.h> #include <Ethernet_v2.h> #include <SerialRelay.h>
//Define o Mac Address da placa de rede. Essa informação pode ser encontrada em uma etiqueta colada embaixo da mesma. byte mac[] = { 0x90, 0xA2, 0xDA, 0x10, 0x02, 0x85 }; //Define o IP da placa. Caso necessário altere o mesmo para se adequar a sua rede. IPAddress ip(192, 168, 1, 12);
EthernetServer server(80); File webFile;
//na linha de baixo está sendo definido as portas em que o módulo relé serial está conectado. SerialRelay relays(8, 9, 10); // (pino de data, pino de clock, quantidade de módulos)
#define REQ_BUF_SZ 60 char HTTP_req[REQ_BUF_SZ] = {0}; char req_index = 0;
int estado_botao[41];
char * pch;
void setup() { //ESTADO INICIAL DOS BOTOES 0 -> desligado, 1 -> ligado: estado_botao[1] = 0; estado_botao[2] = 0; estado_botao[3] = 0; estado_botao[4] = 0;
Serial.begin(9600);
void loop() { EthernetClient client = server.available(); //verifica se existe alguém querendo se conectar
if (client) { // existe cliente? boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { // Existe informacao vinda do cliente char c = client.read(); // Le cada byte enviado pelo cliente, ou seja, cada caracter. // Por padrao, o ultimo caracter enviado pelo cliente (nosso navegador) é em branco e termina com \n // Dessa forma conseguimos saber se o cliente acabou de enviar informacoes para o servidor (Arduino) if (req_index < (REQ_BUF_SZ - 1)) { HTTP_req[req_index] = c; // salva os caracteres das solicitacoes do browser req_index++; } if (c == '\n' && currentLineIsBlank) { // envia para o cliente o protocolo padrao de sucesso HTTP client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); client.println();
//caso a request seja pela ação de um botão: if (StrContains(HTTP_req, "ajax_botao")) { for (int i = 1 ; i <= 40 ; i++) { //Serial.println(HTTP_req); char botao[] = "botaoxx"; if (i < 10) { botao[5] = '0'; botao[6] = '0' + i; } else { botao[5] = '0' + (i / 10); botao[6] = '0' + (i % 10); }
//Serial.println(botao); if (StrContains(HTTP_req, botao)) { SetBotao(i, client); } } } else { // grava no arquivo webFile a página que temos no microSD webFile = SD.open("index.htm"); if (webFile) { while (webFile.available()) { client.write(webFile.read()); // envia para o cliente a página - nessa linha de fato o Arduino imprime no browser a página } webFile.close(); } } Serial.println(HTTP_req); //para debug, verifica no monitor serial a requisição req_index = 0; //reseta o index do buffer e a variável que armazena as requisições StrClear(HTTP_req, REQ_BUF_SZ); break; } // toda linha de texto recebida do cliente termina com \r\n if (c == '\n') { //verifica se acabou a linha, já que \n é o ultimo caracter currentLineIsBlank = true; } else if (c != '\r') { // o cliente ainda está enviando informações currentLineIsBlank = false; } } } delay(1); // dá um tempo para o browser receber os dados client.stop(); // fecha a conexão } }
void SetBotao(int botao, EthernetClient client) {
int modulo = (botao - 1) / 4 + 1; int rele = botao % 4; if (rele == 0) { rele = 4; }
Serial.print("modulo:"); Serial.print(modulo); Serial.print(" rele:"); Serial.print(rele); Serial.print(" - ");
if (estado_botao[botao] == 0) { relays.SetRelay(rele, SERIAL_RELAY_ON, modulo); estado_botao[botao] = 1; //client.print("1"); Serial.println("1"); } else { relays.SetRelay(rele, SERIAL_RELAY_OFF, modulo); estado_botao[botao] = 0; //client.print("0"); Serial.println("0"); } client.print("0|"); for (int i = 1 ; i <= 40 ; i++) { client.print(estado_botao[i]); client.print("|"); }
}
// funcao para limpar arrays (no nosso caso, as variaveis que armazenam requests) void StrClear(char *str, char length) { for (int i = 0; i < length; i++) { str[i] = 0; } }
// funcao que procura pela string SFIND em STR // retorna 1 se a string for encontrada // retorna 0 se a setring não for encontrada char StrContains(char *str, char* sfind) { char found = 0; char index = 0; char len;
len = strlen(str);
if (strlen(sfind) > len) { return 0; } while (index < len) { if (str[index] == sfind[found]) { found++; if (strlen(sfind) == found) { return 1; } } else { found = 0; } index++; } return 0; }
Página hmtl
<DOCTYPE html><html><head> <tittle>AutResidencial</tittle> <meta> <style>
div> h2 { color: blue } body{ font-family: Arial }
.header{ width: 100px; height: : 110px; border: 10px; background-color: #F6F9F9; margin-top: 0px; } #quadrado{ border-style: solid; border-color: #00979C; background-color: #F6F9F9; width: 800px; height:150px; text-align: center; display: inline-block; margin-bottom: 1000px; } #quadrado{ font-size: 30px } #quadrado{ cursor: pointer; } </style> </head>
<body>
<center> <div class"header"> </br> <div> <h2>Quarto</h2> </div> </br> </div>
<div id="quadrado"> <h5>Rele 1</h5> <p class="carga">Ligar/desligar</p> <div>
<div id="quadrado"> <h5>Rele 2</h5> <p class="carga">Ligar/desligar</p> <div>
<div id="quadrado"> <h5>Rele 3</h5> <p class="carga">Ligar/desligar</p> <div>
<div id="quadrado"> <h5>Rele 4</h5> <p class="carga">Ligar/desligar</p> <div>
</center>
</body>
<html>…
Adicionado por Breno Castello ao 20:19 em 22 novembro 2015
ton 8 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };//Ponemos la dirección MAC de la Ethernet Shield que está con una etiqueta debajo la placa IPAddress ip(10,0,0,20); //Asingamos la IP al Arduino EthernetServer server(8080); //Creamos un servidor Web con el puerto 80 que es el puerto HTTP por defecto
boolean count1,count2,count3=0; String estado[]="OFF"; //Estado del Led inicialmente "OFF"
void setup() { Serial.begin(9600); // Inicializamos la comunicación Ethernet y el servidor Ethernet.begin(mac, ip); server.begin(); W5100.setRetransmissionTime(0x07D0); W5100.setRetransmissionCount(20); Serial.print("server is at "); Serial.println(Ethernet.localIP()); pinMode(button, INPUT_PULLUP); } void loop() { EthernetClient client = server.available(); //Creamos un cliente Web //Cuando detecte un cliente a través de una petición HTTP if (client) { Serial.println("new client"); boolean currentLineIsBlank = true; //Una petición HTTP acaba con una línea en blanco String cadena=""; //Creamos una cadena de caracteres vacía while (client.connected()) { if (client.available()) { char c = client.read();//Leemos la petición HTTP carácter por carácter Serial.write(c);//Visualizamos la petición HTTP por el Monitor Serial cadena.concat(c);//Unimos el String 'cadena' con la petición HTTP (c). De esta manera convertimos la petición HTTP a un String //Ya que hemos convertido la petición HTTP a una cadena de caracteres, ahora podremos buscar partes del texto.
int posicion=cadena.indexOf("ESTADO="); //Guardamos la posición de la instancia "LED=" a la variable 'posicion' if(cadena.substring(posicion)=="ESTADO=1ON")//Si a la posición 'posicion' hay "LED=ON" { digitalWrite(led,count1); estado[1]="ON"; count1=1; Serial.println("1"); } if(cadena.substring(posicion)=="ESTADO=1OFF")//Si a la posición 'posicion' hay "LED=OFF" { digitalWrite(led,count1); estado[1]="OFF"; count1=0; Serial.println("0"); } if(cadena.substring(posicion)=="ESTADO=2ON")//Si a la posición 'posicion' hay "LED=ON" { digitalWrite(led,HIGH); estado[2]="ON"; count2=1; Serial.println("1"); } if(cadena.substring(posicion)=="ESTADO=2OFF")//Si a la posición 'posicion' hay "LED=OFF" { digitalWrite(led,LOW); estado[2]="OFF"; count2=0; Serial.println("0"); } if(cadena.substring(posicion)=="ESTADO=3ON")//Si a la posición 'posicion' hay "LED=ON" { digitalWrite(led,HIGH); estado[3]="ON"; count3=1; Serial.println("1"); } if(cadena.substring(posicion)=="ESTADO=3OFF")//Si a la posición 'posicion' hay "LED=OFF" { digitalWrite(led,LOW); estado[3]="OFF"; count3=0; Serial.println("0"); } //Cuando reciba una línea en blanco, quiere decir que la petición HTTP ha acabado y el servidor Web está listo para enviar una respuesta if (c == '\n' && currentLineIsBlank) { // Enviamos al cliente una respuesta HTTP client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // the connection will be closed after completion of the response client.println("Refresh: 5"); client.println(); //Página web en formato HTML client.println(F("<!DOCTYPE html>")); client.println(F("<html>")); client.println(F("<head>")); client.println(F("<title>Automacao com Arduino</title>")); client.println(F("<meta charset=\"windows-1252\">")); client.println(F("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">")); client.println(F("</head>")); client.println(F("<body bgcolor='#c8cdf5'>")); client.println(F("<div style='margin: auto; height: 700px; background-color: white; width: 800px; border-radius: 10px;'>")); client.println(F("<br>")); client.println(F("<h1 style='@media screen { color: #616582; font-family: Lucida Bright;} @media handheld { color: yellow;}'><center>NOME DO SITE</center></h1>")); client.println(F("<br>")); client.println(F("<center>")); client.println(F("<div style='text-align:center;'>")); if(count1==0){ client.println(F("<h4>LAMPADA 01:</h4>")); client.println(F("<button onClick=location.href='./?ESTADO=1ON\' style='margin:auto;background-color: #43B257;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:350px;'>")); client.println(F("<h2>LIGAR<h2>")); client.println(F("</button>")); }else if(count1==1){ client.println(F("<h4>LAMPADA 01:</h4>")); client.println(F("<button onClick=location.href='./?ESTADO=1OFF\' style='margin:auto;background-color: #B24343;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:350px;'>")); client.println(F("<h2>DESLIGAR<h2>")); client.println(F("</button>")); } client.println(F("<br />")); if(count2==0){ client.println(F("<h4>LAMPADA 02:</h4>")); client.println(F("<button onClick=location.href='./?ESTADO=2ON\' style='margin:auto;background-color: #43B257;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:350px;'>")); client.println(F("<h2>LIGAR<h2>")); client.println(F("</button>")); }else if(count2==1){ client.println(F("<h4>LAMPADA 02:</h4>")); client.println(F("<button onClick=location.href='./?ESTADO=2OFF\' style='margin:auto;background-color: #B24343;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:350px;'>")); client.println(F("<h2>DESLIGAR<h2>")); client.println(F("</button>")); } client.println(F("</b><br />")); if(count3==0){ client.println(F("<h4>TELEVISAO:</h4>")); client.println(F("<button onClick=location.href='./?ESTADO=3ON\' style='margin:auto;background-color: #43B257;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:350px;'>")); client.println(F("<h2>LIGAR<h2>")); client.println(F("</button>")); }else if(count3==1){ client.println(F("<h4>TELEVISAO:</h4>")); client.println(F("<button onClick=location.href='./?ESTADO=3OFF\' style='margin:auto;background-color: #B24343;color: snow;padding: 10px;border: 1px solid #3F7CFF;width:350px;'>")); client.println(F("<h2>DESLIGAR<h2>")); client.println(F("</button>")); } client.println(F("</b><br />")); client.println(F("<b>LAMPADA 1 = ")); client.print(estado[1]); client.println(F("</b><br />")); client.println(F("<b>LAMPADA 2 = ")); client.print(estado[2]); client.println(F("</b><br />")); client.println(F("<b>TELEVISAO = ")); client.print(estado[3]); client.println(F("</b><br />")); client.println(F("</center>")); client.println(F("<div style=\"height: 50px; width: 100%; background-color: #9296b0; margin-top: 60px; border-radius: 0 0 10px 10px; color: white; padding-top: 5px;\"><center>Design por Breno Matheus - @brenosantanav - brenosantanav@outlook.com <br> 2015</div>")); client.println(F("</div>")); client.println(F("</body>")); client.println(F("</html>")); break; } if (c == '\n') { currentLineIsBlank = true; } else if (c != '\r') { currentLineIsBlank = false; } } } //Dar tiempo al navegador para recibir los datos delay(1); client.stop();// Cierra la conexión } }
E eu estava querendo passar parâmetros para url a partir do arduino ( enviar), de um jeito que quando eu apertasse um push button atualizasse o botão da web. Resumindo estou querendo controlar o estado de um botão da web pelo acesso online ou pelo push button. Se alguem tiver alguma solução mais facil estou aceitando.…