I2C.write binary data

What is the best way to write binary data over i2c? The i2c.write function only seems to take a string for its second argument. Its easy to create strings in the form “\x01\x02” but this only works for literal stings defined at compile time.

How to you create a binary string at run time?

using i2c.write(0x08, “\xA5”); works fine but

I tried just using string format to create strings as follows

Val = 0xA5;

str = format("\x%2X", Val);

or

str = format(“0x%2X”, Val);

but when you write them using I2C its just writes all the individual characters

‘\’, ‘x’, ‘A’, ‘5’ for the first case

or ‘0’, ‘x’, ‘A’, ‘5’ for the second

How can I build a string with binary data?

You use %c, eg str=format("%c%c%c", 0xa5, 0xd3, 0x00)

Note that squirrel strings can include NULL characters (unlike C strings) so you can send any binary value like this.

You should put this tip in the I2C.write info.
It would have saved me a lot of time.
Kurt

Don’t forget tochar()
If you have
Val = 0xA5;
then Val.tochar() will give you “\xA5”

Fair point, @smittytone could you add some examples that show using format to build a binary string from variables?

That’s done: https://developer.electricimp.com/api/hardware/i2c/write