/*
Purpose: to test speed and direction of a motor driver that uses two PWM pins of an UNO microcontroller
June 30, 2026

Connect the center of a 10kOhm potentiometer to A0
  With one side to 5V and the other pin to GND
  This will control the speed, maped to a 0-255 PWM value in the loop

****** Connections *********
Connect a push button to GND, the digital input for the button will be pulled up internally
  This button will toggle the direction of the motor

If the motor driver is a 3.3volt device, use a logic level converter between the 5volt UNO and 
  the motor driver pins
 PWM pins (for example, D4 and D5) will be connected to HV1 and HV2 pins on the High Volt (HV) side of the logic
  level converter. Other HV connections of the converter: HV to Arduino 5V, and connect the GND to UNO GND
 On the Low Volt (LV) side of the converter, connect LV1 and LV2 to the two inputs of the motor controller carrier.
  Connect the LV pin to the 3.3volt rail and GND pin to ground.

Connections for the Pololu MP6550 Motor Driver Carrier
  Inputs 1 and 2 as indicated above.
  Connect the Sleep pin to the 3.3 voltage via a 10 kOhm resistor
  Connect the two Output pins to the DC motor
  Connect the VIN pin to the supply voltage of the motor. This must be separate from the UNO power pins.

Connect the UNO GND to the GND of the circuit

********* End of the Connections ***********  

*/
 
bool directionToggle=0;
int pwmPin1=5; // the two PWM pins will be connected to the motor driver input via the logic level converter
int pwmPin2=6;
int dirButton=3; // for the momentary push button

void setup() {
pinMode(pwmPin1,OUTPUT);
pinMode(pwmPin2,OUTPUT);
pinMode(dirButton,INPUT_PULLUP);
}

void loop() {
int val = analogRead(A0); // read the potentiometer
int pwmVal = map(val,0,1023,0,255); // convert the analog value (10bits) to 8bits because PWM uses 8bits

if (directionToggle) {
  digitalWrite(pwmPin2,LOW);
  analogWrite(pwmPin1,pwmVal);
} else {
   digitalWrite(pwmPin1,LOW);
  analogWrite(pwmPin2,pwmVal);
}
  delay(10); 
  
if (digitalRead(dirButton)==LOW) { // button pressed so stop power to motor so that the direction can change
  digitalWrite(pwmPin1,LOW);
  digitalWrite(pwmPin2,LOW);
  directionToggle = !directionToggle;
  delay(1000); // giving time for the motor to slow down
}
}
