109 lines
2.2 KiB
Python
109 lines
2.2 KiB
Python
import time
|
|
|
|
import neopixel
|
|
from machine import I2C, PWM, Pin, Timer
|
|
|
|
import ssd1306
|
|
from hx711 import *
|
|
|
|
buzzer = PWM(Pin(8, Pin.OUT))
|
|
neo = neopixel.NeoPixel(Pin(16), 1)
|
|
button = Pin(7, Pin.IN, Pin.PULL_UP)
|
|
i2c = I2C(1, scl=Pin(3), sda=Pin(2), freq=200000)
|
|
display = ssd1306.SSD1306_I2C(128, 64, i2c)
|
|
hx = hx711(Pin(14), Pin(15))
|
|
scaling = 410
|
|
value = 0
|
|
tara = 0
|
|
last_button = None
|
|
|
|
|
|
# freq:hz, duration: ms
|
|
def beep(freq, duration):
|
|
buzzer.freq(freq)
|
|
buzzer.duty_u16(22768)
|
|
time.sleep_ms(duration)
|
|
buzzer.duty_u16(0)
|
|
|
|
|
|
def led(r, g, b):
|
|
neo[0] = (r, g, b)
|
|
neo.write()
|
|
|
|
|
|
def callback(pin):
|
|
global last_button, tara
|
|
if not last_button or time.ticks_diff(time.ticks_ms(), last_button) > 500:
|
|
last_button = time.ticks_ms()
|
|
else:
|
|
print("Nope")
|
|
return
|
|
|
|
print("Interrupt has occured")
|
|
beep(1000, 100)
|
|
tara = value
|
|
print("Tara is {}".format(tara))
|
|
|
|
|
|
smoothing = 3
|
|
smoothing_values = []
|
|
|
|
|
|
def read_scale(_):
|
|
global value, smoothing_values
|
|
val = hx.get_value()
|
|
corrected = val / scaling
|
|
smoothing_values.append(corrected)
|
|
smoothing_values = smoothing_values[-smoothing:]
|
|
|
|
value = int(sum(smoothing_values) / smoothing)
|
|
|
|
|
|
def main():
|
|
global tara
|
|
print("Let's go!")
|
|
led(0, 0, 50)
|
|
|
|
display.text("Hello, World!", 0, 0, 1)
|
|
display.show()
|
|
|
|
# 2. power up
|
|
hx.set_power(hx711.power.pwr_up)
|
|
|
|
# 3. [OPTIONAL] set gain and save it to the hx711
|
|
# chip by powering down then back up
|
|
hx.set_gain(hx711.gain.gain_128)
|
|
hx.set_power(hx711.power.pwr_down)
|
|
hx711.wait_power_down()
|
|
hx.set_power(hx711.power.pwr_up)
|
|
|
|
# 4. wait for readings to settle
|
|
hx711.wait_settle(hx711.rate.rate_10)
|
|
|
|
display.text("Tara....", 0, 20, 1)
|
|
display.show()
|
|
|
|
for _ in range(3):
|
|
read_scale(None)
|
|
|
|
print("offset: {}".format(value))
|
|
tara = value
|
|
|
|
tim = Timer()
|
|
tim.init(period=100, mode=Timer.PERIODIC, callback=read_scale)
|
|
|
|
button.irq(trigger=Pin.IRQ_RISING, handler=callback)
|
|
|
|
while True:
|
|
x = value - tara
|
|
display.fill(0)
|
|
display.text("{} g".format(x), 0, 20, 1)
|
|
display.show()
|
|
time.sleep_ms(20)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
buzzer.init()
|
|
main()
|
|
hx.close()
|
|
buzzer.deinit()
|