Click here to Skip to main content
15,894,405 members
Articles / Programming Languages / C#

Slaving Over a Hot Laptop,PID control loops and Sous Vide cooking

Rate me:
Please Sign up or sign in to vote.
4.81/5 (12 votes)
12 Feb 2012CPOL10 min read 40K   1K   25  
PID thermal control loop simulation
///////////////////////////////////////////////////////////////////////////////
//
//  PID.cs
//
//  By Philip R. Braica (HoshiKata@aol.com, VeryMadSci@gmail.com)
//
//  Distributed under the The Code Project Open License (CPOL)
//  http://www.codeproject.com/info/cpol10.aspx
///////////////////////////////////////////////////////////////////////////////

// Using.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SousVide
{
    /// <summary>
    /// PID.
    /// </summary>
    public class PID
    {
        double m_p = 0;
        double m_i = 0;
        double m_d = 0;
        double m_g = 0;
        double integral = 0;
        double last = 0;
        bool first = true;

        /// <summary>
        /// Setup.
        /// </summary>
        /// <param name="p"></param>
        public PID(double setPoint, double proportional, double integral, double derivative)
        {
            m_g = setPoint;
            m_p = proportional;
            m_i = integral;
            m_d = derivative;
            integral = 0;
        }

        /// <summary>
        /// Update
        /// </summary>
        /// <param name="goal"></param>
        /// <param name="sensor"></param>
        /// <returns></returns>
        public double Update(double sensor, double dt)
        {
            double error = m_g - sensor;

            integral = (0.9 * integral) + error;
            double derivative = first ? 0 : (sensor - last) / dt;
            last = sensor;
            first = false;

            return (m_p * error) + (m_i * integral) + (m_d * derivative);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
United States United States
Phil is a Principal Software developer focusing on weird yet practical algorithms that run the gamut of embedded and desktop (PID loops, Kalman filters, FFTs, client-server SOAP bindings, ASIC design, communication protocols, game engines, robotics).

In his personal life he is a part time mad scientist, full time dad, and studies small circle jujitsu, plays guitar and piano.

Comments and Discussions