使用MicroPython的语法编写ESP32通过IIC的通讯方式与STM32103ZET6进行数据传输的代码和寄存器版本的STM32与ESP32进行IIC通信的代码,其中STM32使用硬件IIC作为从机,ESP32作为主机使用软件IIC
时间: 2023-05-28 11:03:45 浏览: 282
ESP32通过IIC通讯方式与STM32103ZET6进行数据传输的代码:
```python
from machine import Pin, I2C
import time
# 定义I2C总线的地址和频率
i2c = I2C(scl=Pin(22), sda=Pin(23), freq=100000)
# 定义STM32的I2C地址
address = 0x3c
# 向STM32写入数据
def write_data(data):
i2c.writeto(address, data)
# 从STM32读取数据
def read_data(length):
return i2c.readfrom(address, length)
# 发送数据
write_data(b'hello')
# 延时等待
time.sleep(1)
# 接收数据
data = read_data(5)
print(data)
```
寄存器版本的STM32与ESP32进行IIC通信的代码:
STM32代码:
```c
#include "stm32f10x.h"
#define I2C_SLAVE_ADDRESS 0x3c
void I2C1_EV_IRQHandler(void)
{
if (I2C_GetITStatus(I2C1, I2C_IT_EVT) == SET)
{
if (I2C_GetFlagStatus(I2C1, I2C_FLAG_ADDR) == SET)
{
// 读取寄存器地址
I2C1->SR2;
}
else if (I2C_GetFlagStatus(I2C1, I2C_FLAG_RXNE) == SET)
{
// 读取数据
uint8_t data = I2C_ReceiveData(I2C1);
// 处理数据
// ...
}
else if (I2C_GetFlagStatus(I2C1, I2C_FLAG_TXE) == SET)
{
// 发送数据
I2C_SendData(I2C1, data);
}
else if (I2C_GetFlagStatus(I2C1, I2C_FLAG_STOPF) == SET)
{
// 清除停止位标志位
I2C1->CR1 &= ~I2C_CR1_STOP;
// 清除事件标志位
I2C_ClearITPendingBit(I2C1, I2C_IT_EVT);
}
}
}
int main(void)
{
// 初始化I2C1
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
I2C_InitTypeDef I2C_InitStructure;
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = I2C_SLAVE_ADDRESS << 1;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 100000;
I2C_Init(I2C1, &I2C_InitStructure);
I2C_ITConfig(I2C1, I2C_IT_EVT, ENABLE);
I2C_Cmd(I2C1, ENABLE);
NVIC_EnableIRQ(I2C1_EV_IRQn);
while (1)
{
// 处理其他事情
// ...
}
}
```
ESP32代码:
```python
from machine import Pin, I2C
import time
# 定义I2C总线的地址和频率
i2c = I2C(scl=Pin(22), sda=Pin(23), freq=100000)
# 向STM32写入数据
def write_data(data):
i2c.writeto(0x3c, data)
# 从STM32读取数据
def read_data(length):
return i2c.readfrom(0x3c, length)
# 发送数据
write_data(b'hello')
# 延时等待
time.sleep(1)
# 接收数据
data = read_data(5)
print(data)
```
阅读全文