Blob assignment of multiple bytes


#1

I’m creating blobs to send to a uart.write. I’d like to be able to assign multiple bytes at once, but that generates an error when I use the result with uart.write. Apparently it generates a blob that is not a blob. I tried this:

local mod_blob = blob()
mod_blob = [254,65,0,128,1,16,40,126]

It doesn’t complain until I try to use the result in a uart.write where it complains about bad parameters.
So I have to do this instead:

mod_blob.writen(254,‘b’)
mod_blob.writen(65,‘b’)
mod_blob.writen(0,‘b’)
mod_blob.writen(128,‘b’)
mod_blob.writen(1,‘b’)
mod_blob.writen(16,‘b’)
mod_blob.writen(40,‘b’)
mod_blob.writen(126,‘b’)

Which the uart.write likes.

Is there a more compact way to make multi-byte assignments to a blob than individual writen statements?


#2

This doesn’t write to the blob. It changes the mod_blob variable to refer to an array of integer values, instead.

There doesn’t appear to be a constructor that takes an array, or a method that converts from array to blob. I think (but could be wrong) that writen is the best way to do this.

If you’re prepared to take a hit on readability, and you pay attention to byte-ordering (endianness), you can probably write 4 bytes (or even 8, if you’re prepared to monkey around with floats) at a time.


#3

You could try:

local mod_blob = blob()
mod_blob.writestring("\xFE\x41\x00\x80\x01\x10\x28\x7D")

PS You might want to double check those hex values


#4

Thanks for that idea. I hadn’t though of using a byte string. Makes it compact and maintains readability.


#5

The byte string is also immutable, so will get stored in program storage.

If the string doesn’t need to be changed, you can just write strings to the UART too and skip the blob step. Unlike C strings, squirrel strings can include nulls etc.


#6

Good to know. But in this case, I’m building a unique string which has a few standard parts. This is one of those parts. The byte string works perfectly.