Hi all,
I have a custom piece of hardware that communicates over serial (virtualised on USB) that I have working with an old game and I want to update the new game by re-creating it in Unity to make use of the really nice things I see Unity can do.
I’ve stumbled at the first hurdle though because I can’t seem to get my script which polls the serial port for data to work.
I open the serial port and that’s fine but if I execute int bytesToRead = serialport.BytesToRead;
it crashes out with a NullReferenceException:
NullReferenceException: Object reference not set to an instance of an object
System.IO.Ports.WinSerialStream.get_BytesToRead ()
System.IO.Ports.SerialPort.get_BytesToRead ()
(wrapper remoting-invoke-with-check) System.IO.Ports.SerialPort:get_BytesToRead ()
SerialTest.Update () (at Assets/SerialTest.cs:25)
I’ve seen some other questions on here about using serial but I don’t have Pro to use a plug-in and I already have the c# code I used for my old version of the game (it was written in XNA) so it’d be great to just port that over but for some reason BytesToRead gives me the NullReferenceException!
Has anyone got around this problem or worked out what it is?
Thanks a lot for reading,
Carkey
P.S. Here is a stripped down version of my code just to try and get this working:
public static SerialPort sp;
// Use this for initialization
void Start () {
sp = new SerialPort("COM4", 115200, Parity.None, 8, StopBits.One);
sp.Handshake = Handshake.None;
sp.ReadBufferSize = 1024;
sp.WriteBufferSize = 1024;
sp.ReadTimeout = 20;
sp.WriteTimeout = 20;
print ("Serial port object created.");
sp.Open();
}
// Update is called once per frame
void Update () {
byte[] buffer = new byte[1024];
if(sp.IsOpen)
{
print ("serial is open!");
int bytesToRead = sp.BytesToRead;
print ("BYTES TO READ: " + bytesToRead);
}
}
EDIT: Also, is there a way to break on breakpoints in MonoDevelop? If I put a breakpoint in, it doesn’t seem to do anything :-/
EDI 2: Okay BytesToRead still doesn’t work but you can blindly call the blocking ReadLine()
or ReadByte()
etc. This is only reliable if you KNOW the hardware will always be sending data, I am writing the code for the hardware too so I’ve got it to send ping faster than every frame and then relevant data when it gets it so it seems to work so far. Would be so much more useful if BytesToRead worked though