【Follow me Season 2 Episode 1】Basic Task 3: Onboard LED display, sound alarm when intrusion is detected
[Copy link]
Task understanding
Although there are various sensors on the CPX development board, the distance sensor does not appear on the development board.
So for this task, I used the ambient light sensor A8 to sense the approach of objects.
When the brightness drops to the threshold, the red light strip lights up and the buzzer A0 sounds an alarm.
Code section
1. Buzzer speaker.py [Source ]
import time
import array
import math
import board
import digitalio
from audiocore import RawSample
from audioio import AudioOut
FREQUENCY = 550 # 440 Hz middle 'A'
SAMPLERATE = 8000 # 8000 samples/second, recommended!
# Generate one period of sine wav.
length = SAMPLERATE // FREQUENCY
sine_wave = array.array("H", [0] * length)
for i in range(length):
sine_wave[i] = int(math.sin(math.pi * 2 * i / length) * (2 ** 15) + 2 ** 15)
# Enable the speaker
speaker_enable = digitalio.DigitalInOut(board.SPEAKER_ENABLE)
speaker_enable.direction = digitalio.Direction.OUTPUT
speaker_enable.value = True
audio = AudioOut(board.SPEAKER)
def make_sound():
sine_wave_sample = RawSample(sine_wave)
# A single sine wave sample is hundredths of a second long. If you set loop=False, it will play
# a single instance of the sample (a quick burst of sound) and then silence for the rest of the
# duration of the time.sleep(). If loop=True, it will play the single instance of the sample
# continuously for the duration of the time.sleep().
audio.play(sine_wave_sample, loop=True) # Play the single sine_wave sample continuously...
time.sleep(1) # for the duration of the sleep (in seconds)
audio.stop() # and then stop.
2. 著代码 code.py
import time
import board
import neopixel
import analogio
from speaker import make_sound
pixels = neopixel.NeoPixel(board.NEOPIXEL, 10, brightness=.01, auto_write=False)
pixels.fill((0, 0, 0))
pixels.show()
light = analogio.AnalogIn(board.LIGHT)
while True:
print(light.value)
if light.value < 2000:
print('light.value under 2000')
for i in range(0, 10, 1):
pixels[i] = (255, 0, 0)
pixels.show()
make_sound()
else:
for i in range(0, 10, 1):
pixels[i] = (0, 255, 0)
pixels.show()
time.sleep(0.01)
Main logic
1. speaker.py comes from the official case, which mainly defines make_sound to use the buzzer
2. In the main code, the main purpose is to obtain the ambient light sensor value. When it is lower than 2000, the color of the lamp bead is changed and an alarm is sounded.
exhibit
Please refer to the demonstration video
|