Ejemplo n.º 1
0
def setup():
    global hx, logger
    logger = logging.getLogger(__name__)
    if logLevel == "debug":
        logger.setLevel(logging.DEBUG)
    elif logLevel == "info":
        logger.setLevel(logging.INFO)
    elif logLevel == "error":
        logger.setLevel(logging.ERROR)
    else:
        logger.setLevel(logging.INFO)
    streamHandler = logging.StreamHandler()
    rollingFileHandler = RotatingFileHandler(logFilePath,
                                             maxBytes=10000,
                                             backupCount=4)
    formatter = logging.Formatter(loggingFormat)
    streamHandler.setFormatter(formatter)
    rollingFileHandler.setFormatter(formatter)
    logger.addHandler(streamHandler)
    logger.addHandler(rollingFileHandler)

    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("LSB", "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(113)
    hx.set_reference_unit(5091.04)
    hx.reset()
    hx.tare()
    logger.info("Load sensor set up done")
Ejemplo n.º 2
0
def celda2():
    hx = HX711(5, 6)  # sck, dout
    hx.set_reading_format("MSB", "MSB")
    hx.set_reference_unit(-131)
    hx.reset()
    hx.tare()

    print "Tare done! Add weight now..."

    while True:
        try:

            val = hx.get_weight(5)
            print("celda2 : {}".format(val))
            hx.power_down()
            hx.power_up()
            time.sleep(0.000001)

        except (KeyboardInterrupt, SystemExit):
            cleanAndExit()
Ejemplo n.º 3
0
    def __init__(self, dout=5, pd_sck=6):
        super().__init__('scale_node')

        self.declare_parameter('reference_unit', 386.619)
        self._reference_unit = self.get_parameter('reference_unit').value
        self.declare_parameter('update_interval_s', 0.1)
        self._update_interval_s = self.get_parameter('update_interval_s').value

        self._hx = HX711(dout, pd_sck)
        self._hx.set_reading_format("MSB", "MSB")
        self._hx.set_reference_unit(self._reference_unit)

        self._subs = []
        self._subs.append(
            self.create_subscription(Bool, 'scale/enable',
                                     self._enable_callback, 1))
        self._value_pub = self.create_publisher(Float32, 'scale/value', 10)
        self._timer = self.create_timer(self._update_interval_s,
                                        self._timer_callback)
        self._timer.cancel()
Ejemplo n.º 4
0
def get_weight(channel, offset, unit):
    val = []
    hx = HX711(channel[0], channel[1])
    hx.set_reading_format('LSB', 'MSB')
    hx.set_reference_unit(unit)
    hx.reset()
    hx.set_offset(offset)
    while True:
        try:
            for i in range(3):
                val.append(hx.get_weight(1))
            del val[val.index(max(val))]
            del val[val.index(min(val))]
            result[Channels.index(channel)] = float('%.1f' % val[0])
            val = []
            hx.power_down()
            hx.power_up()
            time.sleep(0.2)
        except (KeyboardInterrupt, SystemExit):
            cleanAndExit(Channels.index(channel))
    return result[:]
Ejemplo n.º 5
0
    def test_06_gain_validation(self):
        test_mapping = {
            "wrong_gain_raises_error": (256),
            "string_raises_error": ("128")
        }

        hx711 = HX711(dout_pin=5, pd_sck_pin=6, channel="A", gain=128)

        for name, gain in test_mapping.items():
            with self.subTest(name):
                with self.assertRaises(ParameterValidationError):
                    hx711.channel_a_gain = gain

        for value in hx711._valid_gains_for_channel_A:
            with self.subTest(
                    "valid gain {value} should not raise".format(value=value)):
                try:
                    hx711.channel_a_gain = value
                except Exception as exception:
                    self.fail(
                        "{exception} was raised".format(exception=exception))
def loadread():
    hx = HX711(29, 31)
    hx.set_reading_format("MSB", "MSB")
    #hx.set_reference_unit(92)

    hx.reset()
    
    hx.tare()

    print("Tare done! Add weight now...")

    try:
        val = hx.get_weight(5)
        print(val)
        hx.power_down()
        hx.power_up()
        time.sleep(0.1)

    except (KeyboardInterrupt, SystemExit):
        cleanAndExit()
    return val
Ejemplo n.º 7
0
 def __init__(self, filename):
     bakery = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     self.data_directory = '%s/web/thrust-tests' % bakery
     self.prep_file(filename)
     GPIO.setmode(GPIO.BCM)
     GPIO.setup(LED_PIN, GPIO.OUT)
     GPIO.setup(RELAY_PIN, GPIO.OUT)
     GPIO.output(LED_PIN, False)
     GPIO.output(RELAY_PIN, False)
     self.ignite_start = -1
     self.ignite_duration = 2.
     self.hx = HX711(DATA_PIN, CLOCK_PIN)
     self.hx.set_reading_format("LSB", "MSB")
     self.hx.set_reference_unit(92)
     self.hx.reset()
     self.hx.tare(100)
     self.start_time = time.time()
     self.times = []
     self.triggered = False
     self.thrusts = []
     GPIO.output(LED_PIN, True)
    def __init__(self, gpio1=[18, 23, 24, 25], gpioLoad=[27, 17]):
        self.spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI)
        self.cs = digitalio.DigitalInOut(board.D5)
        self.mcp = MCP.MCP3008(self.spi, self.cs)
        self.channel = AnalogIn(self.mcp, MCP.P0)
        # specify the motor type, the library may need to be changed if the motor is replaced
        self.mymotortest = RpiMotorLib.BYJMotor("MyMotorOne", "28BYJ")
        self.gpio1 = gpio1
        # use pin27 and 17 to connect the driver board
        self.hx = HX711(27, 17)

        self.hx.reset()
        self.hx.zero()

        self.speed = 0
        self.completions = 0
        self.flag = False
        print("Tare done! Add weight now...")

        self.distance = Value('i', 0)
        self.cmd = Value('i', 0)
Ejemplo n.º 9
0
def main():
    # Initialize parameters at t = 0
    num_people = 4  # Initialize number of people
    weight_array = np.zeros(num_people)  # Store weights in an array
    global weight_before
    weight_before = measure_sink()  # Initial weight in sink
    #faces = load_faces(num_people)                        # Stores template faces for each person
    names = ["Brooke", "Eric", "Francis",
             "Nithin"]  # Stores names of each person

    # Initialize load cell
    hx = HX711(5, 6)
    hx.set_reading_format("LSB", "MSB")
    hx.set_reference_unit(92)  # Calibrate reference unit to 1g
    hx.reset()
    hx.tare()

    # Initialize Display
    window = tk.Tk()
    window.title("Dirty dishes")
    window.configure(background="black")
    myFont = tkinter.font.Font(family='Helvetica', size=25, weight="bold")

    # Initialize Face Recognition
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.read('trainer/trainer.yml')
    cascadePath = "haarcascade_frontalface_default.xml"
    faceCascade = cv2.CascadeClassifier(cascadePath)
    font = cv2.FONT_HERSHEY_SIMPLEX
    cam = cv2.VideoCapture(1)

    # Iterate for t > 0
    update_display()  # calls update_data as well
    window.mainloop()

    # Stop the camera
    cam.release()

    # Close all windows
    cv2.destroyAllWindows()
Ejemplo n.º 10
0
    def __init__(self, port, logfname, nscale):
        """
		"""
        if not port:
            logging.warning(
                '## hxboard __init__ requires a clock/data port (as [5,6] eg) please'
            )
            return
        self.logdat = False
        self.recording = False
        self.outfile = None
        self.nscale = nscale
        self.lastval = 0.0
        self.configfile = 'scale%d.config' % nscale
        self.scale = 1.0
        self.offset = 0
        self.port = port
        self.lasttime = datetime.datetime.now()
        if os.path.isfile(self.configfile):
            s = open(self.configfile, 'r').read()
            sc, offs = s.split(',')
            self.scale = float(sc)
            self.offset = int(offs)
            self.calibrated = True
        else:
            self.calibrated = False
        hxnew = HX711(self.port[0], self.port[1])
        hxnew.set_reading_format("MSB", "MSB")
        hxnew.set_reference_unit(self.scale)
        hxnew.set_offset(self.offset)
        self.hx = hxnew
        scale_ready = self.do_Ready()
        if not scale_ready:
            # timeout
            logging.warning(
                "!!! Scale ready timeout - is scale %d @ port %s connected? Not calibrating"
                % (self.nscale, self.port))
        else:
            if not self.calibrated:
                self.do_Calibrate()
Ejemplo n.º 11
0
def balanca():
    hx = HX711(5, 6)

    hx.set_reading_format("LSB", "MSB")

    hx.set_reference_unit(92) #calibragem

    hx.reset()
    hx.tare()

    while True:
        try:
            val = hx.get_weight(5)
            print val

            hx.power_down()
            hx.power_up()
            time.sleep(0.5)
        except (KeyboardInterrupt, SystemExit):
            cleanAndExit()

    return val
Ejemplo n.º 12
0
def grindSpice(motor, amount):
    # Setting up scales
    ### first param a GPIO number?
    print "setting up scale"
    hx = HX711(motorDict[motor]['scale'][0], motorDict[motor]['scale'][1])
    hx.set_reading_format("MSB", "MSB")
    hx.set_reference_unit(motorDict[motor]['reference'])

    hx.reset()
    hx.tare()

    # start the motor
    print "starting motor"
    toggle_motor(1, motorDict[motor]['motor'])

    while True:
        try:
            val_A = abs(hx.get_weight_A(1))
            #val_B = hx.get_weight_B(5)
            print "A: %s" % (val_A)

            hx.power_down()
            hx.power_up()
            #time.sleep(0.01)

            if val_A >= amount:
                #toggle_motor(0, motorDict[motor]['motor'])
                break

        except (KeyboardInterrupt, SystemExit):
            print("error with the scale")
    # stop the motor
    print "stopping motor"
    toggle_motor(0, motorDict[motor]['motor'])

    wiggle(4)
    sleep(1)
    wiggle(4)
Ejemplo n.º 13
0
    def init_hx711(self, hx_conf):
        dout = hx_conf['dout']
        pd_sck = hx_conf['pd_sck']

        try:
            offset_A = hx_conf['channels']['A']['offset']
            refunit_A = hx_conf['channels']['A']['refunit']
        except (ValueError, KeyError):
            offset_A = None
            refunit_A = None
        try:
            offset_B = hx_conf['channels']['B']['offset']
            refunit_B = hx_conf['channels']['B']['refunit']
        except (ValueError, KeyError):
            offset_B = None
            refunit_B = None

        hx = HX711(dout, pd_sck)
        hx.set_reading_format("MSB", "MSB")
        hx.reset()

        if refunit_A:
            hx.set_reference_unit_A(refunit_A)
            if offset_A:
                hx.set_offset_A(offset_A)
            else:
                hx.tare_A()
                self.debug_msg("channel A offset: %s" % hx.OFFSET)

        if refunit_B:
            hx.set_reference_unit_B(refunit_B)
            if offset_B:
                hx.set_offset_B(offset_B)
            else:
                hx.tare_B()
                self.debug_msg("channel B offset: %s" % hx.OFFSET_B)

        return hx
Ejemplo n.º 14
0
    def test_05_channel_name_validation(self):
        test_mapping = {
            "wrong_name": "C",
            "integer": 1,
            "long_string": "channel_A"
        }

        hx711 = HX711(dout_pin=5, pd_sck_pin=6, channel="A", gain=128)

        for name, channel in test_mapping.items():
            with self.subTest(name):
                with self.assertRaises(ParameterValidationError):
                    hx711.channel = channel

        for channel in hx711._valid_channels:
            with self.subTest(
                    "valid gain {channel} should ot raise an error".format(
                        channel=channel)):
                try:
                    hx711.channel = channel
                except Exception as exception:
                    self.fail(
                        "{exception} was raised".format(exception=exception))
Ejemplo n.º 15
0
    def __init__(self, pins=[24,23], units='mN',calweight=309.5, calfactor=-0.00320306508155):
        self.pins = pins
        self.units = units
        self.calweight = calweight
        self.calfactor = calfactor

        self.lc = HX711(self.pins[0], self.pins[1])

        self.lc.set_reading_format("MSB", "MSB")

        print("Set Zero Weight")
        self.lc.reset()
        self.lc.tare()
        print("Tare done. Add weight now...")

        try:
            self.calin = input("Weight added (grams/ [ ENTER for default ] ): ")
            gravity = 9.81

            print("____")
            print("Input Weight = %f grams" % self.calin)
            # to use both channels, you'll need to tare them both
            #hx.tare_A()
            #hx.tare_B()

            self.calout = self.lc.get_weight(5)
            print("Raw Value = %f" % self.calout)
            # y = Ax + B - Assume B set by tare. Therefore A...

            self.Ax = self.calin*gravity/self.calout

        except SyntaxError: # User hits ENTER, enabling use of previous calibration values
            self.calin = self.calweight
            print("Calibration weight set to default (309.5g)")
            self.Ax = self.calfactor

        print("Calibration factor = %s " % self.Ax)
Ejemplo n.º 16
0
class load_cell:

    EMULATE_HX711 = False

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

    hx = HX711(5, 6)
    hx.set_reading_format("MSB", "MSB")
    hx.set_reference_unit(1)
    hx.reset()

    #hx.tare()

    def taring():
        hx.tare()

    def getting_weight():
        chem_weight = hx.get_weight(10)
        hx.power_down()
        return chem_weight
Ejemplo n.º 17
0
import RPi.GPIO as GPIO
import time
import sys
from hx711 import HX711


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


hx = HX711(12, 16)

# 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("LSB", "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(113)
hx.set_reference_unit(-429)
Ejemplo n.º 18
0
#if not EMULATE_HX711:
import RPi.GPIO as GPIO
from hx711 import HX711
#else:
#    from emulated_hx711 import HX711

def cleanAndExit():
    print ("Cleaning...")

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

hx = HX711(9,11)  #DT,CLK

# 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.

#MSB or LSB calibration
def most_common(list_):
	return max(set(list_),key=list_.count)

isMSB = True
if isMSB:
Ejemplo n.º 19
0
import RPi.GPIO as GPIO
import time
import sys
from hx711 import HX711

# Force Python 3 ###########################################################

if sys.version_info[0] != 3:
    raise Exception("Python 3 is required.")

############################################################################

# Make sure you correct these to the correct pins for DOUT and SCK.
# gain is set to 128 as default, change as needed.
hx = HX711(21, 20, gain=128)


def cleanAndExit():
    print("Cleaning up...")
    GPIO.cleanup()
    print("Bye!")
    sys.exit()


def setup():
    """
    code run once
    """
    print("Initializing.\n Please ensure that the scale is empty.")
    scale_ready = False
Ejemplo n.º 20
0
gpio.setup(trig, gpio.OUT)
gpio.setup(piezo, gpio.OUT)
gpio.setup(echo, gpio.IN)

gpio.output(piezo, False)

s1 = gpio.PWM(breakfast_servo, 50)
s2 = gpio.PWM(lunch_servo, 50)
s3 = gpio.PWM(dinner_servo, 50)
play_piezo = True
s1.start(0)
s2.start(0)
s3.start(0)

# Dfrobot SEN0160 Digital Weight Sensor
hx = HX711(20, 16)
hx.set_reading_format("MSB", "MSB")
hx.set_reference_unit(2088)
hx.reset()
hx.tare()


def setServoPos(servo, degree):
    global s1
    if degree > 180:
        degree = 180
    if degree == 0:
        servo.ChangeDutyCycle(0)
    else:
        duty = SERVO_MIN_DUTY + (degree *
                                 (SERVO_MAX_DUTY - SERVO_MIN_DUTY) / 180.0)
Ejemplo n.º 21
0
import RPi.GPIO as GPIO
import time
import sys
from hx711 import HX711


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


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("LSB", "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(113)
#hx.set_reference_unit(92)
Ejemplo n.º 22
0
myAWSIoTMQTTClient.configureEndpoint(host, 8883)
myAWSIoTMQTTClient.configureCredentials(rootCAPath, privateKeyPath, certificatePath)

# AWSIoTMQTTClient connection configuration
myAWSIoTMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myAWSIoTMQTTClient.configureOfflinePublishQueueing(-1)  # Infinite offline Publish queueing
myAWSIoTMQTTClient.configureDrainingFrequency(2)  # Draining: 2 Hz
myAWSIoTMQTTClient.configureConnectDisconnectTimeout(10)  # 10 sec
myAWSIoTMQTTClient.configureMQTTOperationTimeout(10)  # 10 sec

# Connect and subscribe to AWS IoT
myAWSIoTMQTTClient.connect()

data = []

hx1 = HX711(3, 4)
hx1.set_reading_format("LSB", "MSB")
hx1.set_reference_unit(-36205) #scale 1
hx1.reset()
hx1.set_offset(8388607) #scale 1 offset

def cleanAndExit():
    print "Cleaning..."
    GPIO.cleanup()
    if myAWSIoTMQTTClient is not None:
        myAWSIoTMQTTClient.disconnect()
    print "Bye!"
    sys.exit()

def assembleMessage(name, amount, units):
    now = time.mktime(datetime.now().timetuple()) * 1000
Ejemplo n.º 23
0

def cleanAndExit():
    print("Cleaning...")

    if not EMULATE_HX711:
        GPIO.cleanup()

    print("Bye!")
    sys.exit()


CLOCK_PIN = 1

sensors = [
    HX711(0, CLOCK_PIN),
    HX711(2, CLOCK_PIN),
    HX711(3, CLOCK_PIN),
    HX711(5, CLOCK_PIN)
]
sensors[0].set_reference_unit(referenceUnit_0)
sensors[1].set_reference_unit(referenceUnit_1)
sensors[2].set_reference_unit(referenceUnit_2)
sensors[3].set_reference_unit(referenceUnit_3)

for sensor in sensors:
    # 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.
Ejemplo n.º 24
0
import RPi.GPIO as GPIO
import os
from time import sleep
from hx711 import HX711
import Adafruit_DHT
import urllib2



DEBUG = 1
# Setup the pins we are connect to
#RCpin = 24
DHTpin = 4
hx711 = HX711(
            dout_pin=5,
            pd_sck_pin=6,
            channel='A',
            gain=64
        )
		
#Setup API and delay for Thingspeak channel
myAPI = "B6IYS9WQIKAEPJTL"
myDelay = 15 #seconds between posting data

GPIO.setmode(GPIO.BCM)
#GPIO.setup(RCpin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)



def getSensorData():
    RHW, TW = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, DHTpin)
    
Ejemplo n.º 25
0
import RPi.GPIO as GPIO
import time
import sys
from hx711 import HX711

# Force Python 3 ###########################################################

if sys.version_info[0] != 3:
    raise Exception("Python 3 is required.")

############################################################################

# Make sure you correct these to the correct pins for DOUT and SCK.
# gain is set to 128 as default, change as needed.
hx = HX711(2, 3, gain=128)


def cleanAndExit():
    print("Cleaning up...")
    GPIO.cleanup()
    print("Bye!")
    sys.exit()


def setup():
    """
    code run once
    """
    print("Initializing.\n Please ensure that the scale is empty.")
    scale_ready = False
        time.sleep(1)
        for i in range(len(text) - num_cols + 5):
            text_to_print = text[i:i + num_cols]
            display.lcd_display_string(text_to_print, num_line)
            time.sleep(0.2)
    else:
        display.lcd_display_string(text, num_line)
        display = lcddriver.lcd()


try:
    long_string(display, "Welcome to ZoologicalFooding Project", 1)
    display.lcd_display_string(":)", 2)
    GPIO.setmode(GPIO.BCM)

    hx = HX711(dout_pin=5, pd_sck_pin=6)

    error = hx.zero()

    if error:
        raise ValueError('Cannot tare the scale')

    reading = hx.get_raw_data_mean()

    if not reading:
        print('incorrect data', reading)

    input('Place a known weighted object and press <enter>')
    reading = hx.get_data_mean()
    if reading:
        known_weight_grams = input('Weight of the object: ')
Ejemplo n.º 27
0
fan_1 = Pin(in3, mode=Pin.OUT)
fan_2 = Pin(in4, mode=Pin.OUT)

#schakelaar voor de poort open te doen
switch = Pin(switch_pin, mode=Pin.IN)

#maak een pwm aan met timer 0 & frequentie van 5KHz
pwm = PWM(0, frequency=5000)

#creer een pwm kaneel op pin enableA met een duty cycle van 0
gate_speed = pwm.channel(0, pin=enableA, duty_cycle=0)
fan_speed = pwm.channel(0, pin=enableB, duty_cycle=0)
#deze worden niet gebruikt want de motoren bewegen pas vanaf 90% duty cycle

#de load cell amplifier
load_amp = HX711(data_pin, clk_pin)

#wordt gebruikt om de load cell waarde op null te zetten
weight_offset = 969850


def main():
    #kijkt of de poort open of dicht is en sluit/opent deze als de schakelaar gebruikt wordt (zie video)
    gateIsOpen = False
    while True:
        if (switch.value() and gateIsOpen):
            print("gate is closing")
            close_gate()
            isOpen = False
        elif (switch.value() and (not gateIsOpen)):
            print("gate is opening")
def findMostProbableVegetable(labels):
    for label in labels:
        #print label.description," ",label.score
        extractedVegetable = process.extractOne(label.description,
                                                list_of_vegetables,
                                                scorer=fuzz.token_sort_ratio)
        if (extractedVegetable[1] > FUZZY_THRESHOLD):
            return extractedVegetable[0]
    return "None"


deviceID = "CART__0_40"
appID = "CART_0"
#DOUT, SCK
hx = HX711(23, 24)
broker = sys.argv[1]
topic = "estimato/" + deviceID + "/item"
GPIO.setup(4, GPIO.OUT)
camera = PiCamera()
camera.start_preview()


def on_connect(client, userdata, rc):
    print("Connected with result code " + str(rc))
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("$SYS/#")


def on_publish(client, userdata, mid):
Ejemplo n.º 29
0
import RPi.GPIO as GPIO  # import GPIO
from hx711 import HX711  # import the class HX711

try:
    GPIO.setmode(GPIO.BCM)  # set GPIO pin mode to BCM numbering
    # Create an object hx which represents your real hx711 chip
    # Required input parameters are only 'dout_pin' and 'pd_sck_pin'
    hx = HX711(dout_pin=14, pd_sck_pin=15)
    # measure tare and save the value as offset for current channel
    # and gain selected. That means channel A and gain 128
    err = hx.zero()
    # check if successful
    if err:
        raise ValueError('Tare is unsuccessful.')

    reading = hx.get_raw_data_mean()
    if reading:  # always check if you get correct value or only False
        # now the value is close to 0
        print('Data subtracted by offset but still not converted to units:',
              reading)
    else:
        print('invalid data', reading)

    input('Put known weight on the scale and then press Enter')
    reading = hx.get_data_mean()
    if reading:
        print('Mean value from HX711 subtracted by offset:', reading)
        known_weight_grams = 1000
        try:
            value = float(known_weight_grams)
            print(value, 'grams')
Ejemplo n.º 30
0
#!/usr/bin/python3
from hx711 import HX711
import RPi.GPIO as GPIO
import statusLEDs
import statusRelaise
import time
import telegrambot

if __name__ == "__main__": 
	try:
		GPIO.setmode(GPIO.BCM)
		hx711 = HX711(dout_pin=5,pd_sck_pin=6,
						gain_channel_A=64,select_channel='A')
		
		#Offset eliminieren
		print("Bitte entfernen Sie alle Gewichte von der Waage.")
		time.sleep(5)
		hx711.reset()   #Before we start, reset the HX711 (not obligate)
		hx711.zero()
		
		#Scale Ratio setzen
		print("Bitte bekanntes Gewicht auflegen!")
		while True:
			try:
				value = float(input("Wie viel Gramm wiegt das Gewicht?"))
				measures = hx711.get_raw_data_mean()
			except TypeError:
				print("Ungueltige Eingabe! Bitte erneut versuchen.")
				continue
			else:
				break