STM32F407和STM32F051主从I2C通信方法

来源:本站
导读:目前正在解读《STM32F407和STM32F051主从I2C通信方法》的相关信息,《STM32F407和STM32F051主从I2C通信方法》是由用户自行发布的知识型内容!下面请观看由(电工技术网 - www.9ddd.net)用户发布《STM32F407和STM32F051主从I2C通信方法》的详细说明。
简介:本文章主要介绍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;

提醒:《STM32F407和STM32F051主从I2C通信方法》最后刷新时间 2024-03-14 01:13:01,本站为公益型个人网站,仅供个人学习和记录信息,不进行任何商业性质的盈利。如果内容、图片资源失效或内容涉及侵权,请反馈至,我们会及时处理。本站只保证内容的可读性,无法保证真实性,《STM32F407和STM32F051主从I2C通信方法》该内容的真实性请自行鉴别。