-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathI2C_slave_address-11.ino
165 lines (117 loc) · 1.97 KB
/
I2C_slave_address-11.ino
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#include<I2C_Anything.h>
#include<Wire.h>
const byte MY_address=11;
const int encoder1=2;
volatile long count = 0;
long realCount ;
unsigned long lastRead = 0;
int a;
int pb;
const int in1=12;
const int in2=8;
float pwmpin=10;
float error=0;
float previouserror=0;
float ierror=0;
float derror=0;
float kp=0.00545, KP=0;
float ki=0.0099, KI=0;
float kd=0.01, KD=0;
long targetcount;
float output;
int pwm=0;
void setup(){
// put your setup code here, to run once:
Wire.begin(MY_address);
Serial.begin(9600);
Serial.println("start...");
pinMode(encoder1,INPUT_PULLUP);
attachInterrupt(0, isrCount, CHANGE);
a= digitalRead(encoder1);
Wire.onReceive(event);
}
void loop(){
// put your main code here, to run repeatedly:
analogWrite(pwmpin,pwm);
if (millis() - lastRead >= 100)
{
lastRead = millis();
//noInterrupts();
realCount = count;
count = 0;
//interrupts();
PID();
}
Serial.print(targetcount);
Serial.print(" ");
Serial.print(realCount);
Serial.print(" ");
Serial.println(pwm);
}
void isrCount()
{
count++;
}
void event()
{
I2C_readAnything(pb);
// Serial.println(pb);
targetcount=abs(pb);
if(pb>0)
{
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
}
if(pb<0)
{
digitalWrite(in1,LOW);
digitalWrite(in2,HIGH);
}
// if(pb==0)
// {
// analogWrite(pwmpin,0);
// }
//
}
void PID()
{
error=targetcount-realCount;
ierror=ierror+error;
derror=(error-previouserror);
// if(targetcount>=4000)
// {
// if (count==0)
// {
// ierror=0;
// }
// }
if(targetcount==0 || targetcount==1 )
{
KP=0;
KD=0;
KI=0;
ierror=0;
analogWrite(pwmpin,0);
}
else
{
KP=kp;
KD=kd;
KI=ki;
}
output=error*KP+ ierror*KI +derror*KD;
if(output>255)
{
pwm=255;
}
else if(output<=0)
{
pwm=0;
}
else
{
pwm=output;
}
previouserror=error;
analogWrite(pwmpin,pwm);
}