Automatically switch Raspberry HDMI between MagicMirror2 and a desktop

image_print

Running a MagicMirror on a Raspberry Pi alongside a desktop PC? Tired of manually changing inputs when the PC boots or shuts down? Here’s a simple Bash script plus systemd service that:

  • Blanks the Pi’s HDMI output whenever your desktop (IP 192.168.0.114) is up
  • Restores the Pi’s HDMI when the desktop shuts down

Prerequisites

1. Create the Bash Script

Save the following as /home/pi/autoHDMI.sh and make it executable:

#!/bin/bash
# autoHDMI.sh — turn Pi HDMI off/on based on desktop presence

DESKTOP_IP="192.168.0.114"    # ← your desktop’s IP
INTERVAL=10                   # seconds between checks

hdmi_off=0
while true; do
  if ping -c1 -W1 "$DESKTOP_IP" &>/dev/null; then
    if [[ $hdmi_off -eq 0 ]]; then
      /usr/bin/vcgencmd display_power 0    # blank HDMI
      hdmi_off=1
    fi
  else
    if [[ $hdmi_off -eq 1 ]]; then
      /usr/bin/vcgencmd display_power 1    # restore HDMI
      hdmi_off=0
    fi
  fi
  sleep "$INTERVAL"
done
chmod +x /home/pi/autoHDMI.sh

2. Test the Commands Manually

Before automating, confirm the blank/unblank work:

# Blank the HDMI output
sudo vcgencmd display_power 0

# Restore it
sudo vcgencmd display_power 1

If you see your monitor lose signal on “0” and regain it on “1,” you’re good to go.

3. Automate with systemd

Create the service file at /etc/systemd/system/autoHDMI.service:

[Unit]
Description=Auto‑HDMI switching (Pi ↔ Desktop)
After=network-online.target
Wants=network-online.target

[Service]
User=pi
ExecStart=/home/pi/autoHDMI.sh
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

Enable and start it:

sudo systemctl daemon-reload
sudo systemctl enable --now autoHDMI.service

4. How It Works

  1. Ping check every 10 s (ping -c1 -W1) returns exit code 0 if the desktop answers https://ss64.com/bash/ping.html
  2. Blank: when the desktop is up, the script runs vcgencmd display_power 0
  3. Restore: when the desktop goes down, it runs vcgencmd display_power 1
  4. Your monitor, set to Auto‑select input, sees “no signal” on HDMI 1 and switches to your desktop (HDMI 2). When the Pi’s HDMI returns, it flips back to MagicMirror.


5. We run an X‑screen / LXDE

Source: Raspberry Pi forum thread on disabling blanking with xset (forums.raspberrypi.com)

I stopped my MagicMirror Pi’s X screen from going black by editing the LXDE autostart file and adding three xset lines.

Full file with the changes:

# /etc/xdg/lxsession/LXDE-pi/autostart        
@lxpanel --profile LXDE-pi
@pcmanfm --desktop --profile LXDE-pi
point-rpi

# keep the X‑screen awake
@xset s noblank     # no blanking
@xset s off         # disable screensaver


Reboot and the display stays on permanently.

Conclusion

With this setup, your MagicMirror display takes over whenever your desktop is off, and your PC display reclaims the screen as soon as it’s available—no manual input switching needed!


You may also like...