How can I programmatically detect if the Raspberry Pi's HDMI cable is removed? I've tried tools like xrandr, but they give the same output regardless of whether the HDMI cable is plugged in or not.
2 Answers
Try verifying the output of the file:
/sys/class/drm/card0-HDMI-A-1/status
The part card0-HDMI-A-1 may be a little different (verify the parent directory for the correct file) and the content should be connected or disconnected. Also works for another connections, like VGA, LVDS, etc.
After this, simply make a script like:
while [ 1 ]
do
STATUS=`cat /sys/class/drm/card0-HDMI-A-1/status`
if [ "$STATUS" == "disconnected" ]; then
echo "turning off"
sudo shutdown now
fi
#sleep for 10 seconds and check again
sleep 10
done
To run it automatically on background, follow this link.
The following worked for me with a Raspberry Pi 4 B and current default operating system. This solution is based on kmsprint, whereas some older forum posts suggest tvservice which my OS did not recognize / may be deprecated.
This will allow you to safely shut down your Raspberry Pi just by disconnecting the HDMI cable, rather than having to add a physical button. I'm using it for an RPi whose sole purpose in life is to display a looping video on a monitor.
First try this command and see if the output tells you the HDMI connection status: kmsprint
If that works, then create a shell script: sudo nano ~/check_hdmi.sh
Enter in the script:
# Flag to track if HDMI was ever connected
hdmi_connected=false
while true; do
output=$(kmsprint)
if echo "$output" | grep -q "HDMI-A-1 (connected)"; then
logger "HDMI detected."
hdmi_connected=true
else
if [ "$hdmi_connected" = true ]; then
logger "HDMI not detected after being connected. Initiating shutdown."
sudo shutdown -h now
exit 0
else
logger "HDMI not detected and was never connected. Waiting..."
fi
fi
sleep 5
done
Make the script executable: chmod +x ~/check_hdmi.sh
You might comment out (#)the shutdown & exit lines and test the script now. Run the script and read the logs with journalctl -f while plugging/unplugging the hdmi cable. Hdmi has to be connected to a powered device for it to register as connected.
If that works, create a service to start your script when the rpi boots up.
sudo nano /etc/systemd/system/hdmi-monitor.service
Enter in that file:
Description=Monitor HDMI connection and shutdown on disconnect
After=graphical.target
[Service]
User=<enter your username here>
Environment=DISPLAY=:0
Environment=XAUTHORITY=/home/<your username here>/.Xauthority
ExecStart=/home/<your username here>/check_hdmi.sh
Restart=no
[Install]
WantedBy=graphical.target
To enable and start the service you can use:
sudo systemctl enable hdmi-monitor.service
sudo systemctl start hdmi-monitor.service
It should also start every time you boot up your RPi.
- 2,969
- 5
- 27
- 38
- 11
- 1