Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 4476

Python • Controlling Relay Module - Can't turn it off

$
0
0
I have Raspberr PI 4 Model B and Relay SRD-05VDC-SL-C.

I conected rspberry pi and relay in this way
pin 4 (5V power) to VCC
pin 6 (Ground) to GND
pin 40 (GPIO 21) to IN

https://drive.google.com/file/d/1JeHdPP ... drive_link

https://drive.google.com/file/d/11NHpl7 ... drive_link


I have python code to controll relay and the problem is when i turn on relay light turn on and i hear click, but when i try to turn it off nothing happen their is no click and light on relay is still on. but when i run cleanup i hear click and light turn off. why off command is not working?

my code:

Code:

from flask import Flask, jsonifyimport RPi.GPIO as GPIOimport atexitapp = Flask(__name__)# Relay configurationRELAY_PIN = 21  # GPIO21relay_state = False  # Track relay statedef initialize_gpio():    """Initialize GPIO settings"""    GPIO.setmode(GPIO.BCM)    GPIO.setwarnings(False)    GPIO.setup(RELAY_PIN, GPIO.OUT)    # Initialize relay to OFF state    GPIO.output(RELAY_PIN, GPIO.HIGH)def cleanup_gpio():    """Cleanup GPIO on program exit"""    try:        GPIO.output(RELAY_PIN, GPIO.HIGH)  # Turn off relay        GPIO.cleanup()    except:        pass# Register cleanup function to run at exitatexit.register(cleanup_gpio)# Initialize GPIO on startupinitialize_gpio()@app.route('/relay/on', methods=['GET'])def turn_relay_on():    """API endpoint to turn relay ON"""    try:        # Ensure GPIO is set up        if not GPIO.getmode():            initialize_gpio()                GPIO.output(RELAY_PIN, GPIO.LOW)  # Active LOW        global relay_state        relay_state = True                return jsonify({            "status": "success",            "message": "Relay turned ON",            "relay_state": "ON"        }), 200    except Exception as e:        return jsonify({            "status": "error",            "message": f"Failed to turn relay ON: {str(e)}"        }), 500@app.route('/relay/off', methods=['GET'])def turn_relay_off():    """API endpoint to turn relay OFF"""    try:        # Ensure GPIO is set up        if not GPIO.getmode():            initialize_gpio()                    GPIO.output(RELAY_PIN, GPIO.HIGH)  # Active LOW        global relay_state        relay_state = False                return jsonify({            "status": "success",            "message": "Relay turned OFF",            "relay_state": "OFF"        }), 200    except Exception as e:        return jsonify({            "status": "error",            "message": f"Failed to turn relay OFF: {str(e)}"        }), 500@app.route('/relay/status', methods=['GET'])def get_status():    """API endpoint to get relay status"""    try:        if not GPIO.getmode():            initialize_gpio()                    current_state = "ON" if relay_state else "OFF"        return jsonify({            "status": "success",            "relay_state": current_state        }), 200    except Exception as e:        return jsonify({            "status": "error",            "message": f"Failed to get relay status: {str(e)}"        }), 500@app.route('/cleanup', methods=['GET'])def cleanup():    """API endpoint to cleanup GPIO"""    try:        cleanup_gpio()        return jsonify({            "status": "success",            "message": "GPIO cleaned up successfully"        }), 200    except Exception as e:        return jsonify({            "status": "error",            "message": f"Failed to cleanup GPIO: {str(e)}"        }), 500if __name__ == '__main__':    try:        app.run(host='0.0.0.0', port=5000, debug=False)    finally:        cleanup_gpio()     

Statistics: Posted by medved.timotej — Wed Oct 30, 2024 9:48 am — Replies 7 — Views 70



Viewing all articles
Browse latest Browse all 4476

Trending Articles