mirror of
https://github.com/pybricks/pybricks-api.git
synced 2026-09-12 01:24:17 +00:00
all: Format with black.
Also activate auto formatting. Bump flake8 and mark black disagreements in setup.cfg.
This commit is contained in:
@@ -9,17 +9,17 @@
|
||||
from pybricks.messaging import BluetoothMailboxClient, TextMailbox
|
||||
|
||||
# This is the name of the remote EV3 or PC we are connecting to.
|
||||
SERVER = 'ev3dev'
|
||||
SERVER = "ev3dev"
|
||||
|
||||
client = BluetoothMailboxClient()
|
||||
mbox = TextMailbox('greeting', client)
|
||||
mbox = TextMailbox("greeting", client)
|
||||
|
||||
print('establishing connection...')
|
||||
print("establishing connection...")
|
||||
client.connect(SERVER)
|
||||
print('connected!')
|
||||
print("connected!")
|
||||
|
||||
# In this program, the client sends the first message and then waits for the
|
||||
# server to reply.
|
||||
mbox.send('hello!')
|
||||
mbox.send("hello!")
|
||||
mbox.wait()
|
||||
print(mbox.read())
|
||||
|
||||
@@ -17,17 +17,17 @@ from pybricks.messaging import BluetoothMailboxClient, TextMailbox
|
||||
# visible on the EV3. You can skip pairing if you already know the EV3 address.
|
||||
|
||||
# This is the address of the server EV3 we are connecting to.
|
||||
SERVER = 'CC:78:AB:D8:4E:F6'
|
||||
SERVER = "CC:78:AB:D8:4E:F6"
|
||||
|
||||
client = BluetoothMailboxClient()
|
||||
mbox = TextMailbox('greeting', client)
|
||||
mbox = TextMailbox("greeting", client)
|
||||
|
||||
print('establishing connection...')
|
||||
print("establishing connection...")
|
||||
client.connect(SERVER)
|
||||
print('connected!')
|
||||
print("connected!")
|
||||
|
||||
# In this program, the client sends the first message and then waits for the
|
||||
# server to reply.
|
||||
mbox.send('hello!')
|
||||
mbox.send("hello!")
|
||||
mbox.wait()
|
||||
print(mbox.read())
|
||||
|
||||
@@ -18,17 +18,17 @@ BDADDR_ANY = ""
|
||||
|
||||
def str2ba(string, ba):
|
||||
"""Convert string to Bluetooth address"""
|
||||
for i, v in enumerate(string.split(':')):
|
||||
ba.b[5-i] = int(v, 16)
|
||||
for i, v in enumerate(string.split(":")):
|
||||
ba.b[5 - i] = int(v, 16)
|
||||
|
||||
|
||||
def ba2str(ba):
|
||||
"""Convert Bluetooth address to string"""
|
||||
string = []
|
||||
for b in ba.b:
|
||||
string.append('{:02X}'.format(b))
|
||||
string.append("{:02X}".format(b))
|
||||
string.reverse()
|
||||
return ':'.join(string).upper()
|
||||
return ":".join(string).upper()
|
||||
|
||||
|
||||
class RFCOMMServer:
|
||||
@@ -37,6 +37,7 @@ class RFCOMMServer:
|
||||
This is based on the ``socketserver.SocketServer`` class in the Python
|
||||
standard library.
|
||||
"""
|
||||
|
||||
request_queue_size = 1
|
||||
|
||||
def __init__(self, server_address, RequestHandlerClass):
|
||||
@@ -88,6 +89,7 @@ class StreamRequestHandler:
|
||||
This is based on ``socketserver.StreamRequestHandler`` from the Python
|
||||
standard library.
|
||||
"""
|
||||
|
||||
def __init__(self, request, client_address, server):
|
||||
self.request = request
|
||||
self.client_address = client_address
|
||||
@@ -113,6 +115,7 @@ class ThreadingRFCOMMServer(ThreadingMixIn, RFCOMMServer):
|
||||
"""Version of :class:`RFCOMMServer` that handles connections in a new
|
||||
thread.
|
||||
"""
|
||||
|
||||
pass
|
||||
|
||||
|
||||
|
||||
@@ -5,8 +5,12 @@ from _thread import allocate_lock
|
||||
from errno import ECONNRESET
|
||||
from struct import pack, unpack
|
||||
|
||||
from .bluetooth import (BDADDR_ANY, ThreadingRFCOMMServer,
|
||||
ThreadingRFCOMMClient, StreamRequestHandler)
|
||||
from .bluetooth import (
|
||||
BDADDR_ANY,
|
||||
ThreadingRFCOMMServer,
|
||||
ThreadingRFCOMMClient,
|
||||
StreamRequestHandler,
|
||||
)
|
||||
|
||||
|
||||
def resolve(brick):
|
||||
@@ -99,7 +103,7 @@ class LogicMailbox(Mailbox):
|
||||
"""
|
||||
|
||||
def encode(self, value):
|
||||
return b'\x01' if value else b'\x00'
|
||||
return b"\x01" if value else b"\x00"
|
||||
|
||||
def decode(self, payload):
|
||||
return bool(payload[0])
|
||||
@@ -113,10 +117,10 @@ class NumericMailbox(Mailbox):
|
||||
"""
|
||||
|
||||
def encode(self, value):
|
||||
return pack('<f', value)
|
||||
return pack("<f", value)
|
||||
|
||||
def decode(self, payload):
|
||||
return unpack('<f', payload)[0]
|
||||
return unpack("<f", payload)[0]
|
||||
|
||||
|
||||
class TextMailbox(Mailbox):
|
||||
@@ -127,10 +131,10 @@ class TextMailbox(Mailbox):
|
||||
"""
|
||||
|
||||
def encode(self, value):
|
||||
return ('{}\0'.format(value)).encode('utf-8')
|
||||
return ("{}\0".format(value)).encode("utf-8")
|
||||
|
||||
def decode(self, payload):
|
||||
return payload.decode().strip('\0')
|
||||
return payload.decode().strip("\0")
|
||||
|
||||
|
||||
# EV3 standard firmware is hard-coded to use channel 1
|
||||
@@ -155,16 +159,16 @@ class MailboxHandler(StreamRequestHandler):
|
||||
if ex.args[0] == ECONNRESET:
|
||||
break
|
||||
raise
|
||||
size, = unpack('<H', buf)
|
||||
(size,) = unpack("<H", buf)
|
||||
buf = self.rfile.recv(size)
|
||||
msg_count, cmd_type, cmd, name_size = unpack('<HBBB', buf[0:5])
|
||||
msg_count, cmd_type, cmd, name_size = unpack("<HBBB", buf[0:5])
|
||||
if cmd_type != SYSTEM_COMMAND_NO_REPLY:
|
||||
raise ValueError('Bad message type')
|
||||
raise ValueError("Bad message type")
|
||||
if cmd != WRITEMAILBOX:
|
||||
raise ValueError('Bad command')
|
||||
mbox = buf[5:5+name_size].decode().strip('\0')
|
||||
data_size, = unpack('<H', buf[5+name_size:7+name_size])
|
||||
data = buf[7+name_size:7+name_size+data_size]
|
||||
raise ValueError("Bad command")
|
||||
mbox = buf[5 : 5 + name_size].decode().strip("\0")
|
||||
(data_size,) = unpack("<H", buf[5 + name_size : 7 + name_size])
|
||||
data = buf[7 + name_size : 7 + name_size + data_size]
|
||||
|
||||
with self.server._lock:
|
||||
self.server._mailboxes[mbox] = data
|
||||
@@ -216,9 +220,18 @@ class MailboxHandlerMixIn:
|
||||
mbox_len = len(mbox) + 1
|
||||
payload_len = len(payload)
|
||||
send_len = 7 + mbox_len + payload_len
|
||||
fmt = '<HHBBB{}sH{}s'.format(mbox_len, payload_len)
|
||||
data = pack(fmt, send_len, 1, SYSTEM_COMMAND_NO_REPLY, WRITEMAILBOX,
|
||||
mbox_len, mbox.encode('utf-8'), payload_len, payload)
|
||||
fmt = "<HHBBB{}sH{}s".format(mbox_len, payload_len)
|
||||
data = pack(
|
||||
fmt,
|
||||
send_len,
|
||||
1,
|
||||
SYSTEM_COMMAND_NO_REPLY,
|
||||
WRITEMAILBOX,
|
||||
mbox_len,
|
||||
mbox.encode("utf-8"),
|
||||
payload_len,
|
||||
payload,
|
||||
)
|
||||
with self._lock:
|
||||
if brick is None:
|
||||
for client in self._clients.values():
|
||||
@@ -255,7 +268,8 @@ class BluetoothMailboxServer(MailboxHandlerMixIn, ThreadingRFCOMMServer):
|
||||
"""
|
||||
super().__init__()
|
||||
super(ThreadingRFCOMMServer, self).__init__(
|
||||
(BDADDR_ANY, EV3_RFCOMM_CHANNEL), MailboxHandler)
|
||||
(BDADDR_ANY, EV3_RFCOMM_CHANNEL), MailboxHandler
|
||||
)
|
||||
|
||||
def wait_for_connection(self, count=1):
|
||||
"""Waits for a :class:`BluetoothMailboxClient` on a remote device to
|
||||
@@ -326,7 +340,7 @@ class BluetoothMailboxClient(MailboxHandlerMixIn):
|
||||
raise ValueError('no paired devices matching "{}"'.format(brick))
|
||||
client = MailboxRFCOMMClient(self, addr)
|
||||
if self._clients.setdefault(addr, client) is not client:
|
||||
raise ValueError('connection with this address already exists')
|
||||
raise ValueError("connection with this address already exists")
|
||||
try:
|
||||
client.handle_request()
|
||||
except Exception:
|
||||
|
||||
@@ -1,15 +1,9 @@
|
||||
|
||||
from uctypes import addressof, sizeof, struct
|
||||
from usocket import socket, SOCK_STREAM
|
||||
|
||||
from _thread import start_new_thread
|
||||
|
||||
from pybricks.bluetooth import (
|
||||
str2ba,
|
||||
sockaddr_rc,
|
||||
AF_BLUETOOTH,
|
||||
BTPROTO_RFCOMM
|
||||
)
|
||||
from pybricks.bluetooth import str2ba, sockaddr_rc, AF_BLUETOOTH, BTPROTO_RFCOMM
|
||||
from pybricks.tools import wait, StopWatch
|
||||
|
||||
|
||||
@@ -25,7 +19,7 @@ def get_bluetooth_rfcomm_socket(address, channel):
|
||||
return sock
|
||||
|
||||
|
||||
class SpikePrimeStreamReader():
|
||||
class SpikePrimeStreamReader:
|
||||
def __init__(self, address):
|
||||
|
||||
try:
|
||||
@@ -56,8 +50,8 @@ class SpikePrimeStreamReader():
|
||||
break
|
||||
try:
|
||||
data = eval(raw)
|
||||
if data['m'] == 0:
|
||||
self._values = data['p']
|
||||
if data["m"] == 0:
|
||||
self._values = data["p"]
|
||||
except (SyntaxError, KeyError):
|
||||
pass
|
||||
|
||||
@@ -65,8 +59,8 @@ class SpikePrimeStreamReader():
|
||||
return self._values
|
||||
|
||||
def device(self, port):
|
||||
if 'A' <= port <= 'F':
|
||||
return self.values()[ord(port)-ord('A')][1]
|
||||
if "A" <= port <= "F":
|
||||
return self.values()[ord(port) - ord("A")][1]
|
||||
else:
|
||||
raise ValueError
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ ev3 = EV3Brick()
|
||||
ev3.speaker.beep()
|
||||
|
||||
# Create the connection. See README.md to find the address for your SPIKE hub.
|
||||
spike = SpikePrimeStreamReader('F4:84:4C:AA:C8:A4')
|
||||
spike = SpikePrimeStreamReader("F4:84:4C:AA:C8:A4")
|
||||
|
||||
# Now you can simply read values!
|
||||
for i in range(100):
|
||||
|
||||
@@ -12,7 +12,7 @@ ev3 = EV3Brick()
|
||||
ev3.speaker.beep()
|
||||
|
||||
# Create the connection. See README.md to find the address for your SPIKE hub.
|
||||
spike = SpikePrimeStreamReader('F4:84:4C:AA:C8:A4')
|
||||
spike = SpikePrimeStreamReader("F4:84:4C:AA:C8:A4")
|
||||
|
||||
# Initialize the motors and drive base
|
||||
left_motor = Motor(Port.B)
|
||||
@@ -24,5 +24,5 @@ while True:
|
||||
yaw, pitch, roll = spike.orientation()
|
||||
|
||||
# Set speed and turn rate based on orientation
|
||||
robot.drive(-pitch*6, roll*2)
|
||||
robot.drive(-pitch * 6, roll * 2)
|
||||
wait(20)
|
||||
|
||||
@@ -9,15 +9,15 @@
|
||||
from pybricks.messaging import BluetoothMailboxServer, TextMailbox
|
||||
|
||||
server = BluetoothMailboxServer()
|
||||
mbox = TextMailbox('greeting', server)
|
||||
mbox = TextMailbox("greeting", server)
|
||||
|
||||
# The server must be started before the client!
|
||||
print('waiting for connection...')
|
||||
print("waiting for connection...")
|
||||
server.wait_for_connection()
|
||||
print('connected!')
|
||||
print("connected!")
|
||||
|
||||
# In this program, the server waits for the client to send the first message
|
||||
# and then sends a reply.
|
||||
mbox.wait()
|
||||
print(mbox.read())
|
||||
mbox.send('hello to you!')
|
||||
mbox.send("hello to you!")
|
||||
|
||||
@@ -8,7 +8,7 @@ def wait_for_button(ev3):
|
||||
"""
|
||||
|
||||
# Show a picture of the buttons on the screen.
|
||||
ev3.screen.load_image('buttons.png')
|
||||
ev3.screen.load_image("buttons.png")
|
||||
|
||||
# Tip: add text or icons to the image to help you
|
||||
# remember what each button will do in your program.
|
||||
|
||||
@@ -8,7 +8,7 @@ from pybricks.tools import DataLog, StopWatch, wait
|
||||
# log_2020_02_13_10_07_44_431260.csv
|
||||
# * You can optionally specify the titles of your data columns. For example,
|
||||
# if you want to record the motor angles at a given time, you could do:
|
||||
data = DataLog('time', 'angle')
|
||||
data = DataLog("time", "angle")
|
||||
|
||||
# Initialize a motor and make it move
|
||||
wheel = Motor(Port.B)
|
||||
|
||||
@@ -3,13 +3,13 @@ from pybricks.parameters import Color
|
||||
from pybricks.tools import DataLog
|
||||
|
||||
# Create a data log file called my_file.txt
|
||||
data = DataLog('time', 'angle', name='my_file', timestamp=False, extension='txt')
|
||||
data = DataLog("time", "angle", name="my_file", timestamp=False, extension="txt")
|
||||
|
||||
# The log method uses the print() method to add a line of text.
|
||||
# So, you can do much more than saving numbers. For example:
|
||||
data.log('Temperature', 25)
|
||||
data.log('Sunday', 'Monday', 'Tuesday')
|
||||
data.log({'Kiwi': Color.GREEN}, {'Banana': Color.YELLOW})
|
||||
data.log("Temperature", 25)
|
||||
data.log("Sunday", "Monday", "Tuesday")
|
||||
data.log({"Kiwi": Color.GREEN}, {"Banana": Color.YELLOW})
|
||||
|
||||
# You can upload the file to your computer, but you can also print the data:
|
||||
print(data)
|
||||
|
||||
@@ -13,22 +13,22 @@ class MySensor(Ev3devSensor):
|
||||
super().__init__(port)
|
||||
|
||||
# Get the sysfs path.
|
||||
self.path = '/sys/class/lego-sensor/sensor' + str(self.sensor_index)
|
||||
self.path = "/sys/class/lego-sensor/sensor" + str(self.sensor_index)
|
||||
|
||||
def get_modes(self):
|
||||
"""Get a list of mode strings so we don't have to look them up."""
|
||||
|
||||
# The path of the modes file.
|
||||
modes_path = self.path + '/modes'
|
||||
modes_path = self.path + "/modes"
|
||||
|
||||
# Open the modes file.
|
||||
with open(modes_path, 'r') as m:
|
||||
with open(modes_path, "r") as m:
|
||||
|
||||
# Read the contents.
|
||||
contents = m.read()
|
||||
|
||||
# Strip the newline symbol, and split at every space symbol.
|
||||
return contents.strip().split(' ')
|
||||
return contents.strip().split(" ")
|
||||
|
||||
|
||||
# Initialize the sensor
|
||||
|
||||
@@ -10,10 +10,10 @@ sensor = Ev3devSensor(Port.S3)
|
||||
|
||||
while True:
|
||||
# Read the raw RGB values
|
||||
r, g, b = sensor.read('RGB-RAW')
|
||||
r, g, b = sensor.read("RGB-RAW")
|
||||
|
||||
# Print results
|
||||
print('R: {0}\t G: {1}\t B: {2}'.format(r, g, b))
|
||||
print("R: {0}\t G: {1}\t B: {2}".format(r, g, b))
|
||||
|
||||
# Wait
|
||||
wait(200)
|
||||
|
||||
@@ -10,7 +10,7 @@ ev3 = EV3Brick()
|
||||
device = I2CDevice(Port.S2, 0xD2 >> 1)
|
||||
|
||||
# Recommended for reading
|
||||
result, = device.read(reg=0x0F, length=1)
|
||||
(result,) = device.read(reg=0x0F, length=1)
|
||||
|
||||
# Read 1 byte from no particular register:
|
||||
device.read(reg=None, length=1)
|
||||
@@ -23,10 +23,10 @@ device.read(reg=None, length=0)
|
||||
# can choose to skip the register or data as follows:
|
||||
|
||||
# Recommended for writing:
|
||||
device.write(reg=0x22, data=b'\x08')
|
||||
device.write(reg=0x22, data=b"\x08")
|
||||
|
||||
# Write 1 byte to no particular register:
|
||||
device.write(reg=None, data=b'\x08')
|
||||
device.write(reg=None, data=b"\x08")
|
||||
|
||||
# Write 0 bytes to a particular register:
|
||||
device.write(reg=0x08, data=None)
|
||||
|
||||
@@ -21,7 +21,7 @@ in_file = open(infile_path, "rb")
|
||||
|
||||
# Define the format the event data will be read.
|
||||
# https://docs.python.org/3/library/struct.html#format-characters
|
||||
FORMAT = 'llHHi'
|
||||
FORMAT = "llHHi"
|
||||
EVENT_SIZE = struct.calcsize(FORMAT)
|
||||
event = in_file.read(EVENT_SIZE)
|
||||
|
||||
@@ -30,10 +30,11 @@ event = in_file.read(EVENT_SIZE)
|
||||
# numbers (-100 to 100)
|
||||
def scale(val, src, dst):
|
||||
|
||||
result = (float(val - src[0]) / (src[1] - src[0]))
|
||||
result = float(val - src[0]) / (src[1] - src[0])
|
||||
result = result * (dst[1] - dst[0]) + dst[0]
|
||||
return result
|
||||
|
||||
|
||||
# Create a loop to react to events
|
||||
# This loop reacte to all main PS4 button and stick events. I have left out
|
||||
# buttons like share and options, but can easily be added in by referring
|
||||
|
||||
@@ -7,7 +7,7 @@ from pybricks.tools import wait
|
||||
|
||||
class RCXTouchSensor(AnalogSensor):
|
||||
def pressed(self):
|
||||
return self.resistance() < 50*1000
|
||||
return self.resistance() < 50 * 1000
|
||||
|
||||
|
||||
ev3 = EV3Brick()
|
||||
|
||||
@@ -15,12 +15,24 @@ ev3 = EV3Brick()
|
||||
# SPLIT SCREEN ################################################################
|
||||
|
||||
# Make a sub-image for the left half of the screen
|
||||
left = Image(ev3.screen, sub=True, x1=0, y1=0,
|
||||
x2=ev3.screen.width // 2 - 1, y2=ev3.screen.height - 1)
|
||||
left = Image(
|
||||
ev3.screen,
|
||||
sub=True,
|
||||
x1=0,
|
||||
y1=0,
|
||||
x2=ev3.screen.width // 2 - 1,
|
||||
y2=ev3.screen.height - 1,
|
||||
)
|
||||
|
||||
# Make a sub-image for the right half of the screen
|
||||
right = Image(ev3.screen, sub=True, x1=ev3.screen.width // 2, y1=0,
|
||||
x2=ev3.screen.width - 1, y2=ev3.screen.height - 1)
|
||||
right = Image(
|
||||
ev3.screen,
|
||||
sub=True,
|
||||
x1=ev3.screen.width // 2,
|
||||
y1=0,
|
||||
x2=ev3.screen.width - 1,
|
||||
y2=ev3.screen.height - 1,
|
||||
)
|
||||
|
||||
# Use a monospaced font so that text is vertically aligned when we print
|
||||
right.set_font(Font(size=8, monospace=True))
|
||||
@@ -53,7 +65,7 @@ for t in range(200):
|
||||
|
||||
# Print every 10th value on right side
|
||||
if t % 10 == 0:
|
||||
right.print('{:10.2f}{:10.2f}'.format(x1, y1))
|
||||
right.print("{:10.2f}{:10.2f}".format(x1, y1))
|
||||
|
||||
wait(100)
|
||||
|
||||
@@ -64,8 +76,8 @@ for t in range(200):
|
||||
buf = Image(ev3.screen)
|
||||
|
||||
# Load images from file
|
||||
bg = Image('background.png')
|
||||
sprite = Image('sprite.png')
|
||||
bg = Image("background.png")
|
||||
sprite = Image("sprite.png")
|
||||
|
||||
# Number of cells in each sprite animation
|
||||
NUM_CELLS = 8
|
||||
@@ -75,12 +87,28 @@ CELL_WIDTH, CELL_HEIGHT = 75, 100
|
||||
|
||||
# Get sub-images for each individual cell
|
||||
# This is more efficient that loading individual images
|
||||
walk_right = [Image(sprite, sub=True, x1=x * CELL_WIDTH, y1=0,
|
||||
x2=(x + 1) * CELL_WIDTH - 1, y2=CELL_HEIGHT - 1)
|
||||
for x in range(NUM_CELLS)]
|
||||
walk_left = [Image(sprite, sub=True, x1=x * CELL_WIDTH, y1=CELL_HEIGHT,
|
||||
x2=(x + 1) * CELL_WIDTH - 1, y2=2 * CELL_HEIGHT - 1)
|
||||
for x in range(NUM_CELLS)]
|
||||
walk_right = [
|
||||
Image(
|
||||
sprite,
|
||||
sub=True,
|
||||
x1=x * CELL_WIDTH,
|
||||
y1=0,
|
||||
x2=(x + 1) * CELL_WIDTH - 1,
|
||||
y2=CELL_HEIGHT - 1,
|
||||
)
|
||||
for x in range(NUM_CELLS)
|
||||
]
|
||||
walk_left = [
|
||||
Image(
|
||||
sprite,
|
||||
sub=True,
|
||||
x1=x * CELL_WIDTH,
|
||||
y1=CELL_HEIGHT,
|
||||
x2=(x + 1) * CELL_WIDTH - 1,
|
||||
y2=2 * CELL_HEIGHT - 1,
|
||||
)
|
||||
for x in range(NUM_CELLS)
|
||||
]
|
||||
|
||||
|
||||
# Walk from left to right
|
||||
|
||||
@@ -8,7 +8,7 @@ from pybricks.media.ev3dev import Font
|
||||
# load them once at the beginning of the program like this:
|
||||
tiny_font = Font(size=6)
|
||||
big_font = Font(size=24, bold=True)
|
||||
chinese_font = Font(size=24, lang='zh-cn')
|
||||
chinese_font = Font(size=24, lang="zh-cn")
|
||||
|
||||
|
||||
# Initialize the EV3
|
||||
@@ -16,19 +16,19 @@ ev3 = EV3Brick()
|
||||
|
||||
|
||||
# Say hello
|
||||
ev3.screen.print('Hello!')
|
||||
ev3.screen.print("Hello!")
|
||||
|
||||
# Say tiny hello
|
||||
ev3.screen.set_font(tiny_font)
|
||||
ev3.screen.print('hello')
|
||||
ev3.screen.print("hello")
|
||||
|
||||
# Say big hello
|
||||
ev3.screen.set_font(big_font)
|
||||
ev3.screen.print('HELLO')
|
||||
ev3.screen.print("HELLO")
|
||||
|
||||
# Say Chinese hello
|
||||
ev3.screen.set_font(chinese_font)
|
||||
ev3.screen.print('你好')
|
||||
ev3.screen.print("你好")
|
||||
|
||||
# Wait some time to look at the screen
|
||||
wait(5000)
|
||||
|
||||
@@ -26,9 +26,23 @@ wait(1000)
|
||||
# PLAY NOTES ##################################################################
|
||||
|
||||
# Twinkle, Twinkle Little Star
|
||||
A = ['C4/4', 'C4/4', 'G4/4', 'G4/4', 'A4/4', 'A4/4', 'G4/2',
|
||||
'F4/4', 'F4/4', 'E4/4', 'E4/4', 'D4/4', 'D4/4', 'C4/2']
|
||||
B = ['G4/4', 'G4/4', 'F4/4', 'F4/4', 'E4/4', 'E4/4', 'D4/2'] * 2
|
||||
A = [
|
||||
"C4/4",
|
||||
"C4/4",
|
||||
"G4/4",
|
||||
"G4/4",
|
||||
"A4/4",
|
||||
"A4/4",
|
||||
"G4/2",
|
||||
"F4/4",
|
||||
"F4/4",
|
||||
"E4/4",
|
||||
"E4/4",
|
||||
"D4/4",
|
||||
"D4/4",
|
||||
"C4/2",
|
||||
]
|
||||
B = ["G4/4", "G4/4", "F4/4", "F4/4", "E4/4", "E4/4", "D4/2"] * 2
|
||||
TWINKLE = A + B + A
|
||||
|
||||
ev3.speaker.play_notes(TWINKLE)
|
||||
@@ -46,10 +60,10 @@ wait(1000)
|
||||
# TEXT TO SPEECH ##############################################################
|
||||
|
||||
# Say something in English
|
||||
ev3.speaker.say('I am am E V 3. Pleased to meet you.')
|
||||
ev3.speaker.say("I am am E V 3. Pleased to meet you.")
|
||||
|
||||
# Say something in Danish + female
|
||||
ev3.speaker.set_speech_options(voice='da+f5')
|
||||
ev3.speaker.say('Leg godt!')
|
||||
ev3.speaker.set_speech_options(voice="da+f5")
|
||||
ev3.speaker.say("Leg godt!")
|
||||
|
||||
wait(1000)
|
||||
|
||||
@@ -11,7 +11,7 @@ ev3 = EV3Brick()
|
||||
ser = UARTDevice(Port.S2, baudrate=115200)
|
||||
|
||||
# Write some data
|
||||
ser.write(b'\r\nHello, world!\r\n')
|
||||
ser.write(b"\r\nHello, world!\r\n")
|
||||
|
||||
# Play a sound while we wait for some data
|
||||
for i in range(3):
|
||||
|
||||
@@ -10,8 +10,8 @@ def convert_raw_to_temperature(voltage):
|
||||
|
||||
# Convert the raw voltage to the NTC resistance
|
||||
# according to the Vernier Adapter EV3 block.
|
||||
counts = voltage/5000*4096
|
||||
ntc = 15000*(counts)/(4130-counts)
|
||||
counts = voltage / 5000 * 4096
|
||||
ntc = 15000 * (counts) / (4130 - counts)
|
||||
|
||||
# Handle log(0) safely: make sure that ntc value is positive.
|
||||
if ntc <= 0:
|
||||
@@ -21,7 +21,7 @@ def convert_raw_to_temperature(voltage):
|
||||
K0 = 1.02119e-3
|
||||
K1 = 2.22468e-4
|
||||
K2 = 1.33342e-7
|
||||
return 1/(K0 + K1*log(ntc) + K2*log(ntc)**3)
|
||||
return 1 / (K0 + K1 * log(ntc) + K2 * log(ntc) ** 3)
|
||||
|
||||
|
||||
# Initialize the adapter on port 1
|
||||
|
||||
@@ -12,12 +12,11 @@ hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
|
||||
wait(10000)
|
||||
|
||||
# Make the color RED grow faint and bright using a sine pattern.
|
||||
hub.light.animate(
|
||||
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
|
||||
hub.light.animate([Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
|
||||
|
||||
wait(10000)
|
||||
|
||||
# Cycle through a rainbow of colors.
|
||||
hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)
|
||||
hub.light.animate([Color(h=i * 8) for i in range(45)], interval=40)
|
||||
|
||||
wait(10000)
|
||||
|
||||
@@ -12,7 +12,7 @@ hub.light.off()
|
||||
brightness = list(range(0, 100, 4)) + list(range(100, 0, -4))
|
||||
|
||||
# Create an animation of the heart icon with changing brightness.
|
||||
hub.display.animate([Icon.HEART * i/100 for i in brightness], 30)
|
||||
hub.display.animate([Icon.HEART * i / 100 for i in brightness], 30)
|
||||
|
||||
# The animation repeats in the background. Here we just wait.
|
||||
while True:
|
||||
|
||||
@@ -12,15 +12,15 @@ while True:
|
||||
|
||||
# Start with random left brow: up or down.
|
||||
if randint(0, 100) < 70:
|
||||
brows = Icon.EYE_LEFT_BROW*0.5
|
||||
brows = Icon.EYE_LEFT_BROW * 0.5
|
||||
else:
|
||||
brows = Icon.EYE_LEFT_BROW_UP*0.5
|
||||
brows = Icon.EYE_LEFT_BROW_UP * 0.5
|
||||
|
||||
# Add random right brow: up or down.
|
||||
if randint(0, 100) < 70:
|
||||
brows += Icon.EYE_RIGHT_BROW*0.5
|
||||
brows += Icon.EYE_RIGHT_BROW * 0.5
|
||||
else:
|
||||
brows += Icon.EYE_RIGHT_BROW_UP*0.5
|
||||
brows += Icon.EYE_RIGHT_BROW_UP * 0.5
|
||||
|
||||
for i in range(3):
|
||||
# Display eyes open plus the random brows.
|
||||
@@ -28,5 +28,7 @@ while True:
|
||||
wait(2000)
|
||||
|
||||
# Display eyes blinked plus the random brows.
|
||||
hub.display.image(Icon.EYE_LEFT_BLINK*0.7 + Icon.EYE_RIGHT_BLINK*0.7 + brows)
|
||||
hub.display.image(
|
||||
Icon.EYE_LEFT_BLINK * 0.7 + Icon.EYE_RIGHT_BLINK * 0.7 + brows
|
||||
)
|
||||
wait(200)
|
||||
|
||||
@@ -6,13 +6,15 @@ from pybricks.geometry import Matrix
|
||||
hub = PrimeHub()
|
||||
|
||||
# Make a square that is bright on the outside and faint in the middle.
|
||||
SQUARE = Matrix([
|
||||
[100, 100, 100, 100, 100],
|
||||
[100, 50, 50, 50, 100],
|
||||
[100, 50, 0, 50, 100],
|
||||
[100, 50, 50, 50, 100],
|
||||
[100, 100, 100, 100, 100],
|
||||
])
|
||||
SQUARE = Matrix(
|
||||
[
|
||||
[100, 100, 100, 100, 100],
|
||||
[100, 50, 50, 50, 100],
|
||||
[100, 50, 0, 50, 100],
|
||||
[100, 50, 50, 50, 100],
|
||||
[100, 100, 100, 100, 100],
|
||||
]
|
||||
)
|
||||
|
||||
# Display the square.
|
||||
hub.display.image(SQUARE)
|
||||
|
||||
@@ -5,8 +5,8 @@ from pybricks.tools import wait
|
||||
hub = PrimeHub()
|
||||
|
||||
# Display the letter A for two seconds.
|
||||
hub.display.char('A')
|
||||
hub.display.char("A")
|
||||
wait(2000)
|
||||
|
||||
# Display text, one letter at a time.
|
||||
hub.display.text('Hello, world!')
|
||||
hub.display.text("Hello, world!")
|
||||
|
||||
@@ -12,12 +12,11 @@ hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
|
||||
wait(10000)
|
||||
|
||||
# Make the color RED grow faint and bright using a sine pattern.
|
||||
hub.light.animate(
|
||||
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
|
||||
hub.light.animate([Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
|
||||
|
||||
wait(10000)
|
||||
|
||||
# Cycle through a rainbow of colors.
|
||||
hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)
|
||||
hub.light.animate([Color(h=i * 8) for i in range(45)], interval=40)
|
||||
|
||||
wait(10000)
|
||||
|
||||
@@ -13,12 +13,11 @@ hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
|
||||
wait(10000)
|
||||
|
||||
# Make the color RED grow faint and bright using a sine pattern.
|
||||
hub.light.animate(
|
||||
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
|
||||
hub.light.animate([Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
|
||||
|
||||
wait(10000)
|
||||
|
||||
# Cycle through a rainbow of colors.
|
||||
hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)
|
||||
hub.light.animate([Color(h=i * 8) for i in range(45)], interval=40)
|
||||
|
||||
wait(10000)
|
||||
|
||||
@@ -3,10 +3,10 @@
|
||||
import os
|
||||
|
||||
# Get list of scripts to be parsed
|
||||
script_names = [f for f in os.listdir('.') if f != 'make_shared_examples.py']
|
||||
script_names = [f for f in os.listdir(".") if f != "make_shared_examples.py"]
|
||||
|
||||
# Go through all template scripts
|
||||
for script in (open(f, 'r') for f in script_names):
|
||||
for script in (open(f, "r") for f in script_names):
|
||||
|
||||
# First line contains hub info
|
||||
hubs = script.readline().strip().split()[3:]
|
||||
@@ -15,17 +15,17 @@ for script in (open(f, 'r') for f in script_names):
|
||||
|
||||
for hub in hubs:
|
||||
# Determine path to the hub
|
||||
hub_path = os.path.join('..', 'hub_' + hub.lower())
|
||||
hub_path = os.path.join("..", "hub_" + hub.lower())
|
||||
|
||||
# Reset source script
|
||||
script.seek(0)
|
||||
script.readline()
|
||||
|
||||
# Open destination script:
|
||||
with open(os.path.join(hub_path, script.name), 'w') as dest_file:
|
||||
with open(os.path.join(hub_path, script.name), "w") as dest_file:
|
||||
|
||||
# Read script line by line
|
||||
for line in script.readlines():
|
||||
|
||||
# Replace hub name if present
|
||||
dest_file.writelines(line.replace('ExampleHub', hub))
|
||||
dest_file.writelines(line.replace("ExampleHub", hub))
|
||||
|
||||
@@ -12,12 +12,11 @@ hub.light.animate([Color.RED, Color.GREEN, Color.NONE], interval=500)
|
||||
wait(10000)
|
||||
|
||||
# Make the color RED grow faint and bright using a sine pattern.
|
||||
hub.light.animate(
|
||||
[Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
|
||||
hub.light.animate([Color.RED * (0.5 * sin(i / 15 * pi) + 0.5) for i in range(30)], 40)
|
||||
|
||||
wait(10000)
|
||||
|
||||
# Cycle through a rainbow of colors.
|
||||
hub.light.animate([Color(h=i*8) for i in range(45)], interval=40)
|
||||
hub.light.animate([Color(h=i * 8) for i in range(45)], interval=40)
|
||||
|
||||
wait(10000)
|
||||
|
||||
@@ -51,7 +51,7 @@ for port in ports:
|
||||
raise
|
||||
|
||||
# Get the device id
|
||||
id = device.info()['id']
|
||||
id = device.info()["id"]
|
||||
|
||||
# Look up the name.
|
||||
try:
|
||||
|
||||
@@ -15,10 +15,10 @@ MAX = 100
|
||||
# Make the brightness fade in and out.
|
||||
while True:
|
||||
# Get phase of the cosine.
|
||||
phase = watch.time()/PERIOD*2*pi
|
||||
phase = watch.time() / PERIOD * 2 * pi
|
||||
|
||||
# Evaluate the brightness.
|
||||
brightness = (0.5 - 0.5*cos(phase))*MAX
|
||||
brightness = (0.5 - 0.5 * cos(phase)) * MAX
|
||||
|
||||
# Set light brightness and wait a bit.
|
||||
light.on(brightness)
|
||||
|
||||
@@ -7,6 +7,6 @@ my_remote = Remote()
|
||||
print(my_remote.name())
|
||||
|
||||
# Choose a new name.
|
||||
my_remote.name('truck2')
|
||||
my_remote.name("truck2")
|
||||
|
||||
print("Done!")
|
||||
|
||||
@@ -2,7 +2,7 @@ from pybricks.pupdevices import Remote
|
||||
from pybricks.tools import wait
|
||||
|
||||
# Connect to a remote called truck2.
|
||||
truck_remote = Remote('truck2', timeout=None)
|
||||
truck_remote = Remote("truck2", timeout=None)
|
||||
|
||||
print("Connected!")
|
||||
|
||||
|
||||
@@ -15,12 +15,12 @@ PERIOD = 3000
|
||||
|
||||
while True:
|
||||
# The phase is where we are in the unit circle now.
|
||||
phase = watch.time()/PERIOD*2*pi
|
||||
phase = watch.time() / PERIOD * 2 * pi
|
||||
|
||||
# Each light follows a sine wave with a mean of 50, with an amplitude of 50.
|
||||
# We offset this sine wave by 90 degrees for each light, so that all the
|
||||
# lights do something different.
|
||||
brightness = [sin(phase + offset*pi/2) * 50 + 50 for offset in range(4)]
|
||||
brightness = [sin(phase + offset * pi / 2) * 50 + 50 for offset in range(4)]
|
||||
|
||||
# Set the brightness values for all lights.
|
||||
eyes.lights.on(brightness)
|
||||
|
||||
Reference in New Issue
Block a user