Arduino通过UDP脚本与unity使用c#进行通信

本文关键字:通信 使用 unity 通过 UDP 脚本 Arduino | 更新日期: 2023-09-27 18:16:34

我想通过unity 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);
    }
}

谢谢

Arduino通过UDP脚本与unity使用c#进行通信

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