首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过UDP脚本使用C#实现Arduino与unity的通信

通过UDP脚本使用C#实现Arduino与unity的通信
EN

Stack Overflow用户
提问于 2016-11-07 17:41:47
回答 1查看 899关注 0票数 0

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

我有这个脚本,但我不知道为什么它不能工作。我是新来C#的,所以请帮帮我。

脚本

代码语言:javascript
复制
//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);

    }
}

谢谢

EN

回答 1

Stack Overflow用户

发布于 2016-11-07 23:59:44

我曾经不得不做一些类似的事情,我将一个覆盆子pi web服务连接到一个unity游戏,虽然它不是UDP,但如果数据包足够小,http可以相当快。

代码语言:javascript
复制
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;
    }

你要找的部分是:

代码语言:javascript
复制
    mycoord = new WWW(url);

这会启动一个异步http-request,因为它是每一帧都被调用的,所以我等待

代码语言:javascript
复制
    mycoord.isDone 

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

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

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

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40462008

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档