我目前正在开发一个项目,我正在创建的游戏需要通过一个按钮连接到两辆RC车(一辆是Arduino RC车,另一辆是Raspberry Pi RC车)。
我需要P1按钮连接到Arduino RC Car和P2按钮以通过WiFi连接到Raspberry Pi RC Car并将红色框更改为绿色,但我在互联网上找到的代码不起作用。
我想知道是否有人能够帮助我并看一看,因为正如我之前所说,我的经验非常有限,我无法弄清楚以下代码是否有错 -
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
答案 0 :(得分:0)
根据我们在这里提供的信息,我会说你首先需要一个覆盆子pi的IP地址。您需要在引号之间填写:“插入路由器的公共IP或Arduino的本地IP” 你也没有在这里展示任何东西。在Update()方法中尝试Debug.Log()值“receivedData”。
按钮现在做什么?我猜你想让他们写一个socket(“forward(P1)”)或类似的东西,所以你可以在raspberry上读取它并驱动一些GPIO引脚。
Arduino无法连接到开箱即用的互联网。有一些解决方案,但几kb的内存不会让你走得很远。