该代码是磁力计stm32控制QMC5883L磁力计输出角度与三个磁力分量,某宝一些标记有hmc5883L模块实际是QMC5883L,输出角度一直是45的可以试一下,你会感谢我的
单片机源程序如下:
- #include "HMC5883L.h"
- #include "I2C.h"
- #include "delay.h"
- void hmc_write_reg(u8 reg,u8 data)
- {
- IIC_Start();
- IIC_Send_Byte(WRITE_ADDRESS);
- IIC_Wait_Ack();
- IIC_Send_Byte(reg);
- IIC_Wait_Ack();
- IIC_Send_Byte(data);
- IIC_Wait_Ack();
- IIC_Stop();
- //delay_ms(5);
- }
- u8 hmc_read_reg(u8 reg)
- {
- u8 data;
- IIC_Start();
- IIC_Send_Byte(WRITE_ADDRESS);
- IIC_Wait_Ack();
- IIC_Send_Byte(reg);
- IIC_Wait_Ack();
- IIC_Stop();
- IIC_Start();
- IIC_Send_Byte(READ_ADDRESS);
- IIC_Wait_Ack();
- data=IIC_Read_Byte();
- IIC_NAck();
- IIC_Stop();
- return data;
- }
- void hmc_read_XYZ(short int *data)
- {
- // u16 temp;
- // temp=hmc_read_reg(DATAX_M);
- // *data++=(temp<<8)+hmc_read_reg(DATAX_L);
- // temp=hmc_read_reg(DATAY_M);
- // *data++=(temp<<8)+hmc_read_reg(DATAY_L);
- // temp=hmc_read_reg(DATAZ_M);
- // *data++=(temp<<8)+hmc_read_reg(DATAZ_L);
- *data++=((int16_t)hmc_read_reg(DATAX_M)<<8)|hmc_read_reg(DATAX_L);
- *data++=((int16_t)hmc_read_reg(DATAY_M)<<8)|hmc_read_reg(DATAY_L);
- *data++=((int16_t)hmc_read_reg(DATAZ_M)<<8)|hmc_read_reg(DATAZ_L);
- }
- void hmc_init(void)
- {
- hmc_write_reg(0X0B,0x01);
- hmc_write_reg(0X20,0x40);
- hmc_write_reg(0X21,0x01);
- hmc_write_reg(CONFIGA,0x1D);
- delay_ms(10);
- }
复制代码
- #include "stm32f10x.h"
- #include "I2C.h"
- #include "HMC5883L.h"
- #include "delay.h"
- #include "math.h"
- #include "usart.h"
- //连接引脚PA8(SCL)PA11(SDA)
- short int data[3];
- double angle,x,y,z;
- int main(void)
- {
- delay_init();
- i2c_init();
- hmc_init();
- uart_init(115200);
- while(1)
- {
- hmc_read_XYZ(data);
- angle=atan2((double)data[0],(double)data[2])*(180 / 3.14159265)+180;
- x=(double)data[0];
- y=(double)data[1];
- z=(double)data[2];
- printf("%f %f %f %f\r\n",x,y,z,angle);
- delay_ms(100);
- }
- }
复制代码
所有资料51hei提供下载:
STM32F1_QMC5883L.7z
(3.13 MB, 下载次数: 347)
|