I have an Electric meter connected over USB on COM5.
I want to read data from the meter but first check whether it's working or not. Means if I write something over the port I will send and receive again.
So, I am using the SerialPort
class and the DataReceived
event handler.
My code is below.
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));
}
}
}
When compiling I get this error:
port_OnReceivedDatazz does not exist in the current context
Please give some suggestion.