Python实现输入PID参数绘制波形

作者:热心市民鹿先生2024.01.17 14:19浏览量:7

简介:介绍如何使用Python绘制PID控制器的波形图,并通过输入PID参数进行实时控制。

千帆应用开发平台“智能体Pro”全新上线 限时免费体验

面向慢思考场景,支持低代码配置的方式创建“智能体Pro”应用

立即体验
  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. class PIDController:
  4. def __init__(self, kp, ki, kd):
  5. self.kp = kp
  6. self.ki = ki
  7. self.kd = kd
  8. self.previous_error = 0
  9. self.integral = 0
  10. def update(self, setpoint, measured_value):
  11. error = setpoint - measured_value
  12. self.integral += error
  13. derivative = (error - self.previous_error) / 0.01 # 假设采样时间为0.01秒
  14. output = self.kp * error + self.ki * self.integral + self.kd * derivative
  15. self.previous_error = error
  16. return output
  17. # 初始化PID控制器
  18. pid = PIDController(1.0, 0.5, 0.1)
  19. # 生成模拟数据
  20. time = np.arange(0, 10, 0.01) # 假设时间范围为0到10秒,采样间隔为0.01秒
  21. setpoint = np.sin(time) # 设置目标值为正弦波
  22. measurement = np.zeros_like(time) # 初始测量 值设为零
  23. # 绘制波形图
  24. plt.figure()
  25. plt.plot(time, setpoint, label='Setpoint')
  26. plt.plot(time, measurement, label='Measurement')
  27. plt.legend()
  28. plt.show()
  29. # 模拟PID控制过程
  30. for t in time:
  31. measurement[t] = pid.update(setpoint[t], measurement[t]) + np.random.normal(0, 0.1) # 加入随机噪声模拟实际测量 值
  32. plt.plot(t, measurement[t], 'o', ms=3) # 绘制当前时刻的测量 值
  33. plt.pause(0.01) # 暂停0.01秒,模拟实时更新波形图
article bottom image

相关文章推荐

发表评论