Two DC motor is independently controlled with Arduino Nano (Micro compatible) and with a dual H-bridge using PWM. Speed and direction is selectable with two potentiometers. Each potentiometer value is read with Arduino analog input. When potentiometer is on it’s center position then motor is off state.
Video: https://youtu.be/dS4pnsJSH2k
Arduino Nano and Micro contains three timers. Timer0 is used with Arduino internal commands so it leaves two timer (timer1 and timer2) to use with custom programs. Timer1 works with pins 9, 10 and timer2 works with pins 11 and 3.
Pulse width is selected with command analogWrite(pin, value). Analog input is read with command analogRead(pin). Code is below.
void setup() {
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
}
void loop() {
int pot_1 = analogRead(1); // potentiometers values
int pot_2 = analogRead(0);
// MOTOR ONE
// direction backward
if(pot_1 < 512-20) {
digitalWrite(7,0); // motor direction
int mot_1 = map(pot_1, 0, 512-20, 255, 0);
analogWrite(10,mot_1);
}
// stop motor in middle position
else if((pot_1 > 512-19) && (pot_1 < 512+19)) {
digitalWrite(7,0); // motor direction
analogWrite(10,0); // motor speed
}
// direction forward
else if(pot_1 > 512+20) {
digitalWrite(7,1); // motor direction
int mot_1 = map(pot_1, 512+20, 1023, 255, 0);
analogWrite(10,mot_1);
}
// MOTOR TWO
// direction backward
if(pot_2 < 512-20) {
digitalWrite(8,0); // motor direction
int mot_2 = map(pot_2, 0, 512-20, 255, 0);
analogWrite(11,mot_2);
}
// stop motor in middle position
else if((pot_2 > 512-19) && (pot_2 < 512+19)) {
digitalWrite(8,0); // motor direction
analogWrite(11,0); // motor speed
}
// direction forward
else if(pot_2 > 512+20) {
digitalWrite(8,1); // motor direction
int mot_2 = map(pot_2, 512+20, 1023, 255, 0);
analogWrite(11,mot_2);
}
}