Skip to content

Commit 29c922e

Browse files
authored
Merge pull request #10 from caternuson/example_update
Update piano example
2 parents 07ffe38 + b16425e commit 29c922e

File tree

1 file changed

+15
-27
lines changed

1 file changed

+15
-27
lines changed

examples/piano.py

Lines changed: 15 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
# when an input is touched. Note only one note is played at a time!
44
# For use with microcontrollers or computers with PWM support only!
55
# Author: Tony DiCola
6-
import time
6+
# Modified by: Carter Nelson
77

88
import board
99
import busio
@@ -43,31 +43,19 @@
4343
buzzer = pulseio.PWMOut(BUZZER_PIN, duty_cycle=TONE_OFF_DUTY, frequency=440,
4444
variable_frequency=True)
4545

46-
# Main loop.
47-
# First grab an initial touch state for all of the inputs. The touched()
48-
# function can quickly get the state of all input pins and returns them as a
49-
# 12-bit value with a bit set to 1 for each appropriate input (i.e. bit 0 is
50-
# input 0, bit 1 is input 1, etc.)
51-
last = mpr121.touched()
46+
last_note = None
5247
while True:
53-
# Every loop iteration get an updated touch state and look to see if it
54-
# changed since the last iteration.
55-
current = mpr121.touched()
56-
if last != current:
57-
# Some pin changed, turn off playback and look for any touched pins.
48+
# Get touched state for all pins
49+
touched = mpr121.touched_pins
50+
# If no pins are touched, be quiet
51+
if True not in touched:
52+
last_note = None
5853
buzzer.duty_cycle = TONE_OFF_DUTY
59-
# Loop through all 12 inputs (0-11) and look at their bits in the
60-
# current touch state. A bit that's set is touched!
61-
for i in range(12):
62-
if (1 << i) & current > 0:
63-
print('Input {} touched!'.format(i))
64-
# Grab the frequency for the associated pin and check that it's
65-
# not zero (unused).
66-
freq = NOTE_FREQS[i]
67-
if freq != 0:
68-
# Pin with a specified frequency was touched, play the tone!
69-
buzzer.frequency = NOTE_FREQS[i]
70-
buzzer.duty_cycle = TONE_ON_DUTY
71-
# Update touch state and delay a bit before next loop iteration.
72-
last = current
73-
time.sleep(0.01)
54+
continue
55+
# Get index of touched pin
56+
note = touched.index(True)
57+
# Play note if pin is different and has a defined note
58+
if note != last_note and NOTE_FREQS[note] != 0:
59+
last_note = note
60+
buzzer.frequency = NOTE_FREQS[note]
61+
buzzer.duty_cycle = TONE_ON_DUTY

0 commit comments

Comments
 (0)