让chatgpt写一段pid控制算法,看看效果如何。
通过调参也能实现收敛了。实际应用还是要看你具体的需求了。
话不多说上代码:
import matplotlib.pyplot as plt
import numpy as np
class PositionPID(object):
“”“位置式PID算法实现”“”
def __init__(self, target, cur_val, dt, max, min, p, i, d) -> None:self.dt = dt # 循环时间间隔self._max = max # 最大输出限制,规避过冲self._min = min # 最小输出限制self.k_p = p # 比例系数self.k_i = i # 积分系数self.k_d = d # 微分系数self.target = target # 目标值self.cur_val = cur_val # 算法当前PID位置值,第一次为设定的初始位置self._pre_error = 0 # t-1 时刻误差值self._integral = 0 # 误差积分值def calculate(self):"""计算t时刻PID输出值cur_val"""error = self.target - self.cur_val # 计算当前误差# 比例项p_out = self.k_p * error# 积分项self._integral += (error * self.dt)i_out = self.k_i * self._integral# 微分项derivative = (error - self._pre_error) / self.dtd_out = self.k_d * derivative# t 时刻pid输出output = p_out + i_out + d_out# 限制输出值if output > self._max:output = self._maxelif output < self._min:output = self._minself._pre_error = errorself.cur_val = outputreturn self.cur_valdef fit_and_plot(self, count=200):"""使用PID拟合setPoint"""counts = np.arange(count)outputs = []disantce=self.calculate()for i in counts:outputs.append(self.calculate())print('Count %3d: output: %f' % (i, outputs[-1]))print('Done')print(outputs)plt.figure()plt.axhline(self.target, c='red')plt.plot(counts, np.array(outputs), 'b.')plt.ylim(min(outputs) - 0.1 * min(outputs), max(outputs) + 0.1 * max(outputs))plt.plot(outputs)plt.show()
def out_distance(self):disantce = self.calculate()return disantce
p,i,d=0.4, 0.4, 0.01
pid = PositionPID(2000, 300, 0.5, 8000, 0, p,i,d)##pid比例系数、积分、微分
pid.fit_and_plot(200)
distance=pid.out_distance()
print(distance)