This codelab is part of the Viam for educators program, and provides a suggested delivery plan and resources for instructors interested in delivering a hands-on workshop. Take these resources, and make it your own!
Workshop Overview
Goal: Introduce sensors and actuators as concepts and build a people detection alert
Audience: Beginner developers with basic programming and hardware skills
Duration: ~2-3 hours
What You'll Teach
How to build an alert system with Computer Vision that triggers a buzzer when a person is detected
Review the list of required components (hardware, software), and determine which materials are provided or required for participants to bring on their own. Provide instructions to participants, giving them ample time to prepare and complete prerequisites.
How to set up a continuously running process on a Viam machine
How to use environment variables with your Viam machine
How to move control code to your machine
Agenda
Review the suggested agenda, and adjust it according to your goals and audience.
Introduction (10 mins)
Hardware Assembly (30 mins)
Software Setup (30 mins)
Hands-On Experiment (40 mins)
Q&A/Wrap-Up (10 mins)
Pre-workshop checklist ✅
Review these setup steps as you're planning the workshop to help prepare for it.
Planning and Logistics
Verify equipment inventory: Decide which materials are provided or required for participants to bring on their own. Order any materials and supplies that are provided to participants.
Confirm workstation setup: Verify the workshop room layout supports hardware work, such as tables for wiring the components. Ensure participants have power outlets and internet access. Have spare supplies, such as Raspberry Pis, adapters/readers, and cables, in case of failures. For virtual workshops, confirm logistics for breakout sessions, providing support, and checkpoints.
Communicate prerequisites: Share a participant guide prior to the workshop with learning objectives and instructions for installing software and preparing laptops. Provide a checklist for participants to confirm readiness.
Establish support channels: Determine how participants can get support for real-time troubleshooting (e.g. Slack or Discord channel for virtual workshops, additional helpers in the room for on-site workshops).
Prepare workshop teaching materials: Review the Delivery Plan, sample slide deck, and provided resources. Tailor these materials to suit your participants' needs. Decide whether to present them to the group or provide them for independent reference, such as through a web browser or printed handouts.
Determine extensibility: During the Hands-on Experiment portion of the delivery plan, there are many options to guide the workshop on a different learning path. Determine if this section will be self-guided exploration, a group exercise, or self-paced learning for participants to explore on their own after the workshop.
Prepare code and documentation: Review the provided code and add comments as necessary.
Review discussion topics: Review the suggested group discussion topics and adjust for your participants.
Review quiz questions: Review the suggested quiz questions and adjust for your participants. Determine if knowledge assessment will be completed throughout the workshop or afterwards.
Dry Run and Testing
Test the workshop project: Run through the build following the prepared documentation to ensure it works as expected. Simulate common issues and prepare troubleshooting tips for these scenarios. If physical space is limited, consider sharing a Raspberry Pi.
Bring backups: Final check to bring the backup supplies mentioned earlier during planning.
During the workshop, instructors can present this customizable slide deck (see above) tailored to your specific workshop needs. Alternatively, learners can follow step-by-step instructions and checkpoints independently by referencing the pages linked below in a web browser.
The Raspberry Pi boots from a USB flash drive (or microSD card). You need to install Raspberry Pi OS on a USB flash drive that you will use with your Pi. For more details about alternative methods of setting up your Raspberry Pi, refer to the Viam docs.
Install Raspberry Pi OS
Connect the USB flash drive (or microSD card) to your computer.
Click CHOOSE DEVICE. Select your model of Pi, which is Raspberry Pi 4.
Click CHOOSE OS. Select Raspberry Pi OS (64-bit) from the menu.
Click CHOOSE STORAGE. From the list of devices, select the USB flash drive you intend to use in your Raspberry Pi.
Configure your Raspberry Pi for remote access. Click Next. When prompted to apply OS customization settings, select EDIT SETTINGS.
Check Set hostname and enter the name you would like to access the Pi by in that field, for example test shown here. Each Pi should have a unique hostname to avoid conflicts on the shared local network, such as <student-name>-detection or <group-name>-detection if working in groups.
Select the checkbox for Set username and password and set a username (for example, your first name) that you will use to log into the Pi. If you skip this step, the default username will be pi (not recommended for security reasons). And specify a password.
Connect your Pi to Wi-Fi so that you can run viam-server wirelessly. Check Configure wireless LAN and enter your wireless network credentials. SSID (short for Service Set Identifier) is your Wi-Fi network name, and password is the network password. Change the section Wireless LAN country to where your router is currently being operated.
Select the SERVICES tab, check Enable SSH, and select Use password authentication.
Save your updates, and confirm YES to apply OS customization settings. Confirm YES to erase data on the USB flash drive. You may also be prompted by your operating system to enter an administrator password. After granting permissions to the Imager, it will begin writing and then verifying the Linux installation to the USB flash drive.
Remove the USB flash drive from your computer when the installation is complete.
What is the purpose of setting a custom `hostname` during the Raspberry Pi OS configuration?
To improve the speed of the Raspberry Pi.To identify and access the Pi on the network.To secure the Pi by changing the default password.To enable remote access to the Pi.
Connect with SSH
Place the USB flash drive into a USB port on your Raspberry Pi and boot the Pi by plugging it in to an outlet. A red LED will turn on to indicate that the Pi is connected to power.
Once the Pi is started, connect to it with SSH. From a command line terminal window, enter the following command. The text in <> should be replaced (including the < and > symbols themselves) with the user and hostname you configured when you set up your Pi.
ssh <USERNAME>@<HOSTNAME>.local
If you are prompted "Are you sure you want to continue connecting?", type "yes" and hit enter. Then, enter the password for your username. You should be greeted by a login message and a command prompt.
Update your Raspberry Pi to ensure all the latest packages are installed
sudo apt update
sudo apt upgrade
Set up your machine peripherals
Connect the webcam: Connect the webcam's USB lead to any USB port on your Pi. The webcam transmits video data to the Raspberry Pi through the USB interface.
Connect the piezo buzzer: The passive piezo buzzer can be controlled via a GPIO pin on the Raspberry Pi. Refer to the following wiring diagram to connect the Raspberry Pi to the piezo buzzer.
Pin 35 (GPIO 19) to Positive
Pin 39 (GND) to Negative
Now that we have physically connected our hardware components, let's configure the software in the next section.
Configure your machine
In the Viam app under the LOCATIONS tab, create a machine by typing in a name and clicking Add machine.
Click View setup instructions.
Install viam-server on the Raspberry Pi device that you want to use to communicate with and control your camera and piezo buzzer. Select the Linux / Aarch64 platform for the Raspberry Pi, and leave your installation method as viam-agent.
Use the viam-agent to download and install viam-server on your Raspberry Pi. Follow the instructions to run the command provided in the setup instructions from the SSH prompt of your Raspberry Pi.
The setup page will indicate when the machine is successfully connected.
Why is it important to connect your machine to the Viam app during setup?
To remotely monitor, configure, and control hardware components through the cloud.To store sensor data directly on the camera.To eliminate the need for a physical Raspberry Pi.To ensure the machine only works offline.
What is the primary role of `viam-server` in the system architecture of your people detector setup?
It acts as the operating system for the Raspberry Pi.It provides a layer for managing hardware components and enables remote communication via the Viam app.It processes camera data locally without connecting to the cloud.It directly powers the camera.
Configure your Raspberry Pi board
To access the GPIO pins, let's add our Raspberry Pi board to our machine in the Viam app.
Click the + icon in the left-hand menu and select Component.
Select board, and find the raspberry-pi:rpi4 module. This adds the module for working with the Raspberry Pi 4's GPIO pins. Leave the default name board-1 for now.
Notice adding this module adds the board hardware component called board-1. The collapsible card on the right corresponds to the part listed in the left sidebar.
Click Save in the top right to save and apply your configuration changes.
Configure your USB webcam
Make sure your webcam is already connected to the Pi.
In the Viam app under the CONFIGURE tab, click the + icon in the left-hand menu and select Component.
Select camera, and find the webcam module. This adds the module for working with a USB webcam. Leave the default name camera-1 for now.
Notice adding this component adds the webcam hardware component called camera-1. From the Attributes section of the panel, select a video_path.
Click Save in the top right. This may take a moment to apply your configuration changes.
At the bottom of the camera-1 panel, expand the TEST section to ensure you have configured the camera properly and see a video feed.
How does adding modules like `board-1` or `camera-1` contribute to the overall architecture of your machine?
They abstract hardware-specific details, allowing software to interact with components through a consistent API.They provide direct power and connectivity to the components.They eliminate the need for the Raspberry Pi in the system.They store the configuration locally on the camera.
Configure your ML model service
In the Viam app under the CONFIGURE tab, click the + icon in the left-hand menu and select Service.
Select ML model, and find the TFLite CPU module. This adds support for running TensorFlow Lite models on resource-contrained devices. Name the service people.
In the new ML Model service panel, configure the service by by setting the Deployment field to Deploy model on machine.
In the Model field, select the EfficientDet-COCO by viam-labs model under the Registry tab. This model is specifically optimized for resource-constrained devices like the Raspberry Pi.
Your ML model configuration should now look like this:
Click Save to apply your configuration changes.
Configure your vision service
In the Viam app, navigate to the CONFIGURE tab. Click the + icon in the left-hand menu and select Service.
Select vision, then find and choose the ML model module. This adds a new vision service to your machine. Name the service peopleDetector.
In the new vision service panel, configure the service by selecting people in the ML model field. This links your vision service to the ML model service you set up in the previous step.
Click Save to apply your configuration changes. Note that this may take a moment to complete.
At the bottom of the peopleDetector panel, expand the TEST section to verify your configuration. You should see bounding boxes and labels around detected objects.
To control the sensitivity of object detection, adjust the Minimum confidence threshold under the Attributes field.
What is the primary relationship between the ML Model Service and the Vision Service in this configuration?
The ML Model Service uses the Vision Service to perform object detection and image analysis.The Vision Service uses the ML Model Service to analyze visual data, leveraging pre-trained machine learning models.Both services operate independently and do not interact in the configuration process.The Vision Service is a prerequisite for configuring the ML Model Service.
Configure your piezo buzzer
You can manually and programmatically use the GPIO pins of the board component to send PWM signals to control your buzzer. However, to streamline this next step, let's use a prebuilt module.
In the Viam app under the CONFIGURE tab, click the + icon in the left-hand menu and select Component.
Select generic, and find the buzzer:piezo module. This adds the module for controlling your buzzer. Name the component piezo.
In the new piezo panel, configure your component by adding the following attributes in the CONFIGURE field. This tells your piezo component to use a specific pin (physical pin 35) on a specific board (called board-1 in the Viam app) that you wired in a previous step.
{
"piezo_pin": "35",
"board": "board-1"
}
Select your board board-1 from the Depends on field.
Click Save to apply your configuration changes. This may take a moment.
Since we are using a generic component, let's test it out under the CONTROL tab. Find your piezo component on this page. Expand the DO COMMAND field, input the following code, and hit Execute.
You are executing a DoCommand on a generic component that has been predefined to accept parameters such as frequency, duration, and duty_cycle.
Experiment with different values in those fields to see what happens when you execute the command again. If you have extra time, try sending the following Do command.
{
"play_harry_potter": {}
}
What is the primary purpose for using PWM (Pulse Width Modulation) to control a passive piezo buzzer?
To provide a constant high voltage to the buzzer.To generate varying tones by controlling the frequency of the signal.To make sure the buzzer operates at a fixed tone without additional wiring.To power the buzzer directly from a USB port.
Program your people detector
At this point, the Vision Service relies on the ML Model Service to analyze visual data. It uses pre-trained machine learning models, such as EfficientDet-COCO, to perform tasks like object detection. Currently, many objects are being detected in the camera feed.
In this section, we'll write code to alert us when a person is detected. And if a person is detected, the piezo buzzer will sound.
Create an automation script
To configure your machine to automatically run a command that executes a script, use a Viam process. Start by creating a new file called process.py on your computer. On MacOS, Linux, or Windows WSL:
touch process.py
On Windows:
type nul > process.py
Copy and paste this sample code into the newly created process.py file. This code connects your Raspberry Pi to the Vision Service and piezo component to execute the automation logic.
Transfer the process.py file to your Raspberry Pi. First, SSH into your Raspberry Pi if you aren't already connected.
On your Raspberry Pi, install the Python package manager (pip) using the following command:
$ sudo apt install -y python3-pip
Install the Viam Python SDK into a new directory called detector.
$ pip3 install --target=detector viam-sdk
Display the full path of your current directory on your Raspberry Pi using the pwd command. Take note of the output, as you'll need it in the next steps. The output should include the path to the newly created detector/ directory:
$ pwd
Find the executable path for Python3 on your Raspberry Pi using the which python3 command. Note this output as well, as it will be required for running process.py.
$ which python3
Copy the process.py file from your computer to your Raspberry Pi using the scp command. Replace user and host.local with your Raspberry Pi's username and hostanme (or IP address). The part after the colon (:) specifies where the file should be copied on the Raspberry Pi, including the detector/ directory. Make sure you run the command from your computer (not the SSH prompt for your Raspberry Pi).
What is the primary role of the `process.py` script in the people detection system?
To collect camera data from the Raspberry Pi.To define the logic for periodically checking the camera data and turning on the piezo based on detections.To update the firmware of the camera and piezo.To configure the network settings for the Raspberry Pi.
Configure a Viam process
Now let's configure viam-server to run the process as the root user on your Raspberry Pi by setting up a Viam process.
In the Viam app, go to the CONFIGURE tab. Click the + icon in the left-hand menu and select Process.
Find the card for process-1. Enter the following:
The executable path for Python3 on your Raspberry Pi (from a previous step).
The process.py file as an argument.
The working directory where the process should execute (from a previous step).
In the process-1 card, click the advanced settings icon near the top right corner to review the configuration JSON. Add an env property to define your environment variables. Use the following format, replacing the placeholders with your own values.
Update the piezo parameters or use the Harry Potter theme song instead of a single note by modifying this section of the code.
After making your changes:
Save your code changes.
Restart the machine to apply the updates.
nano process.py
Why is the `process-1` configuration in the Viam app important for running the continuous process?
It specifies the environment variables and paths required for the Raspberry Pi to execute the process automatically.It ensures the camera is calibrated before collecting video data.It logs all camera data directly to the Raspberry Pi’s storage.It enables real-time monitoring of peripherals connected to the Pi.
Why is it necessary to configure a continuous process for the alerting system?
To ensure the system can automatically respond to a person detected without manually triggering the piezo.To allow the Raspberry Pi to store camera data locally for future analysis.To reduce the power consumption of the alerting system.To manually refresh the video data at regular intervals.
Finishing touches
Now that your system is working the way you want it, it's time to tidy up our project so it's not a loose jumble of wires and parts.
Assemble the enclosure: 3D print (or buy) an enclosure for your Raspberry Pi. I found an existing design that I liked to fit a Raspberry Pi 4 Model B that provides access to the GPIO pins. You can modify an existing design to include notches for your piezo buzzer and webcam.
Detector placement: Set this up near a place you want to monitor. For example, if you want to sound the buzzer when someone is near your desk, point the camera in a direction that will capture your approach.
Train a custom ML model: Instead of actuating the piezo when any person is detected, train your own ML model to detect when a specific person or pet is detected. You could extend this logic to trigger actuation if a person is detected but not one that is known.
Update the actuation: Instead of actuating the piezo when an object is detected, integrate a service to send a notification, generate an insult, or turn on a smart light.
Additional resources
The website pinout.xyz is a helpful resource with the exact layout and role of each pin for Raspberry Pi. When working with Viam, make sure to reference the physical pin numbers, and not the GPIO numbers listed on pinout.xyz.
Do not share your API credentials publicly. Sharing this information could compromise your system security by allowing unauthorized access to your machine, or to the computer running your machine.
Flashing firmware
Make sure you are using a 5V 5A (25W) power supply for the Raspberry Pi.
Participants must remember the hostname and username they set while flashing their Raspberry Pi, as they will need this when they SSH into the Pi.
To save time, instructors can flash all the Pis ahead of time with pre-determined credentials and share the credentials with participants during the workshop. Each Pi should have a unique hostname to avoid conflicts on the shared local network, such as <student-name>-detection or <group-name>-detection if they are working in groups.
If you're using SD cards, verify that you have a way to write data onto them before providing them to participants.
Working with actuators
Disabling a resource: In a group setting, working with piezos can be fun, but also potentially disruptive. Learners can disable the resource by toggling off process-1, for example.
Alternative actuators: A buzzer is just one type of actuator, but the possibilities are endless.
Use an RGB LED, which functions similarly as a PWM-actuated component
Participants have several options for continuing their projects beyond the workshop environment:
Take-home projects: For participants allowed to take their projects home after the workshop, the viam-agent on the Raspberry Pi can simplify the setup process:
Provisioning mode: Upon rebooting the Raspberry Pi in a new environment like at home, the viam-agent automatically creates a Wi-Fi hotspot if it cannot connect to a known network.
Connect to the hotspot: Look for a network named viam-setup-HOSTNAME in your list of available Wi-Fi networks, where HOSTNAME is the custom hostname you set during the workshop, and viamsetup is the default password. Connect your laptop to this network.
Provide network information for the machine: Go to the provisioning portal at http://viam.setup/ in a browser to follow the on-screen instructions to configure the Raspberry Pi for your home Wi-Fi.
Remote control: If participants are not allowed to take their projects home after the workshop, but want to continue working on their projects from home, they can access the Raspberry Pi remotely from anywhere in the world and continue accessing camera data. If participants do not have SSH access into the Raspberry Pi, participants can write and run code on their laptops from home.
Group discussion topics 🗣️
Review suggested topics for discussion at key points during the workshop.
What were the biggest challenges participants faced during the workshop (e.g., wiring, coding, debugging)?
Share troubleshooting experiences and how participants resolved issues.
How can object detection be used in homes, schools, or offices?
What additional features could improve the system (e.g., alerts, cloud integration, mobile app)?
Discuss how to add multiple cameras can work together while detecting objects in different rooms or in outdoor spaces.
Discuss the feasibility of deploying a network of cameras for larger-scale surveillance (e.g., a citywide project).
Quiz questions ❓
Review the suggested quiz questions below to evaluate participants' understanding of key concepts. These questions can be used to assess knowledge either during (see multiple choice answers in the delivery plan) or after the workshop.
Hardware Assembly
What is the purpose of setting a custom hostname during the Raspberry Pi OS configuration?
What is the primary purpose for using PWM (Pulse Width Modulation) to control a passive piezo buzzer?
Software Setup
Why is it important to connect your machine to the Viam app during setup?
What is the primary role of viam-server in the system architecture of your people detector setup?
How does adding modules like board-1 or camera-1 contribute to the overall architecture of your machine?
What is the primary relationship between the ML Model Service and the Vision Service in our configuration?
What is the advantage of using a generic module like buzzer:piezo to control the piezo buzzer in this system?
How does the Viam app simplify the process of testing and controlling hardware components like the webcam and piezo buzzer?
Hands-on Experiment
What is the advantage of testing the piezo buzzer's DoCommand function during the setup process?
What is the primary role of the process.py script in the people detection system?
Why is the process-1 configuration in the Viam app important for running the continuous process?
Why is it necessary to configure a continuous process for the alerting system?
Next-level projects
Here are some ideas for expanding and enhancing the current project.