You are on page 1of 8

Vasculhando a internet a procura de um exemplo simples que eu possa expandir e

no tiveram sorte e estou esperando que algum pode ajudar. Eu quero controlar um
Arduino atravs de um cabo Ethernet usando o cdigo VB em um PC. Eu descobri que algum
faz isso, mas usa uma conexo WiFi, mas eu no tenho sido capaz de modificar com
sucesso o cdigo para que ele comece a falar Ethernet em vez de WiFi. Vou anexar o
cdigo que eu tenho at agora, mas pode ser mais fcil se algum sabe de um exemplo
simples para acender um nico LED que eu possa modificar o exemplo para conseguir o que
eu quero.
cdigo Arduino:
//*******************************************************************************
******************************************************
// Declarations
//*************************************************************************************
************************************************
#include <SPI.h>
#include <Ethernet.h>
//*************************************************************************************
************************************************
// Wired configuration parameters
//*************************************************************************************
************************************************
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xD1, 0x4B };
unsigned char local_ip[] = {192,168,1,100};
// IP address of WiShield
unsigned char gateway_ip[] = {192,168,1,1};
// router or gateway IP address
unsigned char subnet_mask[] = {255,255,255,0}; // subnet mask for the local network
EthernetServer server(80);
char buffer[20];
void setup()
{
pinMode(8,OUTPUT);
Ethernet.begin(mac, local_ip);
Serial.begin(9600);
}
void loop()
{
EthernetClient client = server.available();
if (client)
{
boolean currentLineIsBlank = true;
while (client.connected())
{
if (client.available())
{
int val;
if (buffer[0] == 'O')
{
digitalWrite(8,HIGH);
}
else if (buffer[0] == 'F')
{
digitalWrite(8,LOW);
}
}
}
}
}
VB Code:
Imports System.Net.Sockets
Imports System.Text

Public Class Form1


Dim tcpClient As New System.Net.Sockets.TcpClient()
Dim networkStream As NetworkStream
Dim KeyPressed As Integer
Private Function Arduino_Connect(ByVal IP As String, ByVal Port As Integer) As
Boolean
tcpClient.Connect(IP, Port)
networkStream = tcpClient.GetStream()
If Not networkStream.CanWrite Or Not networkStream.CanRead Then
tcpClient.Close()
networkStream = Nothing
Return False
End If
Return True
End Function
Private Sub Arduino_Write(ByVal Output As String)
If Not IsNothing(networkStream) Then
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(Output)
Dim endByte As [Byte]() = {&HFE}
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Write(endByte, 0, 1)
Else
MsgBox("ERROR")
End If
End Sub
Private Sub Form1_load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
Arduino_Connect("192.168.1.100", 80)
picOff.Visible = True
picOn.Visible = False
End Sub
Private Sub Arduino_Disconnect()
If Not IsNothing(networkStream) Then
tcpClient.Close()
networkStream = Nothing
End If
End Sub
Private Sub btnOn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnOn.Click
picOff.Visible = False
picOn.Visible = True
Arduino_Write("O")
End Sub
Private Sub btnOff_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnOff.CLick
picOff.Visible = True
picOn.Visible = False
Arduino_Write("F")
End Sub
End Class
Eu descobri mensagens que falam VB ao Arduino atravs de srie e eu tenho que
trabalhar, WiFi ao Arduino, mas no pode testar devido a no ter um escudo WiFi de
qualquer espcie, e eu tenho algumas verses HTML do cdigo de trabalho, mas eu
realmente quer controlar o Arduino usando VB e Ethernet.
Eu no sou muito familiarizado com o Arduino nem VB mas sei o suficiente para
entender o que est acontecendo na maioria das vezes. Qualquer ajuda sobre este muito
apreciada especialmente se um exemplo simples que eu posso modificar podem ser
fornecidos ou ligados a.
So, a client connects to the Arduino-as-server.

if (client)
boolean currentLineIsBlank = true;
while (client.connected())
{
if (client.available())
{
int val;
if (buffer[0] == 'O')
{
digitalWrite(8,HIGH);
}
else if (buffer[0] == 'F')
{
digitalWrite(8,LOW);
}
}
}

}
Voc verifica para ver se o cliente tem alguma coisa a dizer, mas voc nunca se
preocuparam em descobrir o que o cliente tem a dizer (no h client.read () chama).
Ento, voc olha no buffer que voc no tenha escrito para ver se algumas coisas
magicamente apareceu l. Bem, claro que no tem, at tampo no contm 'O' ou 'F' na
primeira posio, ento nada acontece.
Voc nunca leu o que o cliente tem a dizer, por isso permanece conectado. Logo,
no h mais ligaes disponveis, por isso no h mais clientes podem entrar na fila
para ser ignorado.
Qual era o problema, afinal?
Voc verificou o servidor Arduino com um navegador web? Parece que voc declarar
o servidor, mas no inici-lo na configurao.
void setup()

pinMode(8,OUTPUT);
Ethernet.begin(mac, local_ip);
Serial.begin(9600);
// start the server listening on port 80
server.begin();
}
edit: eu deveria ter postado um link para o exemplo esboo servidor no campo de
jogos (campo de jogos = wiki).
http://playground.arduino.cc/Code/WebServerST
Voc vai ter que decidir se voc quer usar uma abordagem HTTP web server / ou uma
abordagem de estilo telnet old-school no Arduino. H uma abundncia de exemplos para o
caso de servidor web (e, de fato Zoomkat vai estar aqui a qualquer momento para
compartilhar algum cdigo HTTP de trabalho slida.)
Pode valer a pena dar uma olhada no exemplo BitlashWebServer que vem com Bitlash
(http://bitlash.net). um esboo que expe Bitlash scripting como um servio web a
partir do Arduino over Ethernet. Ele tambm tem um servidor Telnet para que voc pode
apenas enviar comandos, em oposio aos comandos envoltos em solicitaes HTTP GET.
Para o seu projeto voc poderia simplesmente enviar "d13 = 1" para ligar o LED no
pino 13, e "d13 = 0" para deslig-lo.
Bitlash aqui: http://bitlash.net e voc pode navegar o cdigo esboo servidor /
telnet web que vem na distribuio aqui:
https://github.com/billroy/bitlash/blob/master/examples/BitlashWebServer/BitlashWebServ
er. eu no

Boa sorte com seu projeto,


-br
Edit: D13 no est indo trabalhar para um LED porque usado pelo escudo
Ethernet. Descobri esta ao criar um novo script embutido para o BitlashWebServer. Mas
agora voc pode abrir um browser no servidor ip-address / toggle5 e ele vai se
transformar pino 5 ligado e desligado.
cdigo de controle de pgina web muito simples.
//zoomkat 4-1-12
//simple button GET for servo and pin 5
//for use with IDE 1.0
//open serial monitor to see what the arduino receives
//use the \ slash to escape the " in the html, or use ' instead of "
//address will look like http://192.168.1.102:84 when submited
//for use with W5100 based ethernet shields
#include <SPI.h>
#include <Ethernet.h>
#include <Servo.h>
Servo myservo; // create servo object to control a servo
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //physical mac address
byte ip[] = { 192, 168, 1, 102 }; // ip in lan
byte gateway[] = { 192, 168, 1, 1 }; // internet access via router
byte subnet[] = { 255, 255, 255, 0 }; //subnet mask
EthernetServer server(84); //server port
String readString;
//////////////////////
void setup(){
pinMode(5, OUTPUT); //pin selected to control
//start Ethernet
Ethernet.begin(mac, ip, gateway, gateway, subnet);
server.begin();
myservo.write(90); //set initial servo position if desired
myservo.attach(7); //the pin for the servo control
//enable serial data print
Serial.begin(9600);
Serial.println("server servo/pin 5 test 1.0"); // so I can keep track of what is
loaded
}
void loop(){
// Create a client connection
EthernetClient client = server.available();
if (client) {
while (client.connected()) {
if (client.available()) {
char c = client.read();
//read char by char HTTP request
if (readString.length() < 100) {
//store characters to string
readString += c;
//Serial.print(c);
}
//if HTTP request has ended

if (c == '\n') {
///////////////
Serial.println(readString); //print to serial monitor for debuging
client.println("HTTP/1.1 200 OK"); //send new page
client.println("Content-Type: text/html");
client.println();
client.println("<HTML>");
client.println("<HEAD>");
client.println("<TITLE>Arduino GET test page</TITLE>");
client.println("</HEAD>");
client.println("<BODY>");
client.println("<H1>Zoomkat's simple Arduino button</H1>");
client.println("<a href=\"/?on\">ON</a>");
client.println("<a href=\"/?off\">OFF</a>");
client.println("</BODY>");
client.println("</HTML>");
delay(1);
//stopping client
client.stop();
///////////////////// control arduino pin
if(readString.indexOf("on") >0)//checks for on
{
myservo.write(40);
digitalWrite(5, HIGH);
// set pin 5 high
Serial.println("Led On");
}
if(readString.indexOf("off") >0)//checks for off
{
myservo.write(140);
digitalWrite(5, LOW);
// set pin 5 low
Serial.println("Led Off");
}
//clearing string for next read
readString="";
}
}

}
Eu no tive muita chance de brincar com nenhum cdigo ainda, mas eu posso
responder a algumas perguntas. Eu tentei a verso HTML do controle e eu fiz chegar a
esse trabalho com o meu Arduino. Eu acho que uma coisa que eu estou querendo aqui,
porm, como eu pode implementar uma ao de boto momentneo durante o uso de
comunicaes Ethernet. Da pequena quantidade de experincia web que eu tenho Eu
acredito que uma pgina da web mais como um interruptor on / off. Isso est correto?
Eu estou supondo que eu provavelmente poderia construir em algum tipo de atraso, mas
ele iria ficar velho ter que clicar no boto vrias vezes para manter algo como uma luz
acesa.
Eu no tenho muita experincia com
mais todos os dias. Vou tentar trabalhar
semana, mas se algum tem idias de como
momentnea em vez de um interruptor on /
compartilhar seus pensamentos ou idias.

um Arduino at agora e estou tentando aprender


nas ideias acima mencionadas neste fim de
eu pode implementar um interruptor estilo
off seria muito apreciada, se voc

Voc precisa explicar mais detalhadamente a operao desejada do seu "switch


estilo momentnea". a luz para ser ligado enquanto o interruptor est fechado /
empurrado, e desliga quando o interruptor aberto / lanado? Voc est querendo fazer
isso atravs de uma pgina web ou algum outro aplicativo VB?

S encontrei este link para Arduino VB Lab - interessante


http://sourceforge.net/projects/arduinovblab/?source=recommended
Sade
Obrigado a todos por sua ajuda e mensagens. Eu finalmente tenho que trabalhar !!
PaulS, obrigado por seu post inicial. Dei uma olhada melhor no meu cdigo e comparou-o
mais perto de uma verso de trabalho do cdigo de trabalho HTML e descobriu que, como
voc disse, eu nunca estava lendo o cliente. Quanto a outras formas de fazer a mesma
coisa que eu estou querendo um boto momentneo de modo que no meu PC eu clicar em um
boto e enquanto eu estou segurando o boto do mouse para baixo a luz seria em e uma
vez eu deixar de ir a luz apaga-se at que eu clique e segure o boto novamente. Eu
tenho implementado isso usando o teclado, mas pensei que tambm seria bom faz-lo no
cdigo VB bem usando o mouse, mas no percebi isso ainda. Obrigado tambm a rbright
para o link. Eu posso definitivamente ver alguns usos para essa interface e programa no
futuro muito prximo. Meu cdigo de trabalho est abaixo. Ele tem alguns itens extras
em que eu tenho de mais um exemplo, mas acho que pode modific-la para fazer o que eu
quero.
Arduino Code:
//*******************************************************************************
******************************************************
// Declarations
//*************************************************************************************
************************************************
#include <SPI.h>
#include <Ethernet.h>
//*************************************************************************************
************************************************
// Wired configuration parameters
//*************************************************************************************
************************************************
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xD1, 0x4B };
unsigned char local_ip[] = {192,168,1,100};
// IP address of WiShield
unsigned char gateway_ip[] = {192,168,1,1};
// router or gateway IP address
unsigned char subnet_mask[] = {255,255,255,0}; // subnet mask for the local network
EthernetServer server(80);
//char buffer[20];
String buffer = "";
void setup()
{
pinMode(8,OUTPUT);
Ethernet.begin(mac, local_ip);
Serial.begin(9600);
}
void loop()
{
EthernetClient client = server.available();
if (client)
{
boolean currentLineIsBlank = true;
while (client.connected())
{
if (client.available())
{
char c = client.read();
Serial.print(c);
buffer+=c;
int val;
if (c == 'O')
{
digitalWrite(8,HIGH);
}

}
}

else if (c == 'F')
{
digitalWrite(8,LOW);
}

}
VB Code
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim tcpClient As New System.Net.Sockets.TcpClient()
Dim networkStream As NetworkStream
Dim KeyPressed As Integer
Private Function Arduino_Connect(ByVal IP As String, ByVal Port As Integer) As
Boolean
tcpClient.Connect(IP, Port)
networkStream = tcpClient.GetStream()
If Not networkStream.CanWrite Or Not networkStream.CanRead Then
tcpClient.Close()
networkStream = Nothing
Return False
End If
Return True
End Function
Private Sub Arduino_Write(ByVal Output As String)
If Not IsNothing(networkStream) Then
Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes(Output)
Dim endByte As [Byte]() = {&HFE}
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Write(endByte, 0, 1)
Else
MsgBox("ERROR")
End If
End Sub
Private Sub Form1_load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
Arduino_Connect("192.168.1.100", 80)
picOff.Visible = True
picOn.Visible = False
End Sub
Private Sub Arduino_Disconnect()
If Not IsNothing(networkStream) Then
tcpClient.Close()
networkStream = Nothing
End If
End Sub
Private Sub btnOn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnOn.Click
picOff.Visible = False
picOn.Visible = True
Arduino_Write("O")
End Sub
Private Sub btnOff_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnOff.CLick
picOff.Visible = True
picOn.Visible = False
Arduino_Write("F")
End Sub

Private Sub Control_KeyDown(ByVal sender As Object, ByVal e As


System.Windows.Forms.KeyEventArgs) Handles Control.KeyDown
Select Case KeyPressed
Case 38 ' Up
'Car_Stop()
Case 40 ' Down
' Car_Stop()
Case 39 ' Right
'MsgBox("You pressed Ctrl and Arrowkey Right")
picOff.Visible = False
picOn.Visible = True
Arduino_Write("O")
Case 37 ' Left
' Car_TurnNone()
End Select
KeyPressed = 0
End Sub
Private Sub Control_KeyUp(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles Control.KeyUp
KeyPressed = e.KeyCode
Select Case KeyPressed
Case 38 ' Up
'Car_ForwardDrive(Speed.Text)
Case 40 ' Down
'Car_BackwardDrive(Speed.Text)
Case 39 ' Right
picOff.Visible = True
picOn.Visible = False
Arduino_Write("F")
Case 37 ' Left
' Car_TurnLeft()
End Select
End Sub
End Class
Em pginas HTML aes do mouse pode ser usado como abaixo.
<input type="button" value="<<<"
onmousedown="location.href
('http://127.0.0.1/cgi-bin/cgi3c8.exe?-0p700S100');"
onmouseup="location.href
('http://127.0.0.1/cgi-bin/cgi3c8.exe?STOP0');"/>

You might also like