In the previous tutorial, we successfully set up a Raspberry Pi (RPi) Linux desktop. Now let’s learn Python.
We could start with how to control the hardware by using Python scripts, but that would defeat the purpose of using Raspberry Pi and a Very-High-Level-Language (VHLL) — such as Python — to control electronics.
Certainly, you can easily control electronics and design embedded applications with any microcontroller. The reason we’re using RPi (a single-board computer) and a VHLL are to use the features of a desktop, web, and network programming in embedded applications. This allows us to design powerful and complex applications that employ user interfaces, graphics, networking, and databases — for manipulating, sharing, and using data from embedded sensors and design embedded applications that may be networked to desktop or server systems.
With RPi, we can interface a variety of embedded add-on devices (or circuits) that provide machine-level data in specific applications. This data can, then, be manipulated and used by a VHLL (like Python) to design large applications in several niches. These could include biometrics, robotics, automation, gaming, and cloud computing, etc.
For example, we can interface a fingerprint module with Raspberry Pi and design a biometric attendance system. By using Python features, we can also develop a software solution on this biometric attendance system where an HR manager can view an attendance log, evaluate the productivity of employees, and calculate salaries and overtime payments. We could develop a fully integrated HR management software.
By simply interfacing LED matrix, character LCD, or graphic LCD with RPi, we can design a remote-controlled display board that flashes custom messages via an RPi desktop-based GUI solution. By interfacing an accelerometer sensor and a couple of buttons, we can develop a customized gamepad for gaming on Raspberry Pi.
There are unlimited possibilities when you combine electronics, an operating system, and the features of a VHLL. A strong foundation in Python means it’s possible to build complex applications that go beyond a basic programming hobby.
Python is a Very-High-Level Language (VHLL) that can also be used to code at a bit-and-bytes level. It’s a general-purpose, object-oriented, cross-platform programming language that can run on all major operating systems and hardware platforms. Though Python is object-oriented, it’s not limited to an OOP software design pattern.
This means it’s possible to design software solutions on Python using procedural or functional programming. Software design patterns, such as Singleton, Model-View-Controller (MVC), Template, Proxy, Command, Observer, Factory, and others, can be implemented in Python. The object-oriented features of Python are similar to C++, but simpler.
As a VHLL, Python has a high level of abstraction from the underlying hardware. Apart from this, Python can be integrated with a variety of other programming languages and combined with software components written in other languages. This versatility is a software advantage in almost any niche.
However, Python is an interpreted language, so it’s typically slow compared to compiled languages. This can be a challenge when designing applications that must respond to time-critical events. But it is possible to pre-compile python or use modules written in other compiled languages. And, in most cases, the performance of a Python application is sufficient.
When used for embedded applications on Raspberry Pi, users may encounter limitations. The execution of an embedded application with Python may be slower than by a machine code on a microcontroller. RPi also lacks some important hardware features, such as analog-to-digital converters, real-time clock, and hardware interrupts.
Any requirements for analog-to-digital converters or real-time clock can be compensated by interfacing external ADC or RTC with the RPi. For interrupts, you must rely on the interrupt API of Linux. The software interrupts will need careful management of threads or they’ll fail to implement as quickly as the actual hardware interrupts.
Python is a general-purpose programming language that can be used for a variety of application domains. It has a standard library and several extension modules that let use python in many applications and software solutions.
By running Python on single board computers like Raspberry Pi, Beaglebone, and others in full Linux environments, it can be used in embedded applications. These single-board computers can be interfaced with microcontrollers and programmable chips to design interesting applications in embedded systems, robotics, automation, biometrics, and other niches.
A Python three implementation, called MicroPython, can be used to program a microcontroller board, such as pyBoard. This is similar to how embedded C is used to program Arduino and other microcontrollers.
MicroPython on pyBoard lets you program microcontroller applications using Python, as well as compile Python to bytecode or machine code.
To avoid confusion, we’ll use the conventional Python V3 on RPi. With the support of extension modules, it will interact with the electronic circuits and hardware via the general-purpose input/output (GPIO) and other RPi hardware interfaces. MicroPython produces a bytecode or executable machine code that can run as firmware on pyBoard.
Using RPi, we will be designing general-purpose Python applications that run as Linux processes rather than a bytecode or firmware machine code. One advantage of using Python on the statistical process control (SBC) — rather than Micropython on pyBoard —is that we gain full access to Python’s standard library and extension modules. Micropython lacks most of the features of the standard library.
Other advantages of using conventional Python means that we can:
- Import hardware-control modules to configure and manage electronics via the GPIO and hardware interfaces
- Use the socket library to connect with the Internet services available
- Get interpreter access to hardware devices via the USB serial port and over Telnet protocol
- Respond to external devices and timer events with the help of Linux APIs and special python modules.
- Write power-on boot sequences that implement a Python application of any complexity.
Thanks to these features and versatility, Python has become a top choice when programming the Internet of things (IoT) applications. What’s more, Python can be used for desktop programming, web development, software development, business applications, and scientific computing. With the help of Tk GUI library and toolkits, such as Qt, wxWidgets, and Kivy, it’s possible to design desktop GUIs.
Python’s standard library supports all major Internet protocols and supports the use of HTML, JSON, and XML. There are several Python frameworks for web and Internet development, including Django, Flask, Bottle, Pyramid, and Python-based content management systems — such as Django CMS, and Plone.
Additionally, Python-based tools like SCons, Roundup, Apache Gump, and Buildbot can be used for software development. It can also be used for enterprise resource planning (ERP) and e-commerce solutions. There are packages available that can be used for scientific computing, data analysis, and data visualization.
Python has a lot to offer but it’s up to the developer on how to best use its features with electronics.
Python has four production-quality implementations.
1. Classic Python. This is the most up-to-date and full implementation of Python. CPython, including its interpreter, compiler, and standard library and extension modules, is coded in C language. It can run on any C-compliant platform. CPython is the de facto implementation of Python programming language and is typically referred to as “Python.” It requires no special programming environment.
2. Jython. Compliant with Java 7 and higher, Jython is an implementation of Python that’s developed for Java Virtual Machines (JVM). The latest release, Jython 2.7.1, is compatible with Python 2.7 but does not support Python V3. The V2 and V3 versions of Python are also incompatible with each other.
Jython can use all Java libraries and frameworks, and is compatible with any Java class as an extension module. Jython applications are essentially pure Java applications that can run any device with a JVM, which are available for almost all operating systems and hardware platforms.
3. IronPython. IronPython is a .Net (Common Language Runtime or CLR) implementation of Python. CLR is now open-source and is ported to Linux and macOS. CLR also has a cross-platform implementation, Mono, which can run on Windows and other non-Microsoft operating systems.
IronPython can run on any target machine having a .Net framework. It can use any CLR class as an extension module, including classes written in C# and Visual Basic .Net.
4. PyPy – PyPy. An alternative implementation of CPython that can generate native machine code “just-in-time.” PyPy is faster in speed and memory management compared to all other implementations — and credit goes to its just-in-time compilation to machine code. CPython is faster than Jython and IronPython, and only slightly lags behind PyPy.
PyPy is compliant with Python V2 and V3. It supports most of the standard Python libraries and can use any C-coded extensions. By default, it’s stack-less and provides micro-threads for concurrency.
There’s also a high-performance implementation of Python known as Pyston available. However, the implementations of Python differ depending on the environment in which they run and on the libraries, extension modules, and frameworks they can use. The implementation selected also influences the packaging and distribution of the application.
It’s possible to install and run any of the above implementations of Python on Raspberry Pi. By default, RPi uses CPython. For higher performance, PyPy can be installed, which is two to 10 times faster than the conventional Python. PyPy and CPython can use C-coded extension modules but if you require the Java libraries and modules, Jython may be preferred. For CLR libraries and extension modules, consider IronPython.
Just remember: RPi was never meant for time-critical applications. So, we’ll stick with the default Python installation on Raspbian. It’s CPython and provides the full features of Python language.
Standard library and extension modules
Python’s standard library includes built-in modules (written in C) for OS-related tasks and modules (written in Python) for common programming tasks, such as data handling, string manipulation, date-time operations, mathematical operations, file, and directory access, data compression, etc.
The extension modules — from the standard library or specific Python implementation — permit additional functionalities for the underlying operating system or other software components. It’s also possible to embed Python in applications coded in other languages via app-specific Python extensions.
A few examples:
- CPython can use C++ libraries and classes as extension modules
- Jython can use Java libraries and classes as extension modules
- IronPython can use CLR libraries and classes as extension modules.
However, when using extension modules, the cross-platform portability of a Python application may be compromised and may require additional dependencies accordingly. For example, Jython will require JVM to compile Java libraries and classes.
Typically, Python files are text files that are scripts or modules. Scripts are files that run directly as a process. Modules are source files that are imported to provide certain functionality to the script. Although a Python file can because modules can serve as executable scripts, providing functionality to other scripts on import.
Essentially, any Python application can be seen as a collection of scripts and modules or a script alone.
To develop software, you’ll need a text editor to write code for Python scripts and modules, as well as a compiler and interpreter to generate executable code. There are several integrated development environments available that combine the text editor, compiler, and interpreter into a single programming environment.
Popular integrated development environments (IDEs) for Python include IDLE, Eclipse, Geany, and Thonny. Raspbian comes with the default installation of IDLE. Most IDEs provide an interpreter, whereby Python codes can be executed interactively. These are called interactive sessions. These interactive sessions can be identified by a prompt string “>>>” which indicates that some Python statements are expected for execution.
Python scripts can be run from within the IDE or from a command-line Python interpreter. Within the IDE, Python statements can also be run from an interactive session although it’s typically better to wrap your application as a Python script. For example, on RPi, Python scripts can be run from within the IDLE (or other Python IDE) or from the Bash shell.
When running Python scripts from the shell, the “python” or “python3” command can be used. The command should follow the name and/or path of the target Python script and any optional arguments as required. The bash shell also allows multiple lines as a single argument that can be used to execute multiple Python code statements together. However, some shells only allow a single line command where one or more Python statements can be executed and separated by a semicolon.
The Python script files have a .py extension (suffix to the filename) and complied bytecode files of Python have .pyc or .pyo extensions.
To run Python scripts from bash shell, these commands can be used:
Python 2.7 can be the default Python version on a machine. On running python command, the script will be executed by default version. On running python3 or python3.5 command, the script will be executed explicitly by V3 or V3.5 versions, respectively (if installed).
On Raspbian, Python scripts can be written and compiled using IDLE. You can open IDLE by navigating to Programming -> Python 3 (IDLE).
The IDLE will open with an active, interactive session, like this:
To write a Python script or module, click on Files -> New File.
Write your Python script in the text editor and save it by clicking Files -> Save.
To run a Python script, open it in the IDE and click on Run -> Run Module or press F5.
Python is a mature programming language that offers ongoing learning. The best place to explore Python is on its website. The same goes with Jython, IronPython, and PyPy. The standard library packages and extension modules can be downloaded from the Python Package Index.
CPython is covered by the Python Software Foundation License Version 2, which is compatible with GNU Public License (GPL). Jython, IronPython, and PyPy are also covered by free licenses. This means anything downloaded from the main Python, Jython, IronPython, and PyPy sites are completely free.
Many third-party Python sources, tools, and extension modules offer similar licenses or are covered by the GPL or the Lesser GPL (LGPL). Some commercially developed modules and tools may require a fee. However, Python can be used for any proprietary, free, or open-source software development.
In the next tutorial, we’ll cover the basics of Python programming language.