我在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在当前上下文中不存在
请提出一些建议。
答案 0 :(得分:1)
当前上下文中存在错误port_OnReceivedDatazz
事件处理程序的名称和事件处理程序方法必须对应!
你基本上有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));
}