GithubHelp home page GithubHelp logo

ardity's Introduction

Ardity: Arduino + Unity

Arduino + Unity communication made easy

And not just Arduino: any hardware/software that communicates over serial (COM) ports !

WebSite URL: https://ardity.dwilches.com

(Previously known as: SerialCommUnity)

Instructions

There are three scenes that show how to read/write data from/to a serial device. There is a prefab that you need to add to your scene, this prefab will do all the thread management, queue synchronization and exception handling for you.

If you need a program to test your Unity scene I have created the following Arduino program that sends a heartbeat message each 2 seconds. It also recognizes two input messages and reacts to them, this is for bidirectional communication for the scene "DemoSceneUserPoll_ReadWrite". So if you want to use that scene just run it and press the keys 'A' or 'Z' to see what you Arduino has to say about it.

Installation

You can download the code from GitHub (Code > Download ZIP) and after uncompressing, import the assets into your Unity scene.

Alternative installation using Package Manager

  1. Open the Unity Package Manager by navigating to Packages > Package Manager.
  2. Click on Packages in the top left corner and select Add package from git URL....
  3. Paste the following URL into the input field and click Install:
https://github.com/dwilches/Ardity.git?path=UnityProject/Assets/Ardity

Sample Arduino Program

This sample communicates with any of the scenes called: DemoScene_AutoPoll* or DemoScene_UserPoll*.

unsigned long last_time = 0;

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    // Print a heartbeat
    if (millis() > last_time + 2000)
    {
        Serial.println("Arduino is alive!!");
        last_time = millis();
    }

    // Send some message when I receive an 'A' or a 'Z'.
    switch (Serial.read())
    {
        case 'A':
            Serial.println("That's the first letter of the abecedarium.");
            break;
        case 'Z':
            Serial.println("That's the last letter of the abecedarium.");
            break;
    }
}

Sample with Tear-Down function

This sample has a tear-down function (use it with the scene DemoScene_SampleTearDown), it will be executed when the Unity program stops. This sample expects you to be using an Arduino UNO, if not, change the number of the pin to which the LED is connected.

unsigned long last_time = 0;
int ledPin = 13;

void setup()
{
    Serial.begin(9600);
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, LOW);
}

void loop()
{
    // Print a heartbeat
    if (millis() > last_time + 2000)
    {
        Serial.println("Arduino is alive!!");
        last_time = millis();
    }

    // Send some message when I receive an 'A' or a 'Z'.
    switch (Serial.read())
    {
        case '1':
            digitalWrite(ledPin, HIGH);
            Serial.println("Lights are ON");
            break;
        case '2':
            digitalWrite(ledPin, LOW);
            Serial.println("Lights are OFF");
            break;
        
        // Execute tear-down functionality
        case 'X':
            for (int i = 0; i < 10; i++)
            {
                digitalWrite(ledPin, HIGH);
                delay(100);
                digitalWrite(ledPin, LOW);
                delay(100);
            }
            
            // This message won't arrive at Unity, as it is already in the
            // process of closing the port
            Serial.println("Tearing down some work inside Arduino");
            break;
    }
}

Sample with custom delimiter

// This is the separator configured in Unity
#define SEPARATOR 255

unsigned long last_time = 0;
int ledPin = 13;

byte responseMessage[] = { 65, 66, 67, SEPARATOR };
byte aliveMessage[] = { 65, 76, 73, 86, 69, 33, SEPARATOR };

void setup()
{
    Serial.begin(9600);

    aliveMessage[8] = SEPARATOR;
}

void loop()
{
    // Print a heartbeat
    if (millis() > last_time + 2000)
    {
        Serial.write(aliveMessage, sizeof(aliveMessage));
        Serial.flush();
        last_time = millis();
    }
    
    // React to "commands"
    if (Serial.read() == ' ')
    {
        Serial.write(responseMessage, sizeof(responseMessage));
        Serial.flush();
    }
}

Documentation

Ardity is quite simple to use. You can find the setup guide in PDF format here.

There is also a series of in-depth tutorials by the Interface Lab from the University NYU Shanghai, please take a look here:

COM port names

To open a COM port from Ardity you need to use one of these naming conventions:

  • COM1, COM2, ... for COM1 through COM9
  • \\.\COM10, \\.\COM11, ... for COM10 and up

Can Ardity be used with Bluetooth devices?

Yes, it's possible. You need to configure your device to be seen in your operating system as a COM port. Instructions to do so vary from device to device and from OS to OS. Once you have it configured, use that COM port with Ardity, which will treat it as just another serial device.

Common Issues

The type or namespace name 'Ports' does not exist in the namespace 'System.IO'

If you get this error:

Assets/Ardity/Scripts/SerialThread.cs(9,17): error CS0234: The type or namespace name 'Ports' does not exist in the namespace 'System.IO'. Are you missing an assembly reference?

Check the current "API Compatibility Level" of your Unity project. Go to Edit -> Project Settings -> Player, and under Other Settings find an option that reads "Api Compatibility Level" and change it to .NET 4.0 (or .NET 2.0 if you have a version older than Unity 2018).

Also, some users have reported needing to manually add System.IO.dll to the project. If the above solution doesn't work for you, in Visual Studio go to Project -> Add Reference -> Browse and then select the file System.IO.dll from inside your .NET framework's folder. This file may be located at C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\Facades\System.IO.dll.

Communication with some devices doesn't work out of the box

Some users have reported needing to enable RtsEnable and DtsEnable in order to get Ardity to work with their devices. So if communication is not working for you, try enabling these options in AbstractSerialThread just before the serialPort.Open() invocation:

serialPort.DtrEnable = true;
serialPort.RtsEnable = true;

If Ardity works in the Editor but not outside of it

Try changing the scripting backend from Mono to IL2CPP.

License

This work is released under the Creative Commons Attributions license.

If you use this library please let me know, so I know my work has been useful to you :)

CC Attribution

ardity's People

Contributors

dwilches avatar offchan42 avatar tedliou avatar tkousirmorgan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ardity's Issues

Device recognition

As a suggestion an autoscan for the com ports could be very usefull in later updates, I'll try to implement it myself since the board doesn't get the same com port unless you set it in the system settings.

Greetings!!!!

Can ardity be used with Bluetooth modules connected to an Arduino

Modules like HC-05 which would essentially have serial ports for communication. can ardity be used for complete wireless control of a device(mobile robot, arduino powered) from unity? Thank you.
I am doing a project on wireless gesture control of a robot using mixed reality(VR+AR).

Arduino Uno Wifi Rev2 does not connect with Unity

I have a question using Ardity with an Arduino Uno Wifi Rev2. I'm using the sample scenes provided in the package.

I tested Ardity with an Arduino Uno and it works perfectly fine. However, when I use the Uno Wifi Rev2 it does not work.

When I send a character from Unity to the Arduino, the Arduino does receive something (RX blinks). However, the action (in my case put a light on) does not work.

It seems like my Adruino is not able to read the serial message from Unity and it also does not send information to unity.

Does anyone else has experienced this problem? Or is it possible that the Serial Port of the Uno Wifi Rev2 does not open for Unity? The Arduino code works without using Unity.

Hope someone can help!
Regards

Communication between Ardity and non-Arduino MCU?

Hi there, I've been trying to get Ardity to communicate with devices other than my Arduino Uno, but have failed to so far... The Uno works flawlessly, however, for my application, I need to use this MCU: https://www.sparkfun.com/products/15025 (The Sparkfun Pro nRF52840 Mini). This board is supposed to be Arduino-enabled and I can upload the Ardity example code to it. It appears as a normal COM port, and knowing the baud rate, I can connect to it (Ardity confirms that connection is established).
However, the serial messages that the script is supposed to send (separated by using the println() funtion) don't appear on the console, which is surprising. Any idea why it isn't working properly even though connection is successful?
Thank you for your framework and hopefully there's a simple solution!

Increasing the speed of SerialCommUnity

Hi,

Thank you for the serial package, I've been using it. Perhaps a newbie question but there is a substantial lag that is caused by this now running in a separate thread: I measure something like 30-50 milliseconds from the time of enqueue message to then the serialthread noticing data and starting to writeline it out. The lag varies of course since the threads do not run simultaneously.

Is there any way to reduce this lag? Preferrably down to 0 or as close to it as possible, of course.

(This question was copied from a comment by rainisto from Unity Answers)

Change COM Port and reconnect

Hi,
I am using Ardity in an Arduino project. It works great. But sometimes when I connect the USB the Arduino COM port changes. So I have to change the COM form the editor. Is there a way to change the COM from the application itself using code and re-connect?
Thenk you!

Problem reading output from device

My device is based on USB-COM converter by FTDI CHip. Maker of the device (our inhouse electronics guy) assured me, that on command "@rel#1@" device should respond with "@rel#ON@", but nothing comes out of library. When sending "@rel#1@" the device does what it's supposed. How can I know what's the problem? Is there any other way, to recieve data from the device with the library?

SerialCommUnity on Android

Eduardo wrote:
Hello
I am testing your library of serial port for unity, in pc it works perfect but the final result will be in android. I discovered trying with another application that the driver works on my tablet is / dev / ttyACM0 but I do not know how to call that parameter to your library you can help me how to do it.

I was attentive to your response and thank you.

“returnBuffer” missing from 40 to 39

Your code is cool, data has received safty. But I find a problem with my program. I've lost 1byte in receiving message.

Your code(class,SerialThreadBinaryDelimited):
byte[] returnBuffer = new byte[index]; System.Array.Copy(buffer, returnBuffer, index);

After I've changed. I had received all the data:

byte[] returnBuffer = new byte[index +1]; System.Array.Copy(buffer, returnBuffer, index +1);

I need receive hexadecimal 40 bytes from comm, but recived 39 bytes. I've got all the message after I changed above code. Is it a problem?

Reading from a specific device over virtual COM

The following question is copied from a user's email regarding using Ardity to connect Unity and a specific hardware device without using an Arduino in between.

Dear dwilches,

I have found your Ardity library and I found it quite interesting as I am trying to read in Unity an incremental encoder.

I was wondering if I could use your library to communicate with this specific device:
https://www.rls.si/en/e201-usb-encoder-interface-123

I am really not an expert on this and will have to trial and error a lot I guess, but I was wondering if you could give me some tips/directions to understand if I have to modify your library or I can just use it as it is.

I would really appreciate your help,

Warmest regards,

Issue with COM between PIC and Unity

Hello dwilches,

Thank you for sharing this code base; and sample projects.

I am pretty amateur with Unity/C#, and believe I have having an issue similar to that which jeongcatfish or Andrea-Loriedo seem to be describing. I did not really mess with the scene, or the code; so assume the Listener is per-configured in a mode for debugging.

I was trying to use the ReadWrite sample scene but was not getting the expected behavior @ 115200 Baud rate. So I set up a quick test project using a 9600 Baud, and attempting to use the DemoScene_AutoPoll scene as you suggested this thread: (#19)

//Code above just configures the EUSART and I/Os which are not being used.
// System is running at 4 MHz Default.
Below is the main code snippet:

while (1)
{
// Add your application code
DELAY_milliseconds(1000);
printf("Test Message\r\n");
}

image
image
image
image

I can provide the packaged project, but it is basically just configuring a PIC device's EUSART.
It is POLLING driven, not doing any reads and there are no other task running besides the delay. DELAY_ is blocking; but since I am not doing any reading response yet, I would not expect that to have been an issue.
I cloned from the latest HEAD. I don't have an Arduino for evaluation.

I can keep looking into this; but figured I would message to see if there was something simple being missed.

Thank you for any assistance.
Best Wishes,
ABoyOnFire

Port never seems to close

Hello, first of all, thank you for this package. It's one of the cleanest ones out there. I'm not sure if this is an issue with my device or C#. It seems no matter what I do to disconnect the device via software, the port never closes. So if I call RequestStop() then wait a few seconds and come back to the application, I get IO errors saying the thread is busy.

Exception:

Exception: The I/O operation has been aborted because of either a thread exit or an application request.
 StackTrace:   at System.IO.Ports.WinSerialStream.ReportIOError (System.String optional_arg) [0x00000] in <filename unknown>:0 
  at System.IO.Ports.WinSerialStream.Write (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0 
  at System.IO.Ports.SerialPort.Write (System.Byte[] buffer, Int32 offset, Int32 count) [0x00000] in <filename unknown>:0 
  at System.IO.Ports.SerialPort.Write (System.String str) [0x00000] in <filename unknown>:0 
  at System.IO.Ports.SerialPort.WriteLine (System.String str) [0x00000] in <filename unknown>:0 
  at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:WriteLine (string)
  at SerialThreadLines.SendToWire (System.Object message, System.IO.Ports.SerialPort serialPort) [0x00008] in E:\@Documents\Consulting Projects\VRR\FlexPointController-repo\FlexPointController\Assets\SerialComm\Scripts\Threads\SerialThreadLines.cs:34 
  at AbstractSerialThread.RunOnce () [0x00025] in E:\@Documents\Consulting Projects\VRR\FlexPointController-repo\FlexPointController\Assets\SerialComm\Scripts\Threads\AbstractSerialThread.cs:245 
  at AbstractSerialThread.RunForever () [0x00015] in E:\@Documents\Consulting Projects\VRR\FlexPointController-repo\FlexPointController\Assets\SerialComm\Scripts\Threads\AbstractSerialThread.cs:143 
UnityEngine.Debug:LogWarning(Object)
AbstractSerialThread:RunForever() (at Assets/SerialComm/Scripts/Threads/AbstractSerialThread.cs:150)

My specific code:
https://gist.github.com/Naphier/7dab5b5271f7deb1f70037a39c35ea9e

I must manually stop the application, then unplug the device every time. Any suggestions are appreciated.

Queue is full problem (interfering arduino with unity)

I wanted to get the accelerometer data from arduino to unity for creating an AR game.I was using ardity for serial communication.When i run the stimulation along with the accelerometer data iam getting the queue is full message and also the message has been dropped message.How to fix this and how to get full data without droping of datas.Please reply

Does Ardity work on Mac?

my port name looks like this:
/dev/cu.usbmodem144201

This is the error i get:
Exception: No such file or directory StackTrace: at System.IO.Ports.SerialPortStream.ThrowIOException () [0x0000f] in ...

Multiple Ports

[Moving an email thread over to GitHub]
Hello there,

I have recently been working on a project involving Arduino boards and unity. I finally came across your Ardity plugin and am quite happy with finally getting communication from the Arduino to unity so thank you so much for that. I am new to coding let alone micro controlling and I was wondering if you plugin is able to handle 2 different port communications. I have 2 separate boards that need to communicate with unity and having found your solution for one board I was wondering if it was possible to have it communicate with 2 ports?

Any help or tips would be much appreciated. Thank you for your code and your time.

How to send a message in OnApplicationQuit

I'm trying to use your library, to turn on and off lights in my installation. I also need to turn the lights off when application is turned off. I've put sending off message into OnApplicationQuit, but it doesn't seem to work.

void OnApplicationQuit() { serialController.SendSerialMessage("@REL#0@"); }

Is that an expected behaviour?

Reading serial data from COM3 not working

Hi,
I am using this to read and write data to my Unity application from COM3.
While i can write the data (a & z strings), i'm unable to read any data that i receive from the COM port.
I've tried the DemoScene_AutoPoll, DemoScene_UserPoll_JustRead, DemoScene_UserPoll_ReadWrite.
Either one of these scene won't show the message received from the COM port in the console window.
Any reason why? Anything i may be missing?

Thanks.

I/O operation aborted

I am having issues when sending signals with some frequency. The program starts fine, but after a few seconds it suddenly gives an exception, and I hear disconnecting sound from windows (arduino disconnects). After that, I get an exception that port does not exist.

The error in unity:

Exception: The I/O operation has been aborted because of either a thread exit or an application request.
 StackTrace:   at System.IO.Ports.WinSerialStream.ReportIOError (System.String optional_arg) [0x00039] in <14e3453b740b4bd690e8d4e5a013a715>:0 
  at System.IO.Ports.WinSerialStream.Read (System.Byte[] buffer, System.Int32 offset, System.Int32 count) [0x0009d] in <14e3453b740b4bd690e8d4e5a013a715>:0 
  at System.IO.Ports.SerialPort.read_byte () [0x00007] in <14e3453b740b4bd690e8d4e5a013a715>:0 
  at System.IO.Ports.SerialPort.ReadTo (System.String value) [0x0003c] in <14e3453b740b4bd690e8d4e5a013a715>:0 
  at System.IO.Ports.SerialPort.ReadLine () [0x00000] in <14e3453b740b4bd690e8d4e5a013a715>:0 
  at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort.ReadLine()
  at SerialThreadLines.ReadFromWire (System.IO.Ports.SerialPort serialPort) [0x00001] in C:\Users\Lord\source\diploma\blind-karting\Assets\Ardity\Scripts\Threads\SerialThreadLines.cs:39 
  at AbstractSerialThread.RunOnce () [0x0002e] in C:\Users\Lord\source\diploma\blind-karting\Assets\Ardity\Scripts\Threads\AbstractSerialThread.cs:249 
  at AbstractSerialThread.RunForever () [0x0000f] in C:\Users\Lord\source\diploma\blind-karting\Assets\Ardity\Scripts\Threads\AbstractSerialThread.cs:142 
UnityEngine.Debug:LogWarning(Object)
AbstractSerialThread:RunForever() (at Assets/Ardity/Scripts/Threads/AbstractSerialThread.cs:149)
System.Threading.ThreadHelper:ThreadStart()

Arduino snippet:


      void setup()
      {
        pinMode(3, OUTPUT);
        pinMode(5, OUTPUT);
        pinMode(9, OUTPUT);
        pinMode(10, OUTPUT);
      
        Serial.begin(9600);
      }
      void loop()
      {
        // Print a heartbeat
        if (millis() > last_time + heartbeat_freq)
        {
          Serial.println("Arduino is alive!!");
          last_time = millis();
        }
      
        if (Serial.available() > 0) {
          char *arr = new char[7];
          int i = 0;
          while (Serial.available() > 0) {
            arr[i] = Serial.read();
            ++i;
          }
          message = String(arr);
          int indexOfDelimeter = message.indexOf(' ');
          firstString = message.substring(0, indexOfDelimeter);
          secondString = message.substring(indexOfDelimeter + 1);
          
         updateMotorSpeed(firstString.toInt(),secondString.toInt());
        }
      }

C# where I send the messages:

            leftWeight = Mathf.Round(Map(leftWeight, 0f, 9f, 0f, 255f));
            rightWeight = Mathf.Round(Map(rightWeight, 0f, 9f, 0f, 255f));


            serialController.SendSerialMessage(leftWeight + " " + rightWeight);

reading from sensor to unity3d

want to read position and force value from sensor into unity3d. Attaching the arduino println commands. How to change to read that values using your plugin. Thanks.
serialMonitor

'Access denied: StackTrace at System.IO.Ports.WinSerialStream.ReportIOError'

Hello,
I've run into a issue in Unity:
I get an "Connection attempt failed or disconnection detected" and a:

Exception: Zugriff verweigert
StackTrace: at System.IO.Ports.WinSerialStream.ReportIOError (System.String optional_arg) [0x00039] in <9f8c4786222746238eb929db40bf8dd1>:0
at System.IO.Ports.WinSerialStream..ctor (System.String port_name, System.Int32 baud_rate, System.Int32 data_bits, System.IO.Ports.Parity parity, System.IO.Ports.StopBits sb, System.Boolean dtr_enable, System.Boolean rts_enable, System.IO.Ports.Handshake hs, System.Int32 read_timeout, System.Int32 write_timeout, System.Int32 read_buffer_size, System.Int32 write_buffer_size) [0x00046] in <9f8c4786222746238eb929db40bf8dd1>:0
at (wrapper remoting-invoke-with-check) System.IO.Ports.WinSerialStream..ctor(string,int,int,System.IO.Ports.Parity,System.IO.Ports.StopBits,bool,bool,System.IO.Ports.Handshake,int,int,int,int)
at System.IO.Ports.SerialPort.Open () [0x0001a] in <9f8c4786222746238eb929db40bf8dd1>:0
at (wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort.Open()
at AbstractSerialThread.AttemptConnection () [0x00034] in D:[...]\Assets\Ardity\Scripts\Threads\AbstractSerialThread.cs:191
at AbstractSerialThread.RunForever () [0x00006] in [...]\Assets\Ardity\Scripts\Threads\AbstractSerialThread.cs:137
UnityEngine.Debug:LogWarning(Object)
AbstractSerialThread:RunForever() (at Assets/Ardity/Scripts/Threads/AbstractSerialThread.cs:149)
System.Threading.ThreadHelper:ThreadStart()

I am using the Unity Scene: 'DemoScene_UserPoll_JustRead' (or with all objects from that scene in my own) scene and the Sample Arduino Program (which I just copied into the Arduino IDE) on an Arduino 1.0.1 on COM3

unsigned long last_time = 0;
void setup()
{
    Serial.begin(9600);
}
void loop()
{
    // Print a heartbeat
    if (millis() > last_time + 2000)
    {
        Serial.println("Arduino is alive!!");
        last_time = millis();
    }
    // Send some message when I receive an 'A' or a 'Z'.
    switch (Serial.read())
    {
        case 'A':
            Serial.println("That's the first letter of the abecedarium.");
            break;
        case 'Z':
            Serial.println("That's the last letter of the abecedarium.");
            break;
    }
}

Further: What GameObject should be put in the MessageListener-field in Unity on the SerialController GameObject?

Maybe you can clearly see the error I made here.
Anyways, thank you for your time and thanks for providing the asset to begin with.

Cheers,
Mathias

Sending strings instead of characters

Hello!

First off i just want to start by saying Thank you for this. It has helped me understand using serial devices within unity a lot better.

I need to send a comma separated string over serial to the arduino so that I can then break it down and load it into an array. I can't seem to get a string over to the arduino. I can only send a single character.
Is sending an entire string instead of a character possible? If so, would you possibly be able to show me an example?

Any help would be much appreciated.

Tom

Trying to read bytes, keep getting "?" (ascii 63)

If I send the byte 128 (or anything higher) followed by a newline then I read that into Unity like so:

string message = serialController.ReadSerialMessage ();
print(message[0]);

Outputs: "?" (or ascii 63).

This is just wrong!

Queue is full. Dropping message:

Greetings! Kudos on Ardity! I'm a kinetic artist and really excited about interactive art with Unity! I'm a Unity newbie, as well as C# (two strikes? (o:) but lots of Arduino/ESP32/Parallax Propeller experience.
I've set up your examples and comms to my Arduino are working (getting msgs displayed in Unity console) but it looks like they are only getting displayed after Max Unread Messages value is exceeded. I'm sending msgs at 1 second intervals but get the Queue is full msg right away. I changed Max Unread Messages to 10, and there are no messages for 10 seconds; then (!)Queue is full msgs resume in console. Curious that the msgs aren't being displayed in the console until after Max is exceeded? I'm using your example code, but modified as below:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyMessageListener : MonoBehaviour
{
    // Use this for initialization
    int obstacleDetected = 0;
    void Start()
    {
    }
    // Update is called once per frame
    void Update()
    {
       // transform.Rotate(1, 0, 0);
        if (obstacleDetected == 1)
        {
            transform.Rotate(20, 0, 0);
            obstacleDetected = 0;
        }
    }
    // Invoked when a line of data is received from the serial device.
    void OnMessageArrived(string msg)
    {
        Debug.Log("Arrived: " + msg);
        if (msg == "Obstacle Detected!")
        {
            obstacleDetected = 1;
        }
        Debug.Log(obstacleDetected);
    }
// Invoked when a connect/disconnect event occurs. The parameter 'success'
// will be 'true' upon connection, and 'false' upon disconnection or
// failure to connect.
void OnConnectionEvent(bool success)
    {
        Debug.Log(success ? "Device connected" : "Device disconnected");
    }
}

When I unrem the transform.Rotate line the cube spins on every Update, so that works.....
Oh, and my Arduino code (I cut and pasted the "Obstacle Detected!" message from Arduino IDE into Visual Studio to assure no typos (o:) and using println to assure carriage return sent......

int isObstaclePin = 2;
int isObstacle = HIGH;
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(isObstaclePin, INPUT);
  Serial.begin(9600);
}
void loop() {
  isObstacle = digitalRead(isObstaclePin);
  if (isObstacle == LOW)
  {
    digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
    Serial.println("Obstacle Detected!");
  }
  else
  {Serial.println("All Clear!");
   digitalWrite(LED_BUILTIN, LOW);
  }
  delay(1000);
}

I saw the drop old msg post, but I don't know how to use it; but at only one msg per second, I didn't think that would be necessary, as the code grabs out of the buffer at a much faster rate?
What am I missing?
Thx so much for Ardity and your time!

Queue is Full Droping

Hey There,

First thanks to offer us this amazing lib !

I wanted to printLn a number each time in my loop, to get this in the serial monitor but when i send it, it drop a lot of time, and doesnt go to the next line, so i dont know what to do ! Thanks for helping me :)
Capture d’écran 2019-05-01 à 17 17 42

DtrEnable required for some devices

Hey there,

Just playing around with your project, seems to work well! There was only one gotcha (which I found with other libraries, so it was no big deal to adjust for my use case).

For some devices, such as the AdaFruit Trinket M0 (And similar CircuitPython devices, I think)

Adding the line:
serialPort.DtrEnable = true;

just before
serialPort.Open();

in AbstractSerialThread fixed the issue. However, I'm sure others would want to set through a constructor or similar.

Won't receive COM messages

I have a custom Arduino script that will not display any messages at all in Unity using the plugin. It will display that the device is connected and, in docklight, I am receiving messages. I've wondered into the code and the inputQueue will appear as null (meaning no messages are being received).

the following is my Arduino Code:


//player 2 commented out for single wheel
int p1Pin = 0; //player 1 potentiometer
//int p2Pin = 1;//player 2 potentiometer
int p1Val = 0;
//int p2Val = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
p1Val = analogRead(p1Pin);
//p2Val = analogRead(p2Pin);
Serial.print("P1 Raw Val: ");
Serial.println(p1Val);
p1Val = map(p1Val, 305, 853, 0, 100);
Serial.print("P1 Mapped Val: ");
Serial.println(p1Val);
/*Serial.print("P2 Raw Val: ");
Serial.println(p2Val);
p1Val = map(p2Val, 305, 853, 0, 100);
Serial.print("P2 Mapped Val: ");
Serial.println(p2Val); */
delay(5);
}

Messages not showing

Hello,

I followed the pdf with steps to get incoming messages into Unity from the COM port with the 'MyMessageListener.cs' script.
Upon pressing play, the only message I get is "Device Connected" and no more messages. I checked if the device is sending data via a python script and yes it is constantly sending data.

I have 2 suspicions:

  1. The data being sent from the device is in the form of hex bytes (as shown in the image). Is that a problem? Also, they come as packets.
    packs

  2. Does it matter if the device is arduino or not?

Doesn't seem to work in Unity 5.6.0f3?

I tried this out in Unity, but it doesn't seem to be able to receive serial data on the current version. It can open the connection, see when the serial port is being used by something else, but can't seem to receive data.

I'm not sure if Unity changed something, the project has to be setup special or something wrong with my computer.

I can get serial output in the arduino IDE, in processing 3, but for some reason, even every demo from every forum posted in the last 7yrs, won't receive any data from the serial port. (besides acknowledging it is opened, which does block other applications from using it- so it can open/ block it, but can't read it).

I'm sure this does work in an older version of Unity- but can you tell me which one?

Communicate with mblock over COM

i asked on unity forum but as i'm not an expert i couldn't implement the reply given.
i have a software that send messages ( code ) to COM2 , COM3 etc . what i want now is to get unity receive those messages on windows 10.
the software that broadcast the messages is mblock which is use in programming the mbot arduino robotic kit.
i want to create an emulator for the mbot in unity which will be programmed from mblock .
someone did a similar thing here using mblock and Vrep and Virtual Serial Ports Emulator
Can i achieved this with this package?

No console data

I have been scratching my head how to connect my IMU sensor through arduino into Unity. I actually got a cube rotating from my own coding but it is very lagged and doesn't respond very well. I just found your Ardity unity asset and am following your manual to get it up and running. So at first I kept my Arduino code the same cause I have it setup to combine the x,y,z into a string and I know it works cause I can get the cube working. I'm more concverned about the multithreading which is what brought me here.

So I have everything setup properly and when I press play nothing happens. No console logs show up. Not even the connection log shows. I'm not sure what I'm missing. I am using Unity 2018.3.7f1 if that makes a difference. I setup the cube, added the serialController to it. than created the MyMessageListener Script and added it to the serial controller like in the manual and added the controller game object to message listener spot. So from as far as I can tell everything is setup correctly.

I then tried to upload the sample code in the mabnual to test the basics . In the serial monitor of Arduino I can send the A or Z char and it does indeed reply back the correct response. I'm not sure If need to add a temp Serial.Write function to send out the A or Z using the sample arduino code. Any help would be great as I've been fumbling around trying to get my sensor data to properly rotate a cube for a few weeks now. I am pretty new to unity(about a year of unity) and even newer to arduino(Although I know the arduino is sending the data i need)

How can I send numbers and variables to my arduino?

Here is the script:
/**

using UnityEngine;
using System.Collections;
using UnityEditor;

/**

  • Sample for reading using polling by yourself, and writing too.
    */
    public class SampleUserPolling_ReadWrite : MonoBehaviour
    {
    public SerialController serialController;
    public string speed;

    // Initialization
    void Start()
    {
    serialController = GameObject.Find("SerialController").GetComponent();

    }

    // Executed each frame
    void Update()
    {

     //---------------------------------------------------------------------
     // Send data
     //---------------------------------------------------------------------
    
    
     speed = Car_Controller.speed1.ToString("D5");
     serialController.SendSerialMessage(speed);
     
    
    
    
     //---------------------------------------------------------------------
     // Receive data
     //---------------------------------------------------------------------
    
     string message = serialController.ReadSerialMessage();
    
     if(message == "P")
     {
         EditorApplication.isPlaying = false;
     }
    
     if (message == null)
         return;
    
     // Check if the message is plain data or a connect/disconnect event.
     if (ReferenceEquals(message, SerialController.SERIAL_DEVICE_CONNECTED))
         Debug.Log("Connection established");
     else if (ReferenceEquals(message, SerialController.SERIAL_DEVICE_DISCONNECTED))
         Debug.Log("Connection attempt failed or disconnection detected");
     else
         Debug.Log("Message arrived: " + message);
    

    }
    }

Im trying to send my car speed to my arduino so it can display it to a lcd

Exception: The semaphore timeout period has expired error

Hello

I am trying to set up a project using an Arduino to control motion in Unity, and Ardity seems to be the perfect tool for the job. A colleague is working on this same project (but using Mac and a different Arduino) and has got everything working nicely. :)

However, at the moment I am stuck trying to establish a serial connection between an Arduino (Nano 33 BLE Sense) and Ardity/Unity (Windows 10). I have all the COM ports, .net 4.X settings configured correctly AFAIK, and followed your setup guide, but when I set up the connection and run the basic tests (the one that should print "Arduino is alive!"), I receive the "Connection established" message but can get no serial messages from the Arduino.

Attempting to send messages (keypresses for the readwrite example) from Ardity to the Arduino is similarly not working: no messages reach the Arduino, and after the third attempt/keypress I get the error message "Exception: The semaphore timeout period has expired". This time the Arduino detects that the serial connection is active after the first attempt/keypress, but it gets stuck 'on' without producing any further effect.

I have been investigating what might be blocking the messages on the ostensibly active serial connection (including the suggestions here: #13), but have so far drawn a blank. I'd really appreciate any insights you have here!

Best wishes

Martin

No able to read messages from com port

first of all thanks to create such useful package, but i'm facing some issue when i'm trying to read message from com port but it will show 'Connected' very first time and after that it will not receive any message
can you please tell me some solution to receive message from com port

Got null from ReadSerialMessage

Ardity doesn't see serial messages from arduino. According to port monitor in Arduino IDE messages were sent but Ardity doesn't call OnMessageArrived and ReadSerialMessage returns Null

Sending hexadecimal values

Hi,
firt of all thank you for this package it was verry helpfull. but i have a problem to figure out how to send a hexadecimal data (byte[]) i added this method to your code :
public static byte[] HexStringToByteArray(string hexString)
{

	byte[] result = new byte[hexString.Length / 2];

	for (int i = 0; i < hexString.Length; i += 2)
	{
		result[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16); // base 16
	}

	return result;
}

if (Input.GetKeyDown (KeyCode.I)) {
Debug.Log ("Initializing camera . . .");
string hexString = "88010001FF";
byte[] byteArray = HexStringToByteArray (hexString);
serialController.SendSerialMessage (byteArray);

	}

i have this error : Error CS1502: The method 'SerialController.SendSerialMessage(string)' has non valid arguments
Error CS1503: Argument 1 : impossible to convert 'byte[]' en 'string' (CS1503) (Assembly-CSharp)
Any idea how to fix this,i'll be verry appriciatif !
thanck's in advance!

change behaviour on build

Hi,
Thanks for share this great library! I am using Ardity for sending data from an IMU connected to an Aduino nano to UNITY. On editor mode it works great receiving aroud 30 meesages for second on updating the animation ok. When I build the program it only get 1 massage every 3-5 seconds and then when I return to edit mode, without changing any configuration, the message listener continue receiving massages every 3-5 seconds! I have to return to a previous version of the application before build in order to work again. The serial monitor o Arduino development console show that arduino is sending the messages without changes.
I dont know what could be hapening!
Thanks

Issue with receiving data

Hi

I'm Archus from the Unity Answers page. I figure that it will be easier to message you here instead of the comment section on the Unity page.

Continuing from your answers before, I just tried to add the '\n' however it is still not working. Just in case, I tried to check the project settings and also changing the virtual serial port driver I'm using (currently using Eltima Virtual Serial Port Driver and HHD Software Free Virtual Serial Port Driver) however it is still not working. I have tried sending the string with and without '\0' too (change to length to 2 or 3).

This is the modified main body of the code based on your input

    int main() {
    	Serial* VR = new Serial("\\\\.\\COM7");
    	int input;
    	char toVR1[] = "K\n";
    
    	if (VR->IsConnected())
    		printf("VR is connected\n\n");
    
    	while (true) 
    	{
    		cout << "please enter 0 for send, 1 for read, 2 for receive, and 3 for write receiver" << '\n';
    		cin >> input;
    		if (input == 0)
    		{
    			cout << toVR1;
    			VR->WriteData(toVR1, 3);
    		}
    		else if (input == 1)
    		{
    			VR->ReadData(fromVR1, 2);
    			cout << fromVR1[0] << '\n';
    		}
    	}
    	return 0;
    }

Also, for reference, here is the function that handles writing data to serial port

    bool Serial::WriteData(char *buffer, unsigned int nbChar)
    {
        DWORD bytesSend;
    
        //Try to write the buffer on the Serial port
        if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
        {
            //In case it don't work get comm error and return false
            ClearCommError(this->hSerial, &this->errors, &this->status);
    
            return false;
        }
        else
            return true;
    }

And this is the function that handles connecting to the serial port

Serial::Serial(char *portName)
{
    //We're not yet connected
    this->connected = false;

    //Try to connect to the given port throuh CreateFile
    this->hSerial = CreateFile(portName,
            GENERIC_READ | GENERIC_WRITE,
            0,
            NULL,
            OPEN_EXISTING,
            FILE_ATTRIBUTE_NORMAL,
            NULL);

    //Check if the connection was successfull
    if(this->hSerial==INVALID_HANDLE_VALUE)
    {
        //If not success full display an Error
        if(GetLastError()==ERROR_FILE_NOT_FOUND){

            //Print Error if neccessary
            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);

        }
        else
        {
            printf("ERROR!!!");
        }
    }
    else
    {
        //If connected we try to set the comm parameters
        DCB dcbSerialParams = {0};

        //Try to get the current
        if (!GetCommState(this->hSerial, &dcbSerialParams))
        {
            //If impossible, show an error
            printf("failed to get current serial parameters!");
        }
        else
        {
            //Define serial connection parameters for the arduino board
            dcbSerialParams.BaudRate=CBR_9600;
            dcbSerialParams.ByteSize=8;
            dcbSerialParams.StopBits=ONESTOPBIT;
            dcbSerialParams.Parity=NOPARITY;

             //Set the parameters and check for their proper application
             if(!SetCommState(hSerial, &dcbSerialParams))
             {
                printf("ALERT: Could not set Serial Port parameters");
             }
             else
             {
                 //If everything went fine we're connected
                 this->connected = true;
                 //We wait 2s as the arduino board will be reseting
                 Sleep(ARDUINO_WAIT_TIME);
             }
        }
    }
}

Thank you for your time.

Can't Read Serial Com Port(RS485 to usb)

Hello.
I'm trying to communicate with unity and RS485 to usb.
portName
It appears that it's com6. and baud rate is 57600.
So I set the Serial Controller com6, 57600. but It's not working :(

In unity,
image

image

System.IO.Ports is not available in Unity 2018 .net 4.x

It seems that the System.IO.Ports is not available in Unity 2018. (2018.3.0f2)
I have Player settings->Scripting Runtime Version set to ".NET 4.x or equivalent" and Api Compatibility Level set to .NET 4.x.
I tried changing Api Compatiblity level to ".NET Standard 2.0" which is the only other option available, and I get the same error in the script.
Has anybody had this problem and fixed it? Any ideas?

Arduino Joystick Issue.

Hi. I have a problem with adding the values of arduino analog joystick.
the buttons and leds are working fine, but need to add a joystick to rotate the camera.

the issue is in split. if you can, please tell me what is wrong. thanks
the DATAQ is used also for other inputs.

  string DATAQ = serialController.ReadSerialMessage();
        string[] vec3 = DATAQ.Split(',');
         if (vec3[0] != "" && vec3[1] != "" && vec3[2] != "")
        {
         transform.Rotate(
             float.Parse(vec3[0]) - lastRot[0],
             float.Parse(vec3[1]) - lastRot[1],
             float.Parse(vec3[2]) - lastRot[2]);

           lastRot[0] = float.Parse(vec3[0]);
        lastRot[1] = float.Parse(vec3[1]);
         lastRot[2] = float.Parse(vec3[2]);
        }

SendMessage Issue (How can I solve this issue?)

Hi

RIGHT TO THE POINT!

SendMessage sometimes don't work.

for ex:
led will turn On when I press "A".
but sometimes led is Off even if I press "A" over 2~4 times.

what's wrong with this? (HELP)
and the arduino tx led blinks whenever I press "A"

void setup() {
  Serial.begin(9600);
  pinMode(13,OUTPUT);
}

void loop() {
if(Serial.read()=='1')
  digitalWrite(13,HIGH);
else if(Serial.read() == '2')
  digitalWrite(13,LOW);
}

unity Code

if (Input.GetKeyDown(KeyCode.A))
        {
            Debug.Log("Sending 1");
            serialController.SendSerialMessage("1");
        }

        if (Input.GetKeyDown(KeyCode.Z))
        {
            Debug.Log("Sending 2");
            serialController.SendSerialMessage("2");
        }

Using the input from the Arduino to controll GameObject

Hello,

i am fairly new to working with Arduino and Unity, and i don't really understand how i can use the input from the Arduino to control "stuff" ( movement of a Game Object for example ).
I can print messages to the console in Unity by pressing a pushbutton on an Arduino circuit, but how do i use these messages to trigger something? (" e.g. save the value to a variable and move a cube, when the value is "1" .... i hope you get the point :/ )

Thank you in advance!
kind regards,
Tobi

OSX no connection when using IL2CPP

On OSX 10.14.6, Ardity works fine for me when using Mono, but switching Player Settings to IL2CPP prevents it from connecting. In other words, OnConnectionEvent is never called.

Below is the code I am using to find the connected serial port.
`using System.IO.Ports;
// Search through all potential ports until we find a USB one
string[] arrPorts = SerialPort.GetPortNames();

    foreach (string portName in arrPorts)
    {
        if (portName.Contains("usbmodem"))
        {
            controller.portName = portName;
            controller.baudRate = 115200;
            controller.messageListener = this.gameObject;
            controller.gameObject.SetActive(true);
            break;
        }
    }`

usb serial on android receives data from Arduino but won't connect to unity

Android has an OTG cable attached to my Arduino data glove. The usb serial app on android shows the data stream is being received. Using Ardity this works in Unity on OS X when I compile to Android it doesn't work. I will mention that the physical data glove is connected to a virtual hand. The gyro info and the finger movement data work in the Unity workspace. I thought it might be a naming convention for the USB port. After much searching I found that my original address for the Data glove /dev/cu.Repleo-CH341-00101114 was different that the android port. So I changed the port to /dev/bus/usb/001/002
Still no connection. Various usb apps on android named the chip CH34x and also MPU6050. But Unity is reading it.
The nature of the chip is to communicate with Baud 115200. Android receives the info this way and it's clear. So I'm stumped?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.