Raspberry Pi. Firebase. Turn LED on/off. Get status of a PushButton. Slider. Servo

Hello friends,

in this web site we can see how we can control a set of lights through an application, Firebase and Raspberry Pi:

In this topic we will see how we can turn on/off an LED from the application using Firebase. We will also see how we can obtain the status of a PushButton in real time.

I will use:

  • Android 9
  • Raspberry 3 Model B.
  • Connection to a router (by Wifi or cable)
  • Raspbian 10 (buster)
  • Python 3.
  • Firebase realtime.
  • LED. PushButton.

From Firebase you need (You can also see it on the website indicated above):


firebase5

- App Inventor.
p9i_raspberry_firebase_boton.aia (2.7 KB)

In Designer:

Blocks:
firebase20i

  • When you Click a Button in App or no press PushButton in Raspberry, Firebase gets:

firebase18i

2 Likes

- Raspberry code. Python. Pyrebase.

You need:

pi@raspberrypi:~ $ python3 -V
Python 3.7.3

pi@raspberrypi:~ $ pip --version
pip 18.1 from /usr/lib/python2.7/dist-packages/pip (python 2.7)

If you don't have pip, you can install it:
pi@raspberrypi:~ $ curl https://bootstrap.pypa.io/get-pip.py | python3

You also need "Pyrebase", to communicate Python with Firebase.
pi@raspberrypi:~ $ sudo pip 3 install Pyrebase

  • In Raspbian we have a text editor for Python.
    firebase13

  • Paste this code (Change apiKey, authDomain, databaseURL and storageBucket) :

# Juan A. Villalpando
# http://kio4.com/raspberry/9_firebasedb.htm				 
					 
import RPi.GPIO as GPIO 
import pyrebase 
from time import sleep

config = {     
  "apiKey": "AIzaSyAo9cEmTy2pOEygEEIXdCUHc7uOlSFdcW4",
  "authDomain": "kio4-3c240",
  "databaseURL": "https://kio4-3c240.firebaseio.com/",
  "storageBucket": "project-293607155139"
}

firebase = pyrebase.initialize_app(config)

LED22 = 22         # Terminal by number, el 22 es el GPIO25.
PushButton18 = 18  # Terminal by number, el 18 es el GPIO24.
                   # El otro terminal a GND.

GPIO.setmode(GPIO.BOARD)   # Terminal by number.
GPIO.setwarnings(False)
GPIO.setup(LED22,GPIO.OUT)
GPIO.setup(PushButton18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
                                                               
print("Inicio. (CTRL + C para salir.")
  
try:
    while True:      # Bucle principal

        database = firebase.database()
        ProjectBucket = database.child("project-293607155139")                            
        estadoLED22 = ProjectBucket.child("LED").get().val()
    
        # print(estadoLED22)
                                                                                 
        if str(estadoLED22) == "\"OFF\"":
            print("LED22 now is OFF.")
            GPIO.output(LED22, GPIO.LOW)
        else:
            print("LED22 now is ON.")
            GPIO.output(LED22, GPIO.HIGH)
            
        if GPIO.input(PushButton18) == GPIO.HIGH:
            print("PushButton not pressed.")
            ProjectBucket.child("project-293607155139").child("PushButton").set("no_pressed.")
        else:
            print("PushButton pressed.")
            ProjectBucket.child("project-293607155139").child("PushButton").set("PRESSED.")
        
except KeyboardInterrupt:     # Salir con CTRL+C
    print("Salida.")
    GPIO.cleanup()            # Limpiar GPIO

- Connections.

2 Likes

- Comments:

2 Likes

- A Slider in the app, moves a servo.

A Slider in the app sends a value to Firebase, Raspberry takes that value and moves a Servo.

p9i_raspberry_firebase_Slider.aia (3.0 KB)

# Juan A. Villalpando
# http://kio4.com/raspberry/9_firebasedb.htm				 
					 
import RPi.GPIO as GPIO 
import pyrebase 
from time import sleep

config = {     
  "apiKey": "AIzaSyAo9cEmTy2pOEygEEIXdCUHc7uOlSFdcW4",
  "authDomain": "kio4-3c240",
  "databaseURL": "https://kio4-3c240.firebaseio.com/",
  "storageBucket": "project-293607155139"
}

firebase = pyrebase.initialize_app(config)

LED22 = 22         # Terminal by number, el 22 es el GPIO25.
PushButton18 = 18  # Terminal by number, el 18 es el GPIO24.
                   # El otro terminal a GND.
Servo40 = 40       # Terminal by number, el 40 es el GPIO21.

GPIO.setmode(GPIO.BOARD)   # Terminal by number.
GPIO.setwarnings(False)
GPIO.setup(LED22,GPIO.OUT)
GPIO.setup(PushButton18, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(Servo40,GPIO.OUT)

pwm=GPIO.PWM(40,50) # pin 40 a 50 Hz
pwm.start(0)
valorServo40 = 90

def SetAngle(angle):
    duty = angle / 18 + 2
    GPIO.output(40,True)
    pwm.ChangeDutyCycle(duty)
    sleep(1)
    GPIO.output(40,False)
    pwm.ChangeDutyCycle(0)
                                                               
print("Inicio. (CTRL + C para salir.")
  
try:
    while True:      # Bucle principal

        database = firebase.database()
        ProjectBucket = database.child("project-293607155139")                            
        estadoLED22 = ProjectBucket.child("LED").get().val()
        print(estadoLED22)
        valorServo40 = ProjectBucket.child("project-293607155139").child("Servo").get().val()
        print(valorServo40)
                                                                                 
        if str(estadoLED22) == "\"OFF\"":
            print("LED22 now is OFF.")
            GPIO.output(LED22, GPIO.LOW)
        else:
            print("LED22 now is ON.")
            GPIO.output(LED22, GPIO.HIGH)
            
        if GPIO.input(PushButton18) == GPIO.HIGH:
            print("PushButton not pressed.")
            ProjectBucket.child("project-293607155139").child("PushButton").set("no_pressed.")
        else:
            print("PushButton pressed.")
            ProjectBucket.child("project-293607155139").child("PushButton").set("PRESSED.")
        
        SetAngle(int(valorServo40)) # Cámbia el ángulo
        # pwm.stop()
        
except KeyboardInterrupt:     # Salir con CTRL+C
    print("Salida.")
    GPIO.cleanup()            # Limpiar GPIO

- Raspberry generates two random numbers, sends them to Firebase, the application receives them.

  • Raspberry generates temperature (0 ... 100) and pressure (0 ... 700).
# Juan A. Villalpando
# http://kio4.com/raspberry/9_firebasedb.htm
					 
import RPi.GPIO as GPIO 
import pyrebase 
from time import sleep

# generate random integer values
from random import seed
from random import randint

config = {     
  "apiKey": "AIzaSyAo9cEmTy2pOEygEEIXdCUHc7uOlSFdcW4",
  "authDomain": "kio4-3c240",
  "databaseURL": "https://kio4-3c240.firebaseio.com/",
  "storageBucket": "project-293607155139"
}

firebase = pyrebase.initialize_app(config)
database = firebase.database()
ProjectBucket = database.child("project-293607155139") 

temperatura = 50
presion = 350  
                                                               
print("Inicio. (CTRL + C para salir.)")
  
try:
    while True:      # Bucle principal
        temperatura = randint(0, 100)
        presion = randint(0, 700)
        
        ProjectBucket.child("project-293607155139").child("temperatura").set(temperatura)
        ProjectBucket.child("project-293607155139").child("presion").set(presion)
                                                                                   
        sleep(4)    
    
except KeyboardInterrupt:     # Salir con CTRL+C
    print("Salida.")
    GPIO.cleanup()            # Limpiar GPIO
  • Values ​​arrive in Firebase.
    firebase25

  • App gets the values ​​from Firebase in real time and displays them in Gauges.

  • I use two types of Gauges, through a Canvas with two ImageSprites and through Google Chart.

  • The Canvas has as background image: gauge_firebase1.png.
    For the needles we used two ImageSprites with a transparent background.

p9i_raspberry_firebase_temperatura.aia (176.9 KB)

Summary
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
   <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   <script type="text/javascript">
      // Juan A. Villalpando
	  // http://kio4.com/raspberry/9_firebasedb.htm
      google.charts.load('current', {'packages':['gauge']});
      google.charts.setOnLoadCallback(drawChart);

	  temp_hume = window.AppInventor.getWebViewString().split(":");// Entrada de datos.
      temperatura =  temp_hume[0];
      humedad =  temp_hume[1];

       function drawChart() {

        var data = google.visualization.arrayToDataTable([
          ['Label', 'Value'],
          ['Temp', 50],
        ]);

        var options = {
          width: 400, height: 120,
          redFrom: 90, redTo: 100,
          yellowFrom:75, yellowTo: 90,
          minorTicks: 5
        };

        var chart = new google.visualization.Gauge(document.getElementById('chart_div_1'));
		
		///////////////////////////////////////////////
		 var data2 = google.visualization.arrayToDataTable([
          ['Label', 'Value'],
          ['Pres', 350],
        ]);

        var options2 = {
          width: 400, height: 120,
		  greenFrom: 0, greenTo: 180,
          redFrom: 600, redTo: 700,
          yellowFrom:490, yellowTo: 600,
          minorTicks: 5,
		  max: 700
        };

        var chart2 = new google.visualization.Gauge(document.getElementById('chart_div_2'));
		
       ///////////////////////////////////////////////
        chart.draw(data, options);
        data.setValue(0, 1, temperatura);
        chart.draw(data, options);
		
		chart2.draw(data2, options2);
        data2.setValue(0, 1, humedad);
        chart2.draw(data2, options2);
      };
      </script>
  </head>
 <body>
    <div id="chart_div_1" style="width: 400px; height: 120px;"></div>
	<div id="chart_div_2" style="width: 400px; height: 120px;"></div>
 </body></html>
1 Like

Hi, there! My project is the same as yours using firebase with MIT and wondering if you could help me out? I'm just a beginner though I understand how to connect them, I can't just pick up the logic on the looping side. If I clicked the button, the servo just kept moving non-stop.

Could you please show me how to put a button that can move the servo to 90 degrees every time I clicked this button from the mobile app, please? Thanks a lot.