背景
手头有个树莓派,又有个I2C通信的模块,因此想要用树莓派调一下这个模块,于是找了下树莓派控制模块的文章,发现都是从smbus 的read byte封装的,可是按照I2C协议一次肯定可以读多个数据,于是想找库函数文档看下,发现Py官网文档上smbus 库没有函数描述,但找到了语法与其相同的smbus2 库, 于是记录下库函数用法。不过找到了smbus 的源码, 源码中有函数接口。
结果
smbus 支持的函数列表:
static PyMethodDef SMBus_methods[] = {
{"open", (PyCFunction)SMBus_open, METH_VARARGS | METH_KEYWORDS,
SMBus_open_doc},
{"close", (PyCFunction)SMBus_close, METH_NOARGS,
SMBus_close_doc},
{"write_quick", (PyCFunction)SMBus_write_quick, METH_VARARGS,
SMBus_write_quick_doc},
{"read_byte", (PyCFunction)SMBus_read_byte, METH_VARARGS,
SMBus_read_byte_doc},
{"write_byte", (PyCFunction)SMBus_write_byte, METH_VARARGS,
SMBus_write_byte_doc},
{"read_byte_data", (PyCFunction)SMBus_read_byte_data, METH_VARARGS,
SMBus_read_byte_data_doc},
{"write_byte_data", (PyCFunction)SMBus_write_byte_data, METH_VARARGS,
SMBus_write_byte_data_doc},
{"read_word_data", (PyCFunction)SMBus_read_word_data, METH_VARARGS,
SMBus_read_word_data_doc},
{"write_word_data", (PyCFunction)SMBus_write_word_data, METH_VARARGS,
SMBus_write_word_data_doc},
{"process_call", (PyCFunction)SMBus_process_call, METH_VARARGS,
SMBus_process_call_doc},
{"read_block_data", (PyCFunction)SMBus_read_block_data, METH_VARARGS,
SMBus_read_block_data_doc},
{"write_block_data", (PyCFunction)SMBus_write_block_data, METH_VARARGS,
SMBus_write_block_data_doc},
{"block_process_call", (PyCFunction)SMBus_block_process_call,
METH_VARARGS, SMBus_block_process_call_doc},
{"read_i2c_block_data", (PyCFunction)SMBus_read_i2c_block_data,
METH_VARARGS, SMBus_read_i2c_block_data_doc},
{"write_i2c_block_data", (PyCFunction)SMBus_write_i2c_block_data,
METH_VARARGS, SMBus_write_i2c_block_data_doc},
{NULL},
};
该函数库是C库,smbus2 是纯python库;
用法
常用函数用法介绍及示例:
- 读单字节;
from smbus import SMBus
bus = SMBus(1)
b = bus.read_byte_data(80, 0)
print(b)
bus.close()
上面的代码如果句柄忘记了关闭,存在安全性风险, 可以使用with语句进行自动释放资源:from smbus import SMBus
with SMBus(1) as bus:
b = bus.read_byte_data(80, 0)
print(b)
更进一步可以打开包错误校验(Packet Error Checking, PEC):from smbus import SMBus
with SMBus(1) as bus:
bus.pec = 1
b = bus.read_byte_data(80, 0)
print(b)
- 读取一块数据
from smbus import SMBus
with SMBus(1) as bus:
block = bus.read_i2c_block_data(80, 0, 16)
print(block)
一次最多可以读取32字节; - 写入一个字节
from smbus import SMBus
with SMBus(1) as bus:
data = 45
bus.write_byte_data(80, 0, data)
- 写入一块数据
from smbus import SMBus
with SMBus(1) as bus:
data = [1, 2, 3, 4, 5, 6, 7, 8]
bus.write_i2c_block_data(80, 0, data)
一次最多写入32字节;
参考文档
- smbus2-project description
- smbus源码;
- 树莓派(Raspberry Pi)python smbus 函数说明
|