CircuitPython for Continuous DC Motors
You can learn the basics of CircuitPython with Circuit Playground Express here.
With the special Crickit support in CircuitPython, it saves you tons of code and makes it really fast to get started.
For in-depth information on using DC motors with CircuitPython, see this page
import time from adafruit_crickit import crickit # Create one motor on seesaw motor port #1 motor = crickit.dc_motor_1 # half speed forward motor.throttle = 0.5 # Wait forever... while True: time.sleep(1)
Use the code above to create a single motor on port #1
- Adjust the speed by changing the
motor.throttle
from-1.0
(backwards full speed), to1.0
(forward full speed) - To stop, use
throttle = 0
- Motor will run forever!
- If the motor is going the wrong way, use a negative number to reverse direction
Stop and Start using Circuit Playground Buttons
You can use the adafruit_circuitplayground.express
library to make quick interactive motor projects, it's got ready-to-go button variables!
from digitalio import DigitalInOut, Pull, Direction from adafruit_crickit import crickit import board # Two onboard CPX buttons for input (low level saves memory) button_a = DigitalInOut(board.BUTTON_A) button_a.direction = Direction.INPUT button_a.pull = Pull.DOWN button_b = DigitalInOut(board.BUTTON_B) button_b.direction = Direction.INPUT button_b.pull = Pull.DOWN # Create one motor on seesaw motor port #1 motor = crickit.dc_motor_1 while True: if button_a.value: print("Button A pressed, go!") motor.throttle = 1.0 # full speed! if button_b.value: print("Button B pressed, stop!") motor.throttle = 0 # stop!
In this example above, one button makes the motor run. The other button will make the motor stop.
Using the Circuit Playground Slide Switch to Change Motor Direction
Unlike MakeCode, we don't have the 'inverted' block, instead, we can keep track of the speed we want for our motor in a variable called motor_speed
, then when we check the switch we can assign the throttle
the positive version of that speed, or the negative of it!
import time from digitalio import DigitalInOut, Direction, Pull from adafruit_crickit import crickit import board # Set up slide switch switch = DigitalInOut(board.SLIDE_SWITCH) switch.direction = Direction.INPUT switch.pull = Pull.UP # Create one motor on seesaw motor port #1 motor = crickit.dc_motor_1 motor_speed = 1.0 # full speed! while True: if switch.value: motor.throttle = motor_speed # positive, forwards! else: motor.throttle = - motor_speed # negative means backwards! # small delay to keep from sending crickit tons of messages time.sleep(0.1)
Text editor powered by tinymce.