22EEE136 PythonLabManualFinal
22EEE136 PythonLabManualFinal
22EEE136 PythonLabManualFinal
FOR
Python Programming for Electrical Engineers
[22EEE136]
III Semester
2023-24
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
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.
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 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:
microcontroller board.
❖ Communicate effectively about the chosen problem
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:
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:
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:
Experiment number 2
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:
Program:
output:
Observations:
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 5: Go to step 1
Step 6: Stop
Program
Observations:
C-Out = 1
Observations:
Observations:
Viva Questions:
i=2
while True:
if i%3 == 0:
break
print(i)
i += 2
Experiment number 3
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()
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)
output:
Observations:
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.
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:
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")
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
Experiment number 4
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.
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
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:
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.
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
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:
Experiment number 5
AIM:
a) Write a program in Python to handle user defined exception for given problem
b) Write a python program to perform AC Analysis.
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
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
Description:
Consider an RC circuit as shown in the following figure.
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.
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:
Observations:
Viva Questions:
Experiment number 6
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”.
❖ It is a program used in integrated circuit and board-level design to check the integrity of
❖ handle units
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)
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.
Experiment number 7
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
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()
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]
Observations
Viva Questions:
1. Write python code to draw BHP-Torque d) BHP -slip e) BHP - Power factor for a 1-phase
Induction motor
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)
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:'))
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]
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.
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.
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
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
(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)
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
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.
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
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.
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
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
Program
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)
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
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%).
Algorithm
Step 6: Rotate the servo through 180 degrees in 10 steps using while loop by incrementing
the duty cycle by one upto 12.
Program
# Import libraries
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11,GPIO.OUT)
servo1.start(0)
time.sleep(2)
duty = 2
servo1.ChangeDutyCycle(duty)
time.sleep(1)
duty = duty + 1
time.sleep(2)
servo1.ChangeDutyCycle(7)
time.sleep(2)
servo1.ChangeDutyCycle(2)
time.sleep(0.5)
servo1.ChangeDutyCycle(0)
servo1.stop()
GPIO.cleanup()
print ("Goodbye")
Output:
Observations
Viva Question:
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:
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
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
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.
1 (HIGH) 1 OFF
1 0 (LOW) Backward
0 1 Forward
0 0 OFF
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
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("\n")
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
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()
break
else:
Output:
Observations
Exercise Program: