0

I want send hex value through serial port.

The device manual shows that data should be like this:

Protocol sent ’ENQ’ ’0’ ’0’ ’3’ ’,’ ’0’ ’0’ ’0’ ’ETX’        
Hexadecimal    05   30   30  33  2C  30  30  30   03

The code:



    _serial.BaudRate = 9600;
    _serial.Parity = Parity.None;
    _serial.DataBits = 8;
    _serial.StopBits = StopBits.One;
    _serial.Open();

    byte[] bytesToSend = new byte[9] { 05,30, 30, 33 , 2C , 30 , 30 , 30 , 03 }; // This should be represent bytes equivalent to hex value

    _serial.Write(bytesToSend,0,9);


i know that i should send this using byte array but i don't know how to represent the hex value in data byte array.

2
  • 2
    Just put 0x in front of your values. Like 0x05 and 0x2C. Commented Aug 19, 2014 at 21:07
  • @Donal The question is not about converting a string to a byte array. Commented Aug 19, 2014 at 21:22

1 Answer 1

1

Based on the example you provided, your device wants data encoded as ASCII. 0x30 = '0' in ASCII.

And as others have said, you use '0x' to denote hexadecimal values.

for a generic message that begins with ENQ and ends with ETX:

ASCIIEncoding asciiEncoding = new ASCIIEncoding();

string msg= "003,000";
byte[] msgBytes = asciiEncoding.GetBytes(msg);

byte[] bytesToSend = new byte[msgBytes.Length +2];
bytesToSend[0] = 0x05;
bytesToSend[bytesToSend.Length -1] = 0x03;
Buffer.BlockCopy(msgBytes, 0, bytesToSend, 1, msgBytes.Length);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.