嵌入式技术论坛
直播中

李杰

7年用户 1394经验值
私信 关注
[经验]

如何利用RT Thread Seting中的IIC去读取AS5600 demo呢

一、RT Thread Studio 配置IIC
1、在RT Thread Seting 中开启IIC功能 并保存
一定要保存才能更新工程
2、在board.h中,开启IIC的宏
注意选择对应的管脚
#define BSP_USING_I2C1
#ifdef BSP_USING_I2C1
#define BSP_I2C1_SCL_PIN    GET_PIN(B, 8)
#define BSP_I2C1_SDA_PIN    GET_PIN(B, 7)
#endif
#define BSP_USING_I2C2
#ifdef BSP_USING_I2C2
#define BSP_I2C2_SCL_PIN    GET_PIN(D, 1)
#define BSP_I2C2_SDA_PIN    GET_PIN(D, 0)
#endif
#define BSP_USING_I2C3
#ifdef BSP_USING_I2C3
#define BSP_I2C3_SCL_PIN    GET_PIN(D, 2)
#define BSP_I2C3_SDA_PIN    GET_PIN(C, 12)
#endif
#define BSP_USING_I2C4
#ifdef BSP_USING_I2C4
#define BSP_I2C4_SCL_PIN    GET_PIN(D, 4)
#define BSP_I2C4_SDA_PIN    GET_PIN(D, 3)
#endif
二、读取AS5600demo
#include
#define HALL_I2C_PITCH_NAME     "i2c2"
#define HALL_I2C_ROLL_NAME      "i2c3"
#define HALL_I2C_YAW_NAME       "i2c4"
#define Slave_Addr 0x36
#define Write_Bit 0
#define Read_Bit 1
#define Angle_Hight_Register_Addr 0x0C
#define Angle_Low_Register_Addr 0x0D
static struct rt_i2c_bus_device *i2c_bus = RT_NULL;     /* I2C总线设备句柄 */
/* 写传感器寄存器 */
static rt_err_t write_reg(struct rt_i2c_bus_device *bus)
{
    struct rt_i2c_msg msgs;
    rt_uint8_t buf = Angle_Hight_Register_Addr;
    msgs.addr = Slave_Addr;
    msgs.flags = RT_I2C_WR;
    msgs.buf = &buf;
    msgs.len = 1;
    /* 调用I2C设备接口传输数据 */
    if (rt_i2c_transfer(bus, &msgs, 1) == 1)
    {
        return RT_EOK;
    }
    else
    {
        return -RT_ERROR;
    }
}
/* 读传感器寄存器数据 */
static rt_err_t read_regs(struct rt_i2c_bus_device *bus, rt_uint8_t len, rt_uint8_t *buf)
{
    struct rt_i2c_msg msgs;
    msgs.addr = Slave_Addr;
    msgs.flags = RT_I2C_RD;
    msgs.buf = buf;
    msgs.len = len;
    /* 调用I2C设备接口传输数据 */
    if (rt_i2c_transfer(bus, &msgs, 1) == 1)
    {
        return RT_EOK;
    }
    else
    {
        return -RT_ERROR;
    }
}
static void read_angle()
{
    rt_uint8_t temp[2];
    write_reg(i2c_bus);      /* 发送命令 */
    read_regs(i2c_bus, 2, temp); /* 获取传感器数据 */
    temp[0] = temp[0] & 0xF;
    rt_uint16_t angle = temp[0]*256 + temp[1];
    rt_kprintf("angle:%d",angle);
}
static void hall_init(const char *name)
{
    /* 查找I2C总线设备,获取I2C总线设备句柄 */
    i2c_bus = (struct rt_i2c_bus_device *)rt_device_find(name);
    if (i2c_bus == RT_NULL)
    {
        rt_kprintf("can't find %s device!n", name);
    }
    else
    {
    }
}
static void hall_sample(int argc, char *argv[])
{
    hall_init(HALL_I2C_PITCH_NAME);
    read_angle();
}
/* 导出到 msh 命令列表中 */
MSH_CMD_EXPORT(hall_sample, i2c hall sample);
最后打开串口控制台,输入指令,就可以获取角度了
msh >hall_sample
angle:1158
msh >hall_sample
angle:850

原作者:修理工小刘

更多回帖

发帖
×
20
完善资料,
赚取积分