User Tools

Site Tools


MPU6050

Polling mode

mpu6050.c
void mpu_setup(void) {
    gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, 
         GPIO_CNF_OUTPUT_ALTFN_OPENDRAIN, GPIO_I2C1_SCL | GPIO_I2C1_SDA);
 
    i2c_peripheral_disable(I2C1);
    i2c_reset(I2C1);
    i2c_set_speed(I2C1, i2c_speed_fm_400k, I2C_CR2_FREQ_36MHZ);
    i2c_set_dutycycle(I2C1, I2C_CCR_DUTY_DIV2);
    i2c_peripheral_enable(I2C1);
}
 
uint8_t mpu_read_reg(uint32_t i2c, uint16_t addr, uint8_t reg) {
    uint8_t data = 0;
 
    i2c_enable_ack(i2c);
    i2c_send_start(i2c);
 
    /* I2C_EVENT_MASTER_MODE_SELECT EV5: BUSY, MSL and SB */
    while (!((I2C_SR1(i2c) & I2C_SR1_SB) & 
             (I2C_SR2(i2c) & (I2C_SR2_MSL | I2C_SR2_BUSY))));
 
 
    i2c_send_7bit_address(i2c, addr, I2C_WRITE);
    /* I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED EV6: BUSY, MSL, ADDR, TXE and TRA */
    while (!(  (I2C_SR1(i2c) & (I2C_SR1_TxE | I2C_SR1_ADDR)) & 
               (I2C_SR2(i2c) & (I2C_SR2_MSL | I2C_SR2_BUSY | I2C_SR2_TRA)) ));
    (void)I2C_SR2(i2c);
 
    i2c_send_data(i2c, reg);
    /* I2C_EVENT_MASTER_BYTE_TRANSMITTED EV8_2: TRA, BUSY, MSL, TXE and BTF */
    while (!((I2C_SR1(i2c) & (I2C_SR1_TxE | I2C_SR1_BTF)) & 
             (I2C_SR2(i2c) & (I2C_SR2_MSL | I2C_SR2_BUSY | I2C_SR2_TRA))));
 
    i2c_send_start(i2c);
    /* I2C_EVENT_MASTER_MODE_SELECT EV5: BUSY, MSL and SB */
    while (!((I2C_SR1(i2c) & I2C_SR1_SB) & 
             (I2C_SR2(i2c) & (I2C_SR2_MSL | I2C_SR2_BUSY))));
 
    i2c_send_7bit_address(i2c, addr, I2C_READ);
    /* I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED EV6: BUSY, MSL and ADDR */
    while (!(  (I2C_SR1(i2c) & (I2C_SR1_ADDR)) &
               (I2C_SR2(i2c) & (I2C_SR2_MSL | I2C_SR2_BUSY)) ));
 
    i2c_disable_ack(i2c);
    i2c_send_stop(i2c);
    /* I2C_EVENT_MASTER_BYTE_RECEIVED EV7: BUSY, MSL and RXNE */
    while (!( (I2C_SR1(i2c) & I2C_SR1_RxNE )));
    data = i2c_get_data(i2c);
 
    return data;
}

First PagePrevious PageBack to overview