Project

General

Profile

peso2.py

Sensor Peso - Ignacio Garrido, 12/11/2024 12:27 AM

Download (2.17 KB)

 
1
# -*- coding: utf-8 -*-
2

    
3
import RPi.GPIO as GPIO
4
import time
5

    
6
# Pines GPIO de la Raspberry Pi
7
DT = 5  # Pin Data (GPIO 5)
8
SCK = 6  # Pin Clock (GPIO 6)
9

    
10
# Configuraci?n inicial de GPIO
11
GPIO.setmode(GPIO.BCM)
12
GPIO.setup(DT, GPIO.IN)
13
GPIO.setup(SCK, GPIO.OUT)
14

    
15
class HX711:
16
    def __init__(self, dout, pd_sck):
17
        self.dout = dout
18
        self.pd_sck = pd_sck
19
        GPIO.setup(self.dout, GPIO.IN)
20
        GPIO.setup(self.pd_sck, GPIO.OUT)
21
        GPIO.output(self.pd_sck, False)
22
        self.offset = 0
23
        self.scale = 1
24

    
25
    def is_ready(self):
26
        return GPIO.input(self.dout) == 0
27

    
28
    def read_raw(self):
29
        while not self.is_ready():
30
            pass
31
        count = 0
32
        for _ in range(24):
33
            GPIO.output(self.pd_sck, True)
34
            count = count << 1
35
            GPIO.output(self.pd_sck, False)
36
            if GPIO.input(self.dout):
37
                count += 1
38
        # Pulso adicional para indicar el fin de la lectura
39
        GPIO.output(self.pd_sck, True)
40
        GPIO.output(self.pd_sck, False)
41

    
42
        # Ajuste para n?meros negativos
43
        if count & 0x800000:
44
            count -= 0x1000000
45
        return count
46

    
47
    def tare(self):
48
        print("Calibrando... Por favor, no coloque peso.")
49
        time.sleep(5)
50
        self.offset = self.read_raw()
51
        print("Calibracin completa. Puede colocar peso.")
52

    
53
    def get_units(self, readings=10):
54
        total = 0
55
        for _ in range(readings):
56
            total += self.read_raw() - self.offset
57
        average = total / readings
58
        return average / self.scale
59

    
60
    def set_scale(self, scale):
61
        self.scale = scale
62

    
63

    
64
def main():
65
    scale = HX711(DT, SCK)
66

    
67
    # Configuraci?n inicial
68
    scale.set_scale(500)  # Ajustar despu?s de calibrar
69
    scale.tare()
70

    
71
    try:
72
        while True:
73
            if scale.is_ready():
74
                weight = scale.get_units(10)  # Leer el promedio de 10 muestras
75
                print(f"Peso: {weight:.2f} g")
76
            else:
77
                print("Esperando al sensor...")
78
            time.sleep(1)  # Leer cada segundo
79
    except KeyboardInterrupt:
80
        print("\nSaliendo...")
81
    finally:
82
        GPIO.cleanup()
83

    
84

    
85
if __name__ == "__main__":
86
    main()
87