code.py
 1  # SPDX-FileCopyrightText: 2019 Carter Nelson for Adafruit Industries
 2  #
 3  # SPDX-License-Identifier: MIT
 4  
 5  import time
 6  import array
 7  import board
 8  import audiobusio
 9  
10  #---| User Configuration |---------------------------
11  SAMPLERATE = 16000
12  SAMPLES = 1024
13  THRESHOLD = 100
14  MIN_DELTAS = 5
15  DELAY = 0.2
16  #----------------------------------------------------
17  
18  # Create a buffer to record into
19  samples = array.array('H', [0] * SAMPLES)
20  
21  # Setup the mic input
22  mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK,
23                         board.MICROPHONE_DATA,
24                         sample_rate=SAMPLERATE,
25                         bit_depth=16)
26  
27  while True:
28      # Get raw mic data
29      mic.record(samples, SAMPLES)
30  
31      # Compute DC offset (mean) and threshold level
32      mean = int(sum(samples) / len(samples) + 0.5)
33      threshold = mean + THRESHOLD
34  
35      # Compute deltas between mean crossing points
36      # (this bit by Dan Halbert)
37      deltas = []
38      last_xing_point = None
39      crossed_threshold = False
40      for i in range(SAMPLES-1):
41          sample = samples[i]
42          if sample > threshold:
43              crossed_threshold = True
44          if crossed_threshold and sample < mean:
45              if last_xing_point:
46                  deltas.append(i - last_xing_point)
47              last_xing_point = i
48              crossed_threshold = False
49  
50      # Try again if not enough deltas
51      if len(deltas) < MIN_DELTAS:
52          continue
53  
54      # Average the deltas
55      mean = sum(deltas) / len(deltas)
56  
57      # Compute frequency
58      freq = SAMPLERATE / mean
59  
60      print("crossings: {}  mean: {}  freq: {} ".format(len(deltas), mean, freq))
61  
62      time.sleep(DELAY)