22EEE136 PythonLabManualFinal

Download as pdf or txt
Download as pdf or txt
You are on page 1of 68

LABORATORY MANUAL

FOR
Python Programming for Electrical Engineers
[22EEE136]

III Semester

2023-24

Department of Electrical and Electronics Engg.

B.N.M. Institute of Technology


An Autonomous Institution under VTU

Name: _______________________
Branch/Batch: _________________
USN No.: _____________________
PREFACE

The best way to teach a computer programming language is by examples, and the only way to learn
programming is by doing. The aim of the course “Python Programming for Electrical Engineers” is
is to introduce the concepts of python programming language through project based learning (PBL).
Basic concepts are explained by examples and a variety of programming exercises are provided for
students to practice. The goal is to teach problem solving and programming in a broad context using
a wide variety of interesting examples and exercises.
This practical manual will be helpful for students of Electrical and Electronics Engineering streams
from the point of view of applying the python program to solve problems in the field of Electrical
and Electronics.
B.N.M. Institute of Technology
An Autonomous Institution Under VTU

Approved by AICTE, Affiliated to VTU, Accredited as Grade A Institution by NAAC.

All UG branches – CSE, ECE, EEE, ISE & Mech.E accredited by NBA for academic years 2018-19 to 2021-22 & valid upto
30.06.2022

VISION
• To be one of the premier Institutes of Engineering and Management education in the country.
MISSION
• To provide Engineering and Management education that meets the needs of human resourcesin
the country.

• To develop leadership qualities, team spirit, and concern for environment in students.

DEPARTMENT OF ELECTRICAL & ELECTRONICS ENGINEERING


VISION

To be a premier department for education in Electrical and Electronics Engineering in Karnataka


state, moulding students into professional Engineers.
MISSION
❖ To provide teaching/learning facilities in Electrical and Electronics Engineering for easy
adaptation to industry and higher learning.
❖ Provide environment for self-learning to meet the challenges of changing technology and
inculcate team spirit and leadership qualities to succeed in professional career.
❖ Empathize with the societal needs and environmental concerns in Electrical & Electronics
engineering practices.

PROGRAM EDUCATIONAL OBJECTIVES (PEO)

After 2 to 3 years of graduation, the student will have the ability to:
• Analyze, design and propose solutions in the field of Electrical and Electronics Engineering
and adapt to changes in technology by self-learning.
• Work effectively as an individual or as an entrepreneur and exhibit leadership qualities in a
team to meet the goals of the organization.
• Work with professionalism and concern for environment to meet the societal needs.
• Excel in professional career by achieving higher learning and contribute to technological
innovations.
.
GENERAL
INSTRUCTIONS

Do’s
1. Confirm to the academic discipline of the department.
2. Students have to come to the laboratory with proper dress code and ID Cards.
3. Enter your credentials in the laboratory attendance register.
4. Ensure the uniqueness with respect to the methodology adopted for carrying out the
experiments.
5. After completion of programming exercises, students have to submit their completed
records to the faculty of their lab within 4 days from the completion of the experiment.
6. Come properly prepared for your experiments as per the list of experiments.
7. Shutdown the machine once you are done using it.
8. If you miss any practical class due to unavoidable reasons, intimate the staff in charge
and do the missed experiment in the repetition class.
9. Such of those students who fail to put in a minimum of 85% attendance in the
laboratory class will run the risk of not being allowed for the Practical Examination.

Dont's
1. Usage of mobile phones is strictly prohibited.
2. Do not remove anything from the computer laboratory without permission.
3. Do not touch, connect or disconnect any plug or cable without your faculty/laboratory
technician’s permission.
Course objectives:
The students will be able to

❖ To know the basics of algorithmic problem solving using python.

❖ To develop Python programs with conditionals, loops, and functions.

❖ To use Python data structures –- lists, tuples, dictionaries.

❖ To write Python programs for problem solving and analysis in the field of Electrical

Engineering.
❖ To develop programs using Python for embedded applications

Pre-requisites:
Fundamental knowledge of computer systems, Basic knowledge of C Programming, Basic
Electrical Engineering, Electrical Circuit Analysis, Analog and Digital Circuits
Course outcomes
Lab Course outcomes: At the end of the course the student will be able to:

❖ Develop applications using Python Programming

❖ Develop programs with different data types utilizing loops, decision-making

statements, and functions.


❖ Evaluate the characteristics of the machines and transformer parameters using Python.

❖ Develop a python program for linear circuits and digital circuits.

❖ Develop a Python program to interface sensors, actuators with a Python supported

microcontroller board.
❖ Communicate effectively about the chosen problem

❖ Write technical report for the chosen problem


Sl. Experiments
No.

Installation Guide, Operators, Datatypes, and Basic I/P and O/P operations.
1. Write a python program to convert temperature to and from Celsius to Fahrenheit.
1 2. Write a Python program to compute the distance between two points taking input from the
user.
Decision Making and Loop Statements, strings
1. Write a program to create, concatenate and print a string and access substring from a given
string.
2
2. Write a python program to print prime numbers less than 50.
3. Develop a python code to design and realize Combinational/Sequential logic circuits.
Lists, Tuples, Dictionaries.
1. Write a python program to create a list and perform the following methods 1) insert() 2)
remove() 3) append() 4) len() 5) pop() 6) clear()
3 2. Write a program to Create a tuple and perform the following methods 1) Add items 2)
len() 3) check for item in tuple 4)Access items
3. Write a program to create a dictionary and apply the following methods 1) Print the
dictionary items 2) access items 3) use get() 4)change values 5) use len()
Functions, Modules
1. Write a function to compute GCD, LCM of two numbers. Each function shouldn’t exceed
4 one line.
2. Write a Python program to define a module to find Fibonacci Numbers and import the module
to another program.
Error Handling, Numpy and Matplotlib modules
5 1. Write a program in Python to handle user-defined exception for given problem.
2. Write a python program to perform AC Analysis
6 Introduction to PySpice (Python, Installation Guide)
Write a program to perform DC Nodal Analysis using Pyspice(Python)
7 Write a program to plot the Characteristics of the Induction Motor
8 Write a python code plot the efficiency of Transformer at different loads
Introduction to RaspberryPi, Installation Guide
9 Write a program in Python to send digital data on Raspberry pi GPIO pins to blink LED, Fade an
LED and develop a simple traffic light system.
10 Connect the Digital/Analog I/O module and write a program in python to interface the various
Analog Sensors such as temperature sensors, Motion sensors.
11 Write a python script to control the speed of Servomotor.
12 Speed control of DC motor using Raspberry-pi and python
Sl. No. List of indicative Projects
1 Electricity Bill Management System using python
2 Smart Surveillance Monitoring System Using Raspberry PI and PIR Sensor:
3 Temperature based DC Fan Control
4 Autonomous Lane Detection Car Using Raspberry Pi and python
5 Raspberry Pi-based Automated Street Lighting System
6 Raspberry Pi based Battery monitoring system
7 Smart Energy meter using Raspberry pi and IoT
8 Text to Speech Converter using Python
9 Create an analog clock using python.
10 Power theft identification and alerting system using Raspberry Pi

Reference Book
1. Think Python: How to Think Allen B. Green Tea Press 2nd Edition,
Like a Computer Scientist Downey 2015
2. “Automate the Boring Stuff with Al Sweigart Starch Press 1st Edition,
Python” 2015
3 “Python programming using Reema Oxford university press 1st Edition,
problem solving approach” Thareja 2018
5 Introduction to programming Y. Daniel Pearson Publications 1st
using Python, Liang Edition,2017.
6 Python for Science and Hans-etter https://www.halvorsen.blog/do August,2020
Engineering Halvorsen cuments/programming/python/
7 Programming the Raspberry Pi, Simon McGraw Hill Third Edition
Getting Started with Python Monk
Web links and Video Lectures:
https://www.learnbyexample.org/python/
https://www.learnpython.org/
https://pythontutor.com/visualize.html#mode=edit
https://pyspice.fabrice-salvaire.fr/releases/v1.3/exampl es/index.html
https://nptel.ac.in/courses/106106145
https://www.w3schools.com/python/
Python Programming for Electrical Engineers (22EEE36)

Experiment number 1

Title: Installation Guide, Operators, Datatypes, and Basic I/P and O/P
operations.
AIM:

a) Write a program to perform different arithmetic operations on numbers in python.


b) Write a python program to convert temperature to and from Celsius to Fahrenheit.
Experiment 1:
1. a) Write a python program to convert temperature to and from Celsius
to Fahrenheit.
Description:
Celsius and Fahrenheit are the measurement units of Temperature. The conversion
formulas to convert temperature in degree Celsius to degree Fahrenheit and vice versa.
Celsius = (Fahrenheit – 32) * 5/9
Fahrenheit = (Celsius * 9/5) + 32
Algorithm:
Input: Temperature in Celsius (Fahrenheit)
Output: Temperature in Fahrenheit (Celsius)
Step 1: Start
Step 2: Input temperature in Celsius or Fahrenheit
Step 3: Convert the temperature in Celsius to Fahrenheit or vice versa using the appropriate
formula
Step 4: Print the results
Step 5: Stop
Program:
# To convert temperature in Celsius to fahrenheit
celsius = float(input("Enter temperature in celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("{0:5.2f} Celsius is same as {1:5.2f} Fahrenheit".format(celsius, fahrenheit))
# To convert temperature in Fahrenheit to celsius
fahrenheit = float(input("Enter temperature in fahrenheit: "))
celsius = (fahrenheit - 32) * 5/9
print("{0:5.2f} Fahrenheit is same as {1:5.2f} Celsius".format(fahrenheit, celsius))

Dept. of EEE, BNMIT 1


Python Programming for Electrical Engineers (22EEE36)

output
Enter temperature in celsius: 45
45.00 Celsius is same as 113.00 Fahrenheit
Enter temperature in fahrenheit: 118
118.00 Fahrenheit is same as 47.78 Celsius

Observations:

1. b) Write a python program to compute the distance between two points


taking input from the user.
Description:
Let (x1,y1) and (x2,y2) be the coordinates of points on the xy-plane. From Pythagorean
theorem, the distance between two points is calculated using the formulae:
𝑑 = √(𝑥2 − 𝑥1 )2 + (𝑦2 − 𝑦1 )2
To find the distance, use the method sqrt() which is defined in math module. To find the
power of a number, use ** operator.
Algorithm:
Input: x1, y1, x2 and y2
Output: Distance between two points.
Step1: Start
Step2: Import math module
Step3: Read the values of x1, y1, x2 and y2
Step4: Calculate the distance using the formulae math.sqrt( (x2 - x1)**2 + (y2 - y1)**2 )
and store the result in distance
Step5: Print distance
Step6: Stop
Program:
import math
x1=int(input("enter x1 : "))
y1=int(input("enter y1 : "))
x2=int(input("enter x2 : "))

Dept. of EEE, BNMIT 2


Python Programming for Electrical Engineers (22EEE36)

y1=int(input("enter y1 : "))
y2=int(input("enter y2 : "))
result= math.sqrt(((x2 - x1)**2) + ((y2-y1)**2))
print("distance between",(x1,y1),"and",(x2,y2),"is : ",result)

output

Observations:

Viva Questions:

1. Mention five benefits of using Python?


2. What are the supported data types in Python?
3. How to represent complex numbers in python?
4. Write a print statement to truncate the number 12.34567 to 2 decimal places?
5. What are reserved keywords?
6. List the bitwise operators in python?
7. What is the importance of type conversion?
8. What are the differences between Membership and Identity operators?
9. How to determine the type of a variable in Python?
10. How to write multiline statements in python?

Dept. of EEE, BNMIT 3


Python Programming for Electrical Engineers (22EEE36)

Experiment number 2

Title: Decision Making and Loop Statements, strings


AIM:

a) Write a program to create, concatenate and print a string and access substring from
a given string.
b) Write a python program to print prime numbers less than 50
c) Develop a python code to design and realize Combinational/Sequential logic
circuits.

2a. Write a program to create, concatenate and print a string and access
substring from a given string.
Description:

A string is a sequence of characters. Strings can be created by enclosing characters inside a


single quote or double-quotes. We can access individual characters using indexing and a
range of characters using slicing.
Joining two or more strings into a single one is called concatenation. The + operator does this
in Python. Simply writing two string literals together also concatenates them.
Algorithm:
Input: Two String objects
Output : Concatenated string and a substring
Step 1: Start
Step 2 : input two strings
Step 3: Print the strings entered
Step 4: Concatenate the strings using ‘+’ operator and print the result
Step 5 : Get a substring from a string using slicing operator and print the string
Step4 : Stop

Program:

s1=input("Enter first String : ")


s2=input("Enter second String : ")

Dept. of EEE, BNMIT 4


Python Programming for Electrical Engineers (22EEE36)

print("First string is : ",s1)


print("Second string is : ",s2)
print("concatenation of two strings :",s1+s2)
print("Substring of given string :",s2[1:5])

output:

Observations:

2b. Write a python program to print prime numbers less than 50

Description
A positive integer greater than 1 which has no other factors except 1 and the number itself is
called a prime number. 2, 3, 5, 7 etc. are prime numbers as they do not have any other factors.
But 6 is not prime (it is composite) since, 2 X 3=6.
If a number is exactly divisible by any number from 2 to (num//2+1), then the number is not
prime number, else it’s a prime number.
Algorithm

Step 1: Iterate from Number=2 to 50


Step 2: for each ‘Number’ Iterate from i= 2 to (number//2+1)
Step 3 : If the number is divisible by the inner loop iterator i ,go to step5 else go to step 2.
Step 4: the number is prime and print it.

Dept. of EEE, BNMIT 5


Python Programming for Electrical Engineers (22EEE36)

Step 5: Go to step 1
Step 6: Stop
Program

print("The prime numbers less than 50 are")


for Number in range (2, 51):
for i in range(2, (Number//2 + 1)):
if(Number % i == 0):
break
else:
print(Number, end = ' ')
output:

Observations:

2C: Develop a python code to

(a) Develop a python code to design and realize Full adder


(b) Develop a python code to design and realize S-R Latch
Description:
Full Adder : A Full Adder is a logical circuit that performs an addition operation on three
one-bit binary numbers. The full adder produces a sum of the three inputs and carry value.The
block diagram and truth table as shown below

Dept. of EEE, BNMIT 6


Python Programming for Electrical Engineers (22EEE36)

The sum and carry-out are given by the expressions


sum = c-in xor ( a xor b )
c-out= a b + b c-in + a c-in
Algorithm:
Input: Three Binary bits A, B, and C
Output: Sum and Carry-out bits
Step1: input A, B, and C bits
Step2: Determine Sum and Carry-out using respective Boolean expression
Step3: Display the sum and carry-out bits
Step 4: Stop
Program:
# python program to implement full adder
A=1
B=1
C=1
Sum = C ^ (A ^ B)
C_Out = (A & B)| (B & C) | (C & A)
print("Sum = ", Sum)
print("C-Out = ", C_Out)
output:
Sum = 1

Dept. of EEE, BNMIT 7


Python Programming for Electrical Engineers (22EEE36)

C-Out = 1
Observations:

(b) Develop a python code to realize S-R Latch

#initialize the variables


S=1
R=1
prev_state=1
next_state=None
if (S==0) and (R==0):
next_state=prev_state
elif (S==1) and (R==0):
next_state=1
elif (S==0) and (R==1):
next_state=0
else:
print("invalid input provided")
next_state=None
if next_state != None:
print(f'The next state is {next_state}')
else:

Dept. of EEE, BNMIT 8


Python Programming for Electrical Engineers (22EEE36)

print("Unable to produce the next state, please provide valid inputs")


Output

Observations:

Viva Questions:

1. What is a slicing operator in Python? Explain with examples


2. Explain split() and join() functions in Python?
3. How will you convert a string to all lowercase?
4. Is indentation required in Python?
5. What is the purpose of else in if-elif ladder”
6. What does continue do in python?
7. What is the python syntax for ‘for’ loop?
8. What will be the output of the following Python code?

i=2
while True:
if i%3 == 0:
break
print(i)
i += 2

Dept. of EEE, BNMIT 9


Python Programming for Electrical Engineers (22EEE36)

Experiment number 3

Title: Lists, Tuples, Sets, and Dictionaries.


AIM:

a) Write a python program to create a list and perform the following methods 1) insert()
2) remove() 3) append() 4) len() 5) pop() 6) clear()
b) Write a program to Create a tuple and perform the following methods 1) Add items 2)
len() 3) check for item in tuple 4)Access items
c) Write a program to create a dictionary and apply the following methods 1) Print the
dictionary items 2) access items 3) use get() 4)change values 5) use len()

3 a) Write a python program to create a list and perform various


operations using the following methods 1) insert() 2) remove() 3)
append() 4) len() 5) pop() 6) clear().

Description:

Lists are used to store multiple items in a single variable. List items are ordered, changeable,
and allow duplicate values. List items are indexed, the first item has index [0], the second
item has index [1] etc. Lists are mutable and hence there are various methods and functions
defined to modify a list.

Algorithm:
Step 1: Start
Step 2: Create a list of numbers
Step 3: Perform insert, remove, append, pop, and clear operations on the list and also find
the length of the list. Print the results
Step 4: Stop
Program:
list_num=[4,6,9,12,43,91,60]
print("The list created is:")
print(list_num)

Dept. of EEE, BNMIT 10


Python Programming for Electrical Engineers (22EEE36)

# insert the value 14 at index 2


list_num.insert(2,14)
print("The updated list after insert operation")
print(list_num)
#remove the number 91 from list
list_num.remove(91)
print("The updated list after remove operation")
print(list_num)
#append the number 25 from list
list_num.append(25)
print("The updated list after append operation")
print(list_num)
#Find the length of the list
size=len(list_num)
print("Length of the list:",size)
#pop the last number from list
list_num.pop()
print("The updated list after pop operation")
print(list_num)
#pop the number at position 3 from list
list_num.pop(3)
print("The updated list after pop operation")
print(list_num)
#Clear all the elements from the list
list_num.clear()
print("The updated list after clear operation")
print(list_num)

Dept. of EEE, BNMIT 11


Python Programming for Electrical Engineers (22EEE36)

output:

Observations:

b) Write a program to create a tuple and perform the following methods


1) sort items 2) len() 3) check for item in tuple 4)Access items

Description:

A tuple is a collection that is ordered and unchangeable. Tuples are written with round
brackets. Tuple items are indexed, the first item has an index [0], the second item has an
index [1] etc. There are some methods and functions which perform different tasks in a tuple.
Few functions which are widely used on a tuple are cmp(), len(), max(), min(), tuple(),
index(), count(), sum(), any(), all(), sorted(), reversed() and so on.

Dept. of EEE, BNMIT 12


Python Programming for Electrical Engineers (22EEE36)

Algorithm:
Step 1 : Start
Step 2 : Create a tuple with name ‘color’
Step 3: sort the items in the tuple and print it
Step 4: Find the length of the tuple and print it
Step 5: Check for an item in the tuple and print the output
Step 6: Print each element of the tuple
Step 7 : Stop

Program:
colors=('White','Red','Green','Blue','Yellow','Brown','Orange')
sorted_colors=sorted(colors)
print(sorted_colors)
print("length of tuple:",len(colors))
color="Red"
if color in colors:
print(f"Yes {color} is found in {colors}")
print("The items(1-3) are", colors[1:4])
print(f'Fifth item in the tuple "colors" is {colors[4]}')

Output:

Observations:

Dept. of EEE, BNMIT 13


Python Programming for Electrical Engineers (22EEE36)

c) Write a program to create a dictionary and apply the following methods


1) Print the dictionary items 2) access items 3) use get() 4)change values
5) use len()
Description:

Python Dictionary is used to store the data in a key-value pair format. The dictionary is the
data type in Python, which can simulate the real-life data arrangement where some specific
value exists for some particular key. It is the mutable data-structure. The dictionary is
defined into element Keys and values.
• Keys must be a single element
• Value can be any type such as list, tuple, integer, etc.
In other words, a dictionary is the collection of key-value pairs where the value can be any
Python object. In contrast, the keys are the immutable Python object, i.e., Numbers, string,
or tuple.

Algorithm:
Step 1: Start
Step 2: Create a dictionary with the name ‘phone_book’
Step 3: print the keys and values in the dictionary
Step 4: access each item in the dictionary and print it.
Step 5: Use the get() function to get a value corresponding to the key and print it
Step 6: Change the value using indexing and print the modified dictionary
Step 7: Find the length of the dictionary and print it
Step 8: Stop

Program:
phone_book={'Amit':9823487431,'Rajiv':3467821829,'Lalitha':7012383777}
#Print the dictionary
print(phone_book)
print("--------------------------")
print("Name","Phone_no")

Dept. of EEE, BNMIT 14


Python Programming for Electrical Engineers (22EEE36)

print("--------------------------")
# accesing the items in a dictionary
for name in phone_book:
print(name,phone_book[name])
#Get the value associated with a specified key.
phoneNo=phone_book.get('Rajiv')
print(f"The phone number of Rajiv is {phoneNo}")
# Change the value of a dictionay
phone_book['Lalitha']=9884512988
for name in phone_book:
print(name,":",phone_book[name])
print("The number of items in phone book:",len(phone_book))

output:

Observations:

Viva Questions

Dept. of EEE, BNMIT 15


Python Programming for Electrical Engineers (22EEE36)

1. What is the difference between Python Tuples and lists?


2. How to create a tuple?
3. What are negative indexes and why are they used with lists and tuples?
4. What does [::-1} do?
5. What is a dictionary in Python?
6. What is the difference between append() and extend() methods?
7. Are Python tuples immutable or mutable?
8. How to convert a tuple into list?
9. How to sort the elements of a list?
10. Solve a)[0] * 4 and b) [1, 2, 3] * 3.
11. what is key value pair
12. Mention different data types can be used in key and value
13. What is the use of from keys() in dictioanary.

Dept. of EEE, BNMIT 16


Python Programming for Electrical Engineers (22EEE36)

Experiment number 4

Title: Functions, Modules.


AIM:

a) Write a function to compute GCD, LCM of two numbers.


b) Write a python program to define a module to find Fibonacci Numbers and import the
module to another program.

4 a) Write a function to compute GCD, LCM of two numbers.


Description:
Greatest Common Factor (GCD): The greatest common factor to any two or more two
integer numbers is known as the HCF of these numbers. For example, the HCF of 12 and 18
is 6.
Lowest Common Multiple (LCM): The smallest or lowest common multiple of any two or
more than two integer numbers is termed an LCM. For example, the LCM of 12 and 18 is 36.

Finding HCF Using Euclid’s Division Lemma

Consider two positive numbers 418 and 33 and we have to find the HCF of these two
numbers.
Step 1: The larger integer which is 418 is taken and
using Euclid’s Division Lemma, a = b q +r we get,
→ 418 = 33 x 12 + 22
Where
a = 418; b = 33; q = 12; r = 22
Step 2: Now if the divisor is 33 represented as ‘a’ and 22 as ‘b’, on applying Euclid’s
Division Algorithm, we get
→ 33 = 22 x 1 + 11
Step 3: Again if we take 22 as divisor ‘a’ and 11 as ‘b’ and we apply Euclid’s Division
Algorithm, we get
→ 22 = 11 x 2 + 0
Step 4: The remainder we obtain is 0 and thus we cannot do the process further.

Dept. of EEE, BNMIT 17


Python Programming for Electrical Engineers (22EEE36)

The last divisor that is obtained is 11 and the HCF we get off 418 and 33 is 11.
Finding LCM using Mathematical Formula
We know that
GCD * LCM= product of two numbers
Therefore
LCM= a*b/GCD(a,b)
Algorithm:
Inpur: Two positive numbers
Output : GCD and LCM of two numbers
Step 1: Start
Step 2: Read two integer numbers
Step 3: Cal the function GCD(a,b)
Step 4: Print GCD of two numbers
Step 5 : Cal the function LCM(a,b)
Step 6: Print LCM of two numbers
Step 5: Stop

GCD (a,b)
Step 1: Ler dividend is ‘a’ and divisor ‘b’. Find the remainder of a/b.Let it equal to R
Step 2: Assign a = b and b = R
Step 3: Repeat Steps 1 and 2 as long as remainder of division is greater than 0
Step 4: GCD = b
Step 5 : Return GCD

LCM(a,b)
Step 1: Determine LCM using the formula LCM=a*b/GCD(a,b)
Step 2: Return LCM

Dept. of EEE, BNMIT 18


Python Programming for Electrical Engineers (22EEE36)

Program:
def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(a,b):
lcm_no=int(a*b/gcd(a,b))
return (lcm_no)
# Reading numbers from user
first = int(input('Enter first number: '))
second = int(input('Enter second number: '))
# Function call & displaying output GCD and LCM
print(f'HCF or GCD of {first} and {second} is',gcd(first,second))
print(f'LCM of {first} and {second} is',lcm(first,second))
output:

Observations:

4 b) Write a python program to define a module to find Fibonacci


Numbers and import the module to another program.

Description:
Fibonacci Series: A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8.....
The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms. This
means to say the nth term is the sum of (n-1)th and (n-2)th term.
User defined module: Modules refer to a file containing Python statements and definitions.

Dept. of EEE, BNMIT 19


Python Programming for Electrical Engineers (22EEE36)

A file containing Python code, for example: example.py, is called a module, and its module name
would be example.
We use modules to break down large programs into small manageable and organized files.
Furthermore, modules provide reusability of code.
We can define our most used functions in a module and import it, instead of copying their definitions
into different programs.
In this example program, we will create a file fibonacci.py and define a function to ‘fib’ find the
Fibonacci series in it. Then call import this module “Fibonacci.py” in the new file ‘main.py’ and call
‘fib’ function

Algorithm:
Input: A positive integer n
Output : Fibonacci Series upto n
Step 1 : Start
Step 2 : import fibonacci module
Step 3: input a positive number
Step 4 :Call the function ‘fib’to find Fibonacci series upto ‘n’
Step 5: Stop
Fibonacci.py module
Step 1: Define a function fib(n)
Step 2: Initialize a=0 , b=1
Step 3: print b
Step 4: Find sum of a and b
Step 5: assign b to a and sum to b
Step 6: Repeat steps 3 to 5 until b <=n

Program:
fibonacci.py

# Fibonacci numbers module


def fib(n): # write Fibonacci series up to n
a, b = 0, 1

Dept. of EEE, BNMIT 20


Python Programming for Electrical Engineers (22EEE36)

print(a,end=’ ‘)
while b < n:
print(b, end =" ")
a, b = b, a+b
main.py
#import fibonacci module
import fibonacci
num=int(input("Enter any number to print Fibonacci series "))
fibonacci.fib(num)
output:

Observations:

Viva Questions:

1. How does break, continue and pass work?


2. How can you generate random numbers in Python?
3. What are Python Modules? Name some built-in modules.
4. How to import modules in python?
5. How can the ternary operators be used in python?
6. Are Arguments in Python Passed by Value or by Reference?
7. What is recursion function?
8. How can you return multiple values from function?
9. How to pass a list as argument?
10. Differentiate between local and global variables in Python?

Dept. of EEE, BNMIT 21


Python Programming for Electrical Engineers (22EEE36)

Experiment number 5

Title: Error Handling, Numpy and Matplotlib modules

AIM:
a) Write a program in Python to handle user defined exception for given problem
b) Write a python program to perform AC Analysis.

5. a) Write a program in Python to handle user defined exception for given


problem

Description:
A user defined Exception raised when the salary is not in (25000, 50000) range
for errors in the input salary. This is done by defining a class SalaryNotInRangeError
inherited from built-in class Exception. An exception will be raised when the salary is
not in between 25000 and 50000.

Algorithm
Input: The salary
Output: An exception raised when salary is not the range (25000, 50000)
Step1: Start
Step2: Define a class SalaryNotInRangeError
Step3: Input the salary
Step4: Check if salary is not in the range (25000,50000)
Step5: If yes. Print “Exception occurred: Salary is not in (25000, 50000) range
Step6: else, print “The input is in correct range”
Step7: Stop
Program:
class SalaryNotInRangeError(Exception):
"""Exception raised When
Salary is not in (25000, 50000) range for errors in the input salary. """
pass

Dept. of EEE, BNMIT 22


Python Programming for Electrical Engineers (22EEE36)

try:
salary = int(input("Enter salary amount: "))
if not 25000 < salary < 50000:
raise SalaryNotInRangeError
except SalaryNotInRangeError:
print("Exception occurred: Salary is not in (25000, 50000) range ")
else:
print("The input is in correct range")

Output:

Observations

5 b. Write a program to simulate and Perform AC Analysis for a given RC Circuit.

Description:
Consider an RC circuit as shown in the following figure.

Dept. of EEE, BNMIT 23


Python Programming for Electrical Engineers (22EEE36)

The output voltage is given by the formula

Let us examine these output voltage values and capacitive reactance values by considering
the resistor and capacitor values. Let the value of the resistor R is 4.7 kΩ and capacitor value
as 47 nF. The input A.C voltage supplied is 10V. The frequency values for which we are going
to calculate are at 1 kHz and 10 kHz.
At 1 kHz

From the above analysis, it is clear that as the frequency increases, output voltage and hence
gain of the circuit reduces. Hence the above RC circuit is a low pass filter.

Dept. of EEE, BNMIT 24


Python Programming for Electrical Engineers (22EEE36)

Algorithm
Step 1: Import the modules/classes required (numpy and matplotlib )
Step 2: define the values of R and C elements
Step 3: determine the range of frequency values
Step 4: Determine gain in dB
Step 4 : Perform the AC Simulation
Step 5: Plot frequency response

Program:
import numpy as np
import matplotlib.pyplot as plt
f=np.logspace(0,6,100) # Logarithmic spacing from 1 to 10^6
w=2*np.pi*f ## Convert Hz to radians / second
R=4700 #4700 ohms
C=47e-9 # 47 nF
zR=R
zC=1/(w*C)
gain=zC/(zR+zC)
gaindB=20*np.log10(gain)
#Plot the frequency response i.e dB v/s w
plt.semilogx(f,gaindB)
plt.xlabel('Frequency in Hz')
plt.ylabel('Gain in dB')
corner_freq=1/(2*np.pi*R*C)
plt.plot([corner_freq,corner_freq],[-100,0])
plt.show()

Output:

Dept. of EEE, BNMIT 25


Python Programming for Electrical Engineers (22EEE36)

Observations:

Viva Questions:

1. Name some standard Python errors.


2. What is an exception in Python?
3. How to handle exceptions in Python?
4. How does the raise keyword work in Python?
5. What’s the difference between raising an error and throwing an exception in Python?
6. Why is the else clause used in try/except blocks?
7. How are NumPy arrays better than Python’s lists?
8. What are ndarrays in NumPy?
9. How can you reverse a NumPy array?
10. How do you count the number of times a particular value appears in an array of
integers?
11. How to create a basic plot using Matplotlib?
12. How can you create a histogram using Matplotlib?
13. What is the purpose of the plt.subplots() function in Matplotlib?
14. How can you change the marker style of a plot in Matplotlib?
15. Write a Python code snippet to plot a pie chart with different colors for different slices.

Dept. of EEE, BNMIT 26


Python Programming for Electrical Engineers (22EEE36)

Experiment number 6

Title: Introduction to PySpice(Python,) Installation Guide


AIM: Write a program to perform DC Analysis using Pyspice(Python)

Description:
PySpice (Python SPICE) is an open-source Python module that provides a Python interface
to the Ngspice and Xyce circuit simulators.
What is SPICE?
❖ SPICE stands for "Simulation Program with Integrated Circuit Emphasis”.

❖ They are often general-purpose, open-source analog electronic circuit simulators.

❖ It is a program used in integrated circuit and board-level design to check the integrity of

circuits, designs and to predict circuit behavior.


Examples of SPICE simulators are Multisim, LTSpice, ngSpice, and many more.
Ngspice is the open-source SPICE simulator for electric and electronic circuits, while Xyce is
a SPICE-compatible simulator developed by the Sandia National Laboratories.
PySpice permits:
• Definition of a circuit, through a netlist,
• Simulation using Ngspice and Xyce,
• Analysis of the output using Numpy and Matplotlib.

Note: A SPICE netlist is a text-based representation of a circuit.


The main features of PySPICE
❖ support Ngspice and Xyce circuit simulators

❖ support Linux, Windows and Mac OS X platforms

❖ implement (partial) SPICE netlist parser

❖ implement an Oriented Object API to define circuit

❖ export simulation output to Numpy arrays

❖ plot using Matplotlib

❖ handle units

Dept. of EEE, BNMIT 27


Python Programming for Electrical Engineers (22EEE36)

❖ Summarizing PySpice implements a Ngspice binding and provides an object

oriented API (Application Programming Interface) on top of SPICE, the


simulation output is converted to Numpy arrays for convenience.
Installation:
Installing PySpice involves 3 steps:
Step 1: Install python from: https://www.python.org/downloads/
Step 2: In the windows command prompt, install pySpice using pip command
pip install PySpice
Step 3: In the windows command prompt, install NgSpice by using the PySpice tool to
download and install the DLL library.
pyspice-post-installation --install-ngspice-dll
Check that the installation works by typing the following command
pyspice-post-installation --check-install
Simulate the given circuit and find node voltages. Also Find current and voltage across the
10Ω resistor connected between node 3 and 4.

Dept. of EEE, BNMIT 28


Python Programming for Electrical Engineers (22EEE36)

Algorithm
Step1: Import the modules/classes required ( Logging, Circuit,Unit)
Step 2: Create the given circuit netlist
Step3: Perform the Simulation
Step4: Print the output
Program:
import PySpice.Logging.Logging as Logging
logger = Logging.setup_logging()
from PySpice.Spice.Netlist import Circuit
from PySpice.Unit import *
#Create the circuit
circuit =Circuit('Resistor Bridge')
circuit.V('input',1, circuit.gnd,20@u_V)
circuit.R(1,1,2,10@u_Ohm)
circuit.R(2,2,3,6@u_Ohm)
circuit.R(3,2,4,4@u_Ohm)
circuit.R(4,3,circuit.gnd,9@u_Ohm)
circuit.R(5,4,circuit.gnd,8@u_Ohm)
circuit.R(6,3,4,10@u_Ohm)
#Perform Simulation
simulator=circuit.simulator(temperature=25,nominal_temperature=25)
analysis=simulator.operating_point()
V=[]
for node in analysis.nodes.values():
print('Node {}: {:4.3f} V'.format(str(node), float(node)))
V.append(float(node))
v10= V[0]-V[1]
I10=v10/10.0
print("Voltage across 10ohm ",v10)
print("Current through 10ohm ",I10)

Dept. of EEE, BNMIT 29


Python Programming for Electrical Engineers (22EEE36)

Output:
Node 4: 5.240 V
Node 3: 4.913 V
Node 2: 7.991 V
Node 1: 20.000 V
Voltage across 10ohm 0.3275109170305681 V
Current through 10ohm 0.03275109170305681 A

Observations

Viva Question:
1. Perform Nodal analysis and determine current through 4Ω resistance using PySpice
module and verify the results with theoretical calculations.

Dept. of EEE, BNMIT 30


Python Programming for Electrical Engineers (22EEE36)

Experiment number 7

Title: Write a program to plot the Characteristics of the Induction Motor.


AIM:
Write a program i) plot speed v/s torque ii) Efficiency v/s BHP characteristics of a three
phase induction motor
Description:
A 3-phase induction motor is an electromechanical energy conversion device which converts
3-phase input electrical power into output mechanical power.
A 3-phase induction motor consists of a stator and a rotor. The stator carries a 3-phase stator
winding while the rotor carries a short-circuited winding called rotor winding. The stator
winding is supplied from a 3-phase supply. The rotor winding drives its voltage and power
from the stator winding through electromagnetic induction and hence the name.
Formulae to plot i) speed v/s torque ii) BHP v/s Efficiency

Algorithm
Step1: Import the modules/classes required (matplotlib and numpy)
Step2: Create lists or arrays to store the inputs- speed, input power and spring balance
readings.
Step 3: Create a variable to store the radius of the brake drum
Step 4: Determine the values of torque, BHP, Output and efficiency for each set of inputs
Step 5: Plot the speed v/s toque and Efficiency v/s BHP curves

Dept. of EEE, BNMIT 31


Python Programming for Electrical Engineers (22EEE36)

Program:
import math
import matplotlib.pyplot as plt
import numpy as np
radius=float(input('Enter the radius of the drum in meters'))
s1=np.array([0,3.5,8.5,12.5,14.5,15.8,17.2])
s2=np.array([0,1.1,2,3,3.5,4,4])
speed=np.array([1485,1479,1465,1442,1426,1413,1404])
inputPower=np.array([150,700,1150,1750,2150,2350,2800])
torque=(s1-s2)*radius
print("Torque in Kg-m",torque)
BHP=(speed*torque )*2*np.pi/4500
outputPower=BHP*735.5
eff=(outputPower/inputPower)*100
print("% Efficiency",eff)
fig=plt.figure()
plt.ylim(0, 100)
plt.xlim(0, 3.5)
plt.plot(BHP,eff,label='%efficiency')
plt.legend()
plt.xlabel('BHP')
plt.ylabel('%Efficiency')
#Save Fig
fig.savefig('EffCurve.png',dpi=300)
plt.close(fig)
fig1=plt.figure()
plt.ylim(0, 1600)
plt.xlim(0, 2)
plt.plot(torque,speed,label='Torque v/s Speed')
plt.legend()

Dept. of EEE, BNMIT 32


Python Programming for Electrical Engineers (22EEE36)

plt.xlabel('Torque')
plt.ylabel('Speed')
#Save Fig
fig1.savefig('SpeedTorque.png',dpi=300)
plt.close(fig1)
Output:
Enter the radius of the drum in meters 0.11
Torque in Kg-m [0. 0.264 0.715 1.045 1.21 1.298 1.452]
%Efficiency [0 57.28278077 93.53967525 88.42875973 82.41693652 80.14916897
74.76971486]

Dept. of EEE, BNMIT 33


Python Programming for Electrical Engineers (22EEE36)

Observations

Viva Questions:
1. Write python code to draw BHP-Torque d) BHP -slip e) BHP - Power factor for a 1-phase
Induction motor

Dept. of EEE, BNMIT 34


Python Programming for Electrical Engineers (22EEE36)

Experiment number 8
Title: Write a python code to plot the efficiency of a Transformer at different loads.
AIM:
Develop a Python code to predetermine the efficiency for different loads at a given power
factor
Description:
It is possible to predict the performance of a transformer at various levels of load by using
Open Circuit (OC) and Short Circuit (SC) test data of a transformer. Without actually loading
the transformer, these two assessed tests give the efficiency results.This method of finding the
parameters of a transformer is called as an Indirect Loading Method.
Open Circuit or No Load Test on Transformer
This test is performed to find out the shunt or no load branch parameters of equivalent circuit
of a transformer. This test results the iron losses and no load current values, thereby we can
determine the no load branch parameters with simple calculations.
The open circuit (OC) test is carried out by connecting LV side (as primary) of the transformer
to the AC supply through variac, ammeter, voltmeter and wattmeter instruments. The
secondary side or HV side terminals are left open and in some cases a voltmeter is connected
across it to measure the secondary voltage.
Short Circuit Test on Transformer
This test is performed to find series branch parameters of an equivalent circuit such as
equivalent impedance (Zo1 or Zo2), total winding resistance (Ro1 or Ro2) and total leakage
reactance (Xo1 or Xo2). Also, it is possible to determine copper losses at any desired load
and total voltage drop of the transformer referred to primary or secondary. In this test, usually
LV winding is shorted by a thick wire. And the test is conducted on the other side, i.e. HV
side (as primary).
Algorithm
Step1: Import the modules/classes required ( matplotlib and numpy)
Step2: Input KVA, primary and secondary voltage of the transformer
Step 3: Input open circuit voltage, current and power of transformer (OC test)

Dept. of EEE, BNMIT 35


Python Programming for Electrical Engineers (22EEE36)

Step 4: Input short circuit voltage, current and power of transformer (SC test)
Step 5: Find output power, input power and efficiency using standard formulae.
Step 6: Plot efficiency v/d load curve
Program:
# input kva, primary and secondary voltage of the transformer
import math
import matplotlib.pyplot as plt
kva=int(input('Enter the kva rating of the transformer'))
v1=int(input('Enter the primary winding voltage of the transformer'))
v2=int(input('Enter the secondary winding voltage of the transformer'))

#input open circuit voltage, current and power of transformer (OC test)
Vo=float(input('enter open circuit voltage:'))
Io=float(input('enter open circuit current:'))
Wo=float(input('enter open circuit power:'))

#input short circuit voltage,current and power of transformer (sc test)


Vsc=float(input('enter short circuit voltage:'))
Isc=float(input('enter short circuit current:'))
Wsc=float(input('enter short circuit power:'))
# To find efficiency v/d load curve
eff=[]
pf=1
for x in [0.2,0.4,0.6,0.8,1]:
num=x*kva*1000*pf
den=(x*kva*1000*pf)+Wo+(x*x*Wsc)
n=(num*100)/den
eff.append(n)
print(eff)
fig=plt.figure()

Dept. of EEE, BNMIT 36


Python Programming for Electrical Engineers (22EEE36)

plt.plot([0.2,0.4,0.6,0.8,1],eff,label='%efficiency')
plt.legend()
plt.xlabel('Load')
plt.ylabel('%Efficiency')
plt.show();
#Save Fig
fig.savefig('EffCurve_Tr.png',dpi=300)
plt.close(fig)
Output:
Enter the kva rating of the transformer 1
Enter the primary winding voltage of the transformer 230
Enter the secondary winding voltage of the transformer 115
enter open circuit voltage:115
enter open circuit current:0.48
enter open circuit power:21
enter short circuit voltage:12.5
enter short circuit current:4.34
enter short circuit power:50
Effciency values are [76.78806494076349, 83.993280537557, 85.40751586139581,
85.16851198442633, 84.27236829432726]

Dept. of EEE, BNMIT 37


Python Programming for Electrical Engineers (22EEE36)

Observations

Viva questions
1. Write a python code to determine the equivalent circuit parameters and plot the efficiency
of a Transformer at different loads.
2. Write a python snippet to predetermine regulation of a transformer.

Dept. of EEE, BNMIT 38


Python Programming for Electrical Engineers (22EEE36)

Experiment number 9
Title: Introduction to RaspberryPi, Installation Guide
Write a program in Python to send digital data on GPIO pins to blink LED connected with
any other Python-supported board.

AIM:
(a) Develop a Python code to send digital data on GPIO pins to blink LED 10 times with 3S
delay.
(b) Develop a Python code to ON/OFF an LED depending upon the user input (LED turns
‘ON’ If user input is ‘ON’ and ‘OFF’ if user input is ‘OFF’

Description:
The Raspberry Pi is a fully-fledged minicomputer, capable of doing whatever a computer
does. It comes with 4x USB, HDMI, LAN, built-in Bluetooth/WiFi support, 1GB RAM,
1.2GHz quad-core ARM CPU, 40 GPIO (General Purpose Input Output) pins, audio and
composite video output, and more.
The Raspberry Pi 4 board contains the following components:

General-purpose input–output pins: These pins are used to connect the Raspberry Pi
to electronic components.

Ethernet port: This port connects the Raspberry Pi to a wired network. The Raspberry
Pi also has Wi-Fi and Bluetooth built in for wireless connections.

Two USB 3.0 and two USB 2.0 ports: These USB ports are used to connect peripherals
like a keyboard or mouse. The two black ports are USB 2.0 and the two blue ports are
USB 3.0.

AV jack: This AV jack allows us to connect speakers or headphones to the Raspberry


Pi.

Dept. of EEE, BNMIT 39


Python Programming for Electrical Engineers (22EEE36)

Camera Module port: This port is used to connect the official Raspberry Pi Camera
Module, which enables the Raspberry Pi to capture images.

HDMI ports: These HDMI ports connect the Raspberry Pi to external monitors. The
Raspberry Pi 4 features two micro HDMI ports, allowing it to drive two separate monitors
at the same time.

USB power port: This USB port powers the Raspberry Pi. The Raspberry Pi 4 has a
USB Type-C port, while older versions of the Pi have a micro-USB port.

External display port: This port is used to connect the official seven-inch Raspberry Pi
touch display for touch-based input on the Raspberry Pi.

microSD card slot (underside of the board): This card slot is for the microSD card that
contains the Raspberry Pi operating system and files.

Generally to operate raspberry pi We need a Type-C Power adapter (5v 3A), any class 10
MicroSD Card, any USB or Bluetooth keyboard and mouse, any desktop monitor with at least

Dept. of EEE, BNMIT 40


Python Programming for Electrical Engineers (22EEE36)

1 HDMI port and a micro HDMI to HDMI cable. These are the standard requirement for the
new raspberry pi 4.
Software
The operating system for the Raspberry Pi is stored on a microSD card. If the card did not
come from an official Raspberry Pi kit, then we need to install the operating system on it.

There are multiple ways to set up the operating system on your Raspberry Pi. We can find out
more about the different installation options on the Raspberry Pi website raspberrypi.org.
Raspberry Pi pin out diagram

Dept. of EEE, BNMIT 41


Python Programming for Electrical Engineers (22EEE36)

(a) Develop a Python code to send digital data on GPIO pins to blink LED
10 times with 3S delay.
Algorithm
Step1: Import the modules/classes required ( RPi.GPIO and time)
Step2: Set GPIO mode to Broadcom GPIO numbers (BCM)
Step 3: Set pin no. 14 as output port.
Step 4: Use while loop to output HIGH and LOW value to GPIO 14 to blink the LED 10
times. Set the delay to 3s by using sleep function
Program:
"""
Connect the LED Anode to GPIO14
Connect the ground to GND
"""
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

Dept. of EEE, BNMIT 42


Python Programming for Electrical Engineers (22EEE36)

GPIO.setwarnings(False)
GPIO.setup(14, GPIO.OUT)
count = 1
while count<=10:
GPIO.output(14,GPIO.HIGH)
print("LED is ON")
time.sleep(3)
GPIO.output(14,GPIO.LOW)
print("LED is OFF")
time.sleep(3)
count+=1
Output:

Observations

(b) Develop a Python code to ON/OFF an LED depending upon the user
input (LED turns ‘ON’ If user input is ‘ON’ and ‘OFF’ if user input is
‘OFF’
Algorithm
Step1: Import the modules/classes required ( RPi.GPIO and time)
Step2: Set GPIO mode to Broadcom GPIO numbers (BCM)
Step 3: Set pin no. 14 as output port.
Step 4: Use an infinite while loop to ask the user to input ‘ON’ or ‘OFF’ to control the
LED.
Program
"""
Connect the LED Anode to GPIO14

Dept. of EEE, BNMIT 43


Python Programming for Electrical Engineers (22EEE36)

Connect the ground to GND


"""
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(14, GPIO.OUT)

while True:
command = input("Type 'ON' to turn On the light and 'OFF' to turn off the light: ")
if command == "ON":
GPIO.output(14,GPIO.HIGH)
print("Light is ON")
if command == "OFF":
GPIO.output(14,GPIO.LOW)
print("Light is OFF")
Output:

Observations

Exercise Program
1. Develop a python code for raspberry-pi to control LED On and Off with Button.

Dept. of EEE, BNMIT 44


Python Programming for Electrical Engineers (22EEE36)

Experiment number 10
Title: Connect the Digital/Analog I/O module and write a program in python to interface
the various Analog Sensors.

AIM:
(a) Develop a Python Script interface HC-SR04 Ultrasonic Sensor with Raspberry Pi
Interface and calculate the distance between the sensor and the object.
(b) Write a python Script to Interface LCD with Raspberry Pi and display a message
Description:
Ultrasonic Sensors are very popular among electronic hobbyists and are frequently used in a
variety of projects like Obstacle Avoiding Robot, Distance Measurement, Proximity
Detection and so forth.

The widely used ultrasonic sensor module HC-SR04 Ultrasonic Sensor can be accurately used
for measuring distances in the range of 2cm to 400cm with an accuracy of 3mm. It works on
the principle that is similar to RADAR and SONOR i.e. transmits a signal and analyzes the
target by capturing the reflected signals. It basically consists of three parts: an ultrasonic
transmitter, a control circuit and an ultrasonic receiver. It has only four pins namely VCC,
TRIG (Trigger), ECHO (Echo) and GND as shown in the following figure.

The basic principle behind the Ultrasonic Sensor is that the Ultrasonic Transmitter in the
Sensor generates a 40 KHz Ultrasound. This signal then propagates through air and if there is

Dept. of EEE, BNMIT 45


Python Programming for Electrical Engineers (22EEE36)

any obstacle in its path, the signal hits the object and bounces back. This bounced signal is
then collected by the Ultrasonic Receiver. Based on the signal’s time of travel, the distance
of the object is calculated.

In order to send the 40 KHz Ultrasound, the TRIG Pin of the Ultrasonic Sensor must be held
HIGH for a minimum duration of 10µS. After this, the Ultrasonic Transmitter, will transmits
a burst of 8-pulses of ultrasound at 40 KHz. Immediately, the control circuit in the sensor will
change the state of the ECHO pin to HIGH. This pins stays HIGH until the ultrasound hits an
object and returns to the Ultrasonic Receiver. Based on the Time for which the Echo Pin stays
HIGH, the distance between the sensor and the object is calculated

For example, if the time for which ECHO is HIGH as 588µS, then the distance can be
calculated with the help of the speed of sound, which is equal to 340m/s.

Distance = Velocity of Sound / (Time/2) = 340m/s / (588µS /2) = 10cm.

Circuit Diagram

The following image shows the connections between the Raspberry Pi and the HC-SR04
Ultrasonic Sensor.

Note that Raspberry Pi works at 3.3V Logic while the HC-SR04 Ultrasonic Sensor works at
5V. The Raspberry Pi needs to read the Echo pin to calculate the time and hence the

Dept. of EEE, BNMIT 46


Python Programming for Electrical Engineers (22EEE36)

corresponding GPIO pin on the Raspberry Pi must be configured as Input. So, before
connecting the Echo Pin to the Raspberry Pi, it must be given to a level converter.

Connect the Trig Pin of the HC-SR04 Ultrasonic Sensor to the Physical Pin 16 i.e. GPIO23
of the Raspberry Pi. Use a combination of 680Ω and 1.5 KΩ Resistor to convert the Echo pin
to 3.3V Logic (approximately) and connect it to Physical Pin 18 i.e. GPIO24 of the Raspberry
Pi. Finally, provide the +5V and GND connections to the Ultrasonic Sensor from the
Raspberry Pi Pins.

Algorithm

Step1: Import the modules/classes required ( RPi.GPIO and time)

Step2: Set GPIO mode to Board

Step 3: Set pin no. 16 to Trigger and 18 to Echo.

Step 4: Set TRIG as OUT and ECHO as IN

Step 5: Find the distance and print

Program

import RPi.GPIO as GPIO


import time

GPIO.setmode(GPIO.BOARD)

TRIG = 16
ECHO = 18
i=0

GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)

GPIO.output(TRIG, False)
print ("Calibrating.....")
time.sleep(2)

Dept. of EEE, BNMIT 47


Python Programming for Electrical Engineers (22EEE36)

print ("Place the object......")

try:
while True:
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()

except KeyboardInterrupt:
GPIO.cleanup()
Output:

Observations

Exercise Program

Write a python Script to Interface LCD with Raspberry Pi and display a message

Dept. of EEE, BNMIT 48


Python Programming for Electrical Engineers (22EEE36)

Experiment number 11
Title: Write a python script to control the speed of Servomotor.

AIM:
Develop a Python Script to rotate the servo motor through 180° insteps of 18°.
Description:
A Servo Motor is a simple device that consists of a DC Motor, Gears and a Feed Back based
Position Control System. The main advantage of a Servo Motor is its ability to hold the
angular position of its shaft.
Two of the most common Servo Motors are Tower Pro SG90 and Tower Pro MG90S.
SG90 is a plastic gear motor whereas MG90S is a metal gear motor. In this experiment, we
will be using the SG90 Servo Motor.
The Tower Pro SG90 Servo Motor Consists of three Pins: PWM (Orange or Yellow), VCC
(Red) and GND (Brown). The VCC and GND pins must be connected to +5V and GND of
the power supply.
PWM or Signal Pin of the Servo Motor must be connected to the PWM Output of the
Controller (Raspberry Pi). Based on the width of the Pulses from the PWM signal, the angle
of the Servo Motor’s shaft will vary.
In order to control a Servo Motor, a technique called Pulse Width Modulation or PWM is
employed. In PWM technique a pulse of variable width is applied and the position of the
Servo Motor’s shaft will be set by the width or length of the Pulse.
The frequency of the PWM Signal is a fixed value and is dependent on the type of the Servo
Motor. Both SG90 and MG90S Servo Motors have a PWM Frequency of 50Hz.At 50Hz i.e.
a period of 20ms, the minimum pulse width is 1ms and the maximum pulse width is 2ms.
Most servo motors can have a sweep area of 180 degrees i.e. 90 degrees on either side of the
neutral position.
When the pulse width of the PWM Signal is 1ms, the position of the servo is all the way to
the LEFT. The Duty Cycle of this position is (1ms/20ms) x 100 = 5%.
Similarly, for pulse widths of 1.5ms and 2ms, the position of the servo is MIDDLE (with duty
cycle of 7.5%) and far RIGHT (with duty cycle of 10%).

Dept. of EEE, BNMIT 49


Python Programming for Electrical Engineers (22EEE36)

Algorithm

Step1: Import the modules/classes required ( RPi.GPIO and time)

Step2: Set GPIO mode to Board

Step 3: Set pin no. 11 to output (PWM pulse).

Step 4: Start the servo

Step 5: set variable duty=2

Step 6: Rotate the servo through 180 degrees in 10 steps using while loop by incrementing
the duty cycle by one upto 12.

Step7: Turn the servo through 90°, 0° by calling ChangeDutyCycle function.

Step8: Stop the servo

Dept. of EEE, BNMIT 50


Python Programming for Electrical Engineers (22EEE36)

Program

# Import libraries

import RPi.GPIO as GPIO

import time

# Set GPIO numbering mode

GPIO.setmode(GPIO.BOARD)

# Set pin 11 as an output, and set servo1 as pin 11 as PWM

GPIO.setup(11,GPIO.OUT)

servo1 = GPIO.PWM(11,50) # Note 11 is pin, 50 = 50Hz pulse

#start PWM running, but with value of 0 (pulse off)

servo1.start(0)

print ("Waiting for 2 seconds")

time.sleep(2)

#Let's move the servo!

print ("Rotating 180 degrees in 10 steps")

# Define variable duty

duty = 2

# Loop for duty values from 2 to 12 (0 to 180 degrees)

while duty <= 12:

servo1.ChangeDutyCycle(duty)

Dept. of EEE, BNMIT 51


Python Programming for Electrical Engineers (22EEE36)

time.sleep(1)

duty = duty + 1

# Wait a couple of seconds

time.sleep(2)

# Turn back to 90 degrees

print ("Turning back to 90 degrees for 2 seconds")

servo1.ChangeDutyCycle(7)

time.sleep(2)

#turn back to 0 degrees

print ("Turning back to 0 degrees")

servo1.ChangeDutyCycle(2)

time.sleep(0.5)

servo1.ChangeDutyCycle(0)

#Clean things up at the end

servo1.stop()

GPIO.cleanup()

print ("Goodbye")

Output:

Dept. of EEE, BNMIT 52


Python Programming for Electrical Engineers (22EEE36)

Observations

Viva Question:

1. What is the working principle of servomotor


2. What are the differences between servomotor and stepper motor
3. List few applications of Servomotor

Dept. of EEE, BNMIT 53


Python Programming for Electrical Engineers (22EEE36)

Experiment number 12
Title: Speed control of DC motor using Raspberry-pi and python

AIM:
To Interface L298N Motor Driver with Raspberry Pi and control a DC Motor Speed and
direction with the help of a Python Script.
Description:
Dc motors can be controlled through several drivers which are widely available in the market.
One of the most widely used is L298N motor driver module as it very easy and relatively
inexpensive as well. It is widely used in controlling robots as four motors can be connected
at once. However, if the speed and direction both needs to be controlled then it allows two
motors to be connected. Thus, it is perfect for two wheeled robots. This module is mainly
used in robotics and in controlling dc and stepping motors.
The L298N motor driver module consists of a L298N motor driver IC ,78M05 5V regulator,
5V jumper enable, power LED, heat sink, resistors and capacitors all combined in an
integrated circuit. The diagram below shows all the components consisting inside the module.

The L298N Motor driver IC is powerfully built with a big heat sink. It is a dual channel H
bridge motor driver which can be easily used to drive two motors.
Specifications
The table shows some specifications of the L298N motor driver module:

Dept. of EEE, BNMIT 54


Python Programming for Electrical Engineers (22EEE36)

Driver Model L298N

Driver Chip Double H-bridge L298N

Maximum Power 25W

Maximum Motor Supply Voltage 46V

Maximum Motor Supply Current 2A

Driver Voltage 5-35V

Driver Current 2A

Size 43x43x26mm

The image below shows the L298N Motor Driver Module with names of all the components
on it. To name a few, it contains screw terminals for connecting motors and power supply,
male headers for connecting different pins like enable, IN1, IN2 etc.

NOTE:
There is jumper near the power supply terminals of the L298N Motor Driver Module. If it is
connected, it will enable the on-board 5V regulator, which supplies +5V logic supply for

Dept. of EEE, BNMIT 55


Python Programming for Electrical Engineers (22EEE36)

L298N IC. This must be used only if the supply voltage is less than or equal to +12V. If it is
more than +12V, then disconnect the jumper to disable the regulator.
Controlling DC motors through L298N module
There are two types of control pins found at the bottom right side of the module. One type
controls the speed and the other type controls the direction of the motor.
Speed Control Pins
• The speed control pins labelled ENA and ENB on the module, control the speed of the dc

motor and turn it ON and OFF.


• ENA controls the speed of motor A and ENB controls the speed of motor B. If both of the

pins are in a logic HIGH (5V) state, then both the motors are ON and spinning at maximum
speed. If both of the pins are in a logic LOW (ground) state, then both the motors are OFF.
Through the PWM functionality we can also control the speed of the motor. By default,
there is a jumper connected on these pins which keeps these pins in a HIGH state. In order
to control the speed, we need to remove the jumper and connect these terminals with the
PWM pins of Raspberry Pi and program them in code. The table below demonstrates the
logic signals required for controlling Motor A.
Direction Control (INPUT) Pins
• The direction control pins are the four input pins (IN1, IN2, IN3, IN4) on the module.

• Through these input pins we can determine whether to move the dc motor forward or

backwards. IN1 and IN2 control motor A’s spinning direction whereas IN3 and IN4 control
motor B’s spinning direction. The table below shows the logic signals required for the
appropriate spinning action for motor A.

IN1 IN2 Motor Action

1 (HIGH) 1 OFF

1 0 (LOW) Backward

0 1 Forward

0 0 OFF

Dept. of EEE, BNMIT 56


Python Programming for Electrical Engineers (22EEE36)

Circuit Diagram of Raspberry Pi L298N Interface

Components Required

• Raspberry Pi
• L298N Motor Driver Module
• 12V DC Motor
• 12V Power Supply for Motor and Motor Driver
• Power Supply for Raspberry Pi
• Connecting Wires

Circuit Design
The design of the Raspberry Pi L298N Motor Driver Interface Circuit is very simple. First
connect 12V Power Supply to L298N Motor Driver Module. Then, make the GND terminals
of Raspberry Pi and L298N Motor Driver Module common (connect them together).
Now, since we are controlling a single DC Motor, we need to use a single channel of the
L298N. In order to do that, connect the ENA pin of L298N to Physical Pin 22 (GPIO25) of
Raspberry Pi.
Coming to the Inputs of the Motor, connect the IN1 and IN2 of L298N Module to Physical
Pins 16 and 18 (GPIO23 and GPIO24).
Algorithm
This is followed by a list of commands you must use to control the motor. These commands
are given below.
Step1: Import the modules/classes required ( RPi.GPIO and time)
Step2: Set GPIO mode to BCM
Step 3: Set any three GPIO Pins as Output pin
Step 4: set PWM mode
Step 5: Start the motor
Step 6: Ask the user enter any of the following as input

Dept. of EEE, BNMIT 57


Python Programming for Electrical Engineers (22EEE36)

• r – run (to run or start the motor)


• s – stop (to stop the motor)
• f – forward (to run the motor in forward direction) – default direction
• b – backward (to reverse the direction of rotation)
• l – low (to decrease the speed to 25%) – default speed
• m – medium (to run the motor at medium speed 50%)
• h – high (to increase the speed to 75% level)
• e – exit (to stop the motor and exit Python)
Step7: If Choice == , Stop the program.
Step 8: Control DC motor speed and direction depending on user input

Program
import RPi.GPIO as GPIO
from time import sleep
in1 = 24
in2 = 23
en = 25
temp1=1
GPIO.setmode(GPIO.BCM)

GPIO.setup(in1,GPIO.OUT)

GPIO.setup(in2,GPIO.OUT)

GPIO.setup(en,GPIO.OUT)

GPIO.output(in1,GPIO.LOW)

GPIO.output(in2,GPIO.LOW)

p=GPIO.PWM(en,1000)

p.start(25)

print("\n")

print("The default speed & direction of motor is LOW & Forward.....")

print("r-run s-stop f-forward b-backward l-low m-medium h-high e-exit")

print("\n")

Dept. of EEE, BNMIT 58


Python Programming for Electrical Engineers (22EEE36)

while(1):

x=raw_input()

if x=='r':

print("run")

if(temp1==1):

GPIO.output(in1,GPIO.HIGH)

GPIO.output(in2,GPIO.LOW)

print("forward")

x='z'

else:

GPIO.output(in1,GPIO.LOW)

GPIO.output(in2,GPIO.HIGH)

print("backward")

x='z'

elif x=='s':

print("stop")

GPIO.output(in1,GPIO.LOW)

GPIO.output(in2,GPIO.LOW)

x='z'

elif x=='f':

print("forward")

GPIO.output(in1,GPIO.HIGH)

GPIO.output(in2,GPIO.LOW)

temp1=1

Dept. of EEE, BNMIT 59


Python Programming for Electrical Engineers (22EEE36)

x='z'

elif x=='b':

print("backward")

GPIO.output(in1,GPIO.LOW)

GPIO.output(in2,GPIO.HIGH)

temp1=0

x='z'

elif x=='l':

print("low")

p.ChangeDutyCycle(25)

x='z'

elif x=='m':

print("medium")

p.ChangeDutyCycle(50)

x='z'

elif x=='h':

print("high")

p.ChangeDutyCycle(75)

x='z'

elif x=='e':

GPIO.cleanup()

print("GPIO Clean up")

break

else:

Dept. of EEE, BNMIT 60


Python Programming for Electrical Engineers (22EEE36)

print("<<< wrong data >>>")

print("please enter the defined data to continue.....")

Output:

Observations

Exercise Program:

Write python code to control the speed of two DC motor

Dept. of EEE, BNMIT 61

You might also like