Trying to read load of hx711 on raspberry pi

Hello, i am pretty new in the node red topic and currently trying to get the weight of my hx711 load sensor in node-red but i am not able to do it. I saw that there is the palette node-red-contrib-hx711 which looked easy to use but i only get 0 values even with the given flow of its github entry. I also tried it directly over python on my raspberry pi - there it works to read the load but i am unable to get the data into nodered

nodered v 3.1.3
nodejs 18.19.0

flow:

[
    {
        "id": "5d3ceb36.b1a4a4",
        "type": "tab",
        "label": "Flow 1",
        "disabled": false,
        "info": ""
    },
    {
        "id": "ccb72235.6747",
        "type": "inject",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "2",
        "crontab": "",
        "once": true,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "Initialize",
        "payloadType": "str",
        "x": 360,
        "y": 200,
        "wires": [
            [
                "42a327b2.f97038"
            ]
        ]
    },
    {
        "id": "25eb352f.bccd5a",
        "type": "rbe",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "func": "narrowband",
        "gap": "0.5",
        "start": "",
        "inout": "in",
        "septopics": true,
        "property": "payload",
        "topi": "topic",
        "x": 750,
        "y": 260,
        "wires": [
            [
                "ccc66ff.aaaca9"
            ]
        ]
    },
    {
        "id": "42a327b2.f97038",
        "type": "hx711",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "hx_data": "29",
        "hx_sck": "31",
        "hx_scale": "216",
        "hx_gain": "64",
        "hx_offset": "0",
        "hx_avrg": "1",
        "x": 590,
        "y": 260,
        "wires": [
            [
                "25eb352f.bccd5a"
            ]
        ]
    },
    {
        "id": "285228f5.b48c18",
        "type": "inject",
        "z": "5d3ceb36.b1a4a4",
        "name": "Tare",
        "props": [
            {
                "p": "tare",
                "v": "",
                "vt": "date"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "x": 350,
        "y": 260,
        "wires": [
            [
                "42a327b2.f97038"
            ]
        ]
    },
    {
        "id": "ccc66ff.aaaca9",
        "type": "smooth",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "property": "payload",
        "action": "mean",
        "count": "30",
        "round": "",
        "mult": "single",
        "reduce": false,
        "x": 940,
        "y": 260,
        "wires": [
            [
                "73277f82476c5f13"
            ]
        ]
    },
    {
        "id": "635f5cfa7963a221",
        "type": "ui_chart",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "group": "301ee099fd1bc275",
        "order": 0,
        "width": 0,
        "height": 0,
        "label": "chart",
        "chartType": "line",
        "legend": "false",
        "xformat": "HH:mm:ss",
        "interpolate": "linear",
        "nodata": "",
        "dot": false,
        "ymin": "",
        "ymax": "",
        "removeOlder": 1,
        "removeOlderPoints": "",
        "removeOlderUnit": "3600",
        "cutout": 0,
        "useOneColor": false,
        "useUTC": false,
        "colors": [
            "#1f77b4",
            "#aec7e8",
            "#ff7f0e",
            "#2ca02c",
            "#98df8a",
            "#d62728",
            "#ff9896",
            "#9467bd",
            "#c5b0d5"
        ],
        "outputs": 1,
        "useDifferentColor": false,
        "className": "",
        "x": 1130,
        "y": 260,
        "wires": [
            []
        ]
    },
    {
        "id": "6603f14bc05d712b",
        "type": "python-function-ps",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "pythonPathType": "local",
        "pythonPath": "python3",
        "globalPythonName": "",
        "importPathList": [
            "/home/smartshelf2/hx711py"
        ],
        "fnCodePre": "\n# user code here.\n",
        "fnCode": "#! /usr/bin/python2\n\nimport time\nimport sys\nimport RPi.GPIO as GPIO\nfrom hx711 import HX711\n\nhx = HX711(5, 6)\n\n# I've found out that, for some reason, the order of the bytes is not always the same between versions of python, numpy and the hx711 itself.\n# Still need to figure out why does it change.\n# If you're experiencing super random values, change these values to MSB or LSB until to get more stable values.\n# There is some code below to debug and log the order of the bits and the bytes.\n# The first parameter is the order in which the bytes are used to build the \"long\" value.\n# The second paramter is the order of the bits inside each byte.\n# According to the HX711 Datasheet, the second parameter is MSB so you shouldn't need to modify it.\nhx.set_reading_format(\"MSB\", \"MSB\")\n\n# HOW TO CALCULATE THE REFFERENCE UNIT\n# To set the reference unit to 1. Put 1kg on your sensor or anything you have and know exactly how much it weights.\n# In this case, 92 is 1 gram because, with 1 as a reference unit I got numbers near 0 without any weight\n# and I got numbers around 184000 when I added 2kg. So, according to the rule of thirds:\n# If 2000 grams is 184000 then 1000 grams is 184000 / 2000 = 92.\nhx.set_reference_unit(450)\n#hx.set_reference_unit(referenceUnit)\n\nhx.reset()\n\nhx.tare()\n\nprint(\"Tare done! Add weight now...\")\n\n# to use both channels, you'll need to tare them both\n#hx.tare_A()\n#hx.tare_B()\n\n# These three lines are usefull to debug wether to use MSB or LSB in the reading formats\n# for the first parameter of \"hx.set_reading_format(\"LSB\", \"MSB\")\".\n# Comment the two lines \"val = hx.get_weight(5)\" and \"print val\" and uncomment these three lines to see what it prints.\n\n# np_arr8_string = hx.get_np_arr8_string()\n# binary_string = hx.get_binary_string()\n# print binary_string + \" \" + np_arr8_string\n\n# Prints the weight. Comment if you're debbuging the MSB and LSB issue.\nval = max(0, int(hx.get_weight(5)))\nprint(val)\nmsg = val\n\n# To get weight from both channels (if you have load cells hooked up \n# to both channel A and B), do something like this\n#val_A = hx.get_weight_A(5)\n#val_B = hx.get_weight_B(5)\n#print \"A: %s  B: %s\" % ( val_A, val_B )\n\n#hx.power_down()\n#hx.power_up()\n#time.sleep(0.1)\nGPIO.cleanup()\nreturn msg",
        "fnCodePost": "\n# user code here.\n",
        "x": 610,
        "y": 360,
        "wires": [
            []
        ]
    },
    {
        "id": "49be8df916300aee",
        "type": "ui_button",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "group": "301ee099fd1bc275",
        "order": 1,
        "width": 0,
        "height": 0,
        "passthru": false,
        "label": "button",
        "tooltip": "",
        "color": "",
        "bgcolor": "",
        "className": "",
        "icon": "",
        "payload": "",
        "payloadType": "str",
        "topic": "topic",
        "topicType": "msg",
        "x": 330,
        "y": 360,
        "wires": [
            [
                "6603f14bc05d712b"
            ]
        ]
    },
    {
        "id": "73277f82476c5f13",
        "type": "debug",
        "z": "5d3ceb36.b1a4a4",
        "name": "debug 1",
        "active": true,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 830,
        "y": 360,
        "wires": []
    },
    {
        "id": "cbfdd0f743202280",
        "type": "python-function-ps",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "pythonPathType": "local",
        "pythonPath": "python3",
        "globalPythonName": "",
        "importPathList": [],
        "fnCodePre": "\n# user code here.\n",
        "fnCode": "import RPi.GPIO as GPIO\n\n# Sets up pins as outputs\ndef setup():\n    GPIO.cleanup()\n    GPIO.setmode(GPIO.BCM)\n    GPIO.setup(29, GPIO.OUT)\n\nif __name__ == '__main__':\n    setup()\n    GPIO.output(29, GPIO.HIGH)",
        "fnCodePost": "\n# user code here.\n",
        "x": 590,
        "y": 440,
        "wires": [
            []
        ]
    },
    {
        "id": "301ee099fd1bc275",
        "type": "ui_group",
        "name": "Group 1",
        "tab": "58f9a81bce3d8e2d",
        "order": 1,
        "disp": true,
        "width": 6
    },
    {
        "id": "58f9a81bce3d8e2d",
        "type": "ui_tab",
        "name": "Tab 1",
        "icon": "dashboard",
        "order": 1
    }
]

You have a python script in your node-red flow.

  1. Are you saying that when you run this script from the command line it works, but when you run it using the python-function-ps node it does not?
  2. Do you get any error messages?
  3. Do you have both python2 and python3 on your Raspberry? Why does the script specify python2?
  4. Have you tried running the script using the exec node instead of this python node?

Thanks for the fast reply

  1. yes basically the same script (without return and the measurement in a loop) runs fine in the terminal
  2. with the hx711 node no with the python script yes (currently not at home but it says that the gpio channel is already in use in the debug window and node red crashes with an error in the terminal that is json specific(
  3. copy and paste but python 3 is installed i need to change that
  4. no i have not yet but i will look into it

Gesendet mit der mobilen Mail App

sooo i succeeded in getting load values with my current flow but i have the problem, that i can not read load continuously and the weight is not allowed to stand on the sensor till it starts measuring (before initialisation -> otherwise i get 0 as a value - is there a way to split initialisiation and measurement in node red?)

i tried it with the exec node -> no output and the daemon node -> error:
[daemon:875fb3b7ab347b47] error: Error: spawn sudo python /home/smartshelf2/hx711py/test.py ENOENT
but the file exists i do not understand?

[
    {
        "id": "5d3ceb36.b1a4a4",
        "type": "tab",
        "label": "Flow 1",
        "disabled": false,
        "info": ""
    },
    {
        "id": "49be8df916300aee",
        "type": "ui_button",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "group": "301ee099fd1bc275",
        "order": 1,
        "width": 0,
        "height": 0,
        "passthru": false,
        "label": "START",
        "tooltip": "",
        "color": "",
        "bgcolor": "",
        "className": "",
        "icon": "",
        "payload": "start",
        "payloadType": "str",
        "topic": "topic",
        "topicType": "msg",
        "x": 340,
        "y": 360,
        "wires": [
            [
                "5cfb2eb7c6ae988b"
            ]
        ]
    },
    {
        "id": "73277f82476c5f13",
        "type": "debug",
        "z": "5d3ceb36.b1a4a4",
        "name": "debug 1",
        "active": true,
        "tosidebar": true,
        "console": true,
        "tostatus": false,
        "complete": "payload",
        "targetType": "msg",
        "statusVal": "",
        "statusType": "auto",
        "x": 1230,
        "y": 520,
        "wires": []
    },
    {
        "id": "5cfb2eb7c6ae988b",
        "type": "exec",
        "z": "5d3ceb36.b1a4a4",
        "command": "sudo python /home/smartshelf2/hx711py/measure_load_sensor1.py",
        "addpay": "",
        "append": "",
        "useSpawn": "true",
        "timer": "",
        "winHide": false,
        "oldrc": false,
        "name": "",
        "x": 640,
        "y": 500,
        "wires": [
            [
                "b150bb3124c24617",
                "5e17b55b2ecfffb5"
            ],
            [
                "b150bb3124c24617"
            ],
            [
                "b150bb3124c24617"
            ]
        ]
    },
    {
        "id": "5e17b55b2ecfffb5",
        "type": "ui_gauge",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "group": "301ee099fd1bc275",
        "order": 2,
        "width": 0,
        "height": 0,
        "gtype": "gage",
        "title": "Gewicht",
        "label": "g",
        "format": "{{value}}",
        "min": 0,
        "max": "5000",
        "colors": [
            "#00b500",
            "#e6e600",
            "#ca3838"
        ],
        "seg1": "",
        "seg2": "",
        "diff": false,
        "className": "",
        "x": 1220,
        "y": 480,
        "wires": []
    },
    {
        "id": "d21b603ea1cb00fd",
        "type": "rbe",
        "z": "5d3ceb36.b1a4a4",
        "d": true,
        "name": "",
        "func": "rbei",
        "gap": "",
        "start": "",
        "inout": "out",
        "septopics": true,
        "property": "\"Tare done!\"",
        "topi": "topic",
        "x": 1050,
        "y": 500,
        "wires": [
            [
                "73277f82476c5f13",
                "5e17b55b2ecfffb5"
            ]
        ]
    },
    {
        "id": "b150bb3124c24617",
        "type": "debug",
        "z": "5d3ceb36.b1a4a4",
        "name": "debug 2",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "statusVal": "",
        "statusType": "auto",
        "x": 1040,
        "y": 340,
        "wires": []
    },
    {
        "id": "875fb3b7ab347b47",
        "type": "daemon",
        "z": "5d3ceb36.b1a4a4",
        "name": "",
        "command": "sudo python home/smartshelf2/hx711py/test.py",
        "args": "",
        "autorun": true,
        "cr": false,
        "redo": false,
        "op": "number",
        "closer": "SIGKILL",
        "x": 640,
        "y": 360,
        "wires": [
            [
                "d21b603ea1cb00fd",
                "b150bb3124c24617"
            ],
            [
                "b150bb3124c24617"
            ],
            [
                "b150bb3124c24617"
            ]
        ]
    },
    {
        "id": "301ee099fd1bc275",
        "type": "ui_group",
        "name": "Group 1",
        "tab": "58f9a81bce3d8e2d",
        "order": 1,
        "disp": true,
        "width": 6
    },
    {
        "id": "58f9a81bce3d8e2d",
        "type": "ui_tab",
        "name": "Tab 1",
        "icon": "dashboard",
        "order": 1
    }
]

python files:
test.py

#!/usr/bin/python3

import time
import sys
import os
from hx711 import HX711

EMULATE_HX711 = False
referenceUnit = 1

if not EMULATE_HX711:
    import RPi.GPIO as GPIO
    from hx711 import HX711
else:
    from emulated_hx711 import HX711

def read_sensor():
    hx = HX711(5, 6)
    hx.set_reading_format("MSB", "MSB")
    hx.set_reference_unit(490)
    
    hx.reset()
    hx.tare()

    val = max(0, int(hx.get_weight(5)))
    hx.power_down()
    hx.power_up()
    
    return val

print("TEST")
weight_value = read_sensor()
print(weight_value)  # This output will be captured by Node-RED

measure_load_sensor1.py:

#! /usr/bin/python3

import time
import sys
import os
import inspect
import RPi.GPIO as GPIO
from hx711 import HX711

hx = HX711(5, 6)

# I've found out that, for some reason, the order of the bytes is not always the same between versions of python, numpy and the hx711 itself.
# Still need to figure out why does it change.
# If you're experiencing super random values, change these values to MSB or LSB until to get more stable values.
# There is some code below to debug and log the order of the bits and the bytes.
# The first parameter is the order in which the bytes are used to build the "long" value.
# The second paramter is the order of the bits inside each byte.
# According to the HX711 Datasheet, the second parameter is MSB so you shouldn't need to modify it.
hx.set_reading_format("MSB", "MSB")

# HOW TO CALCULATE THE REFFERENCE UNIT
# To set the reference unit to 1. Put 1kg on your sensor or anything you have and know exactly how much it weights.
# In this case, 92 is 1 gram because, with 1 as a reference unit I got numbers near 0 without any weight
# and I got numbers around 184000 when I added 2kg. So, according to the rule of thirds:
# If 2000 grams is 184000 then 1000 grams is 184000 / 2000 = 92.
hx.set_reference_unit(490)
#hx.set_reference_unit(referenceUnit)

hx.reset()

def cleanAndExit():
    print("Cleaning...")
   
    if not EMULATE_HX711:
        GPIO.cleanup()
        
    print("Bye!")
    sys.exit()

def get_average_weight(hx, readings=5):
    total_weight = 0
    hx.tare()
    for _ in range(readings):
        try:
            # Prints the weight. Comment if you're debugging the MSB and LSB issue.
            weight = max(0, int(hx.get_weight(5)))
            print(weight)
            total_weight += weight

            # To get weight from both channels (if you have load cells hooked up
            # to both channel A and B), do something like this
            # val_A = hx.get_weight_A(5)
            # val_B = hx.get_weight_B(5)
            # print "A: %s  B: %s" % ( val_A, val_B )

            hx.power_down()
            hx.power_up()
            time.sleep(0.1)

        except (KeyboardInterrupt, SystemExit):
            cleanAndExit()

    average_weight = total_weight / readings
    return average_weight

# to use both channels, you'll need to tare them both
#hx.tare_A()

print(get_average_weight(hx))
GPIO.cleanup()
sys.exit()


Sorry but I don't know enough about this sensor to answer that.
Regarding exec vs daemon nodes, if the script returns one reading and then exits, use the exec node. It it runs continuously, returning readings at intervals, use exec in spawn mode or the daemon node.
But since there is a node to interact with these devices, it's best to get that working, exec is just to see if it works by a differnt approach.

The purpose of this first line in a script file is to define what program interprets the file.
So it could be #! /usr/bin/python3, #! /bin/bash or just #! /usr/bin/python

However, it is ignored if you run the script like this python myscript.sh so by changing this line, you have not changed the interpreter from python2 to python3.

It only makes a difference IF the file is executable. See the x's in the permissions:

ls -l myscript.sh
-rwxr-xr-x 1 pi pi 36 Dec 20 16:26 myscript.sh

AND you execute it like this /home/pi/myscript.sh

  • Your exec node calls python. Instead make sure the file is executable and call it by it's full pathname.

  • Do you really need sudo to run this script? If not, don't use it.

Try giving it the full path the the python command. If that doesn't work, what error do you get if you don't use sudo?

You should not be using sudo for this sort of thing. Instead make sure the node-red user can access whatever resource is required to run the script.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.