1

I'm trying to use the output from a serial to write them into a text file for an experiment and trigger the device continuously using the serial port commands. Here is the sample code I'm using to to test the read() functions which all work differently and I'm unable to understand why.

I want to be able to use the bytestoread prperty to keep checkign for any output in the serial to write to my text file.

class Program
{
    static void Main(string[] args)
    {

        byte[] buffer = new byte[2048];
        SerialPort port = new SerialPort("COM4", 9600, Parity.None, 8, StopBits.One);
        port.Open();
        port.DtrEnable = true;
        port.RtsEnable = true;
        port.NewLine = "\r";
        port.Handshake = Handshake.RequestToSend;
        if (port.IsOpen) { Console.WriteLine("port is now open"); } else { Console.WriteLine("port not opened correctly"); }
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
        port.Write("T");
        Console.WriteLine("bytes to read : {0}",port.BytesToRead);
        Console.WriteLine("return value form .read function : {0}",port.Read(buffer,0,20));
        Console.ReadLine();
    }

    static void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        Console.WriteLine(sp.ReadTo("\r"));

    }

}

the output is

port is now open bytes to read : 0 return value form .read function : 1 199.0,+238.0,091

Can somebody help me understand why the port.bytestoread returns 0 and port.Read() which has to return the count returns only one but the readTo() functiosn returns the actaul output?

4

1 回答 1

1

这是因为DataReceived事件处理程序是从后台线程调用的。在调用之后port_DataReceived,该线程不会调用您 的 Console.WriteLine("bytes to read : {0}",port.BytesToRead);

于 2012-08-01T15:20:22.157 回答