Tag Archives: Boost Converter

PID Tutorial C code Example Pt/2

In this PID tutorial C code example Pt/2, the basic concept of a Boost PID controller will be explored.  All the PID controller C code is stepped through, as well as some basic concepts for testing and tuning the controller.  The final C code example can be downloaded via the link at the end of the article.

Hardware Overview

The image below shows a rough blocked out diagram of the boost circuit and feedback loop.

PID Tutorial C code Example using a Stellaris LM3S6965

As can be seen it’s a fairly simple design, with the output voltage being monitored and fed back to the LM3S6965.

A schematic for the boost converter can be seen below, this circuit was originally made to test a variable voltage boost converter.  The original design would use a 5V input which would then be boosted to either 9V, 12V or 15V, this was controlled via a state machine running on the Stellaris LM3S6965.

PID Tutorial C code Example using a Stellaris LM3S6965

The drive circuit for the mosfet uses 2 transistors in a totem pole configuration, and a 3rd transistor is to ensure a small current is sourced from the LM3S6965.  The main boost circuit itself consists of L1, Q1, D1 and C3.  The sampled output voltage via the potential divider is first passed through an operational amplifier U1A, configured as a non inverting amplifier which provides a gain of 2.2.  The operational amplifier U1B acts as a unity gain buffer, it’s input is connected to 3 resistors R7, R8 and R9.  These 3 resistors provide the offset voltage of 770mV and U1B ensures there is a high impedance input.  The output of U1B feeds the offset voltage to R4 and then to the negative input on U1A (effectively offsetting ground).  The boost converter was originally set-up to measure voltages between 4V and 19V.  So the operational amplifier arrangement with offset, ensures the sampled voltage range uses almost the full range of the ADC.  For the PID testing the output voltage will be regulated to 9V, which is equal to 353 on the ADC which is also the set point value.


The software used was written after reading various sources on PID.  It has been designed so it is easy to understand, as it uses local and global variables.  A more efficient way would be to use a typedef structure or typedef struct in C.

So firstly we have our constants and global variables.

In the first part of this tutorial the proportional (Kp), integral (Ki) and derivative (Kd) constant values were mentioned.  These are the values which provide the tuning for the PID control system.  The next constant is the set point, this was observed as the read ADC value, when 9V was present on the output.  The 9V was measured and adjusted using a multimeter with a fixed load on the output, the duty cycle had a fixed value which was then increased until 9 volts was reached.  The first 2 global variables are used to store the accumulated and historic error values required for integration and differentiation.  The global variable PWM_Temp is initially given a value, then this is used to store the old duty cycle value, which is then used in the new duty cycle calculation.

The next set of variables are all local to the PID function called PWM_Duty_Change(), all the code that follows will be inside this function, until the closing brace of the function is stated and mentioned.  Additionally the entire code which was used on the LM3S6965 can be downloaded (bottom of the page), so it can be seen how and when the function was called.

The first 2 local variables are called iMax and iMin, these are used to prevent integral windup.  More will explained on integral windup further in the tutorial, but for now we will just run through the variables.  The next 4 variables have already briefly been touched upon in part 1 of this tutorial, these are Err_Value, P_Term, I_Term and D_Term.  Then we are left with new_ADC_value which is simply the latest sampled value form the ADC, and finally PWM_Duty which will be the new PWM duty cycle value passed to the timer module.

The read ADC code does not need much explanation, other than a function was created to read the ADC and return the value as an integer.  If you are using this code on another microcontroller, you simply need to construct an ADC read function, then insert instead of the read_ADC().

Going back to part 1 of this tutorial it was shown that the error value can be obtained, by simply taking the newest error value away from the set point, that’s all this line performs.

To obtain the proportional term the Kp constant is multiplied by the error value.

The accumulated error value is used in integration to calculate the average error, so first the current error value must be added to the accumulated value, and that’s what this line performs.

The if and else if statements are used to cap the accumulated integral term, by simply setting upper and lower thresholds.

The integral term is then calculated by multiplying the Ki constant with the accumulated integral value.

The first line of this code snippet calculates the derivative term.  To understand how the code works the second line needs to be run through quickly, this basically assigns the newest ADC value to the d_temp global variable.  So the d_Temp variable effectively stores the historic error value, therefore allowing the derivative to be calculated.  Now looking at the first line again, the newest ADC value is taken away from the historic value, the difference between the 2 would allow the rate of change to be calculated (assuming the time between the readings is a known quantity). Then this value is multiplied by the derivative constant and assigned to the derivative term.

Now that we have all the PID terms calculated, they can be used to change the PWM duty cycle.  This next piece of code adds all the PID terms together, then they are subtracted from the PWM_Temp variable (PWM_Temp usage is shown shortly as it comes towards the end of the function).  This value is then assigned to the PWM_Duty variable.  The way the PID terms are used here is specific to this program, firstly the sum of the PID terms is subtracted, this is due to the final electronic circuit used.  What’s important here is the PID terms are summed, then they need to be used in such away as to construct a valid PWM duty cycle or other chosen control method.

The if and else if statements are used to prevent the duty cycle from going too high or too low, in this case this simply prevents the output voltage from going too high or too low.  If say you were using a half bridge driver integrated circuit, these usually state a maximum duty cycle of say 99%, if this is exceeded the voltage doubler cannot function correctly, so having limits can be a good protection system.

This line is again limited to this specific application, it simply calls the function adjust_PWM(), which has the new PID calculated duty cycle value, as a parameter.

The final statement in the function before the closing brace, assigns the current PWM duty cycle value to the PWM_Temp global variable.

Integral windup can occur if the integral term accumulates a significant error, during the rise time to the set point.  This would cause the output to overshoot the set point, with potentially disastrous results, it can also cause additional lag in the system.  The integral windup prevention used in this example, places a cap on the maximum and minimum value the integrated error can be.  This effectively sets a safe working value and is considered good working practice in any PID system.  The values used for integral windup as with the PID constant gain values are specific to this system, these would need to be determined and tuned to your system.

Step Response

The intention was to also explore the well documented Ziegler-Nichols approach, however time constraints for the project did not allow this method to be fully explored.  Some basic concepts of how to carry out a step response test will be shown, as I am sure it will prove useful.

The systems step response shows how the system responds to a sudden change, electronic circuits switch quickly, so an oscilloscope was the best piece of equipment for the job.  The boost converter was set up with a fixed load, a fixed PWM duty cycle and no feedback , therefore in an open loop configuration.  Then some additional test code was added, initiating these 2 extra functions when a button was pressed on the LM3S6965 development board :

  1. A free GPIO pin would be taken from low to high
  2. The PWM duty cycle would decrease by 10% effectively increasing the output voltage

The free GPIO pin would be connected to channel 2 on the oscilloscope, and in this way can be used as a trigger to start a capture event.  Channel 1 on the oscilloscope would be connected to the output of the boost converter, thereby capturing the step response as the output voltage rises.  The image below is a photograph of the captured step response on the oscilloscope.

PID Tutorial C code Example using a Stellaris LM3S6965

The GPIO pin was polled before the PWM duty cycle was updated, however this happens so quickly, it is difficult to distinguish this.  The lower square wave type step is the GPIO pin on channel 2, and the top curved step response is the output from the boost converter.  It can be seen to overshoot it’s settling level at the beginning then oscillate for a time before settling down, this oscilloscopes accuracy wasn’t the best, using a longer time base did not show any extra detail on the oscillations.

If the step response was of a first order, a calculation based on the reaction curve could be performed.  However the step response from the boost circuit is of a second order, and has an under-damped nature.  In order to explore this calculation further, requires another tutorial altogether, however further reading on this can be found here.

The step response of a similar system under the control of a PID controller can also be viewed.  This can be achieved by using a similar set up, the external pin is used again to trigger an oscilloscope capture.  That same GPIO pin is also used to switch a mosfet, which places an additional load in parallel with the output of the boost converter.  The PID algorithm will then regulate the output voltage to ensure it meets the set point with the new load, and the step response can then be captured.

Testing and Tuning

The system was set up and a basic tuning approach was used, the image below shows the system on the test bench.

PID Tutorial C code Example using a Stellaris LM3S6965

The image shows the following pieces of equipment:

  • Hewlett Packard multimeter connected to the output, monitoring the output voltage
  • Bench power supply, supplying 5V to the circuit
  • Oscilloscope, used to monitor the PWM duty cycle
  • 0-100Ω bench potentiometer
  • Boost converter PCB, LM3S6965 development board and a laptop to tweak the code

With everything connected the PID algorithm was set up, but with only the proportional part in operation.  The set point was set to 353 as mentioned previously, which produced close to 9V give or take 10-15mV.  The load was fixed and set to 100Ω.  Initially the proportional gain constant Kp was set very low around 0.001, this was too low so it was increased over a few steps until 0.01.  At this point the output voltage was observed to be approximately 7.5V, and the duty cycle waveform was observed to have a small amount of jitter, as the duty cycle fluctuated +/- 0.5%.  The Kp value was again increased, until the output voltage read approximately 8V, the duty cycle was again observed and found to be fluctuating by a greater amount, by approximately +/-5%.  The increase in jitter on the PWM duty cycle can be equated to greater oscillations on the output voltage, the multimeter was not suitable for observing these.  It would have been possible to see them on the oscilloscope but this probably would have involved a stop capture then restart method, therefore to make the process quicker the PWM duty cycle was considered ‘good enough’.

At this point the Kp value was backed off, to the previous level of 0.01 so the output voltage was at 7.5V.  This point can be considered close to the offset level mentioned in part 1 of this tutorial, and for ease of reading the image showing the offset level can again be seen below. This image also illustrates again how too larger Kp value can introduce instability in the output.

PID Tutorial C code Example using a Stellaris LM3S6965

Now with this level reached, the integral part of the algorithm was introduced.  All the hardware was untouched, just a simple modification to the algorithm was made.  The initial value chosen for Ki was 0.01.  This was then loaded on to the LM3S6965 and the output voltage on the multimeter was immediately observed to read 9.02V, +/-10mV.  The oscilloscope was also observed to have minor jitter as before of only a few half percent.  The integral value was not tweaked any further, but in most cases tuning the Kp and Ki values would take a greater time and under a wide range of conditions.

With the PI controller working on a basic level, the next test was to see how it performed under different load conditions.  First the bench potentiometer was left at 100Ω and the input current and output voltage were noted, the wiper was then moved to the middle (approximately 50Ω) and again the output voltage and input current were noted.  At 100Ω the output voltage was 9.02V with a current of 180mA, at 50Ω the output voltage was 8.99V with a current of 500mA, both output voltages still showed minor voltage variations in the +/-10mV range.

The next step was to move the potentiometer wiper rapidly between the 100Ω and 50Ω position, then observe the output voltage and duty cycle (not the most scientific test, but goes some way to demonstrating the system).  With this test being performed the duty cycle was observed to rapidly increase and decrease, too quick to observe anything further and a step response would be the best method to use here.  The output voltage was observed to have a minor variations, fluctuating +/-15-20mV

After this test, the derivative constant was introduced and tweaked to find the best settings. The Kd constant was not observed to have a huge affect on the system, unless increased dramatically which produced instability.  This set up is not ideal for testing the derivative term and a more detailed and longer term approach would be best.

The basic test performed seemed to conclude the PI controller was working as per the research carried out.  The system used here updates at a very fast rate, therefore observing the step response at this point would be best practice.  As this system has no critical importance other than to explore PID, it simply wasn’t necessary to tune it to a high degree of accuracy.  I have a number of projects in the works however, which touch on this subject again and I intend to post them when I have time.

Example Code

The link below contains the zip file with the complete C code and an external functions folder, there is a small advert page first via Adfly, which can be skipped and just takes a few seconds, but helps me to pay towards the hosting of the website.

PID LM3S6965 C code

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.

PID Tutorial C code Example Pt/1

In this PID tutorial C code example Pt/1, the basic concept of a PID controller will be explored. The full example code is implemented on a Stellaris LM3S6965 microcontroller, and is used to control a simple boost converter circuit, regulating the voltage with a change in load resistance. The boost circuit is not covered in-depth in this tutorial, but the fundamentals of a boost circuit are covered.

In this first part the basic concepts of a control system will be explored, as well as the PID controller.  The second parts covers the code implementation in the C language on the Stellaris LM3S6965, all the code is stepped through and can be downloaded at the end of the second part.

Basic Control System Concepts

To understand how PID controllers are used, it is important to first understand some basic control system principles.  The image below illustrates the 2 basic types of control system.

PID Tutorial C code Example using a Stellaris LM3S6965

The open loop system can clearly be seen to have no feedback, therefore if the load changes on the motor, the motor speed will change.  The control unit cannot command the driver to increase or decrease the power to the motor, as it has no knowledge of the speed change induced in the motor, by the change in load.

The closed loop system however has feedback from the motor.  So if the motors speed were to decrease due to an increase in load, the control unit could command the driver to increase the power to the motor, keeping a constant speed.  Common direct current motor control is achieved via PWM, and simply increasing or decreasing the duty cycle will increase or decrease the motor speed.

On/Off Controller

Using the above closed control loop as an example, the basic operation can be broken down. The feedback signal will often go through some signal conditioning circuitry, before being fed to the control unit.  The control unit will have some reference set point or threshold levels, that it is aiming to keep the motor speed at or between.  If a reference set point is used the new feedback signal could be used to generate an error value in the following way

Error_Value = Set_Point – New_Feedback_Value

We will come back to the Error_Value shortly as this is used in the PID controller, but first lets look at a more simplistic approach using the threshold level.

If threshold levels are used, lets say to keep the motor speed between 1200-1300rpm, the feedback signal could be directly used as a comparison.  Therefore if the feedback signal is 1320rpm the control unit needs to decrease the motor speed.  If we now said the control unit was a microcontroller, and the driver was a simple amplifier.  The microcontroller could reduce the duty cycle of the PWM, this in turn would then slow the motor down.  If we consider the motor to have a very quick response to changes in PWM drive, and the load on the motor to alter subtle over time, then there are 2 important factors to consider.  (1) The speed at which the PWM duty cycle is updated by the microcontroller, and (2) how large a change is made to the duty cycle on each update i.e. 1%, 5% etc.  This control system is often known as an on/off controller, the 2 factors can be tuned to suit the individual control system.  An example of on/off controller which is slightly more complex than this example, as it has other parameters is a Perturb and Observe algorithm used in a solar MPPT for photovoltaics.  The image below shows how an on/off controller usually oscillates around the set output level.

PID Tutorial C code Example using a Stellaris LM3S6965

On/off control systems typically oscillate around the desired output level, as they overshoot and undershoot the desired value.  The threshold level example used has no fixed setpoint so even if the motor speed stayed within these bounds, its speed would still oscillate to some degree.  The size of these oscillations is dependant on the PWM step size and the control loop speed.  If the system is very dynamic and changing at a fast rate, then a compromise between these 2 factors needs to be reached, to ensure good tracking performance.  When the desired reference value is reached, the size of the oscillations will be dependant on the PWM step size.

PID Controller

PID stands for Proportional, Integral and Derivative.  PID controllers have been used since the 1890s, and were originally developed by Elmer Sperry for an automatic ship steering system.  A PID control system uses 3 gain constants, which are multiplied with the Error_Value.  The proportional value gain constant is referred to as Kp, the integral value gain constant as Ki and the derivative value gain constant as Kd.   The results of these multiplications produces 3 further values, for this tutorial these are referred to as the P_term, I_term and D_term.

As previously mentioned the Error_Value can be obtained from simply taking the New_Feedback_Value away from the Set_Point.  In a PID controller the error value can simply be multiplied with the Kp constant, but for the Ki and Kd constants a different approach is required.  In order to calculate the I_term and D_term historic error values are required.  The I_term is using integration which gives the average error value over time, and the D_term is using differentiation which gives the rate of change of the error value over time.  Once all the PID terms are calculated, these new values are then summed together and used in the final control output.

The P, I and D terms have different affects on the final system performance, and need to be tuned to the individual control system.  The ultimate aim for any control system is to respond as quickly as possible, without excessive overshoot and oscillations around the set point.  The system response ideally needs to reach a settled state as quickly as possible, the settled state is very subjective and dependant on the application.  A block diagram of a PID control system can be seen below.

PID Tutorial C code Example using a Stellaris LM3S6965

The proportional term (P_term) provides an output value which is proportional to the current error value.  The Kp constant value determines how large the gain response will be to the current error value.  A high proportional gain constant will induce a large change in the output, often overshooting the set point level.  If the gain is too high the system can become unstable and excessive oscillations can occur.  Another affect of a high Kp constant is faster response time, vice versa a low Kp constant will result in a slower response time.  When a low Kp constant is used, there will still be oscillations and some overshoot of the set point depending on the level, however these will not be as aggressive.

A low Kp value will also settle in an offset position slightly below the set point level, this offset position can be used when tuning a PID system.  The image below illustrates the step response waveforms of a system with high and low Kp gain constants, on a hypothetical control system.

PID Tutorial C code Example using a Stellaris LM3S6965


The integral term (I_term) is used to bring long term precision to the control loop.  It is proportional to both the magnitude and duration of the error.  Using Integration allows for the average error to be calculated, as the sum of the instantaneous error over time provides an accumulated offset.  The accumulated error is then multiplied by the Ki gain constant, allowing the offset which should have been corrected previously, to be added to the controller output.  This then accelerates the controller output response towards the set point, eliminating the offset found when just using a proportional control value.

As with the the Kp gain constant the Ki constant, needs to be tuned.  If the Ki value is too high the system will have a faster response time, but it will also be likely to overshoot the set point, inducing further unwanted oscillations before finally settling.  An ideal Ki value produces a response time that is fast enough for the application, with little or no overshoot and a quick settling time.  The image below illustrates the step response waveforms with a tuned Kp value already set, then a few Ki gain constants are applied on a hypothetical control system.

PID Tutorial C code Example using a Stellaris LM3S6965


The derivative term (D_term) is the least used of the three terms, most controllers are based on PI control algorithms.  Introducing the Kd term is generally used in specific control systems, these are usually where overshooting the set point can cause dangerous results. Differentiation is used to determine the rate of change, by using the instantaneous error value and the previous error value, so a rate of change can be determined.  The derivative term can be used to predict system behaviour, improving settling time.

PID Control Loop Tuning

As can be seen the constant gain values Kp, Ki and Kd all affect the control system in different ways, therefore careful tuning of these values is an essential part of an effective PID controller.  Tuning a PID system is a difficult problem, there are only 3 parameters but finding a balance often takes some time depending on the complexity of the system.  Some systems have auto tuning features, but in some situations to have the best performance from a system, it is often recommended to manually tune.

A well known tuning method is called Ziegler-Nichols, developed by John G. Ziegler and Nathaniel B. Nichols.  This relies on the Ki and Kd gain constants first being set to zero.  The the Kp constant is adjusted until it reaches the ultimate gain, which is classified by the output from the control loop oscillating at a constant amplitude.  Then the ultimate gain value and oscillation period are used to calculate the Ki and Kd constants.  More about the Zieglar-Nichols method can be found here.

There are other methods and simply searching on Google will yield many results.

The C code, set-up and tuning of the boost converter will be covered in part 2 of this tutorial.

I take great care when writing all the tutorials and articles, ensuring all the code is fully tested to avoid issues for my readers.  All this takes time and a great deal of work, so please support the site by using the Adfly links etc.  If you have found this useful or have any problems implementing, please feel free to leave a comment and I will do my best to help.