The VS Code workflow


You may prefer to watch the video on YouTube.

This is the script of the above 17 minute video:

This video shows you how amazingly quick and easy it is to use the Python programming language to write programs for the Lego EV3 robot once everything is set up. Setting up your EV3 and your computer is the subject of a separate video but you should watch this video first. The Lego EV3 is the world's most popular pedagogical robot because it combines high quality, modularity, reliability and above all the capability of being programmed in many different languages. Python is the world's most-taught textual programming language because it's modern, powerful, concise and relatively easy to learn. Python is popular with professional coders and it's the main language behind YouTube, Instagram and many other well-known sites. Python programmers are among the best-paid coders on the planet, earning average salaries well over $100 000 per year in the US.

Wouldn't it be great then if you could program the EV3 with Python? By doing so, you would be learning about robots and at the same time deepening your knowledge of Python. Of course, if you could do all this for no cost that would be even better, right? Well, it's actually been possible to do that for a number of years using an operating system called ev3dev but only recently has the process become very easy. I'm so enthusiastic about programming the EV3 with Python that I made a website, ev3python.com to help people like you get started. Note that it wouldn't make sense to try to use Python to program robots until you have first learnt the basics of the language. My website won't help you learn the basics but there are hundreds of websites that can do that, such as Codecademy.com, for example.

Programming robots is quite different to writing normal programs because normal programs behave very predictably whereas the behaviour of robots is somewhat unpredictable. If you don't believe me then take a look at these very expensive robots trying to carry out simple tasks in a recent competition organised by DARPA, the research arm of the US military. Robotics is where the predictability of computers clashes with the messiness of the real world.



I've published a number of videos about EV3 Python programming and the last one was about different workflows that can be used – I made that video because at that time there was no one workflow that stood out as being much easier than any other. Now, in May 2018, I'm happy to announce that there IS a workflow that is far simpler than any that came before it. The new workflow is based on Microsoft Visual Studio Code, a free, open source multi-platform code editor that runs on Windows, Mac OS and Linux. Visual Studio Code (or simply VS Code) should not be confused with Microsoft Visual Studio, an expensive code editor that only runs on Windows. An extension for VS Code allows programs written in VS Code to be downloaded to the EV3 and run there, all with the touch of a single key. It really couldn't be easier, as I'll show you in this video. The process is so simple it could very easily be used in a classroom context – in my opinion every Python programming course should end with some EV3 Python programming. 

This video demonstrates how easy it is to make and run a Python script using VS Code with the EV3 extension. The process of actually setting up the EV3 and VS Code is explained in a separate video

The VS Code interface

I've started VS Code on my Windows PC and as you can see the interface is remarkably simple. On the left is an 'activities bar' where we can choose between 5 activities:

  • Explorer is the most used view, in which we see a list of open editors, the contents of the open project folder and, since the EV3 extension is installed, we also see the EV3 device browser which lets us see the files on the EV3, run a chosen file, take a screenshot or open a Secure SHell (SSH) session. Note that the VS Code workflow works so well that you may never need to use SSH, which is a major advantage over other workflows.
  • Search allows us to perform the usual find and replace operations, even across multiple files simultaneously.
  • Source Control allows for people to collaborate on the same coding project, in particular using the online system known as Git.
  • Debug helps us find errors in our scripts, for example by tracking the value of variables.
  • Extensions. Note that the Microsoft Python extension and the EV3 extension are already installed. I'll show you how to do that in a separate video.
The code editor is where we write our code.

At the bottom of the window is a panel that may be used as an output panel or may be used for a Secure SHell or SSH session, though the VS Code workflow is so simple you may never need to use SSH.

In the top right corner is a minimap that allows you to move around in long scripts more easily.

Let's quickly scan through the menus so you can see how simple VS Code is compared to some editors.



Writing and running non-EV3 scripts

Before I show you how to write, download and run scripts for the EV3, let me show you how to write and run a Python script that is to run locally and not on the EV3. I'm just going to make a new file, write a script and save it with the .py extension.

I'm opening a folder called 'Demo-scripts_non_EV3'. For non-EV3 scripts it is not obligatory to open a folder containing your scripts – you can also open loose scripts without opening a folder. But since it IS obligatory to open a folder when you want to work with EV3 scripts it's a good idea to get into the habit of opening a folder even when you are working with non-EV3 scripts. The folder containing your scripts is called the 'project folder' and we can also refer to it as the 'workspace'.

As you can see, the folder already contains a few Python scripts. But since this folder contains non-EV3 Python scripts there is no need for the folder to include special helper files in a subfolder called .vscode as is the case with EV3 Python scripts, as we will see later on. I want to make a new script, so I'm going to choose File>New File. You can see the code editor is waiting for me to type my code. To save time, I'm going to paste in some code that I copied earlier.

from time import sleep
import turtle
t = turtle.Pen()
for n in range(4):
    t.forward(100)
    t.left(90)
sleep(4)

I'm saving this file with the name 'turtlesquare.py' and because the VS Code editor recognises .py as the extension for a Python script it's now able to use color coding for the script which helps to make the script more legible. You can see this script is a classic script to make a turtle draw a square.

The best way to run a non-EV3 script is to right-click the code editor and choose 'Run Python File in Terminal'. [The result is:]
It's also possible to run a script by choosing Debug>Start Debugging but that's slightly less convenient because we have to choose 'Python' and because it switches us to the Debug view. Of course, the reason to choose 'Start Debugging' is to start debugging and a way to make that happen is to put a breakpoint on one of the lines by clicking to the left of the line number such that a red dot appears, as I'm doing now. Now when I choose Debug>Start Debugging (or press F5) script execution will pause at the breakpoint, giving me the option of moving through the script line by line by clicking the 'Step over' icon in the control bar. Notice when I do this that you can see the value of n changing each time script execution moves through the loop. This method of debugging is useful for non-EV3 scripts but unfortunately it will not work for EV3 scripts.

Let's try a couple of other non-EV3 scripts.

The 'polygon' script is this one 

from time import sleep
import turtle
t = turtle.Pen()
sides=int(input('How many sides?'))
for n in range(sides):
    t.forward(100)
    t.left(360/sides)
sleep(7)

and it's similar to the script we just saw that drew a square except that in this script we will ask the user to input a number, an integer, which will be the number of sides for a polygon that this script will draw. I'm going to move this graphics window so you can see the terminal panel underneath. In the terminal panel you can see we have the possibility of typing a number and pressing Enter. [I run the script and enter the number 7.]Perhaps you saw the polygon, a seven-sided polygon, being created on the left.
Now we can try this script

for n in range(10):
    print(n, n**2)

which is simply going to print some squares for us in the range 0 to 9 when I run it in the terminal. You can see the result right here.

   

Lastly, let's take a look at the 'bounce' script, which is relatively long. I won't go through that line by line but we can see it uses the 'tkinter' module and this script will demonstrate a little animation when I run it in the terminal.
[The bounce script is demonstrated in the above video]

Writing and running EV3 Python scripts

Having seen how to run some non-EV3 Python scripts let's now see how to run an EV3 Python script, which involves first downloading it to the EV3, of course.

If you want to write and run Python scripts for the EV3 then you MUST open a folder containing your script or scripts as opposed to opening a loose script. I'm opening a project folder called 'demo scripts' which, as you can see, already contains a couple of scripts. For beginners, it's a good idea to have multiple scripts in the same folder since it makes it easy to copy and paste code between scripts. However, it would probably be a bad idea to have more than a couple of dozen scripts in one folder since when you send a script from VS Code to the EV3 all the other scripts in the folder are downloaded as well and this can take several seconds.

I'm going to make a new script and to save time I'm going to paste it rather than type it. I'm going to save the script with the name demo.py

#!/usr/bin/env python3
from ev3dev.ev3 import *
import os
os.system('setfont Lat15-TerminusBold14')
mL = LargeMotor('outB'); mL.stop_action = 'hold'
mR = LargeMotor('outC'); mR.stop_action = 'hold'
print('Hello, my name is EV3!')
Sound.speak('Hello, my name is EV3!').wait()
mL.run_to_rel_pos(position_sp= 840, speed_sp = 250)
mR.run_to_rel_pos(position_sp=-840, speed_sp = 250)
mL.wait_while('running')
mR.wait_while('running')

Let's have a look at this script line by line.
  • The first line is a 'shebang', a special line that tells the computer what interpreter to use to run the script and where to find it on the EV3.
  • The next line imports everything from the ev3dev.ev3 module. That module contains all the functions that are specific to the EV3.
  • I'm also importing the os module so that I can print to the EV3's LCD screen with a larger font than the default font which is tiny.
  • I next specify the large font I wish to use.
  • Then I create a 'largemotor' object called 'mL' for 'motor left' as an instance of the largemotor class. I also specify that when the motor movement completes the motor should actively hold its position.
  • I'm also creating an object called 'mR' for the right motor which is attached to motor port D on my EV3.
  • Printing to the EV3's LCD is as simple as using the print() function.
  • I can easily also make the EV3 speak with the Sound.speak() function. This is one of many features of EV3 Python that cannot be performed in the standard Lego software. The wait() at the end of this line causes script execution to pause until the speech has completed before continuing.
  • Next I instruct both motors to rotate 840° degrees, (run to relative position 840°) but in opposite directions. I specify the target speed or 'speed setpoint' of each motor as 250 degrees per second. In EV3 Python speeds of 0 to 1000 correspond to power values of 0 to 100 in the standard Lego icon-based programming system. This will have the effect of making the EV3 rotate on the spot through one rotation. Script execution will not wait for the left motor to finish before starting the right motor, so the two motors can be assumed to start moving at the same time.
  • The final two lines make script execution pause until both motors have completed their motions before script execution ends.
My EV3 is already turned on and connected to my WiFi network, but I haven't yet connected VS Code to the EV3. That's as easy as clicking 'Click here to connect to a device' in the EV3 device browser and then clicking the correct connection at the top of the window. Once the connection is established the red indicator turns green.

With VS Code set up the way it is here, which is explained in a separate video, all I usually need to do is press F5 and the active script will be downloaded to the EV3 and run. As you can see in the status bar, ALL the scripts in the project folder are downloaded to the EV3. Since you won't be able to see the EV3's LCD screen, I will do a screen capture while the script is running. To do a screen capture, all I need to do is right-click the green indicator and choose 'Take Screenshot'.

[The rotation of the robot is shown in the video at the top of this page. Here is the screen capture:]


I hope you are impressed by how simple it is to write and run an EV3 Python program once everything is set up. Write, save and press F5 – what could be simpler than that? If you have used other workflows to program the EV3 with EV3dev Python you will have often needed to use a Secure Shell (SSH) connection to the EV3 to mark scripts as executable and give scripts control over the LCD. All of that is automatic when using the EV3 extension for VS Code so you may never need to use SSH ever again, though it's easily available if you need it – just right-click the green indicator.

I've shown you how to run your EV3 Python script from with VS Code but of course you can also run the script directly on the EV3. In that case you will want to download the scripts to the EV3 without running the active script and you can do that here in the EV3 Device Browser header.

Now that you've seen how amazingly simple it is to write, download and run EV3 Python programs using the EV3 extension for VS Code, you will want to watch the accompanying video which shows you how to set everything up. So, see you there!
Comments