[英]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.