前言
K230内部包含5个I2C硬件模块,支持标准100kb/s,快速400kb/s模式,高速模式3.4Mb/s。 通道输出IO配置参考IOMUX模块。
一、IIC API
I2C类位于machine模块下。
i2c = I2C(id, freq=100000)
【参数】
id: I2C ID, [0~4] (I2C.I2C0~I2C.I2C4)
freq: I2C时钟频率
i2c.scan()
扫描I2C总线上的从机
【参数】
无
【返回值】
list 对象, 包含了所有扫描到的从机地址
i2c.readfrom(addr, len, True)
从总线读取数据
【参数】
addr: 从机地址
len: 数据长度
stop: 是否产生停止信号,保留,目前只能使用默认值Ture
【返回值】
读取到的数据,bytes 类型
i2c.readfrom_into(addr, buf, True)
读取数据并放到制定变量中
【参数】
addr: 从机地址
buf: bytearray类型, 定义了长度,读取到的数据存放在此
stop: 是否产生停止信号,保留,目前只能使用默认值Ture
【返回值】
无
i2c.writeto(addr, buf, True)
发送数据到从机
【参数】
addr: 从机地址
buf: 需要发送的数据
stop: 是否产生停止信号,保留,目前只能使用默认值Ture
【返回值】
成功发送的字节数
i2c.readfrom_mem(addr, memaddr, nbytes, mem_size=8)
读取从机寄存器
【参数】
addr: 从机地址
memaddr: 从机寄存器地址
nbytes: 需要读取的长度
mem_size: 寄存器宽度, 默认为8位
【返回值】
返回bytes类型的读取到的数据
i2c.readfrom_mem_into(addr, memaddr, buf, mem_size=8)
读取从机寄存器值到指定变量中
【参数】
addr: 从机地址
memaddr: 从机寄存器地址
buf: bytearray类型, 定义了长度,读取到的数据存放在此
mem_size: 寄存器宽度, 默认为8位
【返回值】
无
i2c.writeto_mem(addr, memaddr, buf, mem_size=8)
写数据到从机寄存器
【参数】
addr: 从机地址
memaddr: 从机寄存器地址
buf: 需要写的数据
mem_size: 寄存器宽度, 默认为8位
【返回值】
无
i2c.deinit()
释放i2c资源
【参数】
无
【返回值】
无
二、示例
from machine import I2C
i2c4=I2C(4) # init i2c4
a=i2c4.scan() #scan i2c slave
print(a)
i2c4.writeto_mem(0x3b,0xff,bytes([0x80]),mem_size=8) # write hdmi page address(0x80)
i2c4.readfrom_mem(0x3b,0x00,1,mem_size=8) # read hdmi id0 ,value =0x17
i2c4.readfrom_mem(0x3b,0x01,1,mem_size=8) # read hdmi id1 ,value =0x2
i2c4.writeto(0x3b,bytes([0xff,0x80]),True) # write hdmi page address(0x80)
i2c4.writeto(0x3b,bytes([0x00]),True) #send the address0 of being readed
i2c4.readfrom(0x3b,1) #read hdmi id0 ,value =0x17
i2c4.writeto(0x3b,bytes([0x01]),True) #send the address1 of being readed
i2c4.readfrom(0x3b,1) #read hdmi id0 ,value =0x17
i2c4.writeto_mem(0x3b,0xff,bytes([0x80]),mem_size=8) # write hdmi page address(0x80)
a=bytearray(1)
i2c4.readfrom_mem_into(0x3b,0x0,a,mem_size=8) # read hdmi id0 into a ,value =0x17
print(a) #printf a,value =0x17
i2c4.writeto(0x3b,bytes([0xff,0x80]),True) # write hdmi page address(0x80)
i2c4.writeto(0x3b,bytes([0x00]),True) #send the address0 of being readed
b=bytearray(1)
i2c4.readfrom_into(0x3b,b) #read hdmi id0 into b ,value =0x17
print(b) #printf a,value =0x17
总结
本章提供了IIC的API和基本用法例程