Why don't serial ports work properly in Unity?

老子叫甜甜 提交于 2020-01-21 07:39:10

问题


I 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 up, but I can not get data from the COM port. I've read some forums and the cause of the problem seems to be the 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, in fact I did it and got the same problem: SerialDataReceivedEventHandler does not work. Also, someone recommended me using 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, help me please.

I need to understand the cause of this to continue.


回答1:


Unity is based on Mono, and Mono doesn't implement completely the Serial class, in particular there are no notifications implemented (such as SerialDataReceivedEvent).

That's why it works in Visual Studio, and not in Unity.

Here are the differences between the Mono and complete .NET implementation of the Serial class :

Extract from http://www.mono-project.com/archived/howtosystemioports/#limitations

"Limitations At the time of this writing, there are a a few limitations that one must take note:

1) There is no event notification for received serial data. If you want to receive data, one must set a timeout and watch for received data by polling ReadByte() when you think there might be data.

2) One must Read data in byte[] format only – there is no char[] support. You must do your own reading of bytes and translate that into your encoding.

3) DiscardNull, ParityReplace, ReceivedBytesThreshold are not implemented."




回答2:


I think it happens because the Unity is based on Mono instead of .Net, and a pretty old version of it. You couldn't use Linq on iOS devices for a long time because of AOT bugs, and the localisation implementation is buggy (or at least it was in the previous versions of Unity I tried to work with). I wasn't even able to find the source of System.IO.Ports in the source of Unity's Mono fork, so it's surprising it compiles at all.



来源:https://stackoverflow.com/questions/30011887/why-dont-serial-ports-work-properly-in-unity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!