Writing a bash script to turn on and off the USB ports on a raspberry pi 4. Using uhubctl.
#!/bin/bash
# Script to turn on and off power to usb port
# Uses uhubctl
#
time_w=5
#cd uhubctl
uhubctl -a off -l 1-1
#
sleep "$time_w"
#
uhubctl -a on -l 1-1
#
echo "All done"
I can run this sudo uhubctl -a off -l 1-1
from the command line without issue.
But if I run the script with sudo bash USB_Power.sh
I get the following error.
!o compatible smart hubs detected at location 1-1
Run with -h to get usage info.
All done
2 Answers 2
uhubctl author here.
To configure udev USB permissions, simply follow uhubctl README.
In particular, for Raspberry Pi 4B, you need to add these 2 lines to file /etc/udev/rules.d/52-usb.rules
:
SUBSYSTEM=="usb", ATTR{idVendor}=="2109", MODE="0666"
SUBSYSTEM=="usb", ATTR{idVendor}=="1d6b", MODE="0666"
then either reboot or run this command to apply changes live:
sudo udevadm trigger --attr-match=subsystem=usb
Note that you do not need to write any scripts to automate your task. Your script is exactly equivalent to this command:
uhubctl -l 1-1 -a cycle -d 5
-
Thank you this helped fix my other issue. As for the script - I was just needing it to test to see why it wasn't running. The future plan is it needs to mount and unmount a drive as well as transfer a set of specified video files from the camera - but the camera needs to be mounted and not have any power from the usb in order to record. However the command provided could be useful later.ShekelsBot– ShekelsBot2020年11月27日 20:32:46 +00:00Commented Nov 27, 2020 at 20:32
-
You cannot have camera mounted and not have any powermvp– mvp2020年11月27日 21:35:37 +00:00Commented Nov 27, 2020 at 21:35
-
Correct. The script is meant to un-mount the drive and cut power. Then turn on power and mount the drive. And then transfer files. I cant have it being a mounted drive or receive power when its recording because it turns into a USB and defaults to charging. (Or when its done) Unless you have a different idea I should pursue?ShekelsBot– ShekelsBot2020年11月27日 23:54:26 +00:00Commented Nov 27, 2020 at 23:54
I was writing this script in Microsft Visual Studio Code. I forgot that spaces are interperated differently between Windows and Unix when running Bash. So I changed the document settings in Notepad++ to be Unix, re wrote the code and then it runs fine now.
Still have to use sudo
because the permissions are not working but not it runs correctly.
More info can be found here
#!/bin/bash
uhubctl -a off -l 1-1
sleep 5
uhubctl -a on -l 1-1
echo "All done"
sudo
)? Also what happens if you just runsudo USB_Power.sh
? Is this the only version of the script on your system?sudo
and I also run the script assudo
This is the only version of the script on the system. When I run the command is executes just fine - but when I run it as the script it just doesn't work.