Skip to content

Commit 666d836

Browse files
committed
features/unit/weight: integrates a HX711 24 bits A/D chip
1 parent 4437a4e commit 666d836

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

m5stack/libs/unit/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,5 @@
3232
from .ultrasonic_i2c import ULTRASONIC_I2CUnit
3333
from .limit import LIMITUnit
3434
from .op import OPUnit
35+
from .weight import WEIGHTUnit
36+
from .scales import SCALESUnit

m5stack/libs/unit/manifest.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@
3737
# "can.py",
3838
"limit.py",
3939
"op.py",
40+
"weight.py",
41+
"scales.py",
4042
),
4143
base_path="..",
4244
opt=0,

m5stack/libs/unit/weight.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
from machine import Pin
2+
import time
3+
from micropython import const
4+
5+
CHANNEL_A_128 = const(1)
6+
CHANNEL_A_64 = const(3)
7+
CHANNEL_B_32 = const(2)
8+
9+
DATA_BITS = const(24)
10+
MAX_VALUE = const(0x7fffff)
11+
MIN_VALUE = const(0x800000)
12+
13+
class WEIGHTUnit:
14+
def __init__(self, port) -> None:
15+
self.hx711data = Pin(port[0], Pin.IN)
16+
self.hx711clk = Pin(port[1], Pin.OUT)
17+
self.zero_value = 0
18+
self.hx711clk.value(0)
19+
self._channel=1
20+
self._scale=1.0
21+
22+
@property
23+
def get_raw_weight(self) -> int:
24+
count = 0
25+
if self.is_ready_wait():
26+
for i in range(24):
27+
self.hx711clk.value(1)
28+
time.sleep_us(1)
29+
self.hx711clk.value(0)
30+
time.sleep_us(1)
31+
if self.hx711data.value():
32+
count += 1
33+
count = count << 1
34+
else:
35+
return 0
36+
37+
gain_m = self._channel
38+
while gain_m:
39+
self.hx711clk.value(1)
40+
time.sleep_us(1)
41+
self.hx711clk.value(0)
42+
time.sleep_us(1)
43+
gain_m -= 1
44+
count = count ^ 0x800000
45+
return count
46+
47+
@property
48+
def get_scale_weight(self) -> int:
49+
return int((self.get_raw_weight - self.zero_value) * self._scale)
50+
51+
def set_tare(self) -> None:
52+
self.zero_value = self.get_raw_weight
53+
54+
def set_calibrate_scale(self, weight):
55+
self._scale = (1.0 * weight) / (self.get_raw_weight - self.zero_value)
56+
57+
def is_ready_wait(self) -> bool:
58+
times = 0
59+
while self.hx711data.value():
60+
times += 1
61+
time.sleep_ms(10)
62+
if times > 25:
63+
break
64+
return not self.hx711data.value()
65+
66+
def set_channel(self, chan: int) -> None:
67+
self._channel = chan
68+
for i in range(self._channel):
69+
self.hx711clk.value(1)
70+
time.sleep_us(1)
71+
self.hx711clk.value(0)
72+
time.sleep_us(1)
73+

0 commit comments

Comments
 (0)