RASPBERRY Pi 4 USER GUIDE: The Ultimate Updated Guide to Master the New Raspberry Pi 3 and 4 and Set Up Innovative Projects 1697580890, 9781697580891

HURRAY, The Raspberry Pi 4 is Here!! And with it a New Version of Raspbian. We'll show you How to Set it Up!! The R

294 56 2MB

English Pages 131 [132] Year 2019

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

RASPBERRY Pi 4 USER GUIDE: The Ultimate Updated Guide to Master the New Raspberry Pi 3 and 4 and Set Up Innovative Projects
 1697580890, 9781697580891

Citation preview

RASPBERRY Pi 4 USER GUIDE The Ultimate Updated Guide to Master the New Raspberry Pi 3 & 4 and Set Up Innovative Projects

ENRIQUE

SANCHEZ

Copyright © 2019 Enrique Sanchez All rights reserved. It is not legal to reproduce, duplicate, or transmit any part of this document by either electronic means or in printed format. Recording of this publication is strictly prohibited Disclaimer The information in this book is based on personal experience and anecdotal evidence. Although the author has made every attempt to achieve an accuracy of the information gathered in this book, they make no representation or warranties concerning the accuracy or completeness of the contents of this book. Your circumstances may not be suited to some illustrations in this book. The author disclaims any liability arising directly or indirectly from the use of this book. Readers are encouraged to seek Medical. Accounting, legal, or professional help when required. This guide is for informational purposes only, and the author does not accept any responsibilities for any liabilities resulting from the use of this information. While every attempt has been made to verify the information provided here, the author cannot assume any responsibility for errors, inaccuracies or omission

TABLE OF CONTENTS INTRODUCTION How Raspberry Pi has evolved itself to become a top computer in the modern competitive world? CHAPTER ONE: Getting to know about the details of Raspberry Pi Competences of Raspberry Pi Raspberry Pi Structure Step by Step Instruction to Setup the Hardware Setup Guide Step by Step Instruction to setup Raspbian OS on Raspberry Pi 3 and 4 Setting up the computers Recommended Software for Smooth Experience CHAPTER TWO: The File System Navigation with CLI How to open a Terminal sudo - Super User Do Navigating the File Manager through CLI

File Management with CLI Task scheduler CHAPTER THREE: The shell and its features SHELL Shell types What is Shell Scripting? How to use Shell Scripting Backup Scripts Script Scheduler CHAPTER FOUR: Touch upon Python Programming Language How to get started on Raspbian Pi? Basic Concepts Variables and Types The syntax for declaring a variable in Python Concatenating variables String Formatting Dictionary in Python Common Methods of Dictionary Arithmetic, Logical, Comparison, Assignment, Bitwise & Precedence

Logical Operators Identity Operators Conditions & Loops Loop Functions Classes and Objects Inheritance through classes Constructors in Python CHAPTER FIVE: Sensors, Sense HAT and its features Introducing the Sense HAT How to install Sense HAT? CHAPTER SIX: Coding guidelines for TkInter Widgets Widgets Build a Graphical User Interface with Tkinter and Python CONCLUSION

INTRODUCTION Are you looking for a device that is fully functional at a meager cost? Then Raspberry Pi is the one who can fulfill all your requirements. Whether you want your device for playing games or programming or browsing the internet, it is the perfect choice for you. Raspberry has an exceptional community that is going to assist you in every step of the way. Moving on to the technical details of the computer, we find out that it is a single-board computer. You must be amazed to hear these words “A single-board computer” because how can a single chip be a whole computer. It comes with a single printed circuit board and works as a complete computer just like the other laptops, desktops, etc. The best element about this is that it is small of a size of credit card and immensely powerful. Readers must

be wondering how such a small system can be so strong that it can perform anything that a powerhungry computer can do. It is so because this computer came into being from a wish to enhance hands-on computer education across the globe. The inventors of this computer joined together and formed a Raspberry Pi Foundation didn’t know that they have got such a powerful thing in their hand from which they can bring a revolution to the world. In 2012 few Raspberry Pi systems were sold instantaneously while the demand for millions came through at the same time. From 2012 till now millions of computers have been shipped all across the globe. These boards can now be seen in homes, offices, data centers, and industries. There are numerous models of Raspberry Pi that have come into the market since the introduction of the original one, every time a new Raspberry Pi computer is released; there is some kind of improvement in specs. Raspberry Pi introduced Zero family that is a lighter version of Raspberry Pi full version and lacks a few features such as numerous USB ports and wired

network port. Moreover, the layout is also small and has low power needs. Raspberry Pi has been extremely successful because they are highly compatible computers. It means that the software written for one model will run on any other model. The software compatibility is so high that you can take the latest version of the Raspberry Pi‘s operating system and you can run it with the latest Model B prototype. The updated software might face a few issues such as it might affect the speed of the computer, but it will still run. This book is going to highlight the features of Raspberry Pi 3 and 4 models, but these features are quite similar to the upcoming and the latest computers in the market and these concepts could be easily applied to all other computers. How Raspberry Pi has evolved itself to become a top computer in the modern competitive world? Raspberry Pi has a history that goes back to 2012 when the applications to Computer Science course offered in the University of Cambridge has reduced to just a few hundred. At that time, the director of Studies named

Eben Upton thought as an alarming sign. In order to raise the interest of people in computer science, he came up with a single-board computer to inspire the young generation. Eben didn’t know that this would inspire the world so much that he would be able to build a computing empire.

In 2012 the first computer was launched, and since that moment the company has been able to sell around 27 million computers. In order to inspire youth in the field of computing, the Raspberry Pi Foundation has already spent around £78 million for this mission. The updated model Raspberry Pi 4 Model B is available in the market for £34. Raspberry Pi 4 is an entirely new platform as it completely transformed from the old, less powerful processors that are utilized in all the older versions. Following are the functions of Raspberry Pi

- 4GB RAM - Dual HDMI - USB - Supports 4K video Although Raspberry Pi was initially developed for educational purposes, the strength of this single chipped computer has made itself a compulsory for industrial use. The evolution of Raspberry Pi has proved the fact that it is still getting better. Despite being such a powerful computer, it hasn’t stopped and continues to bring in updated elements. It is the reason due to which Raspberry Pi has been able to do so well in the market and is continuously improving.

CHAPTER ONE: Getting to know about the details of Raspberry Pi Raspberry Pi 3 Model B is the upgraded version of the traditional Raspberry Pi computer. This machine is very different from your traditional computer as the cheapest of the version doesn’t have the case and comes in the size of a credit card. Competences of Raspberry Pi Raspberry Pi is a powerful computer that provides you everything in one chip. The facts shared above are clear proof that this computer its capabilities has made it an integral part of every industry. Whether it is a budget desktop, media center, retro games console, or an industry, Raspberry Pi is a part of every sector. Thousands of Pi are currently in use, and hundreds of them are being used to build laptops, phones, and other technological gadgets. It is essential to know the fact that Pi itself is just aboard and the one who will setup needs to give it a power

supply,

monitor,

and

other

necessary

equipment to make it useful. The first step towards setting up your Pi is to ensure that you have set up the hardware. Connect the following equipment after which you can move forward to the software side. - Connect the Pi to the power cable - Connect to the monitor or TV using an HDMI or VGA (HDMI is preferable) - Connect mouse and keyboard for smooth communication Once you are done with all the hardware essentials, it’s time to move forward to the software. Download the NOOBS (New Out-Of-Box Software) and execute the setup. The wizard will take you along through different steps to install the Operating System on Pi. The installer provides you the option of installing different Operating System of your choice. The preferable OS for beginners is Raspbian, but the installer provides you different options of OS. Talking about the Raspbian OS, you can see that the look and feel of the system are quite similar to other desktop computers. It is continuously upgraded in its

abilities as well as in its layout. With the updated version, you can get an enhanced web browser, an office suite, programming tools, educational games, and other software. Raspberry Pi Structure PIN GROUP

PIN NAME

DESCRIPT ION

POWER

+5V, +3.3V, GND +5V -power

SOURCE

and Vin

output +3.3V

-

power output GND



GROUND pin COMMUNICA

UART

UART

TION

Interface(RXD,

(Universal

INTERFACE

TXD) [(GPIO15,G

Asynchrono

PIO14)]

us Receiver

Transmitter) utilized

for

providing an interface for the

sensors

and additional tools. SPI

SPI

(Serial

Interface(MOSI,

Peripheral

MISO, CLK,CE) x Interface) 2

required for

[SPI0-(GPIO10 ,GPIO9,

GPIO11

collaboratin g

with

additional

,GPIO8)]

boards [SPI1--(GPIO20 ,GPIO19, ,GPIO7)]

GPIO21

or

peripheral devices such as Keyboard and mouse

TWI

TWI

Interface(SDA,

Wire

SCL) 2

(Two

x Interface) [(GPIO2, Interface

is

required

to

GPIO3)] [(ID_SD,ID_SC)]

attach peripheral devices.

INPUTOUTPUT PINS

26 I/O

Despite the fact

that

these

pins

have

got

numerous features, they marked Input

are as /

Output (I/O) pins.

PWM

Hardware

PWM The

available GPIO12,

4

on channels are GPIO13, given

GPIO18, GPIO19

the

task

to

provide PWM (Pulse Width Modulation) outputs. *Software PWM available on all pins EXTERNAL INTERRUPTS

All I/O

All the I/O pins

are

required for dealing Interrupts

Raspberry Pi Technical Specifications Microprocessor

Broadcom BCM2837 64bit Quad Core Processor

Processor

3.3V

Operating Voltage Raw Voltage input

5V, 2A power source

Maximum current 16mA through each I/O pin Maximum

total 54mA

current

drawn

from all I/O pins Flash

Memory 16Gbytes SSD memory card

(Operating System) Internal RAM

1Gbytes DDR2

Clock Frequency

1.2GHz

GPU

Dual Core Video Core IV® Multimedia

Co-Processor.

Provides Open GLES 2.0, hardware-accelerated Open VG, and 1080p30 H.264 high- profile decode. Capable

of

1Gpixel/s,

1.5Gtexel/s or 24GFLOPs with texture filtering and DMA infrastructure. Ethernet

10/100 Ethernet

Wireless

BCM43143 (802.11 b/g/n

Connectivity

Wireless

LAN

Bluetooth 4.1) Operating Temperature

-40ºC to +85ºC

and

Board Connectors Specifications for Raspberry Pi Name

Description

Ethernet

Base T Ethernet Socket

USB

2.0 (Four sockets)

Audio

3.5mm Jack and HDMI

Output Video

HDMI

output Camera

15-pin

MIPI

Camera

Serial

Connector

Interface (CSI-2)

Display

Display Serial Interface (DSI) 15-

Connector

way flat flex cable connector with two data lanes and a clock lane.

Memory

Push/Pull Micro SDIO

Card Slot

A comparison between Raspberry Pi 3 and 4 regarding their technical specifications.

Spec

Raspberry Pi 4 B

Raspberry Pi 3 B+

1.5-GHz,

CPU

Quad-Core

1.4-GHz, Quad Core

Broadcom

Broadcom

BCM2711B0 BCM2837B0 (Cortex (Cortex

A- A-53)

72)

RAM

1

-

DDR4

4GB

1GB DDR2

500 GPU

MHz

VideoCore VI

Video Out

Max resolution

USB Ports

dual

micro

HDMI ports

400 MHz VideoCore IV

single HDMI port

4K 60 Hz + 1080p or 2x 2560 x 1600 4K 30 Hz 2x USB 3.0 / 2x USB 2.0

Wired

Gigabit

Networking

Ethernet

4x USB 2.0

330 Mbps Ethernet

802.11ac (2.4 Wireless

/

5

GHz), 802.11ac

Bluetooth 5.0

(2.4

/

GHz), Bluetooth 4.1

5

Charging Port Power Requirement

USB Type-C micro USB

3A, 5V

2.5A, 5V

3.5 x 2.3 x Size

0.76

inches 3.2 x 2.2 x 0.76 inches

(88 x 58 x (82 x 56 x 19.5mm) 19.5mm)

Weight

0.1

pounds 0.11

(46 grams)

grams)

pounds

(50

Step by Step Instruction to Setup the Hardware Once you have got your Raspberry Pi in your hand, you need to take it out from the box. It is recommended to hold the board from the edges instead from the flat sides. Although these pieces of hardware are quite robust, still you need to be very careful with it. It is important to be extra careful regarding the metal pins because if they are damaged or bent then it might cause short circuit which may damage the board.

Setup Guide Now let’s move on the steps to set up the system for you. You need to read the instructions carefully and move ahead properly so that everything is set up correctly. If you have got the official case, then start by splitting it into five pieces. The five pieces will include the following things - Red Base - 2 white - Sides - Red upper - White lid

1. Once you have ensured that you have got everything, use the base and hold it in such a way that the raised end is on the left side while the other on the right.

2. Now pick up the Raspberry Pi with the help of the USB and the Ethernet ports, but make sure that the GPIO header is on the top and the slot is on the left side. Once the position is according to the image shown now lower down the right side in the case so that it sits down in the case. 3. Now grab the two white sides and locate the one that provides the cut-outs for the power source, HDMI port, and 3.5 mm AV jack. Arrange it

accordingly with the ports on the Raspberry Pi and push it into the case gently. Once you hear a click sound, you are sure of the fact that it will fit in.

4. Use the solid white part and insert into the GPIO header part of the case 5. Now use the red plastic upper piece and inset the clips on the left on to the matching holes that are available on the left-hand side of the case. This position is right above the microSD slot. Once the left side is in its proper position, it’s time to push the right side (right above the USB ports) down until you hear a click.

6. Most of your system is set up, and now you will be moving on the final steps. Grab the white lid in such a way that the Raspberry Pi logo is to your right, and the minor raised clips on its bottom are creased up with the hole on the top of the case. Now push the board into the case until you hear a click.

Now your case is ready to be used for software setup which we will discuss next. Before you move on to the software, make sure that you have attached power supply, a monitor through the HDMI, a keyboard, mouse, and a microSD card to it.

Step by Step Instruction to setup Raspbian OS on Raspberry Pi 3 and 4

Once the hardware is set up, you need to move forward with the software setup so that you can use the system for whatever purposes you desire. This section is going to provide you a step by step instruction that will help you set up the software on your Raspberry Pi. The operating system is the main software that is required to be installed before you start working on your Raspberry Pi. In this book we will be installing NOOBS, the New Out-Of-Box Software that is

specially designed to ensure that you get an exceptional experience. The setup will allow you to install from different options automatically. At the initial startup, when the computer is booted it will show a plain screen with a Raspberry Pi logo on it and a minor window at the upper left corner of the screen. After waiting for a while, you will be shown the following screen as shown below

The above image shows you the NOBOS menu, which is a system that allows you to select from a list of the operating system that you wish to install on your system. Initially, only two operating systems are

available for installation. The first one is the “Raspbian, a version of the Debian Linux operating system” that has been specially personalized for Raspberry Pi computers. The other one is the LibreELEC

which

was

introduced

by

Kodi

Entertainment Centre software. To start off, you need to ensure that Pi is connected to the network; it could be connected through a wire or a WiFi network. You can connect the computer from the top bar of icons available on the interface. The interface also allows you the option of downloading and installing other operating systems. Now click the option with the left click, and you are good to go. Once you are done with this step you will see “Install (i)” menu icon that will be enabled this time. The enabling of this button tells you that the operating system is ready to be installed on your machine. Once the button is enabled, click it to begin the installation, before moving ahead, it will warn you that any data stored in the microSD will be overwritten excluding NOBOS. To proceed the installation you click “Yes” and the installation process will begin. This process can take

up to 30-40 minutes depending upon the space and the speed of your microSD card. As the operating system is being installed you will see a progress bar on the screen that will tell the status of installation. As the installation progress, you will also see the list of features under the progress bar that is being installed. All the details of these features will be discussed below.

WARNING There are a few things that need to be kept in mind while installing the Operating System on the computer. It is significant to ensure the fact that the installation is not interrupted as there is a high chance of the software getting corrupt. Moreover, also ensure that you do not remove microSD or unplug the power cable during the installation as this may corrupt the operating system. If something like this happens, you need to unplug the pi from the power supply and then press the SHIFT key on the keyboard during this time you can connect back the Pi to the power supply. This

will bring the OBOS menu back on the restart. This step is known as the recovery mode, and it provides you an easy way to restore your computer in case of any mishap. It also gives you the option of entering into NOBOs menu after successful installation you can reinstall the OS, and you can even install any other OS you want. Setting up the computers Once the installation is done, a popup window will appear that will indicate that the installation is complete. After successful installation, the computer will restart, and you will see lots of messages on the command prompt as the first time it starts, it takes a few minutes to adjust itself. Once everything is

done, and the OS is sure that the user can use the system, the following popup will show up letting you know that you are good to go. Now click next to proceed where you will be asked to set up Country, Language, and Time zone for the system.

One everything is filled hit Next to proceed to set up your password.

After you have set up your password, you need to set up a connection to the internet. You can do this by connecting your computer your Wi-Fi network available in the given list. Just click the network you wish to connect and provide the password for the network to proceed.

After adding a network connection to your computer hit next where you will be asked to ensure that the Raspberry Pi regularly checks for updates. These updates are introduced to fix bugs and bring new features and enhance performance capacities. If the window shows updates, then you need to be patient as updates might take a bit of time.

After installing the updates, the OS will ask you to reboot the system so that it can apply all the changes that you have made. Just hit the Reboot button and set aside to let the system reboot. Recommended Software for Smooth Experience The operating system comes along with some of the basic features that allow you to operate the computer with ease. Some of this software include - Chromium Browser: It is a browser that will enable you to access different sites on the internet. It is a built-in tool for the Raspbian OS. If you have used chrome on any other machine,

then you will be good to go as it is no different from it. - The File Manager The operating system also accompanies a file manager that provides you the ability to manage your files on your brand new Raspberry Pi. All your files are saved in your home directory by default. File manager allows the opportunity to browse the files and folders that are also regarded as directories. These files are located on your Micro SD card installed on your system. Your Raspberry Pi also allows you to attach removable storage media such as USB flash drives. Here are some directories that are created by default which help to arrange your documents according to their categories. - Desktop - Documents - Downloads - Music - Pictures - Public - Videos

You will have a similar experience just as you have in Windows with these default folders on the left and all your files arranged on the right. Moreover, you can also copy all the files from the Raspberry Pi to your microSD attached to the computer. You can do this simply by copy-paste technique just as you do in Windows or any other Operating system. - The LibreOffice The amazing LibreOffice is another product that comes along with the Operating system. It is a collection of software that allows you to do specific tasks such as you can use the LibreOffice Word to type documents, manage or update them. Other software that is part of this suite are listed as follows:  LibreOffice Base: It is a database tool for analyzing,

arranging,

and

storing

information.  LibreOffice Calc: It is spreadsheet software that

provides

users

the

ability

to

manipulate with number and represent them through graphs.



LibreOffice Draw: It is an illustration software that enables you to enhance your creative skills.



LibreOffice Impress: It is a software that is designed to allow you to create slide shows.

 LibreOffice Math: It is a formula editor that provides formatted mathematical tools which could be easily used in other places. Despite the fact that Raspian comes along with numerous preloaded software, there is various other software which is compatible with it even more. As a user of Raspbian, you can pick and choose software available from the list. Raspian is compatible with various software, and this software is hand-picked by the Raspberry Pi Foundation. This software is also available in the list of Recommended Software tool. It is important to note that to

install

this

recommended software, you will need a connection to the internet. Check the list of recommended software and click on the raspberry menu icon and go to

Preferences and then hit the option “Recommended Software.” It will take a bit of time and will provide you a list of available software.

CHAPTER TWO: The File System Navigation with CLI Raspian is the official operating system of Raspberry Pi. It is a modified version of Debian that has specifically been crafted for Raspberry Pi, and that is the reason it is known as the official Operating System. Raspbian is an operating system that is loved by most of the users because it gives a similar user experience as Windows. As most of the people using Raspberry Pi come from a background of windows operating system, they do not feel a lot of difference in user experience allowing them the facility to adapt quickly to the new OS. The best element of Raspbian is that it has a very powerful command-line interface that provides you excellent control over the computer. While operating from GUI, you cannot get that strong control over the GUI. Moreover with the command-line interface, a lot of the tasks become easier and quicker. There are a few tasks that are only possible through the command-line interface.

However, like all forms of Linux, Raspbian has a powerful command-line interface that gives you a lot more control over the computer than you can get using the GUI. And many important tasks are either easier or only possible via commands. That's why, below we've listed the most important commands for navigating the file system, installing software, editing files and monitoring performance. How to open a Terminal To perform different tasks through the command-line interface, you need to open the Terminal from Windows GUI or via CLI. To open through GUI, just hit the Terminal icon on the desktop. The icon looks like a tiny monitor or if you wish to open through command then hit CTRL+ ALT + T. Once you do so a black screen will appear on your computer. On the terminal you will see a command as follows: [email protected]:~ $ This command tells us that the user is logged in to the computer as pi and the machine name is raspberry pi. The $ sign in the command highlights the permission

you have. You can edit any file, folder or directory on the computer. The home directory allows you to store files and even allow you to modify them. But you cannot touch any of the data in the file system as you are not permitted to do so. To change these files, you need the user named “root,” which is said to be the owner. This user has the same permission as an administrator in Windows. If you cannot switch to that user, you can go for the sudo option that provides you extra abilities. Below you will find some of the commands that could be used to learn more about Raspberry Pi and its processes. sudo - Super User Do As stated above you have to use the sudo command to get admin privileges. Through this command, you can perform some core jobs, such as installing the software. This command could be used with other commands as well. For critical tasks in which admin rights are essential it is recommended to use this command along as it gives you additional privileges.

To use “sudo,” it is important to be under the “subdoers” permission group, but the best element is that you do not have to do anything extra to be a part of it as Raspberry Pi user is already a member of this group. Navigating the File Manager through CLI Transferring files from one place to another is something that we don’t bother about a lot. The terminal allows us to do everything with enormous speed and perfection. Here are some of the commands that could be used to perform different actions on a particular file or directory. - pwd The above command tells you the complete directory path in which you are working right now.

- Is This command lists down all the files and folders inside a particular directory.

- Cd Changes the current directory to the one specified, e.g., cd Documents. - Cat It will print the contents of the file on the terminal window. E.g., cat HelloWorld.py. It will print all the content in the file on to the terminal. - Less This command helps to print the contents of the file in different sections that can be accessed through different up and down keys. - Grep This command helps to look into the file to search for a specific word. File Management with CLI Following are some of the basic commands that help you to move, delete, and copy files from different directories. All this could be easily done from the terminal.

- mv - Move / rename a file If you wish to move or rename file use the command written above. E.g., mv test.py Documents/ - rm - Delete a file This command removes the file from the respective directory. e.g., rm test.py - cp - Copy a file To copy a file from one directory to another, you can use the command-line interface to do so. E.g., cp test.py Documents/

mkdir - Create a directory This command allows you to create a new directory for a better arrangement of files and folders. You can use it like “mkdir Directory Name” to create a directory. Task scheduler Task scheduling is one of the essential parts of the Operating system. In this modern era you cannot dedicate a resource to do repetitive tasks; thus, task

scheduling is done programmatically. In raspberry Pi you can use Cron tool for scheduling your tasks. These tasks run periodically after a set of time interval. Task can be simple such as backing up the user’s folders every night or complex such as logging CPU information after every 60 minutes. You can use cron GUI to schedule the tasks. It can be done by installing the gnome-schedule package. sudo apt-get install gnome-schedule Use the above command in the terminal to install the GUI. In order to edit the task that has been scheduled, you need to execute crontab with the flag. This command is used to edit the cron table. crontab -e The very first time you run the crontab, you are asked to opt for an editor. If you are reluctant in going for a new editor then opt for. Just open the start menu, find Nano and hit enter.

As a beginner user of Raspberry Pi, it is essential to know how the layout of cron works. It is made of six components that include the following: - Minute - Hour - Day of month - Month of year - Day of week - Command - # m h dom mon dow command - # * * * * * command to execute - #┬┬┬┬┬ - #│││││ - #│││││ - # │ │ │ │ └───── day of the week (0 - 7) (0 to 6 are Sunday to Saturday, or use names; 7 is Sunday, the same as 0) - # │ │ │ └────────── month (1 - 12) - # │ │ └─────────────── day of the month (1 - 31)

- # │ └──────────────────── hour (0 23) - # └───────────────────────── min (0 - 59) This task will be executed every day at midnight. If you wish to see your scheduled tasks, then use the following command to view them. crontab -l If you wish to assign a task that runs on Reboot, then you need to modify the command a little bit. Just add the @reboot instead of the time and the date. This command will be scheduled every time your computer is rebooted. @reboot python /home/pi/myscript.py

If you wish to make your command run in the background, then you need to opt for the following script.

@reboot python /home/pi/myscript.py &

CHAPTER THREE: The shell and its features SHELL It is an integral part of the Operating system. The following diagram explains the concept of Shell. In Linux, a shell is the source of input in the form of commands which are processed and then it returns an output. In simple terms we can say that it is an interface in which the user works on the program, commands, and scripts. Shell is normally accessed through the terminal.

Hardware

Kernel

Operatin g System

Shell

Termin al

User

Whenever you run a terminal, the shell issues a command prompt (mostly known as $). On the

command prompt type your input and hit enter to execute the command. The output or the result is normally visible on the terminal. Shell types There are two main types of Shells available in Linux 1. The Bourne Shell This shell uses $ as it’s prompt and possess the following derivatives. - POSIX shell is also called as sh - Korn Shell has another name as sh - Bourne Again Shell is normally known as bash. It is one of the most popular shells available in Linux. 2. The C shell It is the second type of shell that uses % as prompt. There are some subtypes of shell available which are listed as follows. - The c shell is given the name csh - Tops C shell is called as tcsh

What is Shell Scripting? Shell scripting is a term that is referred to a series of command for the shell to implement. It consists of long and monotonous structures of commands in a single script. These scripts can be stored and executed at any time. It is done to reduce human efforts that are required by the user. How to use Shell Scripting Following is the procedure that tells you how to use Shell Scripting on your raspberry pi. 1. First of all, create a new file with the help of your editor. Users mostly prefer vi editors for such jobs. 2. Save the file with .sh extension 3. Start the script with the help of the command “#! /bin/sh” 4. Write the respective code 5. To

implement

yourfilename.sh

the

script

write

bash

The picture below shows how the script is created

The picture below shows how the Is command is added after the #/bin/sh

The picture below shows how the script file executes.

Shell Variables Variables s a term that is referred to terminology that stores data in the form of integer, character. These variables are used to store data in shell, and they are accessible in shell only. #!/bin/sh echo "Hey! May I know your name?" read name

echo "Hope you are doing well, $name?" read remark echo "I am $remark too!"

Using shell scripting is one of the best features of Raspberry Pi. The example above is just a simple script that shows how to use variables. As you advance further, you can also use loops, functions, and classes to make your life easier as a Linux administrator. Backup Scripts Backup scripts are the scripts that are used to back up important files and folders. The recommended tool to create backups is rysnc command-line tool. Following is a command that will create a full backup of your program. [email protected]:~

$

Rsync -

a /nas/data/ /nas/backup/2019-09-26 According to this command, a folder will be created on the mounted drive, and the backup will be kept inside it. The command also has a flag that starts Rsync in archive mode. In this mode, all the Metadata is stored

along with it, such as the modification date, the initial owners, etc. Since the first backup has been created now the coming backups will be the incremental backups that could be created through the following command. [email protected]:~

$

Rsync -a --link-

dest /nas/backup/2018-0801/ /nas/data/ /nas/backup/2019-09-27 Once the backup scripts are finalized, just follow the instructions mentioned below in the script scheduler to schedule the script. Script Scheduler In this section, you will get to know the procedure that you need to go through to schedule a python script. Before moving on to anything else, you need to ensure that you have downloaded the latest version of Python. Just hit to python.org to get the most recent release and install it on your system. If your system already has it, then you are good to go. Here are the steps that you need to follow to schedule a script on your system.

- Log in your system - Go to terminal - Now enter “crontab -e.” Please ensure if you need system admin privileges to run this command, then use word sudo along with it. - Once the above step is done, you will be asked to select an editor. You can choose any editor with which

you

are

comfortable,

but

the

recommended one is NANO. - You can use the up and down arrows to manipulate through the screen - You will have to opt among the Minutes, hours, day of month and weekday command. To skip these add * to the command as input.

CHAPTER FOUR: Touch upon Python Programming Language

Python is a programming language that can be used to perform different task programmatically. Raspbian allows users to use Python on their systems quite effectively. How to get started on Raspbian Pi? Now since we are done with the OS and all other things we can now move on to getting started with Python. After the first reboot, you can kick start programming. To do so, you need to have an IDE where you can code. IDE is a complicated name for the text editor that provides you extra capabilities such as debugging, executing programs. The preferred IDE for Python programming is known as the Thonny IDE. The following picture shows how you can open the IDE and get started with programming

Once the IDE is open, you are ready to get started. Just type the following commands and you are done with your first program on your Raspberry Pi.

The above picture shows you the output of the programming command. Basic Concepts Variables and Types The readers who have a basic concept of objectoriented

programming

know

about

variables.

Variables are not precise to a certain language as they are a concept that needs to be understood so that they could be applied in different situations. A python variable resides in memory reserved for storing values which are retrievable upon the requirement for computer processing.

Every variable you define is of a particular type. For instance, you come across circumstances where you want to store characters, and then the variable is of string type. To define a variable, you are supposed to give them a particular name so that whenever you are accessing the memory location, later on, you can access it through that name. The syntax for declaring a variable in Python There is a proper syntax that you are supposed to follow to declare the variable and use it. Here we will develop an example which provides you an idea about the concept of variables. a=100 print a So, the output on the console will be 100. In this, you have declared a variable with value 100, and you have printed it. Now if later on, you face a situation where you want to transform the declaration and give the same variable another value, then you need to do as follows. # Declare a variable and initialize it

f=0 print (f) # re-declaring the variable works f = 'guru99' print (f)

Concatenating variables Concatenation in programming refers to a term where you join string along. It is usually used to ensure that the string you display is dynamic. Let’s assume a problem that asks you to show the number of products left behind products to the user, and every time the quantity is different. In such scenarios where the value is dynamic, you use string concatenation.

In python, we can concatenate different data types such as string and number together. In the following, we will be concatenating a string value and a numerical value together. The example below clearly shows the difference between Java and Python as it doesn’t allow you to concatenate it until the variable b is declared as a string as well. In case you use number for it then you might have to face a type error which is illustrated in the picture below. a="This is a string." b = 99 print a+b

The code given above is error-prone as the variable “A” has a data type string while the data type of variable” B” is number. The following picture displays the error that you will receive.

The succeeding code will display the correct output. It is so because while printing you are converting the variable b to string. It means you can print concatenate similar datatype variables in python. It makes Python a strongly typed language for software development. a="Guru" b = 99 print(a+str(b))

Local and Global Variables A global variable is a variable that is declared once and used throughout the program. Whereas local variable defined within that particular method, and outside that code block, you cannot access that variable. The subsequent description is a code snippet that describes the concept of a global variable.

The variable “f” in the example given above is global as it is manageable all over the program. This variable is assigned a value of 101, printed in the output. Variable “f” declared again in the function, and that is the local scope. Inside the function, the variable f declared again in the function and assumed as the local scope. The code snippet written above has a function where the variable is assigned the value “I am learning python,” The output screen also shows the same string. This local variable is dissimilar to the global variable “f” that was defined earlier. Once the function is complete, the variable get destroyed. As you go through line 12 the output of the function would be as follows:

It is crucial to know that the global variable can be retrieved anywhere throughout the program. A global

variable can be read inside the function a well. The

picture below shows how the global variable is overwritten inside a function. The code snippet available in the picture above is also given below for better understanding. f = 101; print f # Global vs.local variables in functions def theFunction(): global f print f f = "changing global variable" theFunction() print f Del command is available to delete the variable. The below illustration proclaims a variable and then deletes it. When the program tries to print it again after deleting it, the compiler gives an error.

String Formatting In python, everything is an object, and whenever you declare a string in python, it is an object too. To declare a string variable, you can follow the syntax written below name =” This is the name” Python is a language that does not support the character type. These strings are preserved as the size of one as they are considered one substring. String slicing is also a concept that is commonly used in python. It could be done with the help of square brackets for along with the respective index of the string and get the right string. The example written

below shows how string slicing could be performed in python. var1 = "Guru99!" var2 = "Software Testing" print ("var1[0]:",var1[0]) print ("var2[1:5]:",var2[1:5])

We are now moving on to the basic string operations that apply to a string. The following table shows the operator the description and a small example and its output to show how the operators actually work.

Operato

Description

r []

[:]

Exampl

Output

e Provides you

x="This

the character

is the na Name[2],

from that

me"

particular

print x[1

index

]

It refers to the

x="This

orange slice.

is the na Name[1:2]

Where you can me"

If you access Output “i.”

If you access The output of

get a string

print x[1 “hi.”

within a

:3]

defined range In

It is used to

x=Time" It will return

check if the

print "m true

given

" in x

character exists in the string. Not in

Returns true if x="Gur

L

is

not

the given letter u"

present in the

is not present print "l" list. Thus the in the string

not in x

result will be true.

r/R

Raw

string Print

suppresses the r'\n' real

Prints \n Prints \n

meaning prints

of the string

\n

and

print R'/n' prints \n %

It inserts the name = ' The result will canonical

This is a be This is a

string picture string' of the object. It number will format the = 99 string that will print'%s display

the %d' % (

string and the name,n number together with

umber)

string 99

formatted string. +

Concatenation x="Pyth

The result will

. It will join on"

be Python100

both strings

the y="100" into print x+

one. *

y

Repeat.

The x="Pyth

PythonPytho

string

will on"

n

print

the y="99"

character

print x*

twice.

2

Here is another slicing example where you can assign the variable to another string. The code below illustrates how the variable replaces with the help of one of the string functions. x = "Hello World!" print(x[:6]) print(x[0:6] + "this is an example")

It is important to note that in the above example: 6 means the range 0:6.

String replace is another string function that replaces the string with the given characters. The following example shows another example where you can see the string replaced with the given value. Python provides you the option of manipulating the string according to your requirement. Here are some of the common operations that perform on the string. Following are some of the examples of operations performed on a string.

string="python" print(string.upper()) Output: “PYTHON” string="python" print(string.capitalize()) Output: PYTHON string="PYTHON." print(string.lower()) Output: “python.” Following

are

some

other

common

examples

commonly used while programming in Python. print(":".join("Python")) Joins the string and the yield will be “Python:” string="12345" print(''.join(reversed(string))) This function will reverse the string, and the yield will be “54321”. word="This is python example."

print(word.split(' ')) This function splits the string by spaces. Dictionary in Python Every programming language implements a few data structures that are essential to solving critical problems. Python’s utilization of data structures can be seen through the use of dictionaries. Dictionary is a data structure that stores values and accessed with the aid of keys. It is also known as the key-value pair data structure that could be used to store values. It is imperative to understand that the - Keys are a spare element - Values can contain anything some prominent examples include a list, string, or a number. To declare a dictionary, you need to follow the syntax mentioned below Dict = { ' Tim': 18, XYZ,.. } As the syntax suggests, a dictionary lists in curly brackets where key and values separated by a colon. As we move ahead, it is essential to comprehend the following important aspects.

- Keys in the dictionary are case sensitive, which means that same key with the varying case identified as a unique key. - The data stored in the dictionary could be of any type, but it is vital to ensure that the key value s always immutable such as numbers, string, etc. - Keys should be unique in a dictionary. Common Methods of Dictionary Data structures are used to resolve common programming problems. Thus they come with some conventional methods that help programmers solve complex problems. - Copy Dictionary This function helps to copy the entire dictionary to a new dictionary. The following code snippet shows an example of this function. Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} studentX=Boys.copy() studentY=Girls.copy() print studentX

print studentY

- Update You can also find a function that helps to update the contents of the dictionary. It can add new contents and even update the existing ones. The example below illustrates where a new key-value pair combined in the dictionary. Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Dict.update({"Sarah":9}) print(Dict) - Delete As we add new items to the dictionary, we need to remove some of them as well. To delete an element from the dictionary, we use the “del” command. Here is the code that shows how you can remove an element from an existing dictionary.

Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} del Dict ['Charlie'] print(Dict) - Items While using dictionaries, we face numerous situations where we need to go through all the items of the dictionary. The code snippet below highlights a situation where the program needs to check whether a provided element is obtainable in the list or not. Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} for key in Dict.keys(): if key in Boys.keys(): print True else: print False - Sorting Whenever you have a collection of items, you need some basic functionalities along among which sorting

is the most imperative feature. Python provides sorting for its programmers. The example illustrates the above concept. Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} Students = list(Dict.keys()) Students.sort() for S in Students: print(":".join((S,str(Dict[S])))) - Length In order to find the exact number of elements in a dictionary len function is available. Following is a code that could be used for understanding the concept better. Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print "Length : %d" % len (Dict) - Print the dictionary elements To print the dictionary in the readable form, you need to make a dictionary into a string format. The code

below illustrates the concept. You can use the following code to understand the concept. Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25} print "printable string:%s" % str (Dict)

- Comparison between elements Dictionary also provides you the option to compare items. A method with name “CMP” used for this purpose. Here is an example that will help the reader to have a better understanding of the concept. Boys = {'Tim': 18,'Charlie':12,'Robert':25} Girls = {'Tiffany':22} print cmp(Girls, Boys)

Arithmetic, Logical, Comparison, Assignment, Bitwise & Precedence Operators play a critical role in every programming language. They are used to handle individual items and returns the desired result. The data on which these operations performed is called the operands or

arguments. Most of the operators epitomized by special characters such as “is” and “is not” are two operators commonly used in string manipulation. Following are the typical arithmetic operator that is essential while programming in Python. All the examples below come along with a relevant case to explain the concept better. - Arithmetic Operators All the simple arithmetic operations accomplished with the assistance of arithmetic operators in python. You can find the common operators as follows - Addition - Subtraction - Multiplication - Division - Modulus - Exponent x= 4 y= 5 print(x + y)

- Comparison of Operations These operators are used to equate values on either side of the operand and trace the relation between them. These operators are also known as relational operators. Some of the most common operators are ( ==, != , , >,y)) In the above instance, the result will be true or false as it will match both the values and return the necessary value if the condition met. - Assignment Operations Assignment operators are the operations used for assigning values to variables. The common assignment operators accessible in Python include (+=, - = , *=, /= , etc.). With Python, we can use compound assignment operators as well.

n1 = 4 n2 = 5 print(("Line 1 - Value of num1 : ", n1)) print(("Line 2 - Value of num2 : ", n2)) The example is shown below illustrates the compound assignment operators. n1 = 4 n2 = 5 res = n1 + n2 print(("Line 1 - Result of num1+num2 is ", res)) res += num1 print(("Line 1 - Result of res += num1 is ", res)) The example shows two variables initializes with values and then adding them into a third variable. In the fourth line, the result further adds to the number 1 value, and the result is displayed.

Logical Operators Logical operators in Python used for the conditional statement in which the program has to evaluate the condition based on the situation. Three major logical operators in programming are known as - AND: returns true if both conditions return true. - OR: returns true when even one condition fulfills - NOT: returns true if the condition not met a = True b = False print(('a and b is',a and b)) print(('a or b is',a or b))

print(('not a is',not a)) The above code has the following output, which shows how these logical operators work.

- Membership Operators They are used for a structure such as a list, string, or tuples. The two main membership operators that could be utilized in Python are known as the “in” and “not in.” In the following example, the program is checking whether the given value is accessible in the list or not with the assistance of operators known as membership operators.

V1 = 4 V2 = 8 list = [1, 2, 3, 4, 5 ]; if ( V1 in the list ): print("Line 1 – V1 is available in the given list") else: print("Line 1 – V1 is not available in the given list") if ( y not in the list ): print("Line 2 – V2 is not available in the given list") else: print("Line 2 – V2 is available in the given list")

Identity Operators Identity operators are one of the most useful items of Python as they allow the users to compare the memory location of two objects. Following are the two operators used in Python: - The operator is: This operator will return true if both the variables are directing towards the identical object. - The operator is not: It is going to return false if two variables point the same object.

Operators (In falling Meaning directive of priority) **

Exponent

*, /, //, %

Multiplication,

Division,

Floor division, Modulus +, -

Addition, Subtraction

>=

Comparison operators

= %= /= //= -= += *= Assignment Operators **= is is not

Identity operators

in not in

Membership operators

not or and

Logical operators

x = 20 y = 20 if ( x is y ): print("x & y SAME identity") y=30 if ( x is not y ): print("x & y have DIFFERENT identity")

- Operator Precedence Operator precedence is a concept in which tells which operator evaluated first. If you want to become a handful programmer, it is significant to know about operator precedence as it helps to avoid ambiguity. The above table demonstrates all the operators available with their decreasing order of priority. Conditions & Loops Conditional statements are a major part of every programming language. These statements help the program to act according to the given situation. The

condition evaluated inside a conditional statement returns true or false upon which further action takes place. Conditional statements are known as “if statements” in programming terms. The code below shows a conditional statement in Python. def main(): a,b =2,8 if(a < b): str= "a is less than b" print(str) if __name__ == "__main__": main() In the above code, the program is comparing two integers a and b. whenever the value of x is less than y the if statement will execute the very next statement. If the condition does not returns true you will receive an error message stating that the “str” is not defined.

s To overcome this error, you can write an else statement which will be executed every time if the condition doesn’t return true. Following is the code was written to show you the solution to the problem mentioned above.

There are a few situations when the “else statement” does not give the desired result. The picture above illustrates a scenario where if you give x and y the same value, then it will print “X is greater than Y.” If we look at it logically, then we find out that the result is wrong as both the values are the same. In this scenario we can add another if statement to get the desired result as shown below def main(): x,y =8,8 if(x < y):

st= "x is less than y" elif (x == y): st= "x is same as y" else: st="x is greater than y" print(st) if __name__ == "__main__": main()

Nested If Statements: When you want to have nested conditions, the preferable solution is to go for nested if statements. Python allows programs to utilize nested if statements to get the desired results. The syntax is the same as a simple if statement. The case below illustrates shows how nested if statement could be used. total = 100 #country = "US"

country = "AU" if country == "US": if total