PID: calculate new Pwm-value or adjustment to the current Pwm-value?

I am developing a pid controller voor my bot. I have an error signal and am currently experimenting with the P-term and the calculation of the pwm-signal for the motors.

My question regards calculating the pwm-signal. I have something like this:

PID = error * Kp; ...... analogWrite(m1,m1Pwm);

Question: how to go from PID to m1PWM?

m1Pwm = PID // calculate the new pwm-value or m1Pwm = m1Pwm +PID // calculate the adjustments to the current Pwm-value

In my research I found examples of both. What is the best approach and what are the considerations?

Same variable… The output of the PID is the control signal to the motor. Just cast from
float to int?

However if the motor is bidirectional you may have to convert from a single signed
value into direction + PWM value:

  if (drive < 0.0)
    direction = LOW ;
    PWM = (int) - drive ;
    direction = HIGH ;
    PWM = (int) drive ;

or something similar.

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);
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 PID-code 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;}

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 Pwm-signal equals 0 => no smooth operation

Question: what to do with negative error values?

Decrease pwm-value gradually (if yes, how?)

I tried the following (no satisfactory results)

if (m1Pwm > 127) { m1Pwm = 127;}
if (m1Pwm < -127) {m1Pwm = -127;}
m1Pwm = 127 - m1Pwm;

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