本文介绍了无法读取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.





我尝试过:





What I have tried:

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

推荐答案


这篇关于无法读取COM3端口。始终输出为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 05:49