Salman Mushtaq Salman Mushtaq - 1 year ago 153
C# Question

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

I have USB connected with COM5 and on other side it will connected with Electric meter.

I want to read data from meter but first check whether it's working or not means If I write something on port it will send and receive again.

So, I am using SerialPort Classes and 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
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!!!");


There is error port_OnReceivedDatazz does not exist in the current

Please give some suggestion.

Answer Source

There is error port_OnReceivedDatazz does not exist in the current context

The name of your event handler and your event handler method have to correspond!

You have basically 2 Options either rename this line:

sp.DataReceived += port_OnReceiveDatazz; // event handler

to :

sp.DataReceived += SerialDataReceivedEventHandler;

OR rename the method

public static void port_OnReceiveDatazz(object sender, SerialDataReceivedEventArgs e)


if you still don't see the desired output it might be that Console.ReadLine() blocks the console and prevents it from printing.

In the MSDN Example they use


For Reference see this answer.

Just as last remark, you never save your received data permanently since you use a local variable for storing the input:

Byte[] buf = new Byte[bufSize];

You should use the array from this line:

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

When you read your data take the but array:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download