Black Lives Matter - Action and Equality.
0

while true: execute different operations at the same time
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

while true: execute different operations at the same time

by astro85 on Wed May 13, 2020 2:10 pm

Hello, i try the search option in the forum before post my question, but i was unable to find anything. I'm a beginner python and programmer. Is it possible inside a while true cycle execute different operation at the same time? For example, while true: block of code that do task n.1 and block of code that do task n.2 performed simultaneously. I want to program my board (in may case a playground express) to play a .wav file and in the same time using the microphone to control the leds. Is this possible?

Thank for help and support. Ciao

astro85
 
Posts: 2
Joined: Wed May 13, 2020 1:53 pm

Re: while true: execute different operations at the same tim

by mikeysklar on Wed May 13, 2020 2:47 pm

Hello astro85,

Yes, you can have multiple operations going on inside a while True loop.

There are two examples that come to mind for your task. One is to use the CPX loud_sound() function to trigger the LEDs using the mic.

https://learn.adafruit.com/circuitpytho ... ress/sound

Code: Select all | TOGGLE FULL SIZE
 """
This example lights up the NeoPixels on a Circuit Playground Bluefruit in response to a loud sound.
Try snapping or clapping near the board to trigger the LEDs.

NOTE: This example does NOT support Circuit Playground Express.
"""
import time
from adafruit_circuitplayground import cp

while True:
    if cp.loud_sound():
        cp.pixels.fill((50, 0, 50))
        time.sleep(0.2)
    else:
        cp.pixels.fill((0, 0, 0))



Take a look at the Scream Code Guide for how playing a file and using the mic / LEDs can go on concurrently.

https://learn.adafruit.com/the-scream-m ... cuitpython

Code: Select all | TOGGLE FULL SIZE
 import time
import math
import array
import audiobusio
import audioio
import board
from adafruit_crickit import crickit

# Number of samples to read at once.
NUM_SAMPLES = 160

# Remove DC bias before computing RMS.
def normalized_rms(values):
    minbuf = int(mean(values))
    samples_sum = sum(
        float(sample - minbuf) * (sample - minbuf)
        for sample in values
    )

    return math.sqrt(samples_sum / len(values))

def mean(values):
    return sum(values) / len(values)

mic = audiobusio.PDMIn(board.MICROPHONE_CLOCK, board.MICROPHONE_DATA,
                       sample_rate=16000, bit_depth=16)

# Record an initial sample to calibrate. Assume it's quiet when we start.
samples = array.array('H', [0] * NUM_SAMPLES)
mic.record(samples, len(samples))

head_servo = crickit.servo_1
head_servo.set_pulse_width_range(min_pulse=500, max_pulse=2500)
head_servo.angle = 90  # center the head.

# Set audio out on speaker.
a = audioio.AudioOut(board.A0)

# Start playing the file (in the background).
def play_file(wavfile):
    print("Playing scream!")
    with open(wavfile, "rb") as f:
        wav = audioio.WaveFile(f)
        a.play(wav)
        while a.playing:
            head_servo.angle = 60
            time.sleep(.01)
            head_servo.angle = 120
            time.sleep(.01)


while True:
    mic.record(samples, len(samples))
    magnitude = normalized_rms(samples)
    print(((magnitude),))  # formatting is for the Mu plotter.

    if magnitude < 1000:  # it's quiet, do nothing.
        pass
    else:
        print("LOUD")
        head_servo.angle = 60
        time.sleep(.05)
        head_servo.angle = 120
        time.sleep(.05)
        head_servo.angle = 90
        time.sleep(.02)
        play_file("scream_low.wav")
        head_servo.angle = 90
        time.sleep(2)


mikeysklar
 
Posts: 1068
Joined: Mon Aug 01, 2016 8:10 pm

Re: while true: execute different operations at the same tim

by dastels on Wed May 13, 2020 2:52 pm

In general no, CircuitPython does one thing at a time. You can do multiple things in the loop, but generally not at the same time. There are ways to switch back and forth, doing a bit of one thing, then a bit of another. This is called concurrency. There are several guides on learn.adafruit.com that discuss the idea.

In the situation you mention, things are easier as the audioio module will play tones/files in the background letting your python code carry on. See the examples at https://learn.adafruit.com/adafruit-circuit-playground-express/circuitpython-audio-out.

Dave

dastels
 
Posts: 2473
Joined: Tue Oct 20, 2015 3:22 pm

Re: while true: execute different operations at the same tim

by astro85 on Thu May 14, 2020 2:06 pm

Thank you very much, you confirm that CircuitPython does one thing at a time (i think like arduino).

astro85
 
Posts: 2
Joined: Wed May 13, 2020 1:53 pm

Please be positive and constructive with your questions and comments.