Search code examples
pythonraspberry-pigpio

GPIO in Rapberry Pi no Turn Off


Write this code with python3. But don't work. Only the relay comes on but it does not turn off.

I need this turn on and after 3 seconds to turn off.

This is my code:

import RPi.GPIO as GPIO
import time

channel = 23

# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.OUT)


def motor_on(pin): 
    GPIO.output(pin, GPIO.HIGH)  # Turn motor on


def motor_off(pin):
    GPIO.output(pin, GPIO.LOW)  # Turn motor off


if __name__ == '__main__':
    try:
        motor_on(channel)
        time.sleep(2)
        motor_off(channel)
        time.sleep(2)

        GPIO.cleanup()

        motor_on(channel)
        time.sleep(2)
        motor_off(channel)
        time.sleep(2)

    GPIO.cleanup()
    except KeyboardInterrupt:
    GPIO.cleanup()

enter image description here


Solution

  • There are a couple problems with your code in general -- the indentation at the end should be like this

        try:
            motor_on(channel)
            time.sleep(2)
            motor_off(channel)
            time.sleep(2)
    
            GPIO.cleanup()
    
            motor_on(channel)
            time.sleep(2)
            motor_off(channel)
            time.sleep(2)
    
            GPIO.cleanup()
        except KeyboardInterrupt:
            GPIO.cleanup()
    

    and as above, running motor_on() and motor_off() after GPIO.cleanup() will give you errors if you don't run GPIO.setmode() and GPIO.setup() again first -- but with those things fixed, your code works perfectly fine to turn an LED on and off, so there may be a problem with your circuit.