Introduction to our Raspberry Pi and Firebase trick
Let me introduce you to the latest trick of Raspberry Pi and Firebase we’ll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit we will build is going to connect to the Raspberry Pi using the GPIO pins. After that, we will write a program to collect the data from these sensors. Further, the data that the sensors will collect is sent to the Firebase server in “.json” format. For instance we’ll be using the following components for the circuit:-
Components List
- Raspberry Pi 3 B+ Kit
- Memory Card (16Gb/32Gb)
- DHT 11 (Temperature Sensor)
- Infrared Sensor (IR sensor)
- Bread Board
- Jumper Wires
- Power Supply Adapter
Now let’s learn something about the components we’ve written in the above list. First comes the Raspberry Pi i.e., the processor module. Here we’re using Raspberry Pi model 3 B+.
Raspberry Pi 3 B+
The Raspberry Pi model 3 B+ is by far the most recent edition to the Raspberry Pi 3 family. It incorporates a 64-bit quad-core processor operating at 1.4GHz, dual-band 2.4GHz, and 5GHz wireless LAN, Bluetooth 4.2/BLE, faster Ethernet, and PoE capability via a separate PoE HAT. You can connect different sensors as per the requirement of your project. For example the temperature and Infrared sensors that we’ll be using in this trick to take data from the surroundings. First comes the temperature sensor-
Temperature sensor
The temperature sensor which is a digital sensor that combines two sensors into a single package. This package includes an NTC (Negative Temperature Coefficient) type temperature sensor, a resistive-type Humidity Sensor, and an 8-bit microcontroller to transform the analog signals from these sensors into digital output. For instance, we’ll be using DHT 11 temperature and humidity sensor in this trick. In other words temperature sensor communicates using a single bus data format. For data exchange, we only need a single data line between an MCU (Arduino or Raspberry Pi) and a DHT11 Sensor. The circuit connections for that are shown in the below image.
In the system shown in the above image the Raspberry pi will work as a master while the temperature sensor will work as a slave. To activate the sensor the Data OUT pin of the temperature sensor should be in HIGH state which is done with the help of 5.1 K resistor. This will ensure that sensor is ready to process the data requested by the master only. On the other hand if there is some problem with sensor it will not activate for data processing. Now lets see the interfacing of the sensor with Raspberry.
Raspberry Pi Interface with Humidity and Temperature Sensor
The above diagram shows you the interfacing of the temperature sensor with GPIO pins of Raspberry Pi. These GPIO pins are specially designed for connecting sensors. Connect the Sensor’s Data OUT to the GPIO4 (Physical Pin 7) on the Raspberry Pi and the +VCC and GND pins of the Temperature sensor to +5V and GND on the Raspberry Pi. This will result a circuit similar to the above circuit. Also you can use different GPIO pin for sensor connection but GPIO4 is considered better for receiving data from temperature sensor. Similarly lets take a look at the connections of Infrared sensor.
Infrared Sensor
It is also a digital sensor but unlike temperature sensor it is a type of sensor which emits and receives infrared radiations, and detects the object as it approaches the sensor. The basic components of an IR Sensor Module are an IR Transmitter, an IR Detector, and a control circuit. An infrared Transmitter, Photo Diode, or (less frequently) a Photo Transistor is used as an IR Detector and Comparator IC with appropriate components makes up the control circuit.
Let us learn more about infrared sensors by looking at two real-world applications. Cell phones are the first to use infrared sensors. During a call when we put it closer to our ear, the phone’s display turns off and we don’t accidentally hit something on the screen. That is to say no unwanted button is clicked by mistake. Second, are modern cars which have an inbuilt reverse parking sensor that detects how fast you can back up without hitting anything. The below image shows a IR sensor module.
Next comes the interfacing of this sensor module with raspberry pi.
Interfacing IR Sensor with Raspberry Pi
The below image shows that how we can physically connect the IR Sensor to a Raspberry Pi to create a Obstacle Detection and alert system.
Most importantly, next we have the circuit diagram for connecting IR sensor to GPIO pins of Raspberry Pi.
Circuit Diagram
The below image shows the connection diagram and interfacing of IR Sensor with Raspberry Pi. Similar to the physical circuit the IR sensor pins ( VCC and GND) will be connected to the Raspberry Pi (+5V and GND) pins. Further the IR Sensor’s Data pin will be connected to GPIO23, which is Physical Pin 16 on the Raspberry Pi.
Above all now we need to setup our processing device to receive and process the data. In addition this data will be sent to the Firebase server for representation.
Setting up Raspberry Pi
First of all you need to visit the https://www.raspberrypi.org website and download the .zip file of Debian OS. Once the download is complete extract the file (.iso) format using “Winrar.exe”. After this, we’ve to flash the OS (Debian) in the memory card by using Balena etcher software. But before that Insert the memory card (16 GB, 32 GB) into your computer and format it by using SD card formatter software.
The next step is to connect your Raspberry Pi and the peripheral devices as shown in the below figure.
One you connect all the peripheral devices to your processor. After that power up the Raspberry Pi using an adapter and open the terminal window and run the following commands.
sudo raspi-config
sudo apt-get install
sudo apt-get update
sudo apt-get upgrade
sudo pip install python3
sudo pip3 install pyrebase
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
# After running following codes successfully create a python file in Rpi
sudo nano hello.py
As a result of the above commands you’ve successfully installed the libraries we need for successful execution of the code we’ll be running for the trick. As you’ve created the python file just paste the following code and save the file (Ctrl + O) . Press Y and close the file(Ctrl + X). Below is the code for the trick. But before executing this code you need to setup your Firebase account.
Code
import RPi.GPIO as GPIO
from time import sleep
import datetime
#import firebase
#import pyrebase
import Adafruit_DHT
import urllib3, urllib, httplib2
import json
import os
from functools import partial
#config = {
# "apiKey": "ccbyTCko8khKenmotX3hdKaKMhgMmd1kRD35EHkY",
# "authDomain": "proj1-88a23.firebaseapp.com",
# "databaseURL": "https://proj1-88a23-default-rtdb.firebaseio.com/",
# "projectId": "proj1-88a23",
# "storageBucket": "proj1-88a23.appspot.com",
#};
from firebase import firebase
url = 'https://proj1-88a23-default-rtdb.firebaseio.com/'
firebase = firebase.FirebaseApplication(url)
#firebase = pyrebase.initialize_app(config)
GPIO.setmode(GPIO.BCM)
#GPIO.cleanup()
GPIO.setwarnings(False)
# Sensor should be set to Adafruit_DHT.DHT11,
# Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302.
sensor = Adafruit_DHT.DHT11
# Example using a Beaglebone Black with DHT sensor
# connected to pin P8_11.
pin = 4
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
#firebase = firebase.FirebaseApplication('https://proj1-88a23-default-rtdb-firebaseio.com/', None)
#firebase.put("/dht", "/temp", "0.00")
#firebase.put("/dht", "/humidity", "0.00")
#def update_firebase():
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
while True:
#sleep(5)
str_temp = ' {0:0.2f} *C '.format(temperature)
str_hum = ' {0:0.2f} %'.format(humidity)
print("Temperature=","Humidity=",str_temp,str_hum)
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
#result = firebase.put(str_temp, str_hum)
result = firebase.patch('/sensor/dht',{'Temperature':str_temp,'Humidity':str_hum})
print(result)
sleep(5)
Introduction to Firebase
Google’s Firebase framework allows developers to create mobile and web apps. It started out as a stand-alone business in 2011. Google bought the platform in 2014, and it is now their main product for app growth.
Setting up your Firebase account
As you’ve come so far so let’s setup your Firebase account. Most importantly you need to have a google account for this. Go to “console.firebase.com” and login with your Google account. Below are the step by step explanation that you need to follow to setup your Firebase account:
Step 1: In the “get started” tab click on the “Get Started” button. On this page select Add Project and provide a name to project.
Step2: Select the project from the drop-down list and click continue
Step 3: You’ll get this page. Just click on the continue button.
Step 4: Enable or Disable Google Analytics for your firebase project( Disable for our project). You need to disable the Google Analytics and click the continue button.
Step 5: On the next page select the google analytics location and check the use default settings and I accept Google Analytics terms checkboxes. After that click on Add Firebase.
Step 6: You’ll see that Google will be cresting your firebase and once it finishes you get a message “Your new project is ready”. Click on continue.
Step 7: In the top-left corner select the Realtime Database option and open it. Click the rules option and change the rules as shown here.
Real-time Data on Firebase
After doing this open Terminal window and run the command “sudo python <filename>.py”. If your Python code runs successfully you can see the real time data received from the sensor on your firebase console. If any error is generated try to check if you’ve followed the steps properly.
Now hide the devices somewhere and show the data on the Firebase console to your friends and amaze them.
Hope you’ve enjoyed the tutorial.