Load up the following sketch onto your Arduino.
/* Adafruit Arduino - Lesson 15. Bi-directional Motor */ int enablePin = 11; int in1Pin = 10; int in2Pin = 9; int switchPin = 7; int potPin = 0; void setup() { pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(enablePin, OUTPUT); pinMode(switchPin, INPUT_PULLUP); } void loop() { int speed = analogRead(potPin) / 4; boolean reverse = digitalRead(switchPin); setMotor(speed, reverse); } void setMotor(int speed, boolean reverse) { analogWrite(enablePin, speed); digitalWrite(in1Pin, ! reverse); digitalWrite(in2Pin, reverse); }
Pins are defined and their modes set in the 'setup' function as normal.
In the loop function, a value for the motor speed is found by dividing the analog reading from the pot by 4.
The factor is 4 because the analog reading will be between 0 and 1023 and the analog output needs to be between 0 and 255.
If the button is pressed, the motor will run in forward, otherwise it will run in reverse. The value of the 'reverse' variable is just set to the value read from the switch pin. So, if the button is pressed, this will be False, otherwise it will be True.
The speed and reverse values are passed to a function called 'setMotor' that will set the appropriate pins on the driver chip to control the motor.
void setMotor(int speed, boolean reverse) { analogWrite(enablePin, speed); digitalWrite(in1Pin, ! reverse); digitalWrite(in2Pin, reverse); }
Firstly, the speed is set, by using an analogWrite to the enable pin. The enable pin of the L293 just turns the motor on or off irrespective of what the in1 and in2 pins of the L293 are set to.
To control the direction of the motor, the pins in1 and in2 must be set to opposite values.
If in1 is HIGH and in2 is LOW, the motor will spin one way, if on the other hand in1 is LOW and in2 HIGH then the motor will spin in the opposite direction.
The '!' command means 'not'. So the first digitalWrite command for in1 sets it to the opposite of whatever the value of 'reverse' is, so if reverse is HIGH it sets it to LOW and vice versa.
The second digitalWrite for 'in2' sets the pin to whatever the value of 'reverse' is. This means that it will always be the opposite of whatever in1 is.
Page last edited October 29, 2012
Text editor powered by tinymce.