0
votes

I'm doing a project in Unity 3D that using serial ports , I had problems with the serial port inside Unity. I have a idea but i don't know it will work.

I intend to build a dll in c# that is used for unity, this dll file is the serial port driver and lets to Unity get and send data to serial port through a class c# in Unity .

The doubt is: There's a event in c# called "SerialDataReceivedEventHandler" (Represents the method that will handle the DataReceived event of a SerialPort object) but it seems this event is not raised automatically when the dll file is used.

How can I invoke this method automatically inside the dll ???

Other alternative is to write a dll file in c++ using win32 API , will this be more useful as soon as port communication???

Thanks.

1
Unity and Unity3D are different tags, Unity3D was the one you wanted. Good luck with your problem thoughHoloLady

1 Answers

0
votes

I have seen many people reporting problems with SerialDataReceivedEventHandler. I am sure that SerialPort.BytesToRead works. You can forget about SerialDataReceivedEventHandler and instead, implement your own event system with SerialPort.BytesToRead.

The way to do this:

Your event system should have two events. One that CANNOT be accessed from your application (Event A) and one that can be accessed from your application (Event B).

For event a, you should add SerialPort.BytesToRead to call Event A when SerialPort.BytesToRead changes its value.

When Event A is called, it will check if SerialPort.BytesToRead is more than zero. If SerialPort.BytesToRead is more than 0, then you have new data to read and then Event B should be triggered by Event A. If SerialPort.BytesToRead is 0, don't trigger Event B.

You can then implement your Event B from your application and wait for it to trigger. When it triggers, you can then read your new received data from there.

OR

If that doesn't work for you, You can just do it with the dll style you suggested. Win32 API seems hard and confusing. You can grab the simple SerialClass from Arduino website and add for features to it then compile it to dll. That would work too. I can't post the whole code here since its too large but I will drop the link here. The downside of this method is that it will only work on Windows. To get it working on a Mac and Linux, you have to compile a dll for each platform. I recommend my first solution.

http://playground.arduino.cc/Interfacing/CPPWindows