Here it is stated that:
The Pi uses the HDMI hotplug signal to detect whether a HDMI is attached. If it is not detected then it falls back to composite.
which in turn suggests that there is some kind of software running to detect the change of the hotplug status. But what does the trick?
@SlySven's suggestion to use /opt/vc/bin/tvservice -s
hits the nail head.
Example output of Pi with connected HDMI:
state 0x12001a [HDMI CEA (16) RGB lim 16:9], 1920x1080 @ 60.00Hz, progressive
and with cable unplugged:
state 0x120019 [HDMI CEA (16) RGB lim 16:9], 1920x1080 @ 60.00Hz, progressive
It's time to have a look at tvservice
's source (or more precisely userland/interface/vmcs_host/vc_hdmi.h). They conveniently provide us with the enum VC_HDMI_NOTIFY_T which essentially tells us all we need to know:
typedef enum {
VC_HDMI_UNPLUGGED = (1 << 0), /*HDMI cable is detached */
VC_HDMI_ATTACHED = (1 << 1), /*HDMI cable is attached but not powered on */
[...]
} VC_HDMI_NOTIFY_T;
So all we need to do is to check for the least significant bit - if it is set then the cable is unplugged. So it would seem that running tvservice -s
and parsing the status properly should enable to detect whether HDMI is connected or not.