Let's control EV3 motors and sensors with Python

This article is an entry for ET Robocon Advent Calendar 2016 12/22.


Hello, this is Haneuma.

Until last year, our team "Galaxy Haneuma" participated in ET Robocon in Java, This year, I changed my mind and tried to participate in Python.

However, even when I looked up the information to try it, I couldn't find the information I needed. So, I hope it will be helpful for those who want to run LEGO Mindstorms EV3 with Python from now on. I decided to write this article. This article is intended for Windows because it seems to have many users.

In the future, I will post stories about the Python development environment and the ev3dev cross-compilation environment.

Execution environment

OS: ev3dev 2016-10-17 Release version (Debian-based Linux) Library used: python-ev3dev 0.8.0 (There is a library called ** python-ev3 **, but be careful because it is different) Python version: Python 3.4.2 (Be sure to use Python3 because python-ev3dev 0.8.0 does not support Python2)

Install / start ev3dev

[Reference] Getting Started with ev3dev-ev3dev.org

  1. Download the OS image from the ev3dev official website Click "Download for EV3" at the link below to download the ZIP file. Downloads-ev3dev.org (The version at the time of writing is 2016-10-17 version)

  2. Extract the downloaded ZIP file The ev3dev image file is extracted. (In the 2016-10-17 version, the image file name is "ev3dev-jessie-ev3-generic-2016-10-17.img")

  3. Write the image file to the SD card Use Win32DiskImager to write the extracted image file to the SD card. The writing procedure is described on the following site, so please refer to it. → [SD Card Preparation-OpenRTM-aist](http://openrtm.org/openrtm/ja/content/sd-%E3%82%AB%E3%83%BC%E3%83%89%E3%81] % AE% E6% BA% 96% E5% 82% 99)

The supported SD cards are ** 2GB ~ 32GB </ font> ** ** microSD or microSDHC </ font> **. Please note that microSDXC is not supported.

  1. Insert the written SD card into EV3 and start EV3 The boot log is output, and after waiting for a while, the menu screen is displayed. If the menu screen is displayed, it is successful.

Connect ev3dev to the network

There are several ways to connect your EV3 to your network:

--Wireless LAN connection using wifi dongle → EV3-Python programming (ev3dev) environment wifi connection procedure-Afrel

--Wired LAN connection using a USB LAN adapter → Confirmed operation with Buffalo LUA3-U2-ATX

--Connect using a USB cable (Type A-mini B) → Operation confirmed with the USB cable attached to the educational version LEGO Mindstorms EV3 basic set V2

--Connect using built-in Bluetooth → Operation unconfirmed

  • When connecting to a LAN, it is necessary to set the IP address manually or in an environment where DHCP can be used.

Remote login to EV3 with SSH

Log in to ev3dev using SSH. Here, we are connecting using TeraTerm.

  1. After starting TeraTerm, enter the IP address of EV3 in the host and click the "OK" button. ssh_1.png
  • The IP address is displayed in the upper left of the screen of the EV3 main unit.
  1. If a security warning window is displayed, click the "Continue" button. ssh_2.png

  2. Enter your username and passphrase (password). ID: ** robot ** / Pass: ** maker ** ssh_3.png

  3. Login is successful and the ev3dev logo is displayed on the terminal. ssh_4.png

python-ev3dev update

python-ev3dev included in ev3dev 2016-10-17 Release version will be updated because the version is 0.7.0. (Because the API around the sensor has changed slightly in python-ev3dev 0.8.0, please be careful if you have the source code implemented in the previous version)

robot@ev3dev:~$ sudo apt-get update
robot@ev3dev:~$ sudo apt-get install --only-upgrade python3-ev3dev
  • You will be asked to enter the password in the middle of the command, so enter maker.

Sample program

Below is a sample program for motor control and sensor control. Save the character code of the program in UTF-8.

Motor control

motor.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ev3dev.ev3 as ev3
import time

#Instantiate motor class
m = ev3.LargeMotor('outA')
#Rotate the motor for 3 seconds
m.run_timed(time_sp=3000, speed_sp=500)

#5 loops
for i in range(0,5):
    #Display motor status on standard output
    print(m.state())
    #Sleep for 1 second
    time.sleep(1)

Sensor control (color sensor)

color.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ev3dev.ev3 as ev3

#Instantiate color sensor class
c = ev3.ColorSensor('in1')

#Displays the light reflection intensity of the red LED
print(c.reflected_light_intensity)
#Show sensor mode
print(c.mode)

#Display RGB values
print(c.raw)
#Show sensor mode
print(c.mode)

#Display the acquired color(0:colorless, 1:black, 2:Blue, 3:Green, 4:yellow, 5:Red, 6:White, 7:tea)
print(c.color)
#Show sensor mode
print(c.mode)

Motor + sensor control

motor_color.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import ev3dev.ev3 as ev3
import time

#Instantiate motor class
m = ev3.LargeMotor('outA')

#Instantiate color sensor class
c = ev3.ColorSensor('in1')

#Rotate the motor(Keep spinning until you call stop)
m.run_forever(speed_sp=300)

#Loop until the color sensor detects black
while c.color != 1:
    #Display the acquired color(0:colorless, 1:black, 2:Blue, 3:Green, 4:yellow, 5:Red, 6:White, 7:tea)
    print(c.color)
    #Sleep for 1 second
    time.sleep(1)
    
#Stop the motor(After stopping, stop to fix the position of the motor_Specify hold for action)
m.stop(stop_action="hold")

Transfer of sample program

Since ev3dev can use SFTP by default, it is recommended to use WinSCP when transferring sample programs from Windows. I will omit the operation method of WinSCP.

The settings used for connection are as follows. Transfer protocol: SFTP Host name: IP address displayed in the upper left of the EV3 screen Port number: 22 Username: robot Password: maker

Execution of sample program

This time, we will use the sample program motor.py as an example.

When executing from the terminal

robot@ev3dev:~$ pwd
/home/robot
robot@ev3dev:~$ ls
color.py  motor.py  motor_color.py
robot@ev3dev:~$ python3 motor.py

Execution result

robot@ev3dev:~$ python3 motor.py
['running', 'stalled']
['running']
['running']
[]
[]
robot@ev3dev:~$ 

When booting from the EV3 main unit

If you want to start a program from the EV3 main unit, you need to grant the execution right to the target program in advance. Use the chmod command to grant execution rights.

robot@ev3dev:~$ pwd
/home/robot
robot@ev3dev:~$ ls -l
total 12
-rw-r--r-- 1 robot robot 522 Dec 21 07:55 color.py
-rw-r--r-- 1 robot robot 236 Dec 21 04:19 motor.py
-rw-r--r-- 1 robot robot 735 Dec 21 08:03 motor_color.py
robot@ev3dev:~$ chmod +x motor.py
robot@ev3dev:~$ ls -l
total 12
-rw-r--r-- 1 robot robot 522 Dec 21 07:55 color.py
-rwxr-xr-x 1 robot robot 236 Dec 21 04:19 motor.py
-rw-r--r-- 1 robot robot 735 Dec 21 08:03 motor_color.py
robot@ev3dev:~$

After granting the execution right, select File Browser from the screen of the EV3 main unit. You can move the cursor with the up and down buttons on the EV3 main unit, and make decisions with the center button.

When you open the File Browser, you will first see under / home / robot, so select motor.py. If the execution right has been granted successfully, an asterisk will be displayed next to the file name.

After selecting a file, the program will run, and when it finishes, you will be returned to the File Browser screen.

Execution result

['running', 'stalled']
['running']
['running']
[]
[]

problem

Here are some of the issues I noticed during development.

--Two-wheeled inverted pendulum library is not provided → ET Robocon 2016 officially announced that primary classes cannot participate. Available Platform Information-ET Robocon 2016

--The LED of the color sensor cannot be turned off → Due to the specifications of the OS, the LED of the color sensor cannot be turned off, so a sloppy line trace cannot be performed.

--An error occurs when RGB values are continuously acquired by the color sensor. → If you are using a color sensor, an error may occur when acquiring the value. Checking with dmesg on Linux, is it related to the buffer overrun error? (If anyone knows the cause, please let me know)

--Processing speed is slow → Since the processing speed is slower than RTOS such as TOPPERS, it may be disadvantageous in the competition of ET Robocon.

API Here is an example of using some of the motor class APIs.

-Motor class

motorApiTest.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import ev3dev.ev3 as ev3
import time

l = ev3.LargeMotor('outA')  #EV3 Interactive Servo Motor L
m = ev3.MediumMotor('outB') #EV3 Interactive Servo Motor M

print(l.count_per_rot) #Motor count per revolution

l.speed_sp = 200 #Set target speed(200 counts per second)
print(l.speed_sp) #Display the set target speed value

l.run_forever() #Rotate the motor
m.run_forever(speed_sp=200) #It is also possible to set the speed at the same time as rotation

time.sleep(2)

l.speed_sp = 300 #Change motor rotation speed
l.run_forever()

m.speed_sp = -200 #Reverse rotation of motor
m.run_forever()

time.sleep(2)

l.stop_action = 'hold' #Set the motor state when stopped to "fixed"
print(l.stop_action) #Display the operation after the motor is stopped

l.stop() #Stop the motor
m.stop(stop_action='brake') #Stop the motor(Set the motor state when stopped to "brake"

print(l.position) #Display motor count value

#Rotate the motor for 100 counts
l.run_to_abs_pos(position_sp=l.position_sp+100) #Absolute value specification
m.run_to_rel_pos(position_sp=100) #Relative value specification

Recommended Posts