Step 4Make the DC motor circuit
http://itp.nyu.edu/physcomp/Labs/DCMotorControl
You will need to follow those easy directions for making the DC motor with controllable direction using an H Bridge integrated circuit. The direction changes are made via a switch that is connected to the Arduino's digital input.
At first, I used a external power supply for my DC motors voltage. This allowed me to power the Diecimila via USB and also the ability to upload my Arduino program to the Arduino microcontroller.
I decided to add a speed control to the motor circuit by adding a simple potentiometer circuit that utilizes the Arduino's +5V output and its ground. I send the voltage from the potentiometer circuit into the analog input 0 on the Arduino board.
Finally, I uploaded the following code (based on the website's code with added potentiometer control) to the Arduino so I can control the motor's speed and direction:
int switchPin = 2; // switch input
int motor1Pin = 3; // H-bridge leg 1
int motor2Pin = 4; // H-bridge leg 2
int speedPin = 9; // H-bridge enable pin
int ledPin = 13; //LED
int potPin = 0; // Analog input pin that the potentiometer is attached to
int potValue = 0; // value read from the pot
void setup() {
// set the switch as an input:
pinMode(switchPin, INPUT);
Serial.begin(9600);
// set all the other pins you're using as outputs:
pinMode(motor1Pin, OUTPUT);
pinMode(motor2Pin, OUTPUT);
pinMode(ledPin, OUTPUT);
// set speedPin high so that motor can turn on:
digitalWrite(speedPin, HIGH);
// blink the LED 3 times. This should happen only once.
// if you see the LED blink three times, it means that the module
// reset itself,. probably because the motor caused a brownout
// or a short.
blink(ledPin, 3, 100);
}
void loop() {
// if the switch is high, motor will turn on one direction:
Serial.println(potValue); // print the pot value back to the debugger pane
if (digitalRead(switchPin) == HIGH) {
digitalWrite(motor1Pin, LOW); // set leg 1 of the H-bridge low
digitalWrite(motor2Pin, HIGH); // set leg 2 of the H-bridge high
potValue = analogRead(potPin); // read the pot value
analogWrite(speedPin, potValue/4); // PWM the speedPin with the pot value (divided by 4 to fit in a byte)
}
// if the switch is low, motor will turn in the other direction:
else {
digitalWrite(motor1Pin, HIGH); // set leg 1 of the H-bridge high
digitalWrite(motor2Pin, LOW); // set leg 2 of the H-bridge low
potValue = analogRead(potPin); // read the pot value
analogWrite(speedPin, potValue/4); // PWM the speedPin with the pot value (divided by 4 to fit in a byte)
delay(10); // wait 10 milliseconds before the next loop
}
}
/*
blinks an LED
*/
void blink(int whatPin, int howManyTimes, int milliSecs) {
int i = 0;
for ( i = 0; i < howManyTimes; i++) {
digitalWrite(whatPin, HIGH);
delay(milliSecs/2);
digitalWrite(whatPin, LOW);
delay(milliSecs/2);
}
}
| « Previous Step | Download PDFView All Steps | Next Step » |
![]() |
Add Comment
|














































