from machine import Pin
import utime
from machine import UART
# Pin configuration
HX711_SCK = Pin(4, Pin.OUT)
HX711_DT = Pin(13, Pin.IN)
known_weight = 100 # Known weight in grams
uart = UART(2, 115200, rx=16, tx=17)
fire_struct = Pin(15, Pin.OUT, Pin.PULL_DOWN)
def HX711_Read():
count = 0
HX711_DT.init(Pin.IN)
# Ensure DT line goes low
timeout = utime.ticks_ms() + 1000 # 1 second timeout
while HX711_DT.value() == 1:
if utime.ticks_ms() > timeout:
print("Timeout waiting for HX711 to go low")
return None
for _ in range(24):
HX711_SCK.value(1)
utime.sleep_us(1)
count = count << 1
HX711_SCK.value(0)
utime.sleep_us(1)
if HX711_DT.value() == 1:
count += 1
HX711_SCK.value(1)
count = count ^ 0x800000 # Convert to signed integer
utime.sleep_us(1)
HX711_SCK.value(0)
utime.sleep_us(1)
return count
def HX711_Tare():
tare_value = 0
for _ in range(10):
reading = HX711_Read()
if reading is None:
return None
tare_value += reading
utime.sleep(0.1)
tare_value /= 10
return tare_value
def Calibrate_Scale(tare_value, known_weight):
raw_value = 0
for _ in range(10):
reading = HX711_Read()
if reading is None:
return None
raw_value += reading
utime.sleep(0.1)
raw_value /= 10
return (raw_value - tare_value) / known_weight
def Get_Weight(tare_value, calibration_factor):
raw_value = HX711_Read()
if raw_value is None:
return None
weight = (raw_value - tare_value) / calibration_factor
return weight
if __name__ == "__main__":
fire_struct.value(0)
fire_Value=0
tare_value = HX711_Tare()
if tare_value is None:
print("Failed to tare the scale")
else:
calibration_factor = Calibrate_Scale(tare_value, known_weight)
if calibration_factor is None:
print("Failed to calibrate the scale")
else:
print(f"Calibration Factor: {calibration_factor}")
while True:
weight = Get_Weight(tare_value, calibration_factor)
if weight is not None:
uart.write(f"Weight: {weight:.2f} grams\n")
else:
print("Failed to read weight")
# Check for UART data
if uart.any():
state = uart.read().strip()
print(f"Received: {state}")
if state == b'1':
fire_Value = not fire_Value
fire_struct.value(fire_Value)
utime.sleep(0.05)