Я хочу общаться с arduino, используя UDP через единство 3D. Я нашел сценарий онлайн, и моя задача - прочитать команду из единицы и активировать светодиод или какой-либо другой компонент через arduino.Arduino Связь с единством с использованием C# через UDP-скрипты
У меня есть этот скрипт, но я не знаю, почему он не работает. Я новичок в 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? IP-адрес '172.16.28.255' кажется подозрительным, это широковещательный адрес? Какое оборудование находится на Arduino, чтобы иметь доступ к сети, какой IP-адрес имеет Arduino? –
да, он транслируется, и с arduino я использую ethernet-щит, и это ip 172.16.28.118 –
Затем подключите свой Arduino к компьютеру через USB и начните отлаживать прошивку (также, ** после прошивки **). Посмотрите, действительно ли он получает какие-либо данные и что он пытается отправить. И точная процедура, что вы делаете, и то, что клиенты Unity отправляют через UDP. Здесь много факторов и неизвестных, без которых на ваш вопрос нельзя ответить. –