Controlling a DC motor by PWM at constant speed

yo9hnf:
Firstly i tried to use some PID algorytms but i faild because all the algorytms that i used where designed for relay output, like a thermostat applications, AND, the PID library form Arduino reference is not really PID because when that library don't use a "reaction" in the loop - so if you can't measure (or know) your actual RPM, you can't modify-it to your desired RPM.

But you do have a way to measure RPM. I think you are misunderstanding the PID interface.

Now i whant to use something like this

  • I have an array with few RPM , like 1000, 1500, 2000, 2500 rpm;
  • I start the motor at (for example) 2000 rpm;
  • I push the break -> and the motor speed will slow down (for example down to 1500);
  • from Arduino I increase the PWM lenght so even with the break, my motor will run at 2000 rpm

If you take out all the unnecessary delays in your code, MarkT's suggestion will work.

int motorValue = 0;

void loop()
{                           
  unsigned int setRPM;

  potValue = analogRead(potPin);   
  setRPM = map(potValue, 0, 1023, 0, 2500);
  if (rpm < setRPM) {
       motorValue++;
  } else if (rpm > setRPM) {
       motorValue--;
 }
 motorValue = constrain(motorValue, 0, 255);
 analogWrite(transitorPin, motorValue);

  if (trigger) {
       rpm = 60000000UL / (t1 - t0);
       trigger = 0; 
  }
 
  //--------  AFISARE PE LCD  --------------------
 
  int RPM=rpm;
  lcd.setCursor(10,2);
  lcd.print(RPM);
  if ( RPM < 1000) lcd.print(' ');
 
  lcd.setCursor(0,0);
  lcd.print(potValue);
  if ( potValue < 100 ) lcd.print(' ');
 
 //--------  AFISARE PE LCD  -------------------- 
 
}

The only problem with this approach is that it will react somewhat slowly to large changes in either the motor load (brake) or the desired RPM. That's what PID gives you: the change in the output value is calculated so that the motor settles to the set point quickly, without thrashing or over shooting.