m5stack-encoder-motor-position-control.ino
Absolute positioning command for robotic or precision applications.
The code configures the unit in absolute positioning mode. It sends a target value (here 1000) to the position register. The STM32G031 uses encoder pulses to stop the motor at the exact position. Position bits are sent in little-endian. Ensure you calibrate the zero position before use.
m5stack-encoder-motor-position-control.ino
#include <Wire.h>
#define I2C_ADDRESS 0x2F
#define REG_TARGET_POSITION 0x0D // Registre position cible (32-bit split usually)
#define REG_MODE 0x00
void setup() {
Serial.begin(115200);
Wire.begin();
// Activer mode position
Wire.beginTransmission(I2C_ADDRESS);
Wire.write(REG_MODE);
Wire.write(0x02); // Mode Position
Wire.endTransmission();
}
void loop() {
// Déplacer vers position 1000
movePosition(1000);
delay(2000);
// Déplacer vers position 0
movePosition(0);
delay(2000);
}
void movePosition(int32_t pos) {
// Écriture de la position cible (exemple simplifié, vérifier format datasheet)
Wire.beginTransmission(I2C_ADDRESS);
Wire.write(REG_TARGET_POSITION);
Wire.write(pos & 0xFF);
Wire.write((pos >> 8) & 0xFF);
Wire.write((pos >> 16) & 0xFF);
Wire.write((pos >> 24) & 0xFF);
Wire.endTransmission();
// Attendre que le moteur arrive à position (nécessite lecture registre status)
delay(1000);
}