CircuitPython Prep

Follow this guide https://learn.adafruit.com/adafruit-gemma-m0/circuitpython to get started with coding the Gemma M0 in CircuitPython. Install the latest release version of CircuitPython on the board. You may also want to install the Mu editor https://learn.adafruit.com/adafruit-gemma-m0/installing-mu-editor for your coding needs.

Once you can successfully code in Mu and upload to the board, return here.

Alarm Code

The alarm code will do two fundamental things: measure the analog voltage value on pin A0 to see when it drops below a certain threshold, and use PWM (pulse width modulation) to play alarm tones on the piezo buzzer over pin D0.

Copy the code below, paste it into Mu, and then save it to your Gemma M0 as code.py.

# SPDX-FileCopyrightText: 2018 John Edgar Park for Adafruit Industries
#
# SPDX-License-Identifier: MIT

# Motion Sensor Alarm
# uses Gemma M0, vibration sensor on A0/GND, & piezo on D0/GND
import time
import pwmio
from analogio import AnalogIn
import board

piezo = pwmio.PWMOut(board.D0, duty_cycle=0, frequency=440,
                       variable_frequency=True)

vibrationPin = AnalogIn(board.A0)


def get_voltage(pin):
    return (pin.value * 3.3) / 65536


while True:
    print((get_voltage(vibrationPin),))
    vibration = get_voltage(vibrationPin)

    if vibration < 1:  # the sensor has been tripped, you can adjust this value
        # for sensitivity
        for f in (2620, 4400, 2620, 4400, 2620, 4400, 2620, 4400):
            piezo.frequency = f
            piezo.duty_cycle = 65536 // 2  # on 50%
            time.sleep(0.2)  # on 1/5 second
            piezo.duty_cycle = 0  # off
            time.sleep(0.02)  # pause
    time.sleep(0.01)  # debounce delay

Test the alarm by touching or tapping it. As soon as it senses a bit of movment, BEEP BEEP BEEP BEEP BEEP!!!

This guide was first published on Mar 15, 2018. It was last updated on Mar 15, 2018.

This page (Code the Alarm with CircuitPython) was last updated on May 31, 2023.

Text editor powered by tinymce.