Android Take Picture and Upload to Firebase
In this guide, you'll learn how to have and upload a movie to Firebase Storage using the ESP32-CAM. You'll create a Firebase project with Storage that allows you lot to store your files. Then, you can access your Firebase console to visualize the pictures or create a web app to display them (we'll practise this in a time to come tutorial). The ESP32-CAM volition exist programmed using Arduino IDE.
Note:this projection is compatible with any ESP32 Camera Board with the OV2640 camera. You just need to brand sure you use the right pinout for the board you're using.
What is Firebase?
Firebase is Google's mobile application evolution platform that helps you build, improve, and grow your app. Information technology has many services used to manage data from whatever android, IOS, or spider web application similar hallmark, realtime database, hosting, storage, etc.
Project Overview
This simple tutorial exemplifies how to have and send photos taken with the ESP32-CAM to Firebase Storage. The ESP32-CAM takes a picture and sends it to Firebase every time it resets (press the RST button). The idea is that you add some sort of trigger that might be useful for your projects, like a PIR motility sensor or a pushbutton, for instance.
- When the ESP32 showtime runs, information technology takes a new moving picture and saves it in the filesystem (SPIFFS);
- The ESP32-CAM connects to Firebase as a user with email and password;
- The ESP32-CAM sends the flick to Firebase Storage;
- After that, you can get to your Firebase panel to view the pictures;
- Subsequently, you tin can build a web app that you can admission from anywhere to brandish the ESP32-CAM pictures (we'll create this in a future tutorial).
Contents
Here'due south a summary of the steps yous need to follow to create this project.
- Create a Firebase Project
- Set Authentication Methods
- Create Storage Saucepan
- Get Project API Central
- ESP32-CAM Send Pictures to Firebase Storage
1) Create a Firebase Project
1) Go to Firebase and sign in using a Google Account.
2) Click Become Started and then Add project to create a new project.
3) Requite a name to your project, for case: ESP Firebase Demo .
4) Disable the option Enable Google Analytics for this project as it is non needed and click Create project .
five) It will accept a few seconds to set up your project. Then, click Continue when information technology's ready.
6) Y'all'll exist redirected to your Project panel page.
ii) Prepare Hallmark Methods
To let hallmark with e-mail and password, outset, you need to fix authentication methods for your app.
"Most apps demand to know the identity of a user. In other words, it takes care of logging in and identifying the users (in this instance, the ESP32-CAM). Knowing a user'southward identity allows an app to securely relieve user data in the deject and provide the same personalized experience across all of the user's devices." To learn more about the hallmark methods, you can read the documentation.
1) On the left sidebar, click on Hallmark and then on Become started.
ii) Select the Option Electronic mail/Password.
3) Enable that hallmark method and click Save.
iv) The authentication with email and password should now be enabled.
5) At present, you need to add together a user. Still on the Authentication tab, select the Users tab at the summit. And so, click on Add together User.
vi) Add an email address for the authorized user. It can exist your google account electronic mail or whatsoever other email. You tin besides create an e-mail for this specific projection. Add together a password that will allow you to sign in to your app and access the storage files. Don't forget to salve the password in a safe identify because you'll need it subsequently. When you're done, click Add together user.
7) A new user was successfully created and added to the Users tabular array.
Discover that Firebase creates a unique UID for each registered user. The user UID allows us to place the user and keep track of the user to provide or deny admission to the project or the database. There's besides a column that registers the engagement of the last sign-in. At the moment, information technology is empty because we haven't signed in with that user yet.
3) Create Storage Bucket
1) On the left sidebar, click on Storage and then on Get started.
2) Use the default security rules—click Next.
3) Select your storage location—it should be the closest to your country.
four) Await a few seconds while it creates the storage bucket.
5) The storage bucket is now set upwards. Copy the storage bucket ID because you'll need it afterwards (copy just the section highlighted with a ruby-red rectangle every bit shown beneath).
four) Get Project API Cardinal
To interface with your Firebase project using the ESP32-CAM, you need to get your project API primal. Follow the next steps to get your project API fundamental.
one) On the left sidebar, click on Projection Settings.
2) Copy the Web API Key to a safe place considering you'll need it later.
5) ESP32-CAM – Send Pictures to Firebase Storage
Before proceeding with the tutorial, brand certain you check the following prerequisites.
Installing the ESP32 add-on
We'll program the ESP32-CAM lath using Arduino IDE. And then you need the Arduino IDE installed as well as the ESP32 improver. Follow the adjacent tutorial to install it, if you haven't already.
- Installing the ESP32 Board in Arduino IDE (Mac OS X and Linux instructions)
Installing ESP Firebase Client Library
The Firebase-ESP-Client library provides several examples to interface with Firebase services. It provides an example that shows how to send files to Firebase Storage. Our code we'll be based on that case. So, you demand to brand sure y'all take that library installed.
Installation – VS Code + PlatformIO
If you're using VS Code with the PlatformIO extension, click on thePIO Home icon and select theLibraries tab. Search for "Firebase ESP Client ". Select theFirebase Arduino Customer Library for ESP8266 and ESP32.
Then, clickAdd together to Project and select the project you're working on.
Also, change the monitor speed to 115200 by calculation the post-obit line to the platformio.ini file of your projection:
monitor_speed = 115200
Installation – Arduino IDE
If you're using Arduino IDE, follow the next steps to install the library.
- Get toSketch>Include Library >Manage Libraries
- Search forFirebase ESP Client and install theFirebase Arduino Client Library for ESP8266 and ESP32 by Mobitz.
Now, y'all're all fix to start programming the ESP32-CAM board to send pictures to Firebase Storage.
ESP32-CAM Send Pictures to Firebase – Code
Copy the following code to your Arduino IDE, or to the main.cpp file if you're using VS Code. It takes a moving picture and sends it to Firebase when it first boots.
/********* Rui Santos Consummate instructions at: https://RandomNerdTutorials.com/esp32-cam-save-moving-picture show-firebase-storage/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files. The above copyright observe and this permission observe shall be included in all copies or substantial portions of the Software. Based on the example provided by the ESP Firebase Client Library *********/ #include "WiFi.h" #include "esp_camera.h" #include "Arduino.h" #include "soc/soc.h" // Disable brownout issues #include "soc/rtc_cntl_reg.h" // Disable brownout problems #include "driver/rtc_io.h" #include <SPIFFS.h> #include <FS.h> #include <Firebase_ESP_Client.h> //Provide the token generation process info. #include <addons/TokenHelper.h> //Replace with your network credentials const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD"; // Insert Firebase project API Primal #define API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY" // Insert Authorized Email and Corresponding Password #ascertain USER_EMAIL "REPLACE_WITH_THE_AUTHORIZED_USER_EMAIL" #define USER_PASSWORD "REPLACE_WITH_THE_AUTHORIZED_USER_PASSWORD" // Insert Firebase storage bucket ID e.g bucket-name.appspot.com #define STORAGE_BUCKET_ID "REPLACE_WITH_YOUR_STORAGE_BUCKET_ID" // Photo File Name to save in SPIFFS #define FILE_PHOTO "/data/photo.jpg" // OV2640 camera module pins (CAMERA_MODEL_AI_THINKER) #define PWDN_GPIO_NUM 32 #define RESET_GPIO_NUM -1 #ascertain XCLK_GPIO_NUM 0 #define SIOD_GPIO_NUM 26 #define SIOC_GPIO_NUM 27 #define Y9_GPIO_NUM 35 #define Y8_GPIO_NUM 34 #define Y7_GPIO_NUM 39 #define Y6_GPIO_NUM 36 #define Y5_GPIO_NUM 21 #ascertain Y4_GPIO_NUM 19 #define Y3_GPIO_NUM 18 #define Y2_GPIO_NUM 5 #define VSYNC_GPIO_NUM 25 #define HREF_GPIO_NUM 23 #define PCLK_GPIO_NUM 22 boolean takeNewPhoto = true; //Define Firebase Information objects FirebaseData fbdo; FirebaseAuth auth; FirebaseConfig configF; bool taskCompleted = fake; // Check if photograph capture was successful bool checkPhoto( fs::FS &fs ) { File f_pic = fs.open( FILE_PHOTO ); unsigned int pic_sz = f_pic.size(); render ( pic_sz > 100 ); } // Capture Photograph and Salve it to SPIFFS void capturePhotoSaveSpiffs( void ) { camera_fb_t * fb = NULL; // pointer bool ok = 0; // Boolean indicating if the flick has been taken correctly exercise { // Accept a photograph with the photographic camera Series.println("Taking a photo..."); fb = esp_camera_fb_get(); if (!fb) { Series.println("Camera capture failed"); return; } // Photo file name Series.printf("Film file name: %s\due north", FILE_PHOTO); File file = SPIFFS.open up(FILE_PHOTO, FILE_WRITE); // Insert the data in the photo file if (!file) { Serial.println("Failed to open file in writing mode"); } else { file.write(fb->buf, fb->len); // payload (prototype), payload length Serial.impress("The movie has been saved in "); Serial.print(FILE_PHOTO); Serial.print(" - Size: "); Serial.print(file.size()); Serial.println(" bytes"); } // Close the file file.close(); esp_camera_fb_return(fb); // cheque if file has been correctly saved in SPIFFS ok = checkPhoto(SPIFFS); } while ( !ok ); } void initWiFi(){ WiFi.begin(ssid, password); while (WiFi.condition() != WL_CONNECTED) { delay(grand); Serial.println("Connecting to WiFi..."); } } void initSPIFFS(){ if (!SPIFFS.begin(truthful)) { Serial.println("An Fault has occurred while mounting SPIFFS"); ESP.restart(); } else { filibuster(500); Serial.println("SPIFFS mounted successfully"); } } void initCamera(){ // OV2640 camera module camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 20000000; config.pixel_format = PIXFORMAT_JPEG; if (psramFound()) { config.frame_size = FRAMESIZE_UXGA; config.jpeg_quality = 10; config.fb_count = 2; } else { config.frame_size = FRAMESIZE_SVGA; config.jpeg_quality = 12; config.fb_count = 1; } // Camera init esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { Serial.printf("Camera init failed with fault 0x%10", err); ESP.restart(); } } void setup() { // Serial port for debugging purposes Serial.begin(115200); initWiFi(); initSPIFFS(); // Plow-off the 'brownout detector' WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); initCamera(); //Firebase // Assign the api key configF.api_key = API_KEY; //Assign the user sign in credentials auth.user.email = USER_EMAIL; auth.user.password = USER_PASSWORD; //Assign the callback function for the long running token generation task configF.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h Firebase.begin(&configF, &auth); Firebase.reconnectWiFi(truthful); } void loop() { if (takeNewPhoto) { capturePhotoSaveSpiffs(); takeNewPhoto = false; } filibuster(1); if (Firebase.ready() && !taskCompleted){ taskCompleted = true; Serial.print("Uploading picture... "); //MIME type should exist valid to avoid the download problem. //The file systems for flash and SD/SDMMC can be changed in FirebaseFS.h. if (Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID /* Firebase Storage bucket id */, FILE_PHOTO /* path to local file */, mem_storage_type_flash /* memory storage type, mem_storage_type_flash and mem_storage_type_sd */, FILE_PHOTO /* path of remote file stored in the bucket */, "epitome/jpeg" /* mime blazon */)){ Serial.printf("\nDownload URL: %due south\north", fbdo.downloadURL().c_str()); } else{ Series.println(fbdo.errorReason()); } } }
View raw lawmaking
Yous need to insert your network credentials, storage bucket ID, and projection API key for the project to piece of work.
This sketch was based on a bones example provided by the library. You can find more examples here.
How the Code Works
Keep reading to learn how the lawmaking works or skip to the sit-in section.
Libraries
First, include the required libraries.
#include "WiFi.h" #include "esp_camera.h" #include "Arduino.h" #include "soc/soc.h" // Disable brownout problems #include "soc/rtc_cntl_reg.h" // Disable brownout issues #include "driver/rtc_io.h" #include <SPIFFS.h> #include <FS.h> #include <Firebase_ESP_Client.h> //Provide the token generation process info. #include <addons/TokenHelper.h>
Network Credentials
Insert your network credentials in the following variables so that the ESP tin connect to the net and communicate with Firebase.
//Supercede with your network credentials const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD";
Firebase Projection API Key
Insert your Firebase project API key—see this section: four) Become Projection API Fundamental.
// Insert Firebase project API Central #define API_KEY "REPLACE_WITH_YOUR_FIREBASE_PROJECT_API_KEY."
User Email and Password
Insert the authorized email and the corresponding password—see this section: two) Set Authentication Methods.
#define USER_EMAIL "REPLACE_WITH_THE_AUTHORIZED_USER_EMAIL" #ascertain USER_PASSWORD "REPLACE_WITH_THE_AUTHORIZED_USER_PASSWORD"
Firebase Storage Bucket ID
Insert the Firebase storage saucepan ID, e.k bucket-proper noun.appspot.com. In my example, it is esp-firebase-demo.appspot.com.
define STORAGE_BUCKET_ID "REPLACE_WITH_YOUR_STORAGE_BUCKET_ID"
Film Path
The FILE_PHOTO variable defines the SPIFFS path where the film will be saved. Information technology will exist saved with the proper noun photograph.jpg under the information folder.
#define FILE_PHOTO "/data/photo.jpg"
ESP32-CAM Pin Definition
The following lines define the ESP32-CAM pins. This is the definition for the ESP32-CAM AI-Thinker module. If you're using another ESP32-CAM module, y'all need to modify the pin definition—check this tutorial: ESP32-CAM Photographic camera Boards: Pin and GPIOs Assignment Guide.
// OV2640 photographic camera module pins (CAMERA_MODEL_AI_THINKER) #ascertain PWDN_GPIO_NUM 32 #define RESET_GPIO_NUM -1 #ascertain XCLK_GPIO_NUM 0 #define SIOD_GPIO_NUM 26 #ascertain SIOC_GPIO_NUM 27 #define Y9_GPIO_NUM 35 #ascertain Y8_GPIO_NUM 34 #define Y7_GPIO_NUM 39 #define Y6_GPIO_NUM 36 #define Y5_GPIO_NUM 21 #define Y4_GPIO_NUM xix #define Y3_GPIO_NUM eighteen #ascertain Y2_GPIO_NUM five #define VSYNC_GPIO_NUM 25 #define HREF_GPIO_NUM 23 #define PCLK_GPIO_NUM 22
Other Variables
The takeNewPhoto variable checks if it is time to take a new photo. We'll set it to true, so that it takes a picture when the board get-go runs.
boolean takeNewPhoto = true;
And then, we define Firebase configuration data objects.
//Ascertain Firebase Data objects FirebaseData fbdo; FirebaseAuth auth; FirebaseConfig configF;
The taskCompleted is a boolean variable that checks if we successfully connected to Firebase.
bool taskCompleted = false;
checkPhoto() Function
The checkPhoto() role checks if the picture was successfully taken and saved in SPIFFS.
// Bank check if photo capture was successful bool checkPhoto( fs::FS &fs ) { File f_pic = fs.open up( FILE_PHOTO ); unsigned int pic_sz = f_pic.size(); return ( pic_sz > 100 ); }
capturePhotoSaveSpiffs() Part
The capturePhotoSaveSpiffs() function takes a photo and saves it in the ESP32 filesystem.
// Capture Photo and Save it to SPIFFS void capturePhotoSaveSpiffs( void ) { camera_fb_t * fb = NULL; // pointer bool ok = 0; // Boolean indicating if the moving picture has been taken correctly do { // Take a photo with the camera Series.println("Taking a photo..."); fb = esp_camera_fb_get(); if (!fb) { Serial.println("Photographic camera capture failed"); return; } // Photo file name Serial.printf("Picture file proper noun: %s\northward", FILE_PHOTO); File file = SPIFFS.open up(FILE_PHOTO, FILE_WRITE); // Insert the data in the photo file if (!file) { Serial.println("Failed to open up file in writing manner"); } else { file.write(fb->buf, fb->len); // payload (epitome), payload length Series.print("The picture has been saved in "); Serial.print(FILE_PHOTO); Serial.print(" - Size: "); Series.print(file.size()); Serial.println(" bytes"); } // Close the file file.close(); esp_camera_fb_return(fb); // check if file has been correctly saved in SPIFFS ok = checkPhoto(SPIFFS); } while ( !ok ); }
initWiFi() Function
The initWiFi() office initializes Wi-Fi.
void initWiFi(){ WiFi.begin(ssid, countersign); while (WiFi.status() != WL_CONNECTED) { delay(thousand); Series.println("Connecting to WiFi..."); } }
initSPIFFS() Role
The initSPIFFS() role initializes the SPIFFS filesystem.
void initSPIFFS(){ if (!SPIFFS.brainstorm(true)) { Series.println("An Error has occurred while mounting SPIFFS"); ESP.restart(); } else { filibuster(500); Serial.println("SPIFFS mounted successfully"); } }
initCamera() Role
The initCamera() function initializes the ESP32-CAM.
void initCamera(){ // OV2640 camera module camera_config_t config; config.ledc_channel = LEDC_CHANNEL_0; config.ledc_timer = LEDC_TIMER_0; config.pin_d0 = Y2_GPIO_NUM; config.pin_d1 = Y3_GPIO_NUM; config.pin_d2 = Y4_GPIO_NUM; config.pin_d3 = Y5_GPIO_NUM; config.pin_d4 = Y6_GPIO_NUM; config.pin_d5 = Y7_GPIO_NUM; config.pin_d6 = Y8_GPIO_NUM; config.pin_d7 = Y9_GPIO_NUM; config.pin_xclk = XCLK_GPIO_NUM; config.pin_pclk = PCLK_GPIO_NUM; config.pin_vsync = VSYNC_GPIO_NUM; config.pin_href = HREF_GPIO_NUM; config.pin_sscb_sda = SIOD_GPIO_NUM; config.pin_sscb_scl = SIOC_GPIO_NUM; config.pin_pwdn = PWDN_GPIO_NUM; config.pin_reset = RESET_GPIO_NUM; config.xclk_freq_hz = 20000000; config.pixel_format = PIXFORMAT_JPEG; if (psramFound()) { config.frame_size = FRAMESIZE_UXGA; config.jpeg_quality = x; config.fb_count = ii; } else { config.frame_size = FRAMESIZE_SVGA; config.jpeg_quality = 12; config.fb_count = one; } // Camera init esp_err_t err = esp_camera_init(&config); if (err != ESP_OK) { Serial.printf("Camera init failed with mistake 0x%x", err); ESP.restart(); } }
setup()
In the setup(), initialize the Serial Monitor, Wi-Fi, SPIFFS, and the camera.
// Serial port for debugging purposes Serial.begin(115200); initWiFi(); initSPIFFS(); // Plough-off the 'brownout detector' WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); initCamera();
Then, assign the following settings to the Firebase configuration objects.
// Assign the api key configF.api_key = API_KEY; //Assign the user sign in credentials auth.user.e-mail = USER_EMAIL; auth.user.password = USER_PASSWORD; //Assign the callback function for the long running token generation task configF.token_status_callback = tokenStatusCallback; //come across addons/TokenHelper.h
Finally, initialize Firebase.
Firebase.begin(&configF, &auth); Firebase.reconnectWiFi(true);
loop()
In the loop(), take a new movie and save it to the filesystem.
if (takeNewPhoto) { capturePhotoSaveSpiffs(); takeNewPhoto = false; }
Finally, send the picture to Firebase.
if (Firebase.ready() && !taskCompleted){ taskCompleted = true; Serial.print("Uploading picture... "); //MIME blazon should exist valid to avert the download problem. //The file systems for flash and SD/SDMMC tin can be changed in FirebaseFS.h. if (Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID /* Firebase Storage bucket id */, FILE_PHOTO /* path to local file */, mem_storage_type_flash /* memory storage type, mem_storage_type_flash and mem_storage_type_sd */, FILE_PHOTO /* path of remote file stored in the bucket */, "image/jpeg" /* mime type */)){ Series.printf("\nDownload URL: %due south\n", fbdo.downloadURL().c_str()); } else{ Serial.println(fbdo.errorReason()); } }
The command that actually sends the flick is Firebase.Storage.upload():
Firebase.Storage.upload(&fbdo, STORAGE_BUCKET_ID, FILE_PHOTO, mem_storage_type_flash, FILE_PHOTO, "paradigm/jpeg")
This function returns a boolean variable indicating the success of the operation.
It accepts as the 2d argument, the storage saucepan ID. Then, the path where the file is saved; the storage blazon (information technology tin can be SPIFFS or SD Carte du jour*); the path where the file volition be saved in the Firebase storage; and finally, the mime blazon.
*we were not able to make this example work with the ESP32-CAM + microSD carte du jour. If anyone knows a solution, please share.
Sit-in
Afterward inserting the required credentials, upload the lawmaking to your ESP32-CAM. If you don't know how to upload code to the ESP32-CAM, y'all tin can follow the next tutorial(s):
- How to Program / Upload Code to ESP32-CAM AI-Thinker (Arduino IDE)
- Upload Code to ESP32-CAM AI-Thinker using ESP32-CAM-MB USB Programmer
Afterward uploading the code, open the Serial Monitor at a baud rate of 115200. Printing the ESP32-CAM on-board RST push button.
Information technology will endeavor to accept a picture and will send information technology to Firebase Storage.
Now, become to your Firebase panel, and select the Storage tab. There should exist a folder chosen data that contains your motion-picture show.
You can bank check some metadata about the picture and view it in total size. Yous tin too access the image by accessing the Download URL printed on the Serial Monitor.
Wrapping Up
In this tutorial, you learned how to create a Firebase project with Storage. Firebase Storage allows you to store files on the deject. Then, yous tin can access those files by going to the Firebase console, or yous tin build a spider web app to display those files (we'll exercise this in a future tutorial).
We've shown a simple example about sending a picture taken with the ESP32-CAM to the Firebase Storage. The case is as simple equally possible then that y'all can understand the basics. The idea is to modify the project to make something useful—similar taking a picture show and uploading information technology to Firebase storage when movement is detected, when a door opens or when you press a button.
Nosotros have other Firebase tutorials that you lot may like:
- ESP32: Getting Started with Firebase (Realtime Database)
- ESP32 with Firebase – Creating a Web App
- ESP32/ESP8266: Firebase Hallmark (Email and Password)
- ESP32/ESP8266 Firebase: Ship BME280 Sensor Readings to the Realtime Database
Learn more than nigh the ESP32-CAM with our resources:
- Build ESP32-CAM Projects (eBook)
- Read all our ESP32-CAM Projects, Tutorials and Guides
Larn how to create a Firebase Web App to control outputs and monitor sensors from anywhere:
- Firebase Web App with the ESP32 and ESP8266 eBook
We hope you found this tutorial useful.
Thanks for reading.
Source: https://randomnerdtutorials.com/esp32-cam-save-picture-firebase-storage/
0 Response to "Android Take Picture and Upload to Firebase"
Post a Comment