tutorial (ev3)

✏️ Edit this page on GitHub

#contents

This page explains the EV3 operation procedures used in the RTM seminar.


In this hands-on session, you will control the following modified Educator Vehicle.



LEGO Mindstorms EV3 is a new package in the LEGO Mindstorms series. The main EV3 controller comes with Linux preinstalled, enabling robot development in a variety of programming languages.

Specifications

LEGO Mindstorms EV3 Specifications
Processor ARM9 300MHz
Memory (ROM) 16MB Flash
Memory (RAM) 64MB RAM
OS Linux-based
Display 178 x 128 pixels
Output Ports 4
Input Ports 4
Analog
Digital 460.8kbit/s
USB Communication Speed High Speed (480Mbps)
USB Interface Can connect EV3 units together (up to 4 units)
Wi-Fi communication dongles supported
SD Card Slot Supports Micro SD cards up to 32GB
Smart Device Connectivity iOS, Android, Windows
User Interface 6 buttons, illumination function
Program Size (Line Tracing Example) 0.950KB
Sensor Communication Performance 1000 times/sec, 1ms
Data Logging Up to 1,000 samples/sec
Bluetooth Communication Can connect up to 7 slave devices
Power Source Rechargeable battery or six AA batteries

Devices

The EV3 includes the following devices.

Gyro Sensor Angle Mode: Accuracy +/- 3°
Angular Velocity Mode: Up to 440 deg/sec
Sampling Rate: 1,000 Hz
Color Sensor Measures reflected red light, ambient brightness, and color
Detectable Colors: 8 (None, Black, Blue, Green, Yellow, Red, White, Brown)
Sampling Rate: 1,000 Hz
Distance: Approx. 1mm–18mm (Afrel measurement)
Touch Sensor On (1), Off (0)
Switch Travel Distance: Approx. 4mm
Ultrasonic Sensor Measurement Range: 3cm–250cm
Accuracy: +/- 1cm
Front Indicator: Solid = transmitting, Flashing = receiving
EV3 Large Motor Feedback Resolution: 1°
Rotation Speed: 160–170RPM
Rated Torque: 0.21 N·m
Stall Torque: 0.42 N·m
Weight: 76g
EV3 Medium Motor Feedback Resolution: 1°
Rotation Speed: 240–250RPM
Rated Torque: 0.08 N·m
Stall Torque: 0.12 N·m
Weight: 36g

Download

First, download the RTCs and related tools used on the PC side.

Extract the ZIP file using a tool such as Lhaplus.

Assembling the EV3

Participants receive the EV3 in a disassembled state.

Follow the assembly instructions below.

The ultrasonic sensor, color sensor, and gyro sensor are not used during the seminar and do not need to be installed. Steps marked with ※ may be completed if time permits.

First, take out the base assembly.



Connect a 25cm cable to the Medium Motor first. ※



Next, attach the EV3 main unit.

If you connected the cable to the Medium Motor, route it through the opening on the left side.


;
;



Attach the right touch sensor.


;
;



Attach the ultrasonic sensor. ※



Connect the cables.

The required devices are:

  • Right Large Motor
  • Left Large Motor
  • Touch Sensor
Right Large Motor Port C 25cm cable
Left Large Motor Port B 25cm cable
Medium Motor ※ Port A 25cm cable
Right Touch Sensor Port 3 35cm cable
Left Touch Sensor Port 1 35cm cable
Ultrasonic Sensor ※ Port 4 50cm cable
Gyro Sensor ※ Port 2 25cm cable

The EV3 has ports A–D and 1–4 on the top and bottom. Connect the cables to the appropriate ports.

Powering On and Off

Power On

Press the center button to turn on the EV3.

Power Off

From the main screen, press the Back button (upper-left button on the EV3) and select Power Off.

Reboot

From the main screen, press the Back button and select Reboot.

Reset

If ev3dev stops during startup, press and hold the Center, Back (upper-left), and Left buttons simultaneously. When the screen turns off, release the Back button to reboot.

Connecting to the EV3

As a general rule, connect to the EV3 via Wi-Fi.

Connecting to the Wi-Fi Access Point

Press the center button to power on the EV3.

Before powering it on, make sure the Wi-Fi adapter is attached.

Execute the provided script to start the access point.

From the EV3 menu, select File Browser and press the center button.

Then select the scripts folder.

From the next screen, select start_ap.sh and press the center button.

After a short time, the wireless access point will start.

Connect to the designated SSID.

The SSID and password are written on the label attached to the EV3.

Connecting via USB Cable

The following procedure is only required for wired connections. If you are using Wi-Fi, skip this section.

Connect the EV3 to the PC using the supplied USB cable.

Press the center button to power on the EV3.

Before powering on, remove the Wi-Fi adapter.

If the ev3dev startup screen appears, startup was successful.

If startup freezes, perform the reset procedure described earlier.

If “EV3+ev3dev” appears under “Other Devices” in Device Manager, update the device driver according to the instructions provided in the document.

Preparation

Follow the procedure on this page to start the Name Server and RT System Editor.

If the Name Server is already running, restart it before proceeding.

If two or more network interfaces are available, communication may fail. Therefore, when using a wired connection, disable other network devices before starting the Name Server.





Adding the Name Server

Next, use the Add Name Server button in RT System Editor and add 192.168.0.1 (or 192.168.11.1 when connecting via wireless LAN).


;
;



An RTC named EducatorVehicle0 will then become visible.

EducatorVehicle is a component used for inputting EV3 driving speeds, outputting sensor data, and related functions.



EducatorVehicle
InPort
Name Data Type Description
velocity2D RTC::TimedVelocity2D Target velocity
angle RTC::TimedDouble M motor angle
lcd RTC::TimedString Image file name to display on the LCD
sound RTC::TimedString Audio to output
OutPort
Name Data Type Description
odometry RTC::TimedPose2D Current position and orientation
ultrasonic RTC::RangeData Distance measured by the ultrasonic sensor
gyro RTC::TimedDouble Angle measured by the gyro sensor
color RTC::TimedString Color measured by the color sensor
light_reflect RTC::TimedDouble Reflected light intensity measured by the color sensor
touch RTC::TimedBoolean Touch sensor ON/OFF state. The right side is element 0 and the left side is element 1.
Configuration Parameters
Name Default Value Description
wheelRadius 0.028 Wheel radius
wheelDistance 0.054 Half of the distance between the wheels
medium_motor_speed 1.6 M motor speed

About the TimedVelocity2D Type

The TimedVelocity2D type is defined as follows.

     struct Velocity2D
     {
         double vx;
         double vy;
         double va;
     };
     struct TimedVelocity2D
     {
         Time tm;
         Velocity2D data;
     };

vx, vy, and va represent velocities in the robot-centered coordinate system.



vx represents velocity in the X direction, vy represents velocity in the Y direction, and va represents angular velocity around the Z axis.

For a robot such as the Educator Vehicle, which has two wheels mounted on the left and right sides, vy becomes 0 if side-slipping is assumed not to occur.

The robot is controlled by specifying vx and va.

Audio Output

The following commands can be used for audio input through the sound port.

  • beep
    • Entering beep produces a beep sound.
  • tone
    • Enter tone, frequency, and duration as shown below to play a sound at the specified frequency for the specified number of milliseconds.
tone,100,1000
  • Other strings
    • Any other string will be spoken as speech.

Images Displayed on the LCD

For images displayed on the LCD, use images converted by:

software/saveBinaryImage/EXE/saveBinaryImage.exe

included in the distributed materials.

Drag and drop an image file onto saveBinaryImage.exe to perform the conversion.

Starting the Sample Components

Start start_component_ev3.bat included in the distributed materials.

If the Python version of OpenRTM-aist is not installed, or if the installation failed, a USB memory containing standalone executables will be distributed separately. In that case, use start_component_ev3_exe.bat.

The following two RTCs will start.

Operation Check

First, try controlling the EV3 using the joystick.

Connect EducatorVehicle, FloatSeqToVelocity, and TkJoyStick in RT System Editor as shown below.



After activating the RTCs, you will be able to control the EV3 using the joystick.



Controlling with Your Own RTC

First, disconnect the connector between FloatSeqToVelocity::out and EducatorVehicle::target_velocity_in.

Connect your own RTC between FloatSeqToVelocity and EducatorVehicle, and implement behavior that stops the robot and plays a sound when the touch sensor is activated.

Creating Template Code

Start RTC Builder.



After RTC Builder starts, create a new project.



Set the project name to TestEV3CPP (or TestEV3Py).

Configure the settings as shown below.

Create the component in either C++ or Python.

Basic
Module Name TestEV3CPP or TestEV3Py
Activity
Enabled Actions onInitialize, onExecute, onActivated, onDeactivated
Data Ports
InPort
Name Data Type Description
velocity_in RTC::TimedVelocity2D Input target velocity
touch RTC::TimedBooleanSeq Touch sensor ON/OFF state
OutPort
Name Data Type Description
velocity_out RTC::TimedVelocity2D Output target velocity
sound RTC::TimedString Audio output
Configuration
Name Type Description
sound_output string Audio played when the touch sensor is ON. The default value is beep.
Language / Environment
Language C++ or Python

Click the [Generate Code] button to generate the source code.



Generating the Project

After the code has been generated, use CMake to generate a Visual Studio project (or Code::Blocks project on Ubuntu) if you are using C++.

First, start CMake (cmake-gui).

  • Windows 7



  • Windows 8.1



After starting CMake, specify the source code directory and build directory as shown below.

The values in parentheses are examples assuming the Eclipse workspace directory is C:\workspace.

Where is the source code Folder containing the code generated by RTCBuilder (C:\workspace\TestEV3CPP)
Where to build the binaries build folder created under the folder containing the code generated by RTCBuilder (C:\workspace\TestEV3CPP\build)



Click [Configure] and then [Generate] to generate the Visual Studio project.

Editing the Source Code

Open TestEV3CPP.sln in the build directory.

Next, edit the source code.

For Python, first modify the variable initialization section.

  • TestEV3Py.py
 	def __init__(self, manager):
 		#self._d_velocity_in = RTC.TimedVelocity2D(*velocity_in_arg)
 		self._d_velocity_in = RTC.TimedVelocity2D(RTC.Time(0,0),RTC.Velocity2D(0,0,0))
 		#self._d_distance_sensor = RTC.TimedShortSeq(*distance_sensor_arg)
 		self._d_distance_sensor = RTC.TimedShortSeq(RTC.Time(0,0),[])
 		#self._d_velocity_out = RTC.TimedVelocity2D(*velocity_out_arg)
 		self._d_velocity_out = RTC.TimedVelocity2D(RTC.Time(0,0),RTC.Velocity2D(0,0,0))
 		#self._d_buzzer = RTC.TimedShort(*buzzer_arg)
 		self._d_buzzer = RTC.TimedShort(RTC.Time(0,0),0)

First, write code in onExecute that outputs the input velocity unchanged.


For C++, it is implemented as follows.


Use the isNew function to check whether new input data exists, and store it in the variable (m_velocity_in) using the read function.

Then store the output data in m_velocity_out and call the write function to transmit the data.

  • src/TestEV3CPP.cpp
 	if (m_velocity_inIn.isNew())
 	{
 		m_velocity_inIn.read();
 		// Output the input velocity unchanged
 		m_velocity_out.data.vx = m_velocity_in.data.vx;
 		m_velocity_out.data.vy = m_velocity_in.data.vy;
 		m_velocity_out.data.va = m_velocity_in.data.va;
 		setTimestamp(m_velocity_out);
 		m_velocity_outOut.write();
 	}

For Python, it is implemented as follows.

  • TestEV3Py.py
 		if self._velocity_inIn.isNew():
 			data = self._velocity_inIn.read()
 			# Output the input velocity unchanged
 			self._d_velocity_out.data.vx = data.data.vx
 			self._d_velocity_out.data.vy = data.data.vy
 			self._d_velocity_out.data.va = data.data.va
 			OpenRTM_aist.setTimestamp(self._d_velocity_out)
 			self._velocity_outOut.write()

Next, implement processing that stops the robot when the touch sensor is ON.


Since touch sensor data is not always received continuously, declare a variable to store the sensor state.


For C++, add the following to TestEV3CPP.h.

  • include/TestEV3CPP/TestEV3CPP.h
  private:
 	 bool m_last_sensor_data[2];


For Python, add the following to the constructor.

  • TestEV3Py.py
 	def __init__(self, manager):
 		OpenRTM_aist.DataFlowComponentBase.__init__(self, manager)

 		self._last_sensor_data = [False, False]

Next, add the stop-processing logic to onExecute.


For C++, the implementation is shown below.


First, check whether new data has arrived on the touch InPort using isNew. If new data exists, read it using read and store it in m_last_sensor_data.

Then, if vx of the data received from velocity_in is greater than or equal to 0, the robot is considered to be moving forward and may collide with an obstacle. If the touch sensor is ON, the robot stops and a buzzer sound is played.

  • src/TestEV3CPP.cpp
 RTC::ReturnCode_t TestEV3CPP::onExecute(RTC::UniqueId ec_id)
 {
 	// Store newly received sensor data in m_last_sensor_data
 	if (m_touchIn.isNew())
 	{
 		m_touchIn.read();
 		if (m_touch.data.length() == 2)
 		{
 			for (int i = 0; i < 2; i++)
 			{
 				// Play a sound when the touch sensor changes from OFF to ON
 				if (!m_last_sensor_data[i] && m_touch.data[i])
 				{
 					m_sound.data = m_sound_output.c_str();
 					setTimestamp(m_sound);
 					m_soundOut.write();

 				}
 				m_last_sensor_data[i] = m_touch.data[i];
 			}
 		}
 	}
 	if (m_velocity_inIn.isNew())
 	{
 		m_velocity_inIn.read();
 		// Determine whether to stop only when vx >= 0 (moving forward)
 		if (m_velocity_in.data.vx > 0)
 		{
 			for (int i = 0; i < 2; i++)
 			{
 				// Stop when the touch sensor is ON
 				if (m_last_sensor_data[i])
 				{
 					// Stop the robot
 					m_velocity_out.data.vx = 0;
 					m_velocity_out.data.vy = 0;
 					m_velocity_out.data.va = 0;
 					setTimestamp(m_velocity_out);
 					m_velocity_outOut.write();


 					return RTC::RTC_OK;
 				}
 			}
 		}
 		// Output the input velocity unchanged
 		m_velocity_out.data.vx = m_velocity_in.data.vx;
 		m_velocity_out.data.vy = m_velocity_in.data.vy;
 		m_velocity_out.data.va = m_velocity_in.data.va;
 		setTimestamp(m_velocity_out);
 		m_velocity_outOut.write();
   return RTC::RTC_OK;
 }

For Python, the implementation is as follows.

  • TestEV3Py.py
 	def onExecute(self, ec_id):
 		# Store newly received sensor data in m_last_sensor_data
 		if self._touchIn.isNew():
 			data = self._touchIn.read()
 			if len(data.data) == 2:
 				for i in range(2):
 					# Play a sound when the touch sensor changes from OFF to ON
 					if not self._last_sensor_data[i] and data.data[i]:
 						self._d_sound.data = self._sound_output[0]
 						OpenRTM_aist.setTimestamp(self._d_sound)
 						self._soundOut.write()
 				self._last_sensor_data = data.data[:]

 		if self._velocity_inIn.isNew():
 			data = self._velocity_inIn.read()
 			# Determine whether to stop only when vx >= 0 (moving forward)
 			if data.data.vx > 0:
 				for d in self._last_sensor_data:
 					# Stop when the touch sensor is ON
 					if d:
 						# Stop the robot
 						self._d_velocity_out.data.vx = 0
 						self._d_velocity_out.data.vy = 0
 						self._d_velocity_out.data.va = 0
 						OpenRTM_aist.setTimestamp(self._d_velocity_out)
 						self._velocity_outOut.write()

 						return RTC.RTC_OK

 			# Output the input velocity unchanged
 			self._d_velocity_out.data.vx = data.data.vx
 			self._d_velocity_out.data.vy = data.data.vy
 			self._d_velocity_out.data.va = data.data.va
 			OpenRTM_aist.setTimestamp(self._d_velocity_out)
 			self._velocity_outOut.write()
 		return RTC.RTC_OK

After editing the code, build the project if you are using C++.


If the build succeeds, TestEV3CPPComp.exe will be generated in:

build\src\Release

(or build\src\Debug).

Operation Check

Start TestEV3CPPComp.exe (or TestEV3CPPComp.py) by double-clicking it.


Connect TestEV3CPP (or TestEV3Py) as shown below.



Finally, activate the RTCs and verify that the system operates correctly.

Saving an RT System

To save the RT System, right-click on the System Diagram and select Save As…




Restoring an RT System

To restore a saved RT System, select Open and Restore and choose the file you saved earlier.



Exiting an RTC

To terminate an RTC, execute Exit on the RTC from RT System Editor.


Supplement

About the Script Files

By selecting File Browser from the EV3 button menu, you can operate files and directories under:

/home/robot


The following operations can be performed by executing shell scripts in the scripts folder.

Script File Name Description
run_rtcs.sh Start RTCs
stop_rtcs.sh Stop RTCs