Skip to content

Commit 80284ec

Browse files
committed
pybricks.common.IMU: add tilt()
Gets the pitch and roll using accelerometer data only for now. This will get more accurate once we implement 3D orientation including gyro data.
1 parent ab73631 commit 80284ec

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

pybricks/common/pb_type_imu.c

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,28 @@ STATIC mp_obj_t common_IMU_up(mp_obj_t self_in) {
126126
}
127127
MP_DEFINE_CONST_FUN_OBJ_1(common_IMU_up_obj, common_IMU_up);
128128

129+
// pybricks._common.IMU.tilt
130+
STATIC mp_obj_t common_IMU_tilt(mp_obj_t self_in) {
131+
common_IMU_obj_t *self = MP_OBJ_TO_PTR(self_in);
132+
133+
// Read acceleration in the user frame. In the future, we can make this
134+
// more accurate by using the full IMU orientation.
135+
float_t accl[3];
136+
pb_imu_accel_read(self->imu_dev, accl);
137+
common_IMU_rotate_3d_axis(self, accl);
138+
139+
mp_obj_t tilt[2];
140+
// Pitch
141+
float pitch = atan2f(-accl[0], sqrtf(accl[2] * accl[2] + accl[1] * accl[1]));
142+
tilt[0] = mp_obj_new_int_from_float(pitch * 57.296f);
143+
144+
// Roll
145+
float roll = atan2f(accl[1], accl[2]);
146+
tilt[1] = mp_obj_new_int_from_float(roll * 57.296f);
147+
return mp_obj_new_tuple(2, tilt);
148+
}
149+
MP_DEFINE_CONST_FUN_OBJ_1(common_IMU_tilt_obj, common_IMU_tilt);
150+
129151
// pybricks._common.IMU.acceleration
130152
STATIC mp_obj_t common_IMU_acceleration(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) {
131153
PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args,
@@ -157,6 +179,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_KW(common_IMU_angular_velocity_obj, 1, common_IMU
157179
// dir(pybricks.common.IMU)
158180
STATIC const mp_rom_map_elem_t common_IMU_locals_dict_table[] = {
159181
{ MP_ROM_QSTR(MP_QSTR_up), MP_ROM_PTR(&common_IMU_up_obj) },
182+
{ MP_ROM_QSTR(MP_QSTR_tilt), MP_ROM_PTR(&common_IMU_tilt_obj) },
160183
{ MP_ROM_QSTR(MP_QSTR_acceleration), MP_ROM_PTR(&common_IMU_acceleration_obj) },
161184
{ MP_ROM_QSTR(MP_QSTR_angular_velocity), MP_ROM_PTR(&common_IMU_angular_velocity_obj)},
162185
};

0 commit comments

Comments
 (0)