# Change PWM values according to encoder output

I have a motor with an encoder. When I set the speed of the motor it should change its speed so that encoder readings per second should fit an equation $y = ax^2 + bx + c$ where x is speed value that is given to the motor and y is the encoder readings per second that should get with motor.

Encoder reading is counted in every 1ms and if it is not equal to the value of the encoder output should get from motor (it is calculated using the equation), the PWM input to the motor should vary in-order to get desired encoder output.

I want to control this value using a PID controller but I'm confused in writing equations. Any help would be appreciated..

• Sorry, just realized $y$ is encoder ticks per second, so in that case you will simply have $y = N x$ where $N$ is the number of ticks per radian (or degree, depending on how you define $x$). Dec 1 '15 at 12:50

$$y_d = a x^2 + b x + c$$ is your model, where I am using $y_d$ to represent the desired value of your control variable.

Using the measured value of your encoder $y_m$, define an error value $y_e$ $$y_e = y_d - y_m$$

Your PID controller can then be implemented as

$${PWM}_{dc} = k_p y_e + k_i \int y_e dt + k_d \frac{dy_e}{dt}$$

Here I am using ${PWM}_{dc}$ to be the duty cycle of your PWM signal.

So if you have a mapping showing what PWM duty cycles will achieve which $x$ speeds (perhaps a lookup table?) you can use ${PWM}_{dc}$ to find the value of $x$ to command. Otherwise, go ahead and substitute your $x$ in place of my ${PWM}_{dc}$ and assume the mapping between these two variables is linear.

• I think this what the OP wants, but what would $x$ be? Dec 1 '15 at 20:53
• Good question Brian. OP calls $x$ the speed value given to the motor. It should be related to ${PWM}_{dc}$. Since the speed to PWM mapping isn't linear for a very large range I thought it best to allow the additional scaling. A simple model could substitute $x$ for my ${PWM}_{dc}$ and let the gains take care of any linear scale factors. Dec 1 '15 at 22:14
• Edited answer based on BL's question. Dec 1 '15 at 22:19
• Ok I think I'm starting to understand where this quadratic comes from. Is the speed to encoder ticks per second not linear? How? Dec 1 '15 at 22:27
• Speed to encoder ticks is definitely linear :-) PWM duty cycle to speed has a linear range, which is typically not very large. That curve tends to look like a first order exponential, becoming horizontally asymptotic as the duty cycle approaches 100% Dec 1 '15 at 22:31