Skip to content

Instantly share code, notes, and snippets.

@zawa-works
Created November 27, 2022 20:32
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/1184360d5f628cbdce8a6e5f65865e98 to your computer and use it in GitHub Desktop.
Save zawa-works/1184360d5f628cbdce8a6e5f65865e98 to your computer and use it in GitHub Desktop.
#include <math.h>
//目標の温度
double targetTemperature = 40.0;
//リレーを制御するピン
int enablePin = 2;
//サーミスタ関係
double T; //サーミスタの温度(T)
int currentTemperture = A0;//サーミスタのピン
const float DIVIDER = 10000.0; // 分圧抵抗10kΩ
const float T0 = 273.15;
const float R0 = 27700.0;
const float B = 3435.0;
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);
pinMode(thermistorPin, INPUT);
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() {
float Aout = float(analogRead(thermistorPin));
// Serial.println(Aout);
float Rt = DIVIDER * Aout / (1024.0 - Aout);
float result = calcTemp(Rt);
return result;
}
float calcTemp(float Rt) {
float T_bar = 1 / T0 + 1 / B * log(Rt / R0);
return 1.0 / T_bar - 273.15;
}
void controlRelay() {
if (count >= 2) {
if (pid() > 255 / 2) {
digitalWrite(enablePin, HIGH);
} else {
digitalWrite(enablePin, LOW);
}
}
}
int pid(void) {
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