1. Home
  2. Docs
  3. New sna41 Arduino PS2 motor drive expansion board manual
  4. Step 5: Explain the software code
  5. 1. Control DC motor

1. Control DC motor

a) Connect the motor

The drive has 4 sets of motor terminals M1, M2, M3, and M4.

Note: Please carefully check the motor parameters. If the motor size is too large (too much power), the drive will be overloaded and the drive will be damaged. (Measured 370 motor available)

b) DC motor example


#include <Wire.h>
#include "Adafruit_MotorShield.h"
#include "utility/Adafruit_MS_PWMServoDriver.h"

// Create the motor shield object with the default I2C address
Adafruit_MotorShield AFMS = Adafruit_MotorShield(); 

// Select which 'port' M1, M2, M3 or M4. In this case, M1
Adafruit_DCMotor *myMotor = AFMS.getMotor(3);

void setup() {
  AFMS.begin();  // create with the default frequency 1.6KHz
  
  // Set the speed to start, from 0 (off) to 255 (max speed)
  myMotor->setSpeed(150);
  myMotor->run(FORWARD);
  // turn on motor
  myMotor->run(RELEASE);
}

void loop() {
  myMotor->run(FORWARD);
  myMotor->setSpeed(150); 
  delay(3000);
  myMotor->run(RELEASE);
 
  myMotor->run(BACKWARD);
  myMotor->setSpeed(180); 
  delay(2000);

  myMotor->run(RELEASE);
  delay(1000);
}

Create a MotorShield object:

Adafruit_MotorShield AFMS = Adafruit_MotorShield();

Create a DCMotor object from MotorShield, corresponding to the motor of the M3 port:

Adafruit_DCMotor *myMotor = AFMS.getMotor(3);

getMotor(port#)

Port# : 1~4, corresponding to M1~M4 binding posts

Add the initialization code to the setup() function:

AFMS.begin();

Set the motor speed:

myMotor->setSpeed(100);

setSpeed(speed)

speed :0 (stopped) ~255 (full speed).

Start the motor (forward, reverse, stop)

myMotor->run(FORWARD);

run(direction)

direction : FORWARD, BACKWARD or RELEASE.

*Note: The direction of motor rotation is related to the wiring. If the steering is not correct, please adjust the positive and negative terminals of the motor.

Was this article helpful to you? Yes No

Leave A Comment