code.py
 1  # SPDX-FileCopyrightText: 2018 Dave Astels for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  import time
 6  import board
 7  import pwmio
 8  
 9  C4     = 261
10  C_SH_4 = 277
11  D4     = 293
12  D_SH_4 = 311
13  E4     = 329
14  F4     = 349
15  F_SH_4 = 369
16  G4     = 392
17  G_SH_4 = 415
18  A4     = 440
19  A_SH_4 = 466
20  B4     = 493
21  
22  twinkle = [(C4, 0.5), (C4, 0.5), (G4, 0.5), (G4, 0.5), (A4, 0.5), (A4, 0.5), (G4, 0.5), (0, 0.5),
23             (F4, 0.5), (F4, 0.5), (E4, 0.5), (E4, 0.5), (D4, 0.5), (D4, 0.5), (C4, 0.5)]
24  
25  def play_note(note):
26      if note[0] != 0:
27          pwm = pwmio.PWMOut(board.D12, duty_cycle = 0, frequency=note[0])
28          # Hex 7FFF (binary 0111111111111111) is half of the largest value for a 16-bit int,
29          # i.e. 50%
30          pwm.duty_cycle = 0x7FFF
31      time.sleep(note[1])
32      if note[0] != 0:
33          pwm.deinit()
34  
35  def play_song(song):
36      for note in song:
37          play_note(note)
38  
39  play_song(twinkle)