串口与电表和串口在c#中通信

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

我在 COM5 上通过 USB 连接了一个电表。

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

因此,我正在使用 SerialPort class 和 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 does not exist in the current context

请给点建议。

There is error port_OnReceivedDatazz does not exist in the current context

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

你基本上有 2 个选项,或者重命名此行:

sp.DataReceived += port_OnReceiveDatazz; // event handler

至:

sp.DataReceived += SerialDataReceivedEventHandler;

或重命名方法

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

编辑:

如果您仍然没有看到所需的输出,可能是因为 Console.ReadLine() 阻止控制台并阻止其打印。

MSDN Example 他们使用

Console.ReadKey();

参考 this answer

正如最后所说,您永远不会永久保存接收到的数据,因为您使用局部变量来存储输入:

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));


}