Finished Trinket/Gemma theremin code (PWM yay!)

This commit is contained in:
Phillip Burgess 2017-10-19 14:06:18 -07:00
parent 7f38c588df
commit 0de9a34f08

View file

@ -6,28 +6,22 @@
# and output tone to GPIO #0 (digital 0)
import board
import pulseio
import analogio
import digitalio
import time
speaker_pin = board.D0 # Speaker is connected to this DIGITAL pin
photocell_pin = board.A1 # CdS photocell connected to this ANALOG pin
speaker_pin = board.D0 # Speaker is connected to this DIGITAL pin
scale = 0.03 # Change this to adjust tone scale
readpin = analogio.AnalogIn(photocell_pin)
writepin = digitalio.DigitalInOut(speaker_pin)
writepin.direction = digitalio.Direction.OUTPUT
# Initialize input/output pins
photocell = analogio.AnalogIn(photocell_pin)
pwm = pulseio.PWMOut(speaker_pin, variable_frequency=True, duty_cycle=0)
while True: # Loop forever...
# Read photocell analog pin and convert voltage to frequency
freq_hz = 220 + readpin.value * scale
delay_amount = 0.5 / freq_hz # 1/2 Frequency
note_start = time.monotonic() # Time when note started
while time.monotonic() - note_start < 0.4: # For 400 milliseconds...
writepin.value = True # Set pin high
time.sleep(delay_amount) # Wait for 1/2 of note frequency
writepin.value = False # Set pin low
time.sleep(delay_amount) # Wait for other 1/2 of note freq.
time.sleep(0.05) # Delay 50 ms between notes (also adjustable)
pwm.frequency = 220 + int(scale * float(photocell.value))
pwm.duty_cycle = 32767 # 50% duty cycle
time.sleep(0.4) # Play for 400 ms (adjust to your liking)
pwm.duty_cycle = 0 # Stop playing
time.sleep(0.05) # Delay 50 ms between notes (also adjustable)