Pages: [1]   Go Down
Author Topic: Arduino, PC, Ethernet, and VB  (Read 5416 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 3
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I have been scouring the internet for a simple example that I can expand upon and have had no luck and am hoping someone can help. I want to control an Arduino through an Ethernet cable using VB code on a PC. I have found where someone does this but uses a WiFi connection but I have not been able to successfully modify the code to get it to talk Ethernet instead of WiFi. I will attach the code I have so far but it may be easier if someone knows of a simple example to say turn on a single LED using the above I can modify the example to get what I want. The attached code does talk to my Arduino because I can see the TX and RX lights blink when I click on the form button but I cannot get the LED to turn on or off.

Arduino code:

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];

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:

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

I have found posts that talk VB to Arduino through serial and I have that working, WiFi to Arduino but can't test due to not having a WiFi shield of any sort, and I have some HTML versions of the code working but I would really like to control the Arduino using VB and Ethernet.

I am not extremely familiar with the Arduino nor VB but I know enough to understand what is going on most of the time. Any help on this is greatly appreciated especially if a simple example that I can modify can be provided or linked to.
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

So, a client connects to the Arduino-as-server.
Code:
  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);
        }
      }
    }
  }
You check to see if the client has anything to say, but you never bother to find out what the client has to say (there are no client.read() calls).

Then, you look in the buffer that you haven't written to to see if some stuff magically appeared there. Well, of course it hasn't, so buffer does not contain 'O' or 'F' in the first position, so nothing happens.

You never read what the client has to say, so it stays connected. Pretty soon, there are no more connections available, so no more clients can get in line to be ignored.

What was the problem, anyway?

Logged

Miramar Beach, Florida
Offline Offline
Faraday Member
**
Karma: 138
Posts: 5833
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Have you checked the Arduino server with a web browser? It seems you declare the server, but do not start it in setup.
Code:
void setup()
{
  pinMode(8,OUTPUT);
  Ethernet.begin(mac, local_ip);
  Serial.begin(9600);

  // start the server listening on port 80
  server.begin();
}

edit: I should have posted a link to the server sketch example in the playground (playground = wiki).
http://playground.arduino.cc/Code/WebServerST
« Last Edit: December 14, 2012, 07:31:18 am by SurferTim » Logged

0
Offline Offline
God Member
*****
Karma: 39
Posts: 988
Get Bitlash: http://bitlash.net
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

You're going to have to decide whether you want to use a web server / HTTP approach or an old-school telnet-style approach on the Arduino.  There are plenty of examples for the web server case (and in fact Zoomkat will be here any second to share some solid working HTTP code.)

It might be worth taking a look at the BitlashWebServer example that ships with Bitlash (http://bitlash.net).  It's a sketch that exposes Bitlash scripting as a web service from the Arduino over Ethernet.  It also has a telnet server so you can just send commands, as opposed to commands wrapped in HTTP GET requests.

For your project you could just send "d13=1" to turn on the LED on pin 13, and "d13=0" to turn it off.

Bitlash here: http://bitlash.net and you can browse the web server/telnet sketch code that ships in the distribution here: https://github.com/billroy/bitlash/blob/master/examples/BitlashWebServer/BitlashWebServer.ino

Good luck with your project,

-br

Edit: D13 is not going to work for an LED because it is used by the Ethernet shield.  Discovered this while creating a new built-in script for the BitlashWebServer.  But now you can open a browser on the server ip-address/toggle5 and it will turn pin 5 on and off.
« Last Edit: December 14, 2012, 08:07:09 am by billroy » Logged

0
Offline Offline
Tesla Member
***
Karma: 141
Posts: 9470
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Very simple web page control code.

Code:
//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="";

        }
      }
    }
  }
}

Logged

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   smiley-cool

Offline Offline
Newbie
*
Karma: 0
Posts: 3
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I haven't had much of a chance to play around with any of the code yet but I can answer some questions. I have tried the HTML version of control and I did get that to work with my Arduino. I guess one thing I am wondering here though is how can I implement a momentary button action while using Ethernet communications. From the small amount of web experience that I do have I believe a webpage is more like an on/off switch. Is that correct? I am assuming I could probably build in some kind of delay but it would get old having to click the button many times to keep something like a light on.

I do not have much experience with an Arduino so far and am trying to learn more everyday. I will attempt to work on the ideas mentioned above this weekend but if anyone has ideas of how I can implement a momentary style switch instead of an on/off switch it would be greatly appreciated if you would share your thoughts or ideas.
Logged

0
Offline Offline
Tesla Member
***
Karma: 141
Posts: 9470
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
I do not have much experience with an Arduino so far and am trying to learn more everyday. I will attempt to work on the ideas mentioned above this weekend but if anyone has ideas of how I can implement a momentary style switch instead of an on/off switch it would be greatly appreciated if you would share your thoughts or ideas.

You need to explain in more detail the desired operation of your "momentary style switch". Is the light to be on while the switch is closed/pushed, and off when the switch is opened/released? Are you wanting to do this via a web page or some other VB application?
Logged

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   smiley-cool

Offline Offline
Jr. Member
**
Karma: 1
Posts: 85
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Just found this link to Arduino VB Lab - interesting
http://sourceforge.net/projects/arduinovblab/?source=recommended
Cheers
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 3
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you everyone for your help and posts. I have finally got it working!! PaulS, thank you for your initial post. I took a better look at my code and compared it closer to a working version of the HTML working code and found that, as you said, I was never reading the client. As for other ways of doing the same thing I am wanting a momentary button so that on my PC I would click a button and while I am holding the mouse button down the light would be on and once I let go the light goes off until I click and hold the button again. I have implemented this using the keyboard but thought it would also be nice to do it in VB code as well using the mouse but haven't figured it out just yet. Also thank you to rbright for the link. I can definitely see some uses for that interface and program in the very near future. My working code is below. It has some extra items in it that I got from another example but I think I can modify it to make what I want.

Arduino Code:
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:
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
Logged

0
Offline Offline
Tesla Member
***
Karma: 141
Posts: 9470
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

In html pages mouse actions can be used like below.

Code:
<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');"/>
Logged

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   smiley-cool

Offline Offline
Newbie
*
Karma: 0
Posts: 29
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

In html pages mouse actions can be used like below.

Code:
<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');"/>

REally???? please give some code that people use not just any garbage.

a mouse action is easier done using this:

<form name="input" action="/yourserver" method="get">
Username: <input type="text" name="something">
<input type="submit" value="Submit">
</form>
Logged

0
Offline Offline
Tesla Member
***
Karma: 141
Posts: 9470
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
REally???? please give some code that people use not just any garbage.

Somebody pee in your corn flakes?  smiley-cool
Logged

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   smiley-cool

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
Somebody pee in your corn flakes?
Yep. And I know who it was.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 9
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

i am very interesting your project. Can you upload ur Vb interface  sources? Thank you. smiley
Logged

South Africa
Offline Offline
Newbie
*
Karma: 0
Posts: 7
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello All

I found the discussion very useful, thank you.
I have another question though...Does anyone have example code which will allow the Arduino to transmit data to the VB app as well? Basically using a VB application as SCADA in order to send commands to the Arduino, as well as read commands from the Arduino?

I would appreciate any information / web links / help.

Thank in advance

smiley
Logged

Pages: [1]   Go Up
Jump to: