Introduction To The PC - McGill Undergraduate … To The PC Mark Orchard-Webb...

16
Introduction To The PC Mark Orchard-Webb [email protected] January 5, 2017 1 Introduction Welcome to the 2017 version of this “tutorial!” This is the second year in which we are promoting Python as the environment, in the past we have used MATLAB TM , the lan- guage C, and before that QuickBASIC TM . This is the third year where we will exclusively be using the Arduino UNO TM microcontroller to perform data acquisition. Previously, we had used Labmaster TM data acquisition boards, which were phased out due to their reliance upon the very archaic ISA bus. This is an entirely new tutorial, based upon a new set of user interfaces which should carry through later lab courses. This operation is code named BlameItOnJack. Each workstation is equipped with a workstation, it is a relatively comfortable Pen- tium IV with a six gigabytes of memory. Please do not reboot the computer, if there is a problem, please bring it to the attention of the technician. The workstation is named ws339-nn.ugrad.physics.mcgill.ca, where nn is the bench number. You can re- motely login to your workstation via secure-shell (SSH). 1 To transfer files to and from your workstation, you can use secure-copy (SCP). 2 It may be the case that some of you have experience with Python, but this tutorial will assume none. For those who do have experience, don’t assume this will give you a free ride; there have been numerous instances in this course where students with less experience out performed their more experienced peers — success is more about understanding the problem than being able to write syntatically correct code. 1 ssh ws339-nn.ugrad.physics.mcgill.ca in a terminal on a Linux or MacOS machine, or using PuTTY on a windows machine. 2 scp command on Linux or MacOS, WinSCP is a good, free tool for Windows. 1

Transcript of Introduction To The PC - McGill Undergraduate … To The PC Mark Orchard-Webb...

Introduction To The PC

Mark [email protected]

January 5, 2017

1 Introduction

Welcome to the 2017 version of this “tutorial!” This is the second year in which we arepromoting Python as the environment, in the past we have used MATLABTM, the lan-guage C, and before that QuickBASICTM. This is the third year where we will exclusivelybe using the Arduino UNOTMmicrocontroller to perform data acquisition. Previously,we had used LabmasterTMdata acquisition boards, which were phased out due to theirreliance upon the very archaic ISA bus. This is an entirely new tutorial, based upon anew set of user interfaces which should carry through later lab courses. This operationis code named BlameItOnJack.

Each workstation is equipped with a workstation, it is a relatively comfortable Pen-tium IV with a six gigabytes of memory. Please do not reboot the computer, if there isa problem, please bring it to the attention of the technician. The workstation is namedws339-nn.ugrad.physics.mcgill.ca, where nn is the bench number. You can re-motely login to your workstation via secure-shell (SSH).1 To transfer files to and fromyour workstation, you can use secure-copy (SCP).2

It may be the case that some of you have experience with Python, but this tutorialwill assume none. For those who do have experience, don’t assume this will give youa free ride; there have been numerous instances in this course where students withless experience out performed their more experienced peers — success is more aboutunderstanding the problem than being able to write syntatically correct code.

1ssh ws339-nn.ugrad.physics.mcgill.ca in a terminal on a Linux or MacOS machine, or usingPuTTY on a windows machine.

2scp command on Linux or MacOS, WinSCP is a good, free tool for Windows.

1

2 Login

The login screen for the computer is shown in figure 1. Before logging into the machine,I bring your attention to the name in the upper left corner of the screen. This is thename of your computer. It is of the form ws339-nn, where, nn is your workstationnumber (with a leading zero, if required to pad out two digits.)

Figure 1: The login screen.

To authenticate to the system enter your username into the upper box, your McGillpassword in the lower box. There are three different variations of your McGill identitywhich will work and I have tweaked the graphical login program to convert them allto the best variant. You are no doubt familiar with using what is in my opinion theworst variant, your McGill email address, [email protected] to log intoWindows machines around campus. One can only imagine the wasted man-hours ofthousands of people typing in the highly redundant @mail.mcgill.ca thousands of timesa year each. It also causes problems for people how have the @ symbol in their first orlast name and is not at all helpful when using SSH or SCP to log in remotely, or copyfiles between machines.

2

The best variant would be firstname.lastname, you will notice that if you insist upontyping your whole email address, the @mail.mcgill.ca protion will be excised and a flagplaced in your permanant record identifying you as a hooligan.3

An excellent alternative is to use your “short name.” If you have no idea what thismeans, don’t worry we will look at this later. There are some issues you need to beaware of when using your short name with SSH/SCP which I will address later.

So pick a name and log in.

Figure 2: First time login screen — click “Use default config”.

So, assuming you chose the path of righteousness, you should see a screen asshown in figure 3. You should see your name up in the upper right corner. To the leftof the clock is a virtual desktop. This allows you to switch between multiple desktops,rather than juggling all your applications on a single desktop. Personally I use thisto great excess, others care less for this feature. You can move between desktops byclicking on the corresponding panel, or as intended — by pressing and holding downthe Ctrl and Alt keys and moving left or right using the arrow keys.

3Not yet implimented.

3

Figure 3: Default desktop configuration.

At the bottom of the screen is a bar of applications, which the desktop managerthinks you will use frequently, along with a couple of my additions, which you reallyare going to use a lot!

The left most icon, which looks like a trapezoid with padding on the corners, issomething supplied by the desktop manger. It minimizes all open windows and showsthe desktop. I guess this might be useful if you create a lot of icons on your desktop,but I would just switch to an empty desktop. I guess it is also good to minimize windowswhich contain mischief you don’t want the approaching person of authority to see —think one move ahead, nothing is more suspicious than an empty desktop. You couldsubsitute a desktop image with a open windows full of good works. Also fun to suggestthe machine has crashed and chuckle as the person of authority types frantically intoan image of a terminal. But I digress.

4

3 Command Prompt

The second icon, looking like a computer screen with a prompt, starts a terminal em-ulator, this allows access to the command prompt, or shell. This is a very powerfulinterface and generally my solution to most problems when graphical applications areplaying the fool, is just to open up a terminal and find out what is really going on. Thisis also the interface provided when you use SSH to login remotely.

Click once on the terminal icon. This should open a terminal as shown in figure 4.

Figure 4: The command prompt.

The white text on the black background is the command prompt. It just sits thereand waits for you to type witty things, which it will ridicule heartlessly. The prompt isof the form, usename@machinename:directory$. This is handy because when you aretyping out potentially catastrophic instructions it is good to know both who and whereyou are. But you complain, “you said the part after the colon is the directory, there isjust a stupid tilde!” Indeed, the tilde (∼) is a special shorthand for your home-directory.Work through the example shown in figure 5. To explain these examples, these aretranscripts of everything, the prompt, what I type and what the shell replies. To clarify,the entirety of what I type is, “pwd” followed by the enter/return key. I type it at theprompt. The shell replies, “/home/mwallah”, then displays another prompt.

I go into such detail, because historically there have always been a few students who

5

just type EVERYTHING in the box at the prompt and then complain it doesn’t work forthem.

mcgill.wallah@ws339-21:˜$ pwd/home/mwallahmcgill.wallah@ws339-21:˜$

Figure 5: The print working directory command.

So, having executed the print working directory command, what does it mean? Thecommand prints the actual directory you are in, using no shorthands or other diver-sions. “/home” is actually a resource shared by all machines. The part after “/home/”is your share of that shared resource — it is also your short name. Remember it, orwrite it in your logbook — you can use this name to log in.

3.1 Joining your group

There important administrative task which must be performed by each member ofthe group as soon as possible. In order to share files among group members, I need tohave a record mapping student to group. This is achieved by each member of the grouprunning a simple script on the workstation they will be working on for the remainderof the semester. Happily it is a simple script for me to write, but a long convolutedpath for you to type. This will entice you to learn tab-completion. Tab-completion is amagnificent feature of the shell, rather than typing everything, you just type enough touniquely describe what you want and press the Tab key.

mcgill.wallah@ws339-21:˜$ /mnt/resources/339/intro/remember-me.sh MacYou will be a member of the group phys339-21.You will be known as Mac.mcgill.wallah@ws339-21:˜$

Figure 6: Registering for a group and my preferred name.

As can be seen, that is a lot of typing. However, try the following:

• type “/mn”, then hit the Tab key; the shell adds “t/”

• type “r”, then hit Tab; shell completes, “esources/”

• type “3”, then Tab; shell completes, “39/”

6

• type “i”, Tab; shell completes, “ntro/”

• type “r”, Tab; shell completes, “remember-me.sh”

Are you getting tired of winning yet? Before hitting enter, there is an optional pa-rameter which you may want to add. Often students do not commonly use the namewhich McGill University uses to describe them. This optional parameter lets you spec-ify the first name which you prefer to use. In the example, McGill Wallah, would preferto be known as Mac Wallah. I now regret not using Seymour for the example account,but I digress. If you are happy with your McGill given name, just hit enter. If you wishyou register a different first name, type a space followed by the name you prefer.

At this point, it would be a good idea to log out and allow the other members in thegroup to work though the login and registration process. As shown in figure 7., if youclick on your name in the upper right corner a drop down menu will appear. Please useonly the “Logout” menu item. The network expects you machine to be running all thetime, if you take it off line you will not be able to access it remotely and you will missany automatic reconfigurations which may be necessary and we will all waste valuabletime as a result.

Figure 7: Default window configuration.

7

4 Talking to a microcontroller

Continuing through the icons on the bar at the bottom of the screen, the third iconis a spider-web with a snake superimposed. This is one of the icons which I addedto the desktop, don’t click it just yet, we will come back to this later. The snake is ofcourse a python, because this is a Python integrated environment. The spider-web isbecause they scratched their heads trying to come up with something cold, reptilianand generally unsettling to most people. One might imagine the celebration whensomeone came up with Scientific PYthon Development EnviRonment or Spyder.

Next, the blue circle with an infinity is the icon for the Arduino Development Envi-ronment. The Arduino is a microcontroller. From the icon we can infer that you will besinging the blues about the infinite frustration, because each positive step is perfectlybalanced by a negative.

Figure 8: Arduino Development Environment.

Click on the Arduino icon. But, be careful, the Arduino is already programmed andwe do not yet want to upload any new code to it. Avoid clicking the circle with anarrow to the right. Avoid the Sketch menu. Avoid pressing Ctrl-U. Proceed to the Tools

8

menu. If the Board entry does not read Board: “Arduino/Genuino Uno”, make it so.Then select the Port entry, this should show up something similar to that shown infigure 9, the actual number doesn’t matter, it changes. Just make sure the port is setto something beginning with /dev/ttyACM.

Figure 9: Arduino Port Selection

The software is now configured to communicate with the Arduino. Observe in theupper right corner of the window there is a square containing what might be imaginedto be a magnifying glass. If you hover the mouse over it, it should display the text“Serial Monitor.” Click the button, or if you prefer, press Ctrl-Shift-M. This should openup a new window similar to that shown in figure 10. It is likely that the two boxes atthe bottom right of the window are not the same as shown. Make sure they are set toNewline and 115200 baud.

9

Figure 10: Arduino Serial Monitor ready for action.

Once this is done, you should see some activity. If you do not, alert a person ofauthority.

There are two boxes, the small upper box is for you to type commands. The lowerbox displays the Arduino’s response. Click in the upper box and type “status” then theenter key. Try the command “help” in the same manner.

What is happening here is that a program is running on the Arduino which pro-cesses the text you send to it and sends back responses. For the moment we will notworry about how to write the program on the Arduino.

For your entertainment and devious pedagogy, the program on the Arduino imple-ments a few very simple games. The simplest is higher-lower. The Arduino will pick anumber in the range 0 through 4095 (a 12-bit number) and the player tries to guess thenumber. For each guess the Arduino will provide feedback about whether the numberis higher or lower. Give this a try. Is there an optimal strategy to playing this game?What is the maximum number of guesses that should be required?

10

5 Automation with Python

It should not take too long before you become very frustrated at all the redundanttyping of “GUESS.” Let’s try automating this process. Close all the Arduino windowsand start Spyder. Be patient, it takes a non negligible time to start. You should seesomething like what is shown in figure 11.

Figure 11: Scientific PYthon Development EnviRonment at the ready.

Click on the icon to the right of the Arduino icon, which looks like a filing cabinet,to open the File Manager and navigate your way down to “/mnt/resources/339/intro”.The fastest way to do this is to click in the address bar, type Ctrl-A to select all text andthen use the same tab-completion as we used in the terminal earlier. Click on, thenclick and drag the file autoplay.py and release it over the temp.py tab in the left handpane of Spyder as shown in figure 12.

11

Figure 12: Drag and drop autoplay.py into Spyder.

This should open the file in Spyder. However, it is in a location which you haveonly read permission, so go ahead and save it somewhere in you home directory, asshown in figure 13. I strongly recommend creating a 339 folder in your home folderand placing it there.

12

Figure 13: Save new file in you own space.

If you now click on the green triangle, or press F5, the dialog shown in figure 14should pop up. I recommend setting the various buttons to match what I have set.Then click Run. Now cast your attention to the lower right corner of the Spyder window.

13

Figure 14: Set run time options.

Take a look at the code and see try to figure out how it works. The first block ofcode is well beyond what you are expected to understand, just treat it as a black box.In figure 15 is the entry point of the code. Everything above defines functions whichcan be called.

arduino = introArduino()result = play_hilo(arduino)print "result: %s" % (result)

Figure 15: Simplest overview of autoplay.py.

The first line in the figure creates and object called arduino. All you need knowabout this object is that it has two methods:

• arduino.send(message) - this method will send message to the Arduino micro-controller as if message had been typed in text entry box of the Arduino SerialMonitor.

14

• arduino.getResp() - this method returns the reponse sent from the Arduino.

There is a debug / verbose option when creating the arduino object. If you modifycreation line as shown in figure 16, then re-run the code you might get some insightinto what going on behind the scenes.

arduino = introArduino(1)

Figure 16: Simplest overview of autoplay.py.

The second line shown in figure 15 calls the function play hilo with the newly cre-ated object. Your goal for today will be to create a new function which will play theWARMER COLDER game. (!!!)

To that end, let’s take a quick look at the function, which is shown in figure 17.

def play_hilo(connection):connection.send("PLAY HIGHER_LOWER")resp = connection.getResp()if not "OK_PLAY" == resp[0:7]:

print "Something is wrong, Arduino replied ’%s’" % (resp)return False

bit = 2048acc = 0while bit > 0:

guess = acc + bitprint "Guessing %d" % (guess)connection.send("GUESS %d" % (guess))resp = connection.getResp()if not "OK_GUESS" == resp[0:8]:

print "Something is wrong, Arduino replied ’%s’" % (resp)return False

if "CONGRATULATIONS" == resp[10:10+15]: return respif "HIGHER" == resp[10:10+6]:

acc = guessbit = bit >> 1

Figure 17: The play hilo function.

The first line binds the name connection to what ever we called the function with asan argument. In our case it was the arduino object, but it will be accessed using thisnew name. The keyword def indicates we are defining a function, the definition followsthe colon. Python is indention sensitive. So everything which is indented after a colonis treated as a block of code related to the statement preceding the colon.

15

The second line should be pretty self evident.

The third line gets the response from the Arduino. If the PLAY command worked,we know the first 7 characters of the reply should be “OK PLAY ”.

We test this in the fourth line. Observe another colon, followed by a block. Basicallyif there was an error we bail.

The algorithm begins at line seven. Recall, we are guessing a 12-bit number. Ef-fectively the algorithm determines each bit of the number, starting with the most sig-nificant, which will have the value 211 = 2048. If the most significant bit is set in themystery number it will be great that, or equal to 2048. If it is equal we have already wonthe game. If it is greater, the Arduino will reply with “OK GUESS: HIGHER than 2048”.Once I know the most-significant bit, I repeat the logic for the next-most-significantbit.

The last line might be a little opaque to anyone who has not programmed much withintegers. The effect is to divide bit by 2. You might ask, why not just divide the numberby 2? If you want, go ahead and make that substitution.

6 Good Luck

By brute force, you should be able to solve the WARMER COLDER game in 24 or fewerguesses. I suspect there is an algorithm with a better worst case, or at least averageperformance. The format of the CONGRATULATIONS line is designed so we can collectstatistics. More on this next week.

16