无法从串行端口接收数据

时间:2019-08-26 09:01:27

标签: c# serial-port

[未解决]

我正在尝试接收数据并将其写入txt文件,我检查了此post并正确添加了eventHandler。开启顺序等是相同的。但是,即使尝试打印(在SerialPort_DataReceived内部),我也无法接收任何数据。我无法接收数据。

  

p.CmdSerialPort.DataReceived始终为null,无论我如何更改。

有人可以帮忙吗?

 class Program
{

    private System.IO.Ports.SerialPort CmdSerialPort;
    private StreamWriter swLog;
    private DateTime lastComm = DateTime.MinValue;
    private UdpClient udpClient_Cmd;
    private volatile bool _enabled_Cmd;
    public static int Ethernet_Packet_Header_Length = 14;
    public IPAddress IP { get; protected set; }
    public int Cmd_Port { get; protected set; }
    static void Main(string[] args)
    {
        Console.WriteLine("Please Enter Parameters: ");
        Program p = new Program();
        p.IP = IPAddress.Parse("....");//IP

        p.CmdSerialPort = new SerialPort();
        p.CmdSerialPort.Handshake = Handshake.None;
        p.CmdSerialPort.BaudRate = 9600;
        p.CmdSerialPort.Parity = Parity.None;
        p.CmdSerialPort.StopBits = StopBits.One;
        p.CmdSerialPort.DataBits = 8;

        //takes port, ethernet and filename inputs
        string s = Console.ReadLine();
        string[] input = s.Split(' ').ToArray();

        if (input.Length > 3)
            Console.WriteLine("Wrong input size!");

        string filename = input[2];//takes filename 
        //DEFAULT PATH ROOT
        String root = @".\\";
        string path_combined;

        filename += ".txt";
        path_combined = Path.Combine(root, filename);

        try
        {

            if (p.TryConnect(input[0]))//takes port name  eg.COM9
                p.swLog = File.CreateText(path_combined);

        }
        catch (System.IndexOutOfRangeException ex)
        {
            System.ArgumentException argEx = new System.ArgumentException("File creation failed!", ex);
            throw argEx;
        }



        p.Cmd_Port = Int32.Parse(input[1]);//takes port number  eg.4667

        p.Initialize();

        Console.ReadKey();

        p.Close2();

        p.Close();


    }//end of main

    ////////////////////////////////////////////////////////////
    // SERIAL PORT 
    ////////////////////////////////////////////////////////////

    private bool TryConnect(string portName)
    {

        try
        {

            CmdSerialPort.PortName = portName;
            CmdSerialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(SerialPort_DataReceived);
            CmdSerialPort.Open();

            if (CmdSerialPort.IsOpen)
            {

                return true;

            }
            return false;

        }
        catch (UnauthorizedAccessException e)
        {

            Debug.WriteLine(e.ToString());

            Debug.WriteLine(e.Message);

            return false;

        }

        catch (ArgumentOutOfRangeException e)
        {

            Debug.WriteLine(e.ToString());

            Debug.WriteLine(e.Message);

            return false;
        }
        catch (ArgumentException e)
        {

            Debug.WriteLine(e.ToString());

            Debug.WriteLine(e.Message);

            return false;

        }

    }

    internal void Close2()
    {
        if (CmdSerialPort.IsOpen)
        {

            CmdSerialPort.Close();

        }

        swLog.Close();

        swLog = null;

    }



    private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {

        lastComm = DateTime.Now;

        if (sender is SerialPort sp)
        {

            string indata = sp.ReadExisting();

            indata = indata.Trim(' ').Trim('\n').Trim('\r');

            WriteToFile($"{CmdSerialPort.PortName}\t{lastComm}\t{indata}");

        }

    }

    private void WriteToFile(string v)
    {

        swLog.WriteLine(v);

    }

}

0 个答案:

没有答案