#!/usr/bin/env python
import time
import signal
import sys
import threading
from PyMata.pymata import PyMata
# Digital pins
GREEN_LED = 6
# Analog pin
LIGHTSENSOR = 0
TRIGGER = 500
# Switch states
ON = 1
OFF = 0
# Indices for data list passed to latch callback
LATCH_TYPE = 0
LATCH_PIN = 1
LATCH_DATA_VALUE = 2
LATCH_TIME_STAMP = 3
# Global value
IN_CALLBACK = 0
# Callback functions
def cb_timer():
global IN_CALLBACK
if IN_CALLBACK == OFF:
board.digital_write(GREEN_LED, OFF)
# Callback functions
# Set the LED to current state of the pushbutton switch
def cb_lightsensor(data):
pass
def cb_lightsensor_latch(data):
global IN_CALLBACK
IN_CALLBACK = ON
# Turn on LEDs
board.digital_write(GREEN_LED, ON)
# Print all data from the latch
callback including time stamp
print('Latching Event Mode:%x
Pin:%d Data Value:%d Time of Event:%s' %
(data[LATCH_TYPE], data[LATCH_PIN],
data[LATCH_DATA_VALUE],
time.asctime(time.gmtime(data[LATCH_TIME_STAMP]))))
# Re-Set the latch
board.set_analog_latch(LIGHTSENSOR,
board.ANALOG_LATCH_GT,
TRIGGER,
cb_lightsensor_latch)
t = threading.Timer(1, cb_timer)
t.start()
IN_CALLBACK = OFF
# Create a PyMata instance
board = PyMata("/dev/ttyUSB0", verbose=True)
def signal_handler(sig, frame):
print('You pressed Ctrl+C')
if board is not None:
board.close()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
# Set pin modes
board.set_pin_mode(GREEN_LED, board.OUTPUT, board.DIGITAL)
board.set_pin_mode(LIGHTSENSOR, board.INPUT, board.ANALOG,
cb_lightsensor)
# Set the latch
board.set_analog_latch(LIGHTSENSOR,
board.ANALOG_LATCH_GT,
TRIGGER,
cb_lightsensor_latch)
# A forever loop until user presses Ctrl+C
while 1:
pass
|