两个stm32F103C8T6分别作I2C从机向主机发送数据
时间: 2023-08-21 10:03:42 浏览: 103
STM32F103_I2C_STM32F103_stm32f103i2c_i2c从机_IIC_IIC从机
5星 · 资源好评率100%
好的,下面是两个STM32F103C8T6分别作为I2C从机向主机发送数据的基本步骤:
1. 配置I2C外设:设置I2C的时钟频率、I2C地址等参数。
2. 配置GPIO口:将SDA和SCL引脚配置为I2C模式。
3. 接收主机的读写请求:在I2C的中断服务函数中,检查接收到的I2C事件,例如接收到了地址匹配事件或接收到了数据。
4. 处理主机的读写请求:如果接收到了读取请求,则向主机发送数据;如果接收到了写入请求,则接收主机发送的数据。
5. 主机向从机发送数据:主机通过I2C总线向从机发送数据,从机接收主机发送的数据。
这里给出两个STM32F103C8T6分别作为I2C从机向主机发送数据的简单示例代码:
从机1:
```c
#include "stm32f10x.h"
#define SLAVE1_ADDRESS 0x50
uint8_t data1 = 0x55;
void I2C1_EV_IRQHandler(void) {
// 检查I2C事件
if (I2C1->SR1 & I2C_SR1_ADDR) {
// 接收到地址匹配事件
uint8_t dummy = I2C1->SR2;
}
if (I2C1->SR1 & I2C_SR1_RXNE) {
// 接收到数据
uint8_t received = I2C1->DR;
}
if (I2C1->SR1 & I2C_SR1_TXE) {
// 发送数据
I2C1->DR = data1;
}
}
int main(void) {
// 配置I2C1外设
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
I2C_InitTypeDef i2c;
i2c.I2C_ClockSpeed = 100000;
i2c.I2C_Mode = I2C_Mode_I2C;
i2c.I2C_DutyCycle = I2C_DutyCycle_2;
i2c.I2C_OwnAddress1 = SLAVE1_ADDRESS;
i2c.I2C_Ack = I2C_Ack_Enable;
i2c.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_Init(I2C1, &i2c);
I2C_Cmd(I2C1, ENABLE);
// 配置GPIO口
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef gpio;
gpio.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
gpio.GPIO_Mode = GPIO_Mode_AF_OD;
gpio.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &gpio);
// 配置I2C中断
NVIC_InitTypeDef nvic;
nvic.NVIC_IRQChannel = I2C1_EV_IRQn;
nvic.NVIC_IRQChannelPreemptionPriority = 0;
nvic.NVIC_IRQChannelSubPriority = 0;
nvic.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvic);
I2C_ITConfig(I2C1, I2C_IT_EVT, ENABLE);
while (1);
}
```
从机2:
```c
#include "stm32f10x.h"
#define SLAVE2_ADDRESS 0x60
uint8_t data2 = 0xAA;
void I2C2_EV_IRQHandler(void) {
// 检查I2C事件
if (I2C2->SR1 & I2C_SR1_ADDR) {
// 接收到地址匹配事件
uint8_t dummy = I2C2->SR2;
}
if (I2C2->SR1 & I2C_SR1_RXNE) {
// 接收到数据
uint8_t received = I2C2->DR;
}
if (I2C2->SR1 & I2C_SR1_TXE) {
// 发送数据
I2C2->DR = data2;
}
}
int main(void) {
// 配置I2C2外设
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C2, ENABLE);
I2C_InitTypeDef i2c;
i2c.I2C_ClockSpeed = 100000;
i2c.I2C_Mode = I2C_Mode_I2C;
i2c.I2C_DutyCycle = I2C_DutyCycle_2;
i2c.I2C_OwnAddress1 = SLAVE2_ADDRESS;
i2c.I2C_Ack = I2C_Ack_Enable;
i2c.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_Init(I2C2, &i2c);
I2C_Cmd(I2C2, ENABLE);
// 配置GPIO口
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitTypeDef gpio;
gpio.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11;
gpio.GPIO_Mode = GPIO_Mode_AF_OD;
gpio.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &gpio);
// 配置I2C中断
NVIC_InitTypeDef nvic;
nvic.NVIC_IRQChannel = I2C2_EV_IRQn;
nvic.NVIC_IRQChannelPreemptionPriority = 0;
nvic.NVIC_IRQChannelSubPriority = 0;
nvic.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&nvic);
I2C_ITConfig(I2C2, I2C_IT_EVT, ENABLE);
while (1);
}
```
以上代码中,从机1和从机2的地址分别是0x50和0x60,你可以根据自己的需求修改。主机通过I2C总线向两个从机发送数据时,需要先发送一个地址字节,然后再发送数据字节。
阅读全文