Reputation:
I am trying to implement the following piece of code in order to capture information incoming to me through a serial connection. Im using the .NET SerialPort class:
//serial port initialization
serialPort = new SerialPort();
serialPort.PortName = "COM7";
serialPort.BaudRate = 19200;
serialPort.Parity = Parity.Even;
serialPort.DataBits = 8;
serialPort.StopBits = StopBits.One;
serialPort.Handshake = Handshake.None;
serialPort.ReceivedBytesThreshold = 1;
//this is how the handler is added in Form1.Designer.cs
this.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.DataReceivedHandler);
//Handler
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine("Got Here");
while (serialPort.BytesToRead > 0)
{
byteBuffer.Add((byte)serialPort.ReadByte());
ProcessByteBuffer(byteBuffer);
}
}
I physically connected my Rx and Tx pins on the RS232 port, and im trying to write a message to trigger the event to see if its working. I can't seem to get the event to trigger the "Got Here" text never appears in my console. I know the data is going into my recieve buffer because i can call serialPort.ReadExisting() and see the message I originally input.
Can anyone tell me why this event might not be firing?
Upvotes: 0
Views: 1984
Reputation: 941277
serialPort = new SerialPort();
You got that wrong. You overwrote the SerialPort object reference that designer created. The one that had the DataReceived event assigned. Your new object doesn't have that event assigned. So it will never fire.
Just delete that line.
Upvotes: 3