0% found this document useful (0 votes)
4 views2 pages

Arduino Motor Control Code Guide

This document is an Arduino sketch for controlling a motor shield with four DC motors. It initializes the motors, sets their speed, and defines functions to move the motors forward, backward, left, right, or stop based on serial input commands. The code utilizes the Adafruit Motor Shield library for motor control.

Uploaded by

shaunak.nandigam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views2 pages

Arduino Motor Control Code Guide

This document is an Arduino sketch for controlling a motor shield with four DC motors. It initializes the motors, sets their speed, and defines functions to move the motors forward, backward, left, right, or stop based on serial input commands. The code utilizes the Adafruit Motor Shield library for motor control.

Uploaded by

shaunak.nandigam
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#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();

// Assign motor objects to specific ports on the shield


Adafruit_DCMotor *motor1 = [Link](1);
Adafruit_DCMotor *motor2 = [Link](2);
Adafruit_DCMotor *motor3 = [Link](3);
Adafruit_DCMotor *motor4 = [Link](4);

void setup() {
[Link](9600); // Initialize serial communication
[Link](); // Initialize the motor shield

// Set the speed for all motors


motor1->setSpeed(255); // Speed ranges from 0 to 255
motor2->setSpeed(255);
motor3->setSpeed(255);
motor4->setSpeed(255);
}

void loop() {
if ([Link]() > 0) {
char value = [Link](); // Read the incoming character

// Perform actions based on the received command


switch(value) {
case 'F':
forward();
break;
case 'B':
backward();
break;
case 'L':
left();
break;
case 'R':
right();
break;
case 'S':
stopMotors();
break;
default:
stopMotors();
}
}
}

void forward() {
motor1->run(FORWARD);
motor2->run(FORWARD);
motor3->run(FORWARD);
motor4->run(FORWARD);
}

void backward() {
motor1->run(BACKWARD);
motor2->run(BACKWARD);
motor3->run(BACKWARD);
motor4->run(BACKWARD);
}

void left() {
motor1->run(BACKWARD);
motor2->run(BACKWARD);
motor3->run(FORWARD);
motor4->run(FORWARD);
}

void right() {
motor1->run(FORWARD);
motor2->run(FORWARD);
motor3->run(BACKWARD);
motor4->run(BACKWARD);
}

void stopMotors() {
motor1->run(RELEASE);
motor2->run(RELEASE);
motor3->run(RELEASE);
motor4->run(RELEASE);
}

You might also like