打印
[应用相关]

STM32F407和STM32F051主从I2C通信

[复制链接]
729|2
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
Lewisnx|  楼主 | 2018-6-27 22:05 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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);
}
printf("\naddr is 22:");
for(i = 0; i < 4; i++)
{
printf("%02x ", bbb);
}
}
}
/* 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("transfer\n");
for( i = 0; i < 5; i++)
{
while(I2C_GetFlagStatus(I2C1, I2C_FLAG_TXIS) != SET);
I2C_SendData(I2C1, Data_to_M4_1);
}
}
}
}
}
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 in2\n");
Recv_flag = 1;
沙发
mmuuss586| | 2018-7-25 10:44 | 只看该作者
感谢分享;

使用特权

评论回复
板凳
zhuomuniao110| | 2018-7-25 14:07 | 只看该作者
都不注释一下吗

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

45

主题

380

帖子

0

粉丝