PID controller speed control for a DC motor with encoder

When you take the if out, the loop() can run much faster than the encoder pulses happen, averaging in lots of zeros.

At 138RPM with 100 pulses per rev, that's 13800 pulses/min or 230 pulses/sec or an interval 4ms/pulse (I'll edit my error above).

You'd probably want to use a sample time of at least 40ms in order to catch ~10 pulses at top speed to have 10% resolution.