0
votes

Recently i want to connect and read data from Serial Port Using SerialPort Class in C#. I have a time attendance machine named RTA600 from Hundura. it is connected to my PC via serial-to-USB convertor. the code i have tested as follows

SerialPort serialPort1 = new SerialPort();    
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.RtsEnable = true;

// Open the Serial Port
serialPort1.Open();  

// Read Data from Serial port
string RXstring = serialPort1.ReadLine();

I use SerialPort Class of System.Io.Ports namespace. But it code hangs when serialPort1.ReadLine() executes. Can Some give me a idea how can i read the data from by time machine through serial-to-usb convertor

1
The ReadLine statement will block the code until a newline is received from the device. As suggested in the answers below, use the DataReceived event instead. - nicholas

1 Answers

0
votes

You can use ReadExisting() to read the whole data at a time. You need to handle DataReceived Event of SerialPort

serialPort1.ReadExisting();

Sample:

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
           String myData=serialPort1.ReadExisting();
        }

Example Code: Here i would like to show you the code to Read Data(RFID Tag Code which is basically of length 12)

        String macid  = "";
        private void DoWork()
        {
            Invoke(
                  new SetTextDeleg(machineExe ),
                  new object[] { macid  });
            macid  = "";
        }
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {

            string str1;
            macid += serialPort1.ReadExisting();

            if (macid.Length == 12)
            {
                macid = macid.Substring(0, 10);
                Thread t = new Thread(new ThreadStart(DoWork));
                t.Start();
            }
        }

         public void machineExe(string text)
          {
            TextBox1.Text=text;
          }