请使用MicroPython编写ESP32与STM32f103ZET6进行IIC通信,其中STM32使用硬件IIC作为从机使用,ESP32作为主机
时间: 2023-05-30 13:03:17 浏览: 221
ESP32主机代码:
```python
from machine import Pin, I2C
import time
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000)
slave_addr = 0x68
while True:
# 发送数据
data = bytearray(1)
data[0] = 0x01
i2c.writeto(slave_addr, data)
time.sleep(0.5)
# 接收数据
data = i2c.readfrom(slave_addr, 2)
print("Received data: ", data)
time.sleep(0.5)
```
STM32从机代码:
```c
#include "stm32f10x.h"
#include "stm32f10x_i2c.h"
#define I2C_SLAVE_ADDRESS7 0x68
#define I2C_GPIO_RCC RCC_APB2Periph_GPIOB
#define I2C_RCC RCC_APB1Periph_I2C1
#define I2C_GPIO GPIOB
#define I2C_SCL GPIO_Pin_6
#define I2C_SDA GPIO_Pin_7
void I2C_Configuration(void);
void I2C_GPIO_Configuration(void);
void I2C_NVIC_Configuration(void);
void I2C1_EV_IRQHandler(void);
void I2C1_ER_IRQHandler(void);
u8 data[2] = {0};
int main(void)
{
I2C_Configuration();
while(1);
}
void I2C_Configuration(void)
{
I2C_GPIO_Configuration();
I2C_NVIC_Configuration();
RCC_APB1PeriphClockCmd(I2C_RCC, ENABLE);
I2C_InitTypeDef I2C_InitStructure;
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = I2C_SLAVE_ADDRESS7 << 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 | I2C_IT_ERR, ENABLE);
I2C_Cmd(I2C1, ENABLE);
}
void I2C_GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(I2C_GPIO_RCC, ENABLE);
GPIO_InitStructure.GPIO_Pin = I2C_SCL | I2C_SDA;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(I2C_GPIO, &GPIO_InitStructure);
}
void I2C_NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = I2C1_EV_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = I2C1_ER_IRQn;
NVIC_Init(&NVIC_InitStructure);
}
void I2C1_EV_IRQHandler(void)
{
u8 Event = I2C_GetLastEvent(I2C1);
switch(Event)
{
// 主机发送起始信号
case I2C_EVENT_MASTER_MODE_SELECT:
I2C_Send7bitAddress(I2C1, I2C_SLAVE_ADDRESS7 << 1, I2C_Direction_Transmitter);
break;
// 主机发送数据
case I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED:
I2C_SendData(I2C1, 0x01);
break;
// 主机发送停止信号
case I2C_EVENT_MASTER_BYTE_TRANSMITTED:
I2C_GenerateSTOP(I2C1, ENABLE);
break;
// 主机接收起始信号
case I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED:
break;
// 接收到数据
case I2C_EVENT_MASTER_BYTE_RECEIVED:
data[0] = I2C_ReceiveData(I2C1);
data[1] = I2C_ReceiveData(I2C1);
break;
default:
break;
}
}
void I2C1_ER_IRQHandler(void)
{
if(I2C_GetFlagStatus(I2C1, I2C_FLAG_AF))
{
I2C_ClearFlag(I2C1, I2C_FLAG_AF);
I2C_GenerateSTOP(I2C1, ENABLE);
}
}
```
阅读全文