why don't serial ports work properly in unity?

need help, I’m desperate

During two weeks I have been working in my project, this uses serial port communication (a PIC serial board), I got to set the connection but i can not get data from the com port . I’ve read some forums and the cause of the problem seems to be a incomplete implementation of “System.IO.Ports” class.

When i try to get data of the COM port, the event “SerialDataReceivedEventHandler” (Represents the method that will handle the DataReceived event of a SerialPort object.) is not called or activated. I tried to resolve it but I don’t find a definitive solution. I thought to prove a external DLL but a friend told me that the problem will go on also someone recommended to me use a secondary thread although I don´t understand how to do it at all.

I wrote a program in visual c# and everything works fine. I’m intrigued.

I need to find a solution , some idea or good documentation.

If there’s someone knows something about it,please, help me .

I need to understand the cause of this to continue.

Thanks for read.

If SerialDataReceivedEventHandler isn’t working, is there a way to do what you need to do by just polling instead of using events?

Well I tried to read what was supposed to be on the com port… But it is just blocking / not reading anything whereas it works in any non-unity c# app.

My backup solution is to call a custom windows service that reads from my sensor and populates my data on a UDP socket. Then inside my unity app I connect to this socket.
It works but it is not a clean solution. Things should be so straightforward and are made complicated due to this implementation of COM ports in unity.

Until now the best solution that i found is to use a external dll files, there is a comercial library called serial port component, here is the link:

This is a commercial library but you can test the trial version for 30 days. You can integrate the dll component with c# and other ones. When you install the component you can see examples in your pc.

For using into Unity you must copy the dll file in any folder of your project an the unity folder “C:\Program Files\Unity\Editor”.(I’m using unity 5 free, the last version), with this method I got to read data from the serial port.

I don’t read data from “Update method” for performance reasons. Use a asynchronous coroutine , I installed a free package called “thread ninja” for
simulate an update method but this is executing each second not each frame .This improves the performance.

link: Unity Asset Store - The Best Assets for Game Making

when you install the package, create a class in c# as for example this one (This algorithm requires improvement):

   using UnityEngine;
    using System.Collections;
    using AxSerial;//Import the external class
    using System;
    using System.IO;
    using System.Threading;
    using CielaSpike;//Import the custom thread for unity
    
    
public SerialController : MonoBehaviour {
    
			 ComPort objComport;//Serial port object
			
			 //string of data received for the serial port
			 string datareceived="";
			
			/*
			*method that initializes the serial port
			*/
			 void initComponents()
			 {
					try
					{
						objComport = new ComPort();
						objComport.Device="COM7";//this specifies own port
						objComport.BaudRate = 9600;
						objComport.Open();//Open the port
					}
					catch(Exception ex)
					{
						Debug.Log(ex.GetBaseException());
					}
			}
			
			void Start()
			{
					initComponents();
					if (objComport.IsOpened)
					{
						StartCoroutine("manage_data");//Start coroutine for manage the data
						Debug.Log("Port opened");
					}
					else
					{
						Debug.Log("Could not  to open the port");
			
					} 
			}
			
			void OnDestroy
			{
			   try
			   {
						objComport.Close();	
			   }
			   catch(Exception ex)
			   {
					 Debug.Log(ex.GetBaseException());
			   }
			
			}
			/*
			*  asynchronous coroutine,
			*  the idea is that the method of getting data is executing every so often, for example each one second., 
			*  not for each frame like the Update method because this would down the performance
			*
			*/
			 IEnumerator manage_data()
			{
					this.StartCoroutineAsync(Blocking(), out task);
					yield return StartCoroutine(task.Wait());
			}

			IEnumerator Blocking()
			{
					int sleep = int.MaxValue;
					
					//test cycle, I tried with the while cicle but it crashes Unity, 
					// when this "for" cicle is executing , it reads data and prints them almost in sync when the serial device sends data
					//If you have a best idea, please share !!!
					for (int i = 0; i <= int.MaxValue; i++)
					{
						read_data();
						//wait 0.5 seconds and read again
						yield return new WaitForSeconds(0.5F);
						
					}
					Thread.Sleep(sleep);
			}
			
			/*
			*Read the data from the serial port
			*/
			void read_data()
			{
					 if (objComport.LastError == 0)
					 {
							datareceived=objComport.ReadString();
							//Print data on Console
							print( "Data Received: " +datareceived)
					 }
					 else
					 {
							 Debug.Log("No data");
					 }
       
			}
    
    
}

This code is not perfect and I need to understand how this dll component works and build my own dll solution, I’ve been investigating and most likely is that it uses c++, c# and win32. I’m still seeking how to do it.

If you have some best idea or suggestion, please share. My idea is build a free dll component for manage serial ports inside Unity.

Sorry for my poor English.

more information: http://forum.unity3d.com/threads/alternative-for-reading-serial-ports-into-unity.336326/#post-2176862

Check this site that has one package that allows communication with COM ports from Unity: http://ardity.dwilches.com/