STM32使用硬件IIC作为从机发送数据给作为主机的ESP32,请分别编写STM32103ZET6的代码并使用MicroPython编写ESP32读取STM32从机想要发送的数据的代码
时间: 2024-05-15 10:14:52 浏览: 73
STM32代码:
```c
#include "stm32f10x.h"
#include "stm32f10x_i2c.h"
#define I2C_SLAVE_ADDR 0x50
uint8_t sendData[5] = {0x01, 0x02, 0x03, 0x04, 0x05};
void I2C_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
I2C_InitTypeDef I2C_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);
I2C_DeInit(I2C1);
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStructure.I2C_ClockSpeed = 400000;
I2C_Init(I2C1, &I2C_InitStructure);
I2C_Cmd(I2C1, ENABLE);
}
void I2C_SendData(uint8_t data)
{
I2C_SendData(I2C1, data);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
;
}
int main(void)
{
I2C_Configuration();
while (1)
{
I2C_GenerateSTART(I2C1, ENABLE);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT))
;
I2C_Send7bitAddress(I2C1, I2C_SLAVE_ADDR, I2C_Direction_Transmitter);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED))
;
for (int i = 0; i < 5; i++)
{
I2C_SendData(sendData[i]);
while (!I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED))
;
}
I2C_GenerateSTOP(I2C1, ENABLE);
while (I2C1->CR1 & I2C_CR1_STOP)
;
}
}
```
ESP32代码:
```python
from machine import Pin, I2C
import time
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000)
while True:
i2c.start()
i2c.writeto(0x50, b'') # 发送从机地址,进入写模式
data = i2c.readfrom(0x50, 5) # 读取从机发送的数据
i2c.stop()
print(data)
time.sleep(1)
```
注:ESP32代码中的Pin(22)和Pin(21)分别代表ESP32的SCL和SDA引脚,可以根据实际的接线情况进行修改。
阅读全文