The procedure that drives my motors accepts positive and negative inputs [100, +100].
The sign determines the direction of the motor, the number the speed.
if (motorSpeed >= 0)
{
digitalWrite(m1In1, HIGH); // Forward
digitalWrite(m1In2, LOW);
}
else
{
digitalWrite(m1In1, LOW); // Backward
digitalWrite(m1In2, HIGH);
I use the number to calculate the desired time between the pulses of the wheel encoder (=set point).
The error is the difference between set point and the encoder reading (m1Pulse)
error = (long)desiredPulse (long)m1Pulse;
My PIDcode is as follows:
Kp = 50;
Ki = 0;
Kd = 0;
m1Pwm = Kp * error / 100; // m1Pwm is Pwm value of motor #1
m1Pwm += Ki * sumError / 100;
m1Pwm += Kd * (error  lastError) / 100;
lastError = error; // set the last and sumerrors for next loop iteration
sumError += error;
if (m1Pwm > 255) { m1Pwm = 255;}
if (m1Pwm <= 0) {m1Pwm 0;}
analogWrite(m1D2,m1Pwm);
The error signal can be positive or negative.
If the error is positive it’s the speed goes step by step towards set point => ok
But if the error is negative the Pwmsignal equals 0 => no smooth operation
Question: what to do with negative error values?

Decrease pwmvalue gradually (if yes, how?)
I tried the following (no satisfactory results)
if (m1Pwm > 127) { m1Pwm = 127;}
if (m1Pwm < 127) {m1Pwm = 127;}
m1Pwm = 127  m1Pwm;
analogWrite(m1D2,abs(m1Pwm));

Reverse motor direction and apply the abs value of the error as Pwmvalue (breaking on the motor)?