Doorbell - full code

This commit is contained in:
2021-09-14 17:22:43 +02:00
parent 1c6f0afdeb
commit 7196891717
10 changed files with 328 additions and 0 deletions
@@ -0,0 +1,35 @@
# https://www.instructables.com/id/Arduino-Python-Communication-via-USB/
# in rc.local:
# su tilman -c 'python3 /media/hd/admin/doorbell/doorbell.py >> /media/hd/admin/doorbell/doorbell.log 2>&1 &'
import serial
import urllib.request
import logging
import logging.handlers as handlers
import time
logger = logging.getLogger('Rotating Log')
logger.setLevel(logging.INFO)
logHandler = handlers.RotatingFileHandler('/media/hd/admin/doorbell/doorbell.log', maxBytes=1000000, backupCount=2)
logHandler.setLevel(logging.INFO)
logHandler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s - %(message)s', '%Y-%m-%d %H:%M:%S'))
logger.addHandler(logHandler)
logger.info('Initializing')
arduino = serial.Serial('/dev/ttyUSB0', 9600, timeout=.1)
while True:
data = arduino.readline()[:-2] #the last bit gets rid of the new-line chars
if data:
data = data.decode('utf8')
if (data == 'RING'):
try:
response = urllib.request.urlopen('http://192.168.178.51/bell/on', timeout=5).read().decode('utf-8')
except Exception:
logger.error("Could not ring doorbell")
# logger.exception("Could not ring doorbell")
time.sleep(300)
else:
logger.info(data)
@@ -0,0 +1,49 @@
/*
* https://www.arduino.cc/en/Tutorial/BuiltInExamples/Button
*
* D2 -------------
* | |
* Button |
* | |
* +5V ----- |
* 10kOhm
* |
* GND -------------
*/
const int ledPin = LED_BUILTIN;
const int buttonPin = 2; // Button connected to D2
const int flare_threshold = 20;
bool active = false;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
Serial.println("Doorbell sensor");
}
void loop() {
int val = digitalRead(buttonPin);
if (val == HIGH) {
delay(flare_threshold); // catch flares
val = digitalRead(buttonPin);
if (val == HIGH && active == false) {
Serial.println("RING");
digitalWrite(ledPin, HIGH);
active = true;
delay(250);
}
else if (val == LOW) {
Serial.print("flare (<");
Serial.print(flare_threshold);
Serial.println(")");
}
} else {
digitalWrite(ledPin, LOW);
active = false;
}
}