forked from dcrystalj/hx711py3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscale.py
65 lines (46 loc) · 1.63 KB
/
scale.py
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
#!/usr/bin/python3
import statistics
from hx711 import HX711
class Scale:
def __init__(self, source=None, samples=20, spikes=4, sleep=0.1):
self.source = source or HX711()
self.samples = samples
self.spikes = spikes
self.sleep = sleep
self.history = []
def newMeasure(self):
value = self.source.getWeight()
self.history.append(value)
def getMeasure(self):
"""Useful for continuous measurements."""
self.newMeasure()
# cut to old values
self.history = self.history[-self.samples:]
avg = statistics.mean(self.history)
deltas = sorted([abs(i-avg) for i in self.history])
if len(deltas) < self.spikes:
max_permitted_delta = deltas[-1]
else:
max_permitted_delta = deltas[-self.spikes]
valid_values = list(filter(
lambda val: abs(val - avg) <= max_permitted_delta, self.history
))
avg = statistics.mean(valid_values)
return avg
def getWeight(self, samples=None):
"""Get weight for once in a while. It clears history first."""
self.history = []
[self.newMeasure() for i in range(samples or self.samples)]
return self.getMeasure()
def tare(self, times=25):
self.source.tare(times)
def setOffset(self, offset):
self.source.setOffset(offset)
def setReferenceUnit(self, reference_unit):
self.source.setReferenceUnit(reference_unit)
def powerDown(self):
self.source.powerDown()
def powerUp(self):
self.source.powerUp()
def reset(self):
self.source.reset()