code.py
 1  # SPDX-FileCopyrightText: 2018 Kattni Rembor for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  """CircuitPython Essentials Audio Out tone example"""
 6  import time
 7  import array
 8  import math
 9  import board
10  import digitalio
11  from audiocore import RawSample
12  
13  try:
14      from audioio import AudioOut
15  except ImportError:
16      try:
17          from audiopwmio import PWMAudioOut as AudioOut
18      except ImportError:
19          pass  # not always supported by every board!
20  
21  button = digitalio.DigitalInOut(board.A1)
22  button.switch_to_input(pull=digitalio.Pull.UP)
23  
24  tone_volume = 0.1  # Increase this to increase the volume of the tone.
25  frequency = 440  # Set this to the Hz of the tone you want to generate.
26  length = 8000 // frequency
27  sine_wave = array.array("H", [0] * length)
28  for i in range(length):
29      sine_wave[i] = int((1 + math.sin(math.pi * 2 * i / length)) * tone_volume * (2 ** 15 - 1))
30  
31  audio = AudioOut(board.A0)
32  sine_wave_sample = RawSample(sine_wave)
33  
34  while True:
35      if not button.value:
36          audio.play(sine_wave_sample, loop=True)
37          time.sleep(1)
38          audio.stop()