STM32 软件I2C方式读取AS5600磁编码器获取角度例程
- 🔖本例程使用正点原子例程作为工程模板创建。
📘 硬件电路部分
-
🌿原理图部分:
-
🌿PCB布线和电路
-
✨注意事项:有些硬件需要I2C上拉,否则检测不到设备。软件I2C方式没有上拉的情况下,需要将IO口配置为推挽输出模式才行,没有上拉情况下,开漏模式可能访问不到。
📙驱动代码部分
int main(void)
{
u16 i = 0;
u16 raw_num = 0;
u16 JIAODUnum = 0;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);// 设置中断优先级分组2
delay_init(); //延时函数初始化
uart_init(9600); //串口初始化为9600
LED_Init(); //初始化与LED连接的硬件接口
IIC_Init();
while(1) {
delay_ms(10);
if(++i > 100) {
raw_num = AS5600_ReadTwoByte(_raw_ang_hi, _raw_ang_lo); //读取两个寄存器的值
JIAODUnum = (raw_num * 360) / 4096; //对寄存器值进行处理得到角度值
printf("AS5600 Angle:%d \r\n", JIAODUnum);
LED0 = !LED0; //提示系统正在运行
i = 0;
}
}
}
- 🌿读取效果:
📚测试代码
- 🔖基于stm32f103标准库实现.
链接:https://pan.baidu.com/s/1jmWxyHLhXFY_c5sJyndkmg?pwd=hk0h
提取码:hk0h
📒i2c地址扫描
-
🌿基于HAL STM32F1硬件I2C扫描从设备地址:
https://blog.csdn.net/weixin_42880082/article/details/131869827
-
🌿基于Arduino rp2040 I2C扫描程序代码
#include <Wire.h>
void setup()
{
// Wire.begin();
Serial.begin(115200);
while (!Serial); // Leonardo: wait for serial monitor
Serial.println("\nI2C Scanner");
Wire.setSDA(8);
Wire.setSCL(9);
Wire.begin();
}
void loop()
{
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);//从指定的地址开始向I2C从设备进行传输
error = Wire.endTransmission();//停止与从机的数据传输
/*
* error返回结果:
* 0: 成功
1: 数据量超过传送缓存容纳限制
2: 传送地址时收到 NACK
3: 传送数据时收到 NACK
4: 其它错误
*/
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
nDevices++;
}
else if (error==4)
{
Serial.print("Unknown error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
delay(5000); // wait 5 seconds for next scan
}