This codelab 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 simple air quality monitoring system
Audience: Beginner developers with basic programming and hardware skills
Duration: ~2-3 hours
What You'll Teach
How to build an air quality monitor that triggers an air filtration system when detected values of particulate (PM2.5) exceeds a certain threshold
Watch the Video
See a demonstration of the air quality monitoring system in this video.
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.
Make sure you are using a 5V 5A (25W) power supply. USB boot is disabled by default when connected to a 3A power supply, so adequate amperage is required for the optimal performance of your Raspberry Pi 5.
1 - Store-bought or 3D-printed Raspberry Pi case (like this one here) that provides access to GPIO pins
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. Ensure participants have power outlets and internet access. Have spare supplies, such as Raspberry Pis, sensors, 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.
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 few box fans or use a different corded appliance such as a table lamp to demonstrate the effect.
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 PMS7003 particulate sensor measures the air quality and transmits data in a serial stream from the transmitter pin (TX) to the receiver pin (RX pin) on the Raspberry Pi.
Refer to the following wiring diagram to connect the Raspberry Pi to the PMS7003 air monitoring device.
Pin 4 (3V) to VCC (Power)
Pin 6 (GND) to GND (Ground)
Pin 8 (TX) to RX (receiver)
Pin 10 (RX) to TX (transmitter)
To power the Raspberry Pi, you can use the USB cord from earlier to continue providing power from your computer, or use a separate USB power supply.
How does the air sensor transmit data to your Raspberry Pi?
WiFiI2CSerialMQTT
Why are TX and RX pins crossed between the Raspberry Pi and the PMS7003 device in the wiring diagram?
To prevent power surgesTo enable proper communication between the Raspberry Pi and the deviceTo match the voltage levels of both devicesTo provide a common ground
Set up your air filter
Make your own air purifier by combining a box fan and air filter to effectively clean the air in a small to medium sized, closed room.
Attach the filter to the back of the fan, ensuring the airflow arrow points toward the fan. The fan should pull air through the filter when operating. If the filter will block access to the fan's power knob, now is a good time to switch it to an on position.
Secure the filter using 3D-printed clips or duct tape. Write the date when the filter is first used directly on the filter.
Set up your smart plug
Plug your Kasa smart plug into a power outlet.
Set up your smart plug and connect it to your local Wifi using the Kasa mobile app from the App Store or Google Play.
From the command line of your terminal app, install the python-kasa library, and enter the command kasa discover to locate the IP address of the connected device. Make a note of the IP address since we'll need it again soon.
Plug the box fan into the Kasa smart plug. Toggle the box fan power with the Kasa app to make sure it's working as expected.
Set up your Raspberry Pi
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 5.
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, air.
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.
Connect with SSH
Place the USB flash drive into 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
Enable communication protocols
Launch the Pi configuration tool by running the following command
sudo raspi-config
Use your keyboard to select "Interface Options", and press return.
Enable the relevant protocols to support our hardware. Since you are using a sensor that communicates over the serial port, enable Serial Port.
Confirm the options to enable the serial login shell and serial interface. And reboot the Pi when you're finished.
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 air sensor. Select the Linux / Aarch64 platform for the Raspberry Pi to control the air sensor, 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 air sensor.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 air quality monitoring 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 air quality data locally without connecting to the cloud.It directly powers the air sensor.
Add your Raspberry Pi
In the Viam app, find the CONFIGURE tab. It's time to configure your hardware.
Click the + icon in the left-hand menu and select Component.
Select board, and find the pi5 module. This adds the module for working with the Raspberry Pi 5'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.
Add your air sensor
In the Viam app, click the + icon and select Component. Select sensor, find the air:pms7003 module, and click Add module. This module provides the sensor model that supports the specific hardware we are using for this tutorial. Leave the default name sensor-1 for now.
Notice adding this module adds the sensor hardware component called sensor-1 as well as a module called pms7003 which contains the logic for how our Raspberry Pi and air sensor work with each other.
Save your updates.
How does adding modules like `board-1` or `pms7003` 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 air sensor.
Add your smart plug
In the Viam app, let's configure the rest of our hardware so that your machine can communicate with the smart plug over wifi. Click the + icon in the left-hand menu and select Component. Select generic, and find the kasa:switch module. This is a generic module that's been configured to use the python-kasa library. In other words, it's a layer of abstraction that lets us use the Kasa manufacturer's APIs with Viam.
Notice adding this module adds the generic hardware component called generic-1 as well as a module called kasasmartplug which contains the logic for how our Raspberry Pi and smart plug work with each other.
Under the CONFIGURE section of the generic-1 card, add your own smart plug's IP address that you found in a previous step, formatted like the following.
{
"plug_ip": "192.168.1.169"
}
Save your updates.
What is the advantage of using a generic module like `kasa:switch` to control a smart plug in this system?
It eliminates the need for custom configuration of the Raspberry Pi.It allows Viam to integrate with a variety of smart plug models using a single standardized interface.It provides direct power to the smart plug.It removes the need for an IP address for the smart plug.
Test the air sensor
In the Viam app under the CONTROL tab, you can see two hardware components called generic-1 and sensor-1. They are your smart plug and air sensor that you configured on the CONFIGURE tab.
Find the sensor-1 card, and expand the TEST accordion. The module we added has a GetReadings function to get the readings from our air sensor. Select Manual refresh, and then click the refresh icon to manually get the readings.
When you manually refresh the `GetReadings` function for the air sensor, what type of information is typically returned?
Electrical resistance of the sensor circuit.Current and voltage levels of the Raspberry Pi.Air quality readings such as particulate matter (PM2.5) concentrations.The IP address of the air sensor module.
Test the smart plug
Next, test that your smart plug is working properly. Make sure the fan is still plugged in to the powered smart plug. Also make sure the fan knob is set to on.
In the Viam app under the CONTROL tab, find the generic-1 card, and expand the DOCOMMAND accordion. The module we added has a few functions to control the smart plug. Under the Input section, add the following JSON object (if your fan is still running), and then click Execute to toggle off the smart plug.
{
"toggle_off": []
}
Now update "toggle_off" to "toggle_on" in the JSON object, and Execute once again.
What is the advantage of testing the smart plug’s `DoCommand` function during the setup process?
To confirm the Raspberry Pi can toggle power to the plug in response to sensor readings.To validate that the smart plug’s firmware is updated.To establish a direct network connection between the air sensor and the plug.To monitor how the smart plug processes particulate matter readings.
How does the Viam app simplify the process of testing and controlling hardware components like the air sensor and smart plug?
By storing all sensor data locally on the Raspberry Pi.By providing a unified interface to send commands and get feedback from hardware components in real-time.By running all processes directly on the air sensor.By automatically updating hardware firmware during testing.
Program your air monitoring device
At this point, you have configured and tested your machine and peripherals, but nothing is happening automatically. In the next section, program your air monitoring device to be a little smarter. Make your machine periodically get readings, turn on the air filter if the values are high, and turn off again when the values are low.
Create an automation script
To configure the machine to automatically run a command to execute a script, use a Viam process. Create a new file on your computer called process.py.On MacOS, Linux, or Windows WSL:
touch process.py
On Windows:
type nul > process.py
Copy and paste this sample code into the new file process.py. This code will allow your Raspberry Pi to connect to both our sensor and plug and execute our logic.
Now it's time to move your control code to your Raspberry Pi device. SSH into your Raspberry Pi if you're not already SSH'd.
From the SSH prompt on your Raspberry Pi, install the Python package manager.
$ sudo apt install -y python3-pip
Install the Viam Python SDK into a new directory called process.
$ pip3 install --target=process viam-sdk
Display the full path of the current directory you are working in on your Raspberry Pi with the pwd command. Make a note of this output for the next steps.
$ pwd
Find the executable path of Python3 to run process.py on your Raspberry Pi with which python3. Again, make a note of this output for the next steps.
$ which python3
Run the following command from your computer (not the SSH prompt to your Raspberry Pi) to copy the code from your computer to your Raspberry Pi. In the command, you will copy process.py over to your Raspberry Pi, with the section following the colon : indicating where your file should be copied to on the Raspberry Pi (the path of the directory you are working in on your Raspberry Pi, along with the filename).
What is the primary role of the `process.py` script in the air monitoring system?
To display air quality readings directly on the Raspberry Pi.To define the logic for periodically checking sensor readings and toggling the smart plug based on thresholds.To update the firmware of the air sensor and smart plug.To configure the network settings for the Raspberry Pi.
Configure a Viam process
Now let's allow viam-server to run the process as the root user on your Raspberry Pi by configuring a Viam process. In the Viam app under the CONFIGURE tab, click the + icon in the left-hand menu and select Process.
Find the corresponding card to process-1. Enter the executable path of Python3 running on your Raspberry Pi that you output from a previous step. Add an argument of the process.py file to run on your Raspberry Pi. Enter the working directory where you want the process to execute.
Still within the process-1 card, select the advanced settings icon near the top right corner to review the configuration JSON. Create a new env property, and add your environment variables within the new property, formatted like the following with your own credentials.
You can test the code by updating the process.py file on your Raspberry Pi to update the do_command when thresholds are low from toggle_off to toggle_on. Save your code changes, and Restart the machine to see if the fan turns on when the air quality is healthy.
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 air sensor is calibrated before each reading.It logs all air quality data directly to the Raspberry Pi’s storage.It enables real-time monitoring of air quality on a connected device.
Why is it necessary to configure a continuous process for the air monitoring system?
To ensure the system can automatically respond to changing air quality conditions without manual intervention.To allow the Raspberry Pi to store sensor data locally for future analysis.To reduce the power consumption of the air monitoring device.To manually refresh the sensor readings 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.
3D print (or buy) an enclosure for your Raspberry Pi and sensor. I found an existing design that I liked to fit a standard Raspberry Pi 5. Using a piece of heavy-duty velcro, I mounted the sensor on top to ensure the sensor could accurately measure the surrounding air.
You might prefer to have the Raspberry Pi and air sensor within the same case. If you're planning to design your own enclosure, make sure the air sensor receives adequate ventilation and isn't placed too close to the Raspberry Pi chip, as it can get a bit hot.
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.
The demo video provides a brief overview of the project.
Common pitfalls and troubleshooting guidance
Security
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. USB boot is disabled by default when connected to a 3A power supply, so adequate amperage is required for the optimal performance of your Raspberry Pi 5.
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>-air or <group-name>-air 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.
Locating IP address of smart plug
In a group setting, configure one smart plug at a time in order to avoid confusion and conflicts in identifying the proper IP addresses on the local area network.
If you have access to your router's admin page, you can also find your smart plug's IP address from a web browser. From a web browser, enter your router's IP address (commonly 192.168.1.1 or 192.168.0.1) and log in using your admin username and password. Look for a section like "Connected Devices," "Device List," or "DHCP Clients." Locate your Kasa smart plug by its name, MAC address (shown in the Kasa mobile app), or manufacturer name (usually TP-Link).
Configuring machine and peripherals
If any problems occur while setting up the machine and peripherals in the Viam app, check under the LOGS tab to see what might be going wrong.
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 sensor 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 air quality monitoring 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 sensors for tracking air quality in different rooms or outdoor spaces.
Discuss the feasibility of deploying a network of sensors for larger-scale monitoring (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
How does the air sensor transmit data to your Raspberry Pi?
Why is it necessary to cross TX and RX pins between the Raspberry Pi and the PMS7003 air sensor?
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 air quality monitoring setup?
How does adding modules like board-1 or pms7003 contribute to the overall architecture of your machine?
What is the advantage of using a generic module like kasa:switch to control a smart plug in this system?
How does the Viam app simplify the process of testing and controlling hardware components like the air sensor and smart plug?
Hands-on Experiment
When you manually refresh the GetReadings function for the air sensor, what type of information is typically returned?
What is the advantage of testing the smart plug's DoCommand function during the setup process?
What is the primary role of the process.py script in the air monitoring 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 air monitoring system?
Next-level projects
Here are some ideas for expanding and enhancing the current project.