Skip to content

Instantly share code, notes, and snippets.

@macninja
Last active October 22, 2023 12:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macninja/6c13596f06206eec162f9dce1fc4313b to your computer and use it in GitHub Desktop.
Save macninja/6c13596f06206eec162f9dce1fc4313b to your computer and use it in GitHub Desktop.
Enable and disable the HDMI port on the Raspberry Pi. Uses cec-hdmi. Works on Raspberry Pi 4 as well.
#!/bin/bash
# Enable and disable HDMI output on the Raspberry Pi
# The script uses the cec-hdmi command to manage the hdmi interface.
# https://pimylifeup.com/raspberrypi-hdmi-cec/
# On a Raspberry Pi 4 i could only get this to work if i used the hdmi 2 port.
# To setup the script run "echo 'scan' | cec-client -s -d 1" to identify the adress of the HDMI unit.
_CEC_="0.0.0.0"
_LOG_="/home/pi/rpi-hdmi.log"
is_off() {
if [ "$(echo "$(echo "pow $_CEC_" | cec-client -s -d 1)" | awk '/power/ { print $3 }')" != on ]
then
return 0
else
return 1
fi
}
turn_on() {
echo "on $_CEC_" | cec-client -s -d 1
sleep 5
if is_off
then
# If TV did not turn on exit functin with error
return 1
else
echo "$(date +"%b %d %T") TV turned on" >> "$_LOG_"
fi
}
turn_off() {
echo "standby $_CEC_" | cec-client -s -d 1
sleep 5
if is_off
then
echo "$(date +"%b %d %T") TV turned off" >> "$_LOG_"
else
# If TV did not turn off exit functin with error
return 1
fi
}
case $1 in
off)
while ! turn_off
do
echo "$(date +"%b %d %T") waiting for tv to turn off" >> "$_LOG_"
sleep 5
done
;;
on)
if is_off
then
while ! turn_on
do
echo "$(date +"%b %d %T") waiting for tv to turn on" >> "$_LOG_"
sleep 5
done
curr_vt=$(fgconsole)
if [ "$curr_vt" = "1" ]
then
chvt 2
chvt 1
else
chvt 1
chvt "$curr_vt"
fi
fi
;;
status)
if is_off
then
echo "off"
else
echo "on"
fi
;;
*)
echo "Usage: $0 on|off|status" >&2
exit 2
;;
esac
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment