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

Camera Module

BUY

Fusion HAT+

-

Raspberry Pi

-


Experimental Procedures

  1. 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.

    ../_images/gimbal_assemble.png
  2. Access the Raspberry Pi Desktop:

  3. Open a Terminal and go to the code folder:

    cd ~/ai-lab-kit/python
    
  4. Run the script to start the camera:

    sudo python3 3.1_Photograph.py
    
  5. After the script starts, press the Fusion HAT+ USR button to take photos.

    ../_images/3.1_user_button1.png
    • Each press captures a picture.

    • Photos are saved in ~/user/Pictures as my_photo.jpg.

    • Press Ctrl+C to stop the script.

    ../_images/3.1_take_photo.jpg

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

  1. Imports and Purpose

    import os, time, pwd
    from picamera2 import Picamera2, Preview
    from fusion_hat.user_button import UserButton
    

    These modules provide:

    • os and pwd: used to correctly locate the real user’s home directory, even when the program is run with sudo.

    • time: keeps the program running in a loop.

    • Picamera2 and Preview: control the Raspberry Pi camera and preview modes.

    • UserButton: reads the Fusion HAT+ USR button.

  2. 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_USER is used to find the original user’s home directory.

    • Otherwise, the current user’s home directory is used.

    • A Pictures folder is created if it does not already exist.

    • All photos are saved as my_photo.jpg (each new photo overwrites the last).

  3. 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.

  4. 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.

  5. USR Button Binding

    UserButton().set_on_click(shot)
    

    The Fusion HAT+ USR button is linked to the shot function. Each button press triggers a photo capture.

  6. 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.

  7. 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.

  8. 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+C is 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

  1. 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.

  2. 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.

  3. Photos Saved to Wrong Location

    • Cause: Running with sudo may confuse home directories.

    • Fix: Script already handles this; print REAL_USER or PICTURES_DIR if unsure.

  4. 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.