Nishikant Tayade

Nishikant Tayade

  • NA
  • 22
  • 8.3k

Sending hex data to serial port

Jun 2 2018 5:56 AM
I am trying to send the hex data to serial port where i have connected data logger and the response of that data logger has already been coded.
so I just need to send the correct hex data so that to get that output and display it on the console.

The code is compiling but there is no data received.
 
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SerialPortHexCommunication
{
public class Program
{
static void Main(string[] args)
{

SerialPort port = new SerialPort();
port.PortName = "COM5";
port.Parity = Parity.None;
port.BaudRate = 9600;
port.DataBits = 8;
port.StopBits = StopBits.One;
// port.Handshake = Handshake.RequestToSend;
// port.ReceivedBytesThreshold = 8;
if (port.IsOpen)

{
port.Close();
port.Dispose();
}

byte[] bytesToSend = new byte[6] { 0xD0,0xF2,0xFF,0x00,0x06,0xC7 }; //$D0 $F2 $FF $00 $06 $C7
port.Open();
port.Write(bytesToSend,0,bytesToSend.Length);



port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
port.Close();
port.Dispose();

}

private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = (SerialPort)sender;

int bytes = port.BytesToRead;
byte[] buffer = new byte[bytes];

if (port.BytesToRead > 1)
{

port.Read(buffer, 0, bytes);
}

foreach (byte item in buffer)
{
Console.WriteLine(item);
Console.ReadKey();
}

//string indata = port.ReadExisting();
//Console.WriteLine("Data received");
//Console.WriteLine(indata);
//Console.ReadKey();
}
}
}

 

Answers (1)