Best Answer nhale, 24 March 2014 - 10:34 PM
Ok, got it running.
What did I do?
- Introduce check to see if more than 1 byte is there to read (read in the forum, that check for >0 can be a problem)
- Then I had several messages "Failed to allocate 5 blocks 60 bytes". I tried to set the buffer array as instance variable instead newly created on every DataReceived event. But the problem still existed. (the step with the instance variable was also posted as possible solution in the forum)
- Then I tried to switch between the different Baudrates the GPS receiver support, and boom that's it, now it's running. It seems that the receiver was reset in the meantime, with the full app I set it to 115200 baud but removed this to eliminate every unnecessary. So I think the points above fixed it.
Now I try to enhance the code skeleton to finally provide the full functionality in parsing the NMEA strings.
If someone is interested, here is the code which is running fine now.
public static void Main() { //Required, otherwise redeploy not possible due to Buffer overflow Thread.Sleep(8000); GpsConnector _gpsConnector = new GpsConnector(); Thread.Sleep(Timeout.Infinite); Debug.Print("EXIT - should not happen"); } public class GpsConnector { SerialPort _serialPort; private byte[] _buffer; public GpsConnector() { _serialPort = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One); _serialPort.ReadTimeout = 500; _serialPort.Open(); if (_serialPort.IsOpen) { _serialPort.DataReceived += _serialPort_DataReceived; _serialPort.ErrorReceived += _serialPort_ErrorReceived; } } void _serialPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { Debug.Print("Exception event raised: " + e.EventType.ToString()); } void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { Debug.Print("Data received"); try { int bytesToRead = _serialPort.BytesToRead; if (bytesToRead > 1) { // get the waiting data _buffer = new byte[bytesToRead]; _serialPort.Read(_buffer, 0, _buffer.Length); //copy the byte array to a readable string String str = new String(System.Text.Encoding.UTF8.GetChars(_buffer)); if (str != null) { Debug.Print("Value "+str); } } } catch (Exception ex) { Debug.Print("Exception raised on data received: "+ex.ToString()); } } }Go to the full post