Iot Regular.pdf

  • Uploaded by: Raj Singh
  • 0
  • 0
  • August 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Iot Regular.pdf as PDF for free.

More details

  • Words: 20,037
  • Pages: 162
www.techienest.in

1

[email protected]

TABLE OF CONTENTS

PAGE NO.

INTRODUCTION___________________________________________________________________________

01

IoT Today__________________________________________________________________________________

06

0.2 IoT as Network to Networks_________________________________________________________________

07

0.3 Why is IoT important?_____________________________________________________________________

08

0.4 Evolution of the Web Versus the Internet_______________________________________________________

08

0.5 IoT: First Evolution of the Internet____________________________________________________________

09

0.6 We Evolve Because We Communicate_________________________________________________________

09

0.7 Categories of IoT_________________________________________________________________________

10

0.8 Overview_______________________________________________________________________________

11

UNIT 1 PYTHON PROGRAMMING 1.1Introduction_______________________________________________________________________________

16

1.2 Installation and Documentation_______________________________________________________________

16

1.3 Versions of Python_________________________________________________________________________

16

1.4 Differences between Python 2.7.x and 3.x_______________________________________________________

17

1.5 WHAT IS COMMAND AND SCRIPT WINDOW?______________________________________________

18

1.5.1 Command Window:______________________________________________________________________

18

1.5.2 Script Window:_________________ ________________________________________________________

20

1.6 How statements works without semicolon (;) in Python?___________________________________________

24

1.7 VARIABLE TYPES_______________________________________________________________________

25

1.7.1Assigning Values to Variables______________________________________________________________

25

1.7.2 Multiple Assignment_____________________________________________________________________

25

1.7.3 Standard Data Types_____________________________________________________________________

26

1.7.4 Python Strings__________________________________________________________________________

27

www.techienest.in

2

[email protected]

1.7.5 Python Lists______________________________________________________________________________ 28 1.7.6 Python Tuples_____________________________________________________________________________ 29 1.7.7 Python Dictionary__________________________________________________________________________ 30 1.7.8 Data type Conversion_______________________________________________________________________ 32 1.8 BASIC OPERATOR____________________________________________________________________

33

1.8.1 Types of operators______________________________________________________________________

33

1.8.1.1Python Arithmetic Operators____________________________________________________________

33

1.8.1.2Python Comparison Operators__________________________________________________________

34

1.8.1.3Python Assignment Operators___________________________________________________________

35

1.8.1.4Python Bitwise Operators_____________________________________________________________

36

1.8.1.5Python Logical Operators_____________________________________________________________

38

1.8.1.6 Python Membership Operators_________________________________________________________

38

1.8.2 Python Operators Precedence____________________________________________________________

40

1.9 Decision Making________________________________________________________________________

42

1.10 LOOPS______________________________________________________________________________

47

1.10.1 While Loop________________________________________________________________________

48

1.10.2 For Loop___________________________________________________________________________

51

1.10.3 Nested Loops_______________________________________________________________________

53

1.11 LOOP CONTROL STATEMENT_________________________________________________________

54

1.11.1 Break Statement_____________________________________________________________________

55

1.11.2 Continue Statement__________________________________________________________________

56

1.11.3 Pass statement______________________________________________________________________

57

1.12 Functions____________________________________________________________________________

60

1.13 Brief Introduction of Standard Library_____________________________________________________

65

UNIT 2 COMPUTING 2.1 Raspberry_Pi____________________________________________________________________________ 97 2.2 Specifications___________________________________________________________________________ 97 2.3 Operating System for Raspberry_Pi___________________________________________________________98 2.4 History________________________________________________________________________________98

www.techienest.in

3

[email protected]

2.5 Steps to Installation and use Raspberry_Pi_________________________________________________

99

2.6 Connecting to Raspberry_Pi______________________________________________________________

100

2.7 Various ways to connect Raspberry_Pi___________________________________________________

110

2.8 Display Touch Screen_______________________________________________________________

115

2.9 Serial communication_________________________________________________________________

120

2.10 XRDP (Remote Desktop)_________________________________________________________________

125

2.11 Configuring Wi-Fi(Wireless Fidelity)____________________________________________________

125

2.12 1-Wire GPIO____________________________________________________________________________ 126 UNIT 3 INTERFACING INTERFACING WITH RPi3 3.1 BLINKING LED__________________________________________________________________________ 135 3.1.1 Introduction___________________________________________________________________________ 135 3.2 BUZZER____________________________________________________________________________ __ 140 3.2.1 Introduction___________________________________________________________________________ 140 3.3 SENSORS______________________________________________________________________________ 141 3.3.1 IR Sensor_____________________________________________________________________________ 141 3.3.2 Ultrasonic Sensor_______________________________________________________________________ 142 3.3.2.1 Introduction__________________________________________________________________________ 143 3.4 LCD (Liquid Crystal Display)______________________________________________________________

143

3.4.1 Introduction___________________________________________________________________________ 145 3.4.2 Interfacing with Alphanumeric LCD________________________________________________________ 145 3.4.3 LCD Display as User Input_______________________________________________________________ 146 3.4.4 LCD Display as User____________________________________________________________________ 153 3.5 MOTORS______________________________________________________________________________ 153 3.5.1 Introduction___________________________________________________________________________ 155 3.6 RF ID_________________________________________________________________________________

155

3.6.1 Introduction___________________________________________________________________________ 156 3.6.2 RFID’s History:___________________________________________________________________ 3.6.3 RFID tags classification_____________________________________________________________

www.techienest.in

4

156 158 [email protected]

www.techienest.in

5

[email protected]

UNIT 0

INTRODUCTION Kevin Ashton is accredited for using the term “Internet of things” for the first time during presentation in 1999 on supply chain management. He believes that “things” aspect of the way we interact and live within the physical world that surrounds us needs serious reconsideration, due to computing, Internet, and data-generation rate smart devices. The Internet of Things (IoT), sometimes referred to as the Internet of Objects, will change everythingincluding ourselves. This may seem like a bold statement, but consider the impact the Internet already has had on education, communication, business, science, government, and humanity. Clearly, the Internet is one of the most important and powerful creations in all of human history. Now consider that IoT represents the next evolution of the Internet, taking a huge leap in its ability to gather, analyze, and distribute data that we can turn into information, knowledge, and, ultimately, wisdom. In this context, IoT becomes immensely important. Already, IoT projects are under way that promise to close the gap between poor and rich, improve distribution of the world’s resources to those who need them most, and help us understand our planet so we can be more proactive and less reactive. Even so, several barriers exist that threaten to slow IoT development, including the transition to IPv6, having a common set of standards, and developing energy sources for millions—even billions—of minute sensors. However, as businesses, governments, standards bodies, and academia work together to solve these challenges, IoT will continue to progress. The goal of this course, therefore, is to educate you in plain and simple terms so you can be well versed in IoT and understand its potential to change everything we know to be true today.

0.1 IoT Today As with many new concepts, IoT’s roots can be traced back to the Massachusetts Institute of Technology (MIT), from work at the Auto-ID Center. Founded in 1999, this group was working in the field of networked radio frequency identification (RFID) and emerging sensing technologies. The labs consisted of seven research universities located across four continents. These institutions were chosen by the Auto-ID Center to design the architecture for IoT. Before we talk about the current state of IoT, it is important to agree on a definition. According to the Cisco Internet Business Solutions Group (IBSG), IoT is simply the point in time when more “things or objects” were connected to the Internet than people. In 2003, there were approximately 6.3 billion people living on the planet and 500 million devices www.techienest.in

6

[email protected]

connected to the Internet. By dividing the number of connected devices by the world population,

we find that there was less than one (0.08) device for every person. Based on Cisco IBSG’s definition, IoT didn’t yet existing 2003because the number of connected things was relatively small given that ubiquitous devices such as smartphones were just being introduced. For example, Steve Jobs, Apple’s CEO, didn’t unveil the iPhone until January 9, 2007 at the Macworld conference. Explosive growth of smartphones and tablet PCs brought the number of devices connected to the Internet to 12.5 billion in 2010, while the world’s human population increased to 6.8 billion, making the number of connected devices per person more than 1 (1.84 to be exact) for the first time in history. Refining these numbers further, Cisco IBSG estimates IoT was “born” sometime between 2008 and 2009 (see Figure 1). Today, IoT is well under way, as initiatives such as Cisco’s Planetary Skin, smart grid, and intelligent vehicles continue to progress.

0.2 IoT as Network to Networks Currently, IoT is made up of a loose collection of disparate, purpose-built networks. Today’s cars, for example, have multiple networks to control engine function, safety features, communications systems, and so on. Commercial and residential buildings also have various control systems for heating, venting, and air conditioning (HVAC); telephone service; security; and lighting. As IoT evolves, these networks, and many others, will be connected with added security, analytics, and management capabilities (see Figure). This will allow IoT to become even more powerful in what it can help people achieve.

www.techienest.in

7

[email protected]

Figure: IoT can be Viewed as Network of Networks Interestingly, this situation mirrors what the technology industry experienced in the early days of networking. In the late 1980s and early 1990s, Cisco, for example, established itself by bringing disparate networks together with multi-protocol routing, eventually leading to IP as the common networking standard. With IoT, history is repeating itself, albeit on a much grander scale.

0.3 Why is IoT important? Before we can begin to see the importance of IoT, it is first necessary to understand the differences between the Internet and the World Wide Web (or web)—terms that are often used interchangeably. The Internet is the physical layer or network made up of switches, routers, and other equipment. Its primary function is to transport information from one point to another quickly, reliably, and securely. The web, on the other hand, is an application layer that operates on top of the Internet. Its primary role is to provide an interface that makes the information flowing across the Internet usable.

0.4 Evolution of the Web versus the Internet The web has gone through several distinct evolutionary stages: Stage 1: First was the research phase, when the web was called the Advanced Research Projects Agency Network (ARPANET). During this time, the web was primarily used by academia for research purposes. Stage 2: The second phase of the web can be coined “brochureware.” Characterized by the domain name “gold rush,” this stage focused on the need for almost every company to share information on the Internet so that people could learn about products and services. Stage 3: The third evolution moved the web from static data to transactional information, where products and services could be bought and sold, and services could be delivered. During this phase, companies like eBay and Amazon.com exploded on the scene. This phase also will be infamously remembered as the “dot-com” boom and bust. Stage 4: The fourth stage, where we are now, is the “social” or “experience” web, where companies like Facebook, Twitter, and Groupon have become immensely popular and profitable (a notable distinction from the third stage of the web) by allowing people to communicate, connect, and share information (text, photos, and video) about themselves with friends, family, and colleagues. www.techienest.in

8

[email protected]

0.5 IoT: First Evolution of the Internet By comparison, the Internet has been on a steady path of development and improvement, but arguably hasn’t changed much. It essentially does the same thing that it was designed to do during the ARPANET era. For example, in the early days, there were several communication protocols, including AppleTalk, Token Ring, and IP. Today, the Internet is largely standardized on IP. In this context, IoT becomes immensely important because it is the first real evolution of the Internet—a leap that will lead to revolutionary applications that have the potential to dramatically improve the way people live, learn, work, and entertain themselves. Already, IoT has made the Internet sensory (temperature, pressure, vibration, light, moisture, stress), allowing us to become more proactive and less reactive. In addition, the Internet is expanding into places that until now have been unreachable. Patients are ingesting Internet devices into their own bodies to help doctors diagnose and determine the causes of certain diseases. Extremely small sensors can be placed on plants, animals, and geologic features, and connected to the Internet. At the other end of the spectrum, the Internet is going into space through Cisco’s Internet Routing in Space (IRIS) program.

0.6 We Evolve Because We Communicate Humans evolve because they communicate. Once fire was discovered and shared, for example, it didn’t need to be rediscovered, only communicated. A more modern-day example is the discovery of the helix structure of DNA, molecules that carry genetic information from one generation to another. After the article was published in a scientific paper by James Watson and Francis Crick in April 1953, the disciplines of medicine and genetics were able to build on this information to take giant leaps forward. This principle of sharing information and building on discoveries can best be understood by examining how humans process data (see Figure). From bottom to top, the pyramid layers include data, information, knowledge, and wisdom. Data is the raw material that is processed into information. Individual data by itself is not very useful, but volumes of it can identify trends and patterns. This and other sources of information come together to form knowledge. In the simplest sense, knowledge is information of which someone is aware. Wisdom is then born from knowledge plus experience. While knowledge changes over time, wisdom is timeless, and it all begins with the acquisition of data.

www.techienest.in

9

[email protected]

Figure: Humans turn data into wisdom It is also important to note there is a direct correlation between the input (data) and output (wisdom). The more data that is created, the more knowledge and wisdom people can obtain. IoT dramatically increases the amount of data available for us to process. This, coupled with the Internet’s ability to communicate this data, will enable people to advance even further.

0.7 Categories of IoT IoT is an umbrella term that includes multiple different categories: 

Wireless sensor/actuator networks



Internet-connected wearables



Low power embedded systems



RFID enabled tracking



Use of mobile phones to interact with the real world (e.g. sensing)



Devices that connect via Bluetooth-enabled mobile phones to the Internet



Smart homes



Connected cars, and many more

The result is that no single architecture will suit all these areas and the requirements each area brings. However, a modular scalable architecture that supports adding or subtracting capabilities, as well as supporting many requirements across a wide variety of these use cases is inherently useful and valuable. It provides a starting point for architects looking to create IoT solutions as well as a strong basis for further development. This paper proposes such a reference architecture. The reference architecture must cover multiple aspects including the cloud or server-side architecture that allows us to monitor, manage, interact with and process the data from the IoT devices; the networking model to communicate with the devices; and the agents and code on the devices themselves, as well as the requirements on what sort of device can support this reference architecture.

0.8 Overview The Internet of Things, or IoT, refers to the set of devices and systems that interconnect real-world sensors and actuators to the Internet. This includes many different systems, including 

Internet connected cars

 Wearable devices including health and fitness monitoring devices watches, and even human implanted devices 

Smart meters and smart objects

www.techienest.in

10

[email protected]



Home automation systems and lighting control



Smartphones that are increasingly being used to measure the world around them



Wireless sensor networks that

measure weather, flood defenses, tides and more.

The growth of the number and variety of devices that are collecting data is incredibly rapid. A study by Cisco1estimates that the number of Internet-connected devices overtook the human population in 2010, and that there will be 50 billion Internet-connected devices by 2020. There are of course two key aspects to the IoT- the devices themselves and the server-side architecture that supports them. In fact there is often a third-category as well; in many cases there may be a low power gateway that performs aggregation, event processing, bridging, etc. that might sit between the device and the wider Internet. In both cases, the devices probably have intermittent connections based on factors such as GPRS connectivity, battery discharging, radio interference, or simply being switched off. There are effectively three classes of devices: The smallest devices have embedded 8-bit System-OnChip (SOC) controllers. A good example of this is the open source hardware platform Arduino: e.g the Arduino Uno platform and other 8-bit Arduinos. These typically have no operating system. The next level up are the systems based on Atheros and ARM chips that have a very limited 32-bit architecture. These often include small home routers and derivatives of those devices. Commonly, these run a cut-down or embedded Linux platform, such as OpenWRT, or dedicated embedded operating systems. In some cases they may not use an OS, e.g. the Arduino Zero, or the Arduino Yun.

The most capable IoT platforms are full 32-bit or 64-bit computing platforms. These systems, such as the Raspberry Pi or the BeagleBone, may run a full Linux OS or another suitable Operating System, such as Android. In many cases these are either mobile phones or based on mobile-phone technology. These devices may also act as gateways or bridges for smaller devices, e.g. if a wearable connects via Bluetooth Low Energy to a mobile phone or Raspberry Pi, which then bridges that onto the wider Internet. The communication between devices and the Internet or to a gateway includes many different models:  Direct Ethernet or Wi-Fi connectivity using TCP or UDP (we will look at protocols for this later) 

Bluetooth Low Energy



Near Field Communication (NFC)



Zigbee or other mesh radio networks



SRF and point-to-point radio links



UART or serial lines

www.techienest.in

11

[email protected]



SPI or I2C wired buses

This section has provided a short overview of IoT devices and systems. It is not designed to be comprehensive or even extensive, but simply to provide enough background to support the discussion of requirements and capabilities below. There are many further resources available, which are too numerous to list.

www.techienest.in

12

[email protected]

www.techienest.in

13

[email protected]

UNIT 1 PYTHON PROGRAMMING 1.1 Introduction Python is a powerful modern computer programming language. It bears some similarities to Fortran, one of the earliest programming languages, but it is much more powerful than Fortran. Python allows you to use variables without declaring them (1.e., it determines types implicitly), and it relies on indentation as a control structure. You are not forced to define classes in Python (unlike Java) but you are free to do so when convenient. Python was developed by Guido van Rossum, and it is free software. Free as in “free beer,” in that you can obtain Python without spending any money. But Python is also free in other important ways, for example you are free to copy it as many times as you like, and free to study the source code, and make changes to it. There is a worldwide movement behind the idea of free software, initiated in 1983 by Richard Stallman. This document focuses on learning Python for the purpose of doing mathematical calculations. We assume the reader has some knowledge of basic mathematics, but we try not to assume any previous exposure to computer programming, although some such exposure would certainly be helpful. Python is a good choice for mathematical calculations, since we can write code quickly, test it easily, and its syntax is similar to the way mathematical ideas are expressed in the mathematical literature. By learning Python you will also be learning a major tool used by many web developers.

1.2 Installation and Documentation If you use Mac OS X or Linux, then Python should already be installed on your computer by default. If not, you can download the latest version by visiting the Python home page, at http://www.python.org Where you will also find loads of documentation and other useful information. Windows users can also download Python at this website. Don’t forget this website; it is your first point of reference for all things Python. You will find there, for example, reference, the excellent Python Tutorial by Guido van Rossum. You may find it useful to read along in the Tutorial as a supplement to this document.

1.3 Versions of Python There are two types of versions available in Python. 1) 2.7.x 2) 3.x Many beginning Python users are wondering with which version of Python they should start. My answer to this question is usually something along the lines “just go with the version your favorite tutorial was written in, and check out the differences later on.” But what if you are starting a new project and have the choice to pick? I would say there is currently no “right” or “wrong” as long as both Python 2.7.x and Python 3.x support the libraries that you are planning to use. However, it is worthwhile to have a look at the major differences between those two www.techienest.in

14

[email protected]

most popular versions of Python to avoid common pitfalls when writing the code for either one of them, or if you are planning to port your project.

1.4 Differences between Python 2.7.x and 3.x Following the 2008 release of Python 3.0, Python 2.7 was published on July 3, 2010 and planned as the last of the 2.x releases. The intention behind Python 2.7 was to make it easier for Python 2.x users to port features over to Python 3 by providing some measure of compatibility between the two. This compatibility support included enhanced modules for version 2.7 like unittest to support test automation, arg parse for parsing command-line options, and more convenient classes in collections. Because of Python 2.7’s unique position as a version in between the earlier iterations of Python 2 and Python 3.0, it has persisted as a very popular choice for programmers due to its compatibility with many robust libraries. When we talk about Python 2 today, we are typically referring to the Python 2.7 release as that is the most frequently used version. Python 2.7, however, is considered to be a legacy language and its continued development, which today mostly consists of bug fixes, will cease completely in 2020. Python 3 is regarded as the future of Python and is the version of the language that is currently in development. A major overhaul, Python 3 was released in late 2008 to address and amend intrinsic design flaws of previous versions of the language. The focus of Python 3 development was to clean up the code base and remove redundancy, making it clear that there was only one way to perform a given task. Major modifications to Python 3.0 included changing the print statement into a built-in function, improve the way integers are divided, and providing more Unicode support. At first, Python 3 was slowly adopted due to the language not being backwards compatible with Python 2, requiring people to make a decision as to which version of the language to use. Additionally, many package libraries were only available for Python 2, but as the development team behind Python 3 has reiterated that there is an end of life for Python 2 support, more libraries have been ported to Python 3. The increased adoption of Python 3 can be shown by the number of Python packages that now provide Python 3 support, which at the time of writing includes 339 of the 360 most popular Python packages. The biggest difference between Python 3 and Python 2 is not a syntactical one, but the fact that Python 2.7 will lose continued support in 2020 and Python 3 will continue to be developed with more features and more bug fixes. Recent developments have included formatted string literals, simpler customization of class creation, and a cleaner syntactical way to handle matrix multiplication. Continued development of Python 3 means that developers can rely on having issues fixed in a timely manner, and programs can be more effective with increased functionality being built in over time. As someone starting Python as a new programmer, or an experienced programmer new to the Python language, you will want to consider what you are hoping to achieve in learning the language. www.techienest.in

15

[email protected]

If you are hoping just to learn without a set project in mind, you will likely most want to take into account that Python 3 will continue to be supported and developed, while Python 2.7 will not. If, however, you are planning to join an existing project, you will likely most want to see what version of Python the team is using, how a different version may interact with the legacy codebase, if the packages the project uses are supported in a different version, and what the implementation details of the project are. If you are beginning a project that you have in mind, it would be worthwhile to investigate what packages are available to use and with which version of Python they are compatible. As noted above, though earlier versions of Python 3 had less compatibility with libraries built for versions of Python 2, many have ported over to Python 3 or are committed to doing so in the next four years.

1.5 What is Command & Script Window? 1.5.1 Command Window: Command window is used for Basic mathematical operations and calculator functions and in that IDLE we can directly write our programs but indentation must be follow otherwise it will show as error you can perform any operations in it but in command it isn’t possible to accessing the library functions and modules we can write it in Script window let’s check how it’s working

Figure: Environment of the Command Window.

www.techienest.in

16

[email protected]

Figure: Basic Arithmetic Functions in command window In this Figure, we are taking variables to assign the values after assigning the values we can perform any operations in it.

Figure: Updating variable values in the command window. In this Figure, you can check like the variable values are being updated and if you were given any value to the assigned variable then the memory of value will be updated every time.

www.techienest.in

17

[email protected]

Figure: Indentation Error

1.5.2 Script Window: In script window we can write the libraries and functions in it and also we can perform any operation but make sure that you program should be follows the indentation block.

Figure: Shell Window

www.techienest.in

18

[email protected]

Figure: Script Window How to Open Script Window? Shell window>File >Ctrl+N

Figure: First python program

www.techienest.in

19

[email protected]

How to save my First python program? Ctrl+s>enter file name>save

After saving the file it will look like this.

www.techienest.in

20

[email protected]

How to Run My First Python Program?

File >Ctrl+O>Location of the file > file name.py >Open

After open of the file it will shows the file location and file name like this Run > Run Module or F5

www.techienest.in

21

[email protected]

Figure: Your First Python Program Displayed in Shell Mode

1.6 How statements works without semicolon (;) in Python? Semicolon (;): In computer programming, the semicolon is often used to separate multiple statements (for example, in Perl, Pascal, PL/I, and SQL; see Pascal: Semicolons as statement separators). In other languages, semicolons are called terminators and are required after every statement (such as in Java, and the C family). While coming to python programming semicolon are sometimes used and sometimes not why? Cause in python programming we are writing number of variable’s result in single line we can use it at the end of the line but if we use it in middle of the line it ‘will run the program of before semicolon and after semicolon it will terminate. So it is the reason we are not using semicolon in python programming. Let’s check >>print “Hi”,”welcome”,”2”,”Python” >>Hi welcome 2 Python >>print “Hi”,”welcome”;”Boys/Girls” >>Hi welcome >>print “hi”,”welcome”,”Boys/Girls”; >>hi welcome Boys/Girls

//Without Semicolon in the middle of the line

//Here After the Semicolon line is terminated //Here Semicolon is used at the end of the line

1.7 Variable Types: www.techienest.in

22

[email protected]

Variables are nothing but reserved memory locations to store values. This means when you create a variable, you reserve some space in memory. Based on the data type of a variable, the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store integers, decimals,or characters in these variables. 1.7.1 Assigning Values to Variables: Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the value stored in the variable. For example:

Here, 100, 1000.0, and "John" are the values assigned to counter, miles, and name variables respectively. This produces the following result:

1.7.2 Multiple Assignment: Python allows you to assign a single value to several variables simultaneously. For example:

Here, an integer object is created with the value 1, and all three variables are assigned to the same memory location. You can also assign multiple objects to multiple variables. For example:

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively, and one string object with the value "john" is assigned to the variable c. 1.7.3 Standard Data Types: www.techienest.in

23

[email protected]

The data stored in memory can be of many types. For example, a person's age is stored as a numeric value and his or her address is stored as alphanumeric characters. Python has various standard data types that are used to define the operations possible on them and the storage method for each of them. Python has five standard data types: 

Numbers



Strings



List



Tuple



Dictionary

Python Numbers: Number data types store numeric values. Number objects are created when you assign a value to them. For example:

Python supports four different numerical types:    

Int (signed integers) Long(long integers, they can also be represented in octal and hexadecimal) Float(floating point real values) Complex(complex numbers)

Examples: Here are some examples of numbers: www.techienest.in

24

[email protected]

1.7.4 Python Strings: Strings in Python are identified as a contiguous set of characters represented in thequotation marks. Python allows for either pairs of single or double quotes. Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the string and working their way from -1 at the end. The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator. For example:

www.techienest.in

25

[email protected]

This will produce the following result:

1.7.5 Python Lists: Lists are the most versatile of Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). To some extent, lists are similar to arrays in C. One difference between them is that all the items belonging to a list can be of different data type. The values stored in a list can be accessed using the slice operator ([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their way to end -1. The plus (+) sign is the list concatenation operator, and the asterisk (*) is the repetition operator.

www.techienest.in

26

[email protected]

For example:

This will be the result.

1.7.6 Python Tuples: A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses. The main differences between lists and tuples are: Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists. For example:

www.techienest.in

27

[email protected]

This produces the following result:

The following code is invalid with tuple, because we attempted to update a tuple, which is not allowed. Similar case is possible with lists:

1.7.7 Python Dictionary: Python's dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object. Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

www.techienest.in

28

[email protected]

For example:

This produces the following result:

Dictionaries have no concept of order among elements. It is incorrect to say that the elements are "out of order"; they are simply unordered.

www.techienest.in

29

[email protected]

1.7.8 Data type Conversion:

Sometimes, you may need to perform conversions between the built-in types. To convert between types, you simply use the type name as a function. There are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.

www.techienest.in

30

[email protected]

1.8 Basic Operators: 1.8.1 Types of operators: Python language supports the following types of operators. 

Arithmetic Operators



Comparison (Relational) Operators



Assignment Operators



Logical Operators



Bitwise Operators



Membership Operators

1.8.1.1 Python Arithmetic Operators: Assume variable a holds 10 and variable b holds 20, then:

www.techienest.in

31

[email protected]

1.8.1.2 Python Comparison Operators: These operators compare the values on either sides of them and decide the relation among them. They are also called Relational operators. Assume variable a holds 10 and variable b holds 20, then:

Example: a=10,b=20 if a
print “a
else if a>b:

print “a>b”

else if a<=b:

print “a<=b”

else:

print “a>=b”

www.techienest.in

32

[email protected]

1.8.1.3 Python Assignment Operators:

For example: a=10, b=5 a+=5 a=a+5

//a=5+5=10

b/=5 b=b/5

//b=10/5=2

b*=5 b=b*5

www.techienest.in

//b=5*5=25

33

[email protected]

1.8.1.4 Python Bitwise Operators: Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows: a = 0011 1100 b = 0000 1101 ----------------a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 There are following Bitwise operators supported by Python language

www.techienest.in

34

[email protected]

Example:

When execute the above program it produces the following result:

www.techienest.in

35

[email protected]

1.8.1.5 Python Logical Operators: There are following logical operators supported by Python language. Assume variable a holds 10 and variable b holds 20 then:

1.8.1.6 Python Membership Operators: Python’s membership operators test for membership in a sequence, such as strings, lists, or tuples. There are two membership operators as explained below:

www.techienest.in

36

[email protected]

For example:

When you execute the above program it produces the following result:

www.techienest.in

37

[email protected]

1.8.2 Python Operators Precedence:

The following table lists all operators from highest precedence to lowest. Operator precedence affects how an expression is evaluated. For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than +, so it first multiplies 3*2 and then adds into 7. Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom.

www.techienest.in

38

[email protected]

Example:

When you execute the above program, it produces the following result

1.9 Decision Making: Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise. Following is the general form of a typical decision making structure found in most of the programming languages:

www.techienest.in

39

[email protected]

Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value. Python programming language provides following types of decision making statements. 9   

if statement if else statements nested if statements

If statement: It is similar to that of other languages. The if statement contains a logical expression using which data is compared and a decision is made based on the result of the comparison. Syntax

If the Boolean expression evaluates to TRUE, then the block of statement(s) inside the if statement is executed. If Boolean expression evaluates to FALSE, then the first set of code after the etnd of the if statement(s) is executed.

www.techienest.in

40

[email protected]

Flow Diagram

Example

www.techienest.in

41

[email protected]

When the above code is executed, it produces the following result

If….else Statement An else statement can be combined with an if statement. An else statement contains the block of code that executes if the conditional expression in the if statement resolves to 0 or a FALSE value. The else statement is an optional statement and there could be at most only one else statement following if.

www.techienest.in

42

[email protected]

Syntax if expression: statement(s) else: statement(s)

Flow Diagram var1 = 100 if var1: print "1 - Got a true expression value" print var1 else: print "1 - Got a false expression value" print var1 var2 = 0 if var2: print "2 - Got a true expression value" print var2 else: print "2 - Got a false expression value" print var2 Print "Good bye!"

When the above code is executed, it will produce the following result

www.techienest.in

43

[email protected]

The elif statement The elif statement allows you to check multiple expressions for TRUE and execute a block of code as soon as one of the conditions evaluates to TRUE. Similar to the else, the elif statement is optional. However, unlike else, for which there can be at most one statement, there can be an arbitrary number of elif statements following an if. Syntax if expression1: statement(s) elif expression2: statement(s) elif expression3: statement(s) else: statement(s)

Core Python does not provide switch or case statements as in other languages, but we can use if..elif...statements to simulate switch case as follows:

www.techienest.in

44

[email protected]

When the above code is executed, it will produce the following result

1.10 Loops: In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Programming languages provide various control structures that allow for more complicated execution paths. A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement:

www.techienest.in

45

[email protected]

Python programming language provides following types of loops to handle looping requirements. 

While loop



For loop



Nested loop

1.10.1 While loop: A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. Syntax: The syntax of a while loop in Python programming language is:

Here, statement(s) may be a single statement or a block of statements. The condition may be any expression, and true is any non-zero value. The loop iterates while the condition is true. When the condition becomes false, program control passes to the line immediately following the loop. In Python, all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements.

www.techienest.in

46

[email protected]

Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed. Example

When the above code is executes, it will produce the following result The count is :0 The count is :1 The count is :2 The count is :3 The count is :4 The count is :5 The count is :6 The count is :7 The count is :8 The count is :9 Good bye The block here, consisting of the print and increment statements, is executed repeatedly until count is no www.techienest.in

47

[email protected]

longer less than 9. With each iteration, the current value of the index count is displayed and then increased by 1. The infinite loop: A loop becomes infinite loop if a condition never becomes FALSE. You must use caution when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop. An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.

When the above code is executed, it will produce the following result Enter a number :20 You entered: 20 Enter a number :29 You entered: 29 Enter a number :3 You entered: 3 Above example goes in a infinite loop and you need to use CTRL+C to exit the program. 1.10.2 For Loop: It has the ability to iterate over the items of any sequence, such as a list or a string. Syntax:

If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable iterating_var. Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.

www.techienest.in

48

[email protected]

Flow Diagram

Example:

When the above code is executed, it will produce the following result

Using else statements with Loops: Python supports to have an else statement associated with a loop statement. If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If the else statement is used with a while loop, the else statement is executed when the condition becomes false. www.techienest.in

49

[email protected]

The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20.

for num in range(10,20): #to iterate between 10 to 20 for i in range(2,num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor j=num/i #to calculate the second factor print '%d equals %d * %d' % (num,i,j) break #to move to the next number, the #first FOR else: # else part of the loop print num, 'is a prime number

When the above code is executed, it will produce the following result 10 equals 2 * 5 11 is a prime number 12 equals 2 * 6 13 is a prime number 14 equals 2 * 7 15 equals 3 * 5 16 equals 2 * 8 17 is a prime number 18 equals 2 * 9 19 is a prime number

1.10.3 Nested Loops: Python programming language allows to use one loop inside another loop. Following section shows few examples to illustrate the concept. Syntax:

The syntax for a nested while loop statement in Python programming language is as follows:

www.techienest.in

50

[email protected]

A final note on loop nesting is that you can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa.

Example When the above code is executed, it will produce the following result.

www.techienest.in

51

[email protected]

1.11 Loop Control Statements: Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements. Click the following links to check their detail. They are three types: 

Break statement



Continue statement



Pass statement

1.11.1 Break Statement: It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops. If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block. Syntax The syntax for a break statement in Python is as follows:

Flow Diagram Example:

www.techienest.in

52

[email protected]

When the above code is executed, it will produce the following result.

1.11.2 Continue Statement: It returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops. Syntax

www.techienest.in

53

[email protected]

Flow Diagram

1.11.3 Pass statement: It is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example): Syntax:

Example:

www.techienest.in

54

[email protected]

When the above code is executed, it will produce the following result

1.12 Functions A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions such as print() and but you can also create your own functions. These functions are called user-defined functions. Defining a Function: You can define functions to provide the required functionality. Here are simple rules to define a function in Python. Function blocks begin with the keyword def followed by the function name and parentheses (()). Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses. The first statement of a function can be an optional statement - the documentation string of the function or doc string. The code block within every function starts with a colon (:) and is indented. The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return none. Syntax

By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. www.techienest.in

55

[email protected]

Example: The following function takes a string as input parameter and prints it on standard screen.

Calling a Function: Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code. Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is the example to call print me() function:

www.techienest.in

56

[email protected]

When the above code is executed, it will produce the following result

Passing by Reference versus Passing by Value All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example:

Here, we are maintaining reference of the passed object and appending values in the same object. So, this would produce the following result:

Functions Arguments You can call a function by using the following types of formal arguments:    

Required arguments Keyword arguments Default arguments Variable-length argument

www.techienest.in

57

[email protected]

Required Arguments: Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition. To call the function print me(), you definitely need to pass one argument, otherwise it gives a syntax error as follows:

When the above code is executed, it will produce the following result

Keyword Arguments Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name. This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways: # Function definition is here defprintme( str ): "This prints a passed string into this function" print str; return; # Now you can call printme function printme( str = "My string"); When the above code is executed, it will produce the following result >>>My string The following example gives more clear picture. Note that the order of parameters does not matter. www.techienest.in

58

[email protected]

When the above code is executed, it will produce the followingresult

Default Arguments: A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed:

When the above code is executed, it will produce the following result.

www.techienest.in

59

[email protected]

Variable Length Arguments: You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. Syntax for a function with non-keyword variable arguments is this:

An asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example:

When the above code is executed, it will produce the following result. Output is : 10 Output is: 70 60 50 www.techienest.in

60

[email protected]

The return Statement: The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. All the above examples are not returning any value. You can return a value from a function as follows:

When the above code is executed, it will produce the following result.

1.13 Brief Introduction of Standard Library Operating system interface: The os module provides dozens of functions for interacting with the operating system:

Be sure to use the import os style instead of from os import *. This will keep os.open() from shadowing the builtin open() function which operates much differently. The builtin dir() and help() functions are useful as interactive aids for working with large modules like os :

www.techienest.in

61

[email protected]

For daily file and directory management tasks, the shutil module provides a higher level interface that is easier to use:

File Wildcards: The glob module provides a function for making file lists from directory wildcard searches:

Command Line Arguments: Common utility scripts often need to process command line arguments. These arguments are stored in the sys module’s argv attribute as a list. For instance the following output results from running python demo.py one two three at the command line:

The getopt module processes sys.argv using the conventions of the Unix getopt() function. More powerful and flexible command line processing is provided by the argparse module. Mathematics: The math module gives access to the underlying C library functions for floating point math:

The random module provides tools for making random selections:

www.techienest.in

62

[email protected]

The statistics module calculates median,variance, etc) of numeric data:

basic

statistical

properties

(the

mean,

Internet Access: There are a number of modules for accessing the internet and processing internet protocos. Two of the simplest are urllib.request for retrieving data from URLs and smtplib for sending mail:

Date and Times: The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient member extraction for output formatting and manipulation The module also supports objects that are timezone aware.

www.techienest.in

63

[email protected]

Performance measurement: Some Python users develop a deep interest in knowing the relative performance of different approaches to the same problem. Python provides a measurement tool that answers those questions immediately. For example, it may be tempting to use the tuple packing and unpacking feature instead of the traditional approach to swapping arguments. The timeitmodule quickly demonstrates a modest performance advantages:

In contrast to timeit’sfine level of granularity, the profile and pstatsmodules provide tools for identifying time critical sections in larger blocks of code. Batteries Included Python has a “batteries included” philosophy. This is best seen through the sophisticated and robust capabilities of its larger packages. For example: The xmlrpc.clientand xmlrpc.servermodules make implementing remote procedure calls into an almost trivial task. Despite the modules names, no direct knowledge or handling of XML is needed. The email package is a library for managing email messages, include MIME and other RFC 2822-based message documents. Unlike smtpliband poplibwhich actually send and receive messages, the email package has a complete toolset for building or decoding complex messages structures and for implementing internet encoding and header protocols. The jsonpackage provides robust support for parsing this popular data interchange format. The csv module supports direct reading and writing of files in comma-separated value format, commonly supported databases and spreadsheets. XML processing is supported by the xml.etree.ElementTree, www.techienest.in

64

[email protected]

xml.domand xml.sax packages. Together, these modules and packages greatly simplify data interchange between python application and other tools. The sqlite3 module is a wrapper for the SQLite database library, providing a persistent database that can be updated and accessed using slightly nonstandard SQL syntax.

GUI Programing Python provides various options for developing graphical user interfaces (GUIs). Most Important are listed below: Tkinter: Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. We would look this option in this chapter. wxPython: This is an open-source Python interface for wxWindowshttp://wxpython.org. JPython: JPython is a Python port for Java which gives Python scripts seamless access to Java class libraries on the local machine http://www.jython.org There are many other interfaces available, which you can find them on the net.

Tkinter Programming: Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Tk GUI toolkit. Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps:    

Import the Tkinter module Create the GUI application main window. Add one or more of the above-mentioned widgets to the GUI application. Enter the main event loop to take action against each even triggered by the user Import Tkinter Top=Tkinter.Tk() #code to add widgets will go here top.mainloop()

www.techienest.in

65

[email protected]

This would create a following window.

Tkinter Widgets: Tkinter provides various controls, such as buttons, labels and text boxes used in a GUI application. These controls are commonly called widgets. There are currently 15 types of widgets in Tkinter. We present these widgets as well as a brief description in the following table:

www.techienest.in

66

[email protected]

Button The Button widget is used to add buttons in a Python application. These buttons can display text or images that convey the purpose of the buttons. You can attach a function or a method to a button which is called automatically when you click the button. Syntax

Parameters: Master: This represents the parent window. Options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

www.techienest.in

67

[email protected]

Methods Following are commonly used methods for this widget:

www.techienest.in

68

[email protected]

Example

When the above code is executed, it will produce the following result.

Canvas The Canvas is a rectangular area intended for drawing pictures or other complex layouts. You can place graphics, text, widgets2. or frames on a Canvas. Syntax

Parameters Master: This represents the parent window. Options: Here is the list of most commonly used options for this widget. These options can be used as www.techienest.in

69

[email protected]

key-value pairs separated by commas.

The Canvas widget can support the following standard items:

arc.Creates an arc item, which can be a chord, a pie slice or a simple arc. image. Creates an image item, which can be an instance of either the Bitmap Image or the Photo Image classes.

line .Creates a line item.

Oval Creates a circle or an ellipse at the given coordinates. It takes two pairs of coordinates; the top left and bottom right corners of the bounding rectangle for the oval www.techienest.in

70

[email protected]

polygon. Creates a polygon item that must have at least three vertices.

Example: import Tkinter import tkMessageBox top = Tkinter.Tk() C = Tkinter.Canvas(top, bg="blue", height=250, width=300) coord = 10, 50, 240, 210 arc = C.create_arc(coord, start=0, extent=150, fill="red") C.pack() top.mainloop()

When the above code is executed, it will produce the following result.

Check Button: The Checkbutton widget is used to display a number of options to a user as toggle buttons. The user can then select one or more options by clicking the button corresponding to each option. You can also display images in place of text. Syntax Here is the simple syntax to create this widget:

www.techienest.in

71

[email protected]

Parameters: Master: This represents the parent window. Options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

www.techienest.in

72

[email protected]

Methods Following are commonly used methods for this widget:

Example: from Tkinter import * import tkMessageBox import Tkinter top = Tkinter.Tk() CheckVar1 = IntVar() CheckVar2 = IntVar() C1 = Checkbutton(top, text = "Music", variable = CheckVar1, \ onvalue = 1, offvalue = 0, height=5, \ width = 20) C2 = Checkbutton(top, text = "Video", variable = CheckVar2, \ onvalue = 1, offvalue = 0, height=5, \ width = 20) C1.pack() C2.pack() top.mainloop()

When the above code is executed, it will produce the following result.

www.techienest.in

73

[email protected]

Entry The Entry widget is used to accept single-line text strings from a user. If you want to display multiple lines of text that can be edited, then you should use the Text widget. If you want to display one or more lines of text that cannot be modified by the user, then you should use the Label widget. Syntax Here is the simple syntax to create the widget:

Parameters Master: This represents the parent window. Options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

Methods: www.techienest.in

74

[email protected]

www.techienest.in

75

[email protected]

Example: Try the following example yourself. from Tkinter import * top = Tk() L1 = Label(top, text="User Name") L1.pack( side = LEFT) E1 = Entry(top, bd =5) E1.pack(side = RIGHT) top.mainloop() When the above code is executed, it will produce the following result.

Frame: The Frame widget is very important for the process of grouping and organizing other widgets in a somehow friendly way. It works like a container, which is responsible for arranging the position of other widgets. It uses rectangular areas in the screen to organize the layout and to provide padding of these widgets. A frame can also be used as a foundation class to implement complex widgets. Syntax Here is the simple syntax to create the widget. Parameters Master: This represents the parent window. Options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas

www.techienest.in

76

[email protected]

Try this following example: from Tkinter import * root = Tk() frame = Frame(root) frame.pack() bottomframe = Frame(root) bottomframe.pack( side = BOTTOM ) redbutton = Button(frame, text="Red", fg="red") redbutton.pack( side = LEFT) greenbutton = Button(frame, text="Brown", fg="brown") greenbutton.pack( side = LEFT ) bluebutton = Button(frame, text="Blue", fg="blue") bluebutton.pack( side = LEFT ) blackbutton = Button(bottomframe, text="Black", fg="black") blackbutton.pack( side = BOTTOM) root.mainloop() When the above code is executed it will produce the following result.

www.techienest.in

77

[email protected]

Label: This widget implements a display box where you can place text or images. The text displayed by this widget can be updated at any time you want. It is also possible to underline part of the text (like to identify a keyboard shortcut) and span the text across multiple lines. Syntax: Here is the simple syntax to create the widget.

www.techienest.in

78

[email protected]

Example: Try the following example yourself. from Tkinter import * root = Tk() var = StringVar() label = Label( root, textvariable=var, relief=RAISED ) var.set("Hey!? How are you doing?") label.pack() root.mainloop() When the above code is executed it will produce the following result.

Listbox The Listbox widget is used to display a list of items from which a user can select a number of items. Syntax Here is the simple syntax to create the widget.

www.techienest.in

79

[email protected]

Parameters Master: This represents the parent window. Options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

Methods Methods on listbox objects include.

www.techienest.in

80

[email protected]

Example: Try the following example yourself. from Tkinter import * import tkMessageBox import Tkinter top = Tk() Lb1 = Listbox(top) Lb1.insert(1, "Python") Lb1.insert(2, "Perl") Lb1.insert(3, "C") Lb1.insert(4, "PHP") Lb1.insert(5, "JSP") Lb1.insert(6, "Ruby") Lb1.pack() top.mainloop()

www.techienest.in

81

[email protected]

When the above code is executed, it will produce the following result.

Menu Button: A menubutton is the part of a drop-down menu that stays on the screen all the time. Every menubutton is associated with a Menu widget that can display the choices for that menubutton when the user clicks on it. Syntax Here is the simple syntax to create this widget.

Parameters: master: This represents the parent window. options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas.

www.techienest.in

82

[email protected]

Example: Try this following example yourself. from Tkinter import * import tkMessageBox import Tkinter top = Tk() mb= Menubutton ( top, text="condiments", relief=RAISED ) mb.grid() mb.menu = Menu ( mb, tearoff = 0 ) mb["menu"] = mb.menu mayoVar = IntVar() ketchVar = IntVar() mb.menu.add_checkbutton ( label="mayo", variable=mayoVar ) mb.menu.add_checkbutton ( label="ketchup", variable=ketchVar ) mb.pack() top.mainloop()

www.techienest.in

83

[email protected]

When the above code is executed, it will produce the following result.

Menu The goal of this widget is to allow us to create all kinds of menus that can be used by our applications. The core functionality provides ways to create three menu types: pop-up, toplevel and pull-down. It is also possible to use other extended widgets to implement new types of menus, such as the Option Menu widget, which implements a special type that generates a pop-up list of items within a selection. Syntax Here is the simple syntax to create this widget.

Parameters master: This represents the parent window Options: Here is the list of most commonly used options for this widget. These ptions can be used as key-value pairs separated by commas.

www.techienest.in

84

[email protected]

Methods: These methods are available on Menu objects:

www.techienest.in

85

[email protected]

Example: from Tkinter import * defdonothing(): filewin = Toplevel(root) button = Button(filewin, text="Do nothing button") button.pack() root = Tk() menubar = Menu(root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="New", command=donothing) filemenu.add_command(label="Open", command=donothing) filemenu.add_command(label="Save", command=donothing) filemenu.add_command(label="Save as...", command=donothing) filemenu.add_command(label="Close", command=donothing) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="File", menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label="Undo", command=donothing) editmenu.add_separator() www.techienest.in

86

[email protected]

editmenu.add_command(label="Cut", command=donothing) editmenu.add_command(label="Copy", command=donothing) editmenu.add_command(label="Paste", command=donothing) editmenu.add_command(label="Delete", command=donothing) editmenu.add_command(label="Select All", command=donothing) menubar.add_cascade(label="Edit", menu=editmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="Help Index", command=donothing) helpmenu.add_command(label="About...", command=donothing) menubar.add_cascade(label="Help", menu=helpmenu)

When the above code is executed, it will produce the following result.

Message This widget provides a multiline and noneditable object that displays texts, automatically breaking lines and justifying their contents. Its functionality is very similar to the one provided by the Label widget, except that it can also automatically wrap the text, maintaining a given width or aspect ratio. Parameters Master: This represents the parent window. Options: Here is the list of most commonly used options for this widget. These options can be used as key-value pairs separated by commas. Example: Try the following example yourself. from Tkinter import * root = Tk() var = StringVar() label = Message( root, textvariable=var, relief=RAISED ) var.set("Hey!? How are you doing?") label.pack() root.mainloop() www.techienest.in

87

[email protected]

When the above code is executed, it will produce the following result.

Radio Button This widget implements a multiple-choice button, which is a way to offer many possible selections to the user and lets user choose only one of them.In order to implement this functionality, each group of radio buttons must be associated to the same variable and each one of the buttons must symbolize a single value. You can use the Tab key to switch from one radio button to another. Syntax

from Tkinter import * defsel(): selection = "You selected the option " + str(var.get()) label.config(text = selection) root = Tk() var = IntVar() R1 = Radiobutton(root, text="Option 1", variable=var, value=1, command=sel) R1.pack( anchor = W ) R2 = Radiobutton(root, text="Option 2", variable=var, value=2, command=sel) R2.pack( anchor = W ) R3 = Radiobutton(root, text="Option 3", variable=var, value=3, command=sel) R3.pack( anchor = W) label = Label(root) label.pack() root.mainloop()

www.techienest.in

88

[email protected]

When the code is executed, it will produce the following result.

“ATM System “ Lets us revise what we have learned till now by implementing everything in an ATM System. STEP 1:- To ask user to enter USER ID and respective PWD.

Now, you may notice because of ‘continue’ this loop will go infinite even after entering the authenticated USER ID and password the third time. To stop this we will use ‘break’. Break will cause the program to jump directly to the next statement outside the loop. Also, to ensure user could enter wrong password at a max of three times; we will count & increment its value, and put a break after (count==3)

www.techienest.in

89

[email protected]

Now continue the same for uid : B , C and D

STEP 2:- Asking user to choose any of the three possible operations i.e. Withdraw, Deposit and Cancel. STEP 3:- ensuring the withdrawal amount must not be greater than amount already deposited in account www.techienest.in

90

[email protected]

THINGSPEAK To create an account on ‘www.thingspeak.com’ Step by step explaination for the same.  To sign up onto the website.

www.techienest.in

91

[email protected]



After verifying your email account, Sign In and create a channel as follows.

 

Now its time to login. Once sign in create channel named iot and go to Private then choose API keys.You will get a WRITE and a READ Apiin the bottom right corner you could see 4 newly generated api’s. The first Api is the “POST” api to set the desired input in the URL. The third Api is the “GET” api to be written while retriving values.

 

www.techienest.in

92

[email protected]



(Ctrl + c) the first api and paste it onto the url and edit the value of field 1 at the end of the url.

www.techienest.in

93

[email protected]

www.techienest.in

94

[email protected]

UNIT 2 COMPUTING 2.1 Raspberry_Pi A Raspberry_Pi is a credit card-sized computer originally designed for education. Due its small size and accessible price, it was quickly adopted by tinkerers, makers, and electronics enthusiasts for projects that require more than a basic microcontroller (such as Arduino devices). The Raspberry_Pi is slower than a modern laptop or desktop but is still a complete Linux computer and can provide all the expected abilities that implies, at a low-power consumption level. The Raspberry_Pi is open hardware, with the exception of the primary chip on the Raspberry_Pi, the Broadcom SoC (System on a Chip), which runs many of the main components of the board–CPU, graphics, memory, the USB controller, etc. Many of the projects made with a Raspberry_Pi are open and well-documented as well and are things you can build and modify yourself. Several generations of Raspberry_Pi is have been released. The first generation (Raspberry_Pi 1 Model B) was released in February 2012. It was followed by a simpler and inexpensive model Model A. In 2014, the foundation released a board with an improved design in Raspberry_Pi 1 Model B+. These boards are approximately credit-card sized and represent the standard mainline form-factor. Improved A+ and B+ models were released a year later. A "compute module" was released in April 2014 for embedded applications, and a Raspberry_Pi Zero with smaller size and reduced input/output (I/O) and general-purpose input/output (GPIO) capabilities was released in November 2015. The Raspberry_Pi 2 which added more RAM was released in February 2015. Raspberry_Pi 3 Model B released in February 2016, is bundled with on-board WiFi, Bluetooth and USB boot capabilities. As of January 2017, Raspberry_Pi 3 Model B is the newest mainline Raspberry_Pi. As of 28 February 2017, the Raspberry_Pi Zero W was launched, which is identical to the Raspberry_Pi Zero, but has the Wi-Fi and Bluetooth functionality of the Raspberry_Pi 3.

2.2 Specifications: 

A 1.2GHz 64-bit quad-core ARMv8 CPU



802.11n Wireless LAN



Bluetooth 4.1



Bluetooth Low Energy (BLE)



1GB RAM



4 USB ports



40 GPIO pins



Full HDMI port



Ethernet port

www.techienest.in

95

[email protected]



Combined 3.5mm audio jack and composite video



Camera interface (CSI)



Display interface (DSI)



Micro SD card slot (now push-pull rather than push-push)



VideoCore IV 3D graphics core

2.3 Operating System for Raspberry_Pi The Raspberry_Pi was designed for the Linux operating system, and many Linux distributions now have a version optimized for the Raspberry_Pi. Two of the most popular options are Raspbian, which is based on the Debian operating system, and Pidora, which is based on the Fedora operating system. For beginners, either of these two work well; which one you choose to use is a matter of personal preference. A good practice might be to go with the one which most closely resembles an operating system you’re familiar with, in either a desktop or server environment. If you would like to experiment with multiple Linux distributions and aren't sure which one you want, or you just want an easier experience in case something goes wrong, try NOOBS, which stands for New Out Of Box Software. When you first boot from the SD card, you will be given a menu with multiple distributions (including Raspbian and Pidora) to choose from. If you decide to try a different one, or if something goes wrong with your system, you simply hold the Shift key at boot to return to this menu and start over. There are, of course, lots of other choices. OpenELEC and RaspBMC are both operating system distributions based on Linux that are targeted towards using the Raspberry_Pi as a media centre. There are also non-Linux systems, like RISC OS, which run on the Pi. Some enthusiasts have even used the Raspberry_Pi to learn about operating systems by designing their own.

2.4 History: As of 2016, the vision of the Internet of Things has evolved due to a convergence of multiple technologies, including ubiquitous wireless communication, real-time analytics, machine learning, commodity sensors, and embedded systems. This means that the traditional fields of embedded systems, wireless

sensor

networks, control

systems, automation (including home and building

automation), and others all contribute to enabling the Internet of things (IoT). The concept of a network of smart devices was discussed as early as 1982, with a modified Coke machine at Carnegie Mellon University becoming the first Internet-connected appliance, able to report its inventory and whether newly loaded drinks were cold. Mark Weiser's seminal 1991 paper on ubiquitous computing, "The Computer of the 21st Century", as well as academic venues such as www.techienest.in

96

[email protected]

UbiComp and PerCom produced the contemporary vision of IoT. In 1994 Reza Raji described the concept in IEEE Spectrum as "[moving] small packets of data to a large set of nodes, so as to integrate and automate everything from home appliances to entire factories". Between 1993 and 1996 several companies proposed solutions like Microsoft's at Work or Novell's NEST. However, only in 1999 did the field start gathering momentum. Bill Joy envisioned Device to Device (D2D) communication as part of his "Six Webs" framework, presented at the World Economic Forum at Davos in 1999. The concept of the Internet of Things became popular in 1999, through the Auto-ID Center at MIT and related market-analysis publications. Radio-frequency identification (RFID) was seen by Kevin Ashton (one of the founders of the original Auto-ID Center) as a prerequisite for the Internet of things at that point. Ashton prefers the phrase "Internet for Things." If all objects and people in daily life were equipped with identifiers, computers could manage and inventory them. Besides using RFID, the tagging of things may be achieved through such technologies as near field communication, barcodes, QR codes and digital watermarking. In its original interpretation, one of the first consequences of implementing the Internet of things by equipping all objects in the world with minuscule identifying devices or machine-readable identifiers would be to transform daily life. For instance, instant and ceaseless inventory control would become ubiquitous. A person's ability to interact with objects could be altered remotely based on immediate or present needs, in accordance with existing end-user agreements. For example, such technology could grant motion-picture publishers much more control over end-user private devices by remotely enforcing copyright restrictions and digital rights management, so the ability of a customer who bought a Blu-ray disc to watch the movie could become dependent on the copyright holder's decision, similar to Circuit City's failed DIVX.

2.5 Steps to Installation and use Raspberry_Pi Check your Raspberry_Pi model configuration like RAM , ROM, Processor and GPIO. Then now, the important component which are used to operate Raspberry_Pi board are: Firstly, we need a power adapter to power up the Raspberry_Pi board. Then, Micro SD Card at least 8 GB or more recommended to install and store the operating system image in it. Then, HDMI to VGA Cable to connect a display device like monitor, and Keyboard & mouse (recommended USB) for Raspberry_Pi board. Now, how to install OS in SD card. To install OS image manually, First you need a image copy of raspbian OS in your PC and a image burner named as Win32 disk imager. www.techienest.in

97

[email protected]

Now, Firstly Format the SD card then open win32 disk imager. After opening it should be look like this.

Then select the drive where you want to copy the image of RaspbianOS . And browse the image copy of Raspbain and click write to copy the image. After then connect all these together. It should be look like this,

So now you got Raspberry_Pi with installed OS, Now there are lots of pins on the corner of Raspberry_Pi board. These pins are known as GPIO (Gerenal Purpose Input Output) pins named as.

2.6 Connecting to Raspberry_Pi Step 1: Connect the power cable and LAN cable to Raspberry_Pi Step 2: After completion of Connection it will look like this. Step 3: Create wifi Hotspot and connect with it. Step 4: Open Network and Sharing center.

www.techienest.in

98

[email protected]

Step 5: Click on the Change Adapter Settings. Step 6: Click on Wifi and go to the Properties.

Step 7: Click on the Sharing and open it.

Step 8: Disable the Allow other Network users to connect.

www.techienest.in

99

[email protected]

Step 9: Click on wifi> properties>IPv4

Step 10: Select the Obtain an IP address automatically.

www.techienest.in

100

[email protected]

Step 11: Click on Ethernet and do the same above process.

www.techienest.in

101

[email protected]

Step 12: Open network and Sharing Center > change adapter settings> select Ethernet and wifi

Step 13: Right click on it and make bridge connection.

www.techienest.in

102

[email protected]

Step 14: After Bridge Connection Following icon will get.

Step 15: Open command prompt and enter ipconfig

Then you’ll get the following with Ethernet adapter Network bridge and note it down the IP www.techienest.in

103

[email protected]

Step 16: Open IP Scanner and enter IP here.

After successful scanning you’ll get the RaspberryPiip address.

www.techienest.in

104

[email protected]

Step 17: We need remote Desktop in pi to connect through PC for this Open Putty and enter your pi IP.

Then it’ll open like this enter User name: pi and password: raspberry

www.techienest.in

105

[email protected]

Step 18: For installing XRDP in raspberryPi enter following commands in command terminal.

www.techienest.in

106

[email protected]

After installation of XRDP open Remote Desktop and connect it.

Step 19: Open Remote Desktop and enter the IP and click on connect

After successful connection it will look like this click on Yes and now you’ll going to enter into the Raspberry_Pi world.

www.techienest.in

107

[email protected]

Welcome to Raspberry World

2.7 Various ways to connect Raspberry_Pi 

Bridge Connection



Local server



DHCP Server

Bridge Connection: Create Wi-Fi Hotspot and connect the PC to it. Open Network and Sharing Centre click on the change Adapter settings. Then you’ll get two connections 1)Ethernet 2)Wi-Fi Hotspot. Click on Wi-Fi > Properties > sharing > Disable the Allow other Network Option Click on IPv4>click obtain IP Address Automatically. Click on Ethernet > Properties > sharing > Disable the Allow other Network Option. Click on IPv4>click obtain IP Address Automatically. Select the Both connections and make Bridge Connection www.techienest.in

108

[email protected]

Open cmd Prompt >enter ipconfig Then you will get the IP address in Ethernet Adapter Network Bridge. Open IP Scanner and enter IP and click on scan. After few minutes of scan you’ll get the RaspberryPi IP. Open Putty and Enter IP and connect then it’ll ask to enter Login name and password. Login :pi Password:raspberry Install xrdp by following commands and connect it with Remote Desktop. Sudo apt-get update sudo apt-get installxrdp Local Server Open putty and enter raspberrypi.local in it.

If pi is connected then it will asks to enter login name password

After login the command terminal will turn to pi@raspberrypi www.techienest.in

109

[email protected]

Open remote Desktop and enter raspberrypi.local and click on connect.

Local server will depends on the system sometimes it may connect and sometimes not. DHCP Server Interfacing With Raspberry_Pi Camera Step 1: Connect the camera module at given slot area be careful in connection Step 2: Install the Raspberry_Pi Camera module by inserting the cable into the Rpi. The cable slots into the connector situated between the Ethernet and HDMI Port. Step 3: Boot your pi with the following command sudo reboot Step 4: Open command terminal and enter the following command

www.techienest.in

110

[email protected]

Select the Enable Camera option

Click on Enable

www.techienest.in

111

[email protected]

Click on Finish

Reboot by selecting Yes

www.techienest.in

112

[email protected]

How to Take Image By command Open command terminal enter the following command to take image.

How to Record Video By Command Open command terminal and enter the following command to record video.

2.8 Display Touch Screen Step 1: To install XPT2046 LCD Touch screen open raspberry configuration

Select expand filesystem

www.techienest.in

113

[email protected]

Select Boot Options

Select Desktop Auto Login

www.techienest.in

114

[email protected]

Reboot Raspberry_Pi

Enter the following Command to Download the LCD File

Enter ls to locate the LCD File in pi

www.techienest.in

115

[email protected]

Extract the file by following Command

Go to the location of file by following Command

www.techienest.in

116

[email protected]

Open location by following Command

Enter the following command to final setup of LCD Display

Now your Touch Screen Display is ready to use. Basic Sudo Commands to Install various files in RaspberryPi

www.techienest.in

117

[email protected]

2.9 Serial communication Open Pi Terminal and enter following Command

Click on the down key and select the Advanced Options and Enter on it.

After click on the following window will open use down arrow key and select the Serial option and Enter on it.

www.techienest.in

118

[email protected]

Click on No Option

Now serial is disabled and click on OK

www.techienest.in

119

[email protected]

Use down key and select the Finish Option and click Enter.

It will ask you to reboot click on YES and wait for few seconds it will login itself and now your pi is ready to interface with any UART Modules.

www.techienest.in

120

[email protected]

2.10 XRDP (Remote Desktop)

Before going to install xrdp update the Raspberry_pi by above command. Enter the following command to install remote desktop in Raspberry_Pi

Now xrdp is successfully installed in Raspberry_Pi now it’s ready to use. www.techienest.in

121

[email protected]

www.techienest.in

122

[email protected]

2.11 Configuring Wi-Fi(Wireless Fidelity) Enter the following Command to Scan the Available Wi-Fi Networks.

You’ll get the Wi-Fi names with ESSID Note it down.

Now, enter the following Command to Set up Wi-Fi Network in Configuration file.

In file any Networks are Available Replace with Your Desired Wi-Fi. If not Available enter the following and Replace with You Wi-Fi User name and Password

www.techienest.in

123

[email protected]

Press Ctrl+o and Ctrl+x

Enter the above command to activate the Wi-Fi.

2.12 1-Wire GPIO 1-wire is a device communication data bus system developed by Dallas semiconductor providing low speed data, signalling and power over a single signal wire. One wire is similar to I2C with longer range and low data rates. It can be used to communicate with inexpensive devices like thermometers, humidity www.techienest.in

124

[email protected]

sensors and other one wire sensors over a long range. The main advantage is since each device has a unique address, any number of devices can be connected on a single wire limited by the drive capacity of Raspberry_Pi’s GPIO and the total capacitance seen on the line. Open pi command Terminal enter the following command

Enter the following code in command terminal to enable w1-gpio

Enter the following command and path will be changed as per given command.

Above command and the following command both are same but this command will easy to enable w1gpio after two commands

Enter cat w1_slave and press ctrl+x to exit

www.techienest.in

125

[email protected]

Open Raspberry_Pi and Select the location and run your file. Xlrd and xlwt*

Enter the following command to install xlrd and xlwt in raspberry for database.

www.techienest.in

126

[email protected]

Press y and continue

How to run Python Program in RaspberryPi Importing: www.techienest.in

127

[email protected]

The code “import” in python is used to introduce packages into your program. Because packages can be huge we store them in a separate location and use the import code to minimise the amount of code on your current project. Setup GPIO Pins: To ensure that the Raspberry_Pi understands whether a piece of hardware from the breadboard is an import or an export; we have to tell it. Commenting: #any text written after a “#” is known as a comment. This text is not read by the computer; it is there simply to try and explain what the written code is doing to any human reading it. Sample Program To Blink LED Open Python GUI Press Ctrl+N Copy the following code in it Save the file with name.py Import RPi.GPIO as GPIO ## Import GPIO Library Import time ## Import 'time' library (for 'sleep') pin =7 ## We're working with pin 7 GPIO.setmode(GPIO.BOARD) ## Use BOARD pin numbering GPIO.setup(pin, GPIO.OUT) ## Set pin 7 to OUTPUT GPIO.output(pin, GPIO.HIGH) ## Turn on GPIO pin (HIGH) time.sleep(1) ## Wait 1 second GPIO.output(pin, GPIO.LOW) ## Turn off GPIO pin (LOW) time.sleep(1) ## Wait 1 second GPIO.cleanup() ## Cleanup

Steps To Build Program Open python GUI Press Ctrl+o to Open file Press F5 to Build the Program Now your program will start working. How to Read/Write the File through the Sudo Command in Pi Open command terminal after connecting raspberry_Pi through Putty www.techienest.in

128

[email protected]

Enter sudonano in command terminal to open text file.

Then you will get the following window

Enter the above code in the window Press Ctrl+o to save the file with file name.py

www.techienest.in

129

[email protected]

Press Ctrl+m to write the program then you will get the following window.

Press Ctrl+x to Exit the window Enter sudo python filename.py in command terminal to build the program.

www.techienest.in

130

[email protected]

www.techienest.in

131

[email protected]

www.techienest.in

132

[email protected]

UNIT 3 INTERFACING INTERFACING WITH RPi3 3.1 BLINKING LED 3.1.1 Introduction A Light Emitting diode (LED) is a two-lead semiconductor light source. Led is a type of diode which emits light. ‘ON’ when it is Forward bias and is ‘OFF’ when it is reverse bias. When it is forward bias electrons are able to combine with hole and this combination releases energy in the form of Photon. This effect is known as electroluminescence and color of the light is directly related to the energy band gap of the semiconductor material. LED is small, low power consumption capability, faster switching, efficient compare other source. We find LED in aviation lighting, automotive lighting, advertising, general lighting, traffic signals, text video displays, light sensors, watch, cars light etc

Block Diagram

www.techienest.in

133

[email protected]

Connections: 

Connect the Power cable to Raspberry_Pi



Connect the Raspberry_Pi through Remote Desktop



Connect the Anode Pin of LED with following By resistor to GPIO 7th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin(GPIO 25) of Raspberry_Pi



And make sure that there is no wrong connections made



Open Python GUI and write the following code in New file

Program: Import RPi.GPIO as GPIO ## Import GPIO Library Import time ## Import 'time' library (for 'sleep') pin =7 ## We're working with pin 7 GPIO.setmode(GPIO.BOARD) ## Use BOARD pin numbering GPIO.setup(pin, GPIO.OUT) ## Set pin 7 to OUTPUT GPIO.output(pin, GPIO.HIGH) ## Turn on GPIO pin (HIGH) time.sleep(1) ## Wait 1 second GPIO.output(pin, GPIO.LOW) ## Turn off GPIO pin (LOW) time.sleep(1) ## Wait 1 second GPIO.cleanup()

## Cleanup

Steps To Build Program: Step 1:Open Python GUI Step 2:Press Ctrl+O and select the file Step 3:Press F5 Step 4:Now your LED will Start Blinking LED Pattern 1

www.techienest.in

134

[email protected]

Block Diagram

Connections: 

Connect the Power cable to Raspberry_Pi



Connect the Raspberry_Pi through Remote Desktop



Connect the Anode Pin of LED with following By resistor to GPIO 7th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 29th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 31th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode pin of LED with following By resistor to GPIO 32th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 33th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 35th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 36th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 37th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi

www.techienest.in

135

[email protected]

And make sure that there is no wrong connections made Open Python GUI and write the following code in new file Program import RPi.GPIO as IO ## Import GPIO Library as IO import time ## Import 'time' library (for 'sleep') IO.setmode(IO.BOARD) ## Use BOARD pin numbering IO.setwarnings(False) pin = [7,29,31,32,33,35,36,37] ##We're working with pin 7,29,31,32,33,35,36,37 for i in range(0,8): IO.setup(pin[i],IO.OUT) ## Set pin 7,29,31,32,33,35,36,37 to OUTPUT while True: for i in range(0,8): for j in range(0,8): if j!=(7-i): IO.output(pin[j],False) ## Turn off GPIO pin (LOW) IO.output(pin[7-i],True) ## Turn on GPIO pin (HIGH) time.sleep(0.25) ## Wait 0.25 second IO.cleanup() Steps To Build Program: Step 1: Open Python GUI Step 2: Press Ctrl+O and select the file Step 3: Press F5 Step 4: Now your LED’S will start blinking

www.techienest.in

136

[email protected]

LED PATTERN 2

Block Diagram Connections: 

Connect the Power cable to Raspberry_Pi



Connect the Raspberry_Pi through Remote Desktop



Connect the Anode Pin of LED with following By resistor to GPIO 7th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 29th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 31th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 32th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 33th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 35th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 36th pin of Raspberry_Pi

www.techienest.in

137

[email protected]



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi



Connect the Anode Pin of LED with following By resistor to GPIO 37th pin of Raspberry_Pi



Connect the cathode pin of LED to the Ground pin of Raspberry_Pi

And make sure that there is no wrong connections made Open Python GUI and write the following code in new file

Program import RPi.GPIO as I import time I.setmode(I.BOARD) I.setwarnings(False) pin = [7,11,12,13,15,16,18,22] l=len(pin) for i in range(0,l): I.setup(pin[i],I.OUT) while (1): for i in range(0,l): I.output(pin[7-i], 0) time.sleep(0.25) time.sleep(0.5) for k in range(0,l): I.output(pin[k], 1) time.sleep(0.2) I.cleanup() Steps To Build Program: Step 1: Open Python GUI Step 2: Press Ctrl+O and select the file Step 3: Press F5 Step 4: Now your LED’S will Start Blinking

3.2 BUZZER 3.2.1 Introduction The electric buzzer was invented in 1831 by Joseph Henry. They were mainly used in early doorbells until they were phased out in the early 1930s in favor of musical chimes, which had a softer tone. A buzzer or beeper is an audio signaling device, which may be mechanical, electromechanical, or piezoelectric. Typical uses of buzzers and beepers include alarm devices, timers, and confirmation of user input such as a mouse click or keystroke. www.techienest.in

138

[email protected]

Connections:  Connect the Power cable to Raspberry_Pi  Connect the Raspberry_Pi through Remote Desktop  Connect the buzzer positive pin to GPIO 33rd pin of Raspberry_Pi  Connect the buzzer negative pin to the Ground pin of Raspberry_Pi And make sure that there is no wrong connections made Open Python GUI and write the following code in new file Program import time import RPi.GPIO as taru count=0 taru.setwarnings(False) taru.setmode(taru.BOARD) taru.setup(33,taru.OUT) while(1): taru.output(33,1) print 'hi' time.sleep(1) taru.output(33,0) print 'hi' time.sleep(1) Steps To Build Program: Step 1: Open Python GUI Step 2: Press Ctrl+O and select the file Step 3: Press F5 Step 4: Now your Buzzer will Start. 3.3 SENSORS       

IR Sensor Ultrasonic Sensor Temperature Sensor Humidity Sensor LDR sensor Sound sensor Gas Sensor

www.techienest.in

139

[email protected]

3.3.1 IR Sensor Introduction Infrared Transmitter is a light emitting diode (LED) which emits infrared radiations. Hence, they are called IR LED’s. Even though an IR LED looks like a normal LED, the radiation emitted by it is invisible to the human eye. There are different types of infrared transmitters depending on their wavelengths, output power and response time. Infrared receivers are also called as infrared sensors as they detect the radiation from an IR transmitter. IR receivers come in the form of photodiodes and phototransistors. Infrared Photodiodes are different from normal photo diodes as they detect only infrared radiation. Different types of IR receivers exist based on the wavelength, voltage, package, etc. When used in an infrared transmitter – receiver combination, the wavelength of the receiver should match with that of the transmitter The principle of an IR sensor working as an Object Detection Sensor can be explained using the following figure. An IR sensor consists of an IR LED and an IR Photodiode; together they are called as Photo – Coupler or Opto – Coupler. IR Sensors can be used in Night Vision Devices, Infrared Astronomy, Infrared tracking.

Block Diagram

Connections: 

Connect the Power cable to Raspberry_Pi



Connect the Raspberry_Pi through Remote Desktop



Connect the Data Pin of Sensor to GPIO 33rdpin of Raspberry_Pi



Connect the Ground pin of sensor to Ground Pin of Raspberry_Pi



Connect the Vcc Pin of Sensor to 5V Vcc Pin of Raspberry_Pi

www.techienest.in

140

[email protected]



Connect the Data Pin of Sensor to GPIO 33rd pin of Raspberry_Pi



Connect the Ground pin of sensor to Ground Pin of Raspberry_Pi



Connect the Vcc Pin of Sensor to 5V Vcc Pin of Raspberry_Pi

And make sure that there is no wrong connections made Open Python GUI and write the following code in New file Program import RPi.GPIO as I import time I.setwarnings(False) I.setmode(I.BOARD) ir1 = 33 ir2 = 31 I.setup(ir1,I.IN) I.setup(ir2,I.IN) while True: x = I.input(ir1) y = I.input(ir2) if x == 1: print "Sensor-1 Detected" if y == 1: print "Sensor -2 Detected" if x==1 and y==1: print "Both Sensors are Detected" if x==0 and y==0: print "Both Sensors are Not Detected"

Steps To Build Program: Step 1: Open Python GUI Step 2: Press Ctrl+O and select the file Step 3: Press F5 Step 4:Now your Sensors will Start Working.

3.3.2 Ultrasonic Sensor 3.3.2.1 Introduction Ultrasonic are transducers that convert ultrasound waves to electrical signals or vice versa. Those both transmit and receive may also be called ultrasound transceivers. Many ultrasound sensors besides being sensors are indeed transceivers because they can both sense and transmit. These devices work on principle similar to that of transducers used in radar and sonar systems, which evaluate attributes of a target by interpreting the echoes from radio or sound waves, respectively. www.techienest.in

141

[email protected]

Active ultrasonic sensors generate high frequency sound waves and evaluate the echo which is received back by the sensor, measuring the time interval between sending the signal and receiving the echo to determine the distance to an object. Passive ultrasonic sensors are basically microphones that detect ultrasonic noise that is present under certain conditions, convert it to an electrical signal, and report it to a computer. Systems typically use a transducer which generates sound waves in the ultrasonic range, above 18khzby turning electrical energy into sound, then upon receiving the echo turn the sound waves into electrical energy which can be measured and displaed.

Connections:  Connect the Power cable to Raspberry_Pi  Connect the Raspberry_Pi through Remote Desktop.  Connect the Trig Pin of Ultrasonic sensor to GPIO 23rd pin of Raspberry_Pi  Connect the Echo Pin of Ultrasonic sensor to GPIO 24th pin of RaspberrPi  Connect the Vcc Pin of Ultrasonic sensor to +5v Supply pin of Raspberry_Pi  Connect the Ground pin Ultrasonic Sensor to Ground pin of Raspberry_Pi Make sure that no wrong connection made. Open Python GUI and write the following code Program import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) TRIG = 23 ECHO = 24 print "Distance Measurement In Progress" GPIO.setup(TRIG,GPIO.OUT) GPIO.setup(ECHO,GPIO.IN) GPIO.output(TRIG, False) print "Waiting For Sensor To Settle" time.sleep(1) while(1): www.techienest.in

142

[email protected]

GPIO.output(TRIG, True) time.sleep(0.00001) GPIO.output(TRIG, False) while GPIO.input(ECHO)==0: pulse_start = time.time() while GPIO.input(ECHO)==1: pulse_end = time.time() pulse_duration = pulse_end - pulse_start distance = pulse_duration * 17150 distance = round(distance, 2) print "Distance:",distance,"cm" time.sleep(0.2) GPIO.cleanup()

Steps To Build Program: Step 1: Open Python GUI Step 2: Press Ctrl+O and select the file Step 3: Press F5 Step 4: Now your sensor will Start Working.

3.4 LCD (Liquid Crystal Display) 3.4.1 Introduction Microcontroller is a wonderful piece of engineering and it can do many things (with the help of some great programming), but it is still a black box. As it will not show your effort i.e. your output means that you need to interface some output devices to see your results. The same we did using LEDs, now we are going to interface another output device named as LCD (Liquid Crystal Display). So now is probably a good time to talk about the pins on the LCD. The most basic of the pins are the power pins for the display to be able to function in the first place. There is a VDD pin for 5 volts and a VSS pin for ground. There is a V0 pin for the adjustment of the LCD contrast. Some LCDs even have an LED backlight and are generally the last two pins. Just like the microcontroller, the LCD has a row of 8 pins to serve as its port. The pins that serve as its port is D0, D1, D2, D3, D4, D5, D6 and D7. These pins are generally used to pass information into the LCD, but it can also be set to pass information back to the microcontroller. Two types of information can be passed through these pins: data to display on the LCD screen, or control information that is used to do things such as clearing the screen, controlling the cursor position, turning the display on or off, etc. These data pins are connected to the pins of the desired port on the microcontroller. For example, if you wanted the LCD to be connected to PORTB, the D0 would be connected to Pin0 of Port B, and: D1-PortB Pin1, D2-PortB Pin2, D3-PortB Pin3, D4-PortB Pin4, D5PortB Pin5, D6-PortB Pin6 and D7-PortB Pin7. This way, there is a pin to pin consistency, and if you pass a character in the form of a hexadecimal number, the LCD will receive it in the proper way. If not, there will unexpected results, unless you use a unique form of byte structure, but don't let that get in www.techienest.in

143

[email protected]

your way. There are other pins on the LCD that help the LCD accept information, and tell the LCD to receive a character or control, or control the read or write (input or output) function of the pins. The pin on the LCD that is responsible for the read and write state is labeled R/W. The pin on the LCD that is responsible for whether the information sent is a character or a control is the RS pin (Register Select). And the pin that helps the LCD accept information is called the EN pin (Enable). Checking if the LCD is busy (If you try to display a character to the LCD while the LCD is busy, then the LCD will just ignore the character and it will not be displayed). We set the port to receive data on the microcontroller (Data direction as input). We put the LCD in read mode (RW on). We put the LCD in command mode (RS off). And the port now magically contains the data from the LCD (D7 pin will be ON if the LCD is busy and OFF if the LCD is not busy). Send a command to the LCD We check to see if the LCD is busy (Perform the steps in #1 above). We set the port direction as output so we can send information to the LCD. We turn RW off so we can write. We turn RS off for command mode. We fire up the data lines with the command we want (simply making the port equal to a number that associates to a specific command). We turn on the enable and then turn it off. The LCD will magically perform the command. There are three basic things you will want to do with an LCD for the proper functioning (more advanced functions can be performed with these three fundamental routines): (1) to make sure the LCD is not busy; (2) Control the LCD's cursor, or display function; and (3) Write a character to the LCD for it to display. 3.4.2 Interfacing with Alphanumeric LCD Now let’s play with display. As have learnt how to give ‘0’ (gnd) and ‘1’ (VCC) on the I/O pins of the microcontroller, it won’t be difficult in interfacing LCD with a microcontroller. As we can see from LCD pin diagram there are 8 data pins means data can be transfer from these pins. There are two Hitachi microcontrollers named as HT44780 inside the 16*2 LCD. They control the entire event occurring inside the LCD and its complete working. The data from the microcontroller to microcontroller inside www.techienest.in

144

[email protected]

the LCD can be transferred in two ways; either data can travel using all data pins or using 4 data pins only. It’s not a panic issue, now let’s see how? 1. 8 bit mode 2. 4 bit mode 8 bit mode: For better understanding of both the concepts let’s take an example, as we can see there is a block diagram shown below. It shows the LCD attached to the microcontroller. There are four ports available in our microcontroller as I/O ports; any one of these can be used for connecting the LCD with the microcontroller. We have a maximum of 8 bit port available with us in microcontroller. So we’ll be using two ports of our microcontroller (as we have three control pins (RS, R/W and EN) while 8 data pins, so a total of 11 pins if all the power pins are permanently connected in the system). It should be noted that all control bits and data bits, should be synchronized otherwise there might be any problem in displaying character. There are certain things which should be kept in mind whenever we interface LCD, such as meaning of each control pin and when to use them. There are three control pin in this LCD module (RS, R/W and EN), which we have to control through our programs. There are two things you should tell LCD ‟s microcontroller before it displays a character. Thinking commands? Let’s take an example; when we start our talk with someone, the first thing we do is to say ‘’Hello’’; this informs the other person that I want to share something with him/her. After this has been shared between the two persons, we then start sharing other things. In the similar manner, the two microcontrollers: our development board microcontroller and the microcontroller inside the LCD. Need to share some signals or command before they can actually start data transfer between each other. The information shared before starting any display includes: 1. A 16*4 LCD can be used in three modes: 16*1, 16*2 and 16*4. Similarly other LCD can also be used in different modes. So before displaying any character we need to tell the Hitachi’s microcontroller about the mode in which we want the microcontroller to operate the LCD. 2. Whether we want the backlight ‘ON or OFF’. 3. The most important is the mode of data transfer: 8-bit mode or 4 bit mode. 4. The starting location (as from home position means from 0x80 location), for displaying the first character. This sharing of signals between the two microcontroller is referred as LCD initialization and this is the first step in interfacing a LCD with any microcontroller.

www.techienest.in

145

[email protected]

Block Diagram Connections: 

Connect the power cable to Raspberry_Pi



Connect the Raspberry_Pi through Remote Desktop



Connect the Vss Pin of LCD to Ground Pin of Raspberry_Pi



Connect the Vdd Pin of LCD to +5v Pin of Raspberry_Pi



Connect the Vee Pin of LCD to Ground pin of Raspberry_Pi



Connect the RS Pin of LCD to GPIO 29th pin of Raspberry_Pi



Connect the R/W pin of LCD to Ground pin of Raspberry_Pi



Connect the E pin of LCD to GPIO 31st pin of Raspberry_Pi



Connect the D0 pin of LCD to GPIO 11th pin of Raspberry_Pi



Connect the D1 pin of LCD to GPIO 12th pin of Raspberry_Pi



Connect the D2 pin of LCD to GPIO 13th pin of Raspberry_Pi



Connect the D3 pin of LCD to GPIO 15th pin of Raspberry_Pi



Connect the D4 pin of LCD to GPIO 32 pin of Raspberry_Pi



Connect the D5 pin of LCD to GPIO 33 pin of Raspberry_Pi



Connect the D6 pin of LCD to GPIO 35th pin of Raspberry_Pi



Connect the D7 pin of LCD to GPIO 37th pin of Raspberry_Pi

Make sure that no wrong connection made otherwise LCD will won’t work www.techienest.in

146

[email protected]

Open Python GUI and write the following code. Program import RPi.GPIO as IO import time IO.setwarnings(False) IO.setmode(IO.BOARD) pin1 = 11 pin2 = 12 pin3 = 13 pin4 = 15 pin5 = 32 pin6 = 33 pin7 = 35 pin8 = 37 rs = 29 en = 31 IO.setup(rs,IO.OUT) IO.setup(en,IO.OUT) IO.setup(pin1,IO.OUT) IO.setup(pin2,IO.OUT) IO.setup(pin3,IO.OUT) IO.setup(pin4,IO.OUT) IO.setup(pin5,IO.OUT) IO.setup(pin6,IO.OUT) IO.setup(pin7,IO.OUT) IO.setup(pin8,IO.OUT) def LCD(pin): if(pin&0x01 == 0x01): IO.output(29,1) else: IO.output(29,0) if(pin&0x02 == 0x02): IO.output(11,1) else: IO.output(11,0) if(pin&0x04 == 0x04): IO.output(31,1) else: IO.output(31,0) if(pin&0x08 == 0x08): IO.output(12,1) else: IO.output(12,0) if(pin&0x10 == 0x10): IO.output(32,1) else: IO.output(32,0) if(pin&0x20 == 0x20): www.techienest.in

147

[email protected]

IO.output(33,1) else: IO.output(33,0) if(pin&0x40 == 0x40): IO.output(35,1) else: IO.output(35,0) if(pin&0x80 == 0x80): IO.output(37,1) else: IO.output(37,0) deflcd_command (command): pin=(command & 0xf0) LCD(pin); IO.output(rs,0) IO.output(en,1) time.sleep(0.05) IO.output(en,0) pin=0 LCD(pin); pin=((command<<4)& 0xf0) LCD(pin); IO.output(rs,0) IO.output(en,1) time.sleep(0.05) IO.output(en,0) pin=0 LCD(pin);

deflcd_data (character): pin=(character & 0xf0) LCD(pin); IO.output(rs,1) IO.output(en,1) time.sleep(0.05) IO.output(en,0) pin=0 LCD(pin); pin=((character<<4) & 0xf0) LCD(pin); IO.output(rs,1) IO.output(en,1) time.sleep(0.05) IO.output(en,0) pin=0 LCD(pin); deflcd_init(): www.techienest.in

148

[email protected]

lcd_command(0x02) lcd_command(0x28) lcd_command(0x0E) lcd_command(0x06) deflcd_String(s,pos): l = list(s) size = len(s) lcd_init() lcd_command(pos) print("Hi") for i in range(0,size): lcd_data(ord(l[i])) #time.sleep(0.25) #lcd_command(0x01) #IO.cleanup()

deflcd_Number(num,pos): lcd_String(str(num),pos) lcd_String("357",0x85) #IO.cleanup() lcd_init() print 'lcdinit' time.sleep(1) lcd_command(0x85) lcd_data(0x41) IO.cleanup() print 'lcdgtbghbg' Steps To Build Program: Step 1: Open Python GUI Step 2: Press Ctrl+O and select the file Step 3: Press F5 Step 4:Now your LCD will Start Working. 3.4.3 LCD Display as User Input Program import lcd as a import time a.lcd_init() print 'lcdinit' time.sleep(1) deflcd_clr(): a.lcd_command(0x01) time.sleep(0.01) www.techienest.in

149

[email protected]

s=raw_input('enter a string') deflcd_string(strm): l=len(strm) for i in range(0,l): a.lcd_data(ord(strm[i])) while(1): for k in range(0x80,0x8f,1): a.lcd_command(k) time.sleep(0.01) lcd_string(s) lcd_clr() a.lcd_command(0x04) for j in range(0xcf,0xc0,-1): a.lcd_command(j) time.sleep(0.01) lcd_string(s) lcd_clr() a.lcd_command(0x06) Steps To Build Program: Step 1: Open Python GUI Step 2: Press CTRL+N and copy the above program Step 4: Press Ctrl+O and select the file Step 5: Press F5 Step 6:Now your LCD will Start Working and it will print the text. 3.4.4 LCD Display as User import lcd as a import time a.lcd_init() print 'lcdinit' time.sleep(1) a.lcd_command(0x01) time.sleep(0.01) a.lcd_command(0x80) a.lcd_string("Welcome 2 TechieNest",0x80) a.lcd_command(0xc0) a.lcd_string("Hello User",0xc0) Steps To Build Program: Step 1: Open Python GUI Step 2: Press CTRL+N and copy the above program Step 4: Press Ctrl+O and select the file Step 5: Press F5 Step 6: Now your LCD will Start Working and it will print the text. www.techienest.in

150

[email protected]

3.5 MOTORS 3.5.1 Introduction An electric motor is an electromechanical device that converts electrical energy into mechanical energy. Most electric motors operate through the interaction of magnetic fields and Current -carrying conductors to generate force.

These are the following type of motors: 

DC motor



Stepper motor



Servo motor



Universal motor

DC Motor A DC motor is an electric motor that runs on direct current (DC) electricity. DC motor has simply two wires after giving them DC supply. It will rotate in one direction and its direction can be changed by changing the polarity. DC motors can operate directly from rechargeable batteries, providing the motive power for the first electric vehicles. Principle of Operation In any electric motor, operation is based on simple electromagnetism. The internal configuration of a DC motor is designed to harness the magnetic interaction between a current-carrying conductor and an external magnetic field to generate rotational motion. We don’t connect DC motor with microcontroller directly because to run motor needs some more current than the output of microcontroller. To motor drive we need current but for the motor speed we need voltage. So to connect motor with microcontroller we need an interfacing IC which is also called driver IC. There are different types of driver IC like L293D, L298D, ULN2803 and so many…. We use L293D as a driver IC to interface with Raspberry_Pi L293D-The L293D is ideal for controlling the forward/reverse/brake motions of small DC motors controlled by a microcontroller such as an AVR, 8051 microcontroller. The L293D is a quadruple pushpull 4 channel driver capable of delivering 600mA per channel. One l293D is capable of driving two DC motor at a time. Features: 

600mA output current capability per driver.



Wide supply voltage range 4.5 volt to 36 volt.

www.techienest.in

151

[email protected]



Separate input-logic supply

PIN diagram: It is a 16 pin IC in which four input pins and four output pins. This single IC has a property to drive two DC motor at a time. If we give 1stpin of this Ic to Vcc then left part of this IC is enable and if we give Vcc to pin no 9 then right part of this IC is enable. And if we provide both pins 1& 9 Vcc then both sides input are enable.

Block Diagram

Connections: 

Connect the power cable to Raspberry_Pi.



Connect the Raspberry_Pi through Remote Desktop.



Connect +9v battery L293D Motor Drive.



Connect Motor Driver M1 1st input to 38th Pin of Raspberry_Pi.



Connect Motor Driver M1 2nd input to 40th pin of Raspberry_Pi.



Connect Motor Driver M2 1st input to 16th Pin of Raspberry_Pi.



Connect Motor Driver M2 2nd input to 18th pin of Raspberry_Pi.

Make sure that No wrong connections made otherwise Motors will rotate in wrong direcions. Open Python GUI and copy the following code. Program import time import RPi.GPIO as m m.setwarnings(False) m.setmode(m.BOARD) m.setup(38,m.OUT) m.setup(40,m.OUT) m.setup(16,m.OUT) m.setup(18,m.OUT) while(1): m.output(38,1) m.output(40,0) www.techienest.in

152

[email protected]

m.output(16,1) m.output(18,0) time.sleep(5) m.output(38,0) m.output(40,0) time.sleep(1) m.output(16,0) m.output(18,0) time.sleep(5)

Steps To Build Program: Step 1: Open Python GUI Step 2: Press Ctrl+O and select the file Step 3: Press F5 Step 4: Now your Motors will Start Working.

3.6 RFID 3.6.1 Introduction For many of us, using a key to start a car, a card to access a building or room, using ski lifts on a winter sports holiday and validating a bus or underground ticket have become part of our daily routine. Without always realising it, we use automatic data capture technology that relies on radio-frequency electromagnetic fields. This technology is known as Radio-Frequency Identification or RFID. Just as people use RFID as they go about their daily lives, objects also use this technology, as they transit from manufacture to storage and finally the point of sale. Like us, they also carry RFID tags. The difference between objects and ourselves is that they don’t “voluntarily” present their RFID tag or card when asked. These tags are therefore read in very different conditions and often require greater detection distances. RFID (Radio Frequency Identification) can be defined as follows: Automatic identification technology which uses radio-frequency electromagnetic fields to identify objects carrying tags when they come close to a reader. Data (identification number for instance) included in the electronic chip of the RFID label can be collected by the reader. This reader can also change the content of the label’s memory. However, RFID cannot be reduced to one technology. RFID uses several radio frequencies and many types of tag exist with different communication methods and power supply sources. RFID tags generally feature an electronic chip with an antenna in order to pass information onto the interrogator (also known as a base station or more generally, reader). The assembly is called an inlay and is then packaged to be able to withstand the conditions in which it will operate. This finished product is known as a tag, label or transponder. The information contained within an RFID tag’s electronic chip depends on its application. It may be a unique identifier (UII, Unique Item Identifier or EPC code, Electronic Product Code, etc.). Once this www.techienest.in

153

[email protected]

identifier has been written into the electronic circuit, it can no longer be modified, only read. (This principle is called WORM Write Once Read Multiple). Some electronic chips have another memory in which users can write, modify and erase their own data. These memories vary in size from a few bits to tens of kilobits. 3.6.2 RFID's History: 1940 RFID was first used during World War II to identify aeroplanes (IFF: Identify Friendly Foe). The objective was to use the aeroplane's radar signal to read an identification number in order to identify whether they were allies or enemies. 1970 During the 1960-70s, RFID systems were still considered a secret technology used by the army to control access into sensitive areas (nuclear plants etc.). 1980 Technological developments lead to the creation of passive tags. This technology meant we no longer needed the energy to be embedded into the tag. Therefore the price of the tag and its maintenance could be significantly reduced. 1990 Standardization for the interoperability of RFID equipment began. 1999 The Massachusetts Institute of Technology (MIT) created the Auto-ID center - a research center specialized in automatic identification (including RFID). 2004 The MIT Auto-ID center became the global EPC, an organism in charge of promoting the EPC (Electronic Product Code) standard.

From 2005 RFID technologies are now widely used in almost all industrial sectors (aerospace, automotive, logistics, transport, health, life, etc.).. ISO (International Standard Organization) took part in establishing technical and applicative standards that let to have a high degree of interoperability or interchangeability. From Identification to RFID Electronic identification is divided into two parts: -

Contact identification Contactless identification

www.techienest.in

154

[email protected]

Block Diagram

a. Contact identification Refers to systems with communication ensured by electric contacts. The two main examples of contact identification are: -

Memory: includes embedded memory functions on modules with different forms and sizes. Smart cards: the most famous smart cards are credit cards, SIM Card or social security card.

b. Contactless identification We can divide contactless identifications into three parts: Line of sight - this kind of link requires a direct vision between the identifier and the reader (laser, CCD Camera etc.) The most famous technology is linear bar code and 2D codes (PDF417, QR Code, etc.). The OCR (Optical Character Recognition) is also widely used (scan MRZ (Machine Readable Zone) on passports or National Identity Card). Infrared link - this kind of link allows a high rate of data, a high directivity and a great range. These systems also require direct visibility. Radio-frequency links - this kind of link enables communication between the identifer and an interrogator, without requiring direct visibility. It is also possible to control the simultaneous presence of various identifiers. www.techienest.in

155

[email protected]

3.6.3 RFID tags classification A first classification for RFID tags is based on the presence or absence of an electronic chip. RFID SAW tags (Surface Acoustic Wave) do not have integrated circuits. Today they only represent a small part of the market (a few %). They are read-only transponders and do not include embedded energy. They are also called RF barcode. 1 bit RFID tags are passive systems with capacitive diodes, called "1 bit transponders ". This bit indicates if the tag is present of not in the interrogator's field of action. They are widely used as anti-theft system.

Block Diagram

PROJECTS:   

LFR Smart Bin Accident Detector

 Smart Ticket

Networking With Linux  

Basics of Linux platform and its command line Basic networking with Linux

1. ifconfig ifconfig (interface configurator) command is use to initialize an interface, assign IP Address to interface and enable or disable interface on demand. With this command you can view IP Address and Hardware / MAC address assign to interface and also MTU (Maximum transmission unit) size. # ifconfig eth0 192.168.50.5 netmask 255.255.255.0

To enable or disable specific Interface, we use example command as follows. www.techienest.in

156

[email protected]

Enable eth0

# ifup eth0

Disable eth0

# ifdown eth0

2. PING Command PING (Packet INternet Groper) command is the best way to test connectivity between two nodes. Whether it is Local Area Network (LAN) or Wide Area Network (WAN). Ping use ICMP (Internet Control Message Protocol) to communicate to other devices. You can ping host name of ip address using below command. 3. TRACEROUTE Command traceroute is a network troubleshooting utility which shows number of hops taken to reach destination also determine packets traveling path. Below we are tracing route to global DNS server IP Address and able to reach destination also shows path of that packet is traveling. 4. NETSTAT Command Netstat (Network Statistic) command display connection info, routing table information etc. To displays routing table information use option as -r. 5. DIG Command Dig (domain information groper) query DNS related information like A Record, CNAME, MX Record etc. This command mainly use to troubleshoot DNS related query. 6. NSLOOKUP Command nslookup command also use to find out DNS related query. The following examples shows A Record (IP Address) of tecmint.com. 7. ROUTE Command route command also shows and manipulate ip routing table. To see default routing table in Linux, type the following command. Route Adding # route add -net 10.10.10.0/24 gw 192.168.0.1 Route Deleting # route del -net 10.10.10.0/24 gw 192.168.0.1 Adding default Gateway # route add default gw 192.168.0.1 8. HOST Command host command to find name to IP or IP to name in IPv4 or IPv6 and also query DNS records. 9. ARP Command ARP (Address Resolution Protocol) is useful to view / add the contents of the kernel’s ARP tables. To see default table use the command as. # arp -e Address 192.168.50.1 www.techienest.in

HWtypeHWaddress ether

Flags Mask

00:50:56:c0:00:08

C 157

Iface eth0 [email protected]

10. ETHTOOL Command ethtool is a replacement of mii-tool. It is to view, setting speed and duplex of your Network Interface Card (NIC). You can set duplex permanently in /etc/sysconfig/network-scripts/ifcfg-eth0 with ETHTOOL_OPTS variable. 11. IWCONFIG Command iwconfig command in Linux is use to configure a wireless network interface. You can see and set the basic Wi-Fi details like SSID channel and encryption. You can refer man page of iwconfig to know more 12. HOSTNAME Command hostname is to identify in a network. Execute hostname command to see the hostname of your box. You can set hostname permanently in /etc/sysconfig/network. Need to reboot box once set a proper hostname. 13. GUI tool system-config-network Type system-config-network in command prompt to configure network setting and you will get nice Graphical User Interface (GUI) which may also use to configure IP Address, Gateway, DNS etc. as shown below image.

Basic Linux Commands 

General Commands Command apt-get update

apt-get upgrade Clear Date Find / -nameexample.txt nano example.txt Poweroff raspi-config Reboot shutdown -h now shutdown -h 01:22 Startx

www.techienest.in

Description Synchronizes the list of packages on your system to the list in the repositories. Use it before installing new packages to make sure you are installing the latest version. Upgrades all of the software packages you have installed. Clears previously run commands and text from the terminal screen. Prints the current date Searches the whole system for the file example.txt and outputs a list of all directories that contain the file Opens the file example.txt in the Linux text editor Nano. To shutdown immediately. Opens the configuration settings menu. To reboot immediately. To shutdown immediately. To shutdown at 1:22 AM. Opens the GUI (Graphical User Interface).

158

[email protected]



Networking and Internet Commands Command

Ifconfig Iwconfig iwlist wlan0 scan iwlist wlan0 scan | grep ESSID Nmap

Ping

wgethttp://www.website.com/exa mple.txt 

Description To check the status of the wireless connection you are using (to see if wlan0 has acquired an IP address). To check which network the wireless adapter is using. Prints a list of the currently available wireless networks. Use grep along with the name of a field to list only the fields you need (for example to just list the ESSIDs). Scans your network and lists connected devices, port number, protocol, state (open or closed) operating system, MAC addresses, and other information. Tests connectivity between two devices connected on a network. For example, ping 10.0.0.32 will send a packet to the device at IP 10.0.0.32 and wait for a response. It also works with website addresses. Downloads the file example.txt from the web and saves it to the current directory.

System Information Commands

Command cat /proc/meminfo cat /proc/partitions

Description Shows details about your memory. Shows the size and number of partitions on your SD card or hard drive. cat /proc/version Shows you which version of the Raspberry_Pi you are using. df –h Shows information about the available disk space. df / Shows how much free disk space is available. dpkg – –get–selections | grep XXX Shows all of the installed packages that are related to XXX. dpkg – –get–selections Shows all of your installed packages. Free Shows how much free memory is available. hostname -I Shows the IP address of your Raspberry_Pi. Lsusb Lists USB hardware connected to your Raspberry_Pi. UP key Pressing the UP key will print the last command entered into the command prompt vcgencmdmeasure_temp Shows the temperature of the CPU. vcgencmdget_mem arm Shows the memory split between the CPU and GPU. &&vcgencmdget_memgpu Hopefully this list of commands will make navigating Linux on your Raspberry_Pi more efficient and enjoyable. If you have any other commands that you use a lot.

www.techienest.in

159

[email protected]

www.techienest.in

160

[email protected]

You can reach

TechieNest for

VOCATIONAL COURSES

1-6 Months Internship Regular Industrial Training Project based training Winter industrial training Summer industrial training Faculty Development Programs In-Campus training (1 Week/ 15 Days/ 30 Days)

MANUFACTURING-TESTING & DEVELOPMENT

Project Development (both H/W & S/W based) Minor Project Major Project PCB Designing and Manufacturing Supplying Electronic components (For Projects and Laboratory purpose)

CAREER GUIDANCE BY INDUSTRY EXPERTS

www.techienest.in

161

[email protected]

Head OfficePlot No. 262, Muktanand Nagar, Opp. Pooja Tower Gopalpura Mode, Jaipur (302018),Rajasthan (India) +91- 9251494002, +91-9251094002

Contact for workshop- +91-7340033091

Research & Development162| Training | [email protected] | Project

www.techienest.in

Related Documents

Iot
May 2020 14
Iot Applications
October 2019 25
Iot-connect.pdf
December 2019 21
Iot Regular.pdf
August 2019 24
Exm Iot
October 2019 18
Iot Research.docx
December 2019 12

More Documents from "mehol sharma"

Progress Report Format_2
August 2019 29
Last.pdf
May 2020 4
Emami.docx
May 2020 4