-
Notifications
You must be signed in to change notification settings - Fork 1
/
pid.c
111 lines (95 loc) · 2.54 KB
/
pid.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#include <string.h>
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <wiringPi.h>
int getTemp();
void setCorrection();
int setOut();
void pidcalc();
// pid variables
float e; // error value sp - pv
float ei; // error arkumulated
float kp = 1; //proportional gain
float ki = 1; //integral gain
float kd = 1; // deavirate gain
float pv; // tempereture
float pv_1 = 0; //forige temp
float pv_2 = 0; //forige af forige temp
float co = 0; // controller output
int secPassed = 0;
// cycletime for powerOut
int cycleTime = 2000;
// user setings
float sp = 57.0; // set point
int setTime = 60000;
int main(void)
{
time_t startTime = time(NULL);
unsigned startSec = (unsigned)startTime;
printf("You started cooking %s", ctime(&startTime));
while(setTime > secPassed){
secPassed = (unsigned)time(NULL) +12000 - startSec;
unsigned ssPassed = secPassed % 60;
unsigned hhPassed = secPassed / (60*60);
unsigned mmPassed = (secPassed - hhPassed*60*60) / 60;
printf("time passed is %u hours : %u minutes : %u seconds\n", hhPassed, mmPassed,ssPassed);
getTemp();
if(pv == 85){
getTemp();
}
pidCalc();
// printf("6\n");
setOut();
// printf("e %f\n ei %f\n kp %f\n ki %f\n kd %f\n pv %f\n pv_1 %f\n pv_2 e %f\n co %f\n", e, ei, kp, ki, kd, pv, pv_1, pv_2, co);
}
printf("Done");
}
int pidCalc(){
e = sp - pv;
ei += e;
float p = kp * (pv_1 - pv);
float i = ki*ei;
float d = kd * (2.0 * pv_1 - pv - pv_2);
pv_1 = pv;
pv_2 = pv_1;
co = p + i + d;
}
int setOut()
{
wiringPiSetup () ;
pinMode (0, OUTPUT) ;
float timeHigh = co
;
float timeLow = cycleTime - timeHigh;
printf("timeHigh = %d timeLow = %d\n", (int)timeHigh, (int)timeLow);
if(co > 0 && timeHigh > 0){
digitalWrite (0, HIGH) ; delay ((int)timeHigh) ;
digitalWrite (0, LOW) ; delay ((int)timeLow) ;
}
else{
digitalWrite (0, LOW) ; delay (2000) ;
}
return 0 ;
}
int getTemp() {
char tmp[5];
FILE *fp;
fp = fopen("/sys/bus/w1/devices/28-000005f5dac4/w1_slave", "r");
// fp = fopen("w1_slave", "r");
char buf[80];
if(fp == 0) {
perror ("Couldn't open the w1 device.");
return 1;
}
fgets(buf, 80, fp);
// printf("starting loop in getTemp\n" );
if(strstr(buf, "YES") != NULL){
fgets(buf, 80, fp);
strncpy(tmp, strstr(buf, "t=") + 2, 5);
pv = atoi(tmp) / 1000.0;
printf("pv = %f \n", pv );
}
fclose(fp);
return 1;
}