Skip to content

Instantly share code, notes, and snippets.

@zawa-works
Created November 26, 2022 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zawa-works/4930be12db0b2d2a346182a65de5363a to your computer and use it in GitHub Desktop.
Save zawa-works/4930be12db0b2d2a346182a65de5363a to your computer and use it in GitHub Desktop.
#include <math.h>
//目標の温度
double targetTemperature = 40.0;
//リレーを制御するピン
int enablePin = 2;
double currentTemperture; //温度センサの温度
int count = 0;
double input = 255.0;
double preinput = 255.0;
double deltainput = 0;
double e = 0;
double e1 = 0;
double e2 = 0;
double kp = 2.0; //比例ゲイン
double ki = 1.0; //積分ゲイン
double kd = 0.5; // 微分ゲイン
void setup() {
Serial.begin(9600);
pinMode(A0, INPUT); //A0番ピンを入力用に設定する
pinMode(enablePin, OUTPUT);
digitalWrite(enablePin, HIGH);
}
void loop() {
currentTemperture = getTemperature();
Serial.print(targetTemperature);
Serial.print(", ");
Serial.println(currentTemperture);
if (targetTemperature <= 24.0) {
e = currentTemperture - targetTemperature;
} else {
e = targetTemperature - currentTemperture;
}
controlRelay();
if (count == 0) {
e1 = e;
preinput = input;
} else {
e1 = e;
e2 = e1;
preinput = input;
}
count++;
delay(1000);
}
double getTemperature() {
double result = 0;
for (int i = 0; i < 10; i++) {
result += analogRead(0) * (5.0 / 1023.0) * 100;
}
result /= 10;
return result;
}
void controlRelay() {
if (count >= 2) {
if (pid() > 125) {
digitalWrite(enablePin, HIGH);
} else {
digitalWrite(enablePin, LOW);
}
}
}
//PID制御
int pid() {
deltainput = kp * (e - e1) + ki * e + kd * ((e - e1) - (e1 - e2));
input = preinput + deltainput;
input = constrain(input, 0, 255);
return input;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment