Adam Vengroff
Adam Vengroff

Reputation: 47

Event handler for read serial port never triggers

Goal:

Trying to write a string to a serial port, read it, then print it to console

Code:

// for waiting until event is detected
private static ManualResetEvent waitHandle = new ManualResetEvent(false);

public Driver()
{
    // create new serial port
    comPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
    // add event handler
    comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived);  
    // configure port
    comPort.DtrEnable = true;
    comPort.RtsEnable = true;
    comPort.ReadTimeout = 3000;
    // open port          
    comPort.Open();

    // send string through port
    string command = "test \n";
    byte[] MyMessage = System.Text.Encoding.UTF8.GetBytes(command);
    comPort.Write(MyMessage, 0, MyMessage.Length);

    // wait until event is detected
    waitHandle.WaitOne();
}

private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // Write data to buffer and stop wait
    Console.WriteLine(comPort.ReadExisting());
    waitHandle.Set();
}

Issue:

Write to serial seems to work fine (confirmed by using Serial Port Monitor) but "comPort_DataReceived" never gets called

If I change my code and add

while(true)
{
    Console.WriteLine(comPort.ReadExisting());
}

Right after the "comPort.Write(MyMessage, 0, MyMessage.Length);" line so that I'm polling instead of waiting for the event handler then a whole lot of nothing gets written

If I try polling this way

while (true)
{
    Byte[] buf = new Byte[2048];
    comPort.Read(buf, 0, 2048);
    Console.WriteLine(buf.ToString());
}

It just times out (System.TimeoutException: 'The operation has timed out.' ).

I'm not sure where I am going wrong/why I am unable to read from the serial port

Upvotes: 0

Views: 582

Answers (2)

Adam Vengroff
Adam Vengroff

Reputation: 47

Turns out it was a hardware issue (no device was writing to serial port) coupled with a misunderstanding (thinking I could write to a serial port and then read what I wrote from within the same program)

Upvotes: 0

Tomas Chabada
Tomas Chabada

Reputation: 3019

Ok, from what I see it looks like there is no device listening on serial port. Then, if you write something to serial port it does not mean that the same data will occur as a received data. This data is outgoing data. If you want to receive data there must be another device connected to that serial port and sending data as a response to your data written.

Upvotes: 1

Related Questions