Visual Basic TcpClient + Arduino

kumandan11

Üye
Katılım
4 Ağu 2013
Mesajlar
18
Puanları
1
Merhaba iyi günler.

Amaç: Arduino ethernet shiled'den gönderdiğim veriyi Visual Basic ile okumak istiyorum.
Sonuç: Başarılı ama bir kaç sorunum var.
Sorun1: Ethetnet üzerinden veri gödermen için TcpClient kullandım. Arduino üzerinden oluşturduğum serverdan verileri okudum. Fakat Vb.net'te Bağlan(Yapıldı) ve Bağlantıyı Kes butonları yapmak istiyorum. Bağlantıyı Kes bununu nasıl yapabilirim.
Sorun2: Label üzerinden server'a bağlanıp bağlamadığını kontrol etmek istiyorum. Bağlantı varsa Bağlı , Bağlantı Yoksa Bağlı Değil yazsın. ( Arduinodaki Ethnert kablosunu çektiğimde veya arduino ile bağlantı gidince serverdan bağlatı yok yazmasını istiyorum. Do Loop Until döngüsünden çıkamadım ).

Visual Basic Kodu:
C:
Imports System.Net.Sockets
Public Class Form1

    Private Delegate Sub AppendTextBoxDelegate(ByVal TB As RichTextBox, ByVal txt As String)

    Private Sub AppendTextBoxes(ByVal TB As RichTextBox, ByVal txt As String)
        If TB.InvokeRequired Then
            TB.Invoke(New AppendTextBoxDelegate(AddressOf AppendTextBoxes), New Object() {TB, txt})
        Else
            TB.Text += ""
            TB.Text = RichTextBox1.Text + Environment.NewLine + " >> " + txt
        End If
    End Sub

    Dim clientSocket As New System.Net.Sockets.TcpClient()
    Dim serverStream As NetworkStream
    Dim data As [Byte]()

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'Start Butonu
        If Not BackgroundWorker1.IsBusy Then
            BackgroundWorker1.RunWorkerAsync()
        End If
    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AppendTextBoxes(RichTextBox1, "Client Started")
        'BackgroundWorker1.RunWorkerAsync()
    End Sub

    Private Sub My_BgWorker_DoWork1(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork

        Try
            clientSocket.Connect("192.168.2.195", 4545)
            AppendTextBoxes(RichTextBox1, "Client Socket Program - Server Connected ...")

            Dim serverStream As NetworkStream = clientSocket.GetStream()

            If serverStream.CanRead = True Then
                Do
                    Dim inStream As [Byte]() = New [Byte](256) {}
                    Dim bytes As Int32 = serverStream.Read(inStream, 0, inStream.Length)
                    Dim returndata As String = System.Text.Encoding.ASCII.GetString(inStream, 0, bytes)
                    AppendTextBoxes(RichTextBox1, "Data from Server : " + returndata)
                    Console.WriteLine("Data from Server : " + returndata)
                Loop Until serverStream.CanRead = False
            Else
                AppendTextBoxes(RichTextBox1, "No Data to Receive")
                clientSocket.Close()
                serverStream.Close()
            End If
        Catch ex As Exception
            MessageBox.Show(Environment.NewLine & ex.Message & Environment.NewLine & ex.StackTrace, "Dumping To Log", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1)
        End Try
    End Sub

    Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        If e.Cancelled Then
            MsgBox("Cancelled")
        End If
        AppendTextBoxes(RichTextBox1, "Finished Getting Stream!")
    End Sub

    Private Sub RichTextBox1_TextChanged(sender As Object, e As EventArgs) Handles RichTextBox1.TextChanged
        RichTextBox1.SelectionStart = RichTextBox1.Text.Length
        RichTextBox1.ScrollToCaret()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        clientSocket.GetStream().Close()
        clientSocket.Close()

        If Not BackgroundWorker1.IsBusy Then
            BackgroundWorker1.CancelAsync()
        End If
    End Sub
End Class

Arduino Kodu:
C++:
#include <SPI.h>
#include <Ethernet.h>
#include <MFRC522.h>

#define SS_PIN 8
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance.

int readsuccess;
byte readcard[4];
char str[32] = "";
String StrUID;


// 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
};

IPAddress ip(192, 168, 2, 195);
IPAddress gateway(192, 168, 2, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(192, 168, 2, 1);

EthernetServer server(4545);
bool alreadyConnected = false; // whether or not the client was connected previously


void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  // You can use Ethernet.init(pin) to configure the CS pin
  Ethernet.init(10);  // Most Arduino shields
 
  SPI.begin();      // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card

  // initialize the Ethernet device not using DHCP:
  Ethernet.begin(mac, ip, gateway, primaryDNS, subnet);

  // print your local IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());

  // start listening for clients
  server.begin();

}

void loop() {
  EthernetClient client = server.available();

  readsuccess = getid();
 
  if(readsuccess){
    server.write(StrUID.c_str());
    Serial.println(StrUID);
    delay(1000);
  }

Ethernet.maintain();
}


// --------------------------------------------------------------------
int getid() {
  if (!mfrc522.PICC_IsNewCardPresent()) {
    return 0;
  }
  if (!mfrc522.PICC_ReadCardSerial()) {
    return 0;
  }
  for (int i = 0; i < 4; i++) {
    readcard[i] = mfrc522.uid.uidByte[i]; //storing the UID of the tag in readcard
    array_to_string(readcard, 4, str);
    StrUID = str;
  }
  mfrc522.PICC_HaltA();
  return 1;
}
// --------------------------------------------------------------------
void array_to_string(byte array[], unsigned int len, char buffer[])
{
  for (unsigned int i = 0; i < len; i++)
  {
    byte nib1 = (array[i] >> 4) & 0x0F;
    byte nib2 = (array[i] >> 0) & 0x0F;
    buffer[i * 2 + 0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
    buffer[i * 2 + 1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
  }
  buffer[len * 2] = '\0';
}
 

alarmko

Paylaşımcı üye
Katılım
14 Ocak 2009
Mesajlar
903
Puanları
106
Yaş
57
uzun zamandır ugraşmıyorum ancak kendi projemde şöyle birşey yapmışım,belki işinize yarar:

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Try
If TCPCient.Connected = True Then

Else
PictureBox1.Image = My.Resources.false0
BAGLAN.Text = "BAGLAN"
Timer1.Enabled = False
ON1.Enabled = False
ON2.Enabled = False
ON3.Enabled = False
ON4.Enabled = False
OFF1.Enabled = False
OFF2.Enabled = False
OFF3.Enabled = False
OFF4.Enabled = False
BOLGEAD.Enabled = False
CIHAZ1AD.Enabled = False
CIHAZ2AD.Enabled = False
CIHAZ3AD.Enabled = False
CIHAZ4AD.Enabled = False
ILERI.Enabled = False
GERI.Enabled = False
lamba1.Visible = False
lamba2.Visible = False
lamba3.Visible = False
lamba4.Visible = False

SIFREDEGISTIRMEToolStripMenuItem.Enabled = False
GECMISToolStripMenuItem.Enabled = False
SIFRE_TXTBOX.Visible = True
CIHAZID.Visible = False
End If

If TCPClientStream.DataAvailable = True Then
Dim rcvbytes(TCPCient.ReceiveBufferSize) As Byte
TCPClientStream.Read(rcvbytes, 0, (Int(TCPCient.ReceiveBufferSize)))
TextBox3.Text = System.Text.Encoding.Default.GetString(rcvbytes)
ON1.Enabled = True
ON2.Enabled = True
ON3.Enabled = True
ON4.Enabled = True
OFF1.Enabled = True
OFF2.Enabled = True
OFF3.Enabled = True
OFF4.Enabled = True
BOLGEAD.Enabled = True
CIHAZ1AD.Enabled = True
CIHAZ2AD.Enabled = True
CIHAZ3AD.Enabled = True
CIHAZ4AD.Enabled = True
ILERI.Enabled = True
GERI.Enabled = True
lamba1.Visible = True
lamba2.Visible = True
lamba3.Visible = True
lamba4.Visible = True
SIFREDEGISTIRMEToolStripMenuItem.Enabled = True
GECMISToolStripMenuItem.Enabled = True
SIFRE_TXTBOX.Visible = False
CIHAZID.Visible = True
'Timer2.Enabled = False
'Timer2.Enabled = True
PictureBox1.Image = My.Resources.true1
BAGLAN.Text = "BAGLANTIYI KES"
End If

Catch ex As Exception

End Try
End Sub
burada My.Resources.true1 ve My.Resources.false0 resimleri baglantı kuruldu ve baglantı kesildi resimleri.
Yapılan işlem belli aralıklarla(timer 250 ms) baglantının olup olmadıgının sürekli olarak kontrolü.
 

Forum istatistikleri

Konular
122,961
Mesajlar
868,191
Kullanıcılar
440,386
Son üye
moskowitz

Yeni konular

Üst