Arduino使用C#通过UDP脚本进行统一通信

时间:2016-11-07 09:41:47

标签: c# unity3d arduino udp

我想通过统一3D使用UDP与arduino进行通信。我在网上找到了一个脚本,我的任务是从unity读取命令并通过arduino激活LED或其他组件。

我有这个脚本,但我不知道为什么它不起作用。我是C#的新手,所以请帮助我。

剧本

//UDP-Send
//-----------------------
// [url]http://msdn.microsoft.com/de-de/library/bb979228.aspx#ID0E3BAC[/url]

// > gesendetes unter
// 127.0.0.1 : 8050 empfangen

// nc -lu 127.0.0.1 8050
//*/
using UnityEngine;
using System.Collections;

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

public class UDPsend : MonoBehaviour
{   
    private static int localPort;

    // prefs
    private string IP;  // define in init
    public int port;  // define in init

    // "connection" things
    IPEndPoint remoteEndPoint;
    UdpClient client;

    // gui
    //string strMessage="";

    // call it from shell (as program)
    private static void Main()
    {
        UDPsend sendObj=new UDPsend();
        sendObj.init();

        // testing via console
        // sendObj.inputFromConsole();

        // as server sending endless
        sendObj.sendEndless(" endless infos \n");

    }
    // start from unity3d
    public void Start()
    {
        init();
    }

    // OnGUI
    void OnGUI()
    {
        Rect rectObj=new Rect(40,380,200,400);
        GUIStyle style = new GUIStyle();
        style.alignment = TextAnchor.UpperLeft;
        GUI.Box(rectObj,"# UDPSend-Data\n172.16.28.255 "+port+" #\n"
            + "shell> nc -lu 172.16.28.255  "+port+" \n"
            ,style);

        // ------------------------
        // send it
        // ------------------------
        strMessage=GUI.TextField(new Rect(40,420,140,20),strMessage);
        if (GUI.Button(new Rect(190,420,40,20),"send"))
        {
            sendString(strMessage+"\n");
        }      
    } 

    // init
    public void init()
    {
        //Define endpoint
        print("UDPSend.init()");

        // define
        //IP="127.0.0.1";
        IP = "172.16.28.255";
        port=8888;

        // ----------------------------
        // Send
        // ----------------------------
        remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port);
        client = new UdpClient();

        // status
        print("Sending to "+IP+" : "+port);
        print("Testing: nc -lu "+IP+" : "+port);

    }

    // inputFromConsole
    private void inputFromConsole()
    {
        try
        {
            string text;
            do
            {
                text = Console.ReadLine();

                // Den Text zum Remote-Client senden.
                if (text != "")
                {
                    //UTF8 coding
                    byte[] data = Encoding.UTF8.GetBytes(text);

                    //send data to client
                    client.Send(data, data.Length, remoteEndPoint);
                }
            } while (text != "");
        }
        catch (Exception err)
        {
            print(err.ToString());
        }
    }

    // sendData
    private void sendString(string message)
    {
        try
        {
            //if (message != "")
            //{
            //UTF8 coding
            byte[] data = Encoding.UTF8.GetBytes(message);

            //send data
            client.Send(data, data.Length, remoteEndPoint);
            sendString(strMessage+"\n");
            //}
        }
        catch (Exception err)
        {
            print(err.ToString());
        }
    }

    // endless test
    private void sendEndless(string testStr)
    {
        do
        {
            sendString(testStr);
        }
        while(true);

    }
}

谢谢

1 个答案:

答案 0 :(得分:0)

我曾经不得不做类似的事情,我将覆盆子pi网络服务连接到统一游戏,但它不是UDP,但如果数据包足够小,http可以非常快。

using UnityEngine;
using System.Collections;

public class playercontroller : MonoBehaviour {

public string url; //FIXME hardcoded URL
public string coordinates = "{0,0}";
private string previouscoordinates = "{0,0}";
public WWW mycoord;
private bool previouslyDone = true;

void FixedUpdate() {
    if (previouslyDone) {
        previouslyDone = false;
        Debug.Log("sending HTTP request! to:");
        Debug.Log(url);
        mycoord = new WWW(url);
    } else if (mycoord.isDone) {
        Debug.Log("Got response!"); 
        if(mycoord.text.Length > 4) {
            coordinates = mycoord.text;
        }
        Debug.Log(coordinates);
        previouslyDone = true;
    }
    if (previouscoordinates != coordinates) {
        string x = "";
        string y = "";
        int index = 1;
        char nextchar = '0';
        while (nextchar != ',') {
            x += coordinates [index];
            index++;
            nextchar = coordinates [index];
        }
        index++;
        while (nextchar != '}') {
            y += coordinates [index];
            index++;
            nextchar = coordinates [index];
        }
        float newX = 0 + (float.Parse (x) * 2);
        float newZ = 0 - (float.Parse (y) * 2);
        transform.position = new Vector3 (newX, 1.5f, newZ);
        previouscoordinates = coordinates;
    } else {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");
        Vector3 movement = new Vector3 (moveHorizontal / 10, 0.0f, moveVertical / 10);
        transform.position = transform.position + movement;
    }

您正在寻找的部分是:

    mycoord = new WWW(url);

这会启动一个异步的http请求,因为每次都调用它,我等待

    mycoord.isDone 

之前我可以获取数据(mycoord.text,这是一个字符串)

所以基本上你创建了一个请求(WWW myrequest()); 等待它完成(myrequest.isDone),然后获取结果(myrequest.text)。

对于arduino方只需使用: https://www.arduino.cc/en/Tutorial/WebServer

希望这会有所帮助。