SunFounder ESP32 Starter Kit
(continued from previous page)
buzzer = PWM(Pin(25), duty=0)
# Function to play a tone
def play_tone(frequency, duration):
buzzer.freq(frequency)
buzzer.duty(512)
time.sleep_ms(duration)
buzzer.duty(0)
touch_threshold = 200
# Main loop to check for touch inputs and play the corresponding note
while True:
for i, touch_sensor in enumerate(touch_sensors):
value = touch_sensor.read()
print(i,value)
if value < touch_threshold:
play_tone(notes[i], 100)
time.sleep_ms(50)
time.sleep(0.01)
You can connect fruits to these ESP32 pins: 4, 15, 13, 12, 14, 27, 33, 32.
When the script runs, touching these fruits will play the notes C, D, E, F, G, A, B and C5.
Note: Touch_threshold needs to be adjusted based on the conductivity of different fruits.
You can run the script first to see the values printed by the shell.
0 884
1 801
2 856
3 964
4 991
5 989
6 1072
7 1058
After touching the fruits on pins 12, 14, and 27, the printed values are as follows. Therefore, I set the touch_threshold
to 200, which means that when a value less than 200 is detected, it is considered to be touched, and the buzzer will
emit different notes.
0 882
1 810
2 799
3 109
4 122
5 156
6 1068
7 1055
3.33. 6.1 Fruit Piano 411