/* H-Bridge controller - Specific to my H_Bridge circuits. The circuit: * Potentiometer attached to analog input 0 * center pin of the potentiometer to the analog pin * one side pin (either one) to ground * the other side pin to +5V * The H-Bridge is connected using 3 wires: * Fwd Pin goes to Arduino Digial pin 2 * Rev Pin goes to Arduino Digial pin 3 * Center PWM pin goes to Arduiono Digial pin 10 * Motor and battery are connected to power side of H-Bridge * Turning the pot back and forth will cause the motor to go full-reverse, * slow to stop at center postion, speed up, full fwd. */ #define FORWARD 1 #define REVERSE 0 int sensorPin = A0; // Analog Input pin for the potentiometer int Fwd_Pin = 2; // Forward - Reverse pins on H-Bridge int Rev_Pin = 3; int PWM_Pin = 10; // PWM pin on H-Bridge controls speed. int LED_Pin = 13; // LED on Arduino Board int motorSpeed = 0; // ------------------------------------------------------------------- // read the potenteometer // return a value between -255...0...255 int read_speed_pot() { int rtnValue; rtnValue = (analogRead(sensorPin) - 512) / 2; // get value of pot [0..1023] => [-255..0..255] if (rtnValue < -255) rtnValue = -255; if (rtnValue > 255) rtnValue = 255; if (abs(rtnValue) < 4) rtnValue = 0; return rtnValue; } // --------------------------------------------------------------------------- // DutyCycle input is range -255..0..255 // -255 is full reverse, Zero is stop. 255 is full speed. void Set_Motor_PWM( int DutyCycle ) { int Direction; Serial.print("Duty Cycle: "); Serial.println(DutyCycle); if (DutyCycle < 0) { DutyCycle = -DutyCycle; Direction = REVERSE; } else Direction = FORWARD; if (DutyCycle == 0) { // Stop the motor digitalWrite(Fwd_Pin, LOW); // clear all pins digitalWrite(Rev_Pin, LOW); digitalWrite(PWM_Pin, LOW); digitalWrite(LED_Pin, LOW); Serial.println("Stop Motor"); } else { digitalWrite(LED_Pin, HIGH); if (Direction == FORWARD) { digitalWrite(Fwd_Pin, LOW); // Clear pin digitalWrite(Rev_Pin, HIGH); // Set pin } else { digitalWrite(Fwd_Pin, HIGH); // Set pin digitalWrite(Rev_Pin, LOW); // Clear pin } analogWrite(PWM_Pin, 255 - DutyCycle); // H-Bridge uses 0 = full speed, 255 as slowest } } // ------------------------ void setup() { Serial.begin(9600); pinMode(Fwd_Pin, OUTPUT); pinMode(Rev_Pin, OUTPUT); pinMode(PWM_Pin, OUTPUT); pinMode(LED_Pin, OUTPUT); Set_Motor_PWM( 0 ); // stop command. } // ------------------------ void loop() { int inputValue; inputValue = read_speed_pot(); // returns a value [-255..0..255] if (inputValue != motorSpeed) Set_Motor_PWM( inputValue ); motorSpeed = inputValue; delay(100); }