C# 无法读取COM3端口。始终输出为0

C# 无法读取COM3端口。始终输出为0,c#,serial-port,C#,Serial Port,此代码可以运行,但即使设备具有某些值,它也只打印0。该装置是一台辊道机,应将辊道计量器送至3号端口;但是,我的代码总是将输出读取为0 using System; using System.Text; using System.IO.Ports; using System.Collections.Generic; namespace ConsoleApplication3 { class Program { static SerialPort sp;

此代码可以运行,但即使设备具有某些值,它也只打印0。该装置是一台辊道机,应将辊道计量器送至3号端口;但是,我的代码总是将输出读取为0

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);
        }
    }
}

代码
Console.WriteLine(“值-”+sp.Read(缓冲区,0,字节))始终打印0

执行这行代码时
Console.WriteLine(“Value-”+sp.Read(缓冲区,0,字节))
您不能保证有接收到的字节可以读取,您应该只依赖事件处理程序
lsp\u DataReceived

谢谢Abdullah!我已经按照我的能力调试了这里的所有东西,但是没有运气。如果您能帮助我返回正确的值,我们将不胜感激。您是否通过事件处理程序收到任何数据?