Button handling

The following sample program demonstrates functions for handling the button on XBee Gateway.

import select

fd=open('/var/run/reset_button')(1)
p=select.poll()
p.register(fd, select.POLLPRI)			(2)
fd.read() 	                  (3)
while True:
       p.poll()	            (4)
       fd.seek(0)	        (5)
       val = int(fd.read()[0])		(6)

       if val:	                      (7)
               print "Button pressed!"
      else:
               print "Button released!"

Program notes

  1. The reset button is exposed as a Linux file. It can be read to determine the state of the button, and it is possible to block waiting for the button state to change.
  2. To block waiting for the button, the standard Python select module is used. This line, and the line above, demonstrate how to create a polling object that can wait for button state changes.
  3. Read the current value of the button, but forget it. This is done to “clear” the button and prepare to wait for its state changes.
  4. Rather than reading the button in a loop, the system waits for button state changes using the polling object created earlier.
  5. To read the current value, the system first “rewinds” to the beginning of the “file.”
  6. fd.read() gets pending data from the button file. fd.read()[0] returns the first character of that data. int(fd.read()[0]) makes explicit the fact that the system expects the character it reads to be an integer.
  7. If the system reads a non-zero value, the button is currently pressed.