https://en.wikipedia.org/wiki/Lego_Mindstorms
The ev3dev operating system
The Python EV3 libraries
The motors and how to program them
Popular third-party sensors and parts
Extending the Python libraries to support custom sensors (might cut this one out if running short on time)
Other options to explore
Demo
In [ ]:
#https://github.com/plamere/spotipy
import requests
import spotipy
sp = spotipy.Spotify()
results = sp.search(q='i like to move it move it', limit=20)
for i, t in enumerate(results['tracks']['items']):
print ' ', i, t['name']
with file(r'c:\temp\moveit.mp3','wb') as out:
out.write(requests.get(results['tracks']['items'][0]['preview_url']).content)
import os
os.startfile(r'c:\temp\moveit.mp3')
In [ ]:
# TODO
* toddler photo i had a dream
* word cloud for parts
* picasa collage for parts
* lego intro
* mindstorms robots
* what: tecnic, brain, software
* where: buy online 499 ebay less
* why: community
* history: nxt
* education edition vs home edition
In [6]:
!dir
In [ ]:
%config SqlMagic.autopandas = True
In [ ]:
%%sql sqlite://
CREATE TABLE presidents (first, last, yob);
INSERT INTO presidents VALUES ('George', 'Washington', 1732);
In [1]:
import pandas as pd
import numpy as np
from pivottablejs import pivot_ui
df = pd.read_csv(r'C:\Users\Stoyan\Downloads\ev3set-parts-inventory.csv')
In [2]:
df.head()
Out[2]:
In [48]:
import requests
import os
root = r'C:\work\pyconau2017\pyconau2017\images\parts'
for row in df.itertuples():
#print(row, type(row), dir(row))
name = row.PartName.replace('Ø','').replace('°','').replace('/','-').replace(',','').replace('.','').replace(' ',' ').replace(' ','_')
try:
with open(os.path.join(root, '{0}.jpg'.format(name)), 'wb') as out:
out.write(requests.get(row.ImageURL).content)
except Exception as e:
print(e.args[0], name)
In [50]:
for row in df.itertuples():
#print(row, type(row), dir(row))
name = row.PartName.replace('Ø','').replace('°','').replace('/','-').replace(',','').replace('.','').replace(' ',' ').replace(' ','_')
print(name, row.ImageURL)
In [49]:
names = []
for row in df.itertuples():
#print(row, type(row), dir(row))
name = row.PartName.replace('Ø','').replace('°','').replace('/','-').replace(',','').replace('.','').replace(' ',' ').replace(' ','_')
for i in range(0, row.Quantity):
names.append(name)
with open(os.path.join(root, 'parts.txt'), 'w') as out:
out.write(' '.join(names))
In [3]:
pivot_ui(df)
Out[3]:
| #Programming Lego Mindstorms with Python# |
In [58]:
import glob
from PIL import Image
#https://stackoverflow.com/questions/35438802/making-a-collage-in-pil
'''im= Image.open('Tulips.jpg')
out=im.convert("RGB", (
0.412453, 0.357580, 0.180423, 0,
0.212671, 0.715160, 0.072169, 0,
0.019334, 0.119193, 0.950227, 0 ))
out.save("Image2.jpg")
out2=im.convert("RGB", (
0.9756324, 0.154789, 0.180423, 0,
0.212671, 0.715160, 0.254783, 0,
0.123456, 0.119193, 0.950227, 0 ))
out2.save("Image3.jpg")
out3= im.convert("1")
out3.save("Image4.jpg")
out4=im.convert("RGB", (
0.986542, 0.154789, 0.756231, 0,
0.212671, 0.715160, 0.254783, 0,
0.123456, 0.119193, 0.112348, 0 ))
out4.save("Image5.jpg")
out5=Image.blend(im, out4, 0.5)
out5.save("Image6.jpg")'''
listofimages=['Tulips.jpg', 'Image2.jpg', 'Image3.jpg', 'Image4.jpg', 'Image5.jpg', 'Image6.jpg']
listofimages = glob.glob(r'C:\work\pyconau2017\pyconau2017\images\parts\*.jpg')
print(len(listofimages))
def create_collage(width, height, listofimages):
cols = 10
rows = 10
thumbnail_width = width//cols
thumbnail_height = height//rows
size = thumbnail_width, thumbnail_height
new_im = Image.new('RGB', (width, height))
ims = []
for p in listofimages:
im = Image.open(p)
im.thumbnail(size)
ims.append(im)
i = 0
x = 0
y = 0
for col in range(cols):
for row in range(rows):
print(i, x, y)
if i<len(ims):
new_im.paste(ims[i], (x, y))
i += 1
y += thumbnail_height
x += thumbnail_width
y = 0
new_im.save(r"C:\work\pyconau2017\pyconau2017\images\Collage.jpg")
create_collage(500, 500, listofimages)
In [ ]:
import os
ps=[]
for p in os.listdir(r'C:\work\pyconau2017\pyconau2017\images'):
if p.startswith('Product'):
ps.append(''.format(p))
print(' | '.join(ps))
In [ ]:
#!/usr/bin/env python3
from ev3dev.ev3 import *
from time import sleep
from PIL import Image
lcd = Screen()
logo = Image.open('pics/Bomb.bmp')
lcd.image.paste(logo, (0,0))
lcd.update()
sleep(5)
f = ImageFont.truetype('/usr/share/fonts/truetype/msttcorefonts/Arial.ttf', 75)
lcd.draw.text((3,0), 'Hello', font=f)
lcd.draw.text((2,55), 'world', font=f)
lcd.update()
sleep(7)
lcd.draw.text((10,10), 'Hello World!', font=fonts.load('luBS14'))
lcd.update()
sleep(8)
lcd.draw.rectangle((0,0,177,40), fill='black')
lcd.draw.text((48,13),'Hello, world.', fill='white')
my_string='THIS TEXT IS BLACK'
print(lcd.draw.textsize(my_string))
lcd.draw.text((36,80),my_string)
lcd.update()
sleep(6)
lcd.draw.rectangle((0,0,177,40), fill='black')
lcd.draw.text((48,13),'Hello, world.', fill='white')
lcd.draw.text((36,80),'THIS TEXT IS BLACK')
lcd.update()
sleep(6)
In [ ]:
#!/usr/bin/env python3
from time import sleep
from ev3dev.ev3 import *
lcd = Screen()
smile = True
while True:
lcd.clear()
# lcd.draw returns a PIL.ImageDraw handle
lcd.draw.ellipse(( 20, 20, 60, 60))
lcd.draw.ellipse((118, 20, 158, 60))
if smile:
lcd.draw.arc((20, 80, 158, 100), 0, 180)
else:
lcd.draw.arc((20, 80, 158, 100), 180, 360)
smile = not smile # toggle between True and False
# Update lcd display
lcd.update() # Applies pending changes to the screen.
# Nothing will be drawn on the lcd screen
# until this function is called.
sleep(1)
In [ ]:
screen = ev3.Screen()
def draw_face():
w,h = screen.shape
y = h // 2
eye_xrad = 20
eye_yrad = 30
pup_xrad = 10
pup_yrad = 10
def draw_eye(x):
screen.draw.ellipse((x-eye_xrad, y-eye_yrad, x+eye_xrad, y+eye_yrad))
screen.draw.ellipse((x-pup_xrad, y-pup_yrad, x+pup_xrad, y+pup_yrad), fill='black')
draw_eye(w//3)
draw_eye(2*w//3)
screen.update()
draw_face()
In [ ]:
#!/usr/bin/env python3
from ev3dev.ev3 import *
from time import sleep
btn = Button()
# Do something when state of any button changes:
def left(state):
if state:
print('Left button pressed')
else:
print('Left button released')
def right(state): # neater use of 'if' follows:
print('Right button pressed' if state else 'Right button released')
def up(state):
print('Up button pressed' if state else 'Up button released')
def down(state):
print('Down button pressed' if state else 'Down button released')
def enter(state):
print('Enter button pressed' if state else 'Enter button released')
def backspace(state):
print('Backspace button pressed' if state else 'Backspace button released')
btn.on_left = left
btn.on_right = right
btn.on_up = up
btn.on_down = down
btn.on_enter = enter
btn.on_backspace = backspace
while True: # This loop checks buttons state continuously,
# calls appropriate event handlers
btn.process() # Check for currently pressed buttons.
# If the new state differs from the old state,
# call the appropriate button event handlers.
sleep(0.01) # buttons state will be checked every 0.01 second
# If running this script via SSH, press Ctrl+C to quit
# if running this script from Brickman, long-press backspace button to quit
def change(changed_buttons): # changed_buttons is a list of
# tuples of changed button names and their states.
print('These buttons changed state: ' + str(changed_buttons))
btn.on_change = change
while True: # This loop checks buttons state
# continuously and calls appropriate event handlers
btn.process()
sleep(0.01)
while True:
if btn.any(): # Checks if any button is pressed.
exit()
else:
sleep(0.01) # Check for button press every 0.01 second
while not btn.backspace:
print(btn.left)
sleep(1)
#end the script by pressing ONLY the left and right buttons simultaneously
while True:
print(btn.buttons_pressed)
if btn.check_buttons(buttons=['left','right']):
exit()
sleep(1)
In [ ]:
# This demo shows how to remote control an Explor3r robot
#
# Red buttons control left motor, blue buttons control right motor.
# Leds are used to indicate movement direction.
from time import sleep
from ev3dev.ev3 import *
# Connect two large motors on output ports B and C
lmotor = LargeMotor('outB')
rmotor = LargeMotor('outC')
# Check that the motors are actually connected
assert lmotor.connected
assert rmotor.connected
# Connect remote control
rc = RemoteControl(); assert rc.connected
# Initialize button handler
# button = Button() # not working so disabled
# Turn leds off
Leds.all_off()
def roll(motor, led_group, direction):
"""
Generate remote control event handler. It rolls given motor into given
direction (1 for forward, -1 for backward). When motor rolls forward, the
given led group flashes green, when backward -- red. When motor stops, the
leds are turned off.
The on_press function has signature required by RemoteControl class.
It takes boolean state parameter; True when button is pressed, False
otherwise.
"""
def on_press(state):
if state:
# Roll when button is pressed
motor.run_forever(speed_sp=90*direction)
Leds.set_color(led_group, direction > 0 and Leds.GREEN or Leds.RED)
else:
# Stop otherwise
motor.stop(stop_action='brake')
Leds.set(led_group, brightness_pct=0)
return on_press
# Assign event handler to each of the remote buttons
rc.on_red_up = roll(lmotor, Leds.LEFT, 1)
rc.on_red_down = roll(lmotor, Leds.LEFT, -1)
rc.on_blue_up = roll(rmotor, Leds.RIGHT, 1)
rc.on_blue_down = roll(rmotor, Leds.RIGHT, -1)
# Enter event processing loop
#while not button.any(): #not working so commented out
while True: #replaces previous line so use Ctrl-C to exit
rc.process()
sleep(0.01)
# Press Ctrl-C to exit