Slowly Building a Distance Sensitive Motor BotPosted: December 11, 2014
This morning I had some problems with my code for the ultra-sound module. Even just getting the LED to light up at a certain distance proved difficult. After some internet help and a few key inputs from Paul Granjon on the coding (proper use of if and else statements) we managed to get it working. Next to work on a motor circuit and then replace the LED in my circuit with a motor and then tweak the code appropriately.
Now I am better versed in motor control Paul introduced me to a dual motor control chip (although I only use one motor with the chip) called l293d.
This is an extract from the Adafruit website.
This is a very useful chip. It can actually control two motors independently. We are just using half the chip in this lesson, most of the pins on the right hand side of the chip are for controlling a second motor.
A second motor would be attached between OUT3 and OUT4. You will also need three more control pins.
- EN2 is connected to a PWM enabled output pin on the Arduino
- IN3 and IN4 are connected to digital outputs on the Arduino
The L293D has two +V pins (8 and 16). The pin ‘+Vmotor (8) provides the power for the motors, and +V (16) for the chip’s logic. We have connected both of these to the Arduino 5V pin. However, if you were using a more powerful motor, or a higher voltage motor, you would provide the motor with a separate power supply using pin 8 connected to the positive power supply and the ground of the second power supply is connected to the ground of the Arduino.
- 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);
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 HIGH and in2 LOW 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.