Creating a Bluetooth doorbell

Now that we know how to read button information from Blue Dot, we can build a Bluetooth doorbell button. We will rewrite our DoorbellAlarm class, and use a simple button press from Blue Dot to activate the alarm, as follows:

  1. Open up Thonny from Application Menu | Programming | Thonny Python IDE
  2. Click on the New icon to create a new file
  3. Type the following into the file:
from gpiozero import RGBLED
from gpiozero import Buzzer
from time import sleep

class DoorbellAlarmAdvanced:

led = RGBLED(red=17, green=22, blue=27)
buzzer = Buzzer(26)
num_of_times = 0
delay = 0

def __init__(self, num_of_times, delay):
self.num_of_times = num_of_times
self.delay = delay


def play_sequence(self):
num = 0
while num < self.num_of_times:
self.buzzer.on()
self.light_show()
sleep(self.delay)
self.buzzer.off()
sleep(self.delay)
num += 1


def light_show(self):
self.led.color=(1,0,0)
sleep(0.1)
self.led.color=(0,1,0)
sleep(0.1)
self.led.color=(0,0,1)
sleep(0.1)
self.led.off()


if __name__=="__main__":

doorbell_alarm = DoorbellAlarmAdvanced(5,1)
doorbell_alarm.play_sequence()
  1. Save the file as DoorbellAlarmAdvanced.py

Our new class, DoorbellAlarmAdvanced, is a modified version of the DoorbellAlarm class. What we have done is basically add a new class property that we call delay. This class property will be used to change the delay time between buzzer rings. As you can see in the code, the two methods modified for the change are __init__ and play_sequence.

Now that we have the changes in place for our alarm, let's create a simple doorbell program as follows:

  1. Open up Thonny from Application Menu | Programming | Thonny Python IDE
  2. Click on the New icon to create a new file
  3. Type the following into the file:
from bluedot import BlueDot
from signal import pause
from DoorbellAlarmAdvanced import DoorbellAlarmAdvanced

class SimpleDoorbell:

def pressed():
doorbell_alarm = DoorbellAlarmAdvanced(5, 1)
doorbell_alarm.play_sequence()


blue_dot = BlueDot()
blue_dot.when_pressed = pressed



if __name__=="__main__":

doorbell_alarm = SimpleDoorbell()
pause()
  1. Save the file as SimpleDoorbell.py and run it
  2. Connect the Blue Dot app to the Raspberry Pi, if it is not already connected
  3. Push the big blue dot

You should hear five rings, each lasting one second, from the buzzer in one-second intervals. You will also see that the RGB LED went through a short light show. As you can see, the code is pretty straightforward. We import our new DoorbellAlarmAdvanced class, and then call the play_sequence method after we initialize the class with the doorbell_alarm variable in the pressed method.

The changes we made in creating the DoorbellAlarmAdvanced class are utilized in our code to allow us to set the delay time between rings.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset