Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade

How to Control USB Devices on Raspberry Pi

Controlling USB devices is a critical aspect of many Raspberry Pi projects, allowing users to manage peripherals such as keyboards, mice, storage devices, and more. This article will guide you through the process of controlling USB devices using a Raspberry Pi, including how to detect connected devices, manage power, and interact with USB peripherals programmatically. Understanding how to control USB devices can enhance your ability to create more sophisticated and responsive projects.

Examples:

  1. Detecting Connected USB Devices: To list all connected USB devices, you can use the lsusb command. This command provides information about each USB device connected to your Raspberry Pi.

    lsusb

    Example Output:

    Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
    Bus 001 Device 002: ID 046d:c534 Logitech, Inc. Unifying Receiver
  2. Managing USB Power: You can control the power to USB ports using the uhubctl utility. First, install uhubctl:

    sudo apt-get update
    sudo apt-get install uhubctl

    To turn off power to a specific USB port:

    sudo uhubctl -l 1-1 -p 2 -a off

    To turn the power back on:

    sudo uhubctl -l 1-1 -p 2 -a on
  3. Interacting with USB Devices Programmatically: Python can be used to interact with USB devices. The pyusb library is a useful tool for this purpose. First, install pyusb:

    pip install pyusb

    Example Python script to list USB devices:

    import usb.core
    import usb.util
    
    # Find all devices
    devices = usb.core.find(find_all=True)
    
    # Loop through devices and print information
    for device in devices:
       print(f"ID: {device.idVendor}:{device.idProduct}")
       print(f"Manufacturer: {usb.util.get_string(device, device.iManufacturer)}")
       print(f"Product: {usb.util.get_string(device, device.iProduct)}")
       print("------")
  4. Automating USB Device Detection: You can create a udev rule to automate actions when a USB device is connected. Create a new udev rule file:

    sudo nano /etc/udev/rules.d/99-usb.rules

    Add the following content to trigger a script when a USB device is connected:

    ACTION=="add", SUBSYSTEM=="usb", RUN+="/path/to/your/script.sh"

    Example script.sh:

    #!/bin/bash
    echo "USB device connected" >> /home/pi/usb_log.txt

    Make the script executable:

    chmod +x /path/to/your/script.sh

    Reload udev rules:

    sudo udevadm control --reload-rules

To share Download PDF

Gostou do artigo? Deixe sua avaliação!
Sua opinião é muito importante para nós. Clique em um dos botões abaixo para nos dizer o que achou deste conteúdo.