STM32F103软件I2C读取角度传感器AS5600角度信息

I2C我用的例程,器件地址为0x36,角度信息在寄存器0x0c,0x0d
直接上代码

# include "AS5600.H"
# include "delay.h"
# include "sys.h"

void AS5600_Init(void)
{
	IIC_Init();
}

u16 AS5600_Read_Len(u8 addr,u8 reg,u8 len,u8 *buf)
{
	//SDA_IN();
	
	IIC_Start();
	
	IIC_Send_Byte((addr << 1) | Write_Bit);
	
	if (IIC_Wait_Ack())
	{
		IIC_Stop();
		
		return 1;
	}
	
	IIC_Send_Byte(reg);
	
	IIC_Wait_Ack();
	
	IIC_Start();
	
	IIC_Send_Byte((addr<<1) | Read_Bit);//发送器件地址+读命令
	
	IIC_Wait_Ack();		//等待应答 
	
	while(len)
	{
		if(len==1)*buf=IIC_Read_Byte(0);//读数据,发送nACK 
		else *buf=IIC_Read_Byte(1);		//读数据,发送ACK  
		len--;
		buf++; 
	}    
	
	IIC_Stop();	//产生一个停止条件 
	
	return 0;	
		
}

float Get_Angle(void)
{
	u8 buf[2] = {0};
	u8 i = 0;
	
	float temp = 0;
	float temp1 = 0.0;
	
	for (i = 0; i < 20; i++)
	{
		AS5600_Read_Len(Slave_Addr,Angle_Hight_Register_Addr,2,buf);
		
		temp1 +=buf[0]*256+buf[1];
		
		delay_ms(5);
		//temp = (((u16)buf[0] & (0x0f00)) << 8) | buf[1];
	}
	
	//软件滤波,防止数据不稳定
	temp = temp1/20;
	
	return temp/4096*360;
	
}


AS5600.H

# ifndef __AS5600_H
# define __AS5600_H
# include "I2C.H"

# define Slave_Addr 0x36
# define Write_Bit 0
# define Read_Bit 1
# define Angle_Hight_Register_Addr 0x0C
# define Angle_Low_Register_Addr 0x0D

void AS5600_Init(void);
u16 AS5600_Read_Len(u8 addr,u8 reg,u8 len,u8 *buf);
float Get_Angle(void);

# endif

之后直接用串口打印Get_Angle()函数即可

你可能感兴趣的:(STM32F103软件I2C读取角度传感器AS5600角度信息)