Support » Pololu Simple Motor Controller G2 User’s Guide » 8. Example code »
8.10. Example I²C code for Arduino
This section shows how to use with the Simple Motor Controller G2’s I²C interface from an Arduino, A-Star, or other Arduino-compatible controller.
To use this code, you must check the “Enable I2C” checkbox in the “Input settings” tab of the Simple Motor Control Center G2. You should make sure that “Enable CRC for commands” is not checked. You should make sure that the controller’s “Device number” setting is 13, or else change the smcDeviceNumber
constant in the program to match the device number.
This example assumes the following connections exist between the Arduino and the Simple Motor Controller G2:
- Arduino SCL to Simple Motor Controller SCL
- Arduino SDA to Simple Motor Controller SDA/RX
- Arduino GND to Simple Motor Controller GND
If you are not sure which pins are SCL and SDA on your Arduino, refer to the documentation of your board and to the Wire library documentation.
See Section 4.4 for more information on connecting an I²C device to the Simple Motor Controller G2.
This program demonstrates how to send I²C commands to set the motor speed and read variables. For information about the commands used by this sample code, refer to Section 6.2.1. Note that the Simple Motor Controller G2 must be powered when this Arduino sketch starts running.
#include <Wire.h> const uint8_t smcDeviceNumber = 13; // Required to allow motors to move. // Must be called when controller restarts and after any error. void exitSafeStart() { Wire.beginTransmission(smcDeviceNumber); Wire.write(0x83); // Exit safe start Wire.endTransmission(); } void setMotorSpeed(int16_t speed) { uint8_t cmd = 0x85; // Motor forward if (speed < 0) { cmd = 0x86; // Motor reverse speed = -speed; } Wire.beginTransmission(smcDeviceNumber); Wire.write(cmd); Wire.write(speed & 0x1F); Wire.write(speed >> 5 & 0x7F); Wire.endTransmission(); } uint16_t readUpTime() { Wire.beginTransmission(smcDeviceNumber); Wire.write(0xA1); // Command: Get variable Wire.write(28); // Variable ID: Up time (low) Wire.endTransmission(); Wire.requestFrom(smcDeviceNumber, (uint8_t)2); uint16_t upTime = Wire.read(); upTime |= Wire.read() << 8; return upTime; } void setup() { Wire.begin(); exitSafeStart(); } void loop() { // Read the up time from the controller and send it to // the serial monitor. uint16_t upTime = readUpTime(); Serial.print(F("Up time: ")); Serial.println(upTime); setMotorSpeed(3200); // full-speed forward delay(1000); setMotorSpeed(-3200); // full-speed reverse delay(1000); }