Skip to content

Instantly share code, notes, and snippets.

@RyanBalfanz
Created June 10, 2011 06:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RyanBalfanz/1018321 to your computer and use it in GitHub Desktop.
Save RyanBalfanz/1018321 to your computer and use it in GitHub Desktop.
Arduino-Python
import logging
import random
import sys
import time
from arduino import Arduino
logging.basicConfig(level=logging.DEBUG)
def setup_board(device=None, outputPins=None):
"""docstring for setup_board"""
device_list = (
'/dev/ttyUSB0',
'/dev/tty.usbserial-A8004JwH',
'/dev/cu.usbserial-A8004JwH',
'/dev/tty.Bluetooth-PDA-Sync',
'/dev/cu.Bluetooth-PDA-Sync',
'/dev/tty.Bluetooth-Modem',
'/dev/cu.Bluetooth-Modem',
)
if device:
device_list = (device,)
if not outputPins:
outputPins = (11,12,13)
board = None
for d in device_list:
logging.debug("Trying to connect on {0}".format(d))
try:
board = Arduino(d)
except:
logging.debug("Failed to connect on {address}".format(address=d))
else:
logging.debug("Connected on {address}".format(address=d))
break
if board:
board.output(outputPins)
return board
def blink(board=None, n=1, d=1.0):
"""docstring for blink"""
if not board:
raise AttributeError("board not specified")
logging.debug("Blinking for {0} seconds".format(d))
for i in xrange(n-1):
board.setHigh(13)
logging.debug("On for {s} seconds".format(s=d))
time.sleep(d)
board.setLow(13)
logging.debug("Off for {s} seconds".format(s=d))
time.sleep(d)
def random_blink(board=None, n=1, randFunc=None, *args):
"""docstring for random_blink"""
if not board:
raise AttributeError("board not specified")
if not randFunc:
randFunc = random.random
logging.debug("Random blinking using {0} with args {1}".format(randFunc, args))
for i in xrange(n-1):
board.setHigh(13)
r = randFunc(*args)
logging.debug("On for {s} seconds".format(s=r))
time.sleep(r)
board.setLow(13)
# x, = args
# r = randFunc(x*2)
r = randFunc(*args)
logging.debug("Off for {s} seconds".format(s=r))
time.sleep(r)
def flicker(board=None, n=1):
"""docstring for flicker"""
logging.debug("Flickering {0} times".format(n))
random_blink(board, n, random.expovariate, 7)
if __name__ == "__main__":
board = setup_board()
# assert board, "Could not setup Arduino board"
if not board:
sys.exit("The board does not exist")
blink(board, 5)
random_blink(board, 5)
flicker(board, 100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment