Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >基于Python编写的pid控制器

基于Python编写的pid控制器

作者头像
云深无际
发布于 2021-09-14 08:16:00
发布于 2021-09-14 08:16:00
1.2K00
代码可运行
举报
文章被收录于专栏:云深之无迹云深之无迹
运行总次数:0
代码可运行

我是学数学的,不是学自动化的,啥啥的自动控制,啥啥的信号系统,我啥也不懂,在恶补。

最基本的一个pid控制器

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import time


class PID:
    """PID Controller
    """

    def __init__(self, P=0.2, I=0.0, D=0.0, current_time=None):

        self.Kp = P
        self.Ki = I
        self.Kd = D

        self.sample_time = 0.00
        self.current_time = current_time if current_time is not None else time.time()
        self.last_time = self.current_time

        self.clear()

    def clear(self):
        """Clears PID computations and coefficients"""
        self.SetPoint = 0.0

        self.PTerm = 0.0
        self.ITerm = 0.0
        self.DTerm = 0.0
        self.last_error = 0.0

        # Windup Guard
        self.int_error = 0.0
        self.windup_guard = 20.0

        self.output = 0.0

    def update(self, feedback_value, current_time=None):
        """Calculates PID value for given reference feedback

        .. math::
            u(t) = K_p e(t) + K_i \int_{0}^{t} e(t)dt + K_d {de}/{dt}

        .. figure:: images/pid_1.png
           :align:   center

           Test PID with Kp=1.2, Ki=1, Kd=0.001 (test_pid.py)

        """
        error = self.SetPoint - feedback_value

        self.current_time = current_time if current_time is not None else time.time()
        delta_time = self.current_time - self.last_time
        delta_error = error - self.last_error

        if (delta_time >= self.sample_time):
            self.PTerm = self.Kp * error
            self.ITerm += error * delta_time

            if (self.ITerm < -self.windup_guard):
                self.ITerm = -self.windup_guard
            elif (self.ITerm > self.windup_guard):
                self.ITerm = self.windup_guard

            self.DTerm = 0.0
            if delta_time > 0:
                self.DTerm = delta_error / delta_time

            # Remember last time and last error for next calculation
            self.last_time = self.current_time
            self.last_error = error

            self.output = self.PTerm + \
                (self.Ki * self.ITerm) + (self.Kd * self.DTerm)

    def setKp(self, proportional_gain):
        """Determines how aggressively the PID reacts to the current error with setting Proportional Gain"""
        self.Kp = proportional_gain

    def setKi(self, integral_gain):
        """Determines how aggressively the PID reacts to the current error with setting Integral Gain"""
        self.Ki = integral_gain

    def setKd(self, derivative_gain):
        """Determines how aggressively the PID reacts to the current error with setting Derivative Gain"""
        self.Kd = derivative_gain

    def setWindup(self, windup):
        """Integral windup, also known as integrator windup or reset windup,
        refers to the situation in a PID feedback controller where
        a large change in setpoint occurs (say a positive change)
        and the integral terms accumulates a significant error
        during the rise (windup), thus overshooting and continuing
        to increase as this accumulated error is unwound
        (offset by errors in the other direction).
        The specific problem is the excess overshooting.
        """
        self.windup_guard = windup

    def setSampleTime(self, sample_time):
        """PID that should be updated at a regular interval.
        Based on a pre-determined sampe time, the PID decides if it should compute or return immediately.
        """
        self.sample_time = sample_time
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import PID
import time
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import BSpline, make_interp_spline  # Switched to BSpline


def test_pid(P=0.2,  I=0.0, D=0.0, L=100):
    """Self-test PID class
    .. note::
        ...
        for i in range(1, END):
            pid.update(feedback)
            output = pid.output
            if pid.SetPoint > 0:
                feedback += (output - (1/i))
            if i>9:
                pid.SetPoint = 1
            time.sleep(0.02)
        ---
    """
    pid = PID.PID(P, I, D)

    pid.SetPoint = 0.0
    pid.setSampleTime(0.01)

    END = L
    feedback = 0

    feedback_list = []
    time_list = []
    setpoint_list = []

    for i in range(1, END):
        pid.update(feedback)
        output = pid.output
        if pid.SetPoint > 0:
            feedback += (output - (1/i))
        if i > 9:
            pid.SetPoint = 1
        time.sleep(0.02)

        feedback_list.append(feedback)
        setpoint_list.append(pid.SetPoint)
        time_list.append(i)

    time_sm = np.array(time_list)
    time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300)

    # feedback_smooth = spline(time_list, feedback_list, time_smooth)
    # Using make_interp_spline to create BSpline
    helper_x3 = make_interp_spline(time_list, feedback_list)
    feedback_smooth = helper_x3(time_smooth)

    plt.plot(time_smooth, feedback_smooth)
    plt.plot(time_list, setpoint_list)
    plt.xlim((0, L))
    plt.ylim((min(feedback_list)-0.5, max(feedback_list)+0.5))
    plt.xlabel('time (s)')
    plt.ylabel('PID (PV)')
    plt.title('TEST PID')

    plt.ylim((1-0.5, 1+0.5))

    plt.grid(True)
    plt.show()


if __name__ == "__main__":
    test_pid(1.2, 1, 0.001, L=50)
#    test_pid(0.8, L=50)

测试用代码

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2021-07-31,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 云深之无迹 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
python实现PID
最近捣鼓ROS的时候,发现github上有人用python实现了PID,虽然可能执行效率不高,但是用python写工具的时候还是很方便的。从github上把代码搬下来,简单分析一下
py3study
2020/01/10
2.6K0
PID控制算法原理,并用python实现演示
PID:比列(Proportion),积分(Integral),微分(Differential)
小末快跑
2019/07/03
21.5K0
如何用PID算法,操控无人机悬停?
做控制时,大家经常会有这样的感受“代码很丰满,现实很骨感”,这是因为将计算机指令转移到实际硬件时,由于物体的惯性以及各种非理想化的因素影响,往往会出现实际与预期不符合的情况。
用户2366192
2023/09/02
8390
如何用PID算法,操控无人机悬停?
PID横向控制和仿真实现
PID是一种常见的控制算法,全称为Proportional-Integral-Derivative,即比例-积分-微分控制器。PID控制器是一种线性控制器,它将设定值与实际值进行比较,根据误差的大小,控制器会相应地调整系统的比例、积分和微分系数,以减小误差。
艰默
2024/01/11
4100
PID横向控制和仿真实现
PID算法原理、调整规律及代码
比例控制是一种最简单的控制方式。其控制器的输出与输入误差信号成比例关系。当仅有比例控制时系统输出存在稳态误差(Steady-state error)。
小锋学长生活大爆炸
2020/08/13
2.6K0
PID算法原理、调整规律及代码
电机控制进阶1——PID速度控制
之前的几篇文章(电机控制基础篇),介绍的电机编码器原理、定时器输出PWM、定时器编码器模式测速等。
xxpcb
2021/06/22
2.8K0
蓝桥ROS之f1tenth简单PID沿墙跑起来(Python)
在此案例前需完成: ☞ ​​​​​​蓝桥ROS之f1tenth案例学习与调试(成功) ---- 遥控肯定不过瘾,那么如何用一个PID程序使小车自动沿墙跑呢??? 公式如上…… 跑一跑看看? 阅读pdf文档: python程序模板: #!/usr/bin/env python from __future__ import print_function import sys import math import numpy as np #ROS Imports import rospy f
zhangrelay
2022/05/10
4220
蓝桥ROS之f1tenth简单PID沿墙跑起来(Python)
电机控制进阶——PID速度控制
之前的几篇文章(电机控制基础篇),介绍的电机编码器原理、定时器输出PWM、定时器编码器模式测速等。
xxpcb
2021/06/24
3.5K0
工业自动化中的嵌入式控制系统设计与优化
随着工业自动化的迅速发展,嵌入式控制系统在生产过程中扮演着至关重要的角色。本文将深入探讨工业自动化中嵌入式控制系统的设计与优化,介绍关键概念、技术挑战,并提供实际代码示例。
一键难忘
2023/12/12
4860
一阶系统又称为惯性系统_舵机惯性控制
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
全栈程序员站长
2022/11/09
5970
一阶系统又称为惯性系统_舵机惯性控制
AI在自动驾驶汽车中的应用与未来展望
随着人工智能技术的迅猛发展,自动驾驶汽车逐渐从科幻电影中的梦想走向现实。AI在自动驾驶汽车中的应用极大地提升了汽车的智能化水平,不仅提高了驾驶的安全性和舒适性,还为未来的智能交通系统提供了强大的技术支持。本文将详细介绍AI在自动驾驶汽车中的核心应用,并展望其未来发展方向。
Echo_Wish
2024/12/16
7510
AI在自动驾驶汽车中的应用与未来展望
蓝桥ROS云课→一键配置←f1tenth和PID绕圈
前轮转向移动机器人的实验目的是为了让学生了解和掌握前轮转向移动机器人的基本原理和控制方法,以及学习机器人运动学方面的知识。此外,该实验还可以培养学生的动手能力和团队合作精神,提高学生的实验操作能力和实验设计能力。
zhangrelay
2023/03/31
4290
蓝桥ROS云课→一键配置←f1tenth和PID绕圈
PID 控制器在工业自动化中的应用及参数调整方法
在工业自动化领域中,PID(比例-积分-微分)控制器是一种常用的控制算法,它通过调节输出信号,使被控对象的实际值尽可能接近设定值。PID 控制器的应用广泛,从简单的温度控制到复杂的过程控制都可以采用 PID 算法实现。本文将介绍 PID 控制器的作用与重要性,并编写一个简单的 PID 控制代码,然后解释代码的功能。此外,还将介绍 PID 参数调整的几种常用方法,以及该代码在不同应用场景下的修改部分。
剑指工控
2024/05/22
1.1K0
PID 控制器在工业自动化中的应用及参数调整方法
【C++】ROS:PID控制算法原理与仿真实现示例
PID(比例-积分-微分)算法是一种经典的控制算法,常用于控制系统中的反馈控制。它根据当前误差的大小和变化率,计算输出信号来调节控制器的行为,以使系统稳定并达到期望的目标。
DevFrank
2024/07/24
6840
在 FPGA 上快速构建 PID 算法
《优秀的IC/FPGA开源项目》是新开的系列,旨在介绍单一项目,会比《优秀的 Verilog/FPGA开源项目》内容介绍更加详细,包括但不限于综合、上板测试等。两者相辅相成,互补互充~
碎碎思
2022/11/14
1.4K0
在 FPGA 上快速构建 PID 算法
模糊PID控制算法的C++实现
很久没有更新博客了,今天就来讲讲模糊PID的C++实现方法。先来看一下整体的框架:
全栈程序员站长
2022/08/18
2.8K0
模糊PID控制算法的C++实现
控制工具PID
pressbooks.online.ucf.edu/phy2048tjb/chapter/15-5-damped-oscillations/
zhangrelay
2022/05/01
5870
PID控制算法仿真_连续控制系统的充分必要条件
PID控制是将误差信号e(t)的比例(P),积分(I)和微分(D)通过线性组合构成控制量进行控制,其输出信号为:
全栈程序员站长
2022/08/03
9550
PID控制算法仿真_连续控制系统的充分必要条件
PID控制基础篇(I)
最近有朋友在后台,咨询PID相关的内容。我们这几期来和大家分享下相关的知识和应用。
Hello工控
2024/06/25
3240
PID控制基础篇(I)
一文搞懂 | PID控制算法
PID 算法是工业应用中最广泛算法之一,在闭环系统的控制中,可自动对控制系统进行准确且迅速的校正。PID算法已经有100多年历史,在四轴飞行器,平衡小车、汽车定速巡航、温度控制器等场景均有应用。
混说Linux
2022/07/14
1.7K0
一文搞懂 | PID控制算法
相关推荐
python实现PID
更多 >
领券
💥开发者 MCP广场重磅上线!
精选全网热门MCP server,让你的AI更好用 🚀
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验