Skip to content

Commit

Permalink
Added analog inputs and buzzer with example
Browse files Browse the repository at this point in the history
  • Loading branch information
theycallmeswift committed Mar 13, 2013
1 parent 59cd692 commit f8b6b59
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 10 deletions.
37 changes: 27 additions & 10 deletions breakfast_serial/components.py
@@ -1,6 +1,6 @@
from breakfast_serial import Arduino
from util import EventEmitter, setInterval
import pyfirmata
import pyfirmata, re

class ArduinoNotSuppliedException(Exception):
pass
Expand All @@ -14,7 +14,25 @@ def __init__(self, board, pin):
super(Component, self).__init__()

self._board = board
self._pin = self._board.digital[pin]

analog_regex = re.compile('A(\d)')
match = analog_regex.match(str(pin))

if match:
self._pin = self._board.analog[int(match.group(1))]
else:
self._pin = self._board.digital[int(pin)]

@property
def value(self): return self._pin.value

class Sensor(Component):

def __init__(self, board, pin):
super(Sensor, self).__init__(board, pin)

self._pin.mode = pyfirmata.INPUT
self._pin.enable_reporting()

class Led(Component):

Expand Down Expand Up @@ -46,27 +64,26 @@ def toggle(self):
def blink(self, millis):
self._interval = setInterval(self.toggle, millis)

class Button(Component):
class Buzzer(Led):
pass

class Button(Sensor):

def __init__(self, board, pin):
super(Button, self).__init__(board, pin)

self._pin.mode = pyfirmata.INPUT
self._pin.enable_reporting()

self._old_value = self._pin.value
self._old_value = self.value

self._board.on('data', self._handle_data)

def _handle_data(self):
value = self._pin.value
value = self.value

if self._old_value != value:
self._old_value = value
self._handle_state_changed()

def _handle_state_changed(self):
if self._pin.value == False:
if self.value == False:
self.emit('up')
else:
self.emit('down')
Expand Down
29 changes: 29 additions & 0 deletions examples/buzzer.py
@@ -0,0 +1,29 @@
#! /usr/bin/env python
"""
This is an example that demonstrates how to use a
photoresistor to control a buzzer (piezo element)
using breakfast_serial. It assumes you have an
photoresistor (or some equivalent analog input)
wired up to pin A0 and a buzzer on pin 8.
"""
from breakfast_serial import Arduino, Buzzer, Sensor, setInterval
from time import sleep

board = Arduino()
buzzer = Buzzer(board, "8")
sensor = Sensor(board, "A0")

def loop():
value = sensor.value or 1 # value is initially None
value = value / 2

buzzer.on()
sleep(value)
buzzer.off()
sleep(value)

setInterval(loop, 0)

# Run an interactive shell so you can play (not required)
import code
code.InteractiveConsole(locals=globals()).interact()

0 comments on commit f8b6b59

Please sign in to comment.