Sunday, February 17, 2019

Python and the EV3: Part 4 Writing a Program

This is part of a series, if you haven't already, go read the previous installments:
Part 1: Installing EV3Dev

Just let me write some python already!

In VS Code (or your development environment, if it is different) create a new file.  Name it test.py and save it to the same folder you created when setting up deployment in the last session.  Note that if your EV3 is on when you save it, then it should automatically deploy over to the EV3.  For now, copy the following lines into the file:


#!/usr/bin/env python3
# This tells the OS to use python3 when executing this file

from ev3dev2 import motor, sound
# This means that you are grabbing the motor and sound pieces from the ev3-dev libraries.

car = motor.MoveTank("outB", "outC")
# replace B and C with the left and right ports for your motors.  Case matters!
# Also, you only need to do this once in the file

car.on_for_seconds(left_speed = 50, right_speed = 50, seconds = 5)
# speed is in percents for this example

There!  You have your very first python file.  This time, when you save the file, make sure your EV3 is setup, because we're going to want it deployed in order to run it.

Wait! How do I run it?


Use the built in terminal at the bottom of the screen in VS Code to SSH into your robot.  If you need a reminder, just type in:
ssh robot@ev3dev.local
and the default password is "maker"

Now you are going to want to switch to the directory that your file is in.  You do this by typing:
cd <directoryname>
You can use the tab key to autocomplete the name once you've gotten it typed out a bit.

The first thing you need to do for any new file is make it executable so that the operating system knows you can run it. To do this you will type:
chmod a+x test.py
You only need to do this once after creating the file.

 Finally, to actually run the file, you just need to type:
./test.py
There you go! You've written and run your very first python program for the EV3. Go back to part two, and try out some of the suggestions there and string together a few commands in a row.

Hey!  I told the motor to do a bunch of things, but it only did the last one.


One more weird detail about python and the EV3.  One command will not wait for the previous one to finish running before it starts, so if you pile up a bunch of move commands, it will really only complete the last one.  You can solve this buy placing this line between each of the commands:

No comments:

Post a Comment

Python and the EV3: Part 4 Writing a Program

This is part of a series, if you haven't already, go read the previous installments: Part 1: Installing EV3Dev Part 2: SSH and Python...