tags:

views:

55

answers:

3

hi i have a problem i am writing a code in C# i wanna receive a byte from serial port but when i wanna receive data from port that sounds my program is hang and doesnt work any more

 SerialPort port = new SerialPort("COM3");
 port.Open();
 byte[] b = new byte[10];
 port.Read(b, 0, 1);
 port.Close();

please help me

A: 

Is there actually any data being sent over the serial port? The call to Read might just be waiting to receive some data before returning. Make sure that you have set a value for the ReadTimeout property. This will make the call to Read throw a TimeoutException if no data was read from the port.

Reference: http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readtimeout.aspx

ar
A: 

Also make sure you set the serial speed right (if you're reading too fast you'll miss some data, etc)

lorenzog
A: 

This is because SerialPort reads data synchronously and blocks current thread until the data would be available.

You can use separate thread for this:

public class SerialPort : IDisposable
{
    public SerialPort(byte comNum, int baudRate)
    {
        this.comNum = comNum;
        serialPort = new System.IO.Ports.SerialPort("COM" + comNum.ToString(), baudRate);
        serialPort.Open();
        thread = new System.Threading.Thread(ThreadFn);
        thread.Start();
    }
    public void Dispose()
    {
        if (thread != null)
           thread.Abort();
        if (serialPort != null)
           serialPort.Dispose();
    }

    private void OnReceiveByte(byte b)
    {
        //handle received byte
    }

    private void ThreadFn(object obj)
    {
        Byte[] inputBuffer = new Byte[inputBufferSize];
        while (true)
        {

            try
            {
                int availibleBytes = serialPort.BytesToRead;
                if (availibleBytes > 0)
                {
                    int bytesToRead = availibleBytes < inputBufferSize ? availibleBytes : inputBufferSize;
                    int readedBytes = serialPort.Read(inputBuffer, 0, bytesToRead);
                    for (int i = 0; i < readedBytes; i++)
                        OnReceiveByte(inputBuffer[i]);
                }
                System.Threading.Thread.Sleep(1);
            }
            catch (System.Threading.ThreadAbortException)
            {
                break;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.Assert(false, e.Message);
            }
        }
    }
    private Byte comNum;
    private System.IO.Ports.SerialPort serialPort;
    private System.Threading.Thread thread;
    private const int inputBufferSize = 1024;
}
Sergey Teplyakov