Connection Arduino to Unity

Hi friends, I’ve been trying to connect my Arduino Nano 33 IoT to Unity over wifi. I’ve found a few other topics talking about similar issues, but none with my specific board and none with conclusive solutions that worked for me.

I’m using the following piece of code to set up a wifi server with the Arduino and if I connect to the IP address with Chrome I can read the sensor value I need. I also run another version of this script with Serial to see which IP address I need to connect to and whether a client connects or not.

/*
 WiFi Web Server

 A simple web server that will connect to a WiFi network and serve a webpage.

 The wifiTask will continously attempt to connect when the connection to the WiFi network is lost.
 */

#include <SPI.h>
#include <WiFiNINA.h>

///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "ACT-VR-LAB";
char pass[] = "Saxionxrlab";

WiFiServer server( 80 );
bool wifiActive = false;

int WIFI_LED_PIN =  LED_BUILTIN;

// Application Data

#define NUMBER_OF_RELAYS 20 // (Max 20)
int pin = 4;
int btn = LOW;

int relayArrayState[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // default off
char relcmd[] = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGH";
char *myStringsOn[] =  {"Relay1- On", "Relay2-On", "Relay3- On", "Relay4- On", "Relay5- On", "Relay6- On", "Relay7- On", "Relay8- On", "Relay9- On", "Relay10- On", "Relay11- On", "Relay12- On", "Relay13- On", "Relay14- On", "Relay15- On", "Relay16- On", "Relay17- On", "Relay18- On", "Relay19- On", "Relay20- On"};
char *myStringsOff[] = {"Relay1-Off", "Relay2-Off", "Relay3-Off", "Relay4-Off", "Relay5-Off", "Relay6-Off", "Relay7-Off", "Relay8-Off", "Relay9-Off", "Relay10-Off", "Relay11-Off", "Relay12-Off", "Relay13-Off", "Relay14-Off", "Relay15-Off", "Relay16-Off", "Relay17-Off", "Relay18-Off", "Relay19-Off", "Relay20-Off"};

void setup()
{

  pinMode( WIFI_LED_PIN, OUTPUT );
  pinMode( pin, INPUT_PULLDOWN );

}

void loop()
{
  wifiTask();

  // Run your code here
  // Do not use delay
  


  loopAnalysis();
}

void wifiTask( void )
{
  static int state = 0;
  static int connectTry = 0;
  static int wifiStatus = WL_IDLE_STATUS;
  static unsigned long previousMillis = 0;
  static unsigned long previousMillisClientCheck = 0;
  unsigned long currentMillis = 0;
  static String httpRequest = "";
  static WiFiClient client;
  

#define WIFI_CONNECT_TIMEOUT 10000
#define WIFI_CONNECT_CHECK_INTERVALL 500
#define WIFI_CLIENT_CHECK_INTERVALL 50

  enum WIFI_STATE_TYPE { WIFI_CONNECT,
                         WIFI_START_WEB_SERVER,
                         WIFI_PRINT_STATUS,
                         WIFI_STATUS,
                         WIFI_WAIT_FOR_CLIENT,
                         WIFI_WAIT_FOR_GET,
                         WIFI_SEND_INDEX_HTML,
                         WIFI_PROCESS_GET,
                         WIFI_STATE_RESTART = 255
                       };

  switch ( state )
  {
    case WIFI_CONNECT:
      if ( wifiStatus == WL_CONNECTED )
      {
        state++;
        digitalWrite( WIFI_LED_PIN, HIGH );
        break;
      }
      if ( millis() - previousMillis < WIFI_CONNECT_TIMEOUT && connectTry > 0 )
      {
        // just continue with rest of program for now
        break;
      }
      if ( connectTry > 10 )
      {
        // could not connect, clear everything and try again later
        state = WIFI_STATE_RESTART;
        break;
      }
      wifiStatus = WiFi.begin( ssid, pass );
      previousMillis = millis();
      connectTry++;
      break;
    case WIFI_START_WEB_SERVER:
      server.begin();
      state++;
      break;
    case WIFI_PRINT_STATUS:
      printWiFiStatus();
      state++;
      break;
    case WIFI_STATUS:
      currentMillis = millis();
      if ( currentMillis - previousMillis < WIFI_CONNECT_CHECK_INTERVALL )
      {
        state++;
        break;
      }
      previousMillis = currentMillis;
      if ( WiFi.status() == WL_CONNECTED )
      {
        state++;
      }
      else
      {
        state = WIFI_STATE_RESTART;
      }
      break;
    case WIFI_WAIT_FOR_CLIENT:
      currentMillis = millis();
      if ( currentMillis - previousMillisClientCheck < WIFI_CLIENT_CHECK_INTERVALL )
      {
        state = WIFI_STATUS;
        break;
      }
      previousMillisClientCheck = currentMillis;    
      client = server.available();
      if ( client )
      {
        httpRequest = "";
        state++;
      }
      else
      {
        state = WIFI_STATUS;
      }
      break;
    case WIFI_WAIT_FOR_GET:
      if ( !client.connected() )
      {
        client.stop();
        state = WIFI_WAIT_FOR_CLIENT;
      }
      if ( client.available() )
      {
        printButton(client);
      }
      break;
    case WIFI_SEND_INDEX_HTML:
      sendIndexHtml( client );
      client.stop();
      httpRequest = "";
      state = WIFI_WAIT_FOR_GET;
      break;
    case WIFI_PROCESS_GET:
      if ( httpRequest.startsWith( "GET /" ) )
      {
        int cmd = getCmd( httpRequest );
        setRelays( cmd );
        sendIndexHtml( client );
      }
      client.stop();
      httpRequest = "";
      state = WIFI_WAIT_FOR_GET;
      break;
    default:
      state = 0;
      connectTry = 0;
      wifiStatus = WL_IDLE_STATUS;
      WiFi.disconnect();
      WiFi.end();
      digitalWrite( WIFI_LED_PIN, LOW );
      break;
  }
} // wifiTask

void printButton(WiFiClient client) {

          btn = digitalRead( pin );
          client.print( btn );

}

void printWiFiStatus()
{

}

void sendIndexHtml( WiFiClient client )
{
  client.println( "HTTP/1.1 200 OK" );
  client.println( "Content-type:text/html" );
  client.println();
  client.println( "<style>" );
  client.println( ".button {" );
  client.println( " background-color: #4CAF50;" );

  client.println( " color: white;" );
  client.println( " padding: 15px 32px;" );
  client.println( " text-align: center;" );
  client.println( " text-decoration: none;" );
  client.println( " display: inline-block;" );
  client.println( " font-size: 16px;" );
  client.println( "  margin: 4px 2px;" );

  client.println( "}" );
  client.println( ".button2 {background-color: #008CBA;} /* Blue */" );
  client.println( ".button3 {background-color: #f44336;} /* Red */ " );
  client.println( ".button4 {background-color: #e7e7e7; color: black;} /* Gray */ " );
  client.println( ".button5 {background-color: #555555;} /* Black */" );
  client.println( "</style>" );

  // the content of the HTTP response follows the header:
  client.print( "<html>" );
  client.print( "<body>" );

  client.print( "<h1>Connected</h1>" );
  btn = digitalRead(pin);
  client.print( "<h2>" );
  client.print( btn );
  client.print( "</h2>" );

  client.print( "</body>" );
  client.print( "</html>" );
}

char getRequestChar( String s )
{
  if ( !s.startsWith( "GET /" ) )
  {
    return -1;
  }
  if ( s[6] != ' ' )
  {
    return -1;
  }
  return s[5];
}

int getCmd( String s )
{
  char c = getRequestChar( s );

  String t = relcmd;

  return t.indexOf( c );
}

bool setRelays( int cmd )
{
  if ( cmd < 0 )
  {
    return false;
  }
  if ( cmd % 2 == 0 )
  {
    relayArrayState[ cmd / 2] = 1;
  }
  else
  {
    relayArrayState[ ( cmd - 1 ) / 2 ] = 0;
  }
  return true;
}

void loopAnalysis()
{
  static unsigned long previousMillis = 0;
  static unsigned long lastMillis = 0;
  static unsigned long minLoopTime = 0xFFFFFFFF;
  static unsigned long maxLoopTime = 0;
  static unsigned long loopCounter = 0;

#define INTERVAL 1000

  unsigned long currentMillis = millis();
  if ( currentMillis - previousMillis > INTERVAL )
  {
    previousMillis = currentMillis;
    loopCounter = 0;
    minLoopTime = 0xFFFFFFFF;
    maxLoopTime = 0;
  }
  loopCounter++;
  unsigned long loopTime = currentMillis - lastMillis;
  lastMillis = currentMillis;
  if ( loopTime < minLoopTime )
  {
    minLoopTime = loopTime;
  }
  if ( loopTime > maxLoopTime )
  {
    maxLoopTime = loopTime;
  }
}

But if I try to connect with Unity with the piece of code below, I don’t get anything. The serial monitor does tell me a client connects, but I just don’t het any data in Unity. What am I missing here? I’d love to hear any ideas, please :slight_smile:

What exactly is "Unity" in this context? Is it the Ubuntu Unity desktop? Is it the 3D game engine? Whatever you meant you should describe in more detail how exactly you try to request anything from your Arduino.