Created
May 20, 2019 06:14
-
-
Save yosoufe/c74106efe106dfc86fe5fa08e650f197 to your computer and use it in GitHub Desktop.
Code of MeArmMicroBit to read the Serial port and Drive the servos
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Add your Python code here. E.g. | |
from microbit import * | |
import time | |
###### Initialization of the hardware ###### | |
# Turn off display to use display pins as GPIO | |
display.off() | |
# initialize the pins to control the Servos | |
gripper = pin16 | |
right = pin15 | |
left = pin14 | |
base = pin13 | |
servos = [right, left, base, gripper] | |
for servo in servos: | |
servo.set_analog_period_microseconds(20000) | |
servo.write_analog(76) | |
# initialize serial communication (UART over USB) | |
uart.init(baudrate=115200) | |
# Input string | |
inStr = None | |
# list of values for all 4 servos (4 unsigned integers) | |
servoValues = [] | |
def inStr2servoValues(): | |
""" | |
split and cast the string into integer numbers | |
""" | |
global servoValues, inStr | |
servoValues = [int(a) for a in inStr.split(',')] | |
def parseInputStr(): | |
""" | |
filter the string input based on the starting and ending byte | |
The string input should be comma separated and starting with `s` and ending with `e` | |
It is not being checked that it is comma separated but it should be. | |
example of string: "s19,80,60,110e" | |
Returns True if this sequence of string is complete. Otherwise False | |
""" | |
global inStr | |
msg = uart.read(1) | |
ch = str(msg, 'UTF-8') | |
if ch == 's': | |
inStr = str() | |
elif ch == 'e' and len(inStr)!= 0: | |
inStr2servoValues() | |
inStr = None | |
return True | |
elif inStr != None: | |
inStr += ch | |
return False | |
def updateServos(): | |
""" | |
Update servos and generate the PWMs | |
""" | |
global servoValues, servos | |
for i in range(4): | |
servos[i].write_analog(servoValues[i]) | |
# Main Loop | |
while True: | |
# check if there is any serial character availble | |
if (uart.any()): | |
# reads and parse the character | |
if(parseInputStr()): | |
if(len(servoValues) == 4): | |
# update the servos | |
updateServos() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment