从C#中的串行端口DataReceived方法读取数据

时间:2016-08-03 12:54:37

标签: c# serial-port

我正在编写一个程序来读取串口设备。当在设备上点击接受键时,它会将数据写入串口。但是我得到一些不可读的字符串作为输出

N?N?{w?¦?g?o?s?~?o?N?s?s?s?nN?N?c{{?O^L_?¦?s?s?N?c{s?N?s?{?o?s?N?~?g?^w?f?g?¦?{?

我已经尝试了所有可能的字符串,字节,十六进制转换方法,但我无能为力。以下是我在c#

中的源代码的一些部分
static void Main(string[] args)
    {
        SerialPort mySerialPort = new SerialPort("COM8");
        //var p = new Program();
        mySerialPort.BaudRate = 2400;
        mySerialPort.Parity = Parity.Even;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 7;
        mySerialPort.Handshake = Handshake.XOnXOff;
        //mySerialPort.RtsEnable = true;
        //mySerialPort.DtrEnable = true;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        mySerialPort.PinChanged += new SerialPinChangedEventHandler(PinChangedHandle);
         mySerialPort.Open();

    }

 private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            SerialPort sp = (SerialPort)sender;
            //Get the number of bytes data in the receive buffer
            byte[] indata = new byte[sp.BytesToRead];

            //Get the buffer size
            int dataSize = sp.ReadBufferSize;

           // Console.Write(sp.ReadExisting());

            //Read byte and write bytes into indata
            sp.Read(indata, 0, indata.Length);
            StringBuilder sb = new StringBuilder(indata.Length*2);

            foreach (byte b in indata)
            {
                sb.AppendFormat("{0}", Convert.ToChar(b));
            }
            Console.Write(sb.ToString());
            writeToLog(sb.ToString()); // writes to a text file

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.Read();

        }

    }

我需要帮助。我不知道是否有人通过类似的经历进行了扩展并且愿意帮忙...我真的很感激

0 个答案:

没有答案