0

I'm trying to write a parser for a program on the Raspberry Pi.

My goal is to detect whether or not an HDMI cable is plugged into the raspberry pi, and I have settled on using /opt/vc/bin/tvservice.

Calling

tvservice -s

returns something like

state 0xXXXXXX ......

where XXXXXX is a hex number. I can see this hex number change when I unplug the HDMI cable and replug it back in. I have used this answer to help me program some logic to print out the right status. However, I want to know all of the statuses, which led me to the tvservice source here.

This enum shows stuff like the following:

STATUS0 = 1 << 0
STATUS1 = 1 << 1
STATUS2 = 1 << 2
STATUS3 = 1 << 3
etc etc

Given a hex string (ie 0xa or 0x9 or 0x40000), how can I parse the correct state/status?

The answer in the forum stated that if the least-significant-bit is disabled (a 0), then the HDMI is plugged in, and if it is enabled (a 1), it is not plugged in. This works for when the system boots up with the HDMI cable plugged in but not when it boots up without a cable.

For example, booting with a cable plugged in:

state = 0xa === 1010 === plugged in

and then unplugging it:

state = 0x9 === 1001 === unplugged

However, starting the system without an HDMI cable gives me:

state = 0x40000 === 1000000000000000000 === plugged in

My question is: how can I parse this hex number into the correct status? Bit shifting has always given me trouble, so anything is appreciated. Thank you.

  • You can get the source for TVservice at github.com/raspberrypi/userland/blob/… that may be easier to hack to do what you need. – Dougie Sep 5 at 23:35
  • @jsotola I understand bit shifting a little bit, and how it's done, but what I'm confused about are the states in tvservice. I got 0xa for plugged in and 0x9 for unplugged, with 0x40000 when booting up without hdmi. How do these values correlate to what I see in the TVservice code? IE: 1 << 0, 1 << 1, 1 << 2, etc. I looked through it and I couldn't really piece it together – Devin Sep 6 at 11:37
  • @Dougie reply above ^ – Devin Sep 6 at 11:37
  • 1 << 0, 1 << 1, 1 << 2 ... first one sets bit 0, second one sets bit 1 .... so whenever bit 0 is set, the value is odd – jsotola Sep 6 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.