🛠 Encoder feedback automation with DRV8837
Objectives
This tutorial aims to implement a closed-loop control loop to reach and maintain a precise target position. We will use AB encoder data to correct motor speed via a simple PID algorithm, illustrating a basic automation application.
Required Hardware
- M5Stack Encoder Motor Driver Unit (DRV8837DSGR)
- 6-wire geared motor with encoder (compatible with 3-15 PPR)
- I2C compatible host board (e.g., M5Stack Core2 or ESP32)
- Grove I2C cables
- External DC 6-12V power supply
Steps
- Physical Connection: Connect the board to the I2C bus via the Grove port. Ensure external power (6-12V) is connected for the motor, as the load can reach 1.2A.
- Software Configuration: Initialize I2C communication with the default address 0x2F. Configure the encoder's PPR (e.g., 12 PPR) in the configuration register.
- Encoder Reading: Implement a function that reads the current position by accumulating A and B pulses. Resolution depends on PPR and counting mode (1x, 2x, or 4x).
- PID Algorithm: Write a PID calculation function. The error is the difference between target position and current position. Calculate proportional, integral, and derivative outputs.
- PWM Command: Convert PID output to a PWM value for the DRV8837 H-bridge. Limit the value to respect the max current of 1.2A.
- Main Loop: In your loop, read position, calculate PID correction, and apply PWM. Repeat at a high frequency (e.g., 100 Hz) for optimal stability.
Verification
Try to manually block the motor. The system should increase power to reach the target. Check stability once the position is reached; slight oscillation is normal but should be damped by the derivative term.
Other tutorials for this board
- First connection and startup of the Encoder Motor Driver Unit
- Mastering I/O with the Encoder Motor Driver Unit
- Automating Precise Movement with the Encoder Motor Driver
- First Setup of the Encoder Motor Driver
- GPIO and RGB LED Control on the Encoder Motor Driver Unit
- Advanced Configuration and I2C Bus Validation
Code examples for this board
m5stack-encoder-motor-i2c-esp32.inoC++ (Arduino)m5stack-encoder-motor-pwm-control.inoC++ (Arduino)m5stack-encoder-motor-closed-loop.inoC++ (Arduino)m5stack-encoder-motor-position-control.inoC++ (Arduino)m5stack-encoder-motor-led-status.inoC++ (Arduino)closed_loop_speed_pid.pyMicroPython