from machine import Pin
from hx711 import HX711
import utime
import machine
from time import sleep
from picozero import Speaker


LoadCell_SCK_pin = 8
LoadCell_DOUT_pin = 9
LoadCellDout = Pin(LoadCell_DOUT_pin, Pin.IN, pull=Pin.PULL_DOWN) 
LoadCellSck = Pin(LoadCell_SCK_pin, Pin.OUT)
LoadCell = HX711(LoadCellSck, LoadCellDout)

led_red_load = Pin(26,Pin.OUT)
LoadCell.read_avg()
LoadCellScaling = 2058
LoadCellOffset =  0


trig1 = Pin (2, Pin.OUT)
echo1 = Pin (3, Pin.IN)

led_red = Pin(10,Pin.OUT)
led_blue = Pin(11,Pin.OUT)
led_green = Pin(12,Pin.OUT)
buzzer = Speaker(5)
button = Pin(21,Pin.IN,Pin.PULL_UP)
def dis1():
  timet1 = 0

  trig1.low()
  utime.sleep_us(2)
  trig1.high()
  utime.sleep_us(5)
  trig1.low()

  while echo1.value() == 0:
    signal1off = utime.ticks_us()

  while echo1.value() == 1:
    signal1on = utime.ticks_us()

  timet1 = signal1on - signal1off
  return timet1

buzzer_count = 0
choice = 1

while True:
    print("------ Add weight Main weight ----")
    print("Org Starts .. ....")
    TBW = ((LoadCell.read() - LoadCellOffset)/LoadCellScaling)*4.9
    time1 = dis1()
    sleep(1)
    cm1 = time1 * 0.034 / 2
    # Printing Distance
    print ("Distance : ", cm1, "cm")
    print("Dis-Choice ",choice)
     
    if TBW>-1 and TBW<0:
        TBW =0
    TBW = round(TBW, 2)
    # Printing TBW
    print("Weight :",TBW,"Kg")
    if TBW > 4.7:
        led_red_load.value(1)
        print("Overweight...!! ")
    else:
        led_red_load.value(0)
        

    
  
    if button.value() == 0:
      if choice<3:
          choice +=1
          print(choice)
          buzzer.on()
          sleep(0.5)
          buzzer.off()
      else:
          choice =1
          print(choice)
          buzzer.on()
          sleep(0.5)
          buzzer.off()

    # if choice 1 == buzzer "on" level is 45 cm 
    # if choice 2 == buzzer "on" level is 25 cm 
    # if choice 3 == buzzer "off"

    if cm1 <= 5:
      led_red.value(0)
      led_blue.value(1)
      led_green.value(1)
      if buzzer_count == 0 and choice == 1:
          for i in range(5):
              buzzer.on()
              sleep(1)
              buzzer.off()
              sleep(1)
      buzzer_count = 1

    elif cm1 < 25 and cm1 > 5:
      led_blue.value(1)
      led_red.value(0)
      led_green.value(0)
      if buzzer_count == 0 and choice == 2:
          for i in range(5):
              buzzer.on()
              sleep(1)
              buzzer.off()
              sleep(1)
      buzzer_count = 1
      if choice == 1:
          buzzer_count =0
    else:
      led_green.value(0)
      led_blue.value(1)
      led_red.value(1)
      buzzer_count =0
   
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT