300 views|2 replies

6

Posts

3

Resources
The OP
 

【Follow me Season 2 Episode 1】Simple method to achieve [Copy link]

  This post was last edited by Zaizaobabel on 2024-8-28 17:11

Using the Adafruit Circuit Playground Express and 2442 (Servo)


Getting Started Tasks (Required): Build the Development Environment and Light Up the Onboard LED

First visit Circuit Playground Express Download (circuitpython.org) and update the Bootloader first

Copy it directly to the root directory of the USB flash drive that appears after the development board is connected to the computer. Wait for a moment and the development board will automatically restart, then burn CircuitPython, which is similar.

Simple lighting LED

# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""This example lights up the NeoPixels with a rainbow swirl."""
import time
from adafruit_circuitplayground import cp
from rainbowio import colorwheel

color =(255, 0, 0)
light_off=(0,0,0)
# cp.pixels.auto_write = False
cp.pixels.brightness = 0.01
count = 0
while True:
    for j in range(255):
        cp.pixels[count] = color
        if cp.button_a:
            idx = int((count * 256 / len(cp.pixels)+j))
            cp.pixels[count] = colorwheel(idx & 255)
            time.sleep(0.5)
            cp.pixels[count]= light_off
            count += 1
            if count >= cp.pixels.n:
                count = 0
        time.sleep(0.1)
    

# while True:
   
#     cp.pixels[1]=(0,0,245)
#     cp.pixels[0] = (255, 0, 0)

Basic Task 1 (Must Do): Control the onboard colorful LED, light up the marquee and change the color

# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

"""This example lights up the NeoPixels with a rainbow swirl."""
import time
from rainbowio import colorwheel
from adafruit_circuitplayground import cp


def rainbow_cycle(wait):
    for j in range(255):
        for i in range(cp.pixels.n):
            idx = int((i * 256 / len(cp.pixels)) + j)
            cp.pixels[i] = colorwheel(idx & 255)
        cp.pixels.show()
        time.sleep(wait)


cp.pixels.auto_write = False
cp.pixels.brightness = 0.3
while True:
    rainbow_cycle(0.001)  # rainbowcycle with 1ms delay per step

Basic Task 2 (Required): Monitor ambient temperature and light, and display comfort level through onboard LEDs

from adafruit_circuitplayground import cp
import time

while True:
    temperature_c = cp.temperature
    temperature_f = temperature_c * 1.8 + 32
    print("Temperature celsius:", temperature_c)
    print("Temperature fahrenheit:", temperature_f)
    print("Light:", cp.light)
    score = 100
    if cp.light > 25:
        print('The brightness is:',cp.light,'deduct points:',(cp.light-30))
        score -= (cp.light-30)
    if temperature_c > 27:
        score -=(temperature_c-27)*1.5
        print('temperature is:',temperature_c,'deduct points:',(temperature_c-27)*1.5)
    print("now the score is:",score)
    if score<60:
        for i in range(cp.pixels.n):
            cp.pixels[i]=(255,0,0)
    elif score>=60 and score <= 80:
        for i in range(cp.pixels.n):
            cp.pixels[i]=(255,255,0)
    elif score>80:
        for i in range(cp.pixels.n):
            cp.pixels[i]=(0,255,0)
    time.sleep(1)
    

Low brightness is green, medium brightness is yellow, and high brightness is red.

Basic Task 3 (Required): Proximity Detection - Set a safe distance and display it through the onboard LED. When an intrusion is detected, an audible alarm is triggered.

from adafruit_circuitplayground import cp
from adafruit_circuitplayground.express import cpx
from digitalio import DigitalInOut, Direction,Pull
from analogio import AnalogIn
import time
import board

def wheel(pos):
    #input a value 0 to 255 to get a color value.
    #The colors are a transition r - g - b - back to r.
    if(pos<0) or (pos)>255:
        return (0,0,0)
    if pos<85:
        return(int(255-pos*3),int(pos*3),0)
    elif pos<170:
        pos -=85
        return (0,int(255-pos*3),int(pos*3))
    else:
        pos -=170
    return(int(pos*3),0,int(255-pos*3))
cp.pixels.brightness = 0.2
ir_tx = DigitalInOut(board.IR_TX)
ir_tx.direction = Direction.OUTPUT
proximity = AnalogIn(board.IR_PROXIMITY)
while True:
    ir_tx.value=True
    time.sleep(0.1)
    ir_tx.value = False
    proximity_value = proximity.value
    print("proximity Level: %d" % proximity_value)
    max_value=42500
    min_value=31500
    interval_value = (max_value - min_value)/11
    proximity_index = (proximity_value - min_value)//interval_value
    for p in range(10):
        if p<= proximity_index:
            cpx.pixels[p] = tuple(int(c*((10-p%10))/10.0) for c in wheel(25*(p%10)))
        else:
            cpx.pixels[p] = (0,0,0)
    if proximity_index >5:
        cp.play_tone(500,0.5)

I found that the time for emitting infrared and receiving infrared cannot be too short, otherwise unexpected situations will occur.

Advanced task (must do): Make a tumbler - show the different lighting effects during the movement of the tumbler

from adafruit_circuitplayground import cp
from adafruit_circuitplayground.express import cpx
from digitalio import DigitalInOut, Direction,Pull
from analogio import AnalogIn
import time
import board
import math

def wheel(pos):
    #input a value 0 to 255 to get a color value.
    #The colors are a transition r - g - b - back to r.
    if(pos<0) or (pos)>255:
        return (0,0,0)
    if pos<85:
        return(int(255-pos*3),int(pos*3),0)
    elif pos<170:
        pos -=85
        return (0,int(255-pos*3),int(pos*3))
    else:
        pos -=170
    return(int(pos*3),0,int(255-pos*3))
cp.pixels.brightness = 0.2

while True:
    x,y,z=cpx.acceleration
    angle=(2-(math.atan2(x,y)/math.pi+1))*180
    magnitude = math.sqrt(x*x+y*y)
    print(
        "Accelerometer:(%0.1f,%0.1f,%0.1f) m/s^2;Angle:%0.1f,Magnitude:%0.1f"
        % (x,y,z,angle,magnitude)
    )
    if magnitude >2:
        magnitude = min(magnitude,9.8)
        for p in range(10):
            if p==(angle*10//360):
                cpx.pixels[p]=tuple(
                    int(c*((10-p%10))/10.0) for c in wheel(25*(p%10))
                )
            else:
                cpx.pixels[p] =(0,0,0)
                
  1. Read accelerometer data : Read the acceleration values in the x, y, and z directions of the accelerometer.
  2. Calculate angle and magnitude : Calculate the angle and magnitude based on the acceleration values in the x and y directions.
  3. Control the NeoPixel light ring : Control the color of the NeoPixel light ring based on changes in angle and size.
  4. Loop : Repeat the above steps every second.

Creative Task 2: Squidward - Squidward's tentacles can expand or contract according to the size of the surrounding sound.

from adafruit_circuitplayground import cp
from adafruit_circuitplayground.express import cpx
from digitalio import DigitalInOut, Direction,Pull
import digitalio
import audiobusio
from analogio import AnalogIn
import time
import board
import math
import pwmio
from adafruit_motor import servo
import array


# 定义辅助函数
def mean(values):
    return sum(values) / len(values)

def normalized_rms(values):
    minbuf = int(mean(values))
    sum_of_samples = sum(
        float(sample - minbuf) * (sample - minbuf) for sample in values
    )

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

# 初始化麦克风
mic = audiobusio.PDMIn(
    board.MICROPHONE_CLOCK, board.MICROPHONE_DATA, sample_rate=16000, bit_depth=16
)

# 初始化音频样本数组
samples = array.array("H", [0] * 320)

reachout = False

# # create a PWMOut object on Pin A2.
# pwm = pwmio.PWMOut(board.A2, duty_cycle=2 ** 15, frequency=50)

# # Create a servo object, my_servo.
# my_servo = servo.Servo(pwm)

# create a PWMOut object on Pin A2.
pwm = pwmio.PWMOut(board.A2, frequency=50)

# Create a servo object, my_servo.
my_servo = servo.ContinuousServo(pwm)

temp = 'quiet'
while True:
    mic.record(samples, len(samples))
    sound_value = normalized_rms(samples)
    max_value = 1500
    min_value = 150
    sound_value = min(sound_value, max_value)
    sound_value = max(sound_value, min_value)
    time.sleep(0.5)
    
    if cp.switch:
        if sound_value > 300:
            
            if temp == 'quiet':
                print("Sound is loud.")
                temp = 'loud'
        
            if not reachout:
               
                my_servo.throttle = 1.0
                reachout = True
                print("Sound Level: %d" % sound_value)
                print(reachout)
                print('reaching out')
                time.sleep(0.5)
                my_servo.throttle = 0.0
                time.sleep(0.5)
            
        else:
            if temp == 'loud':
                print("Sound is quiet.")
                temp = 'quiet'
            
            if reachout:
               
                my_servo.throttle = -1.0
                print("Sound Level: %d" % sound_value)
                print(reachout)
                print('withdrawing')
                
                reachout = False
                
            
            time.sleep(0.5)
            my_servo.throttle = 0.0
            time.sleep(0.5)
            
    else:
        my_servo.throttle = 0.0
        pwm.deinit()  # This will deinitialize the PWM output.
        # Wait a bit before checking the switch again.
        
  1. Import the necessary libraries :

    • adafruit_circuitplayground: Used to access features of the Adafruit Circuit Playground Express or Adafruit Circuit Playground Bluefruit.
    • adafruit_circuitplayground.express: Same as above.
    • digitalio: Provides digital input and output functions.
    • audiobusio: Used to process audio signals.
    • analogio: Provides analog input and output functions.
    • time: Provides time-dependent functions, such as sleep().
    • board: Provides access to hardware ports.
    • math: Provides mathematical operation functions.
    • pwmio: Provide PWM (Pulse Width Modulation) output function.
    • array: Provides efficient array storage.
    • adafruit_motor.servo: Provides servo motor control function.
  2. Define the helper function :

    • mean(values): Calculates the average of a set of values.
    • normalized_rms(values): Calculates the normalized root mean square (RMS) of a set of values.
  3. Initialize the microphone :

    • Create a Microphone object using PDMInthe type, specifying the sample rate and bit depth.
  4. Initialize the audio sample array :

    • Create an object containing 320 elements array.arrayto store the sound samples.
  5. Initialize the servo motor :

    • Create an PWMOutobject, specifying the frequency.
    • Create a continuous rotation servo motor object ContinuousServo.
  6. Define variables :

    • reachout: Used to track whether the servo is extending.
    • temp: Used to record the state of sound (noisy or quiet).
  7. Main loop :

    • Continuously record sound samples and use normalized_rmsa function to calculate the intensity of the sound.
    • Set the maximum and minimum acceptable sound level range.
    • If the sound intensity exceeds the threshold (300), then the following actions are performed:
      • Outputs "Sound is loud." and changes tempthe value of the variable.
      • If reachoutso False, the servo motor is driven to rotate forward (extend), then pause, and then stop rotating.
      • If reachoutyes True, log "reaching out".
    • If the sound intensity is below the threshold (300), then do the following:
      • Outputs "Sound is quiet." and changes tempthe value of the variable.
      • If reachoutyes True, the servo motor is driven to reverse (retract), then pause, and then stop rotating.
      • If reachoutyes False, log "withdrawing".
    • If the slide switch is closed, the servo motor is stopped and the PWM output is canceled.

The main function of this program is to make the servo motor extend when it detects a loud enough sound, and retract when the sound stops. It uses the microphone and slide switch on the Circuit Playground Express/Bluefruit board, and the PWM output to control the servo motor.

PS: I am only a beginner in embedded development, so I still have some problems. For example, I don't know why this servo sometimes moves very slowly when it shouldn't.

Source code download

source code

This post is from DigiKey Technology Zone
 
 

6

Posts

3

Resources
2
 
This post was last edited by Zaizaobabel on 2024-8-28 17:20

I forgot to post the video of the proximity detection.

This post is from DigiKey Technology Zone
 
 
 

6

Posts

3

Resources
3
 
 
 

Guess Your Favourite
Just looking around
Find a datasheet?

EEWorld Datasheet Technical Support

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京B2-20211791 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号
快速回复 返回顶部 Return list