-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhx711.js
140 lines (110 loc) · 2.71 KB
/
hx711.js
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
const { Gpio } = require('pigpio');
class HX711 {
constructor(clockPin, dataPin, options) {
this.options = {
scale: 1,
offset: 0,
continous: false,
...options,
}
this.dataPin = new Gpio(dataPin, {mode: Gpio.INPUT});
this.clockPin = new Gpio(clockPin, {mode: Gpio.OUTPUT, pullUpDown: Gpio.PUD_DOWN});
// Start loop if desired
this.continous = this.options.continous;
}
async readRaw(times = 1) {
let sum = 0;
for(let x = 0; x < times; x++) {
let value = 0;
// SCK is made LL
this.clockPin.digitalWrite(0);
// Wait until Data Line goes LOW
await new Promise((resolve, reject) => {
setImmediate(() => {
if(this.dataPin.digitalRead() === 0) {
resolve();
}
})
});
const buff = [];
// Read 24-bit data from HX711
for (let i = 0; i < 24; i++)
{
//generate CLK pulse
this.clock();
// Shift in the current bit
value = value << 1;
value += this.dataPin.digitalRead();
}
//generate CLK pulse
this.clock();
value = value ^ 0x800000;
sum += value;
}
this.lastRead = sum / times;
return sum / times;
}
async readOffset(times = 1) {
let value = await this.readRaw(times);
value -= this.offset;
return value;
}
async read(times = 1) {
let value = await this.readRaw(times);
value -= this.offset;
value *= this.scale;
return value;
}
getLastRaw() {
return this.lastRead;
}
getLastOffset() {
let value = this.lastRead;
value -= this.offset;
return value;
}
getLast() {
let value = this.lastRead;
value -= this.offset;
value *= this.scale;
return value;
}
async tare(times = 1) {
this.offset = await this.readRaw(times);
}
set scale(scale) {
this.options.scale = scale;
}
get scale() {
if(typeof this.options.scale === 'function') {
return this.options.scale();
}
return this.options.scale;
}
set offset(offset) {
this.options.offset = offset;
}
get offset() {
if(typeof this.options.offset === 'function') {
return this.options.offset();
}
return this.options.offset;
}
set continous(delay) {
this.options.continous = delay;
clearInterval(this.loop);
if(this.options.continous && Number.isNaN(this.options.continous) === false) {
// Get immediate first reading
this.readRaw();
// Setup loop at desired rate
this.loop = setInterval(() => {
this.readRaw();
}, this.options.continous);
}
}
clock() {
this.clockPin.digitalWrite(1);
this.clockPin.digitalWrite(0);
}
}
module.exports = HX711;