element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • Members
    Members
    • Benefits of Membership
    • Achievement Levels
    • Members Area
    • Personal Blogs
    • Feedback and Support
    • What's New on element14
  • Learn
    Learn
    • Learning Center
    • eBooks
    • STEM Academy
    • Webinars, Training and Events
    • More
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • More
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • More
  • Products
    Products
    • Arduino
    • Dev Tools
    • Manufacturers
    • Raspberry Pi
    • RoadTests & Reviews
    • Avnet Boards Community
    • More
  • Store
    Store
    • Visit Your Store
    • Choose Another Store
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
Safe and Sound
  • Challenges & Projects
  • Design Challenges
  • Safe and Sound
  • More
  • Cancel
Safe and Sound
Blog MSP432 and TI-RTOS: PID Library Part 1 - Intro
  • Blog
  • Forum
  • Documents
  • Events
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Blog Post Actions
  • Subscribe by email
  • More
  • Cancel
  • Share
  • Subscribe by email
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: Jan Cumps
  • Date Created: 22 Jan 2017 1:02 PM Date Created
  • Views 373 views
  • Likes 10 likes
  • Comments 10 comments
  • safe and sound
  • msp432
  • pid
  • arduino
  • launchpad
  • ti_rt
Related
Recommended

MSP432 and TI-RTOS: PID Library Part 1 - Intro

Jan Cumps
Jan Cumps
22 Jan 2017

A port of the very good Arduino PID library to  MSP432 LaunchPad and TI-RTOS.

 

image source: e2e.ti.com

PID is a control algorithm. It tries to keep the output of a device at a desired level by controlling its input.

Part 1 describes the port from Arduino C++ to C.

 

What you need:

  • MSP432 LaunchPad
  • 1 micro-USB cable
  • Code Composer Studio
  • TI-RTOS for MSP43X

 

Why a PID Library?

When you build a power supply, you want to set the output voltage to a fixed level. And you want to keep it at that level, whatever happens.

When the user connects a heavy load, this shouldn't affect the output.

To get that working, you need to change the input signals to the circuit.

But how do you do that? How much change? How fast? How to prevent that the change pushes the output above the level?

And what if the load is removed?

That's a problem that the PID mechanism tries to resolve:

a stable control of the output, by measuring the difference with the desired output (error), using other factors (such as history) and changing the input signal (feedback) until balance is achieved.

The difference between the desired output and the actual current value is called the error.

P stands for proportional, I for Integral, D for differential. These are the mathematical terms that play a role in the calculations inside the PID library.

 

Why *This* Library?

Because it's based on a good one. It's an as true as possible port of Brett Beauregard's Arduino PID Library.

Because it has Tuning options.

Because it is extremely well documented. You should (really: should) read Brett's blog before continuing here: Improving the Beginner’s PID – Introduction « Project Blog.

 

Port for MSP432

It's not really for the MSP432, it's for any application that's in C. But I'm working on a MSP432 controlled project that needs PID.

 

That project is the reason why I've made the MSP432 blog series: a real world problem that needs to be solved, and me not knowing the MSP432 at all when starting it.

Each post in the series is documentation for one of the aspects that I had to master..

 

As an object oriented design aficionado, I prefer to migrate C code to C++. In this case it's the other way around.

 

What's different from the Arduino lib?

We loose something along the road. Not encapsulation, because I try to expose only public functionality.

But with Brett's OO library, you can have multiple PID objects. That's useful when your instrument has to support different operating modi (e.g.: a power supply with either constant voltage or constant current).

With the Arduino library, you can create two objects, each with their own PID values. That doesn't work yet with my port.

I'm planning to add similar functionality in a later release. I need that myself.

 

The PID() constructor is replaced by an init function

 

void pidInit(double*, double*, double*, double, double, double, int)

 

Public constants are prefixed with "PID_"

 

  #define PID_AUTOMATIC 1
  #define PID_MANUAL    0
  #define PID_DIRECT  0
  #define PID_REVERSE  1

 

Public functions are prefixed with "pid"

 

    void pidInit(double*, double*, double*, double, double, double, int)
    void pidSetMode(int Mode)
    bool pidCompute()
    void pidSetOutputLimits(double, double)

    void pidSetTunings(double, double, double)
    void pidSetControllerDirection(int)
    void pidSetSampleTime(int)

    double pidGetKp()
    double pidGetKi()
    double pidGetKd()
    int pidGetMode()
    int pidGetDirection()

 

The Arduino millis() function internals are replaced with a TI-RTOS portable time function. This is private within the library.

 

    long millis() {
        long t = Timestamp_get32();
        long msecs = (t & 0x7fff) * 1000 /32768;
        return msecs;
    }

 

In your TI-RTOS project, you have to add this line of code to the very end of your .cfg file -  (double-click the file and then press the cfg Script tab at the bottom of the editor window):

 

/* ================ Application Specific Instances ================ */
var TimestampProvider = xdc.useModule('xdc.runtime.Timestamp');

 

The comment line is already in that file. Paste the line of code underneath it.

If you want to use this port in a non-TI-RTOS project, you'll have to build your own implementation of millis().

 

 

How is it used in an TI-RTOS project?

I'm not sure about that yet. My current project will hopefully show the right way to do it.

My current approach is to have an RTOS task schedule. The PID library prefers that the control loop runs at regular intervals.

 

#include "pid.h"

//Define Variables we'll be connecting to
double Setpoint, Input, Output;

/*
 *  ======== fnTaskPID ========
 *
 */
Void fnTaskPID(UArg arg0, UArg arg1)
{

    //Specify the links and initial tuning parameters
    double Kp=2, Ki=5, Kd=1; // todo make these good values for our strategy
    Setpoint = 0.0;
    pidSetSampleTime(((UInt)arg0) / Clock_tickPeriod);
    pidSetOutputLimits(0, 255);
    Input = 0.0; // 
    pidInit(&Input, &Output, &Setpoint, Kp, Ki, Kd, PID_DIRECT);

     //turn the PID on
     pidSetMode(PID_AUTOMATIC);

    while (1) {
        Task_sleep(((UInt)arg0) / Clock_tickPeriod);
    //      Input = analogRead(PIN_INPUT); todo: sample your device actual output value
            if (pidCompute()) {
              System_printf("setpoint = %f ; input = %f ; output =%f \n", Setpoint, Input, Output);
              System_flush();
    //        analogWrite(PIN_OUTPUT, Output);   todo: set your device input to this value. 
            }
    }
}

 

The default output range is 255. That may be rough for some situations. The bigger you set this value, the more steps the library can use.

It makes sense to define this relative to the method you're using to drive your instrument's input.

If you're using a 32-bit PWM module, you could use:

 

     pidSetOutputLimits(0, UINT32_MAX);

 

For a 14-bit DAC, you could set it to:

 

     pidSetOutputLimits(0, 0b11111111111111);

 

 

Side note: logging double values in the TI-RTOS console:

 

By default, TI-RTOS doesn't compile the code to format %f in the System_prinf() function.

RTSC considers the %f an 'extended format' which is not compiled in by default.

 

Add the following line to the end of the TI-RTOS  .cfg file:

 

 

System.extendedFormats = '%$L%$S%$F%f';

 

You can register the task in source code (as done in the TI-RTOS empty example) or by setting it up in the TI-RTOS configuration editor (check here for instructions).

Choose the sleep time based on the requirements of your control process. The 1000 ms that I've put here are arbitrary. You may want to adjust your process faster or less frequent.

If you use the task code above, the PID library's sample time will automatically be initialised to the timeout you define in Argument 0.

This line of code takes care of that:

pidSetSampleTime(((UInt)arg0) / Clock_tickPeriod);

 

Don't forget to register the TimestampProvider in the .cfg file, as explained above.

 

 

Side note: Algorithm

 

The core algorithm of the library is a pure implementation of the PID theory:

 

          /*Compute all the working error variables*/
          double input = *myInput;
          double error = *mySetpoint - input;
          ITerm+= (ki * error);
          if(ITerm > outMax) ITerm= outMax;
          else if(ITerm < outMin) ITerm= outMin;
          double dInput = (input - lastInput);


          /*Compute PID Output*/
          double output = kp * error + ITerm- kd * dInput;


          if(output > outMax) output = outMax;
          else if(output < outMin) output = outMin;
          *myOutput = output;


          /*Remember some variables for next time*/
          lastInput = input;
          lastTime = now;

 

image source: wikipedia

 

 

 

As you can see, my PID is WIP. The ported code is attached to this blog post as a zip archive.

(for the TM4C123GXL lovers, there's a full CCS project attached to this blog )

Have fun. Tell me if anything isn't OK please.

 

 

TI-RTOS Series
MSP432 and TI-RTOS: Getting Started Pt. 1 - Set Up and 1st RTOS Task
MSP432 and TI-RTOS: Getting Started Pt. 2 - Add an ADC Sample Task
MSP432 and TI-RTOS: Getting Started Pt. 3 - USB with Minimal CPU Use
MSP432 and TI-RTOS: PWM
MSP432 and TI-RTOS: I2C Configuration for Sensors BoosterPack
MSP432 and TI-RTOS: another I2C example - talk to a DAC
MSP432 and TI-RTOS: Sharp LCD BoosterPack
MSP432 and TI-RTOS: PID Library Part 1 - Intro
MSP432 and TI-RTOS: PID Library Part 2 - Real World Example
Attachments:
pid_lib.zip
TM4C_PID_TIRTOS_EK_TM4C123GXL_TI.zip
Anonymous

Top Comments

  • fmilburn
    fmilburn over 5 years ago +3

    Jan,

     

    I have worked my way through your examples up to here and they are great!  I did skip the one on DACs because I don't have that part but it was easy to follow.

     

    Regarding your comment on this particular…

  • Jan Cumps
    Jan Cumps over 5 years ago +2

    This part of the blog series is also a good excuse to try out the LED board that jc2048 gave me (I've gone medieval on the PSU  ). I'm going to train myself on the internals of the LIB with that.…

  • DAB
    DAB over 5 years ago +2

    Nice post Jan.

     

    It reminds me of some of the control algorithms I developed in the mid 1980's to control a FLIR device and slave it to the movement of a helicopter.

     

    I had to constantly update the FLIR…

  • Jan Cumps
    Jan Cumps over 2 years ago in reply to mtrobregado

    In the current version of the eload (where I was preparing this library for) I'm not using software PID.

    But I've created a snapshot Git branch specifically to keep the implementation with PID available, for my own and other's reference - just before factoring it out of the code:

    https://github.com/jancumps/msp432/tree/last_version_with_pid_library/MSP432_SCPI_ElectronicLoad

     

    The PID code should be the same as the archive attached to this article.

    • Cancel
    • Up 0 Down
    • Reply
    • More
    • Cancel
  • mtrobregado
    mtrobregado over 2 years ago in reply to fmilburn

    Hi Jan,

     

    I am thinking of using your PID library for my wireless Sous Vide project. Its much more simpler implementation compared to https://learn.adafruit.com/sous-vide-powered-by-arduino-the-sous-viduino . I am studying how the PID auto tuning works, and still confused at the moment.

     

    For Sous Vide, I am thinking of using a TMP006 IR Thermometer to measure the water surface temperature. Although, from what I read it is not recommended due to that IR Thermometer readings can be affected by steam. But, I believe this should also work.

     

    Regards,

    Markel

    • Cancel
    • Up +1 Down
    • Reply
    • More
    • Cancel
  • fmilburn
    fmilburn over 5 years ago

    Jan,

     

    I have worked my way through your examples up to here and they are great!  I did skip the one on DACs because I don't have that part but it was easy to follow.

     

    Regarding your comment on this particular PID code:

    You should (really: should) read Brett's blog before continuing here: Improving the Beginner’s PID – Introduction « Project Blog.

    I fully agree.  It is a great tutorial with some very good links behind it as well.  Sometime back I built a sous vide controller using Brett's library and placed everything in an enclosure.  It controls a slow cooker not shown in the photo.  The temperature probe is inside a broken off whisk bought from the dollar store so as to isolate it from the walls of the cooker and food. There is no mains inside the enclosure - I use an external relay to drive the heating element in the cooker.  Being a mechanical engineer, that seemed the safe thing to do

    This is of course a very slow responding system.  It was a great learning experience and fun playing with the tuning parameters.  In the graph below I reset the temperature part way through to see how it responded.  There was a bit of overshoot but it settles to less than 0.5 F error quickly.

    Anyways, on to your example.  Thanks again for the series.

    • Cancel
    • Up +3 Down
    • Reply
    • More
    • Cancel
  • Jan Cumps
    Jan Cumps over 5 years ago

    A few sneak previews of the library in action.

    - MSP432 generates PWM, and an RC filter converts that to DC.

    - MSP432 ADC samples that DC

    - PID changes PWM duty cycle so that the sampled value matches a preset level.

     

     

    two captures with different PID parameters.

    proportional 1, integral 1, differential 0, steady

     

    proportional 1, integral 0, differential 0: nervous

     

    in part 2 I'll post the firmware and the RC filter.

    • Cancel
    • Up +2 Down
    • Reply
    • More
    • Cancel
  • jc2048
    jc2048 over 5 years ago in reply to Jan Cumps

    Thanks Jan, that's very helpful.

     

    I'm working on a couple of transistor blogs at the moment, but when they're done I'll give it a go and then I can see how I get on tuning a PID loop.

    • Cancel
    • Up 0 Down
    • Reply
    • More
    • Cancel
>
Element14

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2022 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • Facebook
  • Twitter
  • linkedin
  • YouTube