Go Down

Topic: C# receive data continuously from Arduino WI-FI (Read 1 time) previous topic - next topic

chris01928

I have a C# program to receive data from Arduino sensors (gps, roll, pitch...). Everything is working fine when using serial connection (COM/USB). I connected a WIFI module to the Arduino and send/receive using socket. Can I know how to continuous read/receive the data through wifi from the Arduino? (I know the sending part but don't know the receiving part). I need help for translating the receiving part(serialport) to WIFI NetworkStream.

This is part of my C# winform code

    int HostPort = 4998;
    string Host = "192.168.0.2";
    System.Net.Sockets.TcpClient tcpClient = new  System.Net.Sockets.TcpClient();
    private void button2_Click(object sender, EventArgs e) {
      byte[] M1bytesToSend = new byte[1] { 0xFF };
      NetworkStream networkStream = tcpClient.GetStream();
      networkStream.Write(M1bytesToSend, 0, M1bytesToSend.Length);
    }
    private void Form1_Load(object sender, EventArgs e) {
      tcpClient.Connect(Host, HostPort);
    }

The receive part C# for serialport1:

    private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e) {
      Thread.Sleep(50);
      int bytes = serialPort1.BytesToRead;
      string data = serialPort1.ReadExisting();
      Char delimiter = '*';
      String[] substrings = data.Split(delimiter);
      if ((bytesRx > 25) & (bytesRx < 40)) {
        //receive 2nd part Arduino code and do something
      }
      if ((bytesRx > 15) & (bytesRx < 25)) {
        //receive 1st part arduino code and do something
      }
    }

This is my Arduino code that will continuously send data to Winform.

    Serial.print("*"); // 1st part
    ypr[1]=(ypr[1] * 180/M_PI)+90;
    Serial.print(ypr[1]);
    Serial.print("*");
    ypr[2]=(ypr[2] * 180/M_PI)+90;
    Serial.print(ypr[2]);
    Serial.print("*");
    Serial.print(ypr[0] * 180/M_PI);//yaw
    Serial.print("*");
    delay(50);
    Serial.print("*"); //second part
    Serial.print(headingDegrees);
    Serial.print("*");
    Serial.print(b,6);
    Serial.print("*");
    Serial.print(c,6);
    Serial.print("*");

horace

are you planning to use TCP or UDP communicaion? 
have a look at the following for some examples of C# servers and clients
http://csharp.net-informations.com/communications/csharp-socket-programming.htm

on the Arduino have a look under File > Examples > WiFi you will find examples code for servers and clients

chris01928

I'm using TCP Socket connection. I tried to look at example online but doesnt have the method i want. I would like to receive data continuously from Arduino.

horace

below is a simple example of an Arduino using Ethernet to communicate with a TCP server
you need to set up the server and client IP addresses and the server port
Code: [Select]
// conect to server, send message and display response
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 177 };
byte server[] = { 192, 168, 1, 65 }; // Google
int serverPort=10000;
EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(115200);
  delay(1000);
  Serial.println("connecting...");
  // Ethernet ready, connect to server and transmit data
  if (client.connect(server, serverPort)) {
    Serial.println("connected");
    // transmit data
    client.println("Test TCP server - data from Arduino");
    client.println("end of data");
  } else {
    Serial.println("connection failed");
  }
}

// display response from server
void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

a java program which acts as the server
Code: [Select]
// server which waits for messages from a client and echos then back
import java.io.*;
import java.util.*;
import java.net.*;


public class TCPechoServer extends Thread
{
        private ServerSocket   serverSocket;
        InputStream br=null;
        DataOutputStream pw=null;
        int receivePort;                // port to receive  from
        boolean threadRunning = true;   // flag to terminate thread

        TCPechoServer(int receivePort)    // constructor to receive datagrams on port receivePort
    {
                this.receivePort = receivePort;
    }

        // terminate the thread by setting flag
        public void stopTCPserver()
        {
                threadRunning = false;
        }
 

        public void run()                // thread run method, receives and buffers datagrams
        {
          Socket socket=null;
          int frame=0;
          try
              {
              while (threadRunning)
              {
                  System.out.println("TCP  server starting: IP address "
                       + InetAddress.getLocalHost().toString() + " port " + receivePort );
                  serverSocket = new ServerSocket(receivePort);
                  socket = serverSocket.accept(); // Wait for client to connect.
                  System.out.println("Client connect from IP address " + socket.getInetAddress()
                                  + " port " + socket.getPort());
                  br  = ( ( socket.getInputStream() ) );
                  pw = new DataOutputStream( socket.getOutputStream() );
                  while(threadRunning)
                    try
                    {
                      byte data[]=new byte[10000];
                      int length = br.read(data);
                      System.out.println( "\nServer received packet length:" + length + " bytes" );
                      for(int i=0;i<20;i++)
                        System.out.print(" " + data[i]);
                      String text = new String(data, "UTF-8");
                      System.out.println("\n" + text);
                      pw.write(data, 0, length);
                      pw.flush();
                     }
                    catch (Exception se) {System.err.println("done"); break;}
                  serverSocket.close();
                }
              }
          catch (Exception se) {System.err.println("run() " + se); }
     
          System.exit(1);                                                 // exit on failure
        }


public static void main(String args[])
{
        int receivePort=10000;//999;//20000;                                 // port to receive datagrams on
        TCPechoServer frameInput = new TCPechoServer(receivePort);    // create server to receive messages
        frameInput.start();                                   // and start it
        System.out.println("ready to receive from socket " + receivePort);
        }

}

the Arduino serial monitor displays
Code: [Select]
connecting...
connected
Test TCP server - data from Arduino
end of data

and the java console displays
Code: [Select]
ready to receive from socket 10000
TCP  server starting: IP address DESKTOP-OB6C5CA/192.168.1.65 port 10000
Client connect from IP address /192.168.1.177 port 49153

Server received packet length:37 bytes
 84 101 115 116 32 84 67 80 32 115 101 114 118 101 114 32 45 32 100 97
Test TCP server - data from Arduino

similar code for WiFi should work - what WiFi boards are you using?

PaulS

Quote
I would like to receive data continuously from Arduino.
That statement is nonsense, when you explicitly code the serial read function to sleep.
The art of getting good answers lies in asking good questions.

horace

#5
Oct 23, 2017, 07:45 pm Last Edit: Oct 23, 2017, 07:45 pm by horace
not sure what continuously from Arduino means but this example is transmiting data in a loop from an Arduino to a server in C# which echos it back
Code: [Select]
// conect to server, send message and display response
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 177 };
byte server[] = { 192, 168, 1, 65 }; // Google
int serverPort=10000;
EthernetClient client;

void setup()
{
  Ethernet.begin(mac, ip);
  Serial.begin(115200);
  delay(1000);
  Serial.println("connecting...");
  // Ethernet ready, connect to server and transmit data
  if (client.connect(server, serverPort))
   for(int i=0; i< 5; i++){
    Serial.println("connected");
    // transmit data
    client.print("Test TCP server - data from Arduino ");
    client.println(i);
    delay(500);
  } else {
    Serial.println("connection failed");
  }
}

// display response from server
void loop()
{
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;)
      ;
  }
}

to a server in C#
Code: [Select]
// C# TCP server receives data and echos it back to client

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SynchronousTCPserver
{


public class SynchronousSocketListener {
   
    public static void StartListening() {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the
        // host running the application.
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 10000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp );

        // Bind the socket to the local endpoint and  listen for incoming connections.
        try {
            listener.Bind(localEndPoint);
            listener.Listen(10);
            while (true) {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                Console.WriteLine("Client connected");
                // An incoming connection needs to be processed.
                while (true)
                    if (handler.Available > 0){
                        //Console.WriteLine("available " + handler.Available);
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes, 0, handler.Available, SocketFlags.None);
                        String data = Encoding.ASCII.GetString(bytes,0,bytesRec);
                        // Show the data on the console.
                        Console.WriteLine("Data received : {0}", data);
                        // echo data back to client
                        handler.Send(bytes, 0, bytesRec, SocketFlags.None);
                        // if data received was <EOF> terminate connection
                        if (data.IndexOf("<EOF>") >= 0)  break;
                    }
                Thread.Sleep(5000);
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
           
        } catch (Exception e) {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();
       
    }

    public static int Main(String[] args) {
        StartListening();
        return 0;
    }
}
}

the Arduino displays
Code: [Select]

connecting...
connected
connected
connected
connected
connected
Test TCP server - data from Arduino 0
Test TCP server - data from Arduino 1
Test TCP server - data from Arduino 2
Test TCP server - data from Arduino 3
Test TCP server - data from Arduino 4


the C# server displays
Code: [Select]
Waiting for a connection...
Client connected
Data received : Test TCP server - data from Arduino
Data received : 0

Data received : Test TCP server - data from Arduino
Data received : 1
Data received :

Data received : Test TCP server - data from Arduino
Data received : 2
Data received :

Data received : Test TCP server - data from Arduino
Data received : 3

Data received : Test TCP server - data from Arduino
Data received : 4
Data received :

Go Up