Want to learn how to write some apps for the Raspberry Pi? Today I’m going to kick off a new series of tutorials related to the Raspberry Pi and programming. This is a series that will be aimed at beginners, but seasoned programmers may want to take a look as well.
On the Raspberry Pi's pins: Now you can turn your Raspberry Pi on, and we'll begin the code. All together: In your Pi's terminal, do: $ sudo apt-get install python-rpi.gpio. You probably already have it, but just to make sure. Next, create a new python file, and let's begin: import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM).
The Raspberry Pi was created for education, tinkering and bringing technology to the far parts of the world. This is a mission I firmly stand behind, so I’m doing my part to throw some new stuff out there to get people excited about becoming a programmer with this awesome device. Why Python?Python is arguably the biggest programming language on the Pi right now, for good reason.
It has lots of tools, is well supported and development is really fast. Plus it’s easy to learn. It’s very powerful and you can even create simple games and graphics with it. I think it’s a great language to get started with as you’ll see some instant results. Tools we’ll be usingWe are going to be using Python and for our first part of the tutorials, and these are already installed and present if you’re using the Raspian image. Here is what IDLE looks like:This is our Python console and editor.
We’ll be using this extensively to create our programs. While there are many IDEs out there, it’s always good to start with the console, and learn a little how Python works. There’s no long list of tools to download, you can get started programming Python right away with the default Raspian image. Let’s get started!Let’s get comfortable with the Python environment. For this tutorial we’re only going to be covering some basics using Python version 3.2.3. We’ll run a few commands at the console to play with output, but we’ll want to create an file later to make programs that are actually useful.At the prompt (where it shows ) you’ll want to type in the commands I show and press enter. Using the promptAt the prompt you saw how you could output text, but you can also do arithmetic at the prompt.
Type in the following and press enter:3 + 2As you can see, it outputs the answer. But you can also use multiple operators and expressions.((3 + 2). 5) -3and you’ll see 22.
It’s not terribly useful at this time, but it’s nice to know it’s available.Most of the time you’ll use the prompt for setting configuration parameters. For any real useful programs you’ll want to create a file containing a list of commands. Creating a file to runLet’s create a file and run some stuff. In the IDLE 3 window, select File - New WindowYou will see a new window that comes up, and that’s where you’re going to be putting your code. Then you can save it to a text file that Python can run.In this window, type in the following code.
1# my first Python scriptthen, go to File - SaveYou should see a window that looks like this:Type in a file name like “myfirstprogram.py” and click save. Now everything you put into this file will be saved and interpreted by Python.Python is an “interpreted” language, which means the Python program will read a text file line by line and act based on the commands you give it.
This is different from a compiled language like C where you a compiler reads the code and creates a program. We’ll do some C programming later in the series and you’ll see the differences later. Input and outputNow that you know how to create a file we can play with some input and output. First I should let you know that the file you just created won’t exactly do anything.
That’s because all we did was put a comment in the file.A comment is something that’s ignored by the Python interpreter. The purpose of a comment is to leave yourself notes, or leave notes for other programmers. This makes your program easier to understand.Let’s make our file actually do something. Type in the following. 1 2name = input ( 'What is your name? ' ) print ( 'Hi', name, 'how are you?'
)now, click on Run- Run Module again.You will see a prompt that’s asking your name:What is your name?As you probably predicted, you should type in your name. Press enter.You should see this:Pretty cool huh? So how does this work?.You created a variable called “name”. A variable is a storage space for data.
When you create a variable it sets aside some space for you to put things in and take them out, and gives this space a name so you can access it later.When you created name, you assigned it the value from the input method. The primary job of Input is to collect data from the keyboard. Inside the parentheses is a space where you can “pass” data to input. This text is what it displays before input tries to accept data. This is generally used for prompts like this.You used print to output a string. When you “pass” data to print it gets output to the screen.
So you passed in a string ‘Hi’ which by itself would work. But by putting in a comma afterward you are adding to that string. You used something called concatenation.You then appended (added on) the name variable. Notice how it has no quotes around name. This is how you tell Python that it’s a variable.
You have quotes about ‘hi’ and ‘how are you?’ to let Python know that’s a string, and then you added the three together.Lastly you output your newly built string.This is great example of input and output. Let’s do a little more, just for fun. Now type the following into your editor. 1 2 3 4 5 6 7#my first python script name = input ( 'What is your name? ' ) age = input ( 'How old are you? ' ) city = input ( 'What city do you live in?
' ) print ( 'The author of this program is ', name, 'who is ', age, 'years old and lives in ' city )Now, go to Run - Run Module.You will see that it now asks you a series of questions, and once you fill it out, it will display a line back to you after putting all the data together:It’s that easy!SummaryWhile we really didn’t dive that deep into programming the Pi, or even Python I hope this will at least give beginners a general idea of how to get started. I will be adding some more detailed tutorials in the future, but if you can’t wait and really want to keep going check out the at Python.org.You don’t have to stick with Python 3 either. Python 2.6 is still in very active use and there are actually more packages available for it if that’s what you’d prefer. Both versions are very good and it doesn’t hurt to learn them both.In future tutorials we’ll explore python deeper, and even get into some other languages such as C and assembler. I’ll also show some more useful things you can do to get you really pumped about programming on the pi.If you have any questions, leave them in the comments!
Help on module math:NAMEmathMODULE REFERENCEfollowing documentation is automatically generated from the Pythonsource files. It may be incomplete, incorrect or include features thatare considered implementation detail and may vary between Pythonimplementations. When in doubt, consult the module reference at thelocation listed above.DESCRIPTIONThis module is always available. It provides access to themathematical functions defined by the C standard.FUNCTIONSacos(x, /)Return the arc cosine (measured in radians) of x.⋮ ⋮ ⋮Import specific items from a library module to shorten programs. Use from.
To load only specific items from a library module. Then refer to them directly without library name as prefix. Import math angle = math.
Degrees ( math. Pi / 2 ) print ( angle )Since you just wrote the code and are familiar with it, you might actuallyfind the first version easier to read. But when trying to read a huge pieceof code written by someone else, or when getting back to your own huge pieceof code after several months, non-abbreviated names are often easier, exceptwhere there are clear abbreviation conventions. There Are Many Ways To Import Libraries!Match the following print statements with the appropriate library calls.Print commands:. print('sin(pi/2) =', sin(pi/2)).
print('sin(pi/2) =', m.sin(m.pi/2)). print('sin(pi/2) =', math.sin(math.pi/2))Library calls:. from math import sin, pi. import math. import math as m. from math import.Solution. Library calls 1 and 4.
In order to directly refer to sin and pi withoutthe library name as prefix, you need to use the from. Whereas library call 1 specifically imports the two functionssin and pi, library call 4 imports all functions in the math module. Library call 3. Here sin and pi are referred to with a shortened libraryname m instead of math. Library call 3 does exactly that using theimport.
Syntax - it creates an alias for math in the form ofthe shortened name m. Library call 2. Here sin and pi are referred to with the regular libraryname math, so the regular import. Call suffices.Importing Specific Items. Fill in the blanks so that the program below prints 90.0. Do you find this version easier to read than preceding ones?. Why wouldn’t programmers always use this form of import?
From math import degrees, pi angle = degrees ( pi / 2 ) print ( angle )Most likely you find this version easier to read since it’s less dense.The main reason not to use this form of import is to avoid name clashes.For instance, you wouldn’t import degrees this way if you also wanted touse the name degrees for a variable or function of your own. Or if youwere to also import a function named degrees from another library. Reading Error Messages. Read the code below and try to identify what the errors are without running it. Run the code, and read the error message.
What type of error is it? From math import log log ( 0 ) Solution. The logarithm of x is only defined for x 0, so 0 is outside thedomain of the function. You get an error of type “ValueError”, indicating that the functionreceived an inappropriate argument value. The additional message“math domain error” makes it clearer what the problem is.Key Points.Most of the power of a programming language is in its libraries.A program must import a library module in order to use it.Use help to learn about the contents of a library module.Import specific items from a library to shorten programs.Create an alias for a library when importing it to shorten programs.