简介:本文章主要介绍STM32F407和STM32F051主从I2C通信方法。
M4作为主机:
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_I2C1_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
int i;
HAL_I2C_Master_Receive_IT(&hi2c1, 0x22, bbb, 4);
HAL_Delay(1000);
if(i2c_flag == 1)
{
i2c_flag = 0;
printf("naddr is 11:");
for(i = 0; i < 4; i++)
{
printf("%02x ", aaa[i]);
}
printf("naddr is 22:");
for(i = 0; i < 4; i++)
{
printf("%02x ", bbb[i]);
}
}
}
/* USER CODE END 3 */
}
M0作为从机:
void IIC_GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1 , ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;//GPIO_Mode_IN
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_Level_3;
GPIO_InitStruct.GPIO_OType = GPIO_OType_OD;//open-drain
GPIO_Init(GPIOB , &GPIO_InitStruct);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_7;
GPIO_Init(GPIOB , &GPIO_InitStruct);
/* Connect PXx to I2C_SCL*/
GPIO_PinAFConfig( GPIOB , GPIO_PinSource6, GPIO_AF_1);
/* Connect PXx to I2C_SDA*/
GPIO_PinAFConfig( GPIOB , GPIO_PinSource7, GPIO_AF_1);
}
void IIC_Configuration(void)
{
I2C_InitTypeDef I2C_InitStruct;
/* I2C configuration */
I2C_InitStruct.I2C_Mode = I2C_Mode_I2C;
I2C_InitStruct.I2C_AnalogFilter = I2C_AnalogFilter_Enable;
I2C_InitStruct.I2C_DigitalFilter = 0x00;
I2C_InitStruct.I2C_OwnAddress1 = 0x22;
I2C_InitStruct.I2C_Ack = I2C_Ack_Enable;
I2C_InitStruct.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_InitStruct.I2C_Timing = 0xb0420f13;//100Kbits
/* I2C Peripheral Enable */
I2C_Cmd(I2C1, ENABLE);
/* Apply I2C configuration after enabling it */
I2C_Init(I2C1, &I2C_InitStruct);
}
int main(void)
{
peripheral_init();
board_init();
I2C1_isr.CR1 |= 0X08; //地址匹配产生中断
while(1)
{
if(Recv_flag == 1)
{
Recv_flag = 0;
if(I2C_GetFlagStatus(I2C1, I2C_FLAG_TCR) != SET)
{
printf("transfern");
for( i = 0; i < 5; i++)
{
while(I2C_GetFlagStatus(I2C1, I2C_FLAG_TXIS) != SET);
I2C_SendData(I2C1, Data_to_M4_1[i]);
}
}
}
}
}
void I2C1_IRQHandler(void)
{
uint8_t i = 0;
uint8_t j = 0;
I2C_ClearITPendingBit(I2C1, I2C_ISR_ADDR);
I2C1->ISR |= 0x00000001;
I2C_ClearFlag(I2C1, I2C_FLAG_ADDR);
printf("IIC irq in2n");
Recv_flag = 1;
上一篇:关于STM32的以太网问题集锦
下一篇:基于STM32的多路电压测量设计方案
推荐阅读最新更新时间:2024-11-05 01:12
设计资源 培训 开发板 精华推荐
- LTC3851AHMSE-1 高效 3.3V/15A 降压转换器的典型应用电路
- 基于ST25R3916的NFC读卡器扩展板,用于STM32和STM8 Nucleos
- 数控直流电源
- 测量线性稳压器上的 2nV/Hz 噪声和 120dB 电源抑制
- ATMEGA128A开发板第三版
- LTC2170CUKG-12、12 位、25Msps 低功耗四通道 ADC 的典型应用电路
- UDPSDR-TX2、200kHz - 55MHz 发射器开发板具有 AD9744 14 位、210Msps DAC
- AM6TW-2415DH35Z ±15V 6 瓦单输出 DC-DC 转换器的典型应用
- LT1021BCN8-5 电压基准的典型应用,将 10V 单元调整为 10.24V
- EVAL-AD2S1205CBZ,AD2S1200 评估板,12 位,汽车用 ADC