Traffic Light SDK Usage Guide

This chapter will detail how to use the tl.py module in Traffic Light SDK to control traffic lights on a Raspberry Pi.

Running Environment

The Traffic Light SDK is designed to run on a Raspberry Pi with the following specifications:

  • Operating System: Raspbian (or any other compatible Raspberry Pi OS)

  • Python Version: Python 3.7 or higher

  • Hardware Requirements: - Raspberry Pi board (tested on Raspberry Pi 4) - GPIO pins connected to traffic light hardware

Ensure your Raspberry Pi is properly set up with an operating system and Python environment before proceeding.

Install Dependencies

Ensure you have installed the necessary Python libraries. You can install them via pip:

pip install RPi.GPIO

Initialization and Configuration

First, import the TrafficLight class and create an instance:

from tl import TrafficLight

traffic_light = TrafficLight()

This will set up GPIO pins but will not initialize them immediately. You need to manually call the setup_gpio() method to complete the initialization:

if traffic_light.setup_gpio():
    print("GPIO setup completed.")
else:
    print("Failed to setup GPIO.")

Usage Example with Command Line Interface (CLI)

The demo.py script demonstrates how to control traffic lights using the tl.py module via a command line interface (CLI). Below is a detailed explanation of the script and how to use it.

Script Overview

The demo.py script provides several command-line options to control the traffic lights. It uses the argparse module to parse command-line arguments and calls corresponding methods on the TrafficLight object.

Available Commands:

  • Turn on red light:

    python demo.py --red_on
    
  • Turn off red light:

    python demo.py --red_off
    
  • Turn on green light:

    python demo.py --green_on
    
  • Turn off green light:

    python demo.py --green_off
    
  • Turn on both red and green lights:

    python demo.py --all_on
    
  • Turn off both red and green lights:

    python demo.py --all_off
    
  • Turn on red light only:

    python demo.py --red_on_only
    
  • Turn on green light only:

    python demo.py --green_on_only
    

Running the Script

To run the script, simply execute it from the command line with the desired option. For example, to turn on the red light:

python demo.py --red_on

If no command-line arguments are provided, the script will print help information:

python demo.py

This will display all available options and their descriptions.

Contents