2185浏览
查看: 2185|回复: 0

[官方教程] 【新手基础教程】片上外设之 I2C 的使用

[复制链接]

I2C 的使用

关于 I2C 详细介绍请参考I2C-API 文档.

1. 使用方法

1.1. 主机模式

  • 创建 I2C(软件模拟或硬件) 对象
from machine import I2C
from fpioa_manager import fm
# i2c = I2C(I2C.I2C0, freq=100000, scl=28, sda=29) # hardware i2c
i2c = I2C(I2C.I2C4, freq=100000, scl=28, sda=29,gscl=fm.fpioa.GPIOHS3,gsda=fm.fpioa.GPIOHS2) # software i2c
  • 扫描从机, 返回所有从机地址
devices = i2c.scan()
  • 对从机读写数据
for device in devices:
    i2c.writeto(device, b'123')
    i2c.readfrom(device, 3)

1.2. 从机模式

  • 创建从机回调函数
count = 0
def on_receive(data):
    print("on_receive:",data)

def on_transmit():
    count = count+1
    print("on_transmit, send:",count)
    return count

def on_event(event):
    print("on_event:",event)
  • 创建 I2C 对象
from machine import I2C
i2c = I2C(I2C.I2C0, mode=I2C.MODE_SLAVE, scl=28, sda=29, addr=0x24, addr_size=7, on_receive=on_receive, on_transmit=on_transmit, on_event=on_event)

2. 示例

  • 读取所有从机地址并分别收发数据
from machine import I2C

i2c = I2C(I2C.I2C0, freq=100000, scl=28, sda=29) # software i2c

devices = i2c.scan()
print(devices)

for device in devices:
    i2c.writeto(device, b'123')
    i2c.readfrom(device, 3)
  • 从机模式示例
from machine import I2C

count = 0

def on_receive(data):
    print("on_receive:",data)

def on_transmit():
    count = count+1
    print("on_transmit, send:",count)
    return count

def on_event(event):
    print("on_event:",event)

i2c = I2C(I2C.I2C0, mode=I2C.MODE_SLAVE, scl=28, sda=29, addr=0x24, addr_size=7, on_receive=on_receive, on_transmit=on_transmit, on_event=on_event)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail