• Now that all our variables have been set and our functions defined, we can program the main program loop where the actual functionality will be built.
  • We want some way to continuously check for noise into the microphone to know when to sound the current pitch.
  • We can do this with a "while True" loop as the true condition will always be true as long as the program is running and thus will go on as long as the board is on.
  • We record a short clip of audio into the samples array we created earlier.
  • Next we take the RMS of the sample to get our magnitude.
  • We have a print statement here to be able to check our magnitude values in the REPL.
while True:
   #We begin recording samples from the board's mic
   mic.record(samples, len(samples))
   magnitude = normalized_rms(samples)  
   print("mag = ", magnitude) #print the magnitude of the input blowing so we can track values in the serial console
  • Next we will create an "if" statement to check for button presses and track each press.
  • We want a button that moves up pitches and one that moves down pitches.
  • Each time a button is pressed we will have a new NeoPixel value so we must reset the other pixels before setting the new one. Pixels.fill((0,0,0)) does exactly that.
  • To track button presses we will increment the counter by 1 if the up button is pressed and decrement by 1 if the down is pressed.
  • Lastly we need to “debounce” the buttons. When a button is pressed by a human, it’s actually held down for a tiny amount of time that we perceive as just an instant but is actually several thousandths of a second. Thus without debouncing the button it will actually get triggered multiple times when pressed.
  • To prevent this we debounce the button by adding a short delay of 2/10s of a second after a button is pressed.
 #If statements to know when up or down buttons are pushed
   #We will use a counter to track which pitch is selected
   if buttonU.value == True:  # If Up button is pushed then move up a pitch
       pixels.fill((0, 0, 0)) #turn all neopixels off
       counter += 1 #increase the counter by 1
       time.sleep(debounceTime) #to ensure button isn't triggered multiple times in one press we must "debounce" the button by creating a short delay after pressing it
   elif buttonD.value == True: #Do the same for the down button
       pixels.fill((0, 0, 0)) # If Down button is pushed then move down a pitch
       counter -= 1 #decrease counter by one
       time.sleep(debounceTime) #debounce button

This guide was first published on Mar 28, 2018. It was last updated on Mar 28, 2018.

This page (The While Loop) was last updated on Mar 26, 2018.

Text editor powered by tinymce.