Shop OBEX P1 Docs P2 Docs Learn Events
Implementing a PID controller for motor speed control — Parallax Forums

Implementing a PID controller for motor speed control

WhelzornWhelzorn Posts: 256
edited 2011-12-07 07:40 in Propeller 1
Hello everyone,

I'm trying to implement a PID controller in spin to use for keeping a motor at a constant RPM. The equation I'm using can be found here: http://bestune.50megs.com/typeABC.htm

My main PID routine is as follows:
PUB MotorController( SP_addr, PV_addr, output_addr ) | e, SP, PV, PV_D1, PV_D2, Kp, Ki, Kd, T, time, CO, plant

  'init variables
  SP := 0
  PV := 0
  e := 0
  PV_D1 := 0
  PV_D2 := 0
  CO := 0
  plant := 0
  
  'set PID gains
  Kp := 1
  Ki := 1
  Kd := 1

  'set T (in milliseconds)
  T := 1000 / UPDATE_FREQ

  time := cnt
  
  repeat
    SP := long[SP_addr]
    PV := long[PV_addr]

    'calculate the PID output
    e := SP - PV
    CO := CO - ( Kp * ( PV - PV_D1 ) ) + ( Ki * T * e ) - ( ( Kd / T ) * ( PV - ( 2 * PV_D1 ) + PV_D2 ) )
    PV_D2 := PV_D1
    PV_D1 := PV

    'Limit the output for anti-windup
    CO <#= 10
    CO #>= -10
    plant += CO
    plant <#= 100
    plant #>= 0
    long[output_addr] := plant 
    
    'delay for T milliseconds
    waitcnt( time += ( clkfreq / UPDATE_FREQ ) )

where the plant ( long[output_addr] ) is the PWM duty cycle %, the variable at SP_addr is the desired motor RPM and the variable at PV_addr is the current motor RPM (measured by another cog watching the encoder).
Does this appear to be a proper implementation of a PID controller? I cannot seem to get a set of Ks that don't result in an unstable system.

perhaps someone has a better implementation? I looked at the object exchange but I wanted to try this for myself.

Thanks,
Justin

Comments

  • ElectricAyeElectricAye Posts: 4,561
    edited 2011-12-07 04:51
    Whelzorn wrote: »
    ... I cannot seem to get a set of Ks that don't result in an unstable system....

    I think you mean you can't find a set of K's for which the system is stable.

    Sometimes tuning a system for PID can be a little tricky, involving some trial and error. The Parallax book "Process Control" has some info on PID. Free download too. Check out chapter 8.

    http://www.parallax.com/Portals/0/Downloads/docs/prod/sic/Web-PC-v1.0.pdf
  • PJAllenPJAllen Banned Posts: 5,065
    edited 2011-12-07 04:55
    Whelzorn!,
    Where've you been, kid? (:
    [Long time, no appearance.]
  • WhelzornWhelzorn Posts: 256
    edited 2011-12-07 07:40
    PJ Allen wrote: »
    Whelzorn!,
    Where've you been, kid? (:
    [Long time, no appearance.]

    Oh man, it's been over 3 years since I've posted?! I suppose I have college to blame, although I would have to blame this community partially for inspiring me to go for an electrical engineering degree in the first place!
    I'm glad to see everyone is still here and that I'm remembered!
Sign In or Register to comment.