-
-
Save zawa-works/4930be12db0b2d2a346182a65de5363a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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