arduino ethernet class etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

In this example we will try to explain how to make a connection between arduino and c# program by using socket programming.

First of all we can inspect standart ethernet class of arduino library.

#include <SPI.h>
#include <Ethernet.h>


byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177); // ip adresi ayarlanmış


EthernetServer server(80);//port 80 olarak ayarlanmış

void setup() {

  Serial.begin(9600);



//ethernet bağlantısı kuruluyor
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}


void loop() {

  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
//hatta yeni bir client var ise seri ekrana client yazılıyor
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
//hattımızda client olduğu sürece hattımızı dinliyoruz
        Serial.write(c);
        if (c == '\n' && currentLineIsBlank) {
         //eğerki cleint tarafından '\n' bilgisi gelirse standart bir html dosyasını yansıtıyoruz
          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");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");    
          }
          client.println("</html>");
          break;
        }
        if (c == '\n') {
     
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
       
          currentLineIsBlank = false;
        }
      }
    }
 
    delay(1);

    client.stop();
    Serial.println("client disconnected");
  }
}

Below we jusy arranged the standart program by our desires.

#include <SPI.h>
#include <Ethernet.h>


byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177); // ip adresi ayarlanmış


EthernetServer server(80);//port 80 olarak ayarlanmış

void setup() {

  Serial.begin(9600);
  


//ethernet bağlantısı kuruluyor
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}


void loop() {

  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
//hatta yeni bir client var ise seri ekrana client yazılıyor
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
      

          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");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");       
          }
          client.println("</html>");
          break;
        }
      
      }
    }
   
    delay(1);

    client.stop();
    Serial.println("client disconnected");
  }
}

We just want to listen the client and give some responses from the server.
Now we can make some changes the code above

  if (client.available()) {
      

          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");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
             client.println("<br />");       
            client.print(sensorReading);
            client.println("<br />");       
          }
          client.println("</html>");
          break;
        }
This pictures shows server output





Now have can we take these datas to our c#programm

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using asiz;
using System.Net;//html okumak için kullanacağımız kütüphaneler
using System.Net.Sockets;//html okumak için kullanacağımız kütüphaneler
using System.Threading;//multi threading yapacağız sürekli okumada program görsellerim donmasın
using MySql.Data.MySqlClient;
using System.Timers;



namespace asiz
{



    public partial class MainWindow : Window
    {

        Thread t;//yeni bir thread tanımlıyorum
        public MainWindow()
        {
            this.InitializeComponent();
       
         
            try
            {


                t = new Thread(new ThreadStart(okumayabasla));//tanımladığım threade okumayabasla fonksiyonumu ekliyorum
                t.Start();//thread imi başlatıyorum
         
             

            }
            catch (Exception)
            {

                MessageBox.Show("Server ile baglanti kurulurken hata olustu !");
//ethernet bağlantım yok ise uyarı alıyorum
            }
        }
     
   
     static int[5]analog;

   
   
        public void okumayabasla()
        {


            WebClient client = new WebClient();//yeni bir web client oluşturuyorum.Html kodlarını alacağım
            string oku;//oku adında bir değişken ile html kaynağını okuyacağım


            try//bağlantı kurup okumaya başlayacağım
            {
                while (true)//okuma işlemini sürekli yapacağım
                {


                    StreamWriter writer = new StreamWriter("modul.txt");//modul.txt adı altında html kaynağını bilgisayarıma kayıt altına alacağım

                    String htmlCode = client.DownloadString("http://192.168.1.177");//arduinoya bağlanıyorum ve html kodlarını alıyorum

                    writer.Write(htmlCode);//modul.txt dosyasına kayıt ediyorum
                    writer.Close();//kayıt tamam
                    StreamReader ok = new StreamReader("modul.txt");//modul.txt dosyasını okumak için açıyorum


                    while (ok.ReadLine() != "</html>")//html dosyasının sonuna geldim mi gelmedim mi kontrol ediyorum.
                    {
                        oku = ok.ReadLine();//satır satır okuma işlemine devam ediyorum
                        if (oku == "analog input 0")  //analog input 0 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                       
                            label1.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[0]= int.Parse(oku);
                   
                        }
                          if (oku == "analog input 1")  //analog input 1 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label2.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[1]= int.Parse(oku);
                     
                        }
                          if (oku == "analog input 2")  //analog input 2 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label3.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[2]= int.Parse(oku);
                     
                        }
                          if (oku == "analog input 3")  //analog input 3 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label4.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[3]= int.Parse(oku);
                     
                        }
                          if (oku == "analog input 4")  //analog input 4 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label5.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[4]= int.Parse(oku);
                     
                        }
                          if (oku == "analog input 5")  //analog input 5 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label6.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[5]= int.Parse(oku);
                     
                        }

                     
                    }
                    ok.Close();//okuma bufferını kapatıyorum
                }
            }
            catch
            {
               //sistemde okuyamadığınızda ekrana buradan hata yazdırabilirsiniz
            }
        }
        private void MainWindow1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Environment.Exit(1);//kapat butonuna basılında sistemi komple kapat
            t.Abort();//açtığım thread i öldür


        }

   


    }
}
This example just made with microsoft expression blend if you are using visual studio some program structure may be differ from here.

Another importan point is that is this is bidirectional structure means you can only take some datas from arduino and if you want to send some data then you need to make c#as server and arduino as client and make a tcp connection then send your bytes to arduino

Author: Caner ÇAKAR

Merhabalar,
Daha önce arduino ile ethernet class chat server özelliğinden basetmiştik.Bu konumuzda ise arduinonun ethernet örnek kütüphanesindeki webserver özelliğini kullanarak arduinodan gelen değerleri c# ile nasıl okuyacağımızdan bahsedeceğim.

İlk olarak isterseniz arduinonun bize örnek olarak sunduğu webserver programını inceleyelim



#include <SPI.h>
#include <Ethernet.h>


byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177); // ip adresi ayarlanmış


EthernetServer server(80);//port 80 olarak ayarlanmış

void setup() {

  Serial.begin(9600);



//ethernet bağlantısı kuruluyor
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}


void loop() {

  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
//hatta yeni bir client var ise seri ekrana client yazılıyor
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
//hattımızda client olduğu sürece hattımızı dinliyoruz
        Serial.write(c);
        if (c == '\n' && currentLineIsBlank) {
         //eğerki cleint tarafından '\n' bilgisi gelirse standart bir html dosyasını yansıtıyoruz
          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");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");    
          }
          client.println("</html>");
          break;
        }
        if (c == '\n') {
     
          currentLineIsBlank = true;
        }
        else if (c != '\r') {
       
          currentLineIsBlank = false;
        }
      }
    }
 
    delay(1);

    client.stop();
    Serial.println("client disconnected");
  }
}

Şimdi programı kendimize göre düzenleyelim

#include <SPI.h>
#include <Ethernet.h>


byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1,177); // ip adresi ayarlanmış


EthernetServer server(80);//port 80 olarak ayarlanmış

void setup() {

  Serial.begin(9600);
  


//ethernet bağlantısı kuruluyor
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}


void loop() {

  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
//hatta yeni bir client var ise seri ekrana client yazılıyor
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
      

          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");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("<br />");       
          }
          client.println("</html>");
          break;
        }
      
      }
    }
   
    delay(1);

    client.stop();
    Serial.println("client disconnected");
  }
}

Bizim programımız client tarafından bilgi göndermeyeceğinden client tan gelen mesajları görmezden geliyoruz.Biz c# tarafından sadece server ı dinlemek ve ondan gelen verileri almak istiyoruz.

Yukarıdaki kodda yer alan

  if (client.available()) {
      

          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");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("<html>");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
             client.println("<br />");       
            client.print(sensorReading);
            client.println("<br />");       
          }
          client.println("</html>");
          break;
        }
Aşağıdaki resim arduino ide nın standart html çıktısı



Bizim çıkmtımız ise

analog input 0
275
analog input 1
252
.
.
analog input 5
137
şeklinde olacak


Şimdi gelelim biz bu resimdeki çıktıyı nasıl c# tarafında alırız sorusuna 

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using asiz;
using System.Net;//html okumak için kullanacağımız kütüphaneler
using System.Net.Sockets;//html okumak için kullanacağımız kütüphaneler
using System.Threading;//multi threading yapacağız sürekli okumada program görsellerim donmasın
using MySql.Data.MySqlClient;
using System.Timers;



namespace asiz
{



    public partial class MainWindow : Window
    {

        Thread t;//yeni bir thread tanımlıyorum
        public MainWindow()
        {
            this.InitializeComponent();
       
         
            try
            {


                t = new Thread(new ThreadStart(okumayabasla));//tanımladığım threade okumayabasla fonksiyonumu ekliyorum
                t.Start();//thread imi başlatıyorum
         
             

            }
            catch (Exception)
            {

                MessageBox.Show("Server ile baglanti kurulurken hata olustu !");
//ethernet bağlantım yok ise uyarı alıyorum
            }
        }
     
   
     static int[5]analog;

   
   
        public void okumayabasla()
        {


            WebClient client = new WebClient();//yeni bir web client oluşturuyorum.Html kodlarını alacağım
            string oku;//oku adında bir değişken ile html kaynağını okuyacağım


            try//bağlantı kurup okumaya başlayacağım
            {
                while (true)//okuma işlemini sürekli yapacağım
                {


                    StreamWriter writer = new StreamWriter("modul.txt");//modul.txt adı altında html kaynağını bilgisayarıma kayıt altına alacağım

                    String htmlCode = client.DownloadString("http://192.168.1.177");//arduinoya bağlanıyorum ve html kodlarını alıyorum

                    writer.Write(htmlCode);//modul.txt dosyasına kayıt ediyorum
                    writer.Close();//kayıt tamam
                    StreamReader ok = new StreamReader("modul.txt");//modul.txt dosyasını okumak için açıyorum


                    while (ok.ReadLine() != "</html>")//html dosyasının sonuna geldim mi gelmedim mi kontrol ediyorum.
                    {
                        oku = ok.ReadLine();//satır satır okuma işlemine devam ediyorum
                        if (oku == "analog input 0")  //analog input 0 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                       
                            label1.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[0]= int.Parse(oku);
                   
                        }
                          if (oku == "analog input 1")  //analog input 1 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label2.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[1]= int.Parse(oku);
                     
                        }
                          if (oku == "analog input 2")  //analog input 2 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label3.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[2]= int.Parse(oku);
                     
                        }
                          if (oku == "analog input 3")  //analog input 3 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label4.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[3]= int.Parse(oku);
                     
                        }
                          if (oku == "analog input 4")  //analog input 4 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label5.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[4]= int.Parse(oku);
                     
                        }
                          if (oku == "analog input 5")  //analog input 5 olan satırı yakaldım mı ?
                        {
                            oku = ok.ReadLine();//bir alt satırını oku
                         
                            label6.Dispatcher.Invoke(new Action(() => oda_sic.Content = oku));
                            analog[5]= int.Parse(oku);
                     
                        }

                     
                    }
                    ok.Close();//okuma bufferını kapatıyorum
                }
            }
            catch
            {
               //sistemde okuyamadığınızda ekrana buradan hata yazdırabilirsiniz
            }
        }
        private void MainWindow1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Environment.Exit(1);//kapat butonuna basılında sistemi komple kapat
            t.Abort();//açtığım thread i öldür


        }

   


    }
}

Yukarıda bahsettiğimiz örnek benim her zaman kullandığım expression blend 4 ile oluşturulmuştur.Microsoft visual studio ile oluşturacağınız projede sadece label lara değer yazma kısmı değişecektir.

Belirtmemiz gereken diğer bir husus bu sistemle sadece arduinodan değer okuyabilirsiniz.Veri gönderimi için yine arduino ile c# programı arasında tcp socket açmanız ve 2 yönlü haberleşmeniz gerekmektedir.

Yazar: Caner ÇAKAR

ELEKTRO BLOGGER A HOŞGELDINIZ

ARAMA YAP

EN COK OKUNANLAR

- Copyright © ELEKTRO-BLOGGER Blogger