forked from CodersCafeTech/AutoBill
-
Notifications
You must be signed in to change notification settings - Fork 1
/
hx711.py
692 lines (612 loc) · 26.1 KB
/
hx711.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
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
"""
This file holds HX711 class
"""
#!/usr/bin/env python3
import statistics as stat
import time
import RPi.GPIO as GPIO
class HX711:
"""
HX711 represents chip for reading load cells.
"""
def __init__(self,
dout_pin,
pd_sck_pin,
gain_channel_A=128,
select_channel='A'):
"""
Init a new instance of HX711
Args:
dout_pin(int): Raspberry Pi pin number where the Data pin of HX711 is connected.
pd_sck_pin(int): Raspberry Pi pin number where the Clock pin of HX711 is connected.
gain_channel_A(int): Optional, by default value 128. Options (128 || 64)
select_channel(str): Optional, by default 'A'. Options ('A' || 'B')
Raises:
TypeError: if pd_sck_pin or dout_pin are not int type
"""
if (isinstance(dout_pin, int)):
if (isinstance(pd_sck_pin, int)):
self._pd_sck = pd_sck_pin
self._dout = dout_pin
else:
raise TypeError('pd_sck_pin must be type int. '
'Received pd_sck_pin: {}'.format(pd_sck_pin))
else:
raise TypeError('dout_pin must be type int. '
'Received dout_pin: {}'.format(dout_pin))
self._gain_channel_A = 0
self._offset_A_128 = 0 # offset for channel A and gain 128
self._offset_A_64 = 0 # offset for channel A and gain 64
self._offset_B = 0 # offset for channel B
self._last_raw_data_A_128 = 0
self._last_raw_data_A_64 = 0
self._last_raw_data_B = 0
self._wanted_channel = ''
self._current_channel = ''
self._scale_ratio_A_128 = 1 # scale ratio for channel A and gain 128
self._scale_ratio_A_64 = 1 # scale ratio for channel A and gain 64
self._scale_ratio_B = 1 # scale ratio for channel B
self._debug_mode = False
self._data_filter = self.outliers_filter # default it is used outliers_filter
GPIO.setup(self._pd_sck, GPIO.OUT) # pin _pd_sck is output only
GPIO.setup(self._dout, GPIO.IN) # pin _dout is input only
self.select_channel(select_channel)
self.set_gain_A(gain_channel_A)
def select_channel(self, channel):
"""
select_channel method evaluates if the desired channel
is valid and then sets the _wanted_channel variable.
Args:
channel(str): the channel to select. Options ('A' || 'B')
Raises:
ValueError: if channel is not 'A' or 'B'
"""
channel = channel.capitalize()
if (channel == 'A'):
self._wanted_channel = 'A'
elif (channel == 'B'):
self._wanted_channel = 'B'
else:
raise ValueError('Parameter "channel" has to be "A" or "B". '
'Received: {}'.format(channel))
# after changing channel or gain it has to wait 50 ms to allow adjustment.
# the data before is garbage and cannot be used.
self._read()
time.sleep(0.5)
def set_gain_A(self, gain):
"""
set_gain_A method sets gain for channel A.
Args:
gain(int): Gain for channel A (128 || 64)
Raises:
ValueError: if gain is different than 128 or 64
"""
if gain == 128:
self._gain_channel_A = gain
elif gain == 64:
self._gain_channel_A = gain
else:
raise ValueError('gain has to be 128 or 64. '
'Received: {}'.format(gain))
# after changing channel or gain it has to wait 50 ms to allow adjustment.
# the data before is garbage and cannot be used.
self._read()
time.sleep(0.5)
def zero(self, readings=30):
"""
zero is a method which sets the current data as
an offset for particulart channel. It can be used for
subtracting the weight of the packaging. Also known as tare.
Args:
readings(int): Number of readings for mean. Allowed values 1..99
Raises:
ValueError: if readings are not in range 1..99
Returns: True if error occured.
"""
if readings > 0 and readings < 100:
result = self.get_raw_data_mean(readings)
if result != False:
if (self._current_channel == 'A' and
self._gain_channel_A == 128):
self._offset_A_128 = result
return False
elif (self._current_channel == 'A' and
self._gain_channel_A == 64):
self._offset_A_64 = result
return False
elif (self._current_channel == 'B'):
self._offset_B = result
return False
else:
if self._debug_mode:
print('Cannot zero() channel and gain mismatch.\n'
'current channel: {}\n'
'gain A: {}\n'.format(self._current_channel,
self._gain_channel_A))
return True
else:
if self._debug_mode:
print('From method "zero()".\n'
'get_raw_data_mean(readings) returned False.\n')
return True
else:
raise ValueError('Parameter "readings" '
'can be in range 1 up to 99. '
'Received: {}'.format(readings))
def set_offset(self, offset, channel='', gain_A=0):
"""
set offset method sets desired offset for specific
channel and gain. Optional, by default it sets offset for current
channel and gain.
Args:
offset(int): specific offset for channel
channel(str): Optional, by default it is the current channel.
Or use these options ('A' || 'B')
Raises:
ValueError: if channel is not ('A' || 'B' || '')
TypeError: if offset is not int type
"""
channel = channel.capitalize()
if isinstance(offset, int):
if channel == 'A' and gain_A == 128:
self._offset_A_128 = offset
return
elif channel == 'A' and gain_A == 64:
self._offset_A_64 = offset
return
elif channel == 'B':
self._offset_B = offset
return
elif channel == '':
if self._current_channel == 'A' and self._gain_channel_A == 128:
self._offset_A_128 = offset
return
elif self._current_channel == 'A' and self._gain_channel_A == 64:
self._offset_A_64 = offset
return
else:
self._offset_B = offset
return
else:
raise ValueError('Parameter "channel" has to be "A" or "B". '
'Received: {}'.format(channel))
else:
raise TypeError('Parameter "offset" has to be integer. '
'Received: ' + str(offset) + '\n')
def set_scale_ratio(self, scale_ratio, channel='', gain_A=0):
"""
set_scale_ratio method sets the ratio for calculating
weight in desired units. In order to find this ratio for
example to grams or kg. You must have known weight.
Args:
scale_ratio(float): number > 0.0 that is used for
conversion to weight units
channel(str): Optional, by default it is the current channel.
Or use these options ('a'|| 'A' || 'b' || 'B')
gain_A(int): Optional, by default it is the current channel.
Or use these options (128 || 64)
Raises:
ValueError: if channel is not ('A' || 'B' || '')
TypeError: if offset is not int type
"""
channel = channel.capitalize()
if isinstance(gain_A, int):
if channel == 'A' and gain_A == 128:
self._scale_ratio_A_128 = scale_ratio
return
elif channel == 'A' and gain_A == 64:
self._scale_ratio_A_64 = scale_ratio
return
elif channel == 'B':
self._scale_ratio_B = scale_ratio
return
elif channel == '':
if self._current_channel == 'A' and self._gain_channel_A == 128:
self._scale_ratio_A_128 = scale_ratio
return
elif self._current_channel == 'A' and self._gain_channel_A == 64:
self._scale_ratio_A_64 = scale_ratio
return
else:
self._scale_ratio_B = scale_ratio
return
else:
raise ValueError('Parameter "channel" has to be "A" or "B". '
'received: {}'.format(channel))
else:
raise TypeError('Parameter "gain_A" has to be integer. '
'Received: ' + str(gain_A) + '\n')
def set_data_filter(self, data_filter):
"""
set_data_filter method sets data filter that is passed as an argument.
Args:
data_filter(data_filter): Data filter that takes list of int numbers and
returns a list of filtered int numbers.
Raises:
TypeError: if filter is not a function.
"""
if callable(data_filter):
self._data_filter = data_filter
else:
raise TypeError('Parameter "data_filter" must be a function. '
'Received: {}'.format(data_filter))
def set_debug_mode(self, flag=False):
"""
set_debug_mode method is for turning on and off
debug mode.
Args:
flag(bool): True turns on the debug mode. False turns it off.
Raises:
ValueError: if fag is not bool type
"""
if flag == False:
self._debug_mode = False
print('Debug mode DISABLED')
return
elif flag == True:
self._debug_mode = True
print('Debug mode ENABLED')
return
else:
raise ValueError('Parameter "flag" can be only BOOL value. '
'Received: {}'.format(flag))
def _save_last_raw_data(self, channel, gain_A, data):
"""
_save_last_raw_data saves the last raw data for specific channel and gain.
Args:
channel(str):
gain_A(int):
data(int):
Returns: False if error occured
"""
if channel == 'A' and gain_A == 128:
self._last_raw_data_A_128 = data
elif channel == 'A' and gain_A == 64:
self._last_raw_data_A_64 = data
elif channel == 'B':
self._last_raw_data_B = data
else:
return False
def _ready(self):
"""
_ready method check if data is prepared for reading from HX711
Returns: bool True if ready else False when not ready
"""
# if DOUT pin is low data is ready for reading
if GPIO.input(self._dout) == 0:
return True
else:
return False
def _set_channel_gain(self, num):
"""
_set_channel_gain is called only from _read method.
It finishes the data transmission for HX711 which sets
the next required gain and channel.
Args:
num(int): how many ones it sends to HX711
options (1 || 2 || 3)
Returns: bool True if HX711 is ready for the next reading
False if HX711 is not ready for the next reading
"""
for _ in range(num):
start_counter = time.perf_counter()
GPIO.output(self._pd_sck, True)
GPIO.output(self._pd_sck, False)
end_counter = time.perf_counter()
# check if hx 711 did not turn off...
if end_counter - start_counter >= 0.00006:
# if pd_sck pin is HIGH for 60 us and more than the HX 711 enters power down mode.
if self._debug_mode:
print('Not enough fast while setting gain and channel')
print(
'Time elapsed: {}'.format(end_counter - start_counter))
# hx711 has turned off. First few readings are inaccurate.
# Despite it, this reading was ok and data can be used.
result = self.get_raw_data_mean(6) # set for the next reading.
if result == False:
return False
return True
def _read(self):
"""
_read method reads bits from hx711, converts to INT
and validate the data.
Returns: (bool || int) if it returns False then it is false reading.
if it returns int then the reading was correct
"""
GPIO.output(self._pd_sck, False) # start by setting the pd_sck to 0
ready_counter = 0
while (not self._ready() and ready_counter <= 40):
time.sleep(0.01) # sleep for 10 ms because data is not ready
ready_counter += 1
if ready_counter == 50: # if counter reached max value then return False
if self._debug_mode:
print('self._read() not ready after 40 trials\n')
return False
# read first 24 bits of data
data_in = 0 # 2's complement data from hx 711
for _ in range(24):
start_counter = time.perf_counter()
# request next bit from hx 711
GPIO.output(self._pd_sck, True)
GPIO.output(self._pd_sck, False)
end_counter = time.perf_counter()
if end_counter - start_counter >= 0.00006: # check if the hx 711 did not turn off...
# if pd_sck pin is HIGH for 60 us and more than the HX 711 enters power down mode.
if self._debug_mode:
print('Not enough fast while reading data')
print(
'Time elapsed: {}'.format(end_counter - start_counter))
return False
# Shift the bits as they come to data_in variable.
# Left shift by one bit then bitwise OR with the new bit.
data_in = (data_in << 1) | GPIO.input(self._dout)
if self._wanted_channel == 'A' and self._gain_channel_A == 128:
if not self._set_channel_gain(1): # send only one bit which is 1
return False # return False because channel was not set properly
else:
self._current_channel = 'A' # else set current channel variable
self._gain_channel_A = 128 # and gain
elif self._wanted_channel == 'A' and self._gain_channel_A == 64:
if not self._set_channel_gain(3): # send three ones
return False # return False because channel was not set properly
else:
self._current_channel = 'A' # else set current channel variable
self._gain_channel_A = 64
else:
if not self._set_channel_gain(2): # send two ones
return False # return False because channel was not set properly
else:
self._current_channel = 'B' # else set current channel variable
if self._debug_mode: # print 2's complement value
print('Binary value as received: {}'.format(bin(data_in)))
#check if data is valid
if (data_in == 0x7fffff
or # 0x7fffff is the highest possible value from hx711
data_in == 0x800000
): # 0x800000 is the lowest possible value from hx711
if self._debug_mode:
print('Invalid data detected: {}\n'.format(data_in))
return False # rturn false because the data is invalid
# calculate int from 2's complement
signed_data = 0
# 0b1000 0000 0000 0000 0000 0000 check if the sign bit is 1. Negative number.
if (data_in & 0x800000):
signed_data = -(
(data_in ^ 0xffffff) + 1) # convert from 2's complement to int
else: # else do not do anything the value is positive number
signed_data = data_in
if self._debug_mode:
print('Converted 2\'s complement value: {}'.format(signed_data))
return signed_data
def get_raw_data_mean(self, readings=30):
"""
get_raw_data_mean returns mean value of readings.
Args:
readings(int): Number of readings for mean.
Returns: (bool || int) if False then reading is invalid.
if it returns int then reading is valid
"""
# do backup of current channel befor reading for later use
backup_channel = self._current_channel
backup_gain = self._gain_channel_A
data_list = []
# do required number of readings
for _ in range(readings):
data_list.append(self._read())
data_mean = False
if readings > 2 and self._data_filter:
filtered_data = self._data_filter(data_list)
if not filtered_data:
return False
if self._debug_mode:
print('data_list: {}'.format(data_list))
print('filtered_data list: {}'.format(filtered_data))
print('data_mean:', stat.mean(filtered_data))
data_mean = stat.mean(filtered_data)
else:
data_mean = stat.mean(data_list)
self._save_last_raw_data(backup_channel, backup_gain, data_mean)
return int(data_mean)
def get_data_mean(self, readings=30):
"""
get_data_mean returns average value of readings minus
offset for the channel which was read.
Args:
readings(int): Number of readings for mean
Returns: (bool || int) False if reading was not ok.
If it returns int then reading was ok
"""
result = self.get_raw_data_mean(readings)
if result != False:
if self._current_channel == 'A' and self._gain_channel_A == 128:
return result - self._offset_A_128
elif self._current_channel == 'A' and self._gain_channel_A == 64:
return result - self._offset_A_64
else:
return result - self._offset_B
else:
return False
def get_weight_mean(self, readings=30):
"""
get_weight_mean returns average value of readings minus
offset divided by scale ratio for a specific channel
and gain.
Args:
readings(int): Number of readings for mean
Returns: (bool || float) False if reading was not ok.
If it returns float then reading was ok
"""
result = self.get_raw_data_mean(readings)
if result != False:
if self._current_channel == 'A' and self._gain_channel_A == 128:
return float(
(result - self._offset_A_128) / self._scale_ratio_A_128)
elif self._current_channel == 'A' and self._gain_channel_A == 64:
return float(
(result - self._offset_A_64) / self._scale_ratio_A_64)
else:
return float((result - self._offset_B) / self._scale_ratio_B)
else:
return False
def get_current_channel(self):
"""
get current channel returns the value of current channel.
Returns: ('A' || 'B')
"""
return self._current_channel
def get_data_filter(self):
"""
get data filter.
Returns: self._data_filter
"""
return self._data_filter
def get_current_gain_A(self):
"""
get current gain A returns the value of current gain on channel A
Returns: (128 || 64) current gain on channel A
"""
return self._gain_channel_A
def get_last_raw_data(self, channel='', gain_A=0):
"""
get last raw data returns the last read data for a
channel and gain. By default for current one.
Args:
channel(str): select channel ('A' || 'B'). If not then it returns the current one.
gain_A(int): select gain (128 || 64). If not then it returns the current one.
Raises:
ValueError: if channel is not ('A' || 'B' || '') or gain_A is not (128 || 64 || 0)
'' and 0 is default value.
Returns: int the last data that was received for the chosen channel and gain
"""
channel = channel.capitalize()
if channel == 'A' and gain_A == 128:
return self._last_raw_data_A_128
elif channel == 'A' and gain_A == 64:
return self._last_raw_data_A_64
elif channel == 'B':
return self._last_raw_data_B
elif channel == '':
if self._current_channel == 'A' and self._gain_channel_A == 128:
return self._last_raw_data_A_128
elif self._current_channel == 'A' and self._gain_channel_A == 64:
return self._last_raw_data_A_64
else:
return self._last_raw_data_B
else:
raise ValueError(
'Parameter "channel" has to be "A" or "B". '
'Received: {} \nParameter "gain_A" has to be 128 or 64. Received {}'
.format(channel, gain_A))
def get_current_offset(self, channel='', gain_A=0):
"""
get current offset returns the current offset for
a particular channel and gain. By default the current one.
Args:
channel(str): select for which channel ('A' || 'B')
gain_A(int): select for which gain (128 || 64)
Raises:
ValueError: if channel is not ('A' || 'B' || '') or gain_A is not (128 || 64 || 0)
'' and 0 is default value.
Returns: int the offset for the chosen channel and gain
"""
channel = channel.capitalize()
if channel == 'A' and gain_A == 128:
return self._offset_A_128
elif channel == 'A' and gain_A == 64:
return self._offset_A_64
elif channel == 'B':
return self._offset_B
elif channel == '':
if self._current_channel == 'A' and self._gain_channel_A == 128:
return self._offset_A_128
elif self._current_channel == 'A' and self._gain_channel_A == 64:
return self._offset_A_64
else:
return self._offset_B
else:
raise ValueError(
'Parameter "channel" has to be "A" or "B". '
'Received: {} \nParameter "gain_A" has to be 128 or 64. Received {}'
.format(channel, gain_A))
def get_current_scale_ratio(self, channel='', gain_A=0):
"""
get current scale ratio returns the current scale ratio
for a particular channel and gain. By default
the current one.
Args:
channel(str): select for which channel ('A' || 'B')
gain_A(int): select for which gain (128 || 64)
Returns: int the scale ratio for the chosen channel and gain
"""
channel = channel.capitalize()
if channel == 'A' and gain_A == 128:
return self._scale_ratio_A_128
elif channel == 'A' and gain_A == 64:
return self._scale_ratio_A_64
elif channel == 'B':
return self._scale_ratio_B
elif channel == '':
if self._current_channel == 'A' and self._gain_channel_A == 128:
return self._scale_ratio_A_128
elif self._current_channel == 'A' and self._gain_channel_A == 64:
return self._scale_ratio_A_64
else:
return self._scale_ratio_B
else:
raise ValueError(
'Parameter "channel" has to be "A" or "B". '
'Received: {} \nParameter "gain_A" has to be 128 or 64. Received {}'
.format(channel, gain_A))
def power_down(self):
"""
power down method turns off the hx711.
"""
GPIO.output(self._pd_sck, False)
GPIO.output(self._pd_sck, True)
time.sleep(0.01)
def power_up(self):
"""
power up function turns on the hx711.
"""
GPIO.output(self._pd_sck, False)
time.sleep(0.01)
def reset(self):
"""
reset method resets the hx711 and prepare it for the next reading.
Returns: True if error encountered
"""
self.power_down()
self.power_up()
result = self.get_raw_data_mean(6)
if result:
return False
else:
return True
def outliers_filter(self, data_list, stdev_thresh = 1.0):
"""
It filters out outliers from the provided list of int.
Median is used as an estimator of outliers.
Outliers are compared to the standard deviation from the median
Default filter is of 1.0 standard deviation from the median
Args:
data_list([int]): List of int. It can contain Bool False that is removed.
Returns: list of filtered data. Excluding outliers.
"""
# filter out -1 which indicates no signal
# filter out booleans
data = [num for num in data_list if (num != -1 and num != False and num != True)]
if not data:
return []
median = stat.median(data)
dists_from_median = [(abs(measurement - median)) for measurement in data]
stdev = stat.stdev(dists_from_median)
if stdev:
ratios_to_stdev = [(dist / stdev) for dist in dists_from_median]
else:
# stdev is 0. Therefore return just the median
return [median]
filtered_data = []
for i in range(len(data)):
if ratios_to_stdev[i] < stdev_thresh:
filtered_data.append(data[i])
return filtered_data