0% found this document useful (0 votes)
13 views5 pages

Message

Uploaded by

Nicolas Lab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views5 pages

Message

Uploaded by

Nicolas Lab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

import BlynkLib

import RPi.GPIO as GPIO


import time
import threading
from hx711 import HX711
from gpiozero import Servo
from gpiozero.pins.pigpio import PiGPIOFactory

# Declare global variables


weight_grams = 0
adjusted_weight = 0
valuem = 0

BLYNK_AUTH_TOKEN = "gIwMgfU5sNPWDLFH0OAk-EYUX57i-JCa"
led1 = 18
led2 = 19
water_sensor_pin = 16

# Stepper motor GPIO setup


enable_pin_stepper = 12
step_pin_stepper = 23
dir_pin_stepper = 24
mode_pins_stepper = (14, 15, 18)

# Stepper motor setup


step_type_stepper = '1/32'
fullstep_delay_stepper = 0.05

# Hardware PWM for servo motor


factory = PiGPIOFactory()
servo = Servo(17, min_pulse_width=0.5/1000, max_pulse_width=2.5/1000,
pin_factory=factory)

# create stepper motor object


class StepperMotor:
def __init__(self, enable_pin, step_pin, dir_pin, mode_pins, step_type,
fullstep_delay):
self.enable_pin = enable_pin
self.step_pin = step_pin
self.dir_pin = dir_pin
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(enable_pin, GPIO.OUT)
GPIO.setup(step_pin, GPIO.OUT)
GPIO.setup(dir_pin, GPIO.OUT)
GPIO.setup(mode_pins, GPIO.OUT)
resolution = {'Full': (0, 0, 0),
'Half': (1, 0, 0),
'1/4': (0, 1, 0),
'1/8': (1, 1, 0),
'1/16': (0, 0, 1),
'1/32': (1, 0, 1)}
microsteps = {'Full': 1,
'Half': 2,
'1/4': 4,
'1/8': 8,
'1/16': 16,
'1/32': 32}
self.delay = fullstep_delay / microsteps[step_type]
GPIO.output(mode_pins, resolution[step_type])

def enable(self, enable):


GPIO.output(self.enable_pin, not enable)

def run(self, steps, clockwise):


GPIO.output(self.dir_pin, clockwise)
for i in range(steps):
GPIO.output(self.step_pin, GPIO.HIGH)
time.sleep(self.delay)
GPIO.output(self.step_pin, GPIO.LOW)
time.sleep(self.delay)

def set_speed(self, custom_speed_delay):


self.delay = custom_speed_delay

# create stepper motor object


stepper_motor = StepperMotor(enable_pin_stepper, step_pin_stepper, dir_pin_stepper,
mode_pins_stepper,
step_type_stepper, fullstep_delay_stepper)

GPIO.setmode(GPIO.BCM)
GPIO.setup(led1, GPIO.OUT)
GPIO.setup(led2, GPIO.OUT)
GPIO.setup(water_sensor_pin, GPIO.IN)

# Initialize HX711
hx = HX711(dout_pin=5, pd_sck_pin=6)
hx.zero() # Tare the HX711

# Manually adjustable calibration factor and ratio


calibration_factor = 1.0 # Adjust as needed
ratio = 1.0

def calibrate_scale():
global calibration_factor, ratio

print("Do you want to calibrate the scale? (Y/n)")


user_input = input().strip().lower()
if user_input != 'y':
print("Skipping calibration.")
return

print("Calibration process:")
input('1. Place a known weight on the scale and press Enter.')
reading = hx.get_data_mean()
if reading:
print('2. Mean value from HX711 subtracted by offset:', reading)
known_weight_grams = input('3. Enter the weight in grams: ')
try:
value = float(known_weight_grams)
print(f"{value} grams")
except ValueError:
print('Invalid input. Calibration aborted.')
return

ratio = reading / value


calibration_factor = 1.0 / ratio
hx.set_scale_ratio(ratio)
print('Calibration completed successfully.')
else:
print('Invalid data. Calibration aborted.')

# Function to read weight and send it to Blynk


def read_weight_and_send_to_blynk():
global weight_grams, adjusted_weight, calibration_factor, ratio
while True:
# Read weight from HX711 in grams
weight_grams = hx.get_weight_mean(40)

# Manually adjustable calibration


adjusted_weight = weight_grams * calibration_factor

# Send adjusted weight to Blynk


blynk.virtual_write(4, weight_grams)

time.sleep(1) # Adjust delay as needed

# Start the weight reading and Blynk sending thread


weight_blynk_thread = threading.Thread(target=read_weight_and_send_to_blynk)
weight_blynk_thread.daemon = True
weight_blynk_thread.start()

blynk = BlynkLib.Blynk(BLYNK_AUTH_TOKEN)

@blynk.on("V0")
def v0_write_handler(value):
global valuem
if int(value[0]) != 0:
GPIO.output(led1, GPIO.HIGH)
print("LED1 HIGH - Turning on Stepper Motor")

# Set custom speed for the stepper motor (adjust as needed)


custom_speed_delay = 0.0001 * int(value[0])
stepper_motor.set_speed(custom_speed_delay)

# Assuming you want to turn the stepper motor for 200 steps (adjust as
needed)
stepper_motor.enable(True)
stepper_motor.run(30000, True)
stepper_motor.enable(False)

print(value)

# Subtract 25 from the current value of the gauge and update it


blynk.virtual_write(5, valuem - 25)
valuem = valuem - 25

else:
GPIO.output(led1, GPIO.LOW)
print("LED1 LOW")

@blynk.on("V3")
def v3_write_handler(value):
global valuem
if int(value[0]) != 0:
blynk.virtual_write(5, 100)
valuem = 100
print(valuem)
print("Gauge on V2 reset to 100")

#@blynk.on("V1")
#def v1_write_handler(value):
# if int(value[0]) != 0:
# GPIO.output(led2, GPIO.HIGH)
# print("LED2 HIGH")
# else:
# GPIO.output(led2, GPIO.LOW)
# print("LED2 LOW")

@blynk.on("V1")
def v1_write_handler(value):
global servo
if int(value[0]) != 0:
print("Starting servo movement sequence...")
servo.mid()
time.sleep(5)
servo.min()
time.sleep(5)
servo.max()
time.sleep(5)
servo.mid()
time.sleep(5)
print("Servo movement sequence completed.")
else:
print("No action required for virtual pin V1.")

@blynk.on("connected")
def blynk_connected():
global weight_grams, adjusted_weight
print("RPI is connected to Blynk")
calibrate_scale() # Initiate calibration after Blynk connection

print(f"Raw Weight: {weight_grams} grams, Adjusted Weight: {adjusted_weight}


grams")
print(f"Calibration Factor: {calibration_factor}, Ratio: {ratio}")

try:
while True:
# Read water sensor
water_level = GPIO.input(water_sensor_pin)
blynk.virtual_write(2, water_level)

time.sleep(1)
blynk.run()

except KeyboardInterrupt:
print("Code stopped by user.")

finally:
GPIO.cleanup()
print("Clean up")

You might also like