Click here to Skip to main content
14,828,290 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
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.

What I have tried:

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();
        }
    }
}
Posted
Updated 4-Dec-20 1:24am
v2
Comments
[no name] 2-Jun-18 6:59am
   
Think about this sequence:

port.Open();
port.Write(bytesToSend,0,bytesToSend.Length);

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


Among many other things...
a.) Set the receive handler before you write
b.) You write to the port and more or less imediatelly you Close the port. That will not work, at least you Need to wait for the answer before closing the port ;)
Nishikant Tayade 2-Jun-18 7:03am
   
I tried it,but still not working.Can you please elaborate.It will be really helpful
Nishikant Tayade 2-Jun-18 7:13am
   
so i tried it again and it is giving output as 224.
But when i sent the same hex( $D0$F2$FF$00$06$C7) with terminal then it is giving output as E0 F2 01 00 3C 25 82 00 00 EA 95 20 01 2E 23 17 70 20 01 2C 23 17 70 20 01 36 23 17 70 20 01 2E 23 17 70 23 03 E8 23 03 E8 23 03 E8 23 03 E8 23 03 E8 23 03 E8 23 03 E8 23 03 E8 8F
that 224 is E0,but what about rest of it?
[no name] 2-Jun-18 7:20am
   
What do you type in exactly in terminal?
In case you type in "$D0$F2$FF$00$06$C7" you Need also to send the same string in your code.At the Moment in your code you send this as 6 Bytes and not as hex coded strings.

You can try/verify this when you send exactly the same string in your code like you send it with the terminal.
[no name] 2-Jun-18 8:01am
   
Btw. another thing for which I faced a lot of problems in praxis and the following pragmatic approach helped me a lot: Before closing the port I suggest to do this port.DataReceived -= DataReceivedHandler;
Nishikant Tayade 2-Jun-18 8:12am
   
I did what you said earlier,now the program is getting compiled and executing but it shows output only when it is in debug mode,otherwise it just get terminated after executing without any output on the console.
[no name] 2-Jun-18 8:16am
   
Put something like this Console.ReadKey(); at the end of static void Main(string[] args), otherwhise you will not see the output
Nishikant Tayade 2-Jun-18 8:20am
   
Already done that.But still the same
[no name] 2-Jun-18 8:22am
   
To help you, you should post your revised code.

Quote:
The code is compiling but there is no data received.

I fear your problem is that serial port is slooow, but you close the port immediately after sending your data.
You need to keep the port open to give it a chance to receive data from logger.

Since serial port is slow, the handler will be called as data is still coming from logger, before answer is complete.
It is a bad idea to have the handler messing with console and waiting for user input.

Tutos about serial port are available on internet, you need to study the serial port principles because you have another problem, your prograzm is finished before receiving the answer.
Your problem is not just the code to receive data, it is the whole program.
   
Comments
Nishikant Tayade 2-Jun-18 7:55am
   
I have made some changes and now its is showing the output.Thanks for the response.
Patrice T 2-Jun-18 7:59am
   
You are welcome.
If problem is solved, accept the solution to close the question, or post your own solution ans accept.
If 0x01AA have helpful, tell him to post a solution.
[no name] 2-Jun-18 8:08am
   
I think your answer is pretty ok, 5
Patrice T 2-Jun-18 8:14am
   
Thank you.
I think you spend some effort too discussing with OP
[no name] 2-Jun-18 8:20am
   
It is ok like this. I do this mostly to keep my old (55Y) brain trained :-)
Patrice T 2-Jun-18 8:29am
   
Same age for me.
I am actually training my brain with this one: https://www.codeproject.com/Questions/1246743/Cutting-stock-optimization
Finally I decided to write a solution, may be more an answer.
Please see all the comments and also the answer of @ppolymorphe

In case you are interesting in the Details I suggest to read this from @glennPattonWork
Serial Comms in C# for Beginners[^]
   
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;
          
            if (port.IsOpen)

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

            byte[] bytesToSend = new byte[6] { 0xD0, 0xF2, 0xFF, 0x00, 0x06, 0xC7 };

            port.Write(bytesToSend, 0, bytesToSend.Length);

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

            
           

        }

        private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
        {
            Console.WriteLine("In data receive");
            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();
        }
    }
}
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900