Enable HDMI and audio over HDMI on Raspberry Pi

This is just a note so I do not forget during the next update... If the Pi is running in a headless state most of the time and a display or projector only attached e.g. for movie viewing, Pi has to be told to enable the HDMI port and set it to a specific mode (the correct timing and resolution) at boot time.

First, boot the Pi with running display attached and query the HDMI mode using

$ tvservice -s
state 0x12000a [HDMI CEA (16) RGB lim 16:9], 1920x1080 @ 59.94Hz, progressive

This tells us that the display is running in a 1920x1080 CEA (could be DMT in your case) mode. In order to find out the correct mode number we check the available modes by running (replace CEA by DMT if this was indicated in the last command's output)

$ tvservice -m CEA
Group CEA has 16 modes:
           mode 1: 640x480 @ 60Hz 4:3, clock:25MHz progressive
           mode 2: 720x480 @ 60Hz 4:3, clock:27MHz progressive
           mode 3: 720x480 @ 60Hz 16:9, clock:27MHz progressive
           mode 4: 1280x720 @ 60Hz 16:9, clock:74MHz progressive
           mode 5: 1920x1080 @ 60Hz 16:9, clock:74MHz interlaced
           mode 6: 720x480 @ 60Hz 4:3, clock:27MHz x2 interlaced
  (prefer) mode 16: 1920x1080 @ 60Hz 16:9, clock:148MHz progressive
           mode 17: 720x576 @ 50Hz 4:3, clock:27MHz progressive
           mode 18: 720x576 @ 50Hz 16:9, clock:27MHz progressive
           mode 19: 1280x720 @ 50Hz 16:9, clock:74MHz progressive
           mode 20: 1920x1080 @ 50Hz 16:9, clock:74MHz interlaced
           mode 21: 720x576 @ 50Hz 4:3, clock:27MHz x2 interlaced
  (native) mode 31: 1920x1080 @ 50Hz 16:9, clock:148MHz progressive
           mode 32: 1920x1080 @ 24Hz 16:9, clock:74MHz progressive
           mode 33: 1920x1080 @ 25Hz 16:9, clock:74MHz progressive
           mode 34: 1920x1080 @ 30Hz 16:9, clock:74MHz progressive

The actual mode used in this case is number 16. Now we can edit the file /boot/config.txt to include the necessary options:

hdmi_force_hotplug=1   # make sure, the HDMI port is switched on always
hdmi_group=1           # the HDMI mode group (1: CEA, 2: DMT)
hdmi_mode=16           # the mode number we found earlier goes here

After the next reboot the display should be working at the desired resolution even when switched on later. Another issue happens when HDMI is also used for audio output. The output has to be set to HDMI as opposed to DVI. This is done by adding the line

hdmi_drive=2           # set output to HDMI and send audio over HDMI

For more details regarding the possible options, please consult the official documentation.