How to use MPU6050 to generate interrupts and wake up STM32 in sleep mode?

 Using the MPU6050 to generate an interrupt and wake up an STM32 microcontroller from sleep mode is a common technique in low-power motion detection applications. Here's a complete step-by-step guide:




 Goal:

  • Configure MPU6050 to generate an interrupt on motion.

  • Connect the INT pin of MPU6050 to an EXTI (external interrupt) pin on the STM32.

  • Wake up the STM32 from sleep (or stop/standby) mode on motion detection.


 Step 1: Hardware Connections

MPU6050STM32 (e.g., STM32F103)
VCC3.3V
GNDGND
SDAI2C SDA (e.g., PB7)
SCLI2C SCL (e.g., PB6)
INTGPIO with EXTI (e.g., PA0)

 Use pull-up resistors (4.7kΩ) on SDA/SCL lines if not present.

 Step 2: MPU6050 Configuration (Motion Interrupt)

Use I2C to configure MPU6050:

c

// Wake up MPU6050 i2c_write(MPU6050_ADDR, PWR_MGMT_1, 0x00); // Clear sleep bit // Set accelerometer threshold i2c_write(MPU6050_ADDR, MOT_THR, 10); // Threshold (sensitivity) // Set motion duration i2c_write(MPU6050_ADDR, MOT_DUR, 40); // Duration of motion // Enable motion interrupt i2c_write(MPU6050_ADDR, INT_ENABLE, 0x40); // Motion interrupt // Enable motion detection i2c_write(MPU6050_ADDR, MOT_DETECT_CTRL, 0x15); // Enable accelerometer hardware intelligence

 Step 3: STM32 Configuration

 1. Configure I2C Peripheral

Use STM32CubeMX or HAL to initialize I2C (for communication with MPU6050).

 2. Configure EXTI on MPU6050 INT Pin

In stm32f1xx_it.c:

c

void EXTI0_IRQHandler(void) { HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_0); } void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { if (GPIO_Pin == GPIO_PIN_0) { // Wake-up actions here // Re-initialize peripherals if needed } }

Enable interrupt in main.c:

c

HAL_NVIC_SetPriority(EXTI0_IRQn, 0, 0); HAL_NVIC_EnableIRQ(EXTI0_IRQn);

 Step 4: Enter Low-Power Mode on STM32

In your main loop:

c

HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI); // Or use STOP mode for deeper sleep

STM32 wakes up automatically when the EXTI line is triggered by MPU6050 INT.


 Step 5: Optional – Confirm INT Cleared

After waking up, you can read the INT_STATUS register from the MPU6050 to confirm the source:

c

uint8_t status = i2c_read(MPU6050_ADDR, INT_STATUS); if (status & 0x40) { // Motion detected }

 Notes

  • Use STOP mode instead of SLEEP for more power saving.

  • Don’t forget to reconfigure system clocks after STOP mode.

  • Use I2C pull-ups and shield the MPU from vibration if testing is unstable.

评论

此博客中的热门博文

How To Connect Stm32 To PC?

What are the common HDL languages used in FPGA design?

How do you set up ADC (Analog-to-Digital Converter) in STM32?