Once again, a “superused” GPIO… This time, the RPi I/O is used for driving two leds (one blue, one red) and a pushbutton. The schematic is simple, look at the pic below:
There is also a new Python script named service2.py :
import RPi.GPIO as GPIO import time from subprocess import call cnt = 0 # reset counter for pushbutton pressed toggle = 0 # reset toggle flag GPIO.setmode(GPIO.BCM) # set GPIO mode while True: # main loop GPIO.setup(4, GPIO.OUT) # GPIO.4 set as output GPIO.output(4, False) # GPIO.4 output set at low level (red led ON) time.sleep(0.2) # 200mS pause with red led ON if toggle != 0: # if toggle flag set GPIO.output(4, True) # GPIO.4 output set at high level (blue led ON) time.sleep(0.2) # 200mS pause with blue led ON GPIO.setup(4, GPIO.IN, pull_up_down = GPIO.PUD_OFF) # GPIO.4 set as input, no pull-ups (both leds OFF) for n in range(0,2): # exec twice time.sleep(0.1) # wait for 100 mS prior to read pushbutton status if GPIO.input(4): # if GPIO.4 is high (button NOT pressed) if cnt >= 4 and cnt <= 6: # if was pressed for 2-3 sec toggle ^= 1 # invert toggle flag if toggle == 0: # if changed to 0 call("sudo killall x11vnc", shell=True) # terminate x11vnc server else: # if changed to 1 call("sudo x11vnc", shell=True) # start x11vnc server cnt = 0 # reset counter for pushbutton pressed else: # if GPIO.4 is low (button pressed) cnt += 1 # increment counter for pushbutton pressed if cnt >= 10: # if continuously pressed for 5 seconds (cnt increments 2 times in a second) GPIO.setup(4, GPIO.OUT) # GPIO.4 set as output GPIO.output(4, False) # GPIO.4 output set at low level (fix red led ON as signal for user) call("sudo poweroff", shell=True) # terminate and shutdown break if toggle != 0: # if toggle flag set time.sleep(0.4) # (blue blinked for 0.2 Sec) wait the remaining time for 1 Sec main cycle else: time.sleep(0.6) # (blue off) wait the remaining time for 1 Sec main cycle
How it works:
Normally, the red led is lighted for 200 mS, then the button is sampled for pressed state. If the button is pressed for a time between 2 and 3 seconds, then the variable toggle is inverted. When toggle is “1”, after the red led turns off, the blue one turns on for 200 mS. If the button is pressed again for 2-3 Sec, the variable toggle is inverted again and at next cycle the blue led will no more turn on. When the toggle variable changes, there are two actions performed by the script : if toggle is 0 (off) then a call to “killall x11vnc” is performed, while if is 1 (on) a call to “x11vnc” is done. This means that I can control the start or stop of x11vnc server with my pushbutton. If I press the button for a time over 5 seconds, there is a call to the “poweroff” and the board will turn off. Please, note that when the pushbutton is pressed the blue led can’t turn on, while the red one will be forced on (at low current, 1mA).
Hope this will be useful for someone…