- Home /
Unity with Arduino+WiFly
Hello everyone, I have an Arduino with a WiFly module hooked to it. All it does is create a Wireless Access Point with an ip address (169.254.1.21) that talks on port 2000. Here I have the code to connect to it and listen to the socket from Unity
using UnityEngine;
using System.Collections;
using System;
using System.IO;
using System.Net.Sockets;
//using System.Globalization.NumberStyles;
public class wifly : MonoBehaviour
{
public string tekst;
internal Boolean socketReady = false;
TcpClient mySocket;
NetworkStream theStream;
StreamWriter theWriter;
StreamReader theReader;
String Host = "169.254.1.21";
Int32 Port = 2000;
void Update()
{
string receivedText = readSocket();
if (receivedText != "")
{
tekst=receivedText;
print(tekst);
}
}
void OnGUI()
{
if (!socketReady)
{
if (GUILayout.Button("Connect"))
{
setupSocket();
}
}
if (socketReady)
{
//print (tekst);
}
}
void OnApplicationQuit()
{
closeSocket();
}
public void setupSocket()
{
try
{
mySocket = new TcpClient(Host, Port);
theStream = mySocket.GetStream();
theReader = new StreamReader(theStream);
socketReady = true;
}
catch (Exception e)
{
Debug.Log("Socket error: " + e);
}
}
public String readSocket()
{
if (!socketReady)
return "";
if (theStream.DataAvailable)
return theReader.ReadLine();
return "";
}
public void closeSocket()
{
if (!socketReady)
return;
theReader.Close();
mySocket.Close();
socketReady = false;
}
}
I have a strange problem with it though, sometimes it works, sometimes it doesn't. The Arduino sends a message every second and I'm showing it in the console in Unity. When I play the scene it gives me an error that it could not connect to the host address. Although, I observed that it works in one case, if I first connect to the wifi point it created, then use telnet to: "telnet 169.254.1.21 2000", and after that start the unity scene, it works like a charm, as soon as I exit the telnet command prompt it loses the connection and doesn't receive any messages. Could someone explain to me how I can resolve this issue? Thanks.