0% found this document useful (0 votes)
5 views6 pages

Urban Rescue Rover Programming Guide

The Urban Rescue & Resource Rover Technical Programming Guide outlines the programming process for a rover project, divided into three parts: training a machine learning model for waste detection, deploying the model to an ESP32-S3 microcontroller, and setting up a Firebase Realtime Database for data logging. It includes detailed steps for using Google Colab to train a CNN model, convert it to TensorFlow Lite format, and integrate Firebase for real-time updates. The guide emphasizes the importance of data preparation, model evaluation, and obtaining necessary Firebase credentials for successful implementation.

Uploaded by

vishrawaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views6 pages

Urban Rescue Rover Programming Guide

The Urban Rescue & Resource Rover Technical Programming Guide outlines the programming process for a rover project, divided into three parts: training a machine learning model for waste detection, deploying the model to an ESP32-S3 microcontroller, and setting up a Firebase Realtime Database for data logging. It includes detailed steps for using Google Colab to train a CNN model, convert it to TensorFlow Lite format, and integrate Firebase for real-time updates. The guide emphasizes the importance of data preparation, model evaluation, and obtaining necessary Firebase credentials for successful implementation.

Uploaded by

vishrawaj
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Urban Rescue & Resource Rover:

Technical Programming Guide


This guide provides a step-by-step walkthrough for the initial programming phase of the Urban
Rescue & Resource Rover project. It is divided into three main sections:
1. Part A: Training a Machine Learning Model for the Waste Management Monitoring
application using TensorFlow and Google Colab.
2. Part B: Deploying the Model to the XIAO ESP32-S3 and integrating Firebase for real-
time data logging.
3. Part C: Setting up Firebase Realtime Database to receive data from your rover.

Part A: Training a TFLite Model for Waste Detection


For this phase, we will focus on the "Waste Management Monitoring" application. Our goal is to
train a simple image classification model that can distinguish between 'litter' and 'clear' scenes.
We'll use Google Colab for this, as it requires no local setup and provides free access to GPUs.

Step 1: Set Up Google Colab & Gather Data


1. Open Google Colab: Go to [Link] and create a new notebook.
2. Find a Dataset: For a proof-of-concept, a simple dataset is best. A great starting point is
the "SpotGarbage" dataset from Kaggle or by creating your own small dataset.
○ For this guide, let's assume you've created two folders on your Google Drive:
My Drive/rover_data/litter and My Drive/rover_data/clear.
○ Populate these folders with about 50-100 images each. The images should be
representative of what the rover's camera will see. Keep the images varied to build
a robust model. Include pictures taken from different angles, in different lighting
conditions (sunny, cloudy, indoors), and against various backgrounds (grass,
pavement, dirt). For the 'clear' folder, ensure you have many examples of clean
scenes that are similar to the littered ones.
3. Mount Google Drive in Colab: To access your images, you need to connect your
Google Drive. Add a code cell in your notebook and run:
from [Link] import drive
[Link]('/content/drive')

Step 2: Write the Python Code for Model Training


Here is the complete Python script for your Colab notebook. It will load your image data, build a
simple Convolutional Neural Network (CNN), train it, and convert it to the TensorFlow Lite
format required for the microcontroller.
Copy and paste this into separate cells in your notebook.
Cell 1: Imports and Path Setup
import tensorflow as tf
import os
import numpy as np
from [Link] import layers, models
from [Link] import ImageDataGenerator

# Define paths to your dataset in Google Drive


base_dir = '/content/drive/My Drive/rover_data'

Cell 2: Image Data Preparation The XIAO ESP32-S3 camera works well with smaller
resolutions. We'll resize images to 96x96 pixels.
IMAGE_SIZE = 96
BATCH_SIZE = 16

# Rescale images and prepare them for training


datagen = ImageDataGenerator(
rescale=1./255,
validation_split=0.2, # Use 20% of the data for validation
# These parameters perform data augmentation. The generator will
create modified
# versions of your images on-the-fly (e.g., slightly rotated,
shifted, or flipped).
# This makes your model more robust and helps prevent it from
simply memorizing
# the training images, leading to better real-world performance.
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True)

train_generator = datagen.flow_from_directory(
base_dir,
target_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE,
subset='training',
class_mode='categorical')

validation_generator = datagen.flow_from_directory(
base_dir,
target_size=(IMAGE_SIZE, IMAGE_SIZE),
batch_size=BATCH_SIZE,
subset='validation',
class_mode='categorical')

print(train_generator.class_indices) # Should output {'clear': 0,


'litter': 1} or similar

Cell 3: Build the CNN Model This is a simple, lightweight architecture suitable for a
microcontroller.
model = [Link]([
layers.Conv2D(16, (3, 3), activation='relu',
input_shape=(IMAGE_SIZE, IMAGE_SIZE, 3)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(32, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation='relu'),
layers.MaxPooling2D((2, 2)),
[Link](),
[Link](64, activation='relu'),
[Link](train_generator.num_classes, activation='softmax') #
Output layer
])

[Link](optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])

[Link]()

Cell 4: Train the Model


history = [Link](
train_generator,
steps_per_epoch=train_generator.samples // BATCH_SIZE,
validation_data=validation_generator,
validation_steps=validation_generator.samples // BATCH_SIZE,
epochs=15)

Cell 4a: Evaluate Model Performance After training, it's crucial to visualize how the model
performed. This helps you spot issues like overfitting (where the model does well on training
data but poorly on new data). Add a new cell and run this code:
import [Link] as plt

acc = [Link]['accuracy']
val_acc = [Link]['val_accuracy']
loss = [Link]['loss']
val_loss = [Link]['val_loss']

epochs_range = range(15)

[Link](figsize=(8, 8))
[Link](1, 2, 1)
[Link](epochs_range, acc, label='Training Accuracy')
[Link](epochs_range, val_acc, label='Validation Accuracy')
[Link](loc='lower right')
[Link]('Training and Validation Accuracy')
[Link](1, 2, 2)
[Link](epochs_range, loss, label='Training Loss')
[Link](epochs_range, val_loss, label='Validation Loss')
[Link](loc='upper right')
[Link]('Training and Validation Loss')
[Link]()

This new step empowers the user to diagnose their model and is a standard practice in machine
learning workflows.

Step 3: Convert to a TFLite C Array


This is the final, crucial step. We convert the trained model into a format the ESP32 can
understand.
Cell 5: Conversion and Export
# Convert the model to TensorFlow Lite format.
# This simpler conversion uses dynamic range quantization. It makes
the model
# smaller and faster, but without the lengthy calibration step.
converter = [Link].from_keras_model(model)
[Link] = [[Link]]

tflite_model = [Link]()

# Save the TFLite model file


with open('waste_model.tflite', 'wb') as f:
[Link](tflite_model)

# Now, convert the TFLite model to a C array for the Arduino project
!apt-get -qq install xxd
!xxd -i waste_model.tflite > waste_model.h

# Display the content of the C header file to copy it


!cat waste_model.h

Pro Tip: After this cell runs, you can find the waste_model.h file in the file browser on the left
side of the Colab interface. You can right-click on it and select "Download" to save the file
directly to your computer. This is often easier and more reliable than copy-pasting.
After running the final cell, you will get an output containing the C array. It will look something
like this. Note that the Colab output window may show a message like "Streaming output
truncated to the last 5000 lines," which is normal.
unsigned char waste_model_tflite[] = {
0x1c, 0x00, 0x00, 0x00, 0x54, 0x46, 0x4c, 0x33, 0x00, 0x00, 0x00,
0x00,
// ... many more lines of hex values ...
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00,
0x00, 0x00, 0x00, 0x03
};
unsigned int waste_model_tflite_len = 441536;

Copy this entire output. You will save it as a file named waste_model.h in your Arduino project
folder.

Part C: Setting up Firebase Realtime Database


This section will guide you through creating a Firebase project and getting the credentials you
need for the Arduino code.

Step 1: Create a Firebase Project


1. Go to the Firebase Console.
2. Click "Add project" and give your project a name (e.g., "Urban-Rover-Data").
3. Follow the on-screen steps. You can disable Google Analytics for this simple project if you
wish.

Step 2: Set up Realtime Database


1. Once your project is created, look for the Build section on the left menu.
2. Click on Realtime Database.
3. Click the "Create Database" button.
4. Choose a location for your database (any US location is fine).
5. Select "Start in test mode". This will allow your ESP32 to write data without complex
authentication.
○ Security Warning: Test mode leaves your database open for anyone to read and
write. This is okay for initial development but should be secured later for a real-
world application.
6. Click "Enable".

Step 3: Get Database Credentials


1. In the left menu, click the Project Overview gear icon and select Project settings.
2. Under the "General" tab, scroll down to the "Your apps" section.
3. Click on the Web icon (</>) to create a new Web App.
4. Give it a nickname (e.g., "Rover Web App") and click "Register app".
5. Firebase will show you a code snippet with your configuration. You only need two pieces
of information from this:
○ apiKey: This is your Web API Key.
○ databaseURL: This is your Database URL.
6. Copy these two values and paste them into the corresponding #define statements in your
Arduino .ino file.

Step 4: Final Look


After setting up, your Realtime Database will be empty. Once you run the Arduino code, you will
see a rover_status object appear. Inside it, a waste_detected key will have a value of either true
or false, which will update whenever the rover detects a change.

Common questions

Powered by AI

Using TensorFlow Lite on microcontrollers addresses challenges such as limited computational resources and memory. TensorFlow Lite models are lightweight and optimized for edge devices, allowing efficient processing of machine learning inferences on hardware with limited power and processing capabilities. In the Urban Rescue Rover project, after training the model in Google Colab, it's converted to TensorFlow Lite and then further processed into a C array that the microcontroller can use. This involves the conversion process with dynamic range quantization to make the model smaller and faster, ensuring it runs effectively on the XIAO ESP32-S3 microcontroller .

Converting a trained machine learning model into a format for the XIAO ESP32-S3 microcontroller involves several key steps. After training the model in Google Colab, it is first converted into TensorFlow Lite format, which is optimized for efficiency on edge devices. Using TensorFlow's TFLiteConverter, the model undergoes dynamic range quantization to reduce size while retaining performance. The converted TFLite model is then exported as a C array. This C array represents the trained model in a format that can be compiled and used directly in microcontroller projects, enabling the microcontroller to make inferences based on input data from sensors .

Data augmentation enhances the model's performance in waste detection applications by generating modified versions of the training images on-the-fly. This includes rotations, shifts, and flips of images, which helps to prevent the model from merely memorizing the training data. By exposing the model to a variety of image representations, data augmentation increases the model's robustness and improves its ability to generalize to new, unseen data. This is particularly important for real-world applications where the conditions (e.g., lighting, angles) can significantly vary from the training conditions .

The training and validation performance of the machine learning model for waste detection is evaluated by plotting the accuracy and loss over each epoch. This involves using matplotlib in Google Colab to visualize the training and validation accuracy and loss, helping in identifying issues like overfitting. Assessing these plots allows users to understand how well the model is learning the training data and how it generalizes to validation data. Such visualization is a standard practice, allowing developers to tune parameters and improve model performance through iterative refinement .

Running a Firebase Realtime Database in test mode during development allows open access to read and write data, facilitating unimpeded testing without authentication barriers. However, this open access presents security risks in a real-world scenario, as unauthorized users could potentially access and modify data. It is important to plan for security measures once the initial testing phase is completed, such as implementing authentication and access rules to ensure only authorized devices or users can access the database. Transitioning to a production mode with stricter access controls is essential to protect sensitive data and maintain the integrity of the application .

The initial setup of Google Drive and image datasets is crucial for the success of machine learning projects like the Urban Rescue Rover as it establishes a solid foundation for data management and accessibility. Organizing the dataset into structured folders (e.g., 'litter' and 'clear') in Google Drive ensures efficient access and ease of use in Google Colab. This structured approach allows seamless integration with the coding environment for data preprocessing and training. Additionally, using diverse and representative images helps build a robust model capable of generalizing across different real-world scenarios, thereby improving the model's performance and reliability .

The key steps in training a machine learning model for waste management monitoring using Google Colab include setting up Google Colab and gathering data, writing the Python code for model training, and converting the trained model to TensorFlow Lite format for use on a microcontroller. Initially, a dataset is gathered and organized into folders representing different classes ('litter' and 'clear') in Google Drive. The Google Drive is mounted in Colab, and a Convolutional Neural Network (CNN) is built using TensorFlow to perform classification. The training includes data preparation involving image resizing and augmentation for robustness. After the model is trained, it is converted into a TFLite model using TensorFlow's conversion tools to be compatible with devices like the XIAO ESP32-S3 .

Key considerations for setting up a Firebase Realtime Database for use with Arduino-based rovers include creating a Firebase project, selecting an appropriate location for the database, and starting in test mode to simplify initial development. Test mode allows unrestricted read and write access, which is suitable for development but needs to be secured for production use. Additionally, obtaining database credentials like the Web API Key and Database URL is crucial for setting up the Arduino project's code for data logging. Ensuring secure configurations and planning for security changes at later stages are critical to prevent unauthorized access .

The Arduino code serves as a crucial intermediary that enables real-time communication between the rover and Firebase Realtime Database for garbage detection applications. By incorporating Firebase database credentials such as the Web API Key and Database URL obtained during the database setup, the code allows the rover to log data on waste detection events. This setup enables the rover to update the database with a status object, indicating whether waste is detected. This real-time data logging capability facilitates instantaneous updates and monitoring, essential for responsive waste management applications .

Google Colab facilitates the process of training machine learning models by providing a cloud-based platform that requires no local setup, thus making it accessible and straightforward to use. With Colab, users can access powerful GPUs, which are crucial for training deep learning models efficiently. It allows integration with Google Drive to store datasets, enabling seamless data management and sharing. The platform supports Python and TensorFlow, essential for building, training, and converting models into formats suitable for deployment on microcontrollers, as seen in the Urban Rescue Rover project. These features make Colab a versatile and powerful tool for machine learning workflows .

You might also like