Skip to content

Commit 0e20f6d

Browse files
committed
update piano example
1 parent 07ffe38 commit 0e20f6d

File tree

1 file changed

+15
-26
lines changed

1 file changed

+15
-26
lines changed

examples/piano.py

Lines changed: 15 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +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+
# Modified by: Carter Nelson
67
import time
78

89
import board
@@ -43,31 +44,19 @@
4344
buzzer = pulseio.PWMOut(BUZZER_PIN, duty_cycle=TONE_OFF_DUTY, frequency=440,
4445
variable_frequency=True)
4546

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()
47+
last_note = None
5248
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.
49+
# Get touched state for all pins
50+
touched = mpr121.touched_pins
51+
# If no pins are touched, be quiet
52+
if True not in touched:
53+
last_note = None
5854
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)
55+
continue
56+
# Get index of touched pin
57+
note = touched.index(True)
58+
# Play note if pin is different and has a defined note
59+
if note != last_note and NOTE_FREQS[note] != 0:
60+
last_note = note
61+
buzzer.frequency = NOTE_FREQS[note]
62+
buzzer.duty_cycle = TONE_ON_DUTY

0 commit comments

Comments
 (0)