Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Jung Min Yean
- * Learning HBridge Motor Control
- * 04/23/2019
- */
- const int MotorPin = 9;
- const int MC1 = 3; //Motor Control 1 direction
- const int MC2 = 2; //Motor Control other direction
- const int PotPin = A0;
- int val = 0; // for storing the reading from the Pot.
- int velocity = 0; //For stroing the desired velocity (from 0 - 255)
- void setup()
- {
- pinMode(MotorPin, OUTPUT);
- pinMode(MC1, OUTPUT);
- pinMode(MC2, OUTPUT);
- pinMode(PotPin, INPUT);
- brake(); // Initialize w/ motor stopped
- }
- void loop()
- {
- val = analogRead(PotPin);
- // go forward
- if (val > 550)
- {
- velocity = map(val, 550, 1023, 0, 255);
- forward(velocity);
- }
- // go backward
- else if (val < 500)
- {
- velocity = map(val, 500, 0, 0, 255);
- backward(velocity);
- }
- // brake is needed between 500 - 550 to change direction
- else
- {
- brake();
- }
- }
- // Motor goes forward at given Motor rate (from 0 - 255)
- void forward(int rate)
- {
- digitalWrite(MotorPin, LOW);
- digitalWrite(MC1, HIGH);
- digitalWrite(MC2, LOW);
- analogWrite(MotorPin, rate);
- }
- // Motor goes backward at given Motor rate (from 0 - 255)
- void backward(int rate)
- {
- digitalWrite(MotorPin, LOW);
- digitalWrite(MC1, LOW);
- digitalWrite(MC2, HIGH);
- analogWrite(MotorPin, rate);
- }
- void brake()
- {
- digitalWrite(MotorPin, LOW);
- digitalWrite(MC1, LOW);
- digitalWrite(MC2, LOW);
- analogWrite(MotorPin, HIGH);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement