Не в состоянии прочитать порт COM3. Всегда выход равен 0
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.
Что я уже пробовал:
using System; using System.Text; using System.IO.Ports; using System.Collections.Generic; namespace ConsoleApplication3 { class Program { static SerialPort sp; string InputData = string.Empty; static void Main(string[] args) { sp = new SerialPort("COM3", 4800, Parity.None, 8, StopBits.One); sp.DiscardNull = false; sp.RtsEnable = true; sp.ReadTimeout = 500; sp.Handshake = Handshake.None; sp.Encoding = Encoding.UTF8; sp.DtrEnable = true; sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived); sp.Open(); //sp.DataReceived += sp_DataReceived; string InputData = sp.ReadExisting(); while (sp.IsOpen) { try { System.Threading.Thread.Sleep(300); int bytes = sp.BytesToRead; byte[] buffer = new byte[bytes]; Console.WriteLine("Value - " + sp.Read(buffer, 0, bytes)); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } private static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort sport = (SerialPort)sender; string indata = sport.ReadExisting(); Console.WriteLine(indata); } } }