Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
3.1 Photograph Module
Introduction
This project introduces you to using the Raspberry Pi camera module to capture a photograph. The camera module can take high-quality still images and videos, making it a versatile tool for projects ranging from photography to computer vision.
What You’ll Need
Below are the components required for this project:
COMPONENT INTRODUCTION |
PURCHASE LINK |
|---|---|
- |
|
Raspberry Pi |
- |
Experimental Procedures
To use camera module conveniently, Assemble the Pan-tilt (For Camera) is recommended.
Note
Assembling the pan-tilt may obscure some pins, so it is recommended to assemble it only when using the camera, or place it on the outside after assembly.
Access the Raspberry Pi Desktop:
Remote Desktop: Use VNC for a full desktop experience.
Raspberry Pi Connect: Use Raspberry Pi Connect to access your Pi securely from any browser.
Open a Terminal and go to the code folder:
cd ~/ai-lab-kit/python
Run the script to start the camera:
sudo python3 3.1_Photograph.py
After the script starts, press the Fusion HAT+ USR button to take photos.
Each press captures a picture.
Photos are saved in
~/user/Picturesasmy_photo.jpg.Press
Ctrl+Cto stop the script.
Note
QT preview requires a desktop environment. If the preview cannot be started (for example, over SSH), the camera can still capture and save photos normally.
Code
Below is the Python code used for this project:
#!/usr/bin/env python3
import os, time, pwd
from picamera2 import Picamera2, Preview
from fusion_hat.user_button import UserButton
u = os.getenv("SUDO_USER")
home = pwd.getpwnam(u).pw_dir if u else os.path.expanduser("~")
os.makedirs(f"{home}/Pictures", exist_ok=True)
photo = f"{home}/Pictures/my_photo.jpg"
camera = Picamera2()
camera.configure(camera.create_preview_configuration())
def shot():
camera.capture_file(photo)
print(f"Saved: {photo}")
UserButton().set_on_click(shot)
# Start preview only when a GUI display is available
preview_started = False
if os.getenv("DISPLAY"):
try:
camera.start_preview(Preview.QT)
preview_started = True
except Exception as e:
print(f"Preview disabled: {e}")
camera.start()
print("Press USR to take photo. Ctrl+C to exit.")
try:
while True: time.sleep(0.1)
except KeyboardInterrupt:
pass
finally:
try: camera.stop()
except: pass
if preview_started:
try: camera.stop_preview()
except: pass
try: camera.close()
except: pass
Understanding the Code
Imports and Purpose
import os, time, pwd from picamera2 import Picamera2, Preview from fusion_hat.user_button import UserButton
These modules provide:
osandpwd: used to correctly locate the real user’s home directory, even when the program is run withsudo.time: keeps the program running in a loop.Picamera2andPreview: control the Raspberry Pi camera and preview modes.UserButton: reads the Fusion HAT+ USR button.
Resolving the Save Path
u = os.getenv("SUDO_USER") home = pwd.getpwnam(u).pw_dir if u else os.path.expanduser("~") os.makedirs(f"{home}/Pictures", exist_ok=True) photo = f"{home}/Pictures/my_photo.jpg"
This section determines where photos are saved:
If the script is run with
sudo,SUDO_USERis used to find the original user’s home directory.Otherwise, the current user’s home directory is used.
A
Picturesfolder is created if it does not already exist.All photos are saved as
my_photo.jpg(each new photo overwrites the last).
Camera Initialization
camera = Picamera2() camera.configure(camera.create_preview_configuration())
The camera object is created and configured with a default preview setup. This configuration works both with and without a visible preview window.
Photo Capture Function
def shot(): camera.capture_file(photo) print(f"Saved: {photo}")
This function is called whenever the USR button is pressed. It captures a photo and saves it to the predefined path, then prints the save location.
USR Button Binding
UserButton().set_on_click(shot)
The Fusion HAT+ USR button is linked to the
shotfunction. Each button press triggers a photo capture.Conditional Preview Start
preview_started = False if os.getenv("DISPLAY"): try: camera.start_preview(Preview.QT) preview_started = True except Exception as e: print(f"Preview disabled: {e}")
The program checks whether a graphical display is available.
If a display exists, it attempts to start a QT preview window.
If no display is available (for example, when running over SSH), the preview is skipped without stopping the program.
Camera Start and Main Loop
camera.start() print("Press USR to take photo. Ctrl+C to exit.") try: while True: time.sleep(0.1)
The camera is started, and the program enters an infinite loop to keep running and listening for button presses.
Clean Exit and Resource Cleanup
except KeyboardInterrupt: pass finally: try: camera.stop() except: pass if preview_started: try: camera.stop_preview() except: pass try: camera.close() except: pass
When
Ctrl+Cis pressed:The camera is stopped.
The preview is stopped only if it was successfully started.
The camera resources are released cleanly.
This ensures the program exits without error messages, regardless of whether a preview window was used.
Troubleshooting
No Preview Window
Cause: Camera not enabled, missing display, or Picamera2 not installed.
Fix: Run on a system with a display (not pure SSH), and test Picamera2 with a simple script.
USR Button Not Working
Cause: Fusion HAT+ not seated correctly, button not detected, or wrong photo folder checked.
Fix: Reconnect HAT, run script with
sudo, and check photos under~/Pictures.
Photos Saved to Wrong Location
Cause: Running with
sudomay confuse home directories.Fix: Script already handles this; print
REAL_USERorPICTURES_DIRif unsure.
Preview Freezes
Cause: Camera in use by another app or low system resources.
Fix: Close other apps, update the system, or reboot the Pi.
Conclusion
This script lets you capture photos using the Fusion HAT+ USR button and save them automatically to ~/Pictures.
The setup is ideal for simple camera projects and can be extended for timelapses, DIY camera builds, or classroom demos.