PIR Movement Alarm With BBC Micro:bit and External Speaker

by kevinjwalters in Circuits > Microcontrollers

2735 Views, 2 Favorites, 0 Comments

PIR Movement Alarm With BBC Micro:bit and External Speaker

microbit-pir-sensor-create-board-1.jpg

This article shows how to make a simple movement alarm using MicroPython on a BBC micro:bit V2, a 3.3V compatible, miniature passive infrared (PIR) sensor module, a small external speaker and a few extra components. The program plays low bitrate sound samples when a warm, moving object is detected.

The project was implemented with components soldered onto a Kitronik :CREATE Proto Board. A breadboard was used to ensure the circuit worked before soldering onto the final board.

This project should work on both the micro:bit V1 and V2 but the V2 has a few advantages:

The audio samples are still fairly quiet on this setup and will only be audible in a quiet room. Simple tones are more practical for loud alarms as both speakers are more responsive at certain high frequencies.

Supplies

  • BBC micro:bit.
  • Kitronik :CREATE Proto Board.
  • CUI CMT-2512-585T 25mm 32ohm speaker - Mouser | Digi-Key - for alternatives the maximum current needs to be within the limits of the micro:bit.
  • AM312 PIR sensor module or similar 3.3V compatible module like HC-SR505. Always check the documentation and labelling of pinouts. Avoid "standard" HC-SR501 modules as these are typically designed for 5V use.
  • 2N2222 NPN transistor or 2N3904 - most NPN transistors will be ok, check the pinouts and verify the maximum power and current are suitable for the speaker.
  • Diode, 1N4001 or similar.
  • 1k resistor.
  • Solder (and soldering iron!).
  • Some short insulated wires.
  • Optional:
    • 4 small self-adhesive rubber feet at least 3mm tall - these will prevent the board scratching surfaces.
    • Multimeter - useful for checking the soldered connections are good using the resistance mode or continuity mode.

Circuit Diagram

microbit-pir-sensor-speaker-v1_schem-tidied2-65.png

The circuit is very simple using power from the micro:bit edge connector (GND and 3V) and two GPIO pins.

  1. The P0 pin is commonly used for audio output on the micro:bit and on the V2 is also used for the built-in speaker on the back of the micro:bit.
  2. The P8 pin is used as an input for the PIR sensor module.

The GPIO outputs can drive very low current devices directly like piezo speakers but the current required for the 25mm speaker is too high and would stress the output. An NPN transistor (Q1) is used here to buffer the (square wave) output and switch the higher current through the speaker (J1). The resistor (R1) is limiting the current across the base-emitter junction of Q1 when P0 is high (3.3V). The circuit follows the datasheet recommendation with a flyback diode (D1) across the speaker to deal with the back EMF when the square wave causes the transistor to abruptly switch on/off.

The digital P0 output will be pulse-width modulated (PWM) when playing audio samples to approximate the original analogue audio signal.

Breadboard Implementation

microbit-pir-sensor-breadboard-1.jpg

A breadboard is useful to:

  1. check the circuit works,
  2. evaluate sensors and
  3. allow easy refinements before a more rigid implementation.

The AM312 sensor modules are often advertised as having a high signal of around 2 seconds when they detect motion. This is useful because this duration is long enough to allow simple level-based pin reading which will work even if the program is doing other processing for some of the time.

Some quick testing in CircuitPython's REPL from another microcontroller showed this is more-or-less accurate and that the device did not give false indications if no one was in the room for ~6 minutes.

>>> while True:
...     for idx in range(80):
...         print("X" if pir_p6.value else "." , end="")
...         time.sleep(0.4)
...     print()
...XXXXXXX........XXXX..........................................................
................................................................................
...9 more lines full of dots...
................................................................................
..................................................XXXXXXXXXXXX.....XXXXX........
...XXXXX.....Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
KeyboardInterrupt:

The red LED on the breadboard in the photograph above is doing nothing. It was used as a temporary substitute for the rectifier diode to confirm the speaker generates back EMF when playing back audio samples.

Kitronik :CREATE Proto Board Implementation

microbit-pir-sensor-create-board-topside-1.jpg
microbit-pir-sensor-kitronik-create-board-layout-handdrawn-1.jpg
microbit-pir-sensor-create-board-underside-1.jpg

The :CREATE Proto Board is described by Kitronik:

Create prototype circuits using surface mount and/or conventional components with the :CREATE Proto Board for the BBC microbit. The design features a twin grid system that allows for circuits to be made of a mixture of surface mount and through hole. That the circuits are soldered makes for robust prototyping.

It's a convenient size for small projects like this one. The layout was mostly planned with a quick DaveCAD™ sketch and then finished with some improvisation. The steps to attach the components to the board and make the circuit are listed below in order.

  1. Gently bend the pins on the AM312 PIR sensor module to an appropriate angle. Ninety degrees is probably too far because the white plastic lens is too large.
  2. Check all the components fit on the board.
  3. Solder the speaker and PIR sensor module to keep them in place. This speaker is marked on its side with a positive (+) marker for the nearby speaker pin. This is not visible in the photograph above - it's on the right side. This speaker pin connects to the 3.3V power.
  4. Insert the diode and bend its protruding long legs on the underside of the board to reach and connect to the speaker pins. It is very important to get the orientation of the diode correct. The cathode marked by the silver band connects to the 3.3V power.
  5. Cut a black wire to the right length but with excess copper exposed at both ends to allow it to connect to the sensor pin and from the GND pad to the transistor's emitter across the underside of the board. Lightly tinning stripped multi-strand wire will help the proceedings.
  6. Cut two lengths of red wire for routing the 3.3V power from the 3V pad across the bottom of the board to the speaker/diode and PIR sensor module.
  7. Cut another colour wire, e.g. yellow, for the signal to the P8 input pad from the PIR sensor module - excess copper at one end will allow the connection under the board to the sensor module's pin.
  8. Connect the diode/speaker to the transistor's collector by dragging solder across the top surface to form a "solder bridge". Solder bridges are normally an accidental flaw but the top surface on this board is intended to facilitate these for quick, short connections.
  9. Solder the resistor across the top from the P0 output pad to a hole near the transistor's base
  10. Check the connections visually and measure the resistance of each connection with a multimeter. These will all be below 1 ohm if they are good.
  11. Cut off excess pin/lead lengths on the underside.
  12. Add four rubber feet on the corners to prevent scratching of any surface the board sits on.
  13. Insert micro:bit into edge connector. This is best done with the micro:bit not connected to the USB (power).

The soldering was done very quickly here due to time pressure and is far from perfect but is functional! For this type of board where the holes do not provide the connectivity it's not critical for the solder to flow perfectly over the through-holes on the board, it's more important it flows across the various wires between pins.

Always check documentation/datasheets on sensor modules and transistors for the pinouts.

The resistor lead on the right is just above the solder bridge from the transistor. Low wattage resistors tend to have thin leads which means that it could be pressed and bent against the solder bridge creating an unfortunate short. The height of the edge connector socket and speaker make this unlikely but not impossible. There is probably a safer routing or insulation solution for this connection...

The datasheet for the :CREATE Proto Board shows some examples of various components soldered to the board and how to make tracks with solder on the top surface.

Install Code and Audio Files Onto the Micro:bit

python-microbit-org-editor-load-notalanitsstevefiles-1.png
For a browser with WebUSB support like Google Chrome or Microsoft Edge:
  1. Download the files from GitHub:
    1. Click on Raw button on not-alan-its-steve.py and use Save as in browser to download the file.
    2. Click on alan.raw, al.raw, notalan.raw and steve.raw in audio directory, click on Raw on each to download the file.
  2. Connect the micro:bit to the computer using a USB cable (not a charge-only one!).
  3. Go to the micro:bit online editor in a browser: https://python.microbit.org/
    1. Click on Connect, the micro:bit should appear as an entry called BBC micro:bit CMSIS-DAP - select that and click on connect.
    2. Click on Load/Save and then load the not-alan-its-steve.py file in the top section of the pop-up.
    3. Under Project Files at the bottom of the pop-up, click on Show Files (1) to expand the list. Click on Add file at the bottom to add each of the four raw audio files.
    4. Click on the cross at the top right of the pop-up to close it.
  4. Click on Flash - this will download all five files to the (connected) micro:bit and start the program.

The useful connection functionality in the online editor depends on WebUSB and having recent firmware on the micro:bit. If you are using a different browser or this does not work then you can use the online editor's save function to save a hex file onto the MICROBIT drive.

The program on a standalone micro:bit may start playing audio samples. On the V2 these will be audible due to the code enabling the tiny, rear speaker. This is caused by unconnected pins like P8 giving unpredictable inputs, in this case it can make the program think the PIR sensor module is present and has set P8 to a high value.

Test and Enjoy

micro:bit V2 with PIR sensor and small speaker

Five seconds after start-up, the program looks for a high signal from the PIR sensor module and will play through all five audio sample sequences if the PIR sensor continues to "see" movement. It runs forever starting back at the first sequence if the sensor detects nothing.

If it does not work then check the transistor and diode aren't very hot with your finger. If they are then disconnect the power immediately and check your wiring. The micro:bit will scroll any errors across its single character screen. These are challenging to read but for MicroPython errors these can also be seen by clicking on Open Serial in the micro:bit online editor.

Processing Audio to Make Custom Raw Audio Files

audacity-8k-export-raw8bitu-2.png

If you want to change the audio files you need to generate raw mono 8bit unsigned audio samples at 8kHz rate. The rate is documented as 7812.5 Hz if you wish to be more precise / pitch perfect. Audacity can be used to create these files with the steps listed below.

  1. Set the Project Rate to 8000 or 7812.
  2. Select a short mono section of audio** and consider adjusting volume or using compressor (under Effect menu) to make it as loud as possible.
  3. Use File / Export / Export Selected Audio... (shown above) with Header set to RAW (header-less) and Encoding set to Unsigned 8-bit PCM. The default file extension is .raw.

**The balance must be set exactly to the centre to generate mono (single channel) output.

Going Further

cui-speakers-7.5mm-25mm-response.png

Once you've built your movement detector, here's some other ideas:

  • Use your own sound samples.
  • Add some visual effects on the micro:bit LEDs when the sound samples play.
  • Show a count of the number of detections over time on the LEDs as a number or with some sort of graphical representation.
  • Explore the sensitivity of the sensor for object size, temperature (difference to background) and movement speed. And for range and angle.
  • Test different frequency tones to find the sweet spot for loudness. The graphs above are the logarithmic frequency response for a similar speaker to the micro:bit V2 (top) and the 25mm external speaker (bottom).
  • For the micro:bit V2, change the code to use just one speaker and compare the sound of the built-in vs external speaker.
  • Add more sensors to cover all quadrants. These need to be mounted well above (or below) the board if you want good 360 degree coverage.
  • Explore other prototyping boards:

Related projects:

Further reading: