Reorganised file locations for testing
authorNeil Smith <neil.github@njae.me.uk>
Fri, 19 Apr 2013 19:19:06 +0000 (20:19 +0100)
committerNeil Smith <neil.github@njae.me.uk>
Fri, 19 Apr 2013 19:19:06 +0000 (20:19 +0100)
41 files changed:
.Rhistory [new file with mode: 0644]
README.md [deleted file]
arduino/guitar/guitar.ino [deleted file]
raspberrypi/music-maker-handler.py [deleted file]
raspberrypi/music-maker.sb [deleted file]
release/cymbal.mp3 [new file with mode: 0644]
release/drums/drums.ino [new file with mode: 0644]
release/guitar.gif [new file with mode: 0644]
release/guitar/guitar.ino [new file with mode: 0644]
release/guitar1.mp3 [new file with mode: 0644]
release/guitar2.mp3 [new file with mode: 0644]
release/guitar3.mp3 [new file with mode: 0644]
release/guitar4.mp3 [new file with mode: 0644]
release/guitar5.mp3 [new file with mode: 0644]
release/hihat.mp3 [new file with mode: 0644]
release/maracas.gif [new file with mode: 0644]
release/maracas.mp3 [new file with mode: 0644]
release/maracas/maracas.ino [new file with mode: 0644]
release/miniband1.sb [new file with mode: 0644]
release/miniband2.sb [new file with mode: 0644]
release/miniband3.sb [new file with mode: 0644]
release/music-maker-handler.py [new file with mode: 0755]
release/scratchthumbs.db [new file with mode: 0644]
release/slowdrum.mp3 [new file with mode: 0644]
release/snare.mp3 [new file with mode: 0644]
release/tomtom.mp3 [new file with mode: 0644]
writeup/.directory [new file with mode: 0644]
writeup/drums-script.png [new file with mode: 0644]
writeup/drums.fzz [new file with mode: 0644]
writeup/drums_bb.png [new file with mode: 0644]
writeup/drums_schem.png [new file with mode: 0644]
writeup/enable-remote-sensors.png [new file with mode: 0644]
writeup/guitar.fzz [new file with mode: 0644]
writeup/guitar_bb.png [new file with mode: 0644]
writeup/guitar_schem.png [new file with mode: 0644]
writeup/maracas-script.png [new file with mode: 0644]
writeup/maracas.fzz [new file with mode: 0644]
writeup/maracas_bb.png [new file with mode: 0644]
writeup/maracas_schem.png [new file with mode: 0644]
writeup/miniband.doc [new file with mode: 0644]
writeup/miniband.odt [new file with mode: 0644]

diff --git a/.Rhistory b/.Rhistory
new file mode 100644 (file)
index 0000000..e69de29
diff --git a/README.md b/README.md
deleted file mode 100644 (file)
index 80b1043..0000000
--- a/README.md
+++ /dev/null
@@ -1,178 +0,0 @@
-# Code Club - Mini Band Project
-
-<img src="http://farm9.staticflickr.com/8338/8256708023_4a941566e9.jpg" width="500" height="375" alt="photo (2)">
-
-Make your own mini band! 
-You and your friends can form your own finger-sized band and rock out using Raspberry Pi and Arduino. 
-Learn how to build circuits with sensors and outputs and write a simple programme to control your instruments.
-
-## You will make:
-
-* A guitar
-* A set of drums
-* A pair of maracas
-
-## You will need:
-
-* 1 x Raspberry Pi (plus monitor and power supply)
-* USB hub
-* 2 x Arduino Uno boards (with USB cables)
-* 1 x strip potentiometer
-* 2 x tilt sensors
-* 4 x piezo buzzers (the type in greetings cards, easy to get from Maplin)
-* 10K resistors
-* Bread boards (1 per instrument)
-* Card
-* Sugru (or some other modelling material)
-* Electrical tape
-* Plastic drinking straw
-* Pencil
-* Coloured pens (optional)
-
-
-## Software requirements:
-
-* Scratch
-* IDE developer environment for Arduino
-* Py Serial library
-
-
-## Useful links:
-
-* [Pictures](http://bit.ly/codeclubminiband) 
-* [Ardunio code](https://github.com/KatJoyWhite/miniband/tree/master/arduino)
-
-
-
-## Pull-down Resistors
-
-You’ll find your analogue inputs receive signal when you don’t expect them to.
-This is because there’s electricty floating around in the system, or something like that.
-
-To fix this, you need to wire each input to ground, through a 10KΩ resistor.
-
-A better explanation can be found [here](http://arduino.cc/en/Tutorial/DigitalPins).
-
-
-
-## Drum Kit
-
-<img src="http://farm9.staticflickr.com/8074/8257699966_7585ca06e7.jpg" width="375" height="500" alt="Code Club Miniband"><
-
-### 1. Make your drums
-
-Take your 4 piezo buzzers and attach a ring of Sugru (or other modelling material) as shown in the picture. 
-This will increase the flexibility and resonance of the sensors. Let the sugru set.
-
-<img src="http://farm9.staticflickr.com/8353/8256628815_6c3872d3ac.jpg" width="500" height="375" alt="Code Club Miniband">
-
-
-### 2. Connect the circuit
-
-Piezo buzzers generate a small charges when you tap them, so they don’t need a power source.
-Connect one lead from your buzzer to one of your analogue inputs, and connect the other lead to ground.
-Repeat for each of your drums. It is easiest to use a bread board for making your circuit. 
-Look at the picture for an example.
-
-<img src="http://farm9.staticflickr.com/8081/8256628955_f65a76b6fb.jpg" width="500" height="375" alt="Code Club Miniband">
-
-### 3. Program the Arduino
-
-Find the appropriate code from the respository and upload to your Ardunio board.
-
-
-### 4. Set up in Scratch 
-
-Find four different drum sounds (or whatever sounds you'd like your drums to make!). Upload the sounds to Scratch.
-
-
-## Guitar
-
-<img src="http://farm9.staticflickr.com/8070/8257698984_8471e4cf57.jpg" width="500" height="375" alt="Code Club Miniband">
-
-### 1. Make your guitar
-
-Grab your strip potentiomater, a piece of thin card, and a pencil. 
-Lightly draw round your potentiometer on the card and then use this as a guide to draw out your guitar shape. 
-(The potentiomater will be the fret board of your guitar).
-Cut out and colour in the guitar and stick down the potentiomater.
-Tape a pencil or stick to the back of the guitar to make it stiffen the fret board. 
-
-### 2. Connect the circuit
-
-The potentiomater strip adjusts resistance, so you will need to feed it some electricity.
-Run +5V into one of the strip’s outer pins, and ground into the other outer pin.
-It doesn’t matter which way around you connect these, but it will affect which the direction
-the fretboard runs (high and the top, low at the bottom or vice-versa).
-
-Signal will come from the centre pin, so connect that to one of your analogue inputs and you should be good to go.
-
-<img src="http://farm9.staticflickr.com/8363/8257699194_a2645e0e06.jpg" width="500" height="375" alt="Code Club Miniband">
-
-### 3. Program the Arduino
-
-Find the appropriate code from the respository and upload to your Ardunio board.
-
-
-### 4. Set up in Scratch
-
-Find five different guitar sounds and upload to Scratch.
-
-
-## Maracas
-
-<img src="http://farm9.staticflickr.com/8346/8257698652_4a99ee24b4.jpg" width="500" height="375" alt="Code Club Miniband">
-
-### 1. Make your maracas
-
-Cut 2 short lengths of drinking straw for your maraca handles. 
-Using Sugru (or other modelling material), make 2 maraca heads by rolling it up into balls.
-Push the maraca heads onto the straws and mold into a maraca shape.
-Connect lengths of wire to the connectors of the 2 tilt sensors and then push each sensor into a straw until it presses into the Sugru.
-Leave the Sugru to set.
-
-<img src="http://farm9.staticflickr.com/8222/8256627511_118192e52f.jpg" width="500" height="375" alt="Code Club Miniband">
-
-### 2. Connect the circuit
-
-Connect the +5V port on the Arduino board to one of the pins on the tilt switch (it doesn't matter which way round).
-Connect the other pin to an empty digital input on the board. 
-
-<img src="http://farm9.staticflickr.com/8348/8257698572_4157db0b20.jpg" width="500" height="375" alt="Code Club Miniband">
-
-### 3. Program the Arduino
-
-Find the appropriate code from the respository and upload to your Ardunio board.
-
-
-### 4. Set up in Scratch
-
-Find a maraca / shaker sound and upload to Scratch.
-
-
-## Connecting to the Raspberry Pi
-
-Set up your Raspberry Pi with a power supply and monitor. 
-Connect all your Ardunio boards (it's easiest to have one per instrument!) to the Raspberry Pi using USB. 
-You will probably need a USB hub.
-
-
-## Python glueware
-
-Download the music-maker-hander.py file from the repository. Run it with
-    python music-maker-handler.py
-This program sets up a listener for each instrument. When it detects that an instrument has been played, it sends a couple of signals to Scratch.
-
-The first signal appears in Scratch as a sensor value and is the volume (for drums), pitch (for the guitar), or ignored (for the maracas).
-
-The second signal is a broadcast message that makes Scratch play the sound in the instrument.
-
-One problem we had was with how the operating sytem mapped the various Arduinos to devices. It seemed to be pretty arbitrary. In the end, we tracked the device names by running
-    tail -f /var/log/syslog
-in a separate terminal and watching what the devices were called when we plugged them in. We could then edit the various DEVICE parameters in to top of the Python script to fit. You could probably be cleverer by using some udev rules to fix the device names, but we didn't think of that (and didn't have enough time either).
-
-## Scratch front end
-
-The Scratch file, music-maker, makes the sounds. It responds to the signals from the Python handler above by playing the appropriate sounds. It also does some visual feedback for the insturments. 
-
-Scratch on the Raspberry Pi is very slow, especially when it comes to updating the screen. Very often, Scratch would hang mid-way through a jamming session, only to start playing all the sounds after a short while. During the demos, people suggested that we minimise the Scratch window to reduce its workload.
\ No newline at end of file
diff --git a/arduino/guitar/guitar.ino b/arduino/guitar/guitar.ino
deleted file mode 100644 (file)
index f9f530c..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-
-const int THRESHOLD = 10;
-const int GUITAR_PIN = A0;
-const int PINLIMIT = 5000;
-
-int val;
-int pinDelay;
-
-void setup() {
-  Serial.begin(57600);
-}
-
-void loop() {
-  val = analogRead(GUITAR_PIN);
-  
-  if (val >= THRESHOLD && pinDelay < 1) {
-    Serial.print("guitar,");
-    Serial.println(val);
-    pinDelay = PINLIMIT;
-  }
-    
-  if (pinDelay > 0) {
-    pinDelay = pinDelay - 1;
-  }
-}
-  
diff --git a/raspberrypi/music-maker-handler.py b/raspberrypi/music-maker-handler.py
deleted file mode 100755 (executable)
index c935c15..0000000
+++ /dev/null
@@ -1,181 +0,0 @@
-# This code is copyright ...... under the GPL v2.
-# This code is derived from scratch_gpio_handler by Simon Walters, which
-# is derived from scratch_handler by Thomas Preston
-# Version 0.1: It's kind of working.
-
-from array import *
-import threading
-import socket
-import time
-import sys
-import struct
-import serial
-import io
-import datetime as dt
-import logging
-
-PORT = 42001
-DEFAULT_HOST = '127.0.0.1'
-BUFFER_SIZE = 240 #used to be 100
-SOCKET_TIMEOUT = 1
-DEVICES = ['/dev/ttyACM0', '/dev/ttyACM1','/dev/ttyACM3']
-#DEVICES = ['/dev/ttyACM0','/dev/ttyACM1']
-#DRUM_DEVICE = '/dev/ttyACM0'
-#GUITAR_DEVICE = '/dev/ttyUSB1'
-#MARACAS_DEVICE = '/dev/ttyACM1'
-ARDUINO_BAUD_RATE = 57600
-
-BROADCAST_NAMES = {'guitar': 'guitar', 
-    'drum': {0: 'cymbal',
-        1: 'hihat',
-        2: 'slowdrum',
-        3: 'snare',
-        4: 'tomtom'},
-    'maracas': 'maracas'}
-
-SENSOR_NAMES = {'guitar': 'guitar_pitch'}
-
-logging.basicConfig(level = logging.INFO)
-#logging.basicConfig(level = logging.DEBUG)
-
-class MyError(Exception):
-    def __init__(self, value):
-        self.value = value
-
-    def __str__(self):
-        return repr(self.value)
-
-class ScratchSender(threading.Thread):
-    def __init__(self, socket):
-        threading.Thread.__init__(self)
-        self.scratch_socket = socket
-        self._stop = threading.Event()
-        
-    def join(self,timeout=None):
-        self._stop.set()
-        threading.Thread.join(self, timeout)
-
-    def stopped(self):
-        return self._stop.isSet()
-
-    def run(self):
-        while not self.stopped():
-            time.sleep(0.01) # be kind to cpu - not certain why :)
-
-    def send_scratch_command(self, cmd):
-        n = len(cmd)
-        a = array('c')
-        a.append(chr((n >> 24) & 0xFF))
-        a.append(chr((n >> 16) & 0xFF))
-        a.append(chr((n >>  8) & 0xFF))
-        a.append(chr(n & 0xFF))
-        self.scratch_socket.send(a.tostring() + cmd)
-
-
-class ArduinoListener(threading.Thread):
-    def __init__(self, device, speed, sender, instruments, values):
-        threading.Thread.__init__(self)
-        self.arduino_device = serial.Serial(device, speed, timeout=0.5)
-        self._stop = threading.Event()
-        self.scratch_sender = sender
-        self.instruments = instruments
-        self.values = values  
-        logging.info("Started listener on port %s" % device)
-
-    def join(self,timeout=None):
-        self._stop.set()
-        threading.Thread.join(self, timeout)
-
-    def stopped(self):
-        return self._stop.isSet()
-
-    def run(self):
-        self.arduino_device.readline() # discard the first (partial) line
-        while not self.stopped():
-            logging.debug('Thread waiting for a signal')
-            try:
-                device_line = self.arduino_device.readline()
-                if device_line :
-                    instrument, instrument_value_string = device_line.rstrip().split(',', 1)
-                    instrument_value = int(instrument_value_string)
-                    logging.info('Instrument: %s, Value: %d' % (instrument, instrument_value))
-                    if instrument in self.values:
-                        try:
-                            logging.info("sensor-update %s %d" % (self.values[instrument], (instrument_value * 100) / 1024))
-                            self.scratch_sender.send_scratch_command("sensor-update %s %d" % (self.values[instrument], (instrument_value * 100) / 1024))
-                        except KeyError:
-                            # Do nothing
-                            pass
-                    if instrument in self.instruments:
-                        if isinstance(self.instruments[instrument], dict):
-                            broadcast = self.instruments[instrument][instrument_value]
-                        else:
-                            broadcast = self.instruments[instrument]
-                        try:
-                            logging.info("broadcast %s" % broadcast)
-                            self.scratch_sender.send_scratch_command('broadcast %s' % broadcast)
-                        except KeyError:
-                            # Do nothing
-                            pass
-
-            except serial.SerialException:
-                logging.error('Serial exception')
-        logging.debug('Thread run() exiting')
-
-
-def create_socket(host, port):
-    while True:
-        try:
-            logging.info('Connecting to Scratch')
-            scratch_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-            scratch_sock.connect((host, port))
-            break
-        except socket.error:
-            logging.warning("There was an error connecting to Scratch!")
-            logging.warning("I couldn't find a Mesh session at host: %s, port: %s" % (host, port))
-            time.sleep(3)
-    return scratch_sock
-
-def cleanup_threads(threads):
-    logging.debug("Stopping %d threads" % len(threads))
-    for thread in threads:
-        thread.join()
-    logging.debug("Threads joined")
-
-if __name__ == '__main__':
-    if len(sys.argv) > 1:
-        host = sys.argv[1]
-    else:
-        host = DEFAULT_HOST
-
-cycle_trace = 'start'
-while True:
-    if (cycle_trace == 'disconnected'):
-        logging.info("Scratch disconnected")
-        cleanup_threads(listeners + sender)
-        time.sleep(1)
-        cycle_trace = 'start'
-
-    if (cycle_trace == 'start'):
-        # open the socket
-        logging.info('Connecting to Scratch...')
-        the_socket = create_socket(host, PORT)
-        logging.info('Connected to Scratch')
-        the_socket.settimeout(SOCKET_TIMEOUT)
-        sender = ScratchSender(the_socket)
-        listeners = [ArduinoListener(device, ARDUINO_BAUD_RATE, sender, BROADCAST_NAMES, SENSOR_NAMES) for device in DEVICES]
-        cycle_trace = 'running'
-        logging.info("Listeners running....")
-        sender.start()
-        for listener in listeners:
-          listener.start()
-
-    # wait for ctrl+c
-    try:
-        #just pause
-        time.sleep(0.1)
-    except KeyboardInterrupt:
-        logging.warning("Interrrupted")
-        cleanup_threads(listeners + [sender])
-        sys.exit()
-
diff --git a/raspberrypi/music-maker.sb b/raspberrypi/music-maker.sb
deleted file mode 100755 (executable)
index 64f848d..0000000
Binary files a/raspberrypi/music-maker.sb and /dev/null differ
diff --git a/release/cymbal.mp3 b/release/cymbal.mp3
new file mode 100644 (file)
index 0000000..e56c01c
Binary files /dev/null and b/release/cymbal.mp3 differ
diff --git a/release/drums/drums.ino b/release/drums/drums.ino
new file mode 100644 (file)
index 0000000..6ebd466
--- /dev/null
@@ -0,0 +1,27 @@
+
+const int NUMBER_OF_DRUMS = 4;
+const int DELAY = 500;
+
+const int PINS[4] = { 8, 9, 10, 11 };
+int pinDelays[4] = { 0, 0, 0, 0 };
+
+void setup() {
+  for (int i = 0; i < NUMBER_OF_DRUMS; i++) {
+    pinMode(PINS[i], INPUT);
+  }
+  Serial.begin(57600);
+}
+
+void loop() {
+  for (int i = 0; i < NUMBER_OF_DRUMS; i++) {
+    if (digitalRead(PINS[i]) == HIGH && pinDelays[i] < 1) {
+      Serial.print("drum,");
+      Serial.println(i);
+      pinDelays[i] = DELAY;
+    }
+    if (pinDelays[i] > 0) {
+      pinDelays[i] -= 1;
+    }
+  }
+}
+
diff --git a/release/guitar.gif b/release/guitar.gif
new file mode 100644 (file)
index 0000000..b453957
Binary files /dev/null and b/release/guitar.gif differ
diff --git a/release/guitar/guitar.ino b/release/guitar/guitar.ino
new file mode 100644 (file)
index 0000000..f9f530c
--- /dev/null
@@ -0,0 +1,26 @@
+
+const int THRESHOLD = 10;
+const int GUITAR_PIN = A0;
+const int PINLIMIT = 5000;
+
+int val;
+int pinDelay;
+
+void setup() {
+  Serial.begin(57600);
+}
+
+void loop() {
+  val = analogRead(GUITAR_PIN);
+  
+  if (val >= THRESHOLD && pinDelay < 1) {
+    Serial.print("guitar,");
+    Serial.println(val);
+    pinDelay = PINLIMIT;
+  }
+    
+  if (pinDelay > 0) {
+    pinDelay = pinDelay - 1;
+  }
+}
+  
diff --git a/release/guitar1.mp3 b/release/guitar1.mp3
new file mode 100644 (file)
index 0000000..09fb0b7
Binary files /dev/null and b/release/guitar1.mp3 differ
diff --git a/release/guitar2.mp3 b/release/guitar2.mp3
new file mode 100644 (file)
index 0000000..9ec4572
Binary files /dev/null and b/release/guitar2.mp3 differ
diff --git a/release/guitar3.mp3 b/release/guitar3.mp3
new file mode 100644 (file)
index 0000000..ca30fc6
Binary files /dev/null and b/release/guitar3.mp3 differ
diff --git a/release/guitar4.mp3 b/release/guitar4.mp3
new file mode 100644 (file)
index 0000000..234a88d
Binary files /dev/null and b/release/guitar4.mp3 differ
diff --git a/release/guitar5.mp3 b/release/guitar5.mp3
new file mode 100644 (file)
index 0000000..d49a932
Binary files /dev/null and b/release/guitar5.mp3 differ
diff --git a/release/hihat.mp3 b/release/hihat.mp3
new file mode 100644 (file)
index 0000000..3bf8094
Binary files /dev/null and b/release/hihat.mp3 differ
diff --git a/release/maracas.gif b/release/maracas.gif
new file mode 100644 (file)
index 0000000..c5cca75
Binary files /dev/null and b/release/maracas.gif differ
diff --git a/release/maracas.mp3 b/release/maracas.mp3
new file mode 100644 (file)
index 0000000..38789a5
Binary files /dev/null and b/release/maracas.mp3 differ
diff --git a/release/maracas/maracas.ino b/release/maracas/maracas.ino
new file mode 100644 (file)
index 0000000..8410aed
--- /dev/null
@@ -0,0 +1,23 @@
+int newState;
+int states[] = {-1,-1};
+const int pins[] = {6, 7};
+const int wait = 500;
+
+void setup() {
+  for (int i = 0; i < 2; i++) {
+    pinMode(pins[i], INPUT);
+  }
+  Serial.begin(57600);
+}
+
+void loop() {
+  for (int i = 0; i < 2; i++) {
+    newState = digitalRead(pins[i]);
+    if (newState != states[i]) {
+      Serial.println("maracas,1023");
+      states[i] = newState;
+      delay(wait);
+    }
+  }
+}
+
diff --git a/release/miniband1.sb b/release/miniband1.sb
new file mode 100644 (file)
index 0000000..6f1be4b
Binary files /dev/null and b/release/miniband1.sb differ
diff --git a/release/miniband2.sb b/release/miniband2.sb
new file mode 100644 (file)
index 0000000..263b9da
Binary files /dev/null and b/release/miniband2.sb differ
diff --git a/release/miniband3.sb b/release/miniband3.sb
new file mode 100644 (file)
index 0000000..39bef79
Binary files /dev/null and b/release/miniband3.sb differ
diff --git a/release/music-maker-handler.py b/release/music-maker-handler.py
new file mode 100755 (executable)
index 0000000..c935c15
--- /dev/null
@@ -0,0 +1,181 @@
+# This code is copyright ...... under the GPL v2.
+# This code is derived from scratch_gpio_handler by Simon Walters, which
+# is derived from scratch_handler by Thomas Preston
+# Version 0.1: It's kind of working.
+
+from array import *
+import threading
+import socket
+import time
+import sys
+import struct
+import serial
+import io
+import datetime as dt
+import logging
+
+PORT = 42001
+DEFAULT_HOST = '127.0.0.1'
+BUFFER_SIZE = 240 #used to be 100
+SOCKET_TIMEOUT = 1
+DEVICES = ['/dev/ttyACM0', '/dev/ttyACM1','/dev/ttyACM3']
+#DEVICES = ['/dev/ttyACM0','/dev/ttyACM1']
+#DRUM_DEVICE = '/dev/ttyACM0'
+#GUITAR_DEVICE = '/dev/ttyUSB1'
+#MARACAS_DEVICE = '/dev/ttyACM1'
+ARDUINO_BAUD_RATE = 57600
+
+BROADCAST_NAMES = {'guitar': 'guitar', 
+    'drum': {0: 'cymbal',
+        1: 'hihat',
+        2: 'slowdrum',
+        3: 'snare',
+        4: 'tomtom'},
+    'maracas': 'maracas'}
+
+SENSOR_NAMES = {'guitar': 'guitar_pitch'}
+
+logging.basicConfig(level = logging.INFO)
+#logging.basicConfig(level = logging.DEBUG)
+
+class MyError(Exception):
+    def __init__(self, value):
+        self.value = value
+
+    def __str__(self):
+        return repr(self.value)
+
+class ScratchSender(threading.Thread):
+    def __init__(self, socket):
+        threading.Thread.__init__(self)
+        self.scratch_socket = socket
+        self._stop = threading.Event()
+        
+    def join(self,timeout=None):
+        self._stop.set()
+        threading.Thread.join(self, timeout)
+
+    def stopped(self):
+        return self._stop.isSet()
+
+    def run(self):
+        while not self.stopped():
+            time.sleep(0.01) # be kind to cpu - not certain why :)
+
+    def send_scratch_command(self, cmd):
+        n = len(cmd)
+        a = array('c')
+        a.append(chr((n >> 24) & 0xFF))
+        a.append(chr((n >> 16) & 0xFF))
+        a.append(chr((n >>  8) & 0xFF))
+        a.append(chr(n & 0xFF))
+        self.scratch_socket.send(a.tostring() + cmd)
+
+
+class ArduinoListener(threading.Thread):
+    def __init__(self, device, speed, sender, instruments, values):
+        threading.Thread.__init__(self)
+        self.arduino_device = serial.Serial(device, speed, timeout=0.5)
+        self._stop = threading.Event()
+        self.scratch_sender = sender
+        self.instruments = instruments
+        self.values = values  
+        logging.info("Started listener on port %s" % device)
+
+    def join(self,timeout=None):
+        self._stop.set()
+        threading.Thread.join(self, timeout)
+
+    def stopped(self):
+        return self._stop.isSet()
+
+    def run(self):
+        self.arduino_device.readline() # discard the first (partial) line
+        while not self.stopped():
+            logging.debug('Thread waiting for a signal')
+            try:
+                device_line = self.arduino_device.readline()
+                if device_line :
+                    instrument, instrument_value_string = device_line.rstrip().split(',', 1)
+                    instrument_value = int(instrument_value_string)
+                    logging.info('Instrument: %s, Value: %d' % (instrument, instrument_value))
+                    if instrument in self.values:
+                        try:
+                            logging.info("sensor-update %s %d" % (self.values[instrument], (instrument_value * 100) / 1024))
+                            self.scratch_sender.send_scratch_command("sensor-update %s %d" % (self.values[instrument], (instrument_value * 100) / 1024))
+                        except KeyError:
+                            # Do nothing
+                            pass
+                    if instrument in self.instruments:
+                        if isinstance(self.instruments[instrument], dict):
+                            broadcast = self.instruments[instrument][instrument_value]
+                        else:
+                            broadcast = self.instruments[instrument]
+                        try:
+                            logging.info("broadcast %s" % broadcast)
+                            self.scratch_sender.send_scratch_command('broadcast %s' % broadcast)
+                        except KeyError:
+                            # Do nothing
+                            pass
+
+            except serial.SerialException:
+                logging.error('Serial exception')
+        logging.debug('Thread run() exiting')
+
+
+def create_socket(host, port):
+    while True:
+        try:
+            logging.info('Connecting to Scratch')
+            scratch_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+            scratch_sock.connect((host, port))
+            break
+        except socket.error:
+            logging.warning("There was an error connecting to Scratch!")
+            logging.warning("I couldn't find a Mesh session at host: %s, port: %s" % (host, port))
+            time.sleep(3)
+    return scratch_sock
+
+def cleanup_threads(threads):
+    logging.debug("Stopping %d threads" % len(threads))
+    for thread in threads:
+        thread.join()
+    logging.debug("Threads joined")
+
+if __name__ == '__main__':
+    if len(sys.argv) > 1:
+        host = sys.argv[1]
+    else:
+        host = DEFAULT_HOST
+
+cycle_trace = 'start'
+while True:
+    if (cycle_trace == 'disconnected'):
+        logging.info("Scratch disconnected")
+        cleanup_threads(listeners + sender)
+        time.sleep(1)
+        cycle_trace = 'start'
+
+    if (cycle_trace == 'start'):
+        # open the socket
+        logging.info('Connecting to Scratch...')
+        the_socket = create_socket(host, PORT)
+        logging.info('Connected to Scratch')
+        the_socket.settimeout(SOCKET_TIMEOUT)
+        sender = ScratchSender(the_socket)
+        listeners = [ArduinoListener(device, ARDUINO_BAUD_RATE, sender, BROADCAST_NAMES, SENSOR_NAMES) for device in DEVICES]
+        cycle_trace = 'running'
+        logging.info("Listeners running....")
+        sender.start()
+        for listener in listeners:
+          listener.start()
+
+    # wait for ctrl+c
+    try:
+        #just pause
+        time.sleep(0.1)
+    except KeyboardInterrupt:
+        logging.warning("Interrrupted")
+        cleanup_threads(listeners + [sender])
+        sys.exit()
+
diff --git a/release/scratchthumbs.db b/release/scratchthumbs.db
new file mode 100644 (file)
index 0000000..31aaa37
Binary files /dev/null and b/release/scratchthumbs.db differ
diff --git a/release/slowdrum.mp3 b/release/slowdrum.mp3
new file mode 100644 (file)
index 0000000..1aadcf3
Binary files /dev/null and b/release/slowdrum.mp3 differ
diff --git a/release/snare.mp3 b/release/snare.mp3
new file mode 100644 (file)
index 0000000..eac32da
Binary files /dev/null and b/release/snare.mp3 differ
diff --git a/release/tomtom.mp3 b/release/tomtom.mp3
new file mode 100644 (file)
index 0000000..9520eb5
Binary files /dev/null and b/release/tomtom.mp3 differ
diff --git a/writeup/.directory b/writeup/.directory
new file mode 100644 (file)
index 0000000..cdbb188
--- /dev/null
@@ -0,0 +1,4 @@
+[Dolphin]
+Timestamp=2013,4,19,20,12,1
+Version=3
+ViewMode=1
diff --git a/writeup/drums-script.png b/writeup/drums-script.png
new file mode 100644 (file)
index 0000000..767957b
Binary files /dev/null and b/writeup/drums-script.png differ
diff --git a/writeup/drums.fzz b/writeup/drums.fzz
new file mode 100644 (file)
index 0000000..c44172a
Binary files /dev/null and b/writeup/drums.fzz differ
diff --git a/writeup/drums_bb.png b/writeup/drums_bb.png
new file mode 100644 (file)
index 0000000..857eeb0
Binary files /dev/null and b/writeup/drums_bb.png differ
diff --git a/writeup/drums_schem.png b/writeup/drums_schem.png
new file mode 100644 (file)
index 0000000..22d54d3
Binary files /dev/null and b/writeup/drums_schem.png differ
diff --git a/writeup/enable-remote-sensors.png b/writeup/enable-remote-sensors.png
new file mode 100644 (file)
index 0000000..fa30c52
Binary files /dev/null and b/writeup/enable-remote-sensors.png differ
diff --git a/writeup/guitar.fzz b/writeup/guitar.fzz
new file mode 100644 (file)
index 0000000..78aac9a
Binary files /dev/null and b/writeup/guitar.fzz differ
diff --git a/writeup/guitar_bb.png b/writeup/guitar_bb.png
new file mode 100644 (file)
index 0000000..8966d03
Binary files /dev/null and b/writeup/guitar_bb.png differ
diff --git a/writeup/guitar_schem.png b/writeup/guitar_schem.png
new file mode 100644 (file)
index 0000000..d03ea67
Binary files /dev/null and b/writeup/guitar_schem.png differ
diff --git a/writeup/maracas-script.png b/writeup/maracas-script.png
new file mode 100644 (file)
index 0000000..0f3957b
Binary files /dev/null and b/writeup/maracas-script.png differ
diff --git a/writeup/maracas.fzz b/writeup/maracas.fzz
new file mode 100644 (file)
index 0000000..60941d2
Binary files /dev/null and b/writeup/maracas.fzz differ
diff --git a/writeup/maracas_bb.png b/writeup/maracas_bb.png
new file mode 100644 (file)
index 0000000..77050b0
Binary files /dev/null and b/writeup/maracas_bb.png differ
diff --git a/writeup/maracas_schem.png b/writeup/maracas_schem.png
new file mode 100644 (file)
index 0000000..b766079
Binary files /dev/null and b/writeup/maracas_schem.png differ
diff --git a/writeup/miniband.doc b/writeup/miniband.doc
new file mode 100644 (file)
index 0000000..dfc762d
Binary files /dev/null and b/writeup/miniband.doc differ
diff --git a/writeup/miniband.odt b/writeup/miniband.odt
new file mode 100644 (file)
index 0000000..37a7488
Binary files /dev/null and b/writeup/miniband.odt differ