Introduction: Raspberry Pi Made Easy - Part 4 (beneficial Non-essentials)
As a hobbyist, my main goal is to build something that's fun and hopefully useful; as an educator, my main goal is to impart sufficient knowledge that my student not only can build, but can also design. As a hobbyist, I only need to follow a good set of instructions - the more detailed the better; as an educator, I hope my student will gain sufficient knowledge that he/she can make sense of a bad/incomplete set of instructions. While the hobbyist might get stumped when time and advances in technology render a set of instructions somewhat obsolete, the educated student can decipher what parts are still good, and how to work around the parts rendered not particularly practical.
This instructable superficially covers two topics essential to being a good RasPi maker. The good news is that if one doesn't study these topics, eventually he/she will learn them anyway by simply repeating the same or similar actions over many projects - through osmosis, so to speak. The bad news is that it can take many projects to learn even the basic fundamentals if no time is devoted to their direct study. By spending a few hours of dedicated study to these topics, one can progress much faster on his/her journey to maker status.
The two topics are:
- Linux (of which Raspian is but a flavor)
- Python (which is the recommended language for programming the RasPi)
Raspian and Python are the Raspberry Pi Foundation's recommended tools. While other tools can be used, it is much easier to work within the recommendations when new to learning a subject like the RasPi.
This instructable is a brief introduction into these two topics.
Step 1: The Raspian OS
Raspian is the official/recommended operating system for the Raspberry Pi. It is a specially brewed version of Linux for the RasPi. The notes which follow assume you have installed Raspian ( possibly using Noobs.)
Connect to the RasPi Terminal (see Raspberry Pi Made Easy - Part 1 (getting the thing working) if you don't know how. You will be presented with something that looks like: pi@raspberrypi:~ $ (assuming you have not changed the default user name.)
The first part, pi, is the name of the current user. This can be changed in the configuration. raspberrypi: is the name of the machine. This can also be changed in the configuration. We'll discuss the tilde (~) shortly. The $ is the prompt showing the RasPi is awaiting a command. If the prompt is a #, you are logged in as a superuser. This is not recommended unless you are confident you know what you are doing.
The ~ directory is where the majority of user programs/files should reside. This is the directory devoted to the current user.
Type cd .. (there is a space between cd and the two dots) followed by ENTER. (Always follow each command with ENTER.) We are now presented with: pi@raspberrypi:/home $. The cd .. (change directory) command moves the current directory up one level (or moves to the parent directory of the one we were previously in.) We are now in the /home directory. In this directory, each user has their own sub-directory. Repeat the cd .. command. We are now in the root (/ or top level) directory.
Type ls (list directory contents.) This command lists all the sub-directories and files in the current directory. We can see that one of them is the home directory which we were just in.
Type cd home (change to home directory.) We are presented with: pi@raspberrypi:/home $. The cd command followed by a folder name moves down one level into the named directory. Repeat the ls command.The only directory showing is the pi directory if you have not created additional users. Type cd pi. We are presented with: pi@raspberrypi:~$. We have moved to the /home/pi directory for which the ~ is the short form. All directory levels above this are system level so we should not manipulate, change, or modify anything above this level (unless you know what you are doing or are prepared to rebuild your image.)
Type ls to again see the files and directories within the ~ directory.
Type ls --help. Whenever you wish to learn more about what a particular command does, type the command appending --help. This will give you detailed information about the command. From the quantity of information about the ls command, you can see that it is much more powerful than first appears.
Type help. This command lists internally defined shell commands. Notice that the ls command is not listed as a shell command; this means ls is an external executable command called by the shell.
Type cd /bin. This commands changes the current directory to the one specified in the change directory command - root/bin. Type ls. The /bin directory holds many system level commands. Looking through the listed files reveals the ls command and many more. Spend time perusing many of the commands.
We have already shown you how to get more information about any command, be it internal or external to the shell. If even more information is required about a command, you can access the builtin command manual; type man ls to access detailed information about the ls command. This opens a viewer showing great detail about how to use the indicated command. You can use the arrow keys or mouse wheel to scroll through the document. Press the q key to leave the viewer.
To master the RasPi for IoT development will require a level of command line comfort. An excellent resource to learn more is LinuxCommand.org. Perform an Internet search for essential linux commands. You'll find many excellent resources to pursue as you learn more about Linux.
This is just the barest of introductions into Linux. We will introduce additional specific Linux commands in future instructables whenever they are needed.
Step 2: The Python Programming Language
Python is the Raspberry Pi Foundation's preferred/recommended programming language for the RasPi. Python is a high level language used widely in web/internet development and data repository maintenance. If you have programmed in any high-level language, you will make the transition to Python with little trouble. Python is case sensitive. More can be learned about Python here.
A Python program is often called a script because Python is an interpreted language; it is not a compiled language. What is the difference? A compiled source file is converted in its entirety to machine code to be run at execution time; an interpreted source file is compiled and executed one line at a time at execution time. While this does slow code execution, it offers the advantage of being able to issue commands on the fly and have them executed immediately; and, with the speed of the RasPi, slowed code execution should not be a factor except in time critical applications.
What follows assumes you have basic knowledge of C or another high level programming language. I only provide a few elementary details which should get you started with Python.
Raspian includes both Python 2 and Python 3; we will use Python 3 for all work in these instructables. As of this writing, the most recent version of RasPi Python is 3.4.2 while the most recent version for the PC is 3.5.2.
On the RasPi, in the GUI (finally), click on Menu > Programming > Python 3 (IDLE). This starts the Python Shell wherein we can type commands and have them execute immediately. The three chevrons >>> indicate the Shell prompt.
The print command
At the prompt, type print("Hello World!") followed by ENTER. (Commands in the Python Shell are terminated by the ENTER key.) Python dutifully prints Hello World! as output. Notice that the Shell offers syntax highlighting. (Figure 1)
This time we will intentionally misspell the word print. Type prin("Hello") (always follow each Python command by pressing ENTER.) Whenever Python can't execute a command it generates a Traceback telling you the line and word on which it chocked.The line and column numbers of the current cursor position are stated in the lower right corner of the Shell window. (Figure 2)
The print() command prints to the screen whatever is enclosed in the parentheses (). Anything within a pair of single quotes(' ') or a pair of double quotes(" ") is printed as a literal. Allowing both single and double quotes to indicate literals makes it possible to include a single or double quote as part of the literal. Type print('Hello "World"') (the last set of quotes is a double quote followed by a single quote.) In this example, "World" is in double quotes while the entire literal is in single quotes. (Figure 3)
Issue the following commands observing the output each time you press ENTER. (Figure 4)
a = 6
a = "7"
print(a + a)
a = 3.7
print(a + a)
In these code snippets, we assign the integer 6 to variable a. We then print the content of variable a. We then print the value of the variable added to itself to get 12.
We then assign a string/char to the same variable and then print its content. Notice that when we add a string/char to itself, the output is the concatenation/joining of the strings/chars.
We then assign a float to the same variable and print its content. Finally we print the variable added to itself.
While we can not perform arithmetic operations on variables of different types, we can change the type of a variable by simply assigning the desired type to it. We can also perform arithmetic operations on strings; however, the results are textual and not arithmetic. Python has very powerful commands for searching and manipulating strings; generally, these are outside the scope of this series of instructables.
Issue the following commands observing the output each time you press ENTER. (Figure 5)
a = "6"
print(int(a) + int(a))
In these code snippets, we assign the string/char "6" to the variable and then print the variable.
We then repeat the print of the concatenation of the variable added/concatenated to itself.
Finally, we type cast the variable into an integer so that it may be arithmetically added to itself. Note that this only works when the variable content can be converted to a numeric value.
Relational operators are used in conditional statements just as they are in other high level languages.
a < b : a is less than b
a > b : a is greater than b
a <= b : a is less than or equal to b
a >= b : a is greater than or equal to b
a == b : a is equal to b
a != b : a is not equal to b
a + b : a plus b
a - b : a minus b
a * b : a multiplied by b
a / b : a divided by b
a % b : the remainder after a is divided by b
a ** b : a to the power of b
int(a) : typecast a to an integer
float(a) : typecast a to a float
Note that regardless of a variable's numeric type, division results in a float if the answer is not a whole number. If either variable is a float, division will result in a float answer.
Positionally, the first character of a string is 0th character.
string[x] : returns the xth character : "abcde" = '"b"
string[x:y] : returns all characters from and including the xth up to but not including the yth : "abcde"[1:3] = "bc"
string[:y] : returns all characters from the 0th up to but not including the yth : "abcde"[:3] = "abc"
string[x:] : returns all character from xth up to and including the last : "abcde"[3:] = "de"
len(string) : returns string length : len("abcde") = 5
string + string : joins/concatenates the strings : "abc" + "def" - "abcdef"
True : is true
not True : is false
False : is false
not False : is true
True and True : is true
True and False : is false
False and False : is false
True or True : is true
True or False : is true
False or False : is false
The While Loop(Figure 6)
Type the following python instructions in the Shell (observe the indentation):
i = 0
while(i <= 6):
i = i + 1
Press ENTER twice.
This code initializes variable i to 0. It then enters a while loop which will repeat as long as the specified condition is true (i is less than or equal to 6). The colon at the end of this line tells python that this is the start of a block (the while loop) of code. Python automatically indents subsequent lines indicating they are part of the block. Pressing ENTER after the 4th line (i = i + 1) advances the block to the next line. Pressing ENTER again (on a blank line) terminates the block and since we are in the Shell, it also executes the while loop.
The For Loop (Figure 7)
The general for loop syntax is: for var in range(start, stop - 1, optional step): where start is the first value of a count sequence; stop - 1 is the last value in the count sequence; step is the amount by which the sequence is iterated - step = 1 by default. If start > stop and step is negative, the for loop iterates down.
There are variations in the for loop syntax, however, I will only provide the basic syntax here.
Type the following python instructions in the Shell (observe the indentation):
for i in range(1, 13):
Press ENTER twice.
This code declares that variable i will take on the values iterated through the for loop. Those values will be all whole numbers in the range (sequence) bounded by 1 and 13, starting with 1 and ending with one less than 13. The colon again indicates this will be a block of code (hense the indentation.) The only instruction in the block is the print instruction. Again, pressing ENTER terminates the block; pressing ENTER again executes the for loop.
Both while and for loops can be structured in other ways; however, these two basic forms will perform excellently in the majority of times where they are needed.
Python supports the use of break and continue statements in while and for statements.
Time to get a little more practical.
Step 3: Coded Python (about Time)
All python code examined so far has been interactive Python, i.e. each instruction executes as soon as it is typed and the ENTER key is pressed. This is great for testing a line of code to see how/what it does; however, autonomous code (like that required for IoT, robotics, or the vast majority of applications) must be written ahead of time and stored in a program/script which can be run later. We will look at the traditional way to do this now.
Return to the Python 3 Shell. Select File > New File. This opens the Python text/code editor. Type the following (observing the indentation):
# my first python program (Figure 8)
for i in range(1, 10):
print("This is line #", i)
A comment in Python begins with the # symbol and continues to the end of the current line. The second # symbol doesn't indicate a comment because it is part of a literal string.
The for loop and range statement were mentioned in the last Step.
Thiis print statement illustrates how to output a literal string and a variable value in a single output instruction.
Select Run > Check Module. This command checks our syntax for errors.
You will be informed that the source file must first be saved; click OK. In the Save As dialog, navigate to your desired directory or save in the default pi directory. (I'll recommend a directory to use for all your Python code in a future instructable.) If you wish to use a non-existing directory, you will have to create it in the Terminal or the GUI File Manager first. For now, let's save in the default directory. Name your program myFirstProg.py. All Python 3 programs have the extension .py.
Window focus will switch to the Shell. If there are any syntax errors in the source, a Traceback will appear here. Once any errors are fixed in your source code, you are ready to execute the code at a later time.
If we want to execute the code now, we can do so from the editor. Click Run > Run Module. This command varies from the last command in that it actually executes your code if it doesn't find any syntax errors. Python will switch to the Shell window; inform you that it is restarting the Shell (so no residual variable content will interfere with our code) and then execute the code.and display the program output in the Shell if there is any. (Figure 9)
When we used the Shell to execute a line of code in the preceding Step, only the most recently entered instruction was executed; when we used the Python editor to execute the code, the Shell executed the entire program. We didn't observe any difference from the previous output because our whole program consisted of the same single code block.
Once our program is now saved (to the SD card), it can be executed from the Terminal or from the Python code editor at a later time.
Start the Terminal. You must execute your code from the same directory in which it was saved. Assuming you saved to the default directory and that you are in the default directory while in the Terminal, type:
python3 myFirstProg.py. This tells the OS to use Python 3 to execute the named program. Program output will print to the Terminal.
Nested for loops are tricky to enter through the Shell with interactive Python so I have left them until now. Enter the following program into the Python 3 editor (not the Shell) (observing the indentation):
# nested for loops (Figure 10)
for i in range(1, 13):
for j in range (1, 13):
print(i, 'X', j, '=' i * j)
Give the code an appropriate name ending with the extension .py when asked. This program's output is shown in Figure 11.
Python also supports nested while loops.
This structure works the same way it does in other high level programming languages.
Enter the following program into the Python 3 editor - not the Shell (observing indentation):
''' multi-line comments begin with 3 single quotes
this program demonstrates the following:
how to implement a multi-line comment
how to accept keyboard input
an if ... elif ... else construct
multiconditional if costruct
function declaration and usage
very minor error checking
''' # multi-line comments end with 3 single quotes
#function definitions - these perform 1 arithmetic operation each
def add(one, two):
return one + two
def sub(one, two):
return one - two
def mul(one, two):
return one * two
return one / two
# main program code follows
print('Welcome to a calulator') # print a welcome output
print() # print a blank line
while(1): # start an infinite loop
num1 = float(input('Enter your 1st number :')) # get 1st number
num2 = float(input('Enter your 2nd number :')) # get 2nd number
op = input('Enter your operation :') # get arithmetic operation
if op == '+': # test for valid operation and branch accordingly
ans = add(num1, num2)
elif op == '-':
ans = sub(num1, num2)
elif op == '*':
ans = mul(num1, num2)
elif op == '/':
ans = div(num1, num2)
else: # print warning if invalid operation
print('Your entered an invalid operation')
# the following line prints the calculation if the operation is valid
if op == '+' or op == '-' or op == '*' or op == '/':
print(num1, op, num2, '=', ans)
print() # print a blank line then start the loop again
I understand how easy it is to make a mistake when copying code so I am including a file containing this code; it is called calculator.py. If you view this instructable in a browser on the RasPi, you should be able to download the file directly to your RasPi; if you are viewing this instructable using your PC, you can download the file to your PC and copy it to your RasPi using SCP. See Raspberry Pi Made Easy - Part 3 (PC / RasPi File Transfers) for instructions on doing so.
This code uses an infinite loop to retain control over the RasPi so the code can be continuously run. When you wish to terminate the script, press CNTL + C.
Multi-line comments are surrounded by three single quotes.
Function definitions begin with the word def and then the function name followed by any parameters passed to the function. If no parameters are passed to the function, empty () follow the name. The function body is an indented block so the parameter list must be followed by a colon. The function body can contain any number of statements and additional blocks (ex. for loops). The function body ends when the indent is terminated.
Functions can return a value as shown in the code; however, they do not have to return a value.
Error checking is implemented for the operation performed. No other error checking is provided in this program.
Still More Python Tools
Python is a rich language with many more tools for handling specific types of data. These tools include: lists, tuples, dictionaries, and sets. These are beyond the scope of this introductory instructable.
Step 4: All Done
For further study in Linux or Python (or so many other topics), I recommend sites such as Coursera or edX. These sites give major universities from around the world a platform to offer low cost or even no cost courses including certificate specialization streams.
I have taken University of Michigan's Programming for Everbody (Getting Started with Python) and found it excellent for the beginner; and the price is great - free.
While I haven't taken University of Texas' Learn to Program using Python, the course description sounds good.
I have taken other courses through both sites and consider them to offer a wonderful opportunity for anyone to increase their knowledge.
If you have followed along in this instructable, congratulations on completed what might not have been the easiest to get through.
Please leave comments if you have found this instructable useful. Please point out any errors or omissions. Thanks for reading.
We have a be nice policy.
Please be positive and constructive.