论坛元老
- 积分
- 3464
- 金钱
- 3464
- 注册时间
- 2019-5-15
- 在线时间
- 258 小时
|
网上很多HMC5883L的程序,没找到国产的QMC5883的程序,自己在HMC5883上面修改最终弄出来的QMC5883,共同学习,相互探讨。
#include "include.h"
u8 IIC_buf[14];
void QMC5883L_I2C_Init_IO(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(QMC5883L_I2C_RCC_APBxPeriph_GPIOx,ENABLE);
GPIO_InitStructure.GPIO_Pin=QMC5883L_I2C_SCL|QMC5883L_I2C_SDA;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_Init(QMC5883L_GPIO_I2C,&GPIO_InitStructure);
QMC5883L_I2C_SCL_H;
QMC5883L_I2C_SDA_H;
}
void QMC5883L_I2C_SDA_OUT()
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin=QMC5883L_I2C_SDA;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_Init(QMC5883L_GPIO_I2C,&GPIO_InitStructure);
}
void QMC5883L_I2C_SDA_IN(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin=QMC5883L_I2C_SDA;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
GPIO_Init(QMC5883L_GPIO_I2C,&GPIO_InitStructure);
}
//产生起始信号
void QMC5883L_I2C_Start(void)
{
QMC5883L_I2C_SDA_OUT();
QMC5883L_I2C_SDA_H;
QMC5883L_I2C_SCL_H;
delay_us(4);
QMC5883L_I2C_SDA_L;
delay_us(4);
QMC5883L_I2C_SCL_L;
}
//产生停止信号
void QMC5883L_I2C_Stop(void)
{
QMC5883L_I2C_SDA_OUT();
QMC5883L_I2C_SCL_L;
QMC5883L_I2C_SDA_L;
delay_us(4);
QMC5883L_I2C_SCL_H;
QMC5883L_I2C_SDA_H;
delay_us(4);
}
//主机产生应答信号ACK
void QMC5883L_I2C_Ack(void)
{
QMC5883L_I2C_SCL_L;
QMC5883L_I2C_SDA_OUT();
QMC5883L_I2C_SDA_L;
delay_us(2);
QMC5883L_I2C_SCL_H;
delay_us(2);
QMC5883L_I2C_SCL_L;
}
//主机不产生应答信号NACK
void QMC5883L_I2C_NAck(void)
{
QMC5883L_I2C_SCL_L;
QMC5883L_I2C_SDA_OUT();
QMC5883L_I2C_SDA_H;
delay_us(2);
QMC5883L_I2C_SCL_H;
delay_us(2);
QMC5883L_I2C_SCL_L;
}
//等待从机应答信号
//返回值:1 接收应答失败
// 0 接收应答成功
u8 QMC5883L_I2C_Wait_Ack(void)
{
u8 tempTime=0;
QMC5883L_I2C_SDA_IN();
QMC5883L_I2C_SDA_H;
delay_us(1);
QMC5883L_I2C_SCL_H;
delay_us(1);
while(GPIO_ReadInputDataBit(QMC5883L_GPIO_I2C,QMC5883L_I2C_SDA))
{
tempTime++;
if(tempTime>250)
{
QMC5883L_I2C_Stop();
return 1;
}
}
QMC5883L_I2C_SCL_L;
return 0;
}
//I2C 发送一个字节
void QMC5883L_I2C_Send_Byte(u8 txd)
{
u8 i=0;
QMC5883L_I2C_SDA_OUT();
QMC5883L_I2C_SCL_L;//拉低时钟开始数据传输
for(i=0;i<8;i++)
{
if((txd&0x80)>0) //0x80 1000 0000
QMC5883L_I2C_SDA_H;
else
QMC5883L_I2C_SDA_L;
txd<<=1;
QMC5883L_I2C_SCL_H;
delay_us(2); //发送数据
QMC5883L_I2C_SCL_L;
delay_us(2);
}
}
//I2C 读取一个字节
u8 QMC5883L_I2C_Read_Byte(void)
{
u8 i=0,receive=0;
QMC5883L_I2C_SDA_IN();
for(i=0;i<8;i++)
{
QMC5883L_I2C_SCL_L;
delay_us(2);
QMC5883L_I2C_SCL_H;
receive<<=1;
if(GPIO_ReadInputDataBit(QMC5883L_GPIO_I2C,QMC5883L_I2C_SDA))
receive++;
delay_us(1);
}
return receive;
}
|
|