endail / hx711-pico-mpy

MicroPython implementation of HX711 use via RP2040's state machine
MIT License
12 stars 1 forks source link

Multiple sensors #3

Closed yeetivity closed 1 year ago

yeetivity commented 1 year ago

Althought the library works great for a single sensor, it does not yet seem to scale to support multiple sensors/instances of the libraray. When I tried this I received only values from one adc on both instances.

endail commented 1 year ago

Hi,

Can you please provide a copy of the code you've written?

yeetivity commented 1 year ago

Hi Endail,

Ofcourse! Sorry I didn't upload the code earlier. This is the code I used to try and make this library work with two sensors and read outputs:

from machine import Pin
from hx711 import *
from time import sleep_ms

#initialize led
led = Pin(25, Pin.OUT)
led.value(0)

# 1. initalise the two hx711 with the clock and data pin
hx1 = hx711(Pin(14), Pin(15))
hx2 = hx711(Pin(16), Pin(17))

# 2. power up
hx1.set_power(hx711.power.pwr_up)
hx2.set_power(hx711.power.pwr_up)

# 3. [OPTIONAL] set gain and save it to the hx711
# chip by powering down then back up
hx1.set_gain(hx711.gain.gain_128)
hx1.set_power(hx711.power.pwr_down)
hx711.wait_power_down()
hx1.set_power(hx711.power.pwr_up)

hx2.set_gain(hx711.gain.gain_128)
hx2.set_power(hx711.power.pwr_down)
hx711.wait_power_down()
hx2.set_power(hx711.power.pwr_up)

# 4. wait for readings to settle
hx711.wait_settle(hx711.rate.rate_10)

# 5. read values
while(True):
    # wait (block) until a value is read
    led.toggle()
    val1 = hx1.get_value()
    val2 = hx2.get_value()
    print(val1, val2)
    sleep_ms(100)

# 6. stop communication with HX711
#hx.close()

So this code only prints values from hx1, even though I made two instances (hx2.get_value() returns the value of hx1)

endail commented 1 year ago

When you initialise both HX711s, there is a third parameter to specify the index of the State Machine the underlying program runs on. State Machines 0 through 3 run on PIO 0, and State Machines 4 through 7 run on PIO 1. Try this:

# 1. initalise the two hx711 with the clock and data pin
hx1 = hx711(Pin(14), Pin(15), 0)
hx2 = hx711(Pin(16), Pin(17), 1)

That should work. If not, try the following so hx2 runs on PIO 1:

# 1. initalise the two hx711 with the clock and data pin
hx1 = hx711(Pin(14), Pin(15), 0)
hx2 = hx711(Pin(16), Pin(17), 4)

Give that a shot and let me know how you go!

yeetivity commented 1 year ago

I completely missed that I could specify the State Machine!

Just for your information; when I used State Machine 1 the code above will stop after starting up hx1 and doesn't start up hx2. After I switched to State Machine 4 (on the other PIO), it all worked :)

Thank you for your help!