tags:

views:

70

answers:

2

I am trying to read data from a scale RS232 interface. It sends a continuous ASCII string stream through the Serial Port which I am having trouble getting. I just want to get one line of the data that it is sending out. I guess I assumed that I would use Readline to get the data, but it just locks up the PC when I run it. I think it is trying to get all of the data and won't stop until the data stops? Here is the code I'm using:

private void button1_Click(object sender, EventArgs e)
    {
        serialPort1.PortName = "COM4";
        serialPort1.BaudRate = 9600;
        serialPort1.DataBits = 8;
        serialPort1.Parity = Parity.None;
        serialPort1.StopBits = StopBits.One;

        //opening the serial port
        serialPort1.Open();

        string str = serialPort1.ReadLine();

        MessageBox.Show(str);

        serialPort1.Close();

    }

Can you help me to determine how to get just one line of the output data and close the connection?

+1  A: 

SerialPort.ReadLine is defined to block "up to the first occurrence of a NewLine value", where NewLine defaults to a line feed. Are you sending a linefeed in your stream? Note that a linefeed character (ASCII 0x0A) is different that a carriage return (ASCII 0x0D) that you might be sending.

You can redefine the NewLine if needed, or if a line ending doesn't feel right, you can read up to a given string with SerialPort.ReadTo. You can also set a read timeout.

You might prefer to read a given number of bytes from the port, rather than a line, with one of the SerialPort.Read overloads.

If none of this applies, make sure that you're actually sending data where you think you are - bring up HyperTerminal/TeraTerm/your favorite serial terminal, configure it with the same serial port settings as you've used above, and make sure you see the data you expect to see.

Michael Petrotta
A: 

An ideal solution would be to spawn a worker thread to actually read from the serial port (thus, the thread can be blocked all day long without impeding on your main application thread). Once data has been received, it can broadcast an event noting that data has been received and what that data is. The thread would communicate with the main application thread through the event.

Michael