STM32标准库开发—软件I2C读取MPU6050

软件模拟I2C时序

初始化I2C引脚以及时钟
void MyI2C_Init(void)
{	
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB,ENABLE);

	GPIO_InitTypeDef GPIO_InitStruct;
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_Out_OD;
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_10|GPIO_Pin_11;
	GPIO_InitStruct.GPIO_Speed=GPIO_Speed_50MHz;
	GPIO_Init(GPIOA,&GPIO_InitStruct);

	GPIO_SetBits(GPIOB,GPIO_Pin_10|GPIO_Pin_11);
}
模块化I2C写以及I2C读
void MyI2C_W_SCL(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOB,GPIO_Pin_10,(BitAction)BitValue);
	Delay_us(10);
}
void MyI2C_W_SDA(uint8_t BitValue)
{
	GPIO_WriteBit(GPIOB,GPIO_Pin_11,(BitAction)BitValue);
	Delay_us(10);
}
I2C起始以及结束时序代码

STM32标准库开发—软件I2C读取MPU6050_第1张图片

void MyI2C_Start(void)
{
	MyI2C_W_SDA(1);
	MyI2C_W_SCL(1);
	MyI2C_W_SDA(0);
	MyI2C_W_SCL(0);
}
void MyI2C_Stop(void)
{
	MyI2C_W_SDA(0);
	MyI2C_W_SCL(1);
	MyI2C_W_SDA(1);
}
I2C发送以及接收时序代码

STM32标准库开发—软件I2C读取MPU6050_第2张图片

void MyI2C_SendByte(uint8_t Byte)
{
	uint8_t i;
	for (i=0;i<8;i++)
	{
		MyI2C_W_SDA(Byte & (0x80>>i));
		MyI2C_W_SCL(1);
		MyI2C_W_SCL(0);
	}
}

uint8_t MyI2C_ReceiveByte(void)
{
	uint8_t i,Byte=0x00;
	MyI2C_W_SDA(1);
	for (i=0;i<8;i++)
	{
		MyI2C_W_SCL(1);
		if (MyI2C_R_SDA() == 1) {Byte |= (0x80>>i);}
		MyI2C_W_SCL(0);
	}
	return Byte;
}
I2C发送以及接收应答位时序代码

STM32标准库开发—软件I2C读取MPU6050_第3张图片

void MyI2C_SendAck(uint8_t AckBit)
{
		MyI2C_W_SDA(AckBit);
		MyI2C_W_SCL(1);
		MyI2C_W_SCL(0);
}
uint8_t MyI2C_ReceiveAck(void)
{
		uint8_t AckBit;
		MyI2C_W_SDA(AckBit);
		MyI2C_W_SDA(1);
		MyI2C_W_SCL(1);
		AckBit = MyI2C_R_SDA();
		MyI2C_W_SCL(0);
		return AckBit;
}

封装MPU6050读写时序

MPU6050写时序

STM32标准库开发—软件I2C读取MPU6050_第4张图片

void  MPU6050_WriteReg(uint8_t RegAddress , uint8_t Data)
{
	MyI2C_Start();
	MyI2C_SendByte(MPU6050_ADDRESS);
	MyI2C_ReceiveAck();
	MyI2C_SendByte(RegAddress);
	MyI2C_ReceiveAck();
	MyI2C_SendByte(Data);
	MyI2C_ReceiveAck();	
	MyI2C_Stop();
}
MPU6050读时序

STM32标准库开发—软件I2C读取MPU6050_第5张图片

uint8_t  MPU6050_ReadReg(uint8_t RegAddress)
{
	uint8_t Data;
	
	MyI2C_Start();
	MyI2C_SendByte(MPU6050_ADDRESS);
	MyI2C_ReceiveAck();
	
	MyI2C_Start();
	MyI2C_SendByte(MPU6050_ADDRESS|0x01);
	MyI2C_ReceiveAck();
	Data =  MyI2C_ReceiveByte();
	MyI2C_SendAck(1);	
	MyI2C_Stop();
	
	return Data;
}

你可能感兴趣的:(stm32,单片机,嵌入式硬件)