Can anyone explain how the SerialPort.DataReceived works?
I have a serial port read GPS signals but it also fills up the buffer with 0's.
My Netduino 1 Tx and Rx are connected to a small circuit that coverts a single wire serial GPS. It could be that the setup is causing an issue but I'm not sure if that is the case or where to look.
My code is as follows...
namespace SerialPortHelper{ public class SerialPortClass { static SerialPort serialPort; const int bufferMax = 1024*8; static byte[] buffer = new Byte[bufferMax]; static int bufferLength = 0; public SerialPortClass(string portName = SerialPorts.COM1, int baudRate = 4800, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One) { serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits); serialPort.ReadTimeout = 10; // Set to 10ms serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived); serialPort.Open(); } private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { lock (buffer) { int bytesReceived = serialPort.Read(buffer, bufferLength, bufferMax - bufferLength); if (bytesReceived > 0) { bufferLength += bytesReceived; if (bufferLength >= bufferMax) throw new ApplicationException("Buffer Overflow. Send shorter lines, or increase line BufferMax."); } } } public string ReadLine() { string line = ""; lock (buffer) { //-- Look for Return char in buffer -- for (int i = 0; i < bufferLength; i++) { //-- Consider EITHER CR or LF as end of line, so if both were received it would register as an extra blank line. -- if (buffer[i] == 'r' || buffer[i] == 'n') { buffer[i] = 0; // Turn NewLine into string terminator line = "" + new string(Encoding.UTF8.GetChars(buffer)); // The "" ensures that if we end up copying zero characters, we'd end up with blank string instead of null string. //Debug.Print("LINE: <" + line + ">"); bufferLength = bufferLength - i - 1; Array.Copy(buffer, i + 1, buffer, 0, bufferLength); // Shift everything past NewLine to beginning of buffer break; } } } return line; } public string ReadGPSLine() { string line = ""; lock (buffer) { //-- Look for Return char in buffer -- for (int i = 0; i < bufferLength; i++) { //-- Consider EITHER CR or LF as end of line, so if both were received it would register as an extra blank line. -- if (buffer[i] == '$') { line = "" + new string(Encoding.UTF8.GetChars(buffer)); } else if (buffer[i] == 'r' || buffer[i] == 'n') { buffer[i] = 0; // Turn NewLine into string terminator line = "" + new string(Encoding.UTF8.GetChars(buffer)); // The "" ensures that if we end up copying zero characters, we'd end up with blank string instead of null string. //Debug.Print("LINE: <" + line + ">"); bufferLength = bufferLength - i - 1; Array.Copy(buffer, i + 1, buffer, 0, bufferLength); // Shift everything past NewLine to beginning of buffer break; } } } return line; }...