繁体   English   中英

Arduino通过C#通过UDP脚本统一通信

[英]Arduino Communication with unity using C# through UDP scripting

我想通过统一3D使用UDP与arduino进行通信。 我在网上找到了一个脚本,我的任务是统一读取命令并通过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);

    }
}

谢谢

我曾经不得不做类似的事情,将树莓派Web服务连接到一个统一游戏,虽然它不是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

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM