How to disable/enable HDMI on Raspberry Pi?

11,796

Solution 1

If you want to go for pure C, look at the source code for tvservice, which is a C program. It can be found at github. It appears to be using the vc_tv_hdmi_power_on_preferred(); function defined in #include "interface/vmcs_host/vc_tvservice.h"

If you decide to call the tvservice program like in @moffeltje's answer, you could use the execl() it's a little safer - you have to give full path to the binary. (With execlp you can also have control over environment variables):

pid_t pid;


pid = fork();
if (0 == pid) {
    execl("/opt/vc/bin/tvservice", "-p", NULL);
}
if (-1 == pid) {
    // Handle error here, close program?
}

Solution 2

From https://gist.github.com/AGWA/9874925 I found the usefulness of chvt. So I suggest calling the shell commands

hdmioff() { tvservice -o; }
hdmion() { tvservice -p; sudo chvt 1; sudo chvt 7; }

with system().

Solution 3

You can use the system() command to use those commands you described.

int main(){

   //some code before disable hdmi
   system("tvservice -o");

   //do somethings when HDMI is disabled

   //turn HDMI back on
   system("tvservice -p");
   system("fbset -depth 8 && fbset -depth 16");

   return 0;

}
Share:
11,796
AlastairG
Author by

AlastairG

Started programming BBC Basic at age 8 or 9 on BBC Master computers. Moved onto Assembler on Archimedes computers around age 17. Moved to C on Unix at University around age 19. Have since done a huge number of different languages and enjoyed most of them.

Updated on June 11, 2022

Comments

  • AlastairG
    AlastairG almost 2 years

    So I can use "tvservice -o" to turn off the HDMI on the raspberry Pi, and "tvservice -p" to turn it back on. After turning it back on I apparently need to do "fbset -depth 8 && fbset -depth 16" to re-enable the frame buffer and then force an X11 redraw.

    My question is, how do I do this in C? I have an X11 application and I can manage the X11 redraw no problem, but how do I disable/re-enable HDMI in C, and how do I re-enable the frame buffer after re-enabling HDMI?

    To give background, I have a headless application running as a sort of media server, controlled by an Android app. Currently I am permanently disabling the turning off of HDMI after a timeout. However to save energy I would like to disable the HDMI when the app is not in use, and then turn it back on and display the RPi application on screen using libcec to determine when the TV is using the RPi's HDMI connection to turn HDMI on and off.