The vcgencmd
command returned a “0” or “1” depending on the connected monitor being off or on, but unfortunately, this is no longer working with Raspberry Pi OS Bullseye or Bookworm.
I tried tvservice -s
, kmsprint -m
, and ddcutil detect
but neither was working.
So, it was time to see if xrandr
would contain any useful function to achieve something to that effect.
Tested with Raspberry Pi OS Buster and Bookworm on a Raspberry Pi 4 (Oct 2023).
Using
DISPLAY=:0.0 xrandr
you get information about connected displays. But it is almost the same information, regardless of whether the display is powered on or off. But on closer inspection, there were some distinct differences:
On the left is the information when powered on, and the power-off data on the right. When a display is powered on, the resolution information is given after “HDMI-1 connected primary”.
So, I wrote a little Python test script parsing the output and checking if the
3840x2160+0+0
was included.
#!/usr/bin/python3
import subprocess
def is_hdmi1_connected(display=":0.0"):
try:
# Run the xrandr command and capture its output
command = f"DISPLAY={display} xrandr"
output = subprocess.check_output(command, shell=True).decode('utf-8')
# Check if "HDMI-1 connected primary 3840x2160" is in the output and marked as "connected"
if 'HDMI-1 connected primary 3840x2160' in output:
return True
else:
return False
except subprocess.CalledProcessError:
# Handle any errors that may occur
return False
if is_hdmi1_connected():
print("Display is on.")
else:
print("Display is off.")
Depending on your connected display, you must change the resolution to make it work for you.
Was this article helpful?
Thank you for your support and motivation.
Related Articles
- The easiest way to build a Raspberry Pi picture frame: Streaming with the FRAMEN Photo App
- How I added smooth crossfading image transitions to my Raspberry Pi digital picture frame
- Which Raspberry Pi model should you get for your digital photo frame?
- How to reduce the wear on your SD card in your Raspberry Pi digital photo frame