# Writing Hex to Serial

Hi all!

I’m communicating with a serial device which wants values in hex bytes. hence If I want to send e.g. 45 in hex, I have to

1: create a string: “&h45”
2: get decimal value of that string: theDecimalValue = val("&h45")
3: serial1.Write chrb(theDecimalValue)

is there a more elegant way? It’s probably as simple as 1,2,3 but hex, decimal and binary is annoying

thanks!

what code leads up to the point where you know you need to write hex 45 ?
There may be a more elegant way but knowing how you determine that you need to send &h45 might be relevant

DecodeHex function may help.

or maybe better use memory blocks:

```dim m as new memoryblock(4) m.Int8Value(0) = &h45 m.Int8Value(1) = 12 m.Int8Value(2) = 34 m.Int8Value(3) = 56 serial1.Write m```

to send a package with 4 bytes in this case.

[quote=244702:@Norman Palardy]what code leads up to the point where you know you need to write hex 45 ?
There may be a more elegant way but knowing how you determine that you need to send &h45 might be relevant[/quote]

There’s a table of commands to send, so e.g. &h45 does one thing and &h49 does another, and some take a decimal value that has to be split in two hex bytes, so e.g. 350 (15E) must be sent as &h01 &h5E …

would seem a lookup table configured at app start up would work

then still variable values need to go through decimalVal = val(&hXX) and then serial.write chrb(decimalVal) … not that bad anyway.

thanks!

You don’t need to convert to decimal. `ChrB(&hXX)` will work just fine.

Only up to values of 255 (&hFF). Beyond that, you have to do some math.

``````dim s as string

if n >= 256 then
dim m as integer = n \\ 256
n = n mod 256
serial1.Write ChrB( m )
end if

serial1.Write ChrB( n )``````

Or something like that. I’m still a little unclear about what the receiver is wanting.

Thanks to all, memoryblock worked just fine…

cheers and Xojo is awesome!

[quote=244730:@Shant Khatcherian]then still variable values need to go through decimalVal = val(&hXX) and then serial.write chrb(decimalVal) … not that bad anyway.

thanks![/quote]

I’d actually create a class that has each command listed that can give you back the right bytes for the command + parameters

Stuff the parameters into a memoryblock and then write the memoryblock using bytes

Hi
I use structures for data send.
Structure DATA
start as uint8
value as byte
End Structure

Dim a as DATA
a.start=chr (&h45)
a.value=a.start.val
serial.write a.stringvalue (true)

I’m not sure if its literally like this. (I’m writing it from memory)

regards
Kris