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

时间:2017-03-24 17:51:19

标签: 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;
        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("Value - " + sp.Read(buffer, 0, bytes));始终打印为0.

1 个答案:

答案 0 :(得分:0)

在执行这行代码Console.WriteLine("Value - " + sp.Read(buffer, 0, bytes));时,您不能保证有接收的字节要读取,您应该只依赖于事件处理程序lsp_DataReceived