【新手基础教程】片上外设之 I2C 的使用
# I2C 的使用关于 I2C 详细介绍请参考(https://cn.maixpy.sipeed.com/zh/api_reference/machine/i2c.html).
## 1. 使用方法[](https://cn.maixpy.sipeed.com/zh/modules/on_chip/i2c.html#%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95)
### 1.1. 主机模式[](https://cn.maixpy.sipeed.com/zh/modules/on_chip/i2c.html#%E4%B8%BB%E6%9C%BA%E6%A8%A1%E5%BC%8F)
- 创建 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. 从机模式[](https://cn.maixpy.sipeed.com/zh/modules/on_chip/i2c.html#%E4%BB%8E%E6%9C%BA%E6%A8%A1%E5%BC%8F)
- 创建从机回调函数
```
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. 示例[](https://cn.maixpy.sipeed.com/zh/modules/on_chip/i2c.html#%E7%A4%BA%E4%BE%8B)
- 读取所有从机地址并分别收发数据
```
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)
```
页:
[1]