繁体   English   中英

串口与电表和C#中的串口通讯

[英]Serial Port Communication with electric meter and serial port in c#

我有一个通过COM5上的USB连接的电表。

我想从仪表读取数据,但首先要检查它是否正常工作。 意味着如果我在端口上写一些东西,我将再次发送和接收。

因此,我正在使用SerialPort类和DataReceived事件处理程序。

我的代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace Communication
{
    class Program
    {
        static void Main(string[] args)
        {
            const int bufSize = 2048;
            Byte[] but = new Byte[bufSize]; // to save receive data

            SerialPort sp = new SerialPort("COM5");
           sp.BaudRate = 9600;
           sp.Parity = Parity.None;
           sp.StopBits = StopBits.One;
           sp.DataBits = 8;
           sp.Handshake = Handshake.None;
           sp.DtrEnable = true;
           sp.RtsEnable = true;
           sp.Open(); //open the port
            sp.DataReceived += port_OnReceiveDatazz; // event handler

           sp.WriteLine("$"); //start data stream
           Console.ReadLine();
           sp.WriteLine("!"); //stop data  stream
           sp.Close(); //close the port
        }
        //event handler method
        public static void SerialDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort srlport = (SerialPort)sender;
            const int bufSize = 12;
            Byte[] buf = new Byte[bufSize];
            Console.WriteLine("Data Received!!!");
            Console.WriteLine(srlport.Read(buf,0,bufSize));
        }

    }
}

编译时出现此错误:

当前上下文中不存在port_OnReceivedDatazz

请给一些建议。

当前上下文中不存在错误port_OnReceivedDatazz

事件处理程序的名称和事件处理程序的方法必须对应!

您基本上有2个选项可以重命名此行:

sp.DataReceived += port_OnReceiveDatazz; // event handler

至 :

sp.DataReceived += SerialDataReceivedEventHandler;

或重命名方法

public static void port_OnReceiveDatazz(object sender, SerialDataReceivedEventArgs e)
{

编辑:

如果仍然看不到所需的输出,则可能是Console.ReadLine()阻止了控制台并阻止其打印。

MSDN示例中,他们使用

Console.ReadKey();

作为参考,请参见此答案

就像最后一句话一样,您永远不会永久保存收到的数据,因为您使用本地变量来存储输入:

Byte[] buf = new Byte[bufSize];
srlport.Read(buf,0,bufSize);

您应该在此行中使用数组:

Byte[] but = new Byte[bufSize]; // to save receive data

当您读取数据时,使用but数组:

srlport.Read(but,0,bufSize);

编辑2:

如果要打印收到的内容,则需要打印使用Read方法填充的数组的内容:

//event handler method
public static void SerialDataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort srlport = (SerialPort)sender;
    const int bufSize = 12;
    Byte[] buf = new Byte[bufSize];
    Console.WriteLine("Data Received!!!");
    int bytes_read = srlport.Read(buf,0,bufSize)
    Console.WriteLine("Bytes read: " + bytes_read);

    // you can use String.Join to print out the entire array without a loop
   Console.WriteLine("Content:\n" + String.Join(" ", bud));


}

暂无
暂无

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

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