ardupilot icon indicating copy to clipboard operation
ardupilot copied to clipboard

AP_Scripting: Adds I2C transfer() bindings and an example

Open IanBurwell opened this issue 1 year ago • 4 comments

Adds LUA bindings for the I2CDevice transfer() function. This is often needed over write_register() as I2C devices might not have 8 bit registers or desire some other custom transfer.

An example script is also added that allows shutdown of a BQ40Z bms chip which would not be possible with LUA without the transfer() function. This script has functionality similar to a sibling PR that implements such functionality more generally in the AP_BattMonitor domain.

IanBurwell avatar Jun 12 '24 14:06 IanBurwell

Sibling PR: #27288

IanBurwell avatar Jun 12 '24 14:06 IanBurwell

How do you feel about a string vs the tables? The pack and unpack string functions are very powerful for extracting values with the correct format. Its a shame we have the table precedent in the existing read function.

IamPete1 avatar Jun 13 '24 16:06 IamPete1

I hadn't considered taking/returning a string which would be more memory efficient, and it would totally be satisfying to be able to do something like

local some_uint32 = string.unpack("<I4", dev:transfer(string.pack("b", 0xAB), 4))

where the string.unpack in handling the byte assembly into a uint32.

But there is also a nice simplicity with using tables. If I wanted just one byte back after a multi byte write it seems like a bit much to do:

local some_byte = string.unpack("b", dev:transfer(string.pack("bbb", 0xAB, 0xCD, 0xEF), 1))

vs

local some_byte = dev:transfer({0xAB, 0xCD, 0xEF}, 1)[1]

But the more I think about this the more a string seems to help even if it incurs a bit more boilerplate. I am going to try and throw together something that uses strings instead.

IanBurwell avatar Jun 13 '24 18:06 IanBurwell

@IamPete1 I have added an alternative transfer_str binding for comparison and an example that I actually used it to debug with. Do you think we should go with one over the other, or keep both (maybe renaming them slightly)?

IanBurwell avatar Jun 17 '24 17:06 IanBurwell

Having used them both, I do now prefer the string version even though it brings some extra boilerplate with it. string.unpack is just too powerful.

IanBurwell avatar Jul 11 '24 15:07 IanBurwell

I have added back the BQ40Z battery shutdown example as per discussion in the July 15th 2024 dev call and suggestion by @tridge. It works as desired on our dreamer quadrotors, and could be a useful example. With it this PR should be ready for merge pending review.

IanBurwell avatar Jul 16 '24 20:07 IanBurwell