PID Python Demo

# pip install matplotlib
import time
import matplotlib.pyplot as plt
class PIDController:
    def __init__(self, kp, ki, kd):
        self.kp = kp
        self.ki = ki
        self.kd = kd
        self.prev_error = 0
        self.integral = 0
    def calculate(self, setpoint,
                current_value):
        error = setpoint - current_value
        self.integral += error
        derivative = error = self.prev_error
        # python cannot find self.kd,
        # but we defined it above.
        output = self.kp * error +\
            self.ki * self.integral +\
            self.kd * derivative
        self.prev_error = error
        return output

class AircraftSimulator:
    def __init__(self):
        self.height = 0
        self.velocity = 0
    def update(self, throttle, time_step):
        acceleration = throttle - 0.1 * self.velocity
        self.velocity += acceleration * time_step
        self.height += self.velocity * time_step

def main():
    kp = 5.0
    ki = 0.1
    kd = 10
    pid_controller = PIDController(kp, ki, id)
    aircraft_simulator = AircraftSimulator()
    target_height = 10.0
    # 步长0.1秒
    time_step = 0.1
    total_time = 20
    current_time = 0.0
    time_data = []
    height_data = []
    while (current_time < total_time):
        control_signal = pid_controller.calculate(
                target_height,
                aircraft_simulator.height)
        disturbance = -1.5
        control_signal += disturbance
        aircraft_simulator.update(
                control_signal,
                time_step)
        # 横坐标
        time_data.append(current_time)
        # 纵坐标
        height_data.append(
                aircraft_simulator.height)
        current_time += time_step
        time.sleep(time_step)
    print("Simulation completed.")

    plt.plot(time_data,
            height_data,
            label = 'Height')
    plt.axhline(
            y = target_height,
            color = 'r',
            linestyle = '--',
            label = 'Target Height')
    plt.xlabel('Time (s)')
    plt.ylabel('Height (m)')
    plt.title('Aircraft Height Control with Random Disturbance')
    plt.legend()
    plt.grid(True)
    plt.show()

if __name__ == '__main__':
    main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值