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