This article is Chapter 3 of a four-chapter article.
I want to notify the LINE Bot of the time when the motion sensor responded and the number of times it responded within an hour. You can run SQL locally, but I thought it would be easier to store it in a cloud database because the Raspberry Pi with a motion sensor and the Raspberry Pi used as a server for LINE Bot are separate, so I used the standard Firebase.
--Raspberry Pi 3 Model A + (OK if it is higher than this) --Human sensor module --Jumper wire (female-female)
I used the motion sensor from this manufacturer.
[Raspberry Pi] How to use and use the self-made motion sensor was used as it is. Be careful of GPIO connection mistakes (I made the mistake of mistakenly pinning pin 12 and Ground).
Firebase I referred to [python] How to get started with Firebase Realtime Database.
Install firebase-admin on Raspberry Pi with the following command
$ pip install firebase-admin
Create a Database from the Firebase console. There are Cloud Firestore
and Realtime Database
, but please note that this time it is ** Realtime Database
**.
Change the rules as follows:
Also, go to Set Project> Service Account> Firebase Admin SDK
from the gear on the right side of" Project Overview ", select Python
to copy, and click Generate New Private Key
. , Save the downloaded private key to Raspeye.
Below is the code
firebase.py
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
from datetime import datetime
import time
import RPi.GPIO as GPIO
cred = credentials.Certificate("<Downloaded private key>.json")
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://<databaseURL>.firebaseio.com/'
})
ref = db.reference('data')
INTERVAL = 3
SLEEPTIME = 20
GPIO_PIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(GPIO_PIN, GPIO.IN)
while True:
if(GPIO.input(GPIO_PIN) == GPIO.HIGH):
print(datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
new_data_ref = ref.push()
new_data_ref.set({
'timestamp': {'.sv': 'timestamp'}
})
time.sleep(SLEEPTIME)
else:
print(GPIO.input(GPIO_PIN))
time.sleep(INTERVAL)
When it is detected, push it to Database with timestamp. A unique ID is generated by pushing. Apparently the ID is also in chronological order.
It is also Issue here, but it seems that there is a habit of registering timestamps from Python's firebase-admin module. I hope you find the 'timestamp': {'.sv':'timestamp'}
above helpful.
In this way, when detected, it is written to the Realtime Database.
UNIX time 1597307961996
is 2020/08/13 17:39:21 so it's perfect.
That's all for storing the reaction time of the motion sensor in the Firebase Realtime Database. Next, get that data from another Raspberry Pi.
Recommended Posts