繁体   English   中英

无法从串口读取代码

[英]code not reading from serial port

美好的一天,

我已经尽一切努力从csharp的xbee模块中读取了一些字符串。 但是我的代码不断告诉我,串行端口在到达事件处理程序时未打开。 任何帮助将不胜感激。 谢谢string display = myserial.ReadLine();

操作异常

using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace ConsoleApplication2
{
    class Program
    {
        public static  SerialPort myserial = new SerialPort();
        public string display;
        static void Main(string[] args)
        {
            string[] ports = SerialPort.GetPortNames();
            foreach (string p in ports)
            {
                Console.WriteLine(p);
            }
            SerialPort myserial = new SerialPort();

            myserial.BaudRate = 9600;
            myserial.Parity = Parity.None;
            myserial.StopBits = StopBits.One;
            myserial.DataBits = 8;
            myserial.Handshake = Handshake.None;
            myserial.RtsEnable = true;
            myserial.DtrEnable = true;
            myserial.ReadTimeout = 100000;
            myserial.PortName = "COM3";
            myserial.ReadTimeout = 10000;
            myserial.DataReceived += new SerialDataReceivedEventHandler(DataRecievedHandler);
            myserial.Open();
            if (myserial != null)
            {
                if (myserial.IsOpen)
                {
                    Console.WriteLine("connected");
                }
            }
            Console.ReadLine();
        }
   static void DataRecievedHandler(object sender, SerialDataReceivedEventArgs e)
        {
           string display = myserial.ReadLine();
        }

    }
} 

您的问题是您的代码中存在歧义。 2个具有相同名称的变量。

您在main外部声明的类变量:

class Program
{
    public static  SerialPort myserial = new SerialPort();

以及main方法中的变量:

static void Main(string[] args)           
{
    SerialPort myserial = new SerialPort();

在方法内部,编译器将使用局部变量myserial 您打开它并注册事件:

myserial.DataReceived += new SerialDataReceivedEventHandler(DataRecievedHandler);

到目前为止,一切都很好。 但外界Main方法,这SerialPort myserial 存在。 这意味着,当您尝试在DataRecievedHandler方法内访问myserial ,编译器会“认为”您是指类级别的第一个变量! 但是此SerialPort从未打开过! 因此,它给您错误。

您可以通过使用事件内部的sender对象来解决此问题。 由于打开的SerialPort会触发此事件:

static void DataRecievedHandler(object sender, SerialDataReceivedEventArgs e)
{  
    SerialPort port = sender as SerialPort;

    if(port != null)
    {    
        string display = port.ReadLine();
    }
}

注意:此变量display仅存在于DataRecievedHandler方法内部。 您不能在主体上使用它。 因为您再次声明。 这是一个局部变量,与您在类级别上声明的变量不同! 删除string ,将使用类级别变量:

做了:

display = port.ReadLine();

2。

您也可以通过简单地删除Main方法中SerialPort myserial变量的声明来解决此问题。 可能会更简单;)只需在Main方法中删除以下行即可:

SerialPort myserial = new SerialPort();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM