Olá Pessoal.
Já vi aqui no forum projectos de Automacao com arduino blueetooth e Android.
Porem ainda não encontrei nenhum projecto que invés de usar Bluetooth funcione com etherneshield.
Pesquisando um pouco na net encontrei este projecto:
---------------------------------CÓDIGO ARDUINO-------------------------------------
/*
Web Server
A simple web server that switches LED's on and off, based on input from an
Android App Inventor application
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
* LED outputs attached to pins 5 and 6
created 13 Oct 2010
by Rogier van den Berg / rogiervandenberg.nl
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,0, 201 };
//Settings for the two LED's
int ledPin = 5;
int ledState = LOW;
int powerLedPin = 6;
int powerLedState = LOW;
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
Server server(80);
void setup()
{
//Set the LED pins as output
pinMode(ledPin, OUTPUT);
pinMode(powerLedPin, OUTPUT);
//For debugging, set the Serial Output
Serial.begin(9600);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
//Turn one of the LED's on, to know it is ready to go!
digitalWrite(powerLedPin, HIGH);
}
void loop()
{
//Make sure requests are taken care of
handleIncomingInstruction();
//Make sure the power led stays on, when nothing happens.
if(powerLedState == LOW)
switchPowerLed();
}
void handleIncomingInstruction()
{
// listen for incoming clients
Client client = server.available();
if (client) {
// an http request ends with a blank line
boolean newLine = true;
String line = "";
while (client.connected() && client.available()) {
char c = client.read();
//Serial.print(c);
switchPowerLed();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && newLine) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
}
if (c == '\n') {
// you're starting a new line
newLine = true;
evaluateLine(line);
line = "";
}
else if (c != '\r') {
// you've gotten a character on the current line
newLine = false;
line += c;
}
}
evaluateLine(line);
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}
void evaluateLine(String line)
{
if (line.startsWith("tag", 0)) {
String instruction = line.substring(4, line.length());
Serial.println(instruction);
if (instruction == "TestOpdracht")
switchLed();
}
}
void switchLed()
{
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
Serial.println("We switchen de LED!");
}
void switchPowerLed()
{
// if the LED is off turn it on and vice-versa:
if (powerLedState == LOW)
powerLedState = HIGH;
else
powerLedState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(powerLedPin, powerLedState);
}
------------------------------------------------ FIM ------------------------------------------
Código para app inventor para o abrir basta no app inventor fazer:
My projectos-->More Actions-->Upload Source
---------------------- VIDEO DE DEMONSTRAÇÃO----------------------------------
https://www.youtube.com/watch?v=r7y0IpGhk_w
Ora bem o que este projecto faz é basicamente atraves de um Android com um programa apenas com um botao faz ligar e desligar o led.
Agora eu gostaria da vossa ajuda para o seguinte:
Eu pretendo que ao ligar o Led esse botão fique com a cor VERDE e ao desligar o led fique com a cor Vermelha.
E pretendia também o seguinte: se o led tiver acesso e o botão verde, eu gostaria que ao desligar o equipamento android e voltar a ligar o programa, que ele veja o estado do led.. se ele tiver acesso aparece então a cor verde se tiver desligado, aparece vermelho.
Alguem me pode enviar o projecto já modificado com essa funcoes?
Ficaria muito grato.
Tags:
Olá pessoal, já consegui progressos com a aplicacao.
Agora tou aqui entalado em outro problema que é o seguinte:
Aqui no codigo do arduino:
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,0, 201 };
//Settings for the two LED's
int ledPin = 5;
int ledState = LOW;
int powerLedPin = 6;
int powerLedState = LOW;
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
Server server(80);
void setup()
{
//Set the LED pins as output
pinMode(ledPin, OUTPUT);
pinMode(powerLedPin, OUTPUT);
//For debugging, set the Serial Output
Serial.begin(9600);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
//Turn one of the LED's on, to know it is ready to go!
digitalWrite(powerLedPin, HIGH);
}
void loop()
{
//Make sure requests are taken care of
handleIncomingInstruction();
//Make sure the power led stays on, when nothing happens.
if(powerLedState == LOW)
switchPowerLed();
}
void handleIncomingInstruction()
{
// listen for incoming clients
Client client = server.available();
if (client) {
// an http request ends with a blank line
boolean newLine = true;
String line = "";
while (client.connected() && client.available()) {
char c = client.read();
//Serial.print(c);
switchPowerLed();
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && newLine) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
}
if (c == '\n') {
// you're starting a new line
newLine = true;
evaluateLine(line);
line = "";
}
else if (c != '\r') {
// you've gotten a character on the current line
newLine = false;
line += c;
}
}
evaluateLine(line);
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}
void evaluateLine(String line)
{
if (line.startsWith("tag", 0)) {
String instruction = line.substring(4, line.length());
Serial.println(instruction);
if (instruction == "TestOpdracht")
switchLed();
}
}
void switchLed()
{
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
Serial.println("We switchen de LED!");
}
void switchPowerLed()
{
// if the LED is off turn it on and vice-versa:
if (powerLedState == LOW)
powerLedState = HIGH;
else
powerLedState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(powerLedPin, powerLedState);
}
Eu queria que na parte do:
void switchLed()
{
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
Serial.println("We switchen de LED!");
}
Quando o led tivesse HIGH quando eu acessasse a pagina do webbrower do arduino aparecessse um texto a dizer:
LED ligado
e quando tivesse LOW quando eu acessasse novamente a pagina webbrowser do arduino aparecesse um texto a dizer LED DESLIGADO.
quem me ajuda na modificacao do codigo?
Olá amigo eu já fiz um aplicativo usando android e ethernet shield onde passo os parâmetros via URL e trato cada URL como um thread no android, porém usei o sdk do android com o eclipse, não usei o app inventor. Me fale precisamente o que você precisa que te ajudo no seu projeto e posso até montar um tutorial e postar aqui, caso seja alta a demanda.
Um abraço e boas festas!, fique com DEUS,
Ola leandro obrigado pela disponibilidade mas já consegui:
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 75 }; // ip in lan
byte gateway[] = { 192, 168, 1, 254 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(6969);
//Settings for the two LED's
int ledPin = 5;
int ledState = LOW;
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
void setup()
{
//Set the LED pins as output
pinMode(ledPin, OUTPUT);
//For debugging, set the Serial Output
Serial.begin(9600);
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
//Turn one of the LED's on, to know it is ready to go!
}
void loop()
{
//Make sure requests are taken care of
handleIncomingInstruction();
//Make sure the power led stays on, when nothing happens.
}
void handleIncomingInstruction()
{
// listen for incoming clients
EthernetClient client = server.available();
if (client) {
// an http request ends with a blank line
boolean newLine = true;
String line = "";
while (client.connected() && client.available()) {
char c = client.read();
//Serial.print(c);
// if you've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so you can send a reply
if (c == '\n' && newLine) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("<body>");
client.println("<hr />");
client.print("<font size='5'>LED status: ");
if (ledState == LOW)
{
client.println("<font color='green' size='5'>0");
}
else
{
client.println("<font color='green' size='5'>1");
}
// auto reload webpage every 5 second
client.println("<META HTTP-EQUIV=REFRESH CONTENT=5 URL=>");
client.println("</body>");
}
if (c == '\n') {
// you're starting a new line
newLine = true;
evaluateLine(line);
line = "";
}
else if (c != '\r') {
// you've gotten a character on the current line
newLine = false;
line += c;
}
}
evaluateLine(line);
// give the web browser time to receive the data
delay(1);
// close the connection:
client.stop();
}
}
void evaluateLine(String line)
{
if (line.startsWith("tag", 0)) {
String instruction = line.substring(4, line.length());
Serial.println(instruction);
if (instruction == "ligar")
ligar();
if (instruction == "desligar")
desligar();
}
}
void ligar()
{
// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
void desligar()
{
// if the LED is off turn it on and vice-versa:
if (ledState == HIGH)
ledState = LOW;
else
ledState = HIGH;
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
No entanto não tou a conseguir que o app inventor leia os seguintes valores:
if (ledState == LOW)
{
client.println("<font color='green' size='5'>0");
}
else
{
client.println("<font color='green' size='5'>1");
a minha estrutura esta assim:
ou seja o meu botao STATUS LED nao fica verde quando esta 1 nem vermelho quando esta zero.
no entanto quando eu acesso ao meu http://192.168.1.75:6969 aparece lá o estado 0 e 1
alguempode ajudar?
Tem uma maneira fácil de resolver isso, porém creio que irá gerar ma nova pergunta a seguir. Mas para resolver o problema da cor do botão no App Inventor, basta colocar o "status_led.BackgroundColor" na função btnLigar.Click logo após o TinyWebDB.GetValue, definindo a cor como fez no GotValue.
Resumindo, faça com que o Click no Botão diga a cor do status.
Oi pessoal, pois é eu mais o Eduardo e o Bruno Bobbio temos estado a luz aqui na parte do código e estamos a chegar perto do pretendido.
So que voltaram novamente alguns problemas ora vejam as imagens.
Codigo do arduino:
Pagina do web browser:
codigo do app inventor:
entao o que se passa? como podem ver ai na imagem do web browser ele esta a ler dois valores
o primeiro valor 0 é o valor do client.print(digitalRead(luzsalaPin));
e o segundo valor 0 é do client.print(digitalRead(luzcozinhaPin));
agora nao tou a conseguir que o codigo do app inventor faça o pretendido ou seja,
se o valor 0 do client.print(digitalRead(luzsalaPin)); for lido pelo app inventor o botao2 será vermelho caso nao seja deverá ser verde.
E...SE
se o valor 0 do client.print(digitalRead(luzcozinhaPin)); for lido pelo app inventor o botao2 será vermelho caso nao seja deverá ser verde.
alguem pode ajudar ??
obrigado
Rodrigo,
Acerta o resultado para mostrar em uma só linha. No AI leia esse valor num label e teste esse Label. Se for fazer somente esse 2 ambientes, testa esses valores assim:
00 -> OFF OFF
10 -> ON OFF
01 -> OFF ON
11 -> ON ON
Creio que vai dar certo. Só vai dar um trabalhinho a mais. Existem outras formas de fazer, mas precisará de modificar muita coisa tanto no arduino como no AI.
Flw, qualquer coisa estarei por aqui a disposição.
Oi bruno e pessoal do lab.
Bom voltei a ter novos progressos, mas como semrpre fico triste pois nao consigo nunca acabar com sucesso.
entao é o seguinte, consegui ler o valor de dois pins atraves de uma tabela no app inventor como mostro nas imagens.
Agora como é que eu por exemplo consigo fazer um IF estilo assim:
"se o valor do SELECT LIST ITEM N.1 for igual a 0 então o button1 fica vermelho
se não o button1 fica verde.
FICO a aguardar um resposta, em anexo deixo o source do app inventor
E aí Rodolfo,
Você já resolveu o problema rsrsr. Em vez de você mostrar no Label, você testa o Label. IF - Label1.Text - make text - select list item - variable 1 = 0
Then Button.BackgroungColor - RED
IF - Label1.Text - make text - select list item - variable 1 = 0
Then Button.BackgroungColor - GREEN
Faça isso testando o segundo item...
Qualquer coisa estarei por aqui... até logo.
oi mas meto o BLOCO larana do
if test
then do
embaixo de onde?? nao tou a conseguir entender a estrtura que estas a dizer
Olá,
Estou vendo a sua dificuldade em conseguir o seu objetivo.
Existe um pacote que pode adquirir que tem tudo que precisa.
O pacote pode ser adquirido no Link abaixo.
O pacote vem
Codigo Arduino aberto e comentado para conhecimento
Codigo PHP aberto e comentado ( para controlar até 100 lampadas), podendo alterar os nomes dos botões com facilidade, sem necessidade de conhecer o código.
Aplicativo para Android pronto (sem código fonte)
Com o aplicativo você poderá controlar até 10 lampadas, poderá controlar aparelhos com Infra-vermelho, já está configurado para controle de Luminosidade, alterando-a no proprio apk.
pena que o código Android não pode ser aberto, mas os demais são então poderá aprender muito com eles.
http://produto.mercadolivre.com.br/MLB-454514701-aplicativo-android...
Videos:
http://www.youtube.com/watch?v=sYBh5g9VzOs
http://www.youtube.com/watch?v=19ocr4rgfmA
http://www.youtube.com/watch?v=ZRPjJLKaaws
Um abraço
Rodolfo, estou tentando desenvolver no app inventor uma tela para ligar e desligar a luz pelo arduino e um w5100. Ja faz 2 semanas de pesquisa e ate agora nao tive progresso algum. Voce poderia me auxiliar me dizendo como vc fez essa comunicação com o arduino e quais componentes vc usou. Se possivel passar os fontes do app inventor para estudar. Desde ja te agradeço pela ajuda.
Vlw
Obrigado
Estou com a mesma dúvida que vocês, se tiverem alguma evolução me deixem avisado por favor.
Bem-vindo a
Laboratorio de Garagem (arduino, eletrônica, robotica, hacking)
© 2024 Criado por Marcelo Rodrigues. Ativado por