from utime import sleep
from machine import Pin, SoftI2C, PWM
from mpu6050 import *
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
accelerometer = accel(i2c)
while True:
print(accelerometer.get_values())
sleep(0.5)
speaker = PWM(Pin(18))
speaker.duty_u16(1000)
speaker.freq(1000) # 50% on and off
sleep(1) # wait a second
speaker.duty_u16(0)
# turn off the PWM circuits off with a zero duty cycle
#speaker.duty_u16(0)
SAMPLES = 5 # Number of samples to trigger action
SAMPLETIME = 0.1 # Time between samples
# Create shared variables for communication between processes
ins = outs = 0
more = 0 # Extension of prev event
peeping = 0 # Flap open just enough to sniff
ending = 0 # Count to avoid spurious end of event
intruder = False
x = y = z = 0.0
# Main code starts here
try:
while True:
# Create directory for the day
# Read and display the raw magnetometer readings
values = accelerometer.get_values()
z = values["GyZ"]
# print "xyz = %2.2f %2.2f %2.2f" % (x, y, z)
# Detect an entry or exit
# Sometimes the first sample or two are in the wrong sense. Reset.
if ins > 0 and ins <= 2 and z < 0.0 \
or (outs > 0 and outs <= 2 and z > 0.0):
ins = 0
outs = 0
# Detect catflap at least 25 degrees open either way:
if z > 0.43:
ins += 1
outs = 0
elif z < -0.43:
outs += 1
ins = 0
# Detect foreign cat peeping in
# But note that if ins > 30 he's just left his tail in the catflap
if z > 0.2 and z < 0.43 and ins < 30:
peeping += 1
# Detect an intruder
if peeping == 30 or ins + peeping == 60:
if not intruder:
intruder = True
print("Intruder! peeping\n")
# We have an entry or exit if at least SAMPLES readings > 25 degrees
if ins == SAMPLES or outs == SAMPLES:
if ins == SAMPLES:
print("In\n")
else:
print("Out\n")
more = 0
# logfile = open(dirname + "catflap.txt", "a")
# logfile.write("%s Setting cat_evt\n" %asctime())
# logfile.close()
# End of event if catflap < 15 degrees
if abs(z) >= 0.26:
ending = 0
else:
# Intruder? continue event for 5 secs and sound warning after 2 secs
if intruder and more < 50:
more += 1
if more == 20: # Give him 2 secs to think he's safe!
print("Yowl!\n")
speaker.duty_u16(1000)
else:
# Count to 3 samples before accepting end of event
if ending < 3:
ending += 1
else:
if ins > 0 and ins < SAMPLES:
print("Transitory In\n")
elif outs > 0 and outs < SAMPLES:
print("Transitory Out\n")
ins = outs = peeping = more = ending = 0
intruder = False
speaker.duty_u16(0)
# logfile = open(dirname + "catflap.txt", "a")
# logfile.write("%s Clearing cat_evt\n" %asctime())
# logfile.close()
sleep(SAMPLETIME)
except KeyboardInterrupt:
raise