如何让Unity中的按钮连接到Arduino遥控车?
问题描述:
我目前正在研究一个项目,在这个项目中,我正在创建的游戏需要通过使用按钮连接到两个遥控车(一个是Arduino RC车,另一个是Raspberry Pi RC车)。如何让Unity中的按钮连接到Arduino遥控车?
我需要P1按钮连接到Arduino遥控车和P2按钮,通过WiFi连接到Raspberry Pi遥控车,并将红色框更改为绿色,但通过Internet找到的代码没有工作。
我想知道是否有人将能够帮我看一看,因为正如我刚才说我的经验非常有限,我无法弄清楚什么是错用下面的代码 -
using UnityEngine; // These are the librarys being used
using System.Collections;
using System;
using System.IO;
using System.Net.Sockets;
public class ClientSocket : MonoBehaviour
{
bool socketReady = false; // global variables are setup here
TcpClient mySocket;
public NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
public String Host = "INSERT the public IP of router or Local IP of Arduino";
public Int32 Port = 5001;
public bool lightStatus;
void Start()
{
setupSocket(); // setup the server connection when the program starts
}
// Update is called once per frame
void Update()
{
while (theStream.DataAvailable)
{ // if new data is recieved from Arduino
string recievedData = readSocket();
}
}
// write it to a string
public void setupSocket()
{ // Socket setup here
try
{
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theWriter = new StreamWriter(theStream);
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e)
{
Debug.Log("Socket error:" + e); // catch any exceptions
}
}
public void writeSocket(string theLine)
{ // function to write data out
if (!socketReady)
return;
String tmpString = theLine;
theWriter.Write(tmpString);
theWriter.Flush();
}
public String readSocket()
{ // function to read data in
if (!socketReady)
return "";
if (theStream.DataAvailable)
return theReader.ReadLine();
return "NoData";
}
public void closeSocket()
{ // function to close the socket
if (!socketReady)
return;
theWriter.Close();
theReader.Close();
mySocket.Close();
socketReady = false;
}
public void maintainConnection()
{ // function to maintain the connection (not sure why! but Im sure it will become a solution to a problem at somestage)
if (!theStream.CanRead)
{
setupSocket();
}
}
} // end class
答
好吧,首先,让我给你时间给我们一个https://stackoverflow.com/help/mcve。 对不起,但你也忘了在你的文章中添加你引用的图片。
鉴于我们在这里的信息,我会说你首先需要一个覆盆子pi的IP地址。您需要在引号之间填写它:“插入路由器的公共IP或Arduino的本地IP” 您也没有在此处显示任何内容。在Update()方法中尝试Debug.Log()值“receivedData”。
按钮现在做什么?我猜你希望他们写writeSocket(“forward(P1)”)或类似的东西,所以你可以在树莓派上读取它,并驱动一些GPIO引脚。
Arduino's无法连接到互联网开箱即用。有一些解决方案,但几KB的内存不会让你走得很远。
你能比“不工作”更具体吗? –
你不能只写一个代码,并说它不起作用。哪部分不起作用?发布Ardiuno代码也是有意义的。给你的一个建议是从简单的字符串发送到Arduino,从小处着手。一旦完成,您可以继续并继续编写更长的代码。 – Programmer
您是否肯定您使用TCP而不是UDP与车辆进行通信? – Logman