The Raspberry Pi is a very inexpensive, fully programmable computer that is only the size of your palm. Although the Raspberry Pi is small, its potential is unlimited. You can create very cool projects on the Raspberry Pi just like you would on a regular desktop computer. For example, you can set up your own home cloud storage server using the Raspberry Pi.
What programming language does Raspberry Pi use?
The Raspberry Pi uses Python for programming. A core idea of Raspberry Pi projects is the use of the Python programming language. Python allows Raspberry Pi owners to expand their projects to incredible scales.
Python is an interpreted, object-oriented, cross-platform programming language. Its good reliability, clear syntax, and ease of use make it one of the most popular programming languages. Python is an elegant and powerful language.
The Raspberry Pi provides an incredibly inexpensive development platform for Python programming. Python is considered a “teaching” language because it is easy to learn, but that does not mean Python is weak.
With the Raspberry Pi and Python, the only limit is your imagination. You can write games in Python and run them on a Raspberry Pi-controlled game console. You can write programs to control robots connected to the Raspberry Pi. Or you can send your Raspberry Pi to take incredible photos from 39,000 kilometers above the Earth, just like Dave Akerman.
The advantages of the Python language are as follows:
1. Simple: Python is a language that embodies the philosophy of simplicity. Reading a well-written Python program feels like reading English. It allows you to focus on solving problems rather than figuring out the language itself.
2. Easy to learn: Python is extremely easy to get started with, as it has very simple documentation.
3. Fast: Python is written in C, and many standard and third-party libraries are also written in C, making it very fast.
4. Free and open-source: Python is one of the FLOSS (Free/Libre and Open Source Software). Users can freely distribute copies of the software, read its source code, modify it, and incorporate part of it into new free software. FLOSS is based on the concept of a community sharing knowledge.
5. High-level language: When writing programs in Python, you do not need to worry about low-level details such as how to manage memory used by your program.
6. Portability: Due to its open-source nature, Python has been ported to many platforms (modified to work on different platforms). These platforms include Linux, Windows, FreeBSD, Macintosh, Solaris, OS/2, Amiga, AROS, AS/400, BeOS, OS/390, z/OS, Palm OS, QNX, VMS, Psion, Acom RISC OS, VxWorks, PlayStation, Sharp Zaurus, Windows CE, PocketPC, Symbian, and the Android platform developed by Google based on Linux.
7. Interpreted: A program written in a compiled language like C or C++ can be converted from source files (i.e., C or C++ language) to a language used by your computer (binary code, i.e., 0s and 1s). This process is completed by a compiler with various flags and options.
When running a program, the loader software copies your program from the hard disk into memory and runs it. Programs written in Python do not need to be compiled into binary code. You can run the program directly from the source code.
Internally, the Python interpreter converts the source code into an intermediate form called bytecode, which is then translated into machine language used by the computer and executed. This makes using Python simpler and makes Python programs easier to port.
8. Object-oriented: Python supports both procedural and object-oriented programming. In a procedural language, programs are constructed from procedures or simply reusable code functions. In an object-oriented language, programs are built from objects that combine data and functions.
9. Extensibility: If you need a piece of critical code to run faster or want to keep certain algorithms private, you can write part of the program in C or C++ and then use them in your Python program.
10. Embeddability: Python can be embedded in C/C++ programs to provide scripting functionality to program users.
Rich libraries: The Python standard library is indeed large. It helps handle a variety of tasks, including regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interface), Tk and other system-related operations. This is known as Python’s “batteries included” philosophy. In addition to the standard library, there are many other high-quality libraries such as wxPython, Twisted, and the Python Imaging Library, etc.
11. Well-structured code: Python uses mandatory indentation to ensure good readability of the code. Programs written in Python do not need to be compiled into binary code.
Detailed Explanation of Python Programming on Raspberry Pi
When you create a Python program, you must first exit the compiler environment and open a text editor, such as Emacs or the Raspberry Pi’s Leafpad. After creating the program, save it with the “.py” extension. Then you can run the program by entering the following command:
Among many programming languages, Python’s syntax is also quite unique. Python uses spaces or indentation to separate different code blocks. Other languages, such as C, use curly braces to distinguish different code blocks, such as in if statements; Python uses colons and indentation to define a code block.
The code format in C language is as follows:
You may notice two details about Python programming. First, the role of parentheses in the if statement is not very obvious. In Python, parentheses are not required, but in most cases, using parentheses is a good programming habit because it improves the readability of the code. You will also find that most other programming languages end each line of code with a semicolon, while Python does not. This may take some getting used to, but it avoids compilation failures due to misplaced or missing semicolons. In Python, the end of each line of code is simply the end of that statement—it’s that simple.
You have already seen the form of a statement, such as:
As previously mentioned, in Python, you do not need to declare in advance that x is an integer variable, and y is a character variable—Python can distinguish on its own. These statements are called assignment statements; they assign the value on the right side of the equal sign to the variable on the left side. Different programming languages have various naming rules, but the best advice I can give you is to choose one rule and stick to it. If you prefer the Pascal language rule (ThisIsAVariable), then use that rule. If you lean towards the camel case rule (thisIsAVariable), use that rule. But be consistent; you will thank your persistence later. In any case, whether the variable is numeric, character, list, or something else, the work of assignment is simply: assigning a value to a variable. This is the simplest function in programming.
1. If Test
The next programming function to introduce is the if statement, along with its related elif and else functions. As you would expect, if performs a test and then selects an option based on the test result. The most basic if statement is as follows:
‘1’ and the boolean variable “true” have the same effect, so the above statement will always output “true”.
When you enter an if statement in the Python terminal or IDLE and end it with a colon, the next prompt is always an ellipsis (…), which means Python is waiting for an indented block. If you have already indented, press Enter to finish waiting. If you are writing a program in a text editor, make sure you indent when needed.
From this point, I will write code in the format of a text editor and write the output results as they appear after running the script.
This is a more complex program using elif and else:
Clearly, this code will eventually output “Spam is a wonderful thing!” When the program executes, the computer first checks the first if statement; if the evaluated statement is correct, it will immediately execute the code in the subsequent indented block. If it is not correct, it skips the indented block to look for elif and checks its correctness. Similarly, if correct or if there is no elif statement, the computer will execute the code in the next indented block; if it is not correct, it will skip the indented block to look for the next elif or else statement.
There are three points to note here: First, if the content of an if statement is incorrect, none of the content in the subsequent indented block will execute, and the computer will jump directly to the next unindented code.
Second, like other languages, Python uses double equals to check for equality. A single equals sign is used for assignment, and double equals is used for checking. I mention this because every programmer (I am sure I mean every programmer) will sometimes use a single equals sign in an if statement for checking, resulting in many strange outcomes in their programs. You may make the same mistake, but I hope to give you a warning in advance.
Third, Python ignores blank lines, spaces (of course, except in interactive scenarios and within indented blocks), and comments. This is important because you can freely annotate your code to improve its readability for other programmers, even for yourself when you read your code later.
In Python, comments usually start with a “#” and the program ignores everything after the #.
Code readability is a very important factor, and I hope you will regularly recall this statement. Whether you are trying to debug previously written code or programming in the following way:
Although it may not be fun, you can clearly understand the content of the second writing style. After reading hundreds of lines of code without spaces, blank lines, or comments, your eyes will thank you, believe me. Let’s see what happens when using spaces in the second to last line:
You can use spaces freely.
Regarding the if part, the last thing I want to mention is about boolean operators. In a test of correctness, X and Y being correct means both X and Y are correct. X or Y being correct means either X or Y is correct, and not X being correct means X is incorrect. Python uses keywords for boolean operations, unlike C or C++ which use &&, ||, and ! operators. Learn these operators well, they will become very handy.
2. Loops
Typically, a program executes each line from start to finish once. However, some specific statements may cause the program’s execution order to jump from one point to another; these control-flow statements include if (then) statements and loops.
The simplest loop statement might be a piece of code that executes many times, such as:
You can also use a for loop to iterate through a string or a list:
Although the syntax of the for loop in Python is somewhat different from that in C or Java, once you get used to it, using this syntax will be very comfortable.
The second type of loop statement is the while statement. This statement checks a condition and will continue executing the code in the indented block as long as the condition is true, such as:
Perhaps contrary to what you might imagine, this piece of code will never output “10” because x is incremented after it is output. During the 10th loop, the compiler outputs “9” and then x is incremented to 10. At this point, the while condition is no longer true, so the code in the indented block will not be executed.
If you are waiting for a specific event to occur, such as a key press or user pressing “Q” to exit, the while statement is very useful. Let’s look at the next example:
In this code, there are two points worth noting: First, in Python 2.x, the raw_input command is used to get user input, while in Python 3.x, the command has simply changed to input; second, remember to use the break command, which will exit the current loop. So in this case, the loop in the while will run indefinitely, but when the check var == ‘q’ returns true, the program will exit the current loop and end.
3. Functions
Functions allow programmers to reuse the code they write. It can greatly improve work efficiency. Usually, if you find that certain functions in your code need to be executed many times, that function is likely to need to be rewritten as a function.
Suppose you write a simple program to calculate the area and perimeter of a rectangle. The user inputs the height and width of the rectangle, and then the program performs the corresponding calculations. The simplest way to implement this functionality is to write a function with parameters representing the height and width of the rectangle. The function will then return the area and perimeter of the rectangle to the main program. To implement this function, we write using the def assignment statement. The def assignment statement is how we define a function, and its syntax is def function_name(parameter1, parameter2):
This small program requires you to provide some parameters and return the calculated results. This may not be the best example (you can calculate the result with less code), but it illustrates the idea of code reuse well. Through this function, you understand that at any point in your program, whenever you need to calculate the area or perimeter, you can call the AreaPerimeter function and assign values to the parameters “height” and “width.”
It is important to note that the raw_input function will return a string, even if you input a number, it will return a string type value. This explains why the height and width variables in the AreaPerimeter function must be converted to int before calculation.
If you are familiar with other languages, you will find that Python functions differ in methods, functionality, and steps from functions in other languages. For example, in Python, all functions are called by reference (call-by-reference). Without needing overly technical terms, simply put, this means that when you pass a parameter to a function, you are passing a pointer to a variable, not passing a value. This approach makes memory management easier in Python. For example, when you repeatedly pass a list parameter to a function, you do not need to copy the entire contents of the list. Specifically, when a function takes a list as a parameter, you are passing only the location of the first element of the list in memory, and then the function looks up the remaining items based on that first element’s location.
Another interesting aspect of functions is that they are executable statements. This means that a function can actually be declared and called within an if statement. Although this is not very common, defining and calling this way is legal (and sometimes quite useful). The def statement can be nested within loops, nested within other def statements, and even nested within lists and dictionaries.
We will revisit the function part when we work on specific projects; for now, just know of their existence and that they are very useful for every program you write.
4. Objects and Object-Oriented Programming
The last important thing in this chapter is its inherent ability to execute object-oriented code. Object-oriented programming (OOP) is a more advanced topic, which may not be within the scope of this book. However, I believe it is a very important topic that should not be overlooked.
OOP is a paradigm where program data is divided into objects combined with functions (or methods). An object is a data structure, typically a combination of several data types, including integers, characters, or other data types. Objects are typically part of a class, associated with methods within the class, and manipulated through those methods.
The simplest way to explain this part is to use the shape example. In this example, a shape is a class of an object. The class has values, such as name and numberOfSides. The class also has related functions, such as findArea or findPerimeter.
The shape class has many subclasses, which describe things more specifically. A square is an object of the shape, with its shapeType value equal to square and numberOfSides value equal to 4. Its findArea function accepts the numberOfSides value and returns the square of that value. At the same time, a triangle object also has different name, shapeType, and numberOfSides values and a different findArea method.
This example not only briefly introduces the concept of objects but also illustrates the concept of inheritance—a component of OOP. The triangle object inherits the name, numberOfSides, and findArea parts from its parent shape class (although these parts have different values or implementations). If an object inherits from the shape class, it will also inherit those parts. Even if it does not need to use those parts, it will still contain them. It may add some other parts (for example, a circle object may have a radius value), but it will also include those parts from its parent class.
If you use these classes in programming, Python is easier to understand compared to C++ or Java. Regardless of whether an attribute is an object or a method, you can name it using the following syntax: object.attribute. If you have a circle object called holyGrail, its radius value would be expressed as holyGrail.radius. A square named unexplodedScotsman would define its area calculation function as unexplodedScotsman.findArea.
As previously mentioned, OOP content goes beyond the scope of this book. But concepts like functions are very useful, especially in long and complex programs. As you learn Python, feel free to explore. You will find that Python is also a feature-rich language that even allows you to perform other advanced programming tasks. (Adapted from Electronic Enthusiasts)
1.Every hardware developer must not ignore production quality!
2.The Arm open machine learning developer community teaches you how to perform machine learning on Raspberry Pi!
3.One picture to confuse “Internet of Things”
4.Some misuses and summaries of C language in microcontrollers!
5.Five embedded operating systems you must understand when learning STM32
6.Clearing the fog | Is application development on embedded Linux only for experts?
Disclaimer: This article is a network reprint, and the copyright belongs to the original author. If there are any copyright issues, please contact us, and we will confirm the copyright based on the copyright certificate you provide and pay for the manuscript or delete the content.
Leave a Comment
Your email address will not be published. Required fields are marked *