0

I have developed a smart bulb using relay to switch the bulb on and off when I clap. This works with a simple python script but that i want to use django as a server for handling this use case. I could not handle the following cases

1) there will be button for turning the bulb on and off (this i could do) 2) when i clap, the bulb should turn on and again if i clap the bulb should turn off.

For second case, how can i continuously listen for the sensor data so my bulb can act it accordingly.

Here is the simple script which works

#!/usr/bin/python
import RPi.GPIO as GPIO
import time

# telling pi we are not using the pin but BCM standard GPIO names for the pins
GPIO.setmode(GPIO.BCM)

BULB_OUTPUT_PIN = 4
SOUND_INPUT_PIN = 17

# as I am refering to the BCM mode instead of BOARD mode so the output pin is
# GPIO4 which is 7th pin in the pi when starting the first pin from left.
GPIO.setup(BULB_OUTPUT_PIN, GPIO.OUT)
GPIO.output(BULB_OUTPUT_PIN, GPIO.HIGH)

# for sound sensor
GPIO.setup(SOUND_INPUT_PIN, GPIO.IN)

SleepTime = 6

# main loop

try:
    while 1:
        print('#######GPIO INPUT PIN##### ', GPIO.input(SOUND_INPUT_PIN))
        if GPIO.input(SOUND_INPUT_PIN) == GPIO.LOW:
            print("##########Sound is sensed############")
            time.sleep(SleepTime)
            GPIO.output(BULB_OUTPUT_PIN, GPIO.LOW)
            print("#Relay is triggered in the switch 1########")
            time.sleep(SleepTime)
            GPIO.cleanup()
            print("Good bye!")
# End program cleanly with keyboard
except KeyboardInterrupt:
    print("Quit")

    # Reset GPIO settings
    GPIO.cleanup()

using django

#!/usr/bin/python
import RPi.GPIO as GPIO
import time

SleepTime = 6

BULB_OUTPUT_PIN = 4
SOUND_INPUT_PIN = 17


def smart_bulb(request, action=None):
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(BULB_OUTPUT_PIN, GPIO.OUT)
    try:
        if action == "on":
            # telling pi we are not using the pin but BCM standard GPIO names for the pins
            # as I am refering to the BCM mode instead of BOARD mode so the output pin is
            # GPIO4 which is 7th pin in the pi when starting the first pin from left.
            print("bulb will glow now")
            time.sleep(SleepTime)
            GPIO.output(BULB_OUTPUT_PIN, GPIO.HIGH)
        else:
            print("bulb will fade out")
            time.sleep(SleepTime)
            GPIO.output(BULB_OUTPUT_PIN, GPIO.LOW)
    except KeyboardInterrupt:
        GPIO.cleanup()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.