My code for motor control using arduino and pulse width modulation

Posted on March 13th, 2011

This is code I wrote which allows corresponding motors to either move forward or backward. Do not do both at the same time or you will short your board. Common sense, I have included pictures to show my setup. This setup uses the L293B Chip which I wired from a breadboard to my arduino. Check out the pics and code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/////////////////////////////////////
// Motor using pulse-width-modulation
// By Ronald A. Richardson
/////////////////////////////////////
int signal = 0;
// Chip enabling inputs
int chipEnable1 = 1;
int chipEnable2 = 2;
// Motor inputs
int input1 = 3; // left side forward
int input4 = 10; // right side forward
int input2 = 5; // left side backwards
int input3 = 9; // right side backwards

void setup()
{
  pinMode(signal, OUTPUT);
  pinMode(chipEnable1, OUTPUT);
  pinMode(chipEnable2, OUTPUT);
  pinMode(input1, OUTPUT);
  pinMode(input4, OUTPUT);
  pinMode(input3, OUTPUT);
  pinMode(input2, OUTPUT);
}

void runSignal()
{
  digitalWrite(signal, HIGH);
  delay(50);
  digitalWrite(signal, HIGH);
  delay(50);
}

void enableMotors()
{
  digitalWrite(chipEnable1, HIGH);
  digitalWrite(chipEnable2, HIGH);
}

void goForward()
{
  analogWrite(input1, 100);
  analogWrite(input4, 100);
}

void goBackward()
{
  analogWrite(input3, 50);
  analogWrite(input2, 50);
}

void loop()
{
  // runSignal(); // Signal notifies that the pins are configured correctly (optional)
  enableMotors(); // Enables both sides of the motor chip
  goForward(); //Spins the motor forward
  // goBackward(); // Spins the motor backward
}

Leave a Reply

    To syntax highlight code just use [cc lang="whatever language here"]your code here[/cc]