|
3 | 3 | # when an input is touched. Note only one note is played at a time!
|
4 | 4 | # For use with microcontrollers or computers with PWM support only!
|
5 | 5 | # Author: Tony DiCola
|
6 |
| -import time |
| 6 | +# Modified by: Carter Nelson |
7 | 7 |
|
8 | 8 | import board
|
9 | 9 | import busio
|
|
43 | 43 | buzzer = pulseio.PWMOut(BUZZER_PIN, duty_cycle=TONE_OFF_DUTY, frequency=440,
|
44 | 44 | variable_frequency=True)
|
45 | 45 |
|
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 |
52 | 47 | 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 |
58 | 53 | 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