Doorbell — Smart Home (Python)
This example is written twice, once for each firmware. Pick the tab that matches the firmware of your Smart Home: the tab you pick is remembered on the other examples.
Firmware 3.0 renamed the Python names a program writes, and kept none of the old ones: a Smart Home on 2.x does not know the 3.0 names, and a Smart Home on 3.0 does not know the 2.x ones. The name map lists every change. If you open the example from inside MoBot, it picks the version for the firmware of your Smart Home. If you download a file from this page, use the one in the tab for your firmware.
A door that knows who you are. Hold a card on the reader: if the house knows
it, the light goes green, the screen says Welcome!, a happy tune plays and the
door opens. If it does not, the light goes red and you get a cross buzz.
You teach it new cards yourself, and it remembers them after it is switched off.
This is the version for a house on firmware 3.0, where the house is called
home. For a house that still runs firmware 2.x, MoBot opens the 2.x version of
this example instead.
Project for firmware 3.0: 06-doorbell.firmware-3.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A MoBot Smart Home board with the RFID reader, servo (the door), OLED screen, RGB light, buzzer, knob, button and the number display.
- Two or three RFID cards or tags — the ones that come with the kit, or a bus card, or a hotel key card.
- A USB cable and the serial monitor.
How to run it
Section titled “How to run it”- Open 06-doorbell.firmware-3.mobot and press Save. MoBot restarts the board, and it runs the program.
- The screen says
Doorbell / Show a card. - Hold the button down and touch a card to the reader. The screen says
Learned!and shows the card’s number. - Let go of the button and touch the same card again.
What you should see and hear
Section titled “What you should see and hear”| you do | the house does |
|---|---|
| show a known card | green light, Welcome! on the screen, three rising notes, and the servo swings the door open, then closes it again |
| show an unknown card | red light, Who are you?, and three low buzzes |
| hold the button and show a new card | blue light, Learned!, two notes — and from now on that card is a known one |
| turn the knob | changes how long the door stays open, from 1 second to 8 — the screen tells you which |
| all the time | the little red digits show the battery voltage, something like 4.13 |
| switch the board off and on again | it still knows your cards |
If the reader never sees anything, hold the card flat against it and closer than you think — a centimetre or two.
How the house remembers
Section titled “How the house remembers”Every card the house learns is written into a file on the board itself, called
known_cards.txt. It is an ordinary text file with one card number per line, and
you can read it from the serial monitor:
print(open("known_cards.txt").read())To forget everybody again:
import os; os.remove("known_cards.txt")A card’s number is ten letters and digits, like 3906f6945d. Every card in
the world has a different one, and it cannot be changed — which is what makes
this a lock rather than a game.
Showing a decimal on the digits
Section titled “Showing a decimal on the digits”The little red display shows whole numbers, and each digit has a dot you can
light. So show_volts() sends 4.13 volts as 413 with the first dot lit:
home.number_display.show_number(413, [True, False, False]) # 4.13The program
Section titled “The program”This is a reading copy of the program in the project: editing it changes nothing, so open the project and edit it there.
# main.py — Doorbell (Python) (iot)## A reading copy of one file inside 06-doorbell.firmware-3.mobot.# Editing this copy changes nothing: open the project and edit it there.# This is the entry point — the board runs it as main.py.# Written for firmware 3.0; the 2.x version is 06-doorbell.main.py.
"""Doorbell - MoBot Smart Home: a door that knows who you are.
Hold a card on the reader:
a card the house knows -> green, "Welcome", the door opens, a happy tune a card it has never seen -> red, "Who are you?", a cross buzz
To teach the house a new card, HOLD THE BUTTON DOWN and show it the card. Thehouse writes the card's number into a file on itself, so it still rememberstomorrow.
The knob decides how long the door stays open. The little red digits show howmany volts are left in the battery.
This is all your own program, which means you can change every rule in it."""
import time
CARD_FILE = "known_cards.txt"display = home.displaynumber_display = home.number_display
def set_colour(red, green, blue): """Light the RGB lamp: red, green and blue, each 0-255, in that order.""" home.rgb_led.set_color(red, green, blue)
def show_volts(volts): """Show a voltage such as 4.13 on the three digits, with its dot.
The display only shows whole numbers, so 4.13 is sent as 413 with the dot of the first digit lit. Ten volts or more gets one decimal place instead. """ if number_display is None: return hundredths = round(volts * 100) if hundredths < 1000: number_display.show_number(hundredths, [True, False, False]) else: number_display.show_number(round(volts * 10), [False, True, False])
def load_cards(): """Read the card numbers we saved last time. An empty list if there are none.""" try: with open(CARD_FILE) as handle: return [line.strip() for line in handle if line.strip()] except OSError: return []
def remember(uid): """Add one card number to the file, so it survives being switched off.""" with open(CARD_FILE, "a") as handle: handle.write(uid + "\n")
def say(top, bottom=""): display.clear() display.show_text(top[:16], 0, 8) if bottom: display.show_text(bottom[:16], 0, 32)
def open_door(seconds): home.servo.set_angle(90) # 90 degrees is open time.sleep(seconds) home.servo.set_angle(0) # 0 is closed
known = load_cards()print("The house knows", len(known), "card(s).")print("Hold the BUTTON down while showing a new card to teach it.")
say("Doorbell", "Show a card")home.servo.set_angle(0)set_colour(0, 0, 0)
last_uid = ""last_seen = time.ticks_ms()
while True: # The knob, 0..4095, becomes 1 to 8 seconds of open door. open_for = 1 + home.knob.position() * 7 // 4095
# The battery, on the little red digits. 4.13 means 4.13 volts. show_volts(home.battery.voltage())
teaching = home.button.is_pressed() uid = home.rfid.read_card() if home.rfid is not None else None
if uid is None: if teaching: say("Learning...", "show a card") set_colour(0, 0, 150) time.sleep(0.15) continue
# Ignore the same card being read over and over while it sits there. if uid == last_uid and time.ticks_diff(time.ticks_ms(), last_seen) < 2000: time.sleep(0.15) continue last_uid = uid last_seen = time.ticks_ms()
print("card:", uid, " known:", uid in known, " teaching:", teaching)
if teaching and uid not in known: known.append(uid) remember(uid) say("Learned!", uid[:16]) set_colour(0, 0, 255) home.buzzer.play_note("C5", 120) home.buzzer.play_note("G5", 200) time.sleep(1.5)
elif uid in known: say("Welcome!", "Door open " + str(open_for) + "s") set_colour(0, 255, 0) home.buzzer.play_note("C5", 120) home.buzzer.play_note("E5", 120) home.buzzer.play_note("G5", 250) open_door(open_for)
else: say("Who are you?", "Not allowed") set_colour(255, 0, 0) for _ in range(3): home.buzzer.play_tone(180, 150) time.sleep(0.1) time.sleep(1.0)
set_colour(0, 0, 0) say("Doorbell", "Show a card")Try changing it
Section titled “Try changing it”- Give each card a name: keep a dictionary of
number -> nameand sayWelcome, Amina!. - Refuse everybody after 8 in the evening.
- Count how many times each card has been used and show it on the digits with
show_number(). - Make an unknown card set off a proper alarm: red flashing, a siren of
play_tone()calls, and a message on the screen for a minute.
A door that knows who you are. Hold a card on the reader: if the house knows
it, the light goes green, the screen says Welcome!, a happy tune plays and the
door opens. If it does not, the light goes red and you get a cross buzz.
You teach it new cards yourself, and it remembers them after it is switched off.
Project for firmware 2.x: 06-doorbell.mobot. Open it in MoBot.
What you need
Section titled “What you need”- A MoBot Smart Home board with the RFID reader, servo (the door), OLED screen, RGB light, buzzer, knob and button.
- Two or three RFID cards or tags — the ones that come with the kit, or a bus card, or a hotel key card.
- A USB cable and the serial monitor.
How to run it
Section titled “How to run it”- Open 06-doorbell.mobot and press Save. MoBot restarts the board, and it runs the program.
- The screen says
Doorbell / Show a card. - Hold the button down and touch a card to the reader. The screen says
Learned!and shows the card’s number. - Let go of the button and touch the same card again.
What you should see and hear
Section titled “What you should see and hear”| you do | the house does |
|---|---|
| show a known card | green light, Welcome! on the screen, three rising notes, and the servo swings the door open, then closes it again |
| show an unknown card | red light, Who are you?, and three low buzzes |
| hold the button and show a new card | blue light, Learned!, two notes — and from now on that card is a known one |
| turn the knob | changes how long the door stays open, from 1 second to 8 — the screen tells you which |
| all the time | the little red digits show the battery voltage, something like 4.1 |
| switch the board off and on again | it still knows your cards |
If the reader never sees anything, hold the card flat against it and closer than you think — a centimetre or two.
How the house remembers
Section titled “How the house remembers”Every card the house learns is written into a file on the board itself, called
known_cards.txt. It is an ordinary text file with one card number per line, and
you can read it from the serial monitor:
print(open("known_cards.txt").read())To forget everybody again:
import os; os.remove("known_cards.txt")A card’s number is ten letters and digits, like 3906f6945d. Every card in
the world has a different one, and it cannot be changed — which is what makes
this a lock rather than a game.
The program
Section titled “The program”This is a reading copy of the program in the project: editing it changes nothing, so open the project and edit it there.
# main.py — Doorbell (Python) (iot)## A reading copy of one file inside 06-doorbell.mobot.# Editing this copy changes nothing: open the project and edit it there.# This is the entry point — the board runs it as main.py.
"""Doorbell - MoBot Smart Home: a door that knows who you are.
Hold a card on the reader:
a card the house knows -> green, "Welcome", the door opens, a happy tune a card it has never seen -> red, "Who are you?", a cross buzz
To teach the house a new card, HOLD THE BUTTON DOWN and show it the card. Thehouse writes the card's number into a file on itself, so it still rememberstomorrow.
The knob decides how long the door stays open. The little red digits show howmany volts are left in the battery.
None of the five house minds are running here - this is all your own program,which means you can change every rule in it."""
import time
CARD_FILE = "known_cards.txt"oled = mobotIOT.oledseg = mobotIOT.seg
def set_colour(red, green, blue): """Light the RGB lamp. Each value is 0-100.
Firmware 2.0 names each lamp pin by the colour it really drives, so write() takes red, green, blue in that order and set_colour(100, 0, 0) is red. (Boards on older firmware had red and green the other way round and needed the two swapped here; if yours shows green for red, flash 2.0.) """ mobotIOT.rgb_led.write(red, green, blue)
def load_cards(): """Read the card numbers we saved last time. An empty list if there are none.""" try: with open(CARD_FILE) as handle: return [line.strip() for line in handle if line.strip()] except OSError: return []
def remember(uid): """Add one card number to the file, so it survives being switched off.""" with open(CARD_FILE, "a") as handle: handle.write(uid + "\n")
def say(top, bottom=""): oled.clear_screen() oled.display_text(top[:16], 0, 8) if bottom: oled.display_text(bottom[:16], 0, 32)
def open_door(seconds): mobotIOT.servo.set_angle(90) # 90 degrees is open time.sleep(seconds) mobotIOT.servo.set_angle(0) # 0 is closed
known = load_cards()print("The house knows", len(known), "card(s).")print("Hold the BUTTON down while showing a new card to teach it.")
say("Doorbell", "Show a card")mobotIOT.servo.set_angle(0)set_colour(0, 0, 0)
last_uid = ""last_seen = time.ticks_ms()
while True: # The knob, 0..4095, becomes 1 to 8 seconds of open door. open_for = 1 + mobotIOT.pot.read() * 7 // 4095
# The battery, on the little red digits. 4.1 means 4.1 volts. if seg is not None: seg.float(mobotIOT.battery.read())
teaching = mobotIOT.button.is_pressed() uid = mobotIOT.rfid.read() if mobotIOT.rfid is not None else None
if uid is None: if teaching: say("Learning...", "show a card") set_colour(0, 0, 60) time.sleep(0.15) continue
# Ignore the same card being read over and over while it sits there. if uid == last_uid and time.ticks_diff(time.ticks_ms(), last_seen) < 2000: time.sleep(0.15) continue last_uid = uid last_seen = time.ticks_ms()
print("card:", uid, " known:", uid in known, " teaching:", teaching)
if teaching and uid not in known: known.append(uid) remember(uid) say("Learned!", uid[:16]) set_colour(0, 0, 100) mobotIOT.buzzer.play_note("C5", 120) mobotIOT.buzzer.play_note("G5", 200) time.sleep(1.5)
elif uid in known: say("Welcome!", "Door open " + str(open_for) + "s") set_colour(0, 100, 0) mobotIOT.buzzer.play_note("C5", 120) mobotIOT.buzzer.play_note("E5", 120) mobotIOT.buzzer.play_note("G5", 250) open_door(open_for)
else: say("Who are you?", "Not allowed") set_colour(100, 0, 0) for _ in range(3): mobotIOT.buzzer.play_sound(180, 150) time.sleep(0.1) time.sleep(1.0)
set_colour(0, 0, 0) say("Doorbell", "Show a card")Try changing it
Section titled “Try changing it”- Give each card a name: keep a dictionary of
number -> nameand sayWelcome, Amina!. - Refuse everybody after 8 in the evening.
- Count how many times each card has been used and show it on the digits.
- Make an unknown card set off a proper alarm: red flashing, the siren, and a message on the screen for a minute.