代码不从串口读取

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 个同名变量。

你在主函数外声明的class变量:

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

和main方法中的变量:

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

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

myserial.DataReceived += new SerialDataReceivedEventHandler(DataRecievedHandler);

到目前为止一切都很好。但在 Main 方法之外,此 SerialPort myserial 存在。这意味着当您尝试在 DataRecievedHandler 方法中访问 myserial 时,编译器 "thinks" 是指 class 级别的第一个变量!但是这个SerialPort从来没有打开过!因此它给你错误。

你可以使用事件中的sender对象来解决它。由于打开 SerialPort 触发此事件:

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

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

注意:这个变量display只存在于DataRecievedHandler方法中。你不能在 main 中使用它。因为你又声明了。这是一个局部变量,与您在 class 级别声明的不同!删除 string 将使用 class 级别变量:

成功:

display = port.ReadLine();

2.

您也可以通过简单地删除 Main 方法中的 SerialPort myserial 变量的声明来解决它。可能会更简单;) 只需删除 Main 方法中的这一行:

SerialPort myserial = new SerialPort();