使用RT-Thread Studio快速创建工程
选泽对应的开发板
默认生成的LED闪烁程序
打开RT-Thread Settings,添加MPU6050组件
选择I2C对应的引脚好,如92,93对应的是B6,P7引脚
保存配置,会自动从网络拉取代码到本地,并更新组件。注意不要再组件内编辑内容,否则每次更新后就覆盖掉原来的组件代码。
编写如下代码即可完成对MPU6050调用,同时通过加速度计的x轴方向来控制PWM的输出,根据实际情况调节PWM的系数。即加速度的x轴的方向数值乘上一个系数来作为实际输出控制电机转速的PWM值。
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include "sensor_inven_mpu6xxx.h"
/* defined the LED3 pin: PB5 */
#define LED1_PIN GET_PIN(B, 5)
#define LED2_PIN GET_PIN(B, 4)
#define LED3_PIN GET_PIN(A, 8)
#define MPU6050_I2C_BUS_NAME "i2c1" //i2c总线设备名
#define MPU6050_ADDR 0x68 //MPU6050地址
struct mpu6xxx_device *i2c_bus1; //6050控制句柄
struct mpu6xxx_3axes gyro1, accel1; //陀螺仪,加速度结构体
float pitch;
float roll;
float yaw;
#define EVENT_MD_LOOP (1<<0)
#define EVENT_PRINT (1<<1)
#define MPU6050_INT_PIN GET_PIN(A, 15)
extern uint8_t mpu_mpl_get_data(float *pitch,float *roll,float *yaw);
static struct rt_event event_motion;
rt_uint32_t res;
rt_uint32_t recv_set;
#define PWM_DEV_NAME "pwm1"
#define PWM_DEV_CHANNEL 1
#define CYCLE_TIME 3000
struct rt_device_pwm *pwm_dev;
rt_uint32_t GPIO_pulse;
rt_uint32_t period,PWM_pulse;
int main(void)
{
/* set LED3 pin mode to output */
rt_pin_mode(LED1_PIN, PIN_MODE_OUTPUT);
rt_pin_mode(LED2_PIN, PIN_MODE_OUTPUT);
rt_pin_mode(LED3_PIN, PIN_MODE_OUTPUT);
rt_pin_write(LED1_PIN, PIN_HIGH);
rt_pin_write(LED2_PIN, PIN_HIGH);
rt_pin_write(LED3_PIN, PIN_HIGH);
rt_thread_mdelay(1000);
period = 10000;
PWM_pulse = 0;
pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, PWM_pulse);
rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);
i2c_bus1 = (struct mpu6xxx_device *)mpu6xxx_init(MPU6050_I2C_BUS_NAME, MPU6050_ADDR); //初始化MPU6050,测量单位为角速度,加速度
mpu6xxx_set_param(i2c_bus1, MPU6XXX_ACCEL_RANGE, MPU6XXX_GYRO_RANGE_250DPS); //陀螺仪范围配置
mpu6xxx_set_param(i2c_bus1, MPU6XXX_ACCEL_RANGE, MPU6XXX_ACCEL_RANGE_2G);//加速度计
mpu6xxx_set_param(i2c_bus1, MPU6XXX_DLPF_CONFIG, MPU6XXX_DLPF_188HZ);//低通滤波
mpu6xxx_set_param(i2c_bus1, MPU6XXX_SAMPLE_RATE, 500);//采样频率
while (1)
{
mpu6xxx_get_gyro(i2c_bus1, &gyro1);
mpu6xxx_get_accel(i2c_bus1, &accel1);
rt_kprintf("gyro1:%d,%d,%d\n",gyro1.x,gyro1.y,gyro1.z);
rt_kprintf("accel1:%d,%d,%d\n",accel1.x,accel1.y,accel1zx);
if(accel1.x>10) rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, accel1.x);
else rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, 0);
rt_pin_write(LED3_PIN, PIN_HIGH);
rt_thread_mdelay(500);
rt_pin_write(LED3_PIN, PIN_LOW);
rt_thread_mdelay(500);
}
}
更多回帖