NOBのArduino日記!

NOBのArduino日記!

趣味は車・バイク・自転車・ラジコン・電子工作です。

PID_v1.hライブラリ(Display Functionsの使い方)

■Display Functions
 PID_v1.hライブラリのDisplay Functions である各種関数は、一度構築されたPIDコントローラに現在設定されている各種パラメータの設定値を返します。

■使用例
 Arduino IDEで使用するDisplay Functionsの使用例は以下の通りです。
 試しにこのプログラムをArduino UNOで実行すると、PID関数でユーザー定義変数(今回はmyPID)にPID制御に必要な変数とパラメータを設定します。
 setupでSetMode関数を使用し、デフォルトの「MANUAL」から「AUTOMATIC」モードに変更します。
 Display Functionsの各種関数から取得した現在PIDコントローラーに設定されているパラメータをPCのシリアルモニタ上に出力します。
 3番ピンで発生したPWM信号を直結された2番ピンで測定し、その結果から3番ピンの出力を、設定したDuty比70.6%(180)に近づく様にPIDアルゴリズムを含むCompute関数で求め出力します。
 また上記と合わせて、現在の入力値(input)と、出力値(output)が図1の様にPCのシリアルモニタ上に出力されます。

/*NOBのArduino日記!_PID制御!DisplayFunctions編_20170412*/
#include <PID_v1.h>
double Setpoint, Input, Output;
PID myPID(&Input, &Output, &Setpoint, 0.04, 0.04, 0.04, DIRECT); //初期値設定

// PWMのD比測定
volatile float Duty;
volatile unsigned long UpNew, UpOld, DownNew, DownOld;
void SUB() {
  if (digitalRead(2) == LOW) {
    DownOld = DownNew; DownNew = micros();
    Duty = ((DownNew - UpNew) * 1000) / ((UpNew - UpOld)) * 0.1;
  }
  else {
    UpOld = UpNew; UpNew = micros();
    Duty = ((DownNew - UpOld) * 1000) / (UpNew - UpOld) * 0.1;
  }
}

void setup() {
  pinMode(3, OUTPUT); pinMode(2, INPUT_PULLUP); //3ピン出力2ピン入力設定
  attachInterrupt(0, SUB, CHANGE);
  Serial.begin(9600);
  Setpoint = 180;//目標値設定
  myPID.SetMode(AUTOMATIC);//PID関数を実行
  Serial.print("Kp="); Serial.print(myPID.GetKp()); //PID関数のパラメータを出力
  Serial.print(",Ki="); Serial.print(myPID.GetKi());
  Serial.print(",Kd="); Serial.print(myPID.GetKd());
  Serial.print(",Mode="); Serial.print(myPID.GetMode());
  Serial.print(",Direction="); Serial.println(myPID.GetDirection());
}

void loop() {
  Input = map(Duty, 0, 100, 0, 255); //2ピン入力値取得
  myPID.Compute();
  analogWrite(3, Output);
  Serial.print("Input=");
  Serial.print(Input);
  Serial.print(",Output=");
  Serial.println(Output); delay(100);
}
イメージ 1
図1:プログラム例
 

イメージ 1 
図2:プログラム実行結果

 

■構文・パラメータ・戻り値

 取得可能なパラメータは表1に示す5種類です。これら関数は表示目的に便利です。

表1:Display Functionsの各関数と戻り値
構文 内容
 GetKp()  Kp値を返します
 GetKi()  Ki値を返します
 GetKd()  Kd値を返します
 GetMode()   0(MANUAL)または 1(AUTOMATIC)
 GetDirection()  0(DIRECT)または 1(REVERSE)
※これら関数にパラメータは有りません
 
イメージ 1 イメージ 3
励みになりますのでよければクリック下さい(^o^)/

↩【PID制御!】目次に戻る