

Open 4.4Motion Alarm.py in Files and click
.
'''
* Filename : Smart Safe Home: Motion Alarm
* Thonny : Thonny 4.1.4
* Auther : http//www.keyestudio.com
'''
from machine import Pin, PWM
from AK8975C import ak8975c
import neopixel
import time
trumpet = PWM(Pin(2)) # power amplifier
scl = Pin(5)
sda = Pin(4)
bus = 0
Triaxial = ak8975c(bus, scl, sda)
led = Pin(14, Pin.OUT) # 6812RGB module
pixels = neopixel.NeoPixel(led, 4)
brightness=5
while True:
Triaxial.measure() # measure data once
print('x:',Triaxial.X,'y:',Triaxial.Y,'z:',Triaxial.Z) # print the geomagnetic force on axis X Y Z
if Triaxial.AK8975_GET_AZIMUTH(Triaxial.X, Triaxial.Y) == True: # Print the course angle value(azimuth value) only when the angle can be calculated.
degree = Triaxial.angle_val
print('degree:', degree,'°')
if degree > 0.0 and degree < 45.0:
trumpet.duty_u16(0)
for i in range(4):
pixels[i] = (0,0,0)
pixels.write()
else:
for i in range(4):
pixels[i] = (255,255,0)
pixels.write()
trumpet.freq(880)
trumpet.duty_u16(2000)
time.sleep(0.3)

Conceive:
Set a threshold angle range to determine whether objects have been moved.
Place the object and ensure its Course Angle is within the range, which means the object is not moved. Once the Course Angle value is greater than the threshold, it indicates that the item has been moved, so the amplifier alarms and the 6812 RGB lights up.

Code structure:
Initialization. Set the pins of the power amplifier, 6812 RGB module and IIC interface.
Loop.
Print the calculated Course Angle.
Determine whether the angle is within 0° ~ 45°(this range can be modified according to needs).
0° < angle < 45°: the amplifier stay quiet and LED keeps off.
angle is not within 0° ~ 45°: the object is moved, so the amplifier alarms and the LED lights up in yellow.


After uploading code, place the device and maintain the Course Angle within 0° ~ 45°. In the initial state, the amplifier does not emit sound and the pixels are off. Move this device, and the angle will exceed the range of 0° ~ 45°, so the amplifier alarms and the pixels are on in yellow.



