Motor Control with H-Bridge

Hey there,

I have spend hours trying to figure this out, but I dont get it to work.....

I want to use a simple H-Bridge to control a Dc Motor bidirectionaly.

First I used 2 LEDs to symbolize the direction:

int fornpnPin = 8;      // forwards Pin npn
int revnpnPin = 9;      // reverse Pin npn

int forpnpPin = 10;     // forwards Pin pnp
int revpnpPin = 11;    // reverse Pin pnp

void setup() 
{

}

void loop() 
{
  
 digitalWrite(forpnpPin, 1);
 
 digitalWrite(fornpnPin, 1);
 analogWrite(revpnpPin, 0);
delay(1000);

 digitalWrite(revpnpPin, 1);  

  digitalWrite(revnpnPin, 1);
  analogWrite(forpnpPin, 0);
delay(1000);

 
 
delay(3);
}

I know you can make 2 LEDs blink in much simpler ways bit I used it to check the circuit and they blinked/change accordingly.

When I now use the input Values of a potentiometer to control them it is just doing crazy stuff...

int potPin = A0;
int potValue = 0;
int potValuelow = 0;
int potValuehigh = 0;

int forPin = 8;
int revPin = 9;
int forValue = 0;
int revValue = 0;

int forpnpPin = 10;
int revpnpPin = 11;


void setup() 
{
  Serial.begin(9600);
}

void loop() 
{
  
 potValue = analogRead(potPin);

 potValuelow = max(potValue, 511);
 potValuehigh = min(potValue, 512);
 
 forValue = map(potValuelow, 0, 511, 255, 0);
 revValue = map(potValuehigh, 512, 1023, 0, 255);
 



 if (forValue >= 0)
 {

   analogWrite(forPin, -forValue);
   digitalWrite(forpnpPin, 1);
   analogWrite(revpnpPin, 0);
 }
  
 if (revValue >= 0)
 {
  analogWrite(revPin, -revValue);
  digitalWrite(revpnpPin, 1);
  analogWrite(forpnpPin, 0);
 } 
 
 Serial.print("potentiometer = " );     
 Serial.print(potValue);
 Serial.print("\t");
 Serial.print("forward = ");
 Serial.print(-forValue);
 Serial.print("\t");
 Serial.print("reverse = ");
 Serial.println(-revValue);
 
delay(3);
}

The Serial monitor gives me the right values as I have planed. So probably the error lies in the digital/analogWrite??

If necessary I can upload some schematics of the circuit later. But there shouldent be a problem...? As far as I can say.

Please keep it simple as I am just a beginner...

Thanks for any help and suggestions

 potValuelow = max(potValue, 511);
 potValuehigh = min(potValue, 512);
 
 forValue = map(potValuelow, 0, 511, 255, 0);
 revValue = map(potValuehigh, 512, 1023, 0, 255);

is very obscure, you would be clearer to treat the forward and reverse cases
explicitly so its easy to follow:

  potValue = analogRead (...) ;
  if (potValue < 512)
  {
    int amplitude = potToPWM (512 - potValue) ;
    reverse (amplitude) ;
  }
  else
  {
    int amplitude = potToPWM (potValue - 512) ;
    forward (amplitude) ;
  }
  ...

int potToPWM (int potVal)  // clearly named function for range conversion
{
  return map (potVal, 0, 512, 0, 255) ;
}

void forward (int val)
{
  analogWrite (...) ;
  digitalWrite (...)
  ....
}
... etc

Clear code leads to less confusion,