linefollower_instruction_site/code_notepad.py

128 lines
2.6 KiB
Python

import board
import pwmio
import time
motorIN1 = pwmio.PWMOut(board.GP8, frequency=1000, duty_cycle=0)
motorIN2 = pwmio.PWMOut(board.GP9, frequency=1000, duty_cycle=0)
# DRIVE FORWARD
motorIN1.duty_cycle = 65535 # This is the maximum value
motorIN2.duty_cycle = 0 # This is the minimum value
time.sleep(1)
# DRIVE BACKWARD
motorIN1.duty_cycle = 0
motorIN2.duty_cycle = 65535
time.sleep(1)
# STOP
motorIN1.duty_cycle = 0
motorIN2.duty_cycle = 0
import board
import pwmio
import time
# Initialize motor PWM pins
motorIN1 = pwmio.PWMOut(board.GP8, frequency=1000, duty_cycle=0)
motorIN2 = pwmio.PWMOut(board.GP9, frequency=1000, duty_cycle=0)
def motor(power):
# Make sure power is never greater than 100 or less than -100
if power > 100:
power = 100
elif power < -100:
power = -100
# Convert 0-100 value, to 0 to 65535
duty = abs(power) * 65535 // 100
# Apply power to a motor pin, depending on if its greater or less than 0
if power > 0:
motorIN1.duty_cycle = duty
motorIN2.duty_cycle = 0
elif power < 0:
motorIN1.duty_cycle = 0
motorIN2.duty_cycle = duty
else:
motorIN1.duty_cycle = 0
motorIN2.duty_cycle = 0
# TESTS
motor(100) # FULL FORWARD
time.sleep(3)
motor(-100) # FULL REVERSE
time.sleep(3)
# Start at FULL REVERSE and slowly change from -100 to 100
for i in range(-100, 100):
motor(i)
print(i)
time.sleep(0.1)
import board
import time
import motor
left_motor = motor.Motor(board.GP8, board.GP9)
# TESTS
left_motor.move(100) # FULL FORWARD
time.sleep(2)
left_motor.move(-100) # FULL REVERSE
time.sleep(2)
left_motor.move(0)
# Start at FULL REVERSE and slowly change from -100 to 100
for i in range(-100, 100):
left_motor.move(i)
print(i)
time.sleep(0.1)
import pwmio
class Motor:
def __init__(self, in1_pin, in2_pin, frequency=1000):
# Set up PWM outputs on the specified pins
self.in1 = pwmio.PWMOut(in1_pin, frequency=frequency, duty_cycle=0)
self.in2 = pwmio.PWMOut(in2_pin, frequency=frequency, duty_cycle=0)
def move(self, power):
# Constrain power to -100 to 100
if power > 100:
power = 100
elif power < -100:
power = -100
# Scale to duty cycle
duty = abs(power) * 65535 // 100
if power > 0:
self.in1.duty_cycle = duty
self.in2.duty_cycle = 0
elif power < 0:
self.in1.duty_cycle = 0
self.in2.duty_cycle = duty
else:
self.in1.duty_cycle = 0
self.in2.duty_cycle = 0