MiaoUI/examples/STM32F103C8T6/USER/HAL/HAL_I2C.c

94 lines
1.9 KiB
C
Raw Normal View History

#include "HAL_I2C.h"
#include "HAL_Tick.h"
2024-04-06 18:01:42 +00:00
#define delay_us(x) HAL_Delay_Us(x)
2023-06-30 04:50:02 +00:00
2024-04-06 18:55:15 +00:00
static void MyI2C_SCL_W_SetState(uint8_t State)
2023-06-30 04:50:02 +00:00
{
GPIO_WriteBit(I2C_PORT, I2C_SCL, (BitAction)State);
2024-04-06 18:01:42 +00:00
delay_us(10);
2023-06-30 04:50:02 +00:00
}
2024-04-06 18:55:15 +00:00
static void MyI2C_SDA_W_SetState(uint8_t State)
2023-06-30 04:50:02 +00:00
{
GPIO_WriteBit(I2C_PORT, I2C_SDA, (BitAction)State);
2024-04-06 18:01:42 +00:00
delay_us(10);
2023-06-30 04:50:02 +00:00
}
uint8_t MyI2C_SDA_R_SetState(void)
{
uint8_t State;
State=GPIO_ReadInputDataBit(I2C_PORT,I2C_SDA);
2024-04-06 18:01:42 +00:00
delay_us(10);
2023-06-30 04:50:02 +00:00
return State;
}
void HAL_I2C_Init(void)
2023-06-30 04:50:02 +00:00
{
2023-12-08 14:22:57 +00:00
RCC_APB2PeriphClockCmd(I2C_RCC,ENABLE);
2023-06-30 04:50:02 +00:00
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Mode=GPIO_Mode_Out_OD;
GPIO_InitStruct.GPIO_Pin=I2C_SCL|I2C_SDA;
GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(I2C_PORT,&GPIO_InitStruct);
GPIO_SetBits(I2C_PORT,I2C_SCL|I2C_SDA);
}
2024-04-06 18:55:15 +00:00
static void MyI2C_Start(void)
2023-06-30 04:50:02 +00:00
{
MyI2C_SDA_W_SetState(1);
MyI2C_SCL_W_SetState(1);
MyI2C_SDA_W_SetState(0);
MyI2C_SCL_W_SetState(0);
}
2024-04-06 18:55:15 +00:00
static void MyI2C_Stop(void)
2023-06-30 04:50:02 +00:00
{
MyI2C_SDA_W_SetState(0);
MyI2C_SCL_W_SetState(1);
MyI2C_SDA_W_SetState(1);
}
2024-04-06 18:55:15 +00:00
static void MyI2C_SendByte(uint8_t Byte)
2023-06-30 04:50:02 +00:00
{
uint8_t i;
for ( i = 0; i < 8; i++)
{
MyI2C_SDA_W_SetState(Byte&(0x80>>i));
MyI2C_SCL_W_SetState(1);
MyI2C_SCL_W_SetState(0);
}
}
uint8_t MyI2C_ResetByte(void)
{
uint8_t i,Byte=0x00;
MyI2C_SDA_W_SetState(1);
for ( i = 0; i < 8; i++)
{
MyI2C_SCL_W_SetState(1);
if(MyI2C_SDA_R_SetState()==1){Byte|=(0x80>>i);}
MyI2C_SCL_W_SetState(0);
}
return Byte;
}
2024-04-06 18:55:15 +00:00
static void MyI2C_SendAck(uint8_t AckBit)
2023-06-30 04:50:02 +00:00
{
MyI2C_SDA_W_SetState(AckBit);
MyI2C_SCL_W_SetState(1);
MyI2C_SCL_W_SetState(0);
}
uint8_t MyI2C_ReceiveAck(void)
{
uint8_t AckBit;
MyI2C_SDA_W_SetState(1);
MyI2C_SCL_W_SetState(1);
2024-04-06 18:01:42 +00:00
AckBit = MyI2C_SDA_R_SetState();
2023-06-30 04:50:02 +00:00
MyI2C_SCL_W_SetState(0);
return AckBit;
2024-04-06 18:01:42 +00:00
}