You are on page 1of 16

Lego Mindstorms EV3 Essentials

Abid H. Mujtaba









Chapter No. 5
" Connecting with LeJOS"
In this package, you will find:
The authors biography
A preview chapter from the book, Chapter no.5 "Connecting with LeJ OS"
A synopsis of the books content
Information on where to buy this book









About the Author
Abid H. Mujtaba is an electrical engineer and a theoretical physicist by training,
and an Android developer by profession. He spends most of his working and free
time tinkering around with Linux, electronics, and various programming languages.
I would like to thank my wonderful wife for buying me EV3 as an awesome
birthday gift, and then encouraging and supporting me at every step of
writing this book. This would have been literally impossible without her.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Lego Mindstorms EV3 Essentials
EV3 is the latest generation of the Lego Mindstorms robotics series. This book will
introduce you to EV3 and teach you how to program it, empowering you to construct
complex and fantastic robots.
This book is primarily intended as a fast-paced primer on how to get started
with programming EV3, first on the brick itself and later using LeJ OS.
What This Book Covers
Chapter 1, Introducing EV3, introduces EV3 and gives you an overview of the brick,
including its specifications, external components, and a walkthrough of the menu.
Chapter 2, Sensors and Motors, discusses the sensors and motors that are shipped
with EV3.
Chapter 3, EV3 Brick Programming, provides instructions on how to use the on-brick
visual programming language to construct robots of significant complexity, including
an obstacle-avoiding robot.
Chapter 4, LeJOS Unleashing EV3, introduces the powerful and elegant LeJ OS
firmware and programming suite, which allows you to program EV3 using J ava.
It also covers the motivation for and the installation and testing of LeJ OS on EV3.
Chapter 5, Connecting with LeJOS, teaches you how to connect your computer
to EV3 (running LeJ OS) over SSH using a USB cable, Wi-Fi, and Bluetooth.
Access to EV3's internal terminal will give you complete control over it.
Chapter 6, Hello, World Writing Our First Program, helps you to configure
your computer so that you can program EV3 using LeJ OS.
Chapter 7, Sensors and Motors the LeJOS way, talks about controlling the
sensors and motors using LeJ OS.
Chapter 8, The Line-follower Robot, provides an extremely detailed tutorial on how to
construct and program a line-follower robot, which is a robot capable of autonomously
following a path consisting of multiple straight line segments placed end to end. This
chapter covers the robot's physical construction and the programming of the
differential drive.





For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Chapter 9, Sensing the Path, teaches you how to control the color sensor
and use it to interrupt the motion of the robot when it moves off the path.
Chapter 10, Tracking the Line, helps you to complete the implementation of the
line-follower robot, resulting in a fully functional, completely autonomous robot
capable of tracking a line.
Appendix A, The Make Utility, describes the basic usage of the Make utility
and provides a Makefile for LeJ OS projects.
Appendix B, LeJOS and IDEs, outlines the different IDEs that can be used
with LeJ OS.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Connecting with LeJOS
One of the main advantages of using LeJOS is the ability to write programs in Java
and compile them on your computer before running them on EV3. A necessary
precondition for this workow is the ability to copy/transfer the compiled program
from your computer to EV3.
The additional advantage of connecting your computer to EV3 is the ability to look
at the console output when your program is executing. This is an essential part of
debugging your code, and I promise that there will be a lot of debugging.
With the connection set up correctly, you can SSH into EV3, gaining root access
to the shell (terminal), which gives you complete control over the Linux OS that
EV3-LeJOS is running. In essence, at this point, you are communicating with a
remote machine that is capable of motion; that is, you are talking to a robot.
In this chapter, we will cover four means of connecting to an EV3 running LeJOS:
Copying les to the SD card
Mini USB cable
Bluetooth
Wi-Fi
Copying les to the SD card
Since our fundamental requirement is the ability to copy compiled code (executable
les) from a computer to EV3, the most obvious way is to simply remove the SD card
from EV3, plug it into your computer, and simply copy the les over.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Connecting with LeJOS
[ 78 ]
Insert the SD card into the computer's card reader. During installation, LeJOS shrinks
the FAT32 partition to 500 MB and formats the rest as an ext2 partition (a popular
lesystem for Linux). It is the latter partition that we are interested in. In a graphical
le manager, the 500 MB FAT32 partition can be identied by its size and by the
fact that it contains the JRE le we placed during installation and a LeJOSimage.
bz2 le. We ignore this partition. The ext2 partition contains the lesystem of the
Linux OS that LeJOS installed. It has the the same folder structure as any Linux OS:
bin, boot, dev, etc, home, and so on. The contents of this partition belong to the root
user; therefore, you will need superuser privileges to write to it. On Debian/Ubuntu
machines, this means prexing the cp command along with sudo when copying les
to the partition. Exercise caution when using the sudo command.
This is most easily done in a terminal (changing the permissions on this partition is
not advisable; this can interfere with its operation on EV3). To nd the mount point
of the LeJOS ext2 partition, rst run the following command (as root):
sudo fdisk -l
This will show you the two partitions on the SD card. We are interested in the
device path: /dev/<xyz> (on my computer, the ext2 partition on the SD card
shows up as /dev/sdc2). Now, run the following command:
mount
This prints a list of all the mounted devices on the system, relating the device path
to the mount point. Search for the device path of the ext2 partition on the SD card
and nd the corresponding mount point (on my computer, /dev/sdc2 was mounted
at /media/7efc-3842).
Use cd to change the directory to the mount point and run ls -l. You will see a
familiar list of Linux folders. We are interested in one particular subfolder: home/
lejos/programs. This is the location where you need to copy your compiled code
in order to execute it. The .jar les (the compiled code) placed in this location are
accessible from the LeJOS menu on EV3 and can be chosen and executed from there.
Don't forget to properly unmount the partitions before you remove the SD card.
You can use your graphical le manager to do so, or from the terminal, issue
umount <mount-point> for both partitions.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Chapter 5
[ 79 ]
Limitations
The limitations of this technique are obvious. Developing a program is far from
perfect and involves many iterations. When you run the code, it fails (obviously);
so, you debug it, edit it, compile it, and then run it again. This means shutting down
EV3 and transferring the SD card between it and the computer, copying the le,
transferring the SD card back to EV3, turning it on, and then executing the program.
Rinse and repeat. A slow and tiring process.
The art of programming, in part, consists of nding the best tools and procedures to
simplify the task of programming. In this case, the overhead of moving the SD card
around is too high. So, why mention it? Because it works and other than the time
involved, it is a ridiculously simple process. If all else fails, you have this to fall back
upon. The rest of the chapter is dedicated to ensuring that you don't have to.
Mini USB cable
EV3 is shipped with a mini USB cable, one end of which connects to a USB port on
your computer and the other smaller end connects to the mini USB port on the top
face of EV3 with the explanatory label PC.
LeJOS, running on EV3, implements a DHCP server that automatically assigns IP
addresses to the network devices connected to it. So, when a computer running
Linux is connected to an EV3 running LeJOS, a USB Ethernet network is established
using the USB cable. EV3 acts as the server with the IP address 10.0.1.1, and
the computer is assigned an IP address in the 10.0.1.x range. The IP address of
EV3 (10.0.1.1) is displayed proudly on the home screen, indicating that LeJOS is
operating as a DHCP server.
The connection takes a few seconds to be established. If you are running a desktop
environment (such as GNOME), a visual notication might appear, indicating that
the connection has been established. To conrm the connection, re up the terminal
and run ifconfig. You should see a network interface named usb0 with an IP
address (inet addr) in the 10.0.1.x range.
SSH access
Now that we have two Linux machines (EV3 and your computer) on the same
network, it is time for some SSH. We use the SSH utility to shell into EV3 and access
a terminal running within it. The username is root and the password is empty. Not
the safest choice, but simplicity counts for something, and you can, of course, beef up
security yourself later.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Connecting with LeJOS
[ 80 ]
So, to SSH into EV3, run ssh root@10.0.1.1, press Enter when it asks for a
password, and voil! You have root access to the LeJOS terminal. As any Linux
acionado knows, this means that you now have absolute control over the OS. Since
you SSH-ed in as the root, you start off in the /home/root folder, but you can cd to
any place that takes your fancy. To leave the LeJOS terminal, just run exit.
Setting up the SSH conguration
Laziness is the guiding force of programmers, and typing usernames, IP addresses,
and passwords (even empty ones) over and over again is hard work; so, we will set
up an SSH cong to do it for us.
This requires you to edit the ~/.ssh/config le on your computer (create it if it
doesn't exist). Add the following section at the end of the le:
Host ev3
User root
Hostname 10.0.1.1
Downloading the example code
You can download the example code les for all Packt books you have
purchased from your account at http://www.packtpub.com. If you
purchased this book elsewhere, you can visit http://www.packtpub.
com/support and register to have the les e-mailed directly to you.
Once you have saved the changes, you can SSH into the EV3 (running LeJOS) by
simply running ssh ev3 (much more concise).
It still asks for the password though. The next step is to use public-key cryptography
in order to get rid of this nuisance. I recommend that you perform the following
actions in the ~/.ssh folder since it is a good location for storing your public and
private cryptographic keys, especially the ones that you use for SSH access. Run
ssh-keygen and enter ev3 when it asks what to name the le. Press Enter when
you are asked for a password (twice) to leave the password blank. This will come in
handy when we automate SSH commands. This will create two les in the current
folder: ev3 and ev3.pub. These contain the private and public keys, respectively.
The next step is to place the public key in EV3 so that it knows that your private key
is allowed to access the system over SSH. Issue the following sequence of commands
on your computer; you will be asked for a password after each, and you just need to
press Enter every time:
ssh ev3 "mkdir ~/.ssh"
scp ev3.pub ev3:.ssh/
ssh ev3 "cat ~/.ssh/ev3.pub >> ~/.ssh/authorized_keys"



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Chapter 5
[ 81 ]
If a shell command is placed in quotes after an ssh command, it is executed on the
remote machine. The rst command creates the ~/.ssh folder on EV3. The second
uses scp (cp over the SSH tunnel) to copy the public key le to the .ssh folder on
EV3. Note how we use ev3 as the remote machine's hostname. The scp command
such as ssh reads congurations from ~/.ssh/config and can be instructed using
hostnames dened in this le. Without the ssh config entry, this command will
have to take the form scp ev3.pub root@10.0.1.1:.ssh/.
The third command simply concatenates the contents of the public key to the
authorized_keys le. Only SSH attempts using private keys whose corresponding
public keys are in authorized_keys are given access to the system. To test the setup,
run the following:
ssh -i ~/.ssh/ev3 ev3
The -i switch tells SSH to use the specied le as the private key for cryptographic
authentication. You should have gained access to a terminal running inside
EV3 without having to type in a password (since we created the key pair
with a blank password).
The nal step is to edit ~/.ssh/config and add the path of the private key to the
ev3 conguration block:
Host ev3
User root
Hostname 10.0.1.1
IdentityFile ~/.ssh/ev3
Running ssh ev3 now will log you in to EV3 using the private key, which doesn't
require a password. We now have a single command, ssh ev3, that can be used in
automated scripts.
Limitations
This method requires that the EV3 be connected to the computer using the mini USB
cable. This might become a hassle if the robot you are testing has to wander about. For
every code change, you will have to bring the robot back and connect it via the cable.
Additionally, for a moving a robot where the cable has to be disconnected when
it is running, it won't be possible to monitor the output log of the program as it is
being executed.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Connecting with LeJOS
[ 82 ]
Finally, in the case of some robots, the construction might render the mini USB port
(on the top face of EV3) inaccessible. These aren't major hindrances in your ability
to use the cable to connect to EV3, but the next two connection techniques will
remove these limitations.
Bluetooth
EV3 is equipped with Bluetooth. It has been designed to communicate with other
Bluetooth devices, especially smartphones, which can be used to control EV3 when
running the right software. LeJOS takes this concept to the next level.
An EV3 running LeJOS implements a Bluetooth Personal Area Network (PAN)
by acting as a Group Ad-hoc Network (GN) controller. This means that EV3 acts
as a server on a Bluetooth-based network, allowing other devices, for example,
a computer, to act as a PANU (PAN client) and connect to the network. Once
established, the PAN behaves like any other network, most importantly, allowing
transparent SSH access.
Conguring the computer
The rst step is to prepare your computer. The Linux machine must have either
Bluetooth built in or a Bluetooth USB dongle attached. Make sure that Bluetooth is
enabled and visible to other devices, using whichever graphical means are used to
control it. To conrm that Bluetooth is active and running, run hciconfig -a. Here
is some sample output obtained by running this command:
hci0: Type: BR/EDR Bus: USB
BD Address: 00:16:CF:FE:03:A0 ACL MTU: 1017:8 SCO MTU: 64:8
UP RUNNING PSCAN ISCAN
RX bytes:301012 acl:2298 sco:0 events:460 errors:0
TX bytes:94808 acl:966 sco:0 commands:67 errors:0
Features: 0xff 0xff 0x8d 0xfe 0x9b 0xfd 0x00 0x80
Packet type: DM1 DM3 DM5 DH1 DH3 DH5 HV1 HV2 HV3
Link policy: RSWITCH HOLD SNIFF PARK
Link mode: SLAVE ACCEPT
Name: 'laptop-0'
Class: 0x6e010c



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Chapter 5
[ 83 ]
Service Classes: Networking, Rendering, Capturing, Audio, Telephony
Device Class: Computer, Laptop
HCI Version: 2.0 (0x3) Revision: 0x20da
LMP Version: 2.0 (0x3) Subversion: 0x4182
Manufacturer: Broadcom Corporation (15)
The output should have Networking in the Service Classes section and Computer
in the Device Class section.
Conguring EV3
EV3 running LeJOS requires almost no conguration. Just make sure it is turned
on; navigate to the Bluetooth menu and ensure that it says Visibility on (and the
iPhone/iPad/iPod option is disabled). This indicates that EV3 is acting as a PAN
server and is ready to accept clients.
Connecting to EV3 using Bluetooth
EV3 is running as a visible Bluetooth server, and the computer has Bluetooth
activated. We make sure that EV3 is visible to the computer by running the
hcitool scan on the latter. The response should look as follows:
Scanning
00:16:53:40:E9:7D EV3
We are interested in the Bluetooth address of EV3 (the 12 hexadecimal numbers
interspersed with colons). To connect to EV3 as a PANU (Bluetooth client), we use
the pand utility (on Debian/Ubuntu, it is available in the bluez-compat package and
can be installed by running sudo apt-get install bluez-compat). To establish
the connection, run the following command (as root):
sudo pand -connect <BT ADDR> -n
Replace <BT ADDR> with the Bluetooth address of EV3. We are looking for the line
bnep0 connected in the output to conrm that the connection was successful.
The PAN connection has been established, but we need to run a network interface
over it, mainly Bluetooth Network Encapsulation Protocol (BNEP). Since EV3 has
an IP address of 10.0.1.1 on both the Ethernet and BNEP, we choose an IP address
of 10.0.1.2 for our computer and start the BNEP network interface by running the
following (as root):
ifconfig bnep0 10.0.1.2



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Connecting with LeJOS
[ 84 ]
To conrm that the interface is up, run ifconfig and look for an output similar to
the following:
bnep0 Link encap:Ethernet HWaddr 84:a6:c8:9b:ce:58
inet addr:10.0.1.2 Bcast:10.255.255.255 Mask:255.0.0.0
inet6 addr: fe80::86a6:c8ff:fe9b:ce58/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:670 errors:0 dropped:0 overruns:0 frame:0
TX packets:7 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:30820 (30.8 KB) TX bytes:428 (428.0 B)
To verify that the computer is now connected to EV3, run ping -c1 10.0.1.1 and
look for the following:
PING 10.0.1.1 (10.0.1.1) 56(84) bytes of data.
64 bytes from 10.0.1.1: icmp_req=1 ttl=64 time=46.3 ms
--- 10.0.1.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 46.340/46.340/46.340/0.000 ms
With the connection established and EV3 having the same IP address as on the usb0
interface discussed earlier, you can SSH into EV3 over Bluetooth by issuing ssh ev3
(or ssh root@10.0.1.1 if you haven't set up ssh config yet).
Finally, to disconnect the computer from EV3's PAN, run pand -K as the root.
Wi-Fi
The nal means of connecting a computer to EV3 is using a Wi-Fi network. This
connection mechanism is special because it requires a USB Wi-Fi dongle, which
is not supplied with EV3 and must be purchased separately.
This is further complicated by the fact that every Wi-Fi dongle is not supported. An
EV3 running LeJOS has driver modules for the Atheros ATH9K and Realtek 8192cu
chipsets (to nd out which chipset your Wi-Fi dongle is using, insert it in your
computer and run lsusb in a terminal). Wi-Fi dongles based on these will work out
of the box. A popular choice is EDIMAX EW-7811Un, a cheap and reliable device
with the huge bonus of having an extremely small form factor. Once inserted into
the USB port on EV3, only a small part juts out, which is approximately equal to a
standard Technic piece in width.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Chapter 5
[ 85 ]
Conguring EV3
We will set up EV3 (running LeJOS) to connect to your WPA-secured Wi-Fi network
(it is now widely accepted that WEP does not provide enough security to Wi-Fi
networks). The rst step is to insert the USB Wi-Fi dongle into EV3 and then turn
it on. Since we haven't specied which network to use nor provided EV3 with the
credentials needed to access it, EV3 will fail to connect to any network.
The lack of means to search for and connect to available wireless networks is a
shortcoming of this connection method. To an extent, it is understandable; it is not
easy to use just ve hardware keys to enter long wireless security passphrases.
Instead of the graphical approach, we have the nature of Linux on our side, where
every conguration is guaranteed to be just a text le, editable as such. So, we can
change the le directly on the SD card or SSH into EV3 (using the mini USB cable or
Bluetooth) and edit it via the shell (terminal). I will showcase the latter as an exercise
in how to use SSH to modify remote machines. If you want, you can perform the
same actions by plugging the SD card directly into your computer and editing the
relevant le there.
Wi-Fi conguration using SSH
Connect your EV3 to your computer using the mini USB cable or set up the Bluetooth
PAN network (both described earlier). Once the connection has been established,
SSH into EV3 by running ssh ev3 (or ssh root@10.0.1.1).
The rst thing we do is conrm that the USB Wi-Fi dongle has been recognized by
the EV3, by running ifconfig. The output should contain a block related to the
wlan0 interface. To allow the EV3 to connect to a WPA-secured Wi-Fi network, we
need to create and populate the /etc/wpa_supplicant.conf conguration le.
Linux comes with a utility that generates the conguration for you: wpa_passphrase.
To test it out, simply run wpa_passphrase <SSID>, where instead of <SSID>, you
need to type in the SSID (name) of your Wi-Fi network surrounded by quotes. For
instance, my Wi-Fi network at home is called Dumbledore, so this is what I type in
instead of <SSID>.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Connecting with LeJOS
[ 86 ]
When you press Enter, the utility will say # reading passphrase from stdin and it
will wait for you to type in the passphrase for the network. Type in the passphrase
and press Enter. After a few seconds, the utility will spit out the conguration text:
network={
ssid="Dumbledore"
#psk="01234567"
psk=82e6ade8f8319c3a737e89ee125a58178073d66613c9a3af8fb6e7f5e04e1aa7
}
We want this conguration text placed inside /etc/wpa_supplicant.conf. To that
end, we run the command again but we modify it slightly:
wpa_passphrase <SSID> > /etc/wpa_supplicant.conf
Remember to replace <SSID> with the name of your Wi-Fi network (surrounded by
quotes; for example, at home I use wpa_passphrase "Dumbledore" > /etc/wpa_
supplicant.conf). We have used the > redirection operator, an extremely powerful
feature of the Linux shell. Basically, what > says is to take the output of the preceding
command and place it in the le specied after it (overwriting it in the process). The
text # reading passphrase from stdin is also placed in the le; so, when you
run the command, you will see nothing, but the lack of the prompt (root@EV3:~#)
will indicate that the utility is running, and is in fact waiting for you to enter the
passphrase. Type in the passphrase and press Enter. After a few seconds, the prompt
will reappear.
To conrm that it worked, run cat /etc/wpa_supplicant.conf. This will print the
contents of the le:
# reading passphrase from sdtin
network={
ssid="Dumbledore"
#psk="01234567"
psk=82e6ade8f8319c3a737e89ee125a58178073d66613c9a3af8fb6e7f5e04e1aa7
}
The lines preceded by a # are comments and are ignored by EV3 when setting up the
Wi-Fi network. This simple conguration tells EV3 which network to connect to and
what security key to use to connect to it.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Chapter 5
[ 87 ]
Simply disconnect EV3 from your computer and restart it. It will automatically
connect to the specied Wi-Fi network. The one I have at home hands out IP
addresses in the 192.168.1.x range, and my EV3 was given an IP address of
192.168.1.14, which it proudly displays on the home screen (under the
10.0.1.1 address it uses for USB and Bluetooth networks).
To SSH into EV3 over the Wi-Fi network, run ssh root@<wifi ip address>
(in my case, I ran ssh root@192.168.1.14). You can construct a new block
in the ssh config le to connect using the IP address over Wi-Fi.
It is clear that the technique for setting up Wi-Fi connectivity on EV3 is rather
painless. For those of you who would rather modify the SD card directly on your
computer, plug in your SD card and create the /etc/wpa_supplicant.conf le. You
can run the wpa_passphrase command on your Linux computer and place its output
in the le. Now restart EV3 and it will work just as well.
Limitations
Wi-Fi is a powerful means to connect devices, but EV3 doesn't support all USB Wi-Fi
dongles out of the box. The only other shortcoming of using it with EV3 is that the
USB Wi-Fi dongle protrudes out of the brick. This is mitigated by using a smaller
dongle (such as the Edimax), but it can still interfere with certain robot designs.
Summary
In this chapter, we learned how to copy les directly to the SD card and then
augmented this knowledge with three techniques for connecting directly to EV3.
These network connections allow you to SSH into EV3, giving access to its root shell,
which makes you omnipotent on Linux machines.
We learned how to set up each kind of connection mini USB cable, Bluetooth, and
Wi-Fi, as well as their limitations so that we can make an informed decision about
the type of connection we prefer.
We will use this understanding to write, transfer, and execute Java programs on EV3,
which is covered in the next chapter.



For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials
Where to buy this book
You can buy Lego Mindstorms EV3 Essentials from the Packt Publishing website:
ht t ps: / / www. packt pub. com/ har dwar e- and- cr eat i ve/ l ego- mi ndst or ms-
ev3- essent i al s
Free shipping to the US, UK, Europe and selected Asian countries. For more information, please
read our shipping policy.
Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and
most internet book retailers.



















www.PacktPub.com




For More Information:
www.packtpub.com/hardware-and-creative/lego-mindstorms-ev3-essentials

You might also like