I am using raspberry pi5 for controlling a 12V solenoid. 1 channel 5V relay is used for this purpose. The VCC of relay is connected to 5V pin of pi, GND to ground and IN to gpio18. The COM terminal is connected to 12 V battery, NO terminal is connected to solenoid. The relay was supposed to give uninterrupted power supply all the time except for 0.5 seconds, enabling solenoid to come down and then again to give power and solenoid goes up. However, once the program is run relay is always in active position and is not changing its state. what is the solution?
here i am giving the code.
import gpiod
from time import sleep
def test_solenoid():
try:
# Initialize GPIO
chip = gpiod.Chip('gpiochip4')
SOLENOID_PIN = 18
solenoid_line = chip.get_line(SOLENOID_PIN)
# Request output control for solenoid
solenoid_line.request(consumer="Solenoid", type=gpiod.LINE_REQ_DIR_OUT)
# Set initial state (relay off, solenoid up)
solenoid_line.set_value(1)
print("Initial state: Solenoid OFF (GPIO set to 1)")
sleep(1) # Wait for stabilization
# Activate solenoid
print("Activating solenoid...")
solenoid_line.set_value(0) # Turn on relay (solenoid down)
print("Solenoid GPIO set to 0 (Relay ON)")
sleep(0.5) # Keep solenoid active for 0.5 second
# Deactivate solenoid
print("Deactivating solenoid...")
solenoid_line.set_value(1) # Turn off relay (solenoid up)
print("Solenoid GPIO set to 1 (Relay OFF)")
sleep(1) # Wait for stabilization
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Clean up GPIO
if 'solenoid_line' in locals():
solenoid_line.set_value(1) # Reset to default state
solenoid_line.release()
if 'chip' in locals():
chip.close()
print("GPIO resources released.")
if __name__ == "__main__":
test_solenoid()
here i am giving the code.
import gpiod
from time import sleep
def test_solenoid():
try:
# Initialize GPIO
chip = gpiod.Chip('gpiochip4')
SOLENOID_PIN = 18
solenoid_line = chip.get_line(SOLENOID_PIN)
# Request output control for solenoid
solenoid_line.request(consumer="Solenoid", type=gpiod.LINE_REQ_DIR_OUT)
# Set initial state (relay off, solenoid up)
solenoid_line.set_value(1)
print("Initial state: Solenoid OFF (GPIO set to 1)")
sleep(1) # Wait for stabilization
# Activate solenoid
print("Activating solenoid...")
solenoid_line.set_value(0) # Turn on relay (solenoid down)
print("Solenoid GPIO set to 0 (Relay ON)")
sleep(0.5) # Keep solenoid active for 0.5 second
# Deactivate solenoid
print("Deactivating solenoid...")
solenoid_line.set_value(1) # Turn off relay (solenoid up)
print("Solenoid GPIO set to 1 (Relay OFF)")
sleep(1) # Wait for stabilization
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Clean up GPIO
if 'solenoid_line' in locals():
solenoid_line.set_value(1) # Reset to default state
solenoid_line.release()
if 'chip' in locals():
chip.close()
print("GPIO resources released.")
if __name__ == "__main__":
test_solenoid()
Statistics: Posted by Nayana — Sun Feb 16, 2025 4:23 pm — Replies 3 — Views 55