Samsad Hasan

Samsad Hasan

  • NA
  • 10
  • 478

Not able to read COM3 port. Always output is 0

Mar 25 2017 2:20 AM

This code is able to run, however it only return 0 even though the device has some value. The device is a roller machine where it should give the rolling meter value to the port number 3 however, my code always return the output as 0.

Please help me as soon as possible as this is a critical requirement.

  1. using System;  
  2. using System.Text;  
  3. using System.IO.Ports;  
  4. using System.Collections.Generic;  
  5. namespace ConsoleApplication3  
  6. {  
  7.     class Program  
  8.     {  
  9.         static SerialPort sp;  
  10.         string InputData = string.Empty;  
  11.         static void Main(string[] args)  
  12.         {  
  13.             sp = new SerialPort("COM3", 4800, Parity.None, 8, StopBits.One);  
  14.             sp.DiscardNull = false;  
  15.             sp.RtsEnable = true;  
  16.             sp.ReadTimeout = 500;  
  17.             sp.Handshake = Handshake.None;  
  18.             sp.Encoding = Encoding.UTF8;  
  19.             sp.DtrEnable = true;    
  20.             sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);              
  21.             sp.Open();  
  22.             //sp.DataReceived += sp_DataReceived;  
  23.             string InputData = sp.ReadExisting();  
  24.             while (sp.IsOpen)  
  25.             {  
  26.                 try  
  27.                 {  
  28.                     System.Threading.Thread.Sleep(300);  
  29.                     int bytes = sp.BytesToRead;  
  30.                     byte[] buffer = new byte[bytes];  
  31.                     Console.WriteLine("Value - " + sp.Read(buffer, 0, bytes));  
  32.                 }  
  33.                 catch (Exception ex)  
  34.                 {  
  35.                     Console.WriteLine(ex.Message);  
  36.                 }  
  37.             }  
  38.         }  
  39.         private static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)  
  40.         {  
  41.             SerialPort sport = (SerialPort)sender;  
  42.             string indata = sport.ReadExisting();  
  43.             Console.WriteLine(indata);  
  44.         }  
  45.     }  
  46. }