ESYS 57D Industrial IoT Week-3
IoT Systems
A common application for IoT systems is data collection. IoT devices, such as sensors, are often deployed in locations where data collection is to take place. Agriculture, transportation, and manufacturing are just a few examples of areas where data collection is done by one or more IoT systems. While data collection is important, data must be processed before it can be useful. Collected data can be processed close to the point of collection or it can be transmitted and stored in the cloud for processing at a later time. Often data from several sources is combined to provide the most useful information. Computer programs are used for the efficient processing of the collected data.
why learn to code?
1991, Mark Weiser wrote a paper titled "The Computer of the 21st century". In his paper, he envisioned the future of the IoT described as "specialized elements of hardware and software, connected by wires, radio waves, and infrared, that will be so ubiquitous that no one will notice their presence". In a world that is becoming increasingly digital, the ubiquitous nature of computing means that software is everywhere. Today, programmers may work on firmware, device drivers, mobile applications, web interfaces, data analysis, and more. These employment areas were all available before, but the IoT has drastically increased the number of available projects and companies. Another benefit of being able to code is that programmers can create their own software tools. Need a specific network filter not available in the market? Maybe a project requires some specific data analysis. This can all be coded by a good programmer.
Dictionary in Python
A dictionary is a list of elements that are separated by commas. Each element is a combination of a value and a unique key. Each key is separated from its value by a colon. The entire dictionary is written within curly braces. Dictionary elements can be accessed, updated, and deleted. There are also many built-in dictionary functions such as a function that compares elements within different dictionaries and another that provides a count of the total number of elements within a dictionary. Figure 5 shows examples of dictionaries.
Home Automation with Packet Tracer 7
A good example of what PT 7.0 can do with IoT simulations is shown in the Smart Home. Figure shows a screenshot of the smart home built in PT. The model includes connected doors, connected garage doors, connected sprinklers, connected smoke detectors, connected ceiling fans, and more. All this can be controlled and monitored via a web interface, accessible from any device in the home such as a tablet, smart phone or laptop. PT 7.0 does all this while also representing the network underneath with wireless routers, switches and cables.
PT MCU code
A microcontroller unit (MCU) is a small computer built on a System on a Chip (SoC). It is similar to an SBC but it contains less processing power and functionality. It contains a processor core, memory, and programmable input/output peripherals. Microcontrollers are designed for embedded applications or applications that require few computer resources. Examples of applications that rely on microcontrollers are automobile engine control systems, implantable medical devices, remote controls, office machines, and appliances. Mixed signal microcontrollers are also common, integrating the analog components needed to control non-digital electronic systems. PT 7.0 brings support to an MCU emulator. A user can program the PT MCU to perform tasks similar to real-world MCUs. To simplify the process, the PT MCU can also be programmed with Python. PT MCU has one USB port, six digital I/O ports, and four analog I/O ports. The digital I/O ports on the PT MCU allow a user to connect digital sensors and actuators. The analog I/O ports allow a user to connect analog sensors and actuators. From a simulation stand point, PT SBC and PT MCU differ very little from each other. Namely, PT SBC can host files and has a Desktop tab with a number of applications such as web browser and email client. PT MCU does not host files and does not have a Desktop tab. Note: While it is not usual to find Python supported on MCUs in real life, PT 7.0 implements Python support for user convenience Figure shows a screenshot of the PT MCU window.
program
A program is a set of ordered instructions created to accomplish a specific task. Based on that definition, many everyday life activities can be seen as programs. A basic recipe for bread can be seen as a program. In this example, the order of the instructions is relevant. The recipe, like a software program, was designed to accomplish a specific task, in this instance, to make bread. The recipe could have been written in any language; English, Portuguese, Chinese, or Arabic. The only requirement for the language choice is that the person who is to make the bread is able to understand the language. While different languages have different grammar rules and syntax, the recipe's logic should not change. Similarly, computer programs are also a set of ordered instructions created to accomplish a specific task. Also called code, computer programs can be written in several different languages. The syntax and rules vary from language to language but the program's logic should have little to no change.
Tuples in Python
A tuple is a sequence of unchangeable Python objects. Tuples are sequences, separated by parentheses. Figure shows examples of tuples.
PL-App & headless operation
Alternatively, to use the Raspberry Pi as an IoT device, one must be able to control it remotely over the network. Headless is the term used for servers that are solely remotely operated. While many headless setups are available, this course focuses on a customized solution called Prototyping Lab Application (PL-App). The PL-App allows access to the Raspberry Pi directly from the network. Headless access allows for operation without the need for a monitor, keyboard or mouse to be directly connected to the RaPi (Figure 1).
Activity = Identify the Type of Language
Activity = Identify the Type of Language
computer programs
All computers need programs. A computer is any device containing a CPU, memory and I/O devices (monitor, keyboard, mouse, audio card, etc.). Desktop PCs, smartphones, tablets, digital watches, and smart devices are just a few examples of computers. Even though computers are everywhere, they are useless until they are running programs.
Securing IoT Code
An IoT system consists of the interconnection of several functional blocks: the devices, the gateways, the network, the Cloud and the actual application. On each of these blocks, there is code running to fulfil the function it has been designed for. Recommended best practices for securing connected devices in the IoT must include: a) Devices should protect themselves from attacks that impair its function or allow it to be used for unintended purposes without authorization. b) Devices should protect the private authentication credentials and key material from disclosure to unauthorized parties. c) Devices should protect the information received, transmitted, or stored locally on the device, from inappropriate disclosure to unauthorized parties. d) Devices should protect themselves from being used as a vector to attack other devices or hosts on the Internet. In order to help achieve the recommended security best practices, physical security, the ability to trust the integrity of the code, and the ability to be upgraded remotely are crucial to the design of all systems and IoT devices.
IoT Devices Make Decisions
An important aspect of an IoT system is its ability to make decisions. Triggering an alarm if carbon dioxide levels cross a threshold or unlocking a door upon detection of the correct key fob are two examples of decisions that could be made by IoT devices. Some IoT devices are also capable of more complex decision making such as identifying a person's face from a camera feed. The ability to make decisions can be added to some IoT devices via software. Programs must be written and uploaded to the IoT device for execution before the device can make any decisions.
Operating System (OS)
An operating system (OS) is the program that allows users to interact with computers. Modern operating systems include graphical interfaces to facilitate user interaction. Examples of OSs are Windows, Linux, OS X, Apple iOS and Android.
REST API
Any API that uses Representational State Transfer (REST), which means that the two programs, on separate computers, use HTTP messages to request and transfer data. Representational State Transfer (REST), or RESTful web services, is a type of API designed to make it easier for programs to interact over the Internet. REST APIs use HTTP based calls between different applications to access and manipulate information stored within powerful databases. Web resources used to be identified exclusively by a URL. Today, Web resources encompass every entity or thing that can be named, identified, or addressed. Entities could be a day's step goal, temperature setting from your house, or heartrate from a pacemaker. Each resource now has a unique Uniform Resource Identifier (URI), typically beginning with a slash such as /heartrate. REST APIs use the HTTP protocol and either URLs or URIs to request web services. Such REST web-based requests trigger responses in well-defined web formats such as XML and JSON (JavaScript Object Notation). By using HTTP as a protocol, RESTful services can borrow HTTP's operations, including the HTTP verbs GET, POST, PUT, and DELETE. An example could be a pacemaker sending updates about your average heartrate to a medical database. The pacemaker can use a RESP API call in a specific format (HTTP PUT) to update the information in the database.
applications
Applications are programs created to help the user performing a specific task. Examples of applications are Microsoft Word, Mozilla Firefox and Calculator.
errors of undefined variables
Attempts to use a not defined variable (no assigned value), will result in an error, as shown in Figure
Blockly
Blockly is a visual programming language that lets users create programs by connecting blocks, that represent different logic language structures, rather than by writing the actual code. Blockly runs within a web browser and can translate the visually created program as JavaScript, PHP, or Python.
RaPi Micro SD
Bottom view of Pi with SD card
C
C, a compiled language, is great for creating complex and fast programs but its strict rules and syntax makes it more difficult to develop. Created in the early 70s, C has become one of the most widely used programming languages of all time. The Linux operating system is written in C.
components of PL-App
Cisco Prototyping Lab is a set of hardware and software components that enable students and instructors to learn about, to prototype, and to model various IoT, digitization and data analytics solutions. The hardware components are part of the Prototyping Lab Kit (PL-Kit). The PL-Kit is based on Open HW prototyping boards such as Raspberry Pi and Arduino and includes additional sensors, actuators, and electronic components. The PL-Kit can be used to build sophisticated prototypes of end to end IoT systems that can sense and actuate the real physical world, analyze and process the data at the fog layer, and connect to network and cloud systems. The primary software component of the Prototyping Lab is the Prototyping Lab App (PL-App). The PL-App is a software platform running on a Raspberry Pi that exposes a web interface based on a concept of notebooks. A notebook is an interactive web page where content is distributed in what are called cells. The first cell type is called Markdown and is a cell that contains standard objects such as text, images, videos, etc. The second cell type is called Code cell and is a cell with executable code of different programming languages (the default is Python). A notebook can be used as a lab where the explanatory text is placed with executable code and together create a scaffolded learning experience. The explanatory text guides the student through the learning experience, while hands on skills are acquired by modifying, examining and executing executable code. A notebook is also a great tool that can be used to prototype IoT systems, interconnect with existing cloud services using APIs, etc. In a notebook, application code can be split between multiple code cells, executing only the part of the code that is just being developed or troubleshot. Moreover, using markdown cells, documentation and explanatory text can be added between code cells to provide a clean, easy to understand Rapid Prototyping Interface.
Importing Modules into Your Python Code - Part 4
Common modules you will see in IoT , and in this course, include data processing modules (mathematical functions), self-test modules (battery level and memory test), security modules (hashes, encryption/decryption), and network server and client modules (Web, FTP, NTP, etc.). Figure shows different ways to use the import function.
compiled languages
Compiled languages rely on a compiler, another program, to turn the human-readable code into a binary executable code. Compiled code is stored in binary and can executed at any time without the need for re-compiling. Compiled code also runs faster because it is executed directly by the CPU, with no need for an interpreter. Because compiled language is executed by the CPU directly, the compiler and the binary compiled code it generates are platform-specific. Source code is the term used to refer to the compiled-language code before its compilation. In that stage, the code is human-readable and can be easily modified. If a programmer wants to make changes to a compiled program, he or she must apply the changes to the source code and re-compile it before execution. Examples of compiled languages are C and C++.
Java Script
JavaScript, an interpreted computer language, is designed for creating web applications. With JavaScript, a programmer can create web applications that can interact with users and other applications.
functions in Python
Functions are an important part of many programming languages. Functions allow for a block of code to be given a name and re-used as needed. The example below defines a function to add two numbers and print the result, as shown in Figure
FOR loops
FOR Loops - These are used to execute a specific set of instructions a specific number of times, based on an expression. The term loop comes from the fact that a set of instructions are executed repeatedly. While the syntax of FOR loops varies from language to language, the concept remains: a variable is defined to act as a counter and a maximum value for it. Every time the loop is executed, the counter variable is incremented. When the counter is equal to the defined maximum value, the loop is abandoned and the execution moves on to the next instruction.
PL-App connection to new device
Figure shows how to connect a new device using the PL-App Launcher Application.
firmware
Firmware are programs created to allow a computer to perform a specific task. Firmware is often found in small computers such as simple digital watches, modern appliances, and various subsystems found in modern cars (eg. Anti-skid Breaking System (ABS), and Airbags). Due to limited memory and other resource restrictions, IoT devices often rely on firmware for their operation. Firmware and OS functionality often overlap. In some instances, firmware can also act as an OS for simpler computers.
PL-App running multiple Pis
From a second PC, the user establishes network connections to the RaPi and operates it over these connections. Both GUI and text-only operation is supported. Figure shows an example of a classroom topology with the PL-App running on Raspberry Pis.
IF - THEN
IF - THEN: This logic structure allows the computer to make a decision based on the result of an expression. An example of an expression is myVar > 0. This expression is true if the value stored in the myVar variable is greater than zero. When the interpreter or compiler encounters an IF-THEN structure, it evaluates the provided expression. If the expression is false, the computer moves on to the next structure, ignoring the contents of the IF-THEN block. If the expression is true, the computer executes the associated action before moving on to the next instruction in the program.
Transportation IoT System
In a transportation example, data such as the number of trucks using a specific stretch of highway, the temperature of that section of pavement, and winter tire and gas prices, can be collected. Data processing can tell when to install winter tires on the trucks based on the days the roads are frozen.
Agricultural IoT System
In an agricultural example, IoT devices could be used to monitor soil and weather conditions. Sensors would collect data on soil humidity, temperature and acidity levels. Other sensors could collect data on the CO2 levels in the air, in addition to air temperature, barometric pressure, and humidity. All this data has little to no use until it gets processed. A computer program can be written to process the data and estimate the chances of rain based on air temperature, humidity, and barometric pressure variations. The data collected on the soil conditions can also be processed by software to help optimize the harvest process.
software API
In many instances, programs need to communicate with other programs, web sites, or devices. An application program interface (API) is a set of routines and software tools that facilitate communication between programs. Thanks to APIs, applications running across the networks can communicate between each other, share data, and ask for specific services from other applications, such as asking an external API whether the person on a picture is male or female. Different types of APIs are available, including operating system APIs, application APIs, and website APIs. When creating a file manager application, a software developer will take advantage of the operating system API to copy, move or delete a file. If the developer's application does not have the necessary code to perform those functions, it can simply ask the operating system to perform them through its exposed operating system API.
Home Gateway in Home Automation
In the Smart Home example, all devices connect to the Home Gateway. The Home Gateway acts as a concentrator for all devices, providing wired and wireless connectivity. It is also in the Home Gateway that a web-interface is created and hosted to allow users to control and monitor all of the connected devices. Figure shows a screenshot of the PT Home Gateway window.
Home Gateway of Packet Tracer
In the model, sensors monitor the environment and make sure values stay within a pre-defined threshold. If the monitored value passes the defined threshold, an action is taken. The smoke detector, a sensor monitoring CO2 levels in the house, has a pre-defined value of 0.4. If the measured level surpasses 0.4, the alarm goes off. The smoke detector has no user-controlled functionality, it simply responds to the environment. Network connections between the Home Gateway and other network devices are also represented. Notice how the Home Gateway connects to a cable modem which, in turn, connects to a splitter. The splitter breaks the signal coming from the ISP, sending cable TV signals to the TV and data to the cable modem. The cable modem and splitter pair is what provides Internet connectivity to the Home Gateway and consequently, to the entire home. Note: While PT 7.0 is powerful and flexible, different sensors and actuators may have different connections. PT 7.0 implements Ethernet wired and wireless connections but it does not implement all other possible connections.
interpreted languages
Interpreted languages rely on another program to parse and execute the code. This program is called the interpreter. The code stays in human-readable text and it is fed to an interpreter for execution. While interpreted languages make it easier for code maintenance and troubleshooting, execution is also slower than compiled languages. Examples of interpreted languages are Python, JavaScript and PHP.
Java
Java is a "write once, run anywhere" (WORA) compiled language. Despite the similar name, Java and JavaScript are unrelated. Java is designed to run on any platform without the need for recompilation. Java based applications require a JVM (Java Virtual Machine) platform installed on the computer. JVM is the environment where the Java-complied code is executed.
More IoT APIs
IoT applications can talk to each other using APIs, but they can also use APIs to talk to various cloud based services. Regardless of the type of API, the goal remains the same; to allow other programs to interact with one another. Details on how to use a specific API and what tasks are exposed are included in the API's documentation. The figure shows an example of an API documentation. Notice the tasks exposed by the API. All the listed tasks can be utilized by other programs. IoT devices may rely on a third system to process data or extend its connectivity. Cloud-hosted services are a common choice when designing an IoT system.
securing IoT locations
IoT devices are located in traditional locations such as data centers in the cloud and also in many non-traditional locations, such as light poles, parking lots, and people's bodies. Traditional locations can be protected by surveillance cameras, access control systems, biometric identification, and multiple authentication points. Securing IoT devices in non-traditional locations is more difficult. The devices should be manufactured to be resistant to tampering, and they should be placed so that they are not obvious and are very difficult to access. While one should do their best to protect these devices physically, a determined hacker can still gain access. Physical security, in most cases, is a good practice but not enough by itself.
REST APIs in the CLOUD
IoT systems that take advantage of cloud services often rely on RESTful services to communicate. As an example, consider a smart watch with weather capabilities, where an IoT device collects weather information for its current location and displays it to the user. This watch could be programmed to communicate with a web-based weather system though an exposed REST API URL (a web address). This type of URL and its parameters would be described on the API's documentation. The figure shows an example of a RESTful service URL. Similar to a web browser visiting a web page, the watch would contact the URL described in the weather system's API's documentation and request, using the HTTP GET verb, the weather for its current location (based on its GPS sensor). The weather system would respond, conforming to its own API, with JSON or XML formatted data containing the weather information for that location. The code running in the watch, also created according to the weather system's API, would in turn display the information to the user.
remote management of IoT
It is also critical that IoT devices are designed to be able to be remotely upgraded. The design should include functions to allow for remote management of the device and upgrades. The removal of any development-phase backdoors or hard-coded debug access accounts, and enforcing authorized access only must also be taken into account. The data should be encrypted while being received or transmitted to local and remote servers. Remote access to the servers or the remote endpoints should also be secured. This ensures that the data retains its integrity, because it is protected from unauthorized access and tampering. Encryption algorithms and secure transmission protocols are techniques commonly used to secure the software and data.
Artificial Pancreas with Raspberry Pi
Its small size and low resource requirements make the Raspberry Pi something like a Swiss army knife for IoT. This topic explores a few interesting projects that use the Raspberry Pi. Dana Lewis has lived with Type 1 Diabetes since she was 14. The pancreas of people with Type 1 Diabetes does not produce enough insulin to handle the sugar in their bloodstream. People like Dana must monitor and correct the insulin levels. Because the monitor she used had many shortcomings, Dana and her husband decided to use a Raspberry Pi to build an artificial pancreas, as shown in the figure.
understanding Linux
Linux is an operating system that was created in 1991. It was created, and is currently maintained, by a community of programmers. Linux is open source, fast, reliable and small. It requires very little hardware resources to run, and is highly customizable. Linux is part of several platforms and can be found anywhere from "wristwatches to supercomputers". Linux is also a very popular choice in IoT devices. Another important aspect of Linux is that it is designed to be on the network. Network operations and connections are simple in Linux, making it a good choice for network professionals and administrators. Any person can get the kernel's source code, inspect it, modify it and re-compile it at will. Companies and users are free to modify, repackage and run the software. They are able to redistribute the program with or without charges. A Linux distribution is the term used to describe different Linux packages created by different companies. Linux distributions (or distros) include the Linux kernel, plus a number of customized tools and software packages. While some of these will provide and charge for Linux support (geared towards Linux-based businesses), the majority of them also offer their distribution for free without support. Debian, Red Hat, Ubuntu, Slackware and Mint are just a few examples of Linux distributions. Raspbian is a Linux operating system distribution created specifically for the Raspberry Pi. Raspbian is a Debian Linux variation and therefore, maintains its Linux structure.
Lists in Python
Lists are a sequence of changeable Python objects. Lists can be created by putting different comma-separated values between square brackets. Figure shows examples of lists and how they can be updated.
bootable SD card
Modern computers can boot the system from external USB devices and SD cards. With the increase in popularity of larger and cheaper external cards, it is common to have entire operating systems installed in such cards. The Raspberry Pi 3 includes a micro SD Card slot (Figure 1) to be used as a storage device for the system. Before the Raspberry Pi 3 can be used, an operating system must be installed on micro SD card and then placed in the SD slot for booting. While there are a number of ways to install an operating system on a micro SD card, the most common (and arguably the fastest) is to use an image file. An image file is a single file containing an image of an entire filesystem. In that sense, the image file is an exact copy of everything that was in the filesystem and it can be used to re-create the filesystem on other media. Common image file formats are .iso and .img.
result expression in Python
The print statement prints the result of the expression it was given. It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple expressions and strings. Strings are printed without quotes, and a space is inserted between items, so you can format things nicely, as shown in Figure
Importing Modules into Your Python Code - Part 3
Notice that the interpreter does not execute the contents of fibo.py but it now knows where to find the fib() and fib2() functions. To use the module and its functions, simply call them by name, as shown in Figure
hacking IoT
One way a hacker can change the function of a device is by accessing the device, disabling its function, installing new software on the device, and restarting it. Another way to protect the device is to ensure that the code on the device (both firmware and application) is the original code that was created. This security measure can protect the device from attempts to change its function, even if the physical security has been breached. This is done by cryptographically "signing" the original code and ensuring that the device will not start if the code is not signed. This is the same approach used to assure the integrity and provenance of documents. There are several approaches emerging in the industry to cope with different angles of this problem such as Trusted Computing, Cisco Trust Anchor Technologies, and Cisco Secure Boot. As an example, for the IOS on a router, the Cisco Trust Anchor and Cisco Secure Boot check the signed code to help ensure that the code running on Cisco hardware platforms is authentic and unmodified, establishing a hardware-level root of trust and an immutable device identity for the system to build on.
PT SBC code
PT 7.0 also introduces a single board computer (SBC) and a microcontroller unit (MCU). A single board computer is a computer designed to fit all its components such as storage, memory and I/O inside a single board. A good example of an SBC is the Raspberry Pi. SBCs are common in IoT solutions because they are used to execute code and add intelligence to everyday devices. A PT SBC is a PT device created to simulate an SBC by providing code execution capabilities and a number of connections. Specifically, the PT SBC provides 2 USB ports and 10 digital I/O ports which can be used to connect IoT sensors and devices. PT SBC has a Python interpreter built in which allows native Python code to be written and executed right to the device. The Python interpreter can be accessed via PT SBC's Programming tab. Figure shows a screenshot of the PT SBC window and its Config Tab.
Packet Tracer 7 New Devices
Packet Tracer (PT) is not only a powerful tool for modeling, simulating and testing network environments, it can do the same for IoT solutions. PT 7.0 introduces support for a number of IoT devices and functionalities that make it possible to design and build complete IoT solutions. Among the IoT devices supported by PT 7.0, it is possible to highlight programmable models of sensors, actuators, microcontrollers, single board computers, and fog computing devices. This allows the design, configuration, programming, and troubleshooting of increasingly sophisticated models of IoT systems. Figure shows a screenshot of PT 7.0 and many of its supported devices.
parts of a program
People impart logic to computers through programs. Programs use expressions, functions, and logic structures. Expressions are combinations of variables, constants, and operators that produce a new value. Functions define a sequence of expressions that need to be applied to the arguments (x,y) to produce the returned value z. Using specific logic structures, a programmer can prepare a computer to make decisions. Examples of expressions, functions and the most common logic structures. Before writing any code the programmer needs to understand the problem and how this problem can be solved by breaking it down into a sequence of steps and decisions. It is common for programmers to create a first draft of a program in no specific language. These language-independent programs are focused on the logic rather than in the syntax and are often called Algorithms. A flowchart is a common way to represent an algorithm. Figure 4 shows an example of a flowchart. Writing a good algorithm to solve a problem is a fascinating task that some people consider a form of art.
Python interpreter
Python is an interpreted language; therefore, an interpreter is required to parse and execute Python code. The Python interpreter understands and executes Python code. The fact that Python code can be created in any text editor and that Python interpreters are available for many operating systems, allows Python developers to create and deploy Python programs in practically any operating system. Third party tools such as Py2exe and Pyinstaller can also be used to package the Python source code into an executable file, eliminating the need for the Python interpreter when running Python code. In Linux machines, the Python interpreter is usually installed in /usr/bin/python or /usr/bin/python3(depending on the available Python versions on the system). With the new Windows Python installer, Python is by default installed into the user's home directory. In older Windows machines, Python is often placed in C:\PythonXX (where XX is the version of Python). After the Python interpreter has been installed, it operates somewhat like the Linux shell. This means that when called with no arguments, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.
ranges in Python
Python supports many useful functions and datatypes. Some of the more important ones are as follows: Range() : The range() function generates a list of numbers usually used to iterate with for loops. Figure 1 shows examples of the range() function. range(stop)- number of integers (whole numbers) to generate, starting from zero. range([start], stop[, step] starting number of the sequence, generate numbers up to, but not including this number, difference between each number in the sequence.
Python interactive mode
Python's interactive mode implements the special variable "_" to hold the result of the last expression issued, as shown in Figure
Python
Python, another interpreted language, allows for simpler statements. Python is very easy to use, powerful, and versatile and has become the language of choice for many IoT developers. One of the main reasons for Python's popularity is the developer community; Python developers have created and made available many specific modules that can be imported into any program to immediately lend added functionality.
Importing Modules into Your Python Code
Quitting the Python interpreter and entering it again removes all definitions that were previously made; functions and variables will be lost in the process. Because of this, use a text editor when creating a longer or more complex program. When the program is ready, simply feed it to the interpreter for execution. Using a text editor in this way creates a type of program called a script. As the programs get longer and more complex, it may be necessary to break it into smaller programs for easier maintenance. With this approach, a programmer would create a main program which imports all the necessary smaller programs. These smaller programs are called modules. Even if a program is not long or complex, a programmer can still benefit from importing an existing module into his or her program. A programmer may choose to re-use a good function that was already written. Another common scenario is programmers importing modules written by someone else to add functionality to their code or to improve their program. Python has a large and very active community of developers who have written and shared modules for many tasks. Figure shows a piece of code that creates a Python module to calculate and print the Fibonacci series up to a number N.
Raspberry Pi 3B+ specifications
Raspberry Pi 3B+ specifications SoC: Broadcom BCM2837B0 quad-core A53 (ARMv8) 64-bit @ 1.4GHz GPU: Broadcom Videocore-IV RAM: 1GB LPDDR2 SDRAM Networking: Gigabit Ethernet (via USB channel), 2.4GHz and 5GHz 802.11b/g/n/ac Wi-Fi Bluetooth: Bluetooth 4.2, Bluetooth Low Energy (BLE) Storage: Micro-SD GPIO: 40-pin GPIO header, populated Ports: HDMI, 3.5mm analogue audio-video jack, 4x USB 2.0, Ethernet, Camera Serial Interface (CSI), Display Serial Interface (DSI) Dimensions: 82mm x 56mm x 19.5mm, 50g
Sets in Python
Sets are unordered collections of unique elements. Common uses include membership testing, removing duplicates from a sequence, and computing standard math operations on sets such as intersection, union, difference, and symmetric difference. Figure shows examples of sets
IF-THEN in Python
Similar to other languages, Python implements an IF-THEN structure. IF-THEN blocks can be used to allow the code to make decision based upon the result of an expression, as shown in the figure. The code performs a few tests and prints a message in accordance with the results of the test. Notice that Python also implements two sub-structures named ELSE and ELIF. ELSE allows the programmer to specify instructions to be executed if the expression is false. Short for ELSE IF, ELIF is used to perform a second test in case the first expression is false and another test is required. There can be zero or more ELIFs, and the ELSE part is optional.
strings in Python
Strings, defined as a sequence of characters, can also be handled by Interactive mode. Use the backslash character ("\") to escape characters. As an example, a string uses double quotes but also needs to use a double quote within the string. If the string is entered as follows: "I really "need" this.". Python will get confused and think that the first double quote within the string actually ends the string. If you place a backslash (\) before the double quotes inside the string as follows: "I really \"need\" this", the backslash (\) causes Python to escape or ignore the character that follows. Single quotes or double quotes can be used to wrap strings, as shown in Figure
FOR loops in Python
The FOR loop in Python iterates the items of any sequence (a list or a string), in the order that they appear in the sequence, as shown in the figure.
Pi GPIO Pinouts
The RaPi also includes a 40-pin header with GPIOs. GPIO pins, short for General Purpose Input/Output pins, are extremely useful when interacting with the physical world. Sensors, actuators, switches and devices can be connected to GPIOs and controlled by code running on the RaPi. Other RaPi ports include an audio out, an SD card slot, an Ethernet port, 4 USB ports, camera interface (CSI), display interface (DSI), and a micro USB (used for power) connector.
Raspberry Pi 3B+ ports
The Raspberry Pi (Pi) is an inexpensive, small computer. It has a number of USB ports that can be used to connect various devices including keyboards, mice, external drives and cameras. Because it is a full computer in a package the size of a credit card, the RaPi has become the choice for many IoT projects. The Pi3 shares the features of its Pi2 predecessor but adds: A 1.2Ghz 64-bit quad-core ARMv8 CPU 802.11n Wireless LAN Bluetooth 4.1 Bluetooth Low Energy (BLE)
WHILE loops in Python
The WHILE loop executes a block of code if the expression is true. The program below uses a WHILE loop to calculate and print an initial sub-sequence of the Fibonacci series, as shown in the figure. The third line contains a multiple assignment operator. The variables a and b get the new values of 0 and 1 in a single statement. The WHILE loop calculates the next term in the Fibonacci series while the condition b < 10 is true. As in C, Python assumes any non-zero integer value as true and zero as false. The test used in the figure is a simple comparison. Notice that the body of the loop is indented. Indentation is Python's way of grouping statements. At the interactive prompt, you have to type a tab or space(s) for each indented line. More complicated input for Python should be done with a text editor. When a compound statement is entered interactively, it must be followed by a blank line to indicate completion (because the parser cannot guess which line will be the last line). Note that each line within a basic block must be indented by the same amount.
Importing Modules into Your Python Code - Part 2
The code above was created in a text editor and saved as fibo.py. Now that the module is created and saved to the disk, it can be imported into any other Python program and fed to the interpreter via the import keyword, as shown in Figure
4Borg Pi Robot
The figure shows an affordable robot kit from the robotic masters over at PiBorg. It is both fun and educational. Learn more about the project at: https://www.raspberrypi.org/magpi/4borg-robot-review/ Another great example of automation using a Raspberry Pi takes place on a cucumber farm in Japan. They are using the camera as a sensor to do image processing and classification. Then the actuators select which cucumbers are ok and which are not. This process is saving the farmer eight to nine hours of manual work a day. Learn more about this project at: https://www.raspberrypi.org/blog/now-added-cucumbers/.
the Python interpreter
The interpreter receives and executes statements interactively. The interpreter acts as a simple calculator. You can type an expression on it and it will write the value. Expression syntax is straightforward. The operators +, -, * and / work just as they do in most other languages (for example, Pascal or C). Parentheses (()) can be used for grouping, as shown in Figure
Raspberry Pi connections
There are several ways to setup and use a Raspberry Pi. Physically connecting an HDMI screen, USB keyboard and mouse turns the RaPi into a general PC and allows a user to gain local physical access. Once a Raspberry Pi compatible operating system image has been downloaded to the micro SD card, the RaPi is ready for use. Traditionally the Raspberry Pi can be used as a full blown computer with a monitor, keyboard and mouse. These are the steps for using the Raspberry Pi as a computer with physical local access: Step 1. Install an operating system image on the micro SD card. Step 2. Place the card in the micro SD card slot of the RaPi. Step 3. Connect a USB keyboard. Step 4. Connect a monitor or TV using the HDMI port. Step 5. Power the device with a power adapter.
starting the Python interpreter
To start the interpreter, simply type python or python3 at the shell prompt. Some legacy systems are still running on an older version of Python 2, but many new systems are moving to use the new Python version 3. Python's version is printed on the first line when the interpreter is launcher (Figure 1). This course is built on Python 3 code and while it is pretty well backwards compatible with Python 2, some functions might have different behavior. When the Python interpreter is called with no arguments, and commands are entered via the keyboard, the interpreter is said to be in interactive mode. In this mode, the interpreter waits for commands. The primary prompt is represented by three greater-than signs (>>>). Continuation lines are represented by three dots (...). Continuation is the default secondary prompt. The >>> prompt indicates the interpreter is ready and waiting commands. Continuation lines are needed when entering multi-line code. Figure shows an IF-THEN block written in Python. Another way of using the interpreter is python -c command [arg] ... which executes the statement(s) in the command. Because Python statements often contain spaces or other characters that are particular to the shell, it is suggested to enclose the entire command between single quotes.
Python variables
Variables are labeled memory areas that are used to store runtime program data. To assign values to variables in Python, use the = (equal to) sign. No result is displayed before the next interactive prompt, as shown in Figure
WHILE loops
WHILE Loops - These are used to execute a specific set of instructions while an expression is true. Notice that often the instructions inside the loop will eventually make the expression evaluate as false.
Controlling the Arduino through the Pi
While the Raspberry Pi is a powerful and flexible computer, there are some tasks it does not handle well. This is due to the fact that the RaPi does not have analog pins. Sensors such as thermometers, light sensors, and air pressure sensors deliver analog signals. Because the RaPi does not ship with analog pins, some workarounds must be made. Another example relates to size; while the RaPi is quite small and has reduced power requirements, some projects may require even smaller controllers. For those situations, it may be better to work with an Arduino microcontroller. Arduinos are also small and consume very little power, but they include analog pins. This makes Arduinos perfect for working with analog sensors and devices. You can connect and control an Arduino directly from your PC. Because the RaPi is a full computer, it is also possible to use it to connect and control Arduinos. Whether you are using your PC or the Pi, it is necessary to install some specific software before the computer can interact with an Arduino. Another important point is that Arduinos often run code written in C. Some Arduinos support alternative firmware that can implement other languages such as Python, but this is not the norm. When the proper software is installed, use a USB cable to connect the Arduino to the RaPi. The software will facilitate the transfer of data between the RaPi and the Arduino, allowing a user to push code, execute programs, and receive data from the Arduino. In this setup, with the Arduino connected to the RaPi via USB, the Arduino can also act as a secondary controller, managing data received from the analog sensors and relaying this data for processing to the more powerful Raspberry Pi. This also allows for the creation of an Arduino setup environment, where code can be created in the RaPi and pushed to the Arduino for testing. When the user is satisfied and ready to deploy the Arduino on its own, the Arduino can be disconnected and installed in its intended location. The figure shows a picture of a Redboard Arduino connected to a Raspberry Pi 3 via USB cable.
options for Raspian image transfer
everal options are available for image transfer tools. The one used in this course is part of the PL-App Launcher. This is a customized image transfer tool that simplifies the deployment of images used in this course. PL-App Launcher also manages discovery and headless control of the network connected Raspberry Pi. Figure shows the steps to setup a new device. If a user is downloading an image without the specialized PL-App tool, the user would need to obtain the image file created by a manufacturer or maintainer, who makes it available for download. The user can then simply download it from the proper website. The Raspberry Pi Foundation provides an image of Raspbian, a variation of Debian Linux customized for the Raspberry Pi. This course uses a PL-App Image that is based on a modified version of Raspbian.