Example code for saving and retrieving a string from system.storage #2345
Replies: 5 comments 2 replies
-
|
Fixed sized strings would be the easiest. Save: # my_str is always 3 ASCII characters so encoding is always 3 bytes.
my_str = "XYZ"
hub.system.storage(0, my_str.encode())Restore: my_str = hub.system.storage(0, read=3).decode()Variable-length strings require a bit more work since you will need to add some padding to make sure it writes over any previous string that was longer with zeros. Save: MAX_STR_SIZE = 10
my_str = "XYZ"
encoded = my_str.encode()
hub.system.storage(0, write=encoded + "\0" * (MAX_STR_SIZE - len(encoded)))Restore: MAX_STR_SIZE = 10
my_str = hub.system.storage(0, read=MAX_STR_SIZE).decode().strip("\0") |
Beta Was this translation helpful? Give feedback.
-
|
Perfect, thank you! |
Beta Was this translation helpful? Give feedback.
-
|
Now I've tried the code, it claims that str does not have a encode() method: AttributeError: 'str' object has no attribute 'encode' I've just updated the hum to the latest firmware in case that was the issue but to no avail. |
Beta Was this translation helpful? Give feedback.
-
|
Here is an example that stores a string with arbitrary size. from pybricks.hubs import ThisHub
hub = ThisHub()
def store_string(string):
length = len(string).to_bytes(4, "little")
hub.system.storage(0, write=length)
hub.system.storage(4, write=bytes(string, "utf-8"))
def load_string():
length = int.from_bytes(hub.system.storage(0, read=4), "little")
return str(hub.system.storage(4, read=length), "utf-8")
# Example
store_string("Hello, world!")
result = load_string()
print(result) |
Beta Was this translation helpful? Give feedback.
-
|
Thank you Laurens, worked a treat, although the to_/from_bytes methods seemed to need a byteorder parameter. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Is there any example code around to encode a string so it can be saved in system.storage, then retrieved later and converted back to a string?
Thanks
Beta Was this translation helpful? Give feedback.
All reactions