I'm using the Pi to control some decorative lights. I turn the lights on and off via cron scripts and would like to get status on the lights as well. When I run the code below, it reports 'on' if the lights are on, but if they're off, they're turned on by the code.

#!/usr/bin/env ruby
require 'rpi_gpio'
RPi::GPIO.set_numbering :bcm
RPi::GPIO.setup 18, :as => :output

if RPi::GPIO.high? 18
    print "Lights are on\n"
    print "We're in the dark\n"

If I change the setup to => :input, the pin goes low immediately and the lights go out.

What am I doing wrong?

  • but if they're off, they're turned on by the code ..... how do you know that happens only if they are off? .... maybe the lights are always being turned on – jsotola Jul 8 '18 at 6:35
  • The Ruby idiom of the trailing question mark normally means that something is being inquired about and the software returns the current value. They are always being turned on, and this is wrong IMHO. – Leonard Jul 8 '18 at 9:58
  • all i am saying is that the lights are not being turned on because of an if statement result .... they are being turned on by some other part of the program .... the lights probably turn on even if you remove the if statement – jsotola Jul 8 '18 at 19:05
  • Sorry, no. The software above is the whole of my 'status' command. I've tested that line all by itself. The line "if RPi::GPIO.high? 18" turns the light on. I'm shocked. That's why I asked the question here. – Leonard Jul 9 '18 at 0:27
  • Did you ever find a solution to this issue? – Reinstate Monica -- notmaynard Nov 26 '18 at 4:24

When you set a Pi GPIO to be an output (presumably line RPi::GPIO.setup 18, :as => :output) the GPIO level will be set to that last requested.

If the last level requested was high the GPIO will be high (on).

If the last level requested was low the GPIO will be low (off).

  • This makes sense, thanks, but doesn't cover every case: After a power outage and reboot, the pin would be low even though my software set it high before the reboot. There are also conditions where the cron job could fail and not turn on the lights. I could look at the log, but was hoping for something more. – Leonard Jul 8 '18 at 9:30
  • GPIO state is not preserved over a reboot. I'd guess that all GPIO default to be low as far as the "last requested level" is concerned. – joan Jul 8 '18 at 9:44

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.