-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathACS712.cpp
64 lines (55 loc) · 1.22 KB
/
ACS712.cpp
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
#include "ACS712.h"
int zero;
ACS712::ACS712(ACS712_type type, uint8_t _pin) {
switch (type) {
case ACS712_05B:
sensitivity = 0.185;
break;
case ACS712_20A:
sensitivity = 0.100;
break;
case ACS712_30A:
sensitivity = 0.066;
break;
default:
sensitivity = 0.066;
break;
}
pin = _pin;
}
int ACS712::calibrate() {
int _zero = 0;
for (int i = 0; i < 10; i++) {
_zero += analogRead(pin);
delay(10);
}
_zero /= 10;
zero = _zero;
return _zero;
}
void setZeroPoint(int _zero) {
zero = _zero;
}
void ACS712::setSensitivity(float sens) {
sensitivity = sens;
}
float ACS712::getCurrentDC() {
float I = (zero - analogRead(pin)) / ADC_SCALE * VREF / sensitivity;
return I;
}
float ACS712::getCurrentAC() {
return getCurrentAC(DEFAULT_FREQUENCY);
}
float ACS712::getCurrentAC(uint16_t frequency) {
uint32_t period = 1000000 / frequency;
uint32_t t_start = micros();
uint32_t Isum = 0, measurements_count = 0;
int32_t Inow;
while (micros() - t_start < period) {
Inow = zero - analogRead(pin);
Isum += Inow*Inow;
measurements_count++;
}
float Irms = sqrt(Isum / measurements_count) / ADC_SCALE * VREF / sensitivity;
return Irms;
}