🛠 Discovering I/O: RGB LED and Encoder Reading

Unit 4-Encoder Motor Driver (DRV8837DSGR) · debutant · Apprenez à interagir avec les périphériques intégrés du module en contrôlant la LED RGB et en lisant les données des encodeurs via I2C.

Objectives

This tutorial aims to understand how the 4-Encoder Motor Driver module communicates with a host microcontroller via the I2C bus. We will explore two fundamental aspects of I/O: output (controlling the integrated WS2812C RGB LED for visual feedback) and input (reading encoder pulses for position feedback). This module is ideal for beginners as it centralizes motor control complexity, allowing you to focus on communication logic.

Required Materials

Steps

  1. Physical Connection: Connect the module to the M5Stack board via a Grove cable. Ensure the connector matches the I2C pins (SDA/SCL). Power the module either via the Grove port (5V) or via the external DC input if your motors require more power (6-12V).
  1. Code Configuration: Include the necessary libraries. The module uses the default I2C address 0x24.
#include <Wire.h>
#include "M5StackUnit4EncoderMotorDriver.h"

M5StackUnit4EncoderMotorDriver motorDriver;

void setup() {
  M5.begin();
  Wire.begin();
  // Initialize the module
  motorDriver.init();
  // Set RGB LED to red to indicate startup
  motorDriver.setRgbColor(255, 0, 0);
}
  1. Reading Encoders: In the main loop, read the current position of the motor connected to channel 1. The encoders provide pulses that the module converts into numerical position.
void loop() {
  // Read position of Motor 1
  int32_t position = motorDriver.getEncoderPosition(1);
  
  // Display on serial terminal
  Serial.printf("Motor 1 Position: %ld\n", position);
  
  // Change LED color based on position (simple example)
  if (position > 100) {
    motorDriver.setRgbColor(0, 255, 0); // Green
  } else {
    motorDriver.setRgbColor(0, 0, 255); // Blue
  }
  
  delay(100);
}
  1. Upload: Compile and upload the code to your M5Stack board. Open the Serial Monitor at 115200 bauds.

Verification

Observe the RGB LED on the module. It should light up red at startup, then change color (green or blue) based on the encoder position. If you manually rotate the motor shaft, the values displayed in the Serial Monitor should change. If the LED does not light up, check the power supply and I2C address (0x24). If values do not change, check the 6-wire motor connection (motor + encoder).

Further Learning

Once reading is mastered, explore closed-loop control modes. The module allows setting a target speed or target position, and it automatically handles PID regulation. Try using the setTargetPosition function to move the motor to a precise position without managing calculations manually.

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials