Initial code with Python stubs for Lego Spike API, Go Robot Code and an example how to structure our code
This commit is contained in:
commit
a58ba5fd6d
18 changed files with 4561 additions and 0 deletions
27
.gitignore
vendored
Normal file
27
.gitignore
vendored
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
|
# C extensions
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Distribution / packaging
|
||||||
|
.Python
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
48
README.md
Normal file
48
README.md
Normal file
|
@ -0,0 +1,48 @@
|
||||||
|
|
||||||
|
# Entwickler Setup
|
||||||
|
|
||||||
|
- Installiere VS Code
|
||||||
|
- Installiere Git
|
||||||
|
- Installiere VS Code Extension:
|
||||||
|
https://marketplace.visualstudio.com/items?itemName=PeterStaev.lego-spikeprime-mindstorms-vscode
|
||||||
|
- Clone unsere Code Vorlage aus Git
|
||||||
|
|
||||||
|
In der VSCode Extension pre-compile einstellen:
|
||||||
|
![VSCode Lego Settings](vscode-lego-extension-settings.png "VSCode Lego Settings")
|
||||||
|
![VSCode Lego Precompile](vscode-lego-extension-precompile.png "VSCode Lego Precompile")
|
||||||
|
|
||||||
|
# Code auf den Spike laufen lassen
|
||||||
|
|
||||||
|
1. Über die VSCode Extension auf einen Slot hochladen (Extension Button oder F1->LEGO)
|
||||||
|
2. Slot starten (kann auch über die "autostart" Option im Kopf des Codes automatisiert werden)
|
||||||
|
|
||||||
|
```
|
||||||
|
# LEGO type:standard slot:5 autostart
|
||||||
|
```
|
||||||
|
|
||||||
|
# Code als gemeinsame Bibiothek entwickeln und auf dem Spike ausführen
|
||||||
|
|
||||||
|
1. Eigene Python Datei anlegen zB `meincode.py`
|
||||||
|
2. Auf einen Slot hochladen (am besten Pre-Compile unter VS Code Settings einstellen, siehe Entwickeler Setup)
|
||||||
|
3. `importFile` Funktion aus der `main.py` nutzen:
|
||||||
|
|
||||||
|
```
|
||||||
|
importFile(slotid=6, precompiled=True, module_name="meincode")
|
||||||
|
import meincode as mc
|
||||||
|
print(mc.HELLO)
|
||||||
|
```
|
||||||
|
|
||||||
|
Siehe auch
|
||||||
|
https://forums.firstinspires.org/forum/general-discussions/first-programs/first-lego-league/the-challenge/programming-ab/93873-spike-prime-programming-lessons-for-first-lego-league-challenge-teams
|
||||||
|
|
||||||
|
|
||||||
|
# Project Setup History
|
||||||
|
|
||||||
|
```
|
||||||
|
git clone https://github.com/fluffyhuskystudio/spike-prime-api.git
|
||||||
|
mkdir spike-all-py
|
||||||
|
cd spike-all-py
|
||||||
|
cp -r ../spike-prime-api/hub ./
|
||||||
|
cp -r ../spike-prime-api/spike ./
|
||||||
|
```
|
||||||
|
|
984
gorobot.py
Normal file
984
gorobot.py
Normal file
|
@ -0,0 +1,984 @@
|
||||||
|
# LEGO type:standard slot:3 autostart
|
||||||
|
|
||||||
|
import math
|
||||||
|
from spike import PrimeHub, Motor, MotorPair, ColorSensor
|
||||||
|
from spike.control import wait_for_seconds, Timer
|
||||||
|
from hub import battery
|
||||||
|
hub = PrimeHub()
|
||||||
|
|
||||||
|
|
||||||
|
import hub as hub2
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
Initialize motor and color Sensors
|
||||||
|
"""
|
||||||
|
# adjust the sensor ports until they match your configuration,
|
||||||
|
# we recommend assigning your ports to the ones in the program for ease of use
|
||||||
|
colorE = ColorSensor('E')
|
||||||
|
colorF = ColorSensor('E')
|
||||||
|
smallMotorA = Motor('A')
|
||||||
|
smallMotorD = Motor('B')
|
||||||
|
|
||||||
|
#Preperation for parallel code execution
|
||||||
|
accelerate = True
|
||||||
|
run_generator = True
|
||||||
|
runSmall = True
|
||||||
|
|
||||||
|
lastAngle = 0
|
||||||
|
oldAngle = 0
|
||||||
|
|
||||||
|
gyroValue = 0
|
||||||
|
|
||||||
|
# Create your objects here.
|
||||||
|
hub = PrimeHub()
|
||||||
|
|
||||||
|
#PID value Definition
|
||||||
|
pRegler = 0.0
|
||||||
|
iRegler = 0.0
|
||||||
|
dRegler = 0.0
|
||||||
|
|
||||||
|
pReglerLight = 0.0
|
||||||
|
iReglerLight = 0.0
|
||||||
|
dReglerLight = 0.0
|
||||||
|
|
||||||
|
#Set variables based on robot
|
||||||
|
circumference = 17.6 #circumference of the wheel powered by the robot in cm
|
||||||
|
sensordistance = 7 #distance between the two light sensors in cm. Used in Tangent alignment 6.4 in studs
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
cancel = False
|
||||||
|
inMain = True
|
||||||
|
|
||||||
|
class DriveBase:
|
||||||
|
|
||||||
|
def __init__(self, hub, leftMotor, rightMotor):
|
||||||
|
self.hub = hub
|
||||||
|
self.leftMotor = Motor(leftMotor)
|
||||||
|
self.rightMotor = Motor(rightMotor)
|
||||||
|
self.movement_motors = MotorPair(leftMotor, rightMotor)
|
||||||
|
|
||||||
|
def lineFollower(self, distance, startspeed, maxspeed, endspeed, sensorPort, side, addspeed = 0.2, brakeStart = 0.7 , stopMethod=None, generator = None, stop = True):
|
||||||
|
"""
|
||||||
|
This is the function used to let the robot follow a line until either the entered distance has been achieved or the other sensor of the robot senses a line.
|
||||||
|
Like all functions that drive the robot this function has linear acceleration and breaking. It also uses PID values that are automatically set depending on the
|
||||||
|
current speed of the robot (See function PIDCalculationLight)
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
distance: The value tells the program the distance the robot has to drive. Type: Integer. Default: No default value
|
||||||
|
speed: The speed which the robot is supposed to start at. Type: Integer. Default: No default value
|
||||||
|
maxspeed: The highest speed at which the robot drives. Type: Integer. Default: No default value
|
||||||
|
endspeed: The speed which the robot achieves at the end of the function. Type: Integer. Default: No default value
|
||||||
|
addspeed: The percentage after which the robot reaches its maxspeed. Type: Float. Default: No default value
|
||||||
|
brakeStart: The value which we use to tell the robot after what percentage of the distance we need to slow down. Type: Float. Default: No default value
|
||||||
|
stopMethod: the Stopmethod the robot uses to stop. If no stopMethod is passed stopDistance is used instead. Default: stopDistance
|
||||||
|
generator: the generator that runs something parallel while driving. Default: No default value
|
||||||
|
stop: the boolean that determines whether the robot should stop the motors after driving or not. Default: True
|
||||||
|
"""
|
||||||
|
|
||||||
|
if cancel:
|
||||||
|
return
|
||||||
|
|
||||||
|
global run_generator, runSmall
|
||||||
|
|
||||||
|
if generator == None:
|
||||||
|
run_generator = False
|
||||||
|
|
||||||
|
#set the speed the robot starts at
|
||||||
|
speed = startspeed
|
||||||
|
#reset PID values to eliminate bugs
|
||||||
|
change = 0
|
||||||
|
old_change = 0
|
||||||
|
integral = 0
|
||||||
|
#reset the driven distance of the robot to eliminate bugs
|
||||||
|
|
||||||
|
#specifies the color sensor
|
||||||
|
colorsensor = ColorSensor(sensorPort)
|
||||||
|
#Get degrees of motors turned before robot has moved, allows for distance calculation without resetting motors
|
||||||
|
loop = True
|
||||||
|
#Going backwards is not supported on our robot due to the motors then being in front of the colour sensors and the program not working
|
||||||
|
if distance < 0:
|
||||||
|
print('ERR: distance < 0')
|
||||||
|
distance = abs(distance)
|
||||||
|
#Calculate target values for the motors to turn to
|
||||||
|
finalDistance = (distance / 17.6) * 360
|
||||||
|
#Calculate after what distance the robot has to reach max speed
|
||||||
|
accelerateDistance = finalDistance * addspeed
|
||||||
|
deccelerateDistance = finalDistance * (1 - brakeStart)
|
||||||
|
|
||||||
|
invert = 1
|
||||||
|
|
||||||
|
#Calculation of steering factor, depending on which side of the line we are on
|
||||||
|
if side == "left":
|
||||||
|
invert = 1
|
||||||
|
elif side == "right":
|
||||||
|
invert = -1
|
||||||
|
|
||||||
|
#Calculation of the start of the robot slowing down
|
||||||
|
|
||||||
|
self.left_Startvalue = self.leftMotor.get_degrees_counted()
|
||||||
|
self.right_Startvalue = self.rightMotor.get_degrees_counted()
|
||||||
|
drivenDistance = getDrivenDistance(self)
|
||||||
|
|
||||||
|
brakeStartValue = brakeStart * finalDistance
|
||||||
|
while loop:
|
||||||
|
if cancel:
|
||||||
|
print("cancel")
|
||||||
|
break
|
||||||
|
|
||||||
|
if run_generator: #run parallel code execution
|
||||||
|
next(generator)
|
||||||
|
|
||||||
|
#Checks the driven distance as an average of both motors for increased accuracy
|
||||||
|
oldDrivenDistance = drivenDistance
|
||||||
|
drivenDistance = getDrivenDistance(self)
|
||||||
|
#Calculates target value for Robot as the edge of black and white lines
|
||||||
|
old_change = change
|
||||||
|
|
||||||
|
change = colorsensor.get_reflected_light() - 50
|
||||||
|
|
||||||
|
|
||||||
|
#Steering factor calculation using PID, sets new I value
|
||||||
|
|
||||||
|
|
||||||
|
steering = (((change * pReglerLight) + (integral * iReglerLight) + (dReglerLight * (change - old_change)))) * invert
|
||||||
|
integral = change + integral
|
||||||
|
#Calculation of current speed for robot, used for acceleratiion, braking etc.
|
||||||
|
speed = speedCalculation(speed, startspeed, maxspeed, endspeed, accelerateDistance, deccelerateDistance, brakeStartValue, drivenDistance, oldDrivenDistance)
|
||||||
|
|
||||||
|
pidCalculationLight(speed)
|
||||||
|
#PID value updates
|
||||||
|
steering = max(-100, min(steering, 100))
|
||||||
|
|
||||||
|
#Driving using speed values calculated with PID and acceleration for steering, use of distance check
|
||||||
|
self.movement_motors.start_at_power(int(speed), int(steering))
|
||||||
|
|
||||||
|
if stopMethod != None:
|
||||||
|
if stopMethod.loop():
|
||||||
|
loop = False
|
||||||
|
else:
|
||||||
|
if finalDistance < drivenDistance:
|
||||||
|
break
|
||||||
|
|
||||||
|
if stop:
|
||||||
|
self.movement_motors.stop()
|
||||||
|
|
||||||
|
run_generator = True
|
||||||
|
runSmall = True
|
||||||
|
generator = 0
|
||||||
|
return
|
||||||
|
|
||||||
|
def gyroRotation(self, angle, startspeed, maxspeed, endspeed, addspeed = 0.3, brakeStart = 0.7, rotate_mode = 0, stopMethod = None, generator = None, stop = True):
|
||||||
|
"""
|
||||||
|
This is the function that we use to make the robot turn the length of a specific angle or for the robot to turn until it senses a line. Even in this function the robot
|
||||||
|
can accelerate and slow down. It also has Gyrosensor calibrations based on our experimental experience.
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
angle: The angle which the robot is supposed to turn. Use negative numbers to turn counterclockwise. Type: Integer. Default value: No default value
|
||||||
|
startspeed: The speed which the robot is supposed to start at. Type: Integer. Default: No default value
|
||||||
|
maxspeed: The highest speed at which the robot drives. Type: Integer. Default: No default value
|
||||||
|
endspeed: The speed which the robot achieves at the end of the function. Type: Integer. Default: No default value
|
||||||
|
addspeed: The percentage after which the robot reaches the maxspeed. Type: Float. Default: No default value
|
||||||
|
brakeStart: The percentage after which the robot starts slowing down until it reaches endspeed. Type: Float. Default: No default value
|
||||||
|
rotate_mode: Different turning types. 0: Both motors turn, robot turns on the spot. 1: Only the outer motor turns, resulting in a corner. Type: Integer. Default: 0
|
||||||
|
stopMethod: the Stopmethod the robot uses to stop. If no stopMethod is passed stopDistance is used instead. Default: stopDistance
|
||||||
|
generator: the generator that runs something parallel while driving. Default: No default value
|
||||||
|
stop: the boolean that determines whether the robot should stop the motors after driving or not. Default: True
|
||||||
|
"""
|
||||||
|
|
||||||
|
if cancel:
|
||||||
|
return
|
||||||
|
|
||||||
|
global run_generator, runSmall
|
||||||
|
|
||||||
|
if generator == None:
|
||||||
|
run_generator = False
|
||||||
|
|
||||||
|
if rotate_mode == 0:
|
||||||
|
startspeed = abs(startspeed)
|
||||||
|
maxspeed = abs(maxspeed)
|
||||||
|
endspeed = abs(endspeed)
|
||||||
|
|
||||||
|
speed = startspeed
|
||||||
|
|
||||||
|
#set standard variables
|
||||||
|
rotatedDistance = 0
|
||||||
|
steering = 1
|
||||||
|
|
||||||
|
accelerateDistance = abs(angle * addspeed)
|
||||||
|
deccelerateDistance = abs(angle * (1 - brakeStart))
|
||||||
|
|
||||||
|
#gyro sensor calibration
|
||||||
|
angle = angle * (2400/2443) #experimental value based on 20 rotations of the robot
|
||||||
|
|
||||||
|
#Setting variables based on inputs
|
||||||
|
loop = True
|
||||||
|
gyroStartValue = getGyroValue() #Yaw angle used due to orientation of the self.hub. This might need to be changed
|
||||||
|
brakeStartValue = (angle + gyroStartValue) * brakeStart
|
||||||
|
|
||||||
|
#Inversion of steering value for turning counter clockwise
|
||||||
|
if angle < 0:
|
||||||
|
steering = -1
|
||||||
|
|
||||||
|
#Testing to see if turining is necessary, turns until loop = False
|
||||||
|
|
||||||
|
while loop:
|
||||||
|
if cancel:
|
||||||
|
break
|
||||||
|
|
||||||
|
if run_generator: #run parallel code execution
|
||||||
|
next(generator)
|
||||||
|
|
||||||
|
oldRotatedDistance = rotatedDistance
|
||||||
|
rotatedDistance = getGyroValue() #Yaw angle used due to orientation of the self.hub. This might need to be changed
|
||||||
|
|
||||||
|
#Checking for variants
|
||||||
|
#Both Motors turn, robot moves on the spot
|
||||||
|
if rotate_mode == 0:
|
||||||
|
self.movement_motors.start_tank_at_power(int(speed) * steering, -int(speed) * steering)
|
||||||
|
#Only outer motor turns, robot has a wide turning radius
|
||||||
|
|
||||||
|
elif rotate_mode == 1:
|
||||||
|
|
||||||
|
if angle * speed > 0:
|
||||||
|
self.leftMotor.start_at_power(- int(speed))
|
||||||
|
else:
|
||||||
|
self.rightMotor.start_at_power(+ int(speed))
|
||||||
|
|
||||||
|
if stopMethod != None:
|
||||||
|
if stopMethod.loop():
|
||||||
|
loop = False
|
||||||
|
break
|
||||||
|
elif abs(angle) <= abs(rotatedDistance - gyroStartValue):
|
||||||
|
loop = False
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#Stops movement motors for increased accuracy while stopping
|
||||||
|
if stop:
|
||||||
|
self.movement_motors.stop()
|
||||||
|
|
||||||
|
run_generator = True
|
||||||
|
runSmall = True
|
||||||
|
|
||||||
|
return # End of gyroStraightDrive
|
||||||
|
|
||||||
|
def gyroStraightDrive(self, distance, startspeed, maxspeed, endspeed, addspeed = 0.3, brakeStart = 0.7, stopMethod=None, offset = 0, generator = None, stop = True):
|
||||||
|
"""
|
||||||
|
This is the function that we use to make the robot go forwards or backwards without drifting. It can accelerate, it can slow down and there's also PID. You can set the values
|
||||||
|
in a way where you can either drive until the entered distance has been achieved or until the robot senses a line.
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
distance: the distance that the robot is supposed to drive. Type: Integer. Default: No default value
|
||||||
|
speed: The speed which the robot is supposed to start at. Type: Integer. Default: No default value
|
||||||
|
maxspeed: The highest speed at which the robot drives. Type: Integer. Default: No default value
|
||||||
|
endspeed: The speed which the robot achieves at the end of the function. Type: Integer. Default: No default value
|
||||||
|
addspeed: The speed which the robot adds in order to accelerate. Type: Float. Default: 0.2
|
||||||
|
brakeStart: The value which we use to tell the robot after what percentage of the distance we need to slow down. Type: Float. Default: 0.8
|
||||||
|
port: This value tells the program whether the robot is supposed to check for a black line with the specified light snsor. Type: String. Default: 0
|
||||||
|
lightValue: This value tells the program the value the robot should stop at if port sees it. Type: Integer. Default: 0
|
||||||
|
align_variant: Tells the robot to align itself to a line if it sees one. 0: No alignment. 1: standard alignment. 2: tangent based alignment Type: Integer. Default: 0
|
||||||
|
detectLineStart: The value which we use to tell the robot after what percentage of the distance we need to look for the line to drive to. Type: Float. Default: 0
|
||||||
|
offset: The value sends the robot in a direction which is indicated by the value entered. Type: Integer. Default: 0
|
||||||
|
generator: Function executed while robot is executing gyroStraightDrive. Write the wanted function and its parameters here. Type: . Default: 0
|
||||||
|
stopMethod: the Stopmethod the robot uses to stop. If no stopMethod is passed stopDistance is used instead. Default: stopDistance
|
||||||
|
generator: the generator that runs something parallel while driving. Default: No default value
|
||||||
|
stop: the boolean that determines whether the robot should stop the motors after driving or not. Default: True
|
||||||
|
"""
|
||||||
|
|
||||||
|
if cancel:
|
||||||
|
return
|
||||||
|
|
||||||
|
global run_generator, runSmall
|
||||||
|
global pRegler, iRegler, dRegler
|
||||||
|
|
||||||
|
if generator == None:
|
||||||
|
run_generator = False
|
||||||
|
|
||||||
|
#Set starting speed of robot
|
||||||
|
speed = startspeed
|
||||||
|
#Sets PID values
|
||||||
|
|
||||||
|
change = 0
|
||||||
|
old_change = 0
|
||||||
|
integral = 0
|
||||||
|
steeringSum = 0
|
||||||
|
|
||||||
|
invert = -1
|
||||||
|
|
||||||
|
#Sets values based on user inputs
|
||||||
|
loop = True
|
||||||
|
|
||||||
|
|
||||||
|
gyroStartValue = getGyroValue()
|
||||||
|
|
||||||
|
#Error check for distance
|
||||||
|
if distance < 0:
|
||||||
|
print('ERR: distance < 0')
|
||||||
|
distance = abs(distance)
|
||||||
|
|
||||||
|
#Calulation of degrees the motors should turn to
|
||||||
|
#17.6 is wheel circumference in cm. You might need to adapt it
|
||||||
|
rotateDistance = (distance / 17.6) * 360
|
||||||
|
accelerateDistance = rotateDistance * addspeed
|
||||||
|
deccelerateDistance = rotateDistance * (1 - brakeStart)
|
||||||
|
|
||||||
|
#Inversion of target rotation value for negative values
|
||||||
|
if speed < 0:
|
||||||
|
invert = 1
|
||||||
|
|
||||||
|
#Calculation of braking point
|
||||||
|
self.left_Startvalue = self.leftMotor.get_degrees_counted()
|
||||||
|
self.right_Startvalue = self.rightMotor.get_degrees_counted()
|
||||||
|
brakeStartValue = brakeStart * rotateDistance
|
||||||
|
drivenDistance = getDrivenDistance(self)
|
||||||
|
|
||||||
|
while loop:
|
||||||
|
if cancel:
|
||||||
|
break
|
||||||
|
if run_generator: #run parallel code execution
|
||||||
|
next(generator)
|
||||||
|
|
||||||
|
#Calculation of driven distance and PID values
|
||||||
|
oldDrivenDistance = drivenDistance
|
||||||
|
drivenDistance = getDrivenDistance(self)
|
||||||
|
|
||||||
|
pidCalculation(speed)
|
||||||
|
change = getGyroValue() - gyroStartValue #yaw angle used due to orientation of the self.hub
|
||||||
|
|
||||||
|
|
||||||
|
currenSteering = (change * pRegler + integral * iRegler + dRegler * (change - old_change)) + offset + steeringSum*0.02
|
||||||
|
|
||||||
|
currenSteering = max(-100, min(currenSteering, 100))
|
||||||
|
#print("steering: " + str(currenSteering) + " gyro: " + str(change) + " integral: " + str(integral))
|
||||||
|
|
||||||
|
steeringSum += change
|
||||||
|
integral += change - old_change
|
||||||
|
old_change = change
|
||||||
|
|
||||||
|
#Calculation of speed based on acceleration and braking, calculation of steering value for robot to drive perfectly straight
|
||||||
|
speed = speedCalculation(speed, startspeed,maxspeed, endspeed, accelerateDistance, deccelerateDistance, brakeStartValue, drivenDistance, oldDrivenDistance)
|
||||||
|
self.movement_motors.start_at_power(int(speed), invert * int(currenSteering))
|
||||||
|
|
||||||
|
|
||||||
|
if stopMethod != None:
|
||||||
|
if stopMethod.loop():
|
||||||
|
loop = False
|
||||||
|
elif rotateDistance < drivenDistance:
|
||||||
|
loop = False
|
||||||
|
|
||||||
|
|
||||||
|
if stop:
|
||||||
|
self.movement_motors.stop()
|
||||||
|
|
||||||
|
run_generator = True
|
||||||
|
runSmall = True
|
||||||
|
|
||||||
|
return #End of gyroStraightDrive
|
||||||
|
|
||||||
|
def arcRotation(self, radius, angle, startspeed, maxspeed, endspeed, addspeed = 0.3, brakeStart = 0.7, stopMethod=None, generator = None, stop = True):
|
||||||
|
"""
|
||||||
|
This is the function that we use to make the robot drive a curve with a specified radius and to a given angle
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
radius: the radius of the curve the robot is supposed to drive; measured from the outside edge of the casing. Type: Integer. Default: 0
|
||||||
|
angle: the angle that the robot is supposed to rotate on the curve. Type: Integer. Default: 0
|
||||||
|
speed: The speed which the robot is supposed to start at. Type: Integer. Default: No default value
|
||||||
|
maxspeed: The highest speed at which the robot drives. Type: Integer. Default: No default value
|
||||||
|
endspeed: The speed which the robot achieves at the end of the function. Type: Integer. Default: No default value
|
||||||
|
addspeed: The speed which the robot adds in order to accelerate. Type: Float. Default: 0.2
|
||||||
|
brakeStart: The value which we use to tell the robot after what percentage of the distance we need to slow down. Type: Float. Default: 0.8
|
||||||
|
stopMethod: the Stopmethod the robot uses to stop. If no stopMethod is passed stopDistance is used instead. Default: stopDistance
|
||||||
|
generator: the generator that runs something parallel while driving. Default: No default value
|
||||||
|
stop: the boolean that determines whether the robot should stop the motors after driving or not. Default: True
|
||||||
|
"""
|
||||||
|
|
||||||
|
if cancel:
|
||||||
|
print("cancel")
|
||||||
|
return
|
||||||
|
|
||||||
|
global run_generator, runSmall
|
||||||
|
|
||||||
|
if generator == None:
|
||||||
|
run_generator = False
|
||||||
|
|
||||||
|
angle = angle * (336/360) #gyro calibration
|
||||||
|
|
||||||
|
gyroStartValue = getGyroValue()
|
||||||
|
finalGyroValue = gyroStartValue + angle
|
||||||
|
currentAngle = gyroStartValue
|
||||||
|
|
||||||
|
accelerateDistance = abs(angle * addspeed)
|
||||||
|
deccelerateDistance = abs(angle * (1 - brakeStart))
|
||||||
|
brakeStartValue = abs(angle * brakeStart)
|
||||||
|
|
||||||
|
loop = True
|
||||||
|
|
||||||
|
#Calculating the speed ratios based on the given radius
|
||||||
|
if angle * startspeed > 0:
|
||||||
|
speed_ratio_left = (radius+14) / (radius+2) #calculate speed ratios for motors. These will need to be adapted based on your robot design
|
||||||
|
speed_ratio_right = 1
|
||||||
|
else:
|
||||||
|
speed_ratio_left = 1
|
||||||
|
speed_ratio_right = (radius+14) / (radius+2)
|
||||||
|
|
||||||
|
#Calculating the first speed to drive with
|
||||||
|
left_speed = speedCalculation(startspeed, startspeed, maxspeed, endspeed, accelerateDistance, deccelerateDistance, brakeStartValue, 1, 0)
|
||||||
|
right_speed = speedCalculation(startspeed, startspeed , maxspeed , endspeed , accelerateDistance, deccelerateDistance, brakeStartValue, 1, 0)
|
||||||
|
while loop:
|
||||||
|
#when the cancel button is pressed stop the gyrostraight drive directly
|
||||||
|
if cancel:
|
||||||
|
break
|
||||||
|
|
||||||
|
if run_generator: #run parallel code execution
|
||||||
|
next(generator)
|
||||||
|
|
||||||
|
currentAngle = getGyroValue() #Yaw angle used due to orientation of the self.hub. This might need to be changed
|
||||||
|
|
||||||
|
#Calculating the current speed the robot should drive
|
||||||
|
left_speed = speedCalculation(left_speed, startspeed, maxspeed, endspeed, accelerateDistance, deccelerateDistance, brakeStartValue, 1, 0)
|
||||||
|
right_speed = speedCalculation(right_speed, startspeed , maxspeed , endspeed , accelerateDistance, deccelerateDistance, brakeStartValue, 1, 0)
|
||||||
|
|
||||||
|
|
||||||
|
self.movement_motors.start_tank_at_power(int(left_speed* speed_ratio_left), int(right_speed* speed_ratio_right))
|
||||||
|
|
||||||
|
#if there is a stopMethod passed use it and stop the loop if it returns true otherwise check if the robot has rotated to the given angle
|
||||||
|
if stopMethod != None:
|
||||||
|
#print("stoMeth")
|
||||||
|
if stopMethod.loop():
|
||||||
|
loop = False
|
||||||
|
break
|
||||||
|
|
||||||
|
(angle / abs(angle))
|
||||||
|
if finalGyroValue * (angle / abs(angle)) < currentAngle * (angle / abs(angle)):
|
||||||
|
#print("finalGyroValue: " + str(finalGyroValue) + " rotatedDistance: " + str(currentAngle))
|
||||||
|
loop = False
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
#if stop is true then stop the motors otherwise don't stop the motor
|
||||||
|
if stop:
|
||||||
|
self.movement_motors.stop()
|
||||||
|
|
||||||
|
run_generator = True
|
||||||
|
runSmall = True
|
||||||
|
return #End of arcRotation
|
||||||
|
|
||||||
|
def resetGyroValue():
|
||||||
|
global gyroValue
|
||||||
|
hub2.motion.yaw_pitch_roll(0)
|
||||||
|
|
||||||
|
gyroValue = 0
|
||||||
|
|
||||||
|
def getGyroValue():
|
||||||
|
|
||||||
|
#this method is used to return the absolute gyro Angle and the angle returned by this method doesn't reset at 180 degree
|
||||||
|
global lastAngle
|
||||||
|
global oldAngle
|
||||||
|
global gyroValue
|
||||||
|
|
||||||
|
#gets the angle returned by the spike prime program. The problem is the default get_yaw_angle resets at 180 and -179 back to 0
|
||||||
|
angle = hub.motion_sensor.get_yaw_angle()
|
||||||
|
|
||||||
|
if angle != lastAngle:
|
||||||
|
oldAngle = lastAngle
|
||||||
|
|
||||||
|
lastAngle = angle
|
||||||
|
|
||||||
|
if angle == 179 and oldAngle == 178:
|
||||||
|
hub2.motion.yaw_pitch_roll(0)#reset
|
||||||
|
gyroValue += 179
|
||||||
|
angle = 0
|
||||||
|
|
||||||
|
if angle == -180 and oldAngle == -179:
|
||||||
|
hub2.motion.yaw_pitch_roll(0) #reset
|
||||||
|
gyroValue -= 180
|
||||||
|
angle = 0
|
||||||
|
|
||||||
|
return gyroValue + angle
|
||||||
|
|
||||||
|
def getDrivenDistance(data):
|
||||||
|
|
||||||
|
|
||||||
|
#print(str(abs(data.leftMotor.get_degrees_counted() - data.left_Startvalue)) + " .:. " + str(abs(data.rightMotor.get_degrees_counted() - data.right_Startvalue)))
|
||||||
|
|
||||||
|
drivenDistance = (
|
||||||
|
abs(data.leftMotor.get_degrees_counted() - data.left_Startvalue) +
|
||||||
|
abs(data.rightMotor.get_degrees_counted() - data.right_Startvalue)) / 2
|
||||||
|
|
||||||
|
return drivenDistance
|
||||||
|
|
||||||
|
def defaultClass(object, db):
|
||||||
|
object.db = db
|
||||||
|
object.leftMotor = db.leftMotor
|
||||||
|
object.rightMotor = db.rightMotor
|
||||||
|
|
||||||
|
object.left_Startvalue = abs(db.leftMotor.get_degrees_counted())
|
||||||
|
object.right_Startvalue = abs(db.rightMotor.get_degrees_counted())
|
||||||
|
return object
|
||||||
|
|
||||||
|
class stopMethods(): #This class has all our stopmethods for easier coding and less redundancy
|
||||||
|
|
||||||
|
class stopLine():
|
||||||
|
"""
|
||||||
|
Drive until a Line is detected
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
db: the drivebase of the robot
|
||||||
|
port: Port to detect line on
|
||||||
|
lightvalue: Value of the light to detect
|
||||||
|
detectLineDistance: Distance until start detecting a line
|
||||||
|
"""
|
||||||
|
def __init__(self, db, port, lightvalue, detectLineDistance):
|
||||||
|
self = defaultClass(self, db)
|
||||||
|
|
||||||
|
self.port = port
|
||||||
|
self.detectLineDistance = (detectLineDistance / 17.6) * 360
|
||||||
|
|
||||||
|
#if lightvalue bigger 50 stop when lightvalue is higher
|
||||||
|
self.lightvalue = lightvalue
|
||||||
|
|
||||||
|
|
||||||
|
def loop(self):
|
||||||
|
|
||||||
|
|
||||||
|
drivenDistance = getDrivenDistance(self)
|
||||||
|
|
||||||
|
if abs(self.detectLineDistance) < abs(drivenDistance):
|
||||||
|
if self.lightvalue > 50:
|
||||||
|
if ColorSensor(self.port).get_reflected_light() > self.lightvalue:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
if ColorSensor(self.port).get_reflected_light() < self.lightvalue:
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
class stopAlign():
|
||||||
|
"""
|
||||||
|
Drive until a Line is detected
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
db: the drivebase of the robot
|
||||||
|
port: Port to detect line on
|
||||||
|
lightvalue: Value of the light to detect
|
||||||
|
speed: speed at which the robot searches for other line
|
||||||
|
"""
|
||||||
|
def __init__(self, db, lightvalue, speed):
|
||||||
|
self = defaultClass(self, db)
|
||||||
|
self.speed = speed
|
||||||
|
|
||||||
|
|
||||||
|
#if lightvalue bigger 50 stop when lightvalue is higher
|
||||||
|
self.lightValue = lightvalue
|
||||||
|
|
||||||
|
|
||||||
|
def loop(self):
|
||||||
|
|
||||||
|
if colorE.get_reflected_light() < self.lightValue:
|
||||||
|
self.rightMotor.stop()
|
||||||
|
#Turning robot so that other colour sensor is over line
|
||||||
|
while True:
|
||||||
|
|
||||||
|
self.leftMotor.start_at_power(-int(self.speed))
|
||||||
|
|
||||||
|
#Line detection and stopping
|
||||||
|
if colorF.get_reflected_light() < self.lightValue or cancel:
|
||||||
|
self.leftMotor.stop()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
#Colour sensor F sees line first
|
||||||
|
elif colorF.get_reflected_light() < self.lightValue:
|
||||||
|
|
||||||
|
self.leftMotor.stop()
|
||||||
|
|
||||||
|
#Turning robot so that other colour sensor is over line
|
||||||
|
while True:
|
||||||
|
self.rightMotor.start_at_power(int(self.speed))
|
||||||
|
|
||||||
|
#Line detection and stopping
|
||||||
|
if colorE.get_reflected_light() < self.lightValue or cancel:
|
||||||
|
self.rightMotor.stop()
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
class stopTangens():
|
||||||
|
"""
|
||||||
|
Drive until a Line is detected
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
db: the drivebase of the robot
|
||||||
|
port: Port to detect line on
|
||||||
|
lightvalue: Value of the light to detect
|
||||||
|
speed: Distance until start detecting a line
|
||||||
|
"""
|
||||||
|
def __init__(self, db, lightvalue, speed):
|
||||||
|
self.count = 0
|
||||||
|
self = defaultClass(self, db)
|
||||||
|
self.speed = speed
|
||||||
|
#if lightvalue bigger 50 stop when lightvalue is higher
|
||||||
|
self.lightValue = lightvalue
|
||||||
|
self.detectedLineDistance = 0
|
||||||
|
|
||||||
|
self.invert = 1
|
||||||
|
if speed < 0:
|
||||||
|
self.invert = -1
|
||||||
|
|
||||||
|
def loop(self):
|
||||||
|
drivenDistance = getDrivenDistance(self)
|
||||||
|
if colorE.get_reflected_light() < self.lightValue:
|
||||||
|
#measuring the distance the robot has driven since it has seen the line
|
||||||
|
if(self.detectedLineDistance == 0):
|
||||||
|
self.detectedLineDistance = getDrivenDistance(self)
|
||||||
|
self.detectedPort = 'E'
|
||||||
|
|
||||||
|
elif self.detectedPort == 'F':
|
||||||
|
db.movement_motors.stop() #Stops robot with sensor F on the line
|
||||||
|
angle = math.degrees(math.atan(((drivenDistance - self.detectedLineDistance) / 360 * circumference) / sensordistance)) #Calculating angle that needs to be turned using tangent
|
||||||
|
#print("angle: " + str(angle))
|
||||||
|
db.gyroRotation(-angle, self.invert * self.speed, self.invert * self.speed, self.invert * self.speed, rotate_mode=1) #Standard gyrorotation for alignment, but inverting speed values if necessary
|
||||||
|
|
||||||
|
db.movement_motors.stop() #Stopping robot for increased reliability
|
||||||
|
return True
|
||||||
|
|
||||||
|
#Colour sensor F sees line first
|
||||||
|
elif colorF.get_reflected_light() < self.lightValue:
|
||||||
|
#measuring the distnace the robot has driven since it has seen the line
|
||||||
|
if(self.detectedLineDistance == 0):
|
||||||
|
self.detectedLineDistance = drivenDistance
|
||||||
|
self.detectedPort = 'F'
|
||||||
|
|
||||||
|
elif self.detectedPort == 'E':
|
||||||
|
db.movement_motors.stop() #Stops robot with sensor E on the line
|
||||||
|
angle = math.degrees(math.atan(((drivenDistance - self.detectedLineDistance) / 360 * circumference) / sensordistance)) #Calculation angle that needs to be turned using tangent
|
||||||
|
db.gyroRotation(angle, self.invert * self.speed, self.invert * self.speed, self.invert * self.speed, rotate_mode=1) #Standard gyrorotation for alignment, but inverting speed values if necessary
|
||||||
|
db.movement_motors.stop() #Stopping robot for increased reliablity
|
||||||
|
return True
|
||||||
|
|
||||||
|
return False
|
||||||
|
class stopDegree():
|
||||||
|
"""
|
||||||
|
Roates until a certain degree is reached
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
db: the drivebase of the robot
|
||||||
|
angle: the angle to rotate
|
||||||
|
"""
|
||||||
|
def __init__(self, db, angle):
|
||||||
|
self.angle = angle * (336/360)
|
||||||
|
|
||||||
|
self.gyroStartValue = getGyroValue() #Yaw angle used due to orientation of the self.hub.
|
||||||
|
|
||||||
|
|
||||||
|
def loop(self):
|
||||||
|
rotatedDistance = getGyroValue() #Yaw angle used due to orientation of the self.hub.
|
||||||
|
|
||||||
|
if abs(self.angle) <= abs(rotatedDistance - self.gyroStartValue):
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
class stopTime():
|
||||||
|
|
||||||
|
"""
|
||||||
|
Drive until a certain time is reached
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
db: the drivebase of the robot
|
||||||
|
time: the time to drive
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, db, time) -> None:
|
||||||
|
self = defaultClass(self, db)
|
||||||
|
self.time = time
|
||||||
|
self.timer = Timer()
|
||||||
|
self.startTime = self.timer.now()
|
||||||
|
|
||||||
|
def loop(self):
|
||||||
|
if self.timer.now() > self.startTime + self.time:
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
class stopResistance():
|
||||||
|
|
||||||
|
"""
|
||||||
|
Drive until the Robot doesn't move anymore
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
db: the drivebase of the robot
|
||||||
|
restistance: the value the resistance has to be below to stop
|
||||||
|
"""
|
||||||
|
def __init__(self, db, resistance):
|
||||||
|
self = defaultClass(self, db)
|
||||||
|
self.resistance = resistance
|
||||||
|
self.timer = Timer()
|
||||||
|
|
||||||
|
self.startTime = 0
|
||||||
|
self.lower = False
|
||||||
|
self.runs = 0
|
||||||
|
|
||||||
|
def loop(self):
|
||||||
|
|
||||||
|
self.runs += 1
|
||||||
|
motion = abs(hub2.motion.accelerometer(True)[2])
|
||||||
|
|
||||||
|
if motion < self.resistance:
|
||||||
|
self.lower = True
|
||||||
|
|
||||||
|
if self.runs > 15:
|
||||||
|
if self.lower:
|
||||||
|
if self.startTime == 0:
|
||||||
|
self.startTime = self.timer.now()
|
||||||
|
|
||||||
|
if self.timer.now() > self.startTime:
|
||||||
|
return True
|
||||||
|
|
||||||
|
else:
|
||||||
|
self.lower = False
|
||||||
|
return False
|
||||||
|
|
||||||
|
def motorResistance(speed, port, resistancevalue):
|
||||||
|
"""
|
||||||
|
lets the motor stop when it hits an obstacle
|
||||||
|
"""
|
||||||
|
if abs(resistancevalue) > abs(speed):
|
||||||
|
return
|
||||||
|
|
||||||
|
|
||||||
|
if cancel:
|
||||||
|
return
|
||||||
|
|
||||||
|
if port == "A":
|
||||||
|
smallMotorA.start_at_power(speed)
|
||||||
|
while True:
|
||||||
|
old_position = smallMotorA.get_position()
|
||||||
|
wait_for_seconds(0.4)
|
||||||
|
if abs(old_position - smallMotorA.get_position())<resistancevalue or cancel:
|
||||||
|
smallMotorA.stop()
|
||||||
|
print("detected stalling")
|
||||||
|
return
|
||||||
|
|
||||||
|
elif port == "D":
|
||||||
|
smallMotorD.start_at_power(speed)
|
||||||
|
while True:
|
||||||
|
old_position = smallMotorD.get_position()
|
||||||
|
wait_for_seconds(0.4)
|
||||||
|
if abs(old_position - smallMotorD.get_position())<resistancevalue or cancel:
|
||||||
|
smallMotorD.stop()
|
||||||
|
print("detected stalling")
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
print("wrong port selected. Select A or D")
|
||||||
|
return
|
||||||
|
|
||||||
|
def speedCalculation(speed, startspeed, maxspeed, endspeed, accelerateDistance, deccelerateDistance, brakeStartValue, drivenDistance, oldDrivenDistance):
|
||||||
|
"""
|
||||||
|
Used to calculate all the speeds in out programs. Done seperatly to reduce redundancy. Brakes and accelerates
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
speed: The current speed the robot has
|
||||||
|
startspeed: Speed the robot starts at. Type: Integer. Default: No default value.
|
||||||
|
maxspeed: The maximum speed the robot reaches. Type: Integer. Default: No default value.
|
||||||
|
endspeed: Speed the robot aims for while braking, minimum speed at the end of the program. Type: Integer. Default: No default value.
|
||||||
|
addspeed: Percentage of the distance after which the robot reaches the maximum speed. Type: Integer. Default: No default value.
|
||||||
|
brakeStartValue: Percentage of the driven distance after which the robot starts braking. Type: Integer. Default: No default value.
|
||||||
|
drivenDistance: Calculation of the driven distance in degrees. Type: Integer. Default: No default value.
|
||||||
|
"""
|
||||||
|
|
||||||
|
addSpeedPerDegree = (maxspeed - startspeed) / accelerateDistance
|
||||||
|
subSpeedPerDegree = (maxspeed - endspeed) / deccelerateDistance
|
||||||
|
|
||||||
|
|
||||||
|
subtraction = (abs(drivenDistance) - abs(oldDrivenDistance) if abs(drivenDistance) - abs(oldDrivenDistance) >= 1 else 1) * subSpeedPerDegree
|
||||||
|
addition = (abs(drivenDistance) - abs(oldDrivenDistance) if abs(drivenDistance) - abs(oldDrivenDistance) >= 1 else 1) * addSpeedPerDegree
|
||||||
|
|
||||||
|
if abs(drivenDistance) > abs(brakeStartValue):
|
||||||
|
|
||||||
|
if abs(speed) > abs(endspeed):
|
||||||
|
speed = speed - subtraction
|
||||||
|
|
||||||
|
elif abs(speed) < abs(maxspeed):
|
||||||
|
|
||||||
|
speed = speed + addition
|
||||||
|
|
||||||
|
return speed
|
||||||
|
|
||||||
|
def breakFunction(args):
|
||||||
|
"""
|
||||||
|
Allows you to manually stop currently executing round but still stays in main.
|
||||||
|
This is much quicker and more reliable than pressing the center button.
|
||||||
|
"""
|
||||||
|
global cancel, inMain
|
||||||
|
if not inMain:
|
||||||
|
cancel = True
|
||||||
|
|
||||||
|
def pidCalculation(speed):
|
||||||
|
#golbally sets PID values based on current speed of the robot, allows for fast and accurate driving
|
||||||
|
global pRegler
|
||||||
|
global iRegler
|
||||||
|
global dRegler
|
||||||
|
#Important note: These PID values are experimental and based on our design for the robot. You will need to adjust them manually. You can also set them statically as you can see below
|
||||||
|
if speed > 0:
|
||||||
|
pRegler = -0.17 * speed + 12.83
|
||||||
|
iRegler = 12
|
||||||
|
dRegler = 1.94 * speed - 51.9
|
||||||
|
if pRegler < 3.2:
|
||||||
|
pRegler = 3.2
|
||||||
|
else:
|
||||||
|
pRegler = (11.1 * abs(speed))/(0.5 * abs(speed) -7) - 20
|
||||||
|
iRegler = 10
|
||||||
|
#iRegler = 0.02
|
||||||
|
dRegler = 1.15**(- abs(speed)+49) + 88
|
||||||
|
|
||||||
|
def pidCalculationLight(speed):
|
||||||
|
#Sets the PID values for the lineFollower based on current speed. Allows for accurate and fast driving
|
||||||
|
#Important note: these PID values are experimental and based on our design for the robot. You will need to adjust them. See above on how to do so
|
||||||
|
global pReglerLight
|
||||||
|
global dReglerLight
|
||||||
|
|
||||||
|
pReglerLight = -0.04 * speed + 4.11
|
||||||
|
dReglerLight = 0.98 * speed - 34.2
|
||||||
|
#set hard bottom for d value, as otherwise the values don't work
|
||||||
|
if dReglerLight < 5:
|
||||||
|
dReglerLight = 5
|
||||||
|
|
||||||
|
def driveMotor(rotations, speed, port):
|
||||||
|
"""
|
||||||
|
Allows you to drive a small motor in parallel to driving with gyroStraightDrive
|
||||||
|
Parameters
|
||||||
|
-------------
|
||||||
|
rotations: the rotations the motor turns
|
||||||
|
speed: the speed at which the motor turns
|
||||||
|
port: the motor used. Note: this cannot be the same motors as configured in the motor Drivebase
|
||||||
|
"""
|
||||||
|
|
||||||
|
global runSmall
|
||||||
|
global run_generator
|
||||||
|
|
||||||
|
if cancel:
|
||||||
|
runSmall = False
|
||||||
|
run_generator = False
|
||||||
|
|
||||||
|
while runSmall:
|
||||||
|
smallMotor = Motor(port)
|
||||||
|
smallMotor.set_degrees_counted(0)
|
||||||
|
|
||||||
|
loop_small = True
|
||||||
|
while loop_small:
|
||||||
|
drivenDistance = smallMotor.get_degrees_counted()
|
||||||
|
smallMotor.start_at_power(speed)
|
||||||
|
if (abs(drivenDistance) > abs(rotations) * 360):
|
||||||
|
loop_small = False
|
||||||
|
if cancel:
|
||||||
|
loop_small = False
|
||||||
|
yield
|
||||||
|
|
||||||
|
smallMotor.stop()
|
||||||
|
runSmall = False
|
||||||
|
run_generator = False
|
||||||
|
yield
|
||||||
|
|
||||||
|
hub2.motion.yaw_pitch_roll(0)
|
||||||
|
|
||||||
|
db = DriveBase(hub, 'A', 'B') #this lets us conveniently hand over our motors (B: left driver; C: right driver). This is necessary for the cancel function
|
||||||
|
|
||||||
|
def exampleOne():
|
||||||
|
#This example aims to show all the options for following a line. See the specific documentation of the function for further information.
|
||||||
|
db.lineFollower(15, 25, 35, 25, 'E', 'left') #follows the left side of a line on the E sensor for 15cm. Accelerates from speed 25 to 35 and ends on 25 again
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.lineFollower(15, 25, 35, 25, 'E', 'left', 0.4, 0.6) #same line follower as before but with a longer acceleration and breaking period
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.lineFollower(15, 25, 35, 25, 'E', 'left', stopMethod=stopMethods.stopLine(db, 'F', 0.7)) #same linefollower as the first, but this time stopping, when the other sensor sees a black line after at least 70% of the driven distance
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.lineFollower(15, 25, 35, 25, 'E', 'left', stopMethod=stopMethods.stopResistance(db, 20)) #same as first linefollower, but stops when desired resistance is reached. Test the resistance value based on your robot
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
generator = driveMotor(5, 100, 'A')
|
||||||
|
db.lineFollower(15, 25, 35, 25, 'E', 'left', generator=generator) #same as first linefollower, but drives while turning the A-Motor for 5 rotations
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.lineFollower(15, 25, 35, 25, 'E', 'left', stop=False) #same as first linefollower, but does not actively brake the motors. The transistion form this action to the next is then smoother
|
||||||
|
return
|
||||||
|
|
||||||
|
def exampleTwo():
|
||||||
|
#This example aims to show all the options for turning the robot. See the specific documentation of the function for further information.
|
||||||
|
db.gyroRotation(90, 25, 35, 25) #turns the robot 90° clockwise while accelerating from speed 25 to 35 and back down to 25
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.gyroRotation(90, 25, 35, 25, 0.4, 0.5) #same turning as in first rotation but with longer acceleration/braking phase
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.gyroRotation(90, 25, 35, 25, rotate_mode=1) #same turn as in first rotation but this time turning using only one wheel rather than turning on the spot. Your speeds may need to be higher for this
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.gyroRotation(90, 25, 35, 25, stopMethod=stopMethods.stopAlign(db, 25, 25)) #aligns the robot with a line in turning path
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.gyroRotation(90, 25, 35, 25, stopMethod=stopMethods.stopLine(db, 'E', 25, 0.7)) #turns until the robot sees a line on sensor E after at least 70% of turning
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.gyroRotation(90, 25, 35, 25, stopMethod=stopMethods.stopTangens(db, 25, 25)) #aligns the robot like stopAlign but is a bit more precise
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
#remaining parameters are the same as in linefollower. Please refer to exampleOne or the documentation of the individual functions
|
||||||
|
return
|
||||||
|
|
||||||
|
def exampleThree():
|
||||||
|
#This example aims to show all the options for driving in a straight line. See the specific documentation of the function for further information.
|
||||||
|
db.gyroStraightDrive(30, 25, 35, 25) #drives in a straight line for 30cm
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.gyroStraightDrive(30, 25, 55, 25, 0.1, 0.9) #same as first drive, but faster and with harder acceleration/braking
|
||||||
|
hub.left_button.wait_until_pressed()
|
||||||
|
db.gyroStraightDrive(30, 25, 35, 25, offset=15) #same as first drive, but aims 15° in clockwise direction as target orientation
|
||||||
|
#remaining features of code are explained in previous examples. Please refer to exampleOne, exampleTwo and additional documentation within individual functions
|
||||||
|
return
|
||||||
|
|
||||||
|
def exampleFour():
|
||||||
|
#This example aims to show all the options for turning in a large curve. See the specific documentation of the function for further information.
|
||||||
|
db.arcRotation(5, 35, 25, 30, 25) #robot drives 35° on a circle with a radius of 5cm measured from the inside edge of the robot
|
||||||
|
#remaining features of code are explained in previous examples. Please refer to exampleOne, exampleTwo and additional documentation within individual functions
|
||||||
|
return
|
||||||
|
|
||||||
|
def exampleFive():
|
||||||
|
#add your own code here
|
||||||
|
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
def exampleSix():
|
||||||
|
#add your own code here
|
||||||
|
|
||||||
|
|
||||||
|
return
|
||||||
|
|
||||||
|
class bcolors:
|
||||||
|
BATTERY = '\033[32m'
|
||||||
|
BATTERY_LOW = '\033[31m'
|
||||||
|
|
||||||
|
ENDC = '\033[0m'
|
||||||
|
|
||||||
|
pReglerLight = 1.6
|
||||||
|
iReglerLight = 0.009
|
||||||
|
dReglerLight = 16
|
||||||
|
|
||||||
|
accelerate = True
|
||||||
|
|
||||||
|
# see comment for breakFunction
|
||||||
|
#hub2.button.right.callback(breakFunction)
|
||||||
|
|
||||||
|
gyroValue = 0
|
||||||
|
|
||||||
|
|
||||||
|
#Battery voltage printout in console for monitoring charge
|
||||||
|
if battery.voltage() < 8000: #set threshold for battery level
|
||||||
|
print(bcolors.BATTERY_LOW + "battery voltage is too low: " + str(battery.voltage()) + " \n ----------------------------- \n >>>> please charge robot <<<< \n ----------------------------- \n"+ bcolors.ENDC)
|
||||||
|
else:
|
||||||
|
print(bcolors.BATTERY + "battery voltage: " + str(battery.voltage()) + bcolors.ENDC)
|
||||||
|
|
||||||
|
|
||||||
|
db.movement_motors.set_stop_action("hold") #hold motors on wait for increased reliability
|
||||||
|
|
||||||
|
|
||||||
|
print("successfully loaded the Go-Robot code :)")
|
50
hub/__init__.py
Normal file
50
hub/__init__.py
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
from typing import Tuple, overload
|
||||||
|
from hub import port, battery, bluetooth, button, display, motion, sound, supervision
|
||||||
|
from hub.display import Image
|
||||||
|
|
||||||
|
__version__ = 'v1.0.0.0000-0000000'
|
||||||
|
config = {}
|
||||||
|
|
||||||
|
TOP = 0
|
||||||
|
FRONT = 1
|
||||||
|
RIGHT = 2
|
||||||
|
BOTTOM = 3
|
||||||
|
BACK = 4
|
||||||
|
LEFT = 5
|
||||||
|
|
||||||
|
def info() -> dict:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def status() -> dict:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def temperature() -> float:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def power_off(fast=True, restart=False):
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def power_off(timeout=0):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def repl_restart(restart: bool):
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def led(color: int):
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def led(red: int, green: int, blue: int):
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def led(color: Tuple[int, int, int]):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def file_transfer(filename: str, filesize: int, packetsize=1000, timeout=2000, mode=None):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
96
hub/battery.py
Normal file
96
hub/battery.py
Normal file
|
@ -0,0 +1,96 @@
|
||||||
|
from typing import Union
|
||||||
|
|
||||||
|
def voltage() -> int:
|
||||||
|
"""
|
||||||
|
Gets the battery voltage.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- The voltage in mV.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def current() -> int:
|
||||||
|
"""
|
||||||
|
Gets current flowing out of the battery.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- The current in in mA.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def capacity_left() -> int:
|
||||||
|
"""
|
||||||
|
Gets the remaining capacity as a percentage of a fully charged battery.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- The remaining battery capacity.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def temperature() -> float:
|
||||||
|
"""
|
||||||
|
Gets the temperature of the battery.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- The temperature in degrees Celsius.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def charger_detect() -> Union[bool, int]:
|
||||||
|
"""
|
||||||
|
Checks what type of charger was detected.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- See charging constants for all possible return values. Returns False if it failed to detect a charger.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def info() -> dict:
|
||||||
|
"""
|
||||||
|
Gets status information about the battery.
|
||||||
|
|
||||||
|
This returns a dictionary of the form:
|
||||||
|
|
||||||
|
```
|
||||||
|
{
|
||||||
|
# Battery measurements as documented above.
|
||||||
|
'battery_capacity_left': 100
|
||||||
|
'temperature': 25.7,
|
||||||
|
'charge_current': 248,
|
||||||
|
'charge_voltage': 8294,
|
||||||
|
|
||||||
|
# Filtered version of the battery voltage.
|
||||||
|
'charge_voltage_filtered': 8287,
|
||||||
|
|
||||||
|
# A list of active errors. See constants given below.
|
||||||
|
'error_state': [0],
|
||||||
|
|
||||||
|
# Charging state. See constants given below.
|
||||||
|
'charger_state': 2,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### Returns
|
||||||
|
- Battery status information.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Battery status values
|
||||||
|
BATTERY_NO_ERROR = 0 #The battery is happy.
|
||||||
|
BATTERY_HUB_TEMPERATURE_CRITICAL_OUT_OF_RANGE= -1 #The battery temperature is outside of the expected range.
|
||||||
|
BATTERY_TEMPERATURE_OUT_OF_RANGE= -2 #The battery temperature is outside of the critical range.
|
||||||
|
BATTERY_TEMPERATURE_SENSOR_FAIL= -3 #The battery temperature sensor is not working.
|
||||||
|
BATTERY_BAD_BATTERY= -4 #Something is wrong with the battery.
|
||||||
|
BATTERY_VOLTAGE_TOO_LOW= -5 #The battery voltage is too low.
|
||||||
|
BATTERY_MISSING= -6 #No battery detected.
|
||||||
|
|
||||||
|
#Charger types
|
||||||
|
USB_CH_PORT_NONE= 0 #No charger detected.
|
||||||
|
USB_CH_PORT_SDP= 1 #Standard downstream port (typical USB port).
|
||||||
|
USB_CH_PORT_CDP= 2 #Charging Downstream Port (wall charger).
|
||||||
|
USB_CH_PORT_DCP= 3 #Dedicated charging port (high current USB port).
|
||||||
|
|
||||||
|
#Charging states
|
||||||
|
CHARGER_STATE_FAIL= -1 #There was a problem charging the battery.
|
||||||
|
CHARGER_STATE_DISCHARGING= 0 #The battery is discharging.
|
||||||
|
CHARGER_STATE_CHARGING_ONGOING= 1 #The battery is charging.
|
||||||
|
CHARGER_STATE_CHARGING_COMPLETED= 2 #The battery is fully charged.
|
144
hub/bluetooth.py
Normal file
144
hub/bluetooth.py
Normal file
|
@ -0,0 +1,144 @@
|
||||||
|
from typing import Callable, overload
|
||||||
|
|
||||||
|
# The Bluetooth module.
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def discoverable() -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def discoverable(time: int):
|
||||||
|
"""
|
||||||
|
Gets or sets the Bluetooth classic discoverability state.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `time` - For how many seconds the hub should be discoverable. During this time, you can find the hub when you search for Bluetooth devices using your computer or phone.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- If no argument is given, this returns the remaining number of seconds that the hub is discoverable. Once the hub is no longer discoverable, it returns 0.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def rfcomm_connect() -> str:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def rfcomm_connect(address: str) -> bool:
|
||||||
|
"""
|
||||||
|
Connects to a Bluetooth Classic MAC address.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `address` - A string of format aa:bb:cc:dd:ee:ff that represents the MAC address of the Bluetooth Classic device to connect with.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- If no argument is given, returns the MAC address that the RFCOMM service is conneted to. If there is no active connection the address is 00:00:00:00:00:00.
|
||||||
|
- True if a valid address was given, or False if the address is not a valid MAC address string.
|
||||||
|
- The result does not reflect the status of the connection attempt.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def rfcomm_disconnect() -> None:
|
||||||
|
"""
|
||||||
|
Disconnects an active RFCOMM channel
|
||||||
|
|
||||||
|
The result does not reflect the status of the disconnection attempt.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def info() -> dict:
|
||||||
|
"""
|
||||||
|
Gets a dictionary of the form:
|
||||||
|
|
||||||
|
```
|
||||||
|
{
|
||||||
|
# The Bluetooth device MAC address.
|
||||||
|
'mac_addr': '38:0B:3C:A2:E1:E4',
|
||||||
|
|
||||||
|
# The Bluetooth device UUID.
|
||||||
|
'device_uuid': '03970000-1800-3500-1551-383235373836'
|
||||||
|
|
||||||
|
# The outgoing service UUID.
|
||||||
|
'service_uuid': '',
|
||||||
|
|
||||||
|
# Bluetooth name of the device.
|
||||||
|
'name': 'LEGO Hub 38:0B:3C:A2:E1:E4',
|
||||||
|
|
||||||
|
# iPod Accessory Protocol (iAP) status dictionary.
|
||||||
|
'iap': {
|
||||||
|
'device_version': 7,
|
||||||
|
'authentication_revision': 1,
|
||||||
|
'device_id': -1,
|
||||||
|
'certificate_serial_no': '54D2891DEC5E5104F7132BC3059365CB',
|
||||||
|
'protocol_major_version': 3,
|
||||||
|
'protocol_minor_version': 0
|
||||||
|
},
|
||||||
|
|
||||||
|
# A list of devices that the hub has been connected to.
|
||||||
|
'known_devices': ['8C:8D:28:2D:E0:0F', 'E8:6D:CB:77:64:D5'],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### Returns
|
||||||
|
- Bluetooth subsystem information dictionary similar to the example above, or None if the Bluetooth subsystem is not running.
|
||||||
|
- The MAC address in known_devices is reversed for Windows devices.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def forget(address) -> bool:
|
||||||
|
"""
|
||||||
|
Removes a device from the list of known Bluetooth devices.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `address` - Bluetooth address of the form '01:23:45:67:89:AB'.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- True if a valid address was given, or False if not.
|
||||||
|
- Functions for the LEGO Wireless Protocol
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def lwp_advertise() -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def lwp_advertise(timeout: int):
|
||||||
|
"""
|
||||||
|
Gets or sets the Bluetooth Low Energy LEGO Wireless protocol advertising state.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `time` - For how many seconds the hub should advertise the LEGO Wireless Protocol. During this time, you can find the hub when you search for Bluetooth devices using your computer or phone.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- If no argument is given, this returns the remaining number of seconds that the hub will advertise. Once the hub is no longer advertising, it returns 0.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def lwp_bypass() -> bool:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def lwp_bypass(bypass: bool):
|
||||||
|
"""
|
||||||
|
Controls whether the LEGO Wireless Protocol is bypassed when using Bluetooth Low Energy.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `bypass` - Choose True to bypass the LEGO Wireless protocol or choose False to enable it.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- If no argument is given, this returns the current bypass state.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def lwp_monitor(self, handler: Callable[[int], None]):
|
||||||
|
"""
|
||||||
|
Sets the callback function that is called when a connection is made using the LEGO Wireless Protocol.
|
||||||
|
|
||||||
|
The function must accept one argument, which provides information about the incoming connection.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `handler` - Callable function that takes one argument. Choose None to disable the callback.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
57
hub/button.py
Normal file
57
hub/button.py
Normal file
|
@ -0,0 +1,57 @@
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
|
||||||
|
class Button:
|
||||||
|
"""
|
||||||
|
Provides access to button state and callback.
|
||||||
|
|
||||||
|
Each of the buttons listed below are instances of this class. You cannot instantiate additional button objects.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def is_pressed(self) -> bool:
|
||||||
|
"""
|
||||||
|
Gets the state of the button.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- True if it is pressed, False otherwise.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def was_pressed() -> bool:
|
||||||
|
"""
|
||||||
|
Checks if this button was pressed since this method was last called.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- True if it was pressed at least once since the previous call, False otherwise.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def presses() -> int:
|
||||||
|
"""
|
||||||
|
Gets the number of times this button was pressed since this method was last called.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- The number of presses since the last call.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def callback(function: Callable[[int], None]) -> None:
|
||||||
|
"""
|
||||||
|
Sets the callback function that is called when the button is pressed and when it is released.
|
||||||
|
|
||||||
|
The function must accept one argument, whose value indicates why the callback was called:
|
||||||
|
|
||||||
|
If the value is 0, the button is now pressed.
|
||||||
|
|
||||||
|
Otherwise, the button is now released. The value represents how many milliseconds it was pressed before it was released.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `function` - Callable function that takes one argument. Choose None to disable the callback.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
left: Button # The left button.
|
||||||
|
right: Button # The right button.
|
||||||
|
center: Button # The center button.
|
||||||
|
connect: Button # The button with the Bluetooth symbol.
|
378
hub/display.py
Normal file
378
hub/display.py
Normal file
|
@ -0,0 +1,378 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import Callable, Iterable
|
||||||
|
|
||||||
|
"""
|
||||||
|
The Image class lets you create and modify images that you can show on the hub matrix display using the hub.display module.
|
||||||
|
"""
|
||||||
|
class Image:
|
||||||
|
|
||||||
|
def __init__(self, *args):
|
||||||
|
"""
|
||||||
|
Create a new image object for use with the hub.display.show() function.
|
||||||
|
|
||||||
|
```
|
||||||
|
Image(string: str)
|
||||||
|
Image(width: int, height: int)
|
||||||
|
Image(width: int, height: int, buffer: bytes)
|
||||||
|
```
|
||||||
|
|
||||||
|
You can use one of the signatures above to initialize an image, depending on what you need.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
|
||||||
|
- `string` - String of the form "00900:09990:99999:09990:09090:", representing the brightness of each pixel (0 to 9). Pixels are listed row by row, separated by a colon (:) or line break (\\n).
|
||||||
|
- `width` - Number of pixels in one row of the new image.
|
||||||
|
- `height` - Number of pixels in one column of the new image.
|
||||||
|
- `buffer` - Bytes representing the brightness values of each pixel in the new image. The buffer size must be equal to width * height. If you give a with and height but no buffer, you will get an image where all pixels are zero.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def width(self) -> int:
|
||||||
|
"""
|
||||||
|
Gets the width of the image as a number of pixels.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def height(self) -> int:
|
||||||
|
"""
|
||||||
|
Gets the width of the image as a number of pixels.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def shift_left(n: int) -> 'Image':
|
||||||
|
"""
|
||||||
|
Shifts the image to the left.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `n1 - By how many pixels to shift the image.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- A new, shifted image.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def shift_right(n: int) -> 'Image':
|
||||||
|
"""
|
||||||
|
Shifts the image to the right.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `n` - By how many pixels to shift the image.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- A new, shifted image.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def shift_up(n: int) -> 'Image':
|
||||||
|
"""
|
||||||
|
Shifts the image up.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `n` - By how many pixels to shift the image.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- A new, shifted image.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def shift_down(n: int) -> 'Image':
|
||||||
|
"""
|
||||||
|
Shifts the image down.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `n` - By how many pixels to shift the image.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- A new, shifted image.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def get_pixel(x: int, y: int, brightness: int) -> int:
|
||||||
|
"""
|
||||||
|
Gets the brightness of one pixel in the image.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `x` - Pixel position counted from the left, starting at zero.
|
||||||
|
- `y` - Pixel position counted from the top, starting at zero.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- Brightness (0-9) of the requested pixel.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def set_pixel(x: int, y: int, brightness: int) -> None:
|
||||||
|
"""
|
||||||
|
Sets the brightness of one pixel in the image.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `x` - Pixel position counted from the left, starting at zero.
|
||||||
|
- `y` - Pixel position counted from the top, starting at zero.
|
||||||
|
- `brightness` - Brightness between 0 (fully off) and 9 (fully on).
|
||||||
|
|
||||||
|
### Raises
|
||||||
|
- `ValueError` - If x or y are negative or larger than the image size.
|
||||||
|
- `TypeError` - If you try to modify a built-in image such as HEART.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
ANGRY: Image
|
||||||
|
ARROW_E: Image
|
||||||
|
ARROW_N: Image
|
||||||
|
ARROW_NE: Image
|
||||||
|
ARROW_NW: Image
|
||||||
|
ARROW_S: Image
|
||||||
|
ARROW_SE: Image
|
||||||
|
ARROW_SW: Image
|
||||||
|
ARROW_W: Image
|
||||||
|
ASLEEP: Image
|
||||||
|
BUTTERFLY: Image
|
||||||
|
CHESSBOARD: Image
|
||||||
|
CLOCK1: Image
|
||||||
|
CLOCK2: Image
|
||||||
|
CLOCK3: Image
|
||||||
|
CLOCK4: Image
|
||||||
|
CLOCK5: Image
|
||||||
|
CLOCK6: Image
|
||||||
|
CLOCK7: Image
|
||||||
|
CLOCK8: Image
|
||||||
|
CLOCK9: Image
|
||||||
|
CLOCK10: Image
|
||||||
|
CLOCK11: Image
|
||||||
|
CLOCK12: Image
|
||||||
|
CONFUSED: Image
|
||||||
|
COW: Image
|
||||||
|
DIAMOND: Image
|
||||||
|
DIAMOND_SMALL: Image
|
||||||
|
DUCK: Image
|
||||||
|
FABULOUS: Image
|
||||||
|
GHOST: Image
|
||||||
|
GIRAFFE: Image
|
||||||
|
GO_DOWN: Image
|
||||||
|
GO_LEFT: Image
|
||||||
|
GO_RIGHT: Image
|
||||||
|
GO_UP: Image
|
||||||
|
HAPPY: Image
|
||||||
|
HEART: Image
|
||||||
|
HEART_SMALL: Image
|
||||||
|
HOUSE: Image
|
||||||
|
MEH: Image
|
||||||
|
MUSIC_CROTCHET: Image
|
||||||
|
MUSIC_QUAVER: Image
|
||||||
|
MUSIC_QUAVERS: Image
|
||||||
|
NO: Image
|
||||||
|
PACMAN: Image
|
||||||
|
PITCHFORK: Image
|
||||||
|
RABBIT: Image
|
||||||
|
ROLLERSKATE: Image
|
||||||
|
SAD: Image
|
||||||
|
SILLY: Image
|
||||||
|
SKULL: Image
|
||||||
|
SMILE: Image
|
||||||
|
SNAKE: Image
|
||||||
|
SQUARE: Image
|
||||||
|
SQUARE_SMALL: Image
|
||||||
|
STICKFIGURE: Image
|
||||||
|
SURPRISED: Image
|
||||||
|
SWORD: Image
|
||||||
|
TARGET: Image
|
||||||
|
TORTOISE: Image
|
||||||
|
TRIANGLE: Image
|
||||||
|
TRIANGLE_LEFT: Image
|
||||||
|
TSHIRT: Image
|
||||||
|
UMBRELLA: Image
|
||||||
|
XMAS: Image
|
||||||
|
YES: Image
|
||||||
|
ALL_CLOCKS: Image
|
||||||
|
ALL_ARROWS: Image
|
||||||
|
|
||||||
|
#Built-in images
|
||||||
|
Image.ANGRY = Image('90009:09090:00000:99999:90909:')
|
||||||
|
Image.ARROW_E = Image('00900:00090:99999:00090:00900:')
|
||||||
|
Image.ARROW_N = Image('00900:09990:90909:00900:00900:')
|
||||||
|
Image.ARROW_NE = Image('00999:00099:00909:09000:90000:')
|
||||||
|
Image.ARROW_NW = Image('99900:99000:90900:00090:00009:')
|
||||||
|
Image.ARROW_S = Image('00900:00900:90909:09990:00900:')
|
||||||
|
Image.ARROW_SE = Image('90000:09000:00909:00099:00999:')
|
||||||
|
Image.ARROW_SW = Image('00009:00090:90900:99000:99900:')
|
||||||
|
Image.ARROW_W = Image('00900:09000:99999:09000:00900:')
|
||||||
|
Image.ASLEEP = Image('00000:99099:00000:09990:00000:')
|
||||||
|
Image.BUTTERFLY = Image('99099:99999:00900:99999:99099:')
|
||||||
|
Image.CHESSBOARD = Image('09090:90909:09090:90909:09090:')
|
||||||
|
Image.CLOCK1 = Image('00090:00090:00900:00000:00000:')
|
||||||
|
Image.CLOCK2 = Image('00000:00099:00900:00000:00000:')
|
||||||
|
Image.CLOCK3 = Image('00000:00000:00999:00000:00000:')
|
||||||
|
Image.CLOCK4 = Image('00000:00000:00900:00099:00000:')
|
||||||
|
Image.CLOCK5 = Image('00000:00000:00900:00090:00090:')
|
||||||
|
Image.CLOCK6 = Image('00000:00000:00900:00900:00900:')
|
||||||
|
Image.CLOCK7 = Image('00000:00000:00900:09000:09000:')
|
||||||
|
Image.CLOCK8 = Image('00000:00000:00900:99000:00000:')
|
||||||
|
Image.CLOCK9 = Image('00000:00000:99900:00000:00000:')
|
||||||
|
Image.CLOCK10 = Image('00000:99000:00900:00000:00000:')
|
||||||
|
Image.CLOCK11 = Image('09000:09000:00900:00000:00000:')
|
||||||
|
Image.CLOCK12 = Image('00900:00900:00900:00000:00000:')
|
||||||
|
Image.CONFUSED = Image('00000:09090:00000:09090:90909:')
|
||||||
|
Image.COW = Image('90009:90009:99999:09990:00900:')
|
||||||
|
Image.DIAMOND = Image('00900:09090:90009:09090:00900:')
|
||||||
|
Image.DIAMOND_SMALL = Image('00000:00900:09090:00900:00000:')
|
||||||
|
Image.DUCK = Image('09900:99900:09999:09990:00000:')
|
||||||
|
Image.FABULOUS = Image('99999:99099:00000:09090:09990:')
|
||||||
|
Image.GHOST = Image('99999:90909:99999:99999:90909:')
|
||||||
|
Image.GIRAFFE = Image('99000:09000:09000:09990:09090:')
|
||||||
|
Image.GO_DOWN = Image('00000:99999:09990:00900:00000:')
|
||||||
|
Image.GO_LEFT = Image('00090:00990:09990:00990:00090:')
|
||||||
|
Image.GO_RIGHT = Image('09000:09900:09990:09900:09000:')
|
||||||
|
Image.GO_UP = Image('00000:00900:09990:99999:00000:')
|
||||||
|
Image.HAPPY = Image('00000:09090:00000:90009:09990:')
|
||||||
|
Image.HEART = Image('09090:99999:99999:09990:00900:')
|
||||||
|
Image.HEART_SMALL = Image('00000:09090:09990:00900:00000:')
|
||||||
|
Image.HOUSE = Image('00900:09990:99999:09990:09090:')
|
||||||
|
Image.MEH = Image('09090:00000:00090:00900:09000:')
|
||||||
|
Image.MUSIC_CROTCHET = Image('00900:00900:00900:99900:99900:')
|
||||||
|
Image.MUSIC_QUAVER = Image('00900:00990:00909:99900:99900:')
|
||||||
|
Image.MUSIC_QUAVERS = Image('09999:09009:09009:99099:99099:')
|
||||||
|
Image.NO = Image('90009:09090:00900:09090:90009:')
|
||||||
|
Image.PACMAN = Image('09999:99090:99900:99990:09999:')
|
||||||
|
Image.PITCHFORK = Image('90909:90909:99999:00900:00900:')
|
||||||
|
Image.RABBIT = Image('90900:90900:99990:99090:99990:')
|
||||||
|
Image.ROLLERSKATE = Image('00099:00099:99999:99999:09090:')
|
||||||
|
Image.SAD = Image('00000:09090:00000:09990:90009:')
|
||||||
|
Image.SILLY = Image('90009:00000:99999:00909:00999:')
|
||||||
|
Image.SKULL = Image('09990:90909:99999:09990:09990:')
|
||||||
|
Image.SMILE = Image('00000:00000:00000:90009:09990:')
|
||||||
|
Image.SNAKE = Image('99000:99099:09090:09990:00000:')
|
||||||
|
Image.SQUARE = Image('99999:90009:90009:90009:99999:')
|
||||||
|
Image.SQUARE_SMALL = Image('00000:09990:09090:09990:00000:')
|
||||||
|
Image.STICKFIGURE = Image('00900:99999:00900:09090:90009:')
|
||||||
|
Image.SURPRISED = Image('09090:00000:00900:09090:00900:')
|
||||||
|
Image.SWORD = Image('00900:00900:00900:09990:00900:')
|
||||||
|
Image.TARGET = Image('00900:09990:99099:09990:00900:')
|
||||||
|
Image.TORTOISE = Image('00000:09990:99999:09090:00000:')
|
||||||
|
Image.TRIANGLE = Image('00000:00900:09090:99999:00000:')
|
||||||
|
Image.TRIANGLE_LEFT = Image('90000:99000:90900:90090:99999:')
|
||||||
|
Image.TSHIRT = Image('99099:99999:09990:09990:09990:')
|
||||||
|
Image.UMBRELLA = Image('09990:99999:00900:90900:09900:')
|
||||||
|
Image.XMAS = Image('00900:09990:00900:09990:99999:')
|
||||||
|
Image.YES = Image('00000:00009:00090:90900:09000:')
|
||||||
|
|
||||||
|
#Built-in tuples of images
|
||||||
|
Image.ALL_CLOCKS = (Image('00900:00900:00900:00000:00000:'), Image('00090:00090:00900:00000:00000:'), Image('00000:00099:00900:00000:00000:'), Image('00000:00000:00999:00000:00000:'), Image('00000:00000:00900:00099:00000:'), Image('00000:00000:00900:00090:00090:'), Image('00000:00000:00900:00900:00900:'), Image('00000:00000:00900:09000:09000:'), Image('00000:00000:00900:99000:00000:'), Image('00000:00000:99900:00000:00000:'), Image('00000:99000:00900:00000:00000:'), Image('09000:09000:00900:00000:00000:'))
|
||||||
|
Image.ALL_ARROWS = (Image('00900:09990:90909:00900:00900:'), Image('00999:00099:00909:09000:90000:'), Image('00900:00090:99999:00090:00900:'), Image('90000:09000:00909:00099:00999:'), Image('00900:00900:90909:09990:00900:'), Image('00009:00090:90900:99000:99900:'), Image('00900:09000:99999:09000:00900:'), Image('99900:99000:90900:00090:00009:'))
|
||||||
|
|
||||||
|
|
||||||
|
"""
|
||||||
|
The display module lets you control the light matrix display on the hub.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def clear():
|
||||||
|
"""
|
||||||
|
Turns off all the pixels.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def rotation(rotation: int) -> None:
|
||||||
|
"""
|
||||||
|
Rotates the display clockwise relative to its current orientation.
|
||||||
|
|
||||||
|
DEPRECATION WARNING - In the next release this is a do-nothing operation. Use the def align() API instead!
|
||||||
|
|
||||||
|
Following the next release this call will be removed.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def align() -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def align(face: int) -> int:
|
||||||
|
"""
|
||||||
|
Rotates the display by aligning the top with the given face of the hub.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `face` - Choose hub.FRONT, hub.BACK, hub.LEFT, or hub.RIGHT.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- The new or current alignment.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def invert() -> bool:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def invert(invert: bool) -> bool:
|
||||||
|
"""
|
||||||
|
Inverts all pixels. This affects what is currently displayed, as well as everything you display afterwards.
|
||||||
|
|
||||||
|
In the inverted state, the brightness of each pixel is the opposite of the normal state. If a pixel has brightness b, it will be displayed with brightness 9 - b.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `invert` - Choose True to activate the inverted state. Choose False to restore the normal state.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- The new or current inversion state.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def callback(self, function: Callable[[int], None]) -> None:
|
||||||
|
"""
|
||||||
|
Sets the callback function that is called when a display operation is completed or interrupted.
|
||||||
|
|
||||||
|
The function must accept one argument, which indicates why the callback was called. It will receive 0 if a display operation completed successfully, or 1 if it was interrupted.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `function` - Callable function that takes one argument. Choose None to disable the callback.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def pixel(x: int, y: int) -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def pixel(x: int, y: int, brightness: int) -> None:
|
||||||
|
"""
|
||||||
|
Gets or sets the brightness of one pixel.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `x` - Pixel position counted from the left, starting at zero.
|
||||||
|
- `y` - Pixel position counted from the top, starting at zero.
|
||||||
|
- `brightness` - Brightness between 0 (fully off) and 9 (fully on).
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- If no brightness is given, this returns the brightness of the selected pixel. Otherwise it returns None.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def show(image: Image) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def show(image: Iterable[Image], delay=400, level=9, clear=False, wait=True, loop=False, fade=0) -> None:
|
||||||
|
"""
|
||||||
|
Shows an image or a sequence of images.
|
||||||
|
|
||||||
|
Except for image, all arguments must be specified as keywords.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `image` - The image or iterable of images to be displayed.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `delay` - Delay between each image in the iterable.
|
||||||
|
- `level` - Scales the brightness of each pixel in and image or character to a value between 0 (fully off) and 9 (fully on).
|
||||||
|
- `clear` - Choose `True` to clear the display after showing the last image in the iterable.
|
||||||
|
- `wait` - Choose `True` to block your program until all images are shown. Choose `False` to show all images in the background while your program continues.
|
||||||
|
- `loop` - Choose `True` repeat the sequence of images for ever. Choose `False` to show it only once.
|
||||||
|
- `fade` -
|
||||||
|
|
||||||
|
Sets the transitional behavior between images in the sequence:
|
||||||
|
|
||||||
|
The image will appear immediately.
|
||||||
|
|
||||||
|
The image will appear immediately.
|
||||||
|
|
||||||
|
The image fades out while the next image fades in.
|
||||||
|
|
||||||
|
Images will scroll to the right.
|
||||||
|
|
||||||
|
Images will scroll to the left.
|
||||||
|
|
||||||
|
Images will fade in, starting from an empty display.
|
||||||
|
|
||||||
|
Images will fade out, starting from the original image.
|
||||||
|
"""
|
||||||
|
pass
|
125
hub/motion.py
Normal file
125
hub/motion.py
Normal file
|
@ -0,0 +1,125 @@
|
||||||
|
from typing import Tuple, Callable
|
||||||
|
from typing import overload
|
||||||
|
|
||||||
|
def accelerometer(filtered=False) -> Tuple[int, int, int]:
|
||||||
|
"""
|
||||||
|
Gets the acceleration of the hub along the x, y, and z axis.
|
||||||
|
|
||||||
|
#### Parameters
|
||||||
|
- `filtered` - Selecting True gives a more stable value, but it is delayed by 10-100 milliseconds. Selecting False gives the unfiltered value.
|
||||||
|
|
||||||
|
#### Returns
|
||||||
|
- Acceleration of the hub with units of `cm/s^2`. On a perfectly level surface, this gives (0, 0, 981).
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def gyroscope(filtered=False) -> Tuple[int, int, int]:
|
||||||
|
"""
|
||||||
|
Gets the angular velocity of the hub along the x, y, and z axis.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `filtered` - Selecting True gives a more stable value, but it is delayed by 10-100 milliseconds. Selecting False gives the unfiltered value.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- Angular velocity with units of degrees per second.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def align_to_model(top: int, front: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def align_to_model(nsamples: int, callback: Callable[[int], None]) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def align_to_model(top: int, front: int, nsamples: int, callback: Callable[[int], None]) -> None:
|
||||||
|
"""
|
||||||
|
Sets the default hub orientation and/or calibrates the gyroscope.
|
||||||
|
|
||||||
|
The hub must not move while calibrating. It takes about one second by default.
|
||||||
|
|
||||||
|
Changing the model alignment affects most other methods in this module. They will now be relative to the hub alignment that you specify.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `top` - Which hub side is at the top of your model. See the hub `constants` for all possible values.
|
||||||
|
- `front` - Which hub side is on the front of your model.
|
||||||
|
- `nsamples` - Number of samples for calibration between 0 and 10000. It is 100 by default.
|
||||||
|
- `callback` - Function that will be called when calibration is complete. It must accept one argument. Choose None to disable the callback. This is the default.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def yaw_pitch_roll() -> Tuple[int, int, int]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def yaw_pitch_roll(yaw_preset: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def yaw_pitch_roll(yaw_correction: float) -> None:
|
||||||
|
"""
|
||||||
|
Gets the yaw, pitch, and roll angles of the hub, or resets the yaw.
|
||||||
|
|
||||||
|
The yaw_correction is an optional keyword argument to improve the accuracy of the yaw value after one full turn. To use it:
|
||||||
|
|
||||||
|
Reset the yaw angle to zero using def yaw_pitch_roll(0).
|
||||||
|
|
||||||
|
Rotate the hub smoothly exactly one rotation clockwise.
|
||||||
|
|
||||||
|
Call error = def yaw_pitch_roll()[0] to get the yaw error.
|
||||||
|
|
||||||
|
The error should be 0. If it is not, you can set the correction using def yaw_pitch_roll(yaw_correction=error).
|
||||||
|
|
||||||
|
For even more accuracy, you can turn clockwise 5 times, and use error / 5 as the correction factor.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `yaw_preset` - Sets the current yaw to the given value (-180 to 179).
|
||||||
|
- `yaw_correction` - Adjusts the gain of the yaw axis values. See the yaw adjustment section below.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- If no arguments are given, this returns a tuple of yaw, pitch, and roll values in degrees.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def orientation() -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def orientation(callback: Callable[[int], None]) -> int:
|
||||||
|
"""
|
||||||
|
Gets which hub side of the hub is mostly pointing up.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `callback` - Function that will be called when the orientation changes. It must accept one argument, which will tell you which hub side is up. Choose None to disable the callback. This is the default.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- Number representing which side is up. See hub constants for all possible values.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def gesture() -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def gesture(callback: Callable[[int], None]) -> int:
|
||||||
|
"""
|
||||||
|
Gets the most recent gesture that the hub has made since this function was last called.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `callback` - Function that will be called when a gesture is detected. It must accept one argument, which will tell you which gesture was detected. Choose None to disable the callback. This is the default.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- Number representing the gesture. See motion constants for all possible values. If no gesture was detected since this function was last called, it returns None.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
#These values are used by the gesture() function.
|
||||||
|
TAPPED = 0 #The hub was tapped.
|
||||||
|
DOUBLETAPPED = 1 #The hub was quickly tapped twice.
|
||||||
|
SHAKE = 2 #The hub was shaken.
|
||||||
|
FREEFALL = 3 #The hub fell.
|
456
hub/port.py
Normal file
456
hub/port.py
Normal file
|
@ -0,0 +1,456 @@
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import Callable, Union, Optional, Iterable, Tuple, overload
|
||||||
|
|
||||||
|
|
||||||
|
class Pin():
|
||||||
|
"""
|
||||||
|
This class can be used to read and control the two logic pins on pins 5 and 6 of each port. You can access two `Pin` objects via each `Port` instance if the port has been set to `MODE_GPIO` mode.
|
||||||
|
|
||||||
|
Control a general purpose input/output (GPIO) pin.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def direction(self, direction: Optional[int]) -> int:
|
||||||
|
"""
|
||||||
|
Gets and sets the direction of the pin.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `direction` - Choose 0 to make the pin an input or 1 to make it an output.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- The configured direction.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def value(self, value: Optional[int]) -> int:
|
||||||
|
"""
|
||||||
|
Gets and sets the logic value of the pin.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `value` - Choose 1 to make the pin high or 0 to make it low. If the pin is configured as an input, this argument is ignored.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- Logic value of the pin.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
class Device():
|
||||||
|
|
||||||
|
"""
|
||||||
|
This class is the blueprint for the device attributes of the ports in the `hub.port` module, which in turn are instances of the `Port` class. You cannot import or instantiate this class manually.
|
||||||
|
|
||||||
|
Read values from a Powered Up device and configure its modes.
|
||||||
|
"""
|
||||||
|
FORMAT_RAW = 0
|
||||||
|
FORMAT_PCT= 1
|
||||||
|
FORMAT_SI= 2
|
||||||
|
|
||||||
|
def get(self, format: Optional[int]) -> list:
|
||||||
|
"""
|
||||||
|
Gets the values that the active device mode provides.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `format` - Format of the data. Choose `FORMAT_RAW`, `FORMAT_PCT`, or `FORMAT_SI`.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- Values or measurements representing the device state.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def mode(self, mode: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def mode(self, mode: int, data: bytes) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def mode(self, mode: Iterable[Tuple[int, int]]) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def mode(self) -> Iterable[Tuple[int, int]]:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def pwm(self, value: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def write_direct(self, data: bytes) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
class Motor(Device):
|
||||||
|
"""
|
||||||
|
This class is the blueprint for the motor attributes of the ports in the hub.port module, which in turn are instances of the Port class. You cannot import or instantiate this class manually.
|
||||||
|
|
||||||
|
Control a motor.
|
||||||
|
|
||||||
|
"""
|
||||||
|
BUSY_MODE = 0 #The port is busy configuring the device mode."""
|
||||||
|
BUSY_MOTOR = 1 #The motor is busy executing a command.
|
||||||
|
STOP_FLOAT = 0 #When stopping, the motor floats. See also float().
|
||||||
|
STOP_BRAKE = 1 #When stopping, the motor brakes. See also brake().
|
||||||
|
STOP_HOLD = 2 #When stopping, the motor holds position. See also hold().
|
||||||
|
EVENT_COMPLETED = 0 #The motor command completed successfully.
|
||||||
|
EVENT_INTERRUPTED = 1 #The motor command was interrupted.
|
||||||
|
EVENT_STALLED = 2 #The motor command stopped because the motor was stalled.
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def float(self) -> None:
|
||||||
|
"""
|
||||||
|
Floats (coasts) the motor, as if disconnected from the hub.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def brake(self) -> None:
|
||||||
|
"""
|
||||||
|
Passively brakes the motor, as if shorting the motor terminals.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def hold(self) -> None:
|
||||||
|
"""
|
||||||
|
Actively hold the motor in its current position.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def busy(self, type:int = BUSY_MODE) -> bool:
|
||||||
|
"""
|
||||||
|
Checks whether the motor is busy changing modes, or executing a motor command such as running to a position.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `type` - Choose `BUSY_MODE` or `BUSY_MOTOR`.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- Whether the motor is busy with the specified activity.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_at_speed(self, speed: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_at_speed(self, speed: int, max_power: int, acceleration: int, deceleration: int, stall: bool) -> None:
|
||||||
|
"""
|
||||||
|
Starts running a motor at the given speed.
|
||||||
|
|
||||||
|
If a keyword argument is not given, its default value will be used.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `speed` - Sets the speed as a percentage of the rated speed for this motor. Positive means clockwise, negative means counterclockwise.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `max_power` - Sets percentage of maximum power used during this command.
|
||||||
|
- `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill.
|
||||||
|
- `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed.
|
||||||
|
- `stall` - Selects whether the motor should stop when stalled (True) or not (False).
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_for_time(self, msec: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_for_time(self, msec: int, speed: int, max_power: int, stop: int, acceleration: int, deceleration: int, stall: bool) -> None:
|
||||||
|
"""
|
||||||
|
Runs a motor for a given amount of time.
|
||||||
|
|
||||||
|
If a keyword argument is not given, its default value will be used.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `msec` - How long the motor should run in milliseconds. Negative values will be treated as zero.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `speed` - Sets the speed as a percentage of the rated speed for this motor. Positive means clockwise, negative means counterclockwise.
|
||||||
|
- `max_power` - Sets percentage of maximum power used during this command.
|
||||||
|
- `stop` - How to stop. Choose type: Choose `STOP_FLOAT`, `STOP_BRAKE`, or `STOP_HOLD`.
|
||||||
|
- `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill.
|
||||||
|
- `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed.
|
||||||
|
- `stall` - Selects whether the motor should stop trying to reach the endpoint when stalled (True) or not (False).
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_for_degrees(self, degrees: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_for_degrees(self, degrees: int, speed: int, max_power: int, stop: int, acceleration: int, deceleration: int, stall: bool) -> None:
|
||||||
|
"""
|
||||||
|
Runs a motor for a given number of degrees at a given speed.
|
||||||
|
|
||||||
|
If a keyword argument is not given, its default value will be used.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `degrees` - How many degrees to rotate relative to the starting point.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `speed` -
|
||||||
|
|
||||||
|
Sets the speed as a percentage of the rated speed for this motor.
|
||||||
|
|
||||||
|
If degrees > 0 and speed > 0, the motor turns clockwise.
|
||||||
|
|
||||||
|
If degrees > 0 and speed < 0, the motor turns counterclockwise.
|
||||||
|
|
||||||
|
If degrees < 0 and speed > 0, the motor turns clockwise.
|
||||||
|
|
||||||
|
If degrees < 0 and speed < 0, the motor turns counterclockwise.
|
||||||
|
|
||||||
|
- `max_power` - Sets percentage of maximum power used during this command.
|
||||||
|
- `stop` - How to stop. Choose type: Choose `STOP_FLOAT`, `STOP_BRAKE`, or `STOP_HOLD`.
|
||||||
|
- `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill.
|
||||||
|
- `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed.
|
||||||
|
- `stall` - Selects whether the motor should stop trying to reach the endpoint when stalled (True) or not (False).
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_to_position(self, position: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_to_position(self, position: int, speed: int, max_power: int, stop: int, acceleration: int, deceleration: int, stall: bool) -> None:
|
||||||
|
"""
|
||||||
|
Runs a motor to the given position.
|
||||||
|
|
||||||
|
The angular position is measured relative to the motor position when the hub was turned on or when the motor was plugged in. You can preset this starting position using preset.
|
||||||
|
|
||||||
|
If a keyword argument is not given, its default value will be used.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `position` - Position to rotate to.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `speed` - Sets the speed as a percentage of the rated speed for this motor. The sign of the speed will be ignored.
|
||||||
|
- `max_power` - Sets percentage of maximum power used during this command.
|
||||||
|
- `stop` - How to stop. Choose type: Choose STOP_FLOAT, STOP_BRAKE, or STOP_HOLD.
|
||||||
|
- `acceleration` - The time in milliseconds (0-10000) for the motor to reach maximum rated speed from standstill.
|
||||||
|
- `deceleration` - The time in milliseconds (0-10000) for the motor to stop when starting from the maximum rated speed.
|
||||||
|
- `stall` - Selects whether the motor should stop trying to reach the endpoint when stalled (True) or not (False).
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def preset(self, position: int) -> None:
|
||||||
|
"""
|
||||||
|
Presets the starting position used by run_to_position.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `position` - The new position preset.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def callback(self, function: Callable[[int], None]) -> None:
|
||||||
|
"""
|
||||||
|
Sets the callback function that is called when a command is completed, interrupted, or stalled.
|
||||||
|
|
||||||
|
The function must accept one argument, which indicates why the callback was called. It will receive either EVENT_COMPLETED, EVENT_INTERRUPTED, or EVENT_STALLED.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `function` - Callable function that takes one argument. Choose None to disable the callback.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def pid(self) -> tuple:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def pid(self, p: int, i: int, d: int) -> None:
|
||||||
|
"""
|
||||||
|
Sets the p, i, and d constants of the motor PID controller.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `p` - Proportional constant.
|
||||||
|
- `i` - Integral constant.
|
||||||
|
- `d` - Derivative constant.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- If no arguments are given, this returns the values previously set by the user, if any. The system defaults cannot be read.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def default(self) -> dict:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def default(self, speed: int, max_power: int, acceleration: int, deceleration: int, stop: int, pid: tuple, stall: bool, callback: Optional[Callable[[int], None]]):
|
||||||
|
"""
|
||||||
|
Gets or sets the motor default settings. These are used by some of the methods listed above, when no explicit argument is given.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `speed` - The default speed.
|
||||||
|
- `max_power` - The default max_power.
|
||||||
|
- `acceleration` - The default acceleration.
|
||||||
|
- `deceleration` - The default deceleration.
|
||||||
|
- `stop` - The default stop argument.
|
||||||
|
- `pid` - Tuple of p, i, and d. See also pid.
|
||||||
|
- `stall` - The default stall argument.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- If no arguments are given, this returns the current settings.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def pair(self, other_motor: Motor) -> MotorPair:
|
||||||
|
"""
|
||||||
|
Pairs this motor to other_motor to create a MotorPair object.
|
||||||
|
|
||||||
|
You can only pair two different motors that are not already part of another pair. Both motors must be of the same type.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `other_motor` - The motor to pair to.
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- On success, this returns the MotorPair object. It returns False to indicate an incompatible pair or None for other errors.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class MotorPair():
|
||||||
|
"""
|
||||||
|
This class can be used to control pairs of motors. You create `MotorPair` objects using the `pair()` method of a `Motor` object.
|
||||||
|
|
||||||
|
Control two motors simultaneously in a synchronized way.
|
||||||
|
"""
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def id(self) -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def primary(self) -> Motor:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def secondary(self) -> Motor:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def unpair(self) -> bool:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def float(self) -> None:
|
||||||
|
"""
|
||||||
|
Floats (coasts) the motor, as if disconnected from the hub.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def brake(self) -> None:
|
||||||
|
"""
|
||||||
|
Passively brakes the motor, as if shorting the motor terminals.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def hold(self) -> None:
|
||||||
|
"""
|
||||||
|
Actively hold the motor in its current position.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def pwm(self, pwm_0: int, pwm_1: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_at_speed(self, speed_0: int, speed_1: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_at_speed(self, speed_0: int, speed_1: int, max_power: int, acceleration: int, deceleration: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_for_time(self, msec: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_for_time(self, msec: int, speed_0: int, speed_1: int, max_power: int, acceleration: int, deceleration: int, stop: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_for_degrees(self, degrees: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_for_degrees(self, degrees: int, speed_0: int, speed_1: int, max_power: int, acceleration: int, deceleration: int, stop: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_to_position(self, position_0: int, position_1: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def run_to_position(self, position_0: int, position_1: int, speed: int, max_power: int, acceleration: int, deceleration: int, stop: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def preset(self, position_0: int, position_1: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def callback(self, function: Callable[[int], None]) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def pid(self, p: int, i: int, d: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
class Port():
|
||||||
|
"""
|
||||||
|
This class is the blueprint for the port instances in the `hub.port` module. Those instances are automatically instantiated on boot, and further populated when devices are plugged in. You cannot import or instantiate this class manually.
|
||||||
|
|
||||||
|
Provides access to port configuration and devices on a port. Some methods and attributes can only be used if the port is in the right mode, as shown below.
|
||||||
|
|
||||||
|
Attributes for use with MODE_DEFAULT
|
||||||
|
|
||||||
|
- `device`: Powered Up Device on this port. If no device is attached or the port is in a different mode, this attribute is None.
|
||||||
|
- `motor`: Powered Up Motor on this port. If no motor is attached or the port is in a different mode, this attribute is None.
|
||||||
|
"""
|
||||||
|
# motor: Motor
|
||||||
|
# device: Device
|
||||||
|
# p5: Pin
|
||||||
|
# p6: Pin
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.motor: Motor
|
||||||
|
self.device: Device
|
||||||
|
self.p5: Pin
|
||||||
|
self.p6: Pin
|
||||||
|
|
||||||
|
def info(self) -> dict:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def pwm(self, value: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def callback(self, function: Callable[[int], None]) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def mode(self, mode: int, baud_rate=2400) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def baud(self, baud: int) -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def read(self, read: Union[int, any]) -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def write(self, write: bytes) -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
A: Port
|
||||||
|
B: Port
|
||||||
|
C: Port
|
||||||
|
D: Port
|
||||||
|
E: Port
|
||||||
|
F: Port
|
||||||
|
|
||||||
|
# Constants
|
||||||
|
## Port events
|
||||||
|
DETACHED = 0
|
||||||
|
ATTACHED = 1
|
||||||
|
## Port modes
|
||||||
|
MODE_DEFAULT = 0
|
||||||
|
MODE_FULL_DUPLEX = 1
|
||||||
|
MODE_HALF_DUPLEX = 2
|
||||||
|
MODE_GPIO = 3
|
72
hub/sound.py
Normal file
72
hub/sound.py
Normal file
|
@ -0,0 +1,72 @@
|
||||||
|
from typing import Callable, overload
|
||||||
|
|
||||||
|
"""
|
||||||
|
The sound module lets you control the hub speaker to play sound files and beeps.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def volume() -> int:
|
||||||
|
pass
|
||||||
|
|
||||||
|
@overload
|
||||||
|
def volume(volume: int) -> None:
|
||||||
|
"""
|
||||||
|
Sets the volume of the speaker.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- volume - Volume between 0 (no sound) and 10 (maximum volume).
|
||||||
|
|
||||||
|
### Returns
|
||||||
|
- If no argument is given, this returns the current volume.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def beep(freq=1000, time=1000, waveform=0) -> None:
|
||||||
|
"""
|
||||||
|
Starts beeping with a given frequency, duration, and wave form.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `freq` - Frequency of the beep in Hz (100 - 10000).
|
||||||
|
- `time` - Duration of the beep in milliseconds (0 - 32767).
|
||||||
|
- `waveform` - Wave form used for the beep. See constants for all possible values.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def play(filename: str, rate=16000) -> None:
|
||||||
|
"""
|
||||||
|
Starts playing a sound file.
|
||||||
|
|
||||||
|
The sound file must be raw 16 bit data at 16 kHz.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `filename` - Absolute path to the sound file.
|
||||||
|
|
||||||
|
### Keyword Arguments
|
||||||
|
- `rate` - Playback speed in Hz.
|
||||||
|
|
||||||
|
### Raises
|
||||||
|
- `OSError (ENOENT)` - If the file does not exist.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def callback(self, function: Callable[[int], None]) -> None:
|
||||||
|
"""
|
||||||
|
Sets the callback function that is called when a sound finished playing or when it is interrupted.
|
||||||
|
|
||||||
|
The function must accept one argument, whose value indicates why the callback was called:
|
||||||
|
|
||||||
|
If the value is 0, the sound completed successfully.
|
||||||
|
|
||||||
|
If the value is 1, the sound was interrupted.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `function` - Callable function that takes one argument. Choose None to disable the callback.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
#These values are used by the beep() function.
|
||||||
|
SOUND_SIN = 0 #The beep is a smooth sine wave.
|
||||||
|
SOUND_SQUARE = 1 #The beep is a loud and raw square wave.
|
||||||
|
SOUND_TRIANGLE = 2 #The beep has a triangular wave form.
|
||||||
|
SOUND_SAWTOOTH = 3 #The beep has a sawtooth-shaped wave form.
|
||||||
|
|
42
hub/supervision.py
Normal file
42
hub/supervision.py
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
"""
|
||||||
|
The supervision module lets you monitor critical states of the hub.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def info() -> dict:
|
||||||
|
"""
|
||||||
|
Gets status information from the subsystem that supervises the hub.
|
||||||
|
|
||||||
|
This returns a dictionary of the form:
|
||||||
|
|
||||||
|
```
|
||||||
|
{
|
||||||
|
# Checks if the peak current is too high.
|
||||||
|
'peek_current_too_high': False,
|
||||||
|
|
||||||
|
# Checks if the current is too high.
|
||||||
|
'continous_current_too_high': False,
|
||||||
|
|
||||||
|
# The current value in mA.
|
||||||
|
'continuous_current': 60,
|
||||||
|
|
||||||
|
# Checks if the hub temperature is too high.
|
||||||
|
'temperature_too_high': False
|
||||||
|
}
|
||||||
|
```
|
||||||
|
### Returns
|
||||||
|
- Supervision status information.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def callback(self, function: Callable[[int], None]) -> None:
|
||||||
|
"""
|
||||||
|
Sets the callback function that is called when an over-current event occurs.
|
||||||
|
|
||||||
|
The function must accept one argument, which indicates the current in mA that triggered the callback.
|
||||||
|
|
||||||
|
### Parameters
|
||||||
|
- `function` - Callable function that takes one argument. Choose None to disable the callback.
|
||||||
|
"""
|
||||||
|
pass
|
47
iqrobot.py
Normal file
47
iqrobot.py
Normal file
|
@ -0,0 +1,47 @@
|
||||||
|
# LEGO type:standard slot:6 autostart
|
||||||
|
|
||||||
|
from spike import PrimeHub, Motor, MotorPair, ColorSensor
|
||||||
|
from spike.control import wait_for_seconds
|
||||||
|
|
||||||
|
HELLO = "HELLO IQ"
|
||||||
|
|
||||||
|
'''
|
||||||
|
Wir nutzen "Duck typing", dh wir schreiben hinter jede Variabel mit ':' die Klasse, zB `leftMotor: Motor`
|
||||||
|
damit man dann später auch wieder Code Completion hat bei Nutzung der Variablen
|
||||||
|
'''
|
||||||
|
class IQRobot:
|
||||||
|
|
||||||
|
def __init__(self, hub: PrimeHub, leftMotorPort: str, rightMotorPort: str, colorSensorPort: str):
|
||||||
|
self.hub: PrimeHub = hub
|
||||||
|
self.leftMotor: Motor = Motor(leftMotorPort)
|
||||||
|
self.rightMotor: Motor = Motor(rightMotorPort)
|
||||||
|
self.movementMotors: MotorPair = MotorPair(leftMotorPort, rightMotorPort)
|
||||||
|
self.colorSensor: ColorSensor = ColorSensor(colorSensorPort)
|
||||||
|
|
||||||
|
|
||||||
|
def show(self, image: str):
|
||||||
|
'''
|
||||||
|
Zeige Bild auf LED Matrix des Spikes
|
||||||
|
image: Bildname wie zB 'HAPPY'
|
||||||
|
'''
|
||||||
|
self.hub.light_matrix.show_image(image)
|
||||||
|
|
||||||
|
|
||||||
|
def driveForward(self, seconds: float):
|
||||||
|
# Fahre die übergebene Anzahl seconds gerade aus
|
||||||
|
self.movementMotors.start()
|
||||||
|
wait_for_seconds(seconds)
|
||||||
|
self.movementMotors.stop()
|
||||||
|
|
||||||
|
def getColorIntensity(self):
|
||||||
|
# Ermittele Farbintensität über den Farbsensor
|
||||||
|
(red, green, blue, colorIntensity) = self.colorSensor.get_rgb_intensity()
|
||||||
|
return colorIntensity
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
print("successfully loaded the Backsteinclub code :)")
|
||||||
|
|
||||||
|
|
93
main.py
Normal file
93
main.py
Normal file
|
@ -0,0 +1,93 @@
|
||||||
|
# LEGO type:standard slot:5 autostart
|
||||||
|
|
||||||
|
import os, sys
|
||||||
|
|
||||||
|
from spike import PrimeHub, LightMatrix, Button, StatusLight, ForceSensor, MotionSensor, Speaker, ColorSensor, App, DistanceSensor, Motor, MotorPair
|
||||||
|
from spike.control import wait_for_seconds, wait_until, Timer
|
||||||
|
from hub import battery
|
||||||
|
from math import *
|
||||||
|
|
||||||
|
############## Allgemein: Prüfe Batteriezustand ###############################
|
||||||
|
if battery.voltage() < 8000: #set threshold for battery level
|
||||||
|
print("Spannung der Batterie zu niedrig: " + str(battery.voltage()) + " \n"
|
||||||
|
+ "--------------------------------------- \n "
|
||||||
|
+ "#### UNBEDINGT ROBOTER AUFLADEN !!! #### \n"
|
||||||
|
+ "---------------------------------------- \n")
|
||||||
|
else:
|
||||||
|
print("Spannung der Batterie " + str(battery.voltage()) + "\n")
|
||||||
|
################################################################################
|
||||||
|
|
||||||
|
############################## NICHT ÄNDERN ###############################
|
||||||
|
def importFile(slotid=0, precompiled=False, module_name='importFile'):
|
||||||
|
print("##### START # IMPORTING CODE FROM SLOT "+str(slotid)+" ##############")
|
||||||
|
import os, sys
|
||||||
|
suffix = ".py"
|
||||||
|
if precompiled:
|
||||||
|
suffix = ".mpy"
|
||||||
|
with open("/projects/.slots","rt") as f:
|
||||||
|
slots = eval(str(f.read()))
|
||||||
|
print(slots)
|
||||||
|
print(os.listdir("/projects/"+str(slots[slotid]["id"])))
|
||||||
|
with open("/projects/"+str(slots[slotid]["id"])+"/__init__"+suffix,"rb") as f:
|
||||||
|
print("trying to read import program")
|
||||||
|
program = f.read()
|
||||||
|
print(program)
|
||||||
|
try:
|
||||||
|
os.remove("/"+module_name+suffix)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
with open("/"+module_name+suffix,"w+") as f:
|
||||||
|
print("trying to write import program")
|
||||||
|
f.write(program)
|
||||||
|
if (module_name in sys.modules):
|
||||||
|
del sys.modules[module_name]
|
||||||
|
#exec("from " + module_name + " import *")
|
||||||
|
print("##### END # IMPORTING CODE FROM SLOT "+str(slotid)+" ##############")
|
||||||
|
#####################################################################################
|
||||||
|
|
||||||
|
|
||||||
|
################ Importiere Code aus andere Dateien #################################
|
||||||
|
|
||||||
|
# Importiere Code aus der Datei "iqrobot.py"
|
||||||
|
# Dateiname und Modulname sollten gleich sein, dann kann man Code Completion nutzen
|
||||||
|
importFile(slotid=6, precompiled=True, module_name="iqrobot")
|
||||||
|
import iqrobot as iq
|
||||||
|
print(iq.HELLO)
|
||||||
|
|
||||||
|
# Importiere Go Robot Code
|
||||||
|
#importFile(slotid=3, precompiled=True, module_name="gorobot")
|
||||||
|
#import gorobot as gr
|
||||||
|
#gr.exampleFour()
|
||||||
|
#gr.db.gyroRotation(90, 25, 35, 25)
|
||||||
|
|
||||||
|
|
||||||
|
################### Hauptcode ####################################
|
||||||
|
'''
|
||||||
|
Code zum Lösen einer Aufgabe, kann oben importierten Code nutzen
|
||||||
|
Es können auch pro Aufgabe eigene Funktionen geschrieben werden
|
||||||
|
Wichtig ist, dass die PORTS der Sensoren überall gleich sind
|
||||||
|
und auch `hub` als Instanz von PrimeHub
|
||||||
|
dh auch an die Funktionen im importierten Code übergeben werde
|
||||||
|
'''
|
||||||
|
|
||||||
|
# Definiere an welchen Ports die Sensoren angeschlossen sind
|
||||||
|
COLOR_SENSOR_PORT = 'E'
|
||||||
|
LEFT_MOTOR_PORT = 'A'
|
||||||
|
RIGHT_MOTOR_PORT = 'B'
|
||||||
|
|
||||||
|
# Initialisieren des Hubs, der Aktoren und Sensoren
|
||||||
|
hub = PrimeHub()
|
||||||
|
|
||||||
|
# Initialisiere Robot Klasse mit unseren Funktionen
|
||||||
|
iqRobot: iq.IQRobot = iq.IQRobot(hub, LEFT_MOTOR_PORT, RIGHT_MOTOR_PORT, COLOR_SENSOR_PORT)
|
||||||
|
|
||||||
|
# Führe Funktionen aus unser Robot Klasse aus:
|
||||||
|
iqRobot.show('HAPPY')
|
||||||
|
iqRobot.driveForward(2.0)
|
||||||
|
colorIntensity = iqRobot.getColorIntensity()
|
||||||
|
print("Farbintensität: " + str(colorIntensity))
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
1839
spike/__init__.py
Normal file
1839
spike/__init__.py
Normal file
File diff suppressed because it is too large
Load diff
103
spike/control.py
Normal file
103
spike/control.py
Normal file
|
@ -0,0 +1,103 @@
|
||||||
|
def wait_for_seconds(seconds):
|
||||||
|
"""
|
||||||
|
Waits for a specified number of seconds before continuing the program.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
--------------
|
||||||
|
seconds : The time to wait in seconds.
|
||||||
|
|
||||||
|
Type : float (decimal value)
|
||||||
|
|
||||||
|
Values : any value
|
||||||
|
|
||||||
|
Default : no default value
|
||||||
|
|
||||||
|
Errors
|
||||||
|
----------------
|
||||||
|
TypeError : seconds is not a number.
|
||||||
|
|
||||||
|
ValueError : seconds is not at least 0.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def wait_until(get_value_function, operator_function, target_value=True):
|
||||||
|
"""
|
||||||
|
Waits until the condition is True before continuing with the program.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
--------------
|
||||||
|
get_value_function
|
||||||
|
|
||||||
|
Type : callable function
|
||||||
|
|
||||||
|
Values : A function that returns the current value to be compared to the target value.
|
||||||
|
|
||||||
|
Default : no default value
|
||||||
|
|
||||||
|
operator_function
|
||||||
|
|
||||||
|
Type : callable function
|
||||||
|
|
||||||
|
Values : A function that compares two arguments. The first argument will be the result of get_value_function() and the second argument will be target_value. The function will compare these two values and return the result.
|
||||||
|
|
||||||
|
Default : no default value
|
||||||
|
|
||||||
|
target_value
|
||||||
|
|
||||||
|
Type : any type
|
||||||
|
|
||||||
|
Values : Any object that can be compared by operator_function.
|
||||||
|
|
||||||
|
Default : no default value
|
||||||
|
|
||||||
|
Errors
|
||||||
|
----------------
|
||||||
|
TypeError : get_value_function or operator_function is not callable or operator_function does not compare two arguments.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
def greater_than(a, b):
|
||||||
|
"""
|
||||||
|
Tests whether value a is greater than value b.
|
||||||
|
This is the same as a > b.
|
||||||
|
|
||||||
|
Parameters
|
||||||
|
---------
|
||||||
|
a : Any object that can be compared to b.
|
||||||
|
|
||||||
|
Type : any type
|
||||||
|
|
||||||
|
Values : any value
|
||||||
|
|
||||||
|
Default : no default value
|
||||||
|
|
||||||
|
b : Any object that can be compared to a.
|
||||||
|
|
||||||
|
Type : any type
|
||||||
|
|
||||||
|
Values : any value
|
||||||
|
|
||||||
|
Default : no default value
|
||||||
|
|
||||||
|
Returns
|
||||||
|
---------
|
||||||
|
Type : boolean
|
||||||
|
|
||||||
|
Values : True if a > b, otherwise False.
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
|
||||||
|
class Timer:
|
||||||
|
def __init__(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def reset(self):
|
||||||
|
"""
|
||||||
|
Sets the Timer to "0."
|
||||||
|
"""
|
||||||
|
pass
|
||||||
|
def now(self):
|
||||||
|
"""
|
||||||
|
Retrieves the "right now" time of the Timer
|
||||||
|
"""
|
||||||
|
pass
|
BIN
vscode-lego-extension-precompile.png
Normal file
BIN
vscode-lego-extension-precompile.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 361 KiB |
BIN
vscode-lego-extension-settings.png
Normal file
BIN
vscode-lego-extension-settings.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 439 KiB |
Loading…
Reference in a new issue