SlideShare ist ein Scribd-Unternehmen logo
1 von 32
Faculty of Engineering Science & Technology(FEST)
Hamdard Institute of Engineering Technology(HIET)
HAMDARD UNIVERSITY
Instructor
ABDUL HASEEB
HANDS-ON WORKSHOP ON PYTHON
PROGRAMMING LANGUAGE
Faculty Development Program (Session-10)
Python Arduino Interfacing
Arduino and MS Excel Interface
with Python
Arduino
Firmata
• Firmata (Italian word)
Library is use to make
Arduino board as Slave
board for Computer
programs like Python, C
etc.
• Simply it MAKES or ADD
IO pins to computer
Process of Interfacing Arduino
• Configure Arduino with Standard Firmata
Program
• Interface Arduino through PC or Laptop via
PyFirmata package
Setting Arduino Board and Port
Open Standard Firmata from Example
Upload the Standard Firmata program to
Arduino Board
Complete the Arduino IDE window
• Arduino Board is
Configure with Firmata.
Note the Port name:
Tool>>Port>>Port_Name
• No need of Arduino
Software further, so
close it
Working on PyFirmata
• PyFirmata is not a build-in package for Python
IDLE, so first install PyFirmata
Initializing PyFirmata
1) Import Module
import pyfirmata
2) Initialize Arduino Board and Com Port Name
Syntax:
board_name_variable = pyfirmata.Arduino_Board(Com Port Name)
Example:
Arduino Uno
board = pyfirmata.Arduino(‘COM4')
Arduino Mega
board = pyfirmata.ArduinoMega (‘COM4')
Arduino Due
board = pyfirmata.ArduinoDue (‘COM4')
For Raspberry pi the com name will be /dev/ttyACM0
Example:
board = pyfirmata.Arduino('/dev/ttyACM0')
Setup Pin
The get_pin function is used to set pin as Input or Output and also set
the
Syntax:
Pin_name = board_name.get_pin(‘d/a:pin_number:i/o’)
Example:
• LED = board.get_pin('d:13:o')
• switch = board.get_pin('d:4:i')
• analog = board.get_pin('a:0:i')
• led_PWM = board.get_pin('d:10:p')
• servo = board.get_pin('d:11:s')
Working
Signal Type
a (analog) d (digital)
i (input)  
o (output)  
p (PWM)  
s (servo)  
Digital Output
import pyfirmata
from time import sleep
board = pyfirmata.Arduino("COM4")
led = board.get_pin('d:13:o')
print("Press Ctrl + c to Exit")
try:
while True: #Infinite Loop
led.write(1) #ON LED
sleep(1) #Delay
led.write(0) #OFF LED
sleep(1) #Delay
except:
print("Program End!")
finally:
led.write(0) #Clear LED before close
board.exit()
Analog Out (PWM)
Analog Out (PWM)
import pyfirmata
board = pyfirmata.Arduino("COM4")
led_brightness = board.get_pin("d:3:p")
print("Press Ctrl + c to Exit")
try:
while True:
duty = int(input("Enter Brightness (0 to 100)= "))
led_brightness.write(duty / 100.0)
except:
print("Program End!")
finally:
board.exit()
Controlling a Servo Using PyFirmata
Controlling a Servo Using PyFirmata
import pyfirmata
board = pyfirmata.Arduino("COM4")
servo_pin = board.get_pin("d:7:s")
print("Press Ctrl + c to Exit")
try:
while True:
angle = int(input("Enter Angle (0 to 180):"))
servo_pin.write(angle)
except:
print("Program End!")
finally:
board.exit()
Reading Analog or Digital data from
Arduino
• PyFirmata uses the concept of an Iterator to
monitor the Arduino input pin. The reasons
for this are bound up in the implementation of
Firmata.
it = pyfirmata.util.Iterator(board)
it.start()
Pin_name.enable_reporting()
Digital Input
import pyfirmata
board = pyfirmata.Arduino("COM4")
switch = board.get_pin(“d:4:I”)
led = board.get_pin(“d:7:o”)
it = pyfirmata.util.Iterator(board)
it.start()
switch.enable_reporting()
print("Press Ctrl + c to Exit")
try:
while True:
if switch.read() == True:
led.write(1) #ON LED
print('Switch is High')
else:
led.write(0) #OFF LED
print('Switch is Low')
except:
print("Program End!")
finally:
led.write(0) #Clear LED before close
board.exit()
Analog Read
import pyfirmata
from time import sleep
board = pyfirmata.Arduino("COM4")
analog = board.get_pin('a:0:i')
it = pyfirmata.util.Iterator(board)
it.start()
analog.enable_reporting()
print("Press Ctrl + c to Exit")
try:
while True:
reading = analog.read()
print(reading)
sleep(1)
except:
print("Program End!")
finally:
board.exit()
Python Interface MS Excel
About MS Excel
For today`s Workshop participant must know
the following about MS Excel
• Workbook
• Worksheet
• Cell
• Rows address
• Column address
• Charts
MS Excel View
Writing data in MS Excel through Python
import openpyxl
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws1 = wb.create_sheet()
ws.title = "Workshop Sheet"
ws['A1'] = "Integer"
ws['B1'] = "Float"
ws['C1'] = "String"
ws['A2'] = 1000
ws['B2'] = 50.50
ws['C2'] = "Hamdard"
wb.save(r"C:.........workshop.xlsx")
Handle the file open Error
import openpyxl
from openpyxl import Workbook
try:
wb = Workbook()
ws = wb.active
wb.save(r"C:.........workshop.xlsx")
except PermissionError:
print("Please close the MS Excel Workbook")
Add Image and Merge Cell
import openpyxl
from openpyxl import Workbook
from openpyxl.drawing.image import Image
try:
wb = Workbook()
ws = wb.active
ws.merge_cells('A1:B1') #Merge Cell
ws['A1'] = "Pakistan Zindabad"
Pak_Flag = Image(r"C:.........Pakistan.PNG")
ws.add_image(Pak_Flag, 'A2')
wb.save(r"C:.........workshop.xlsx")
except PermissionError:
print("Please close the MS Excel Workbook")
Add Sheet to Workbook
import openpyxl
from openpyxl import Workbook
try:
wb = Workbook()
ws = wb.active #First Sheet
ws.title = "First"
ws['A25'] = "First Sheet"
ws2 = wb.create_sheet() #New Sheet
ws2['A25'] = "Second Sheet"
ws2.title = "Second"
ws3 = wb.create_sheet() #New Sheet
ws3['A25'] = "Third Sheet"
ws3.title = "Third"
wb.save(r"C:.........workshop.xlsx")
except PermissionError:
print("Please close the MS Excel Workbook")
Accessing Multiple cell
import openpyxl
from openpyxl import Workbook
try:
wb = Workbook()
ws = wb.active
ws['A1'] = "Number"
ws['B1'] = "Square"
for i in range(10):
ws.cell(row = i+2 , column = 1 , value = i)
ws.cell(row = i+2 , column = 2 , value = i*i)
wb.save(r"C:.........workshop.xlsx")
except PermissionError:
print("Please close the MS Excel Workbook")
Adding Chart to Worksheet
Adding Chart to Worksheet
import openpyxl
from openpyxl import Workbook
from openpyxl.chart import
BarChart,Reference,Series
try:
wb = Workbook()
ws = wb.active
ws['A1'] = "Number"
ws['B1'] = "Square"
for i in range(1,11):
ws.cell(row = i+1 , column = 1 , value = i)
ws.cell(row = i+1 , column = 2 , value = i*i)
#Working for Chart
chart = BarChart()
chart.title = "Square Values Chart"
chart.style = 13
chart.x_axis.title = 'Number'
chart.y_axis.title = 'Square of Number'
x_axis = Reference(ws, min_col=1, min_row=2,
max_row=i+1)
y_axis = Reference(ws, min_col=2, min_row=1,
max_col=2, max_row=i+1)
chart.add_data(y_axis, titles_from_data=True)
chart.set_categories(x_axis)
ws.add_chart(chart, "D2")
#Save Workbook
wb.save(r"C:UsersHomeDesktopworkshop.xlsx")
except PermissionError:
print("Please close the MS Excel Workbook")
Chart
Workshop Exercise
• Get Analog data from Arduino, Save it in Excel
sheet and Generate its chart

Weitere ähnliche Inhalte

Was ist angesagt?

02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and VariablesIntro C# Book
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONvikram mahendra
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to KleisliHermann Hueck
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]vikram mahendra
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output Intro C# Book
 
Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Naveen Kumar
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!Hermann Hueck
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]vikram mahendra
 
Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Naveen Kumar
 
OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2vikram mahendra
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language Mohamed Loey
 

Was ist angesagt? (20)

09. Methods
09. Methods09. Methods
09. Methods
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
C++ Language
C++ LanguageC++ Language
C++ Language
 
USER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHONUSER DEFINE FUNCTIONS IN PYTHON
USER DEFINE FUNCTIONS IN PYTHON
 
From Function1#apply to Kleisli
From Function1#apply to KleisliFrom Function1#apply to Kleisli
From Function1#apply to Kleisli
 
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
USER DEFINE FUNCTIONS IN PYTHON[WITH PARAMETERS]
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
04. Console Input Output
04. Console Input Output 04. Console Input Output
04. Console Input Output
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3Develop Embedded Software Module-Session 3
Develop Embedded Software Module-Session 3
 
Use Applicative where applicable!
Use Applicative where applicable!Use Applicative where applicable!
Use Applicative where applicable!
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Cbse marking scheme 2006 2011
Cbse marking scheme 2006  2011Cbse marking scheme 2006  2011
Cbse marking scheme 2006 2011
 
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]FUNCTIONS IN PYTHON[RANDOM FUNCTION]
FUNCTIONS IN PYTHON[RANDOM FUNCTION]
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2Develop Embedded Software Module-Session 2
Develop Embedded Software Module-Session 2
 
C++
C++C++
C++
 
OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2OPERATOR IN PYTHON-PART2
OPERATOR IN PYTHON-PART2
 
C++ Programming Language
C++ Programming Language C++ Programming Language
C++ Programming Language
 

Ähnlich wie Python workshop session 6

Introduction to pcDuino
Introduction to pcDuinoIntroduction to pcDuino
Introduction to pcDuinoJingfeng Liu
 
Cassiopeia Ltd - standard Arduino workshop
Cassiopeia Ltd - standard Arduino workshopCassiopeia Ltd - standard Arduino workshop
Cassiopeia Ltd - standard Arduino workshoptomtobback
 
Processing - MORE Erasmus+ PAU, 2016 February
Processing - MORE Erasmus+ PAU, 2016 FebruaryProcessing - MORE Erasmus+ PAU, 2016 February
Processing - MORE Erasmus+ PAU, 2016 Februarydecibeldanilo
 
Lecture-01-2020J.pptx
Lecture-01-2020J.pptxLecture-01-2020J.pptx
Lecture-01-2020J.pptxpradeepwalter
 
Raspberry Pi Using Python
Raspberry Pi Using PythonRaspberry Pi Using Python
Raspberry Pi Using PythonSeggy Segaran
 
pcDuino Presentation at SparkFun
pcDuino Presentation at SparkFunpcDuino Presentation at SparkFun
pcDuino Presentation at SparkFunJingfeng Liu
 
arduino
arduinoarduino
arduinomurbz
 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Windows Developer
 
Arduino Development For Beginners
Arduino Development For BeginnersArduino Development For Beginners
Arduino Development For BeginnersFTS seminar
 
Arduino by bishal bhattarai IOE, Pashchimanchal Campus Pokhara, Nepal
Arduino by bishal bhattarai  IOE, Pashchimanchal Campus Pokhara, NepalArduino by bishal bhattarai  IOE, Pashchimanchal Campus Pokhara, Nepal
Arduino by bishal bhattarai IOE, Pashchimanchal Campus Pokhara, Nepalbishal bhattarai
 
Embedded L1_notes_unit2_architecture.pptx
Embedded L1_notes_unit2_architecture.pptxEmbedded L1_notes_unit2_architecture.pptx
Embedded L1_notes_unit2_architecture.pptxaartis110
 
DeviceHub - First steps using Intel Edison
DeviceHub - First steps using Intel EdisonDeviceHub - First steps using Intel Edison
DeviceHub - First steps using Intel EdisonGabriel Arnautu
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in ScalaHermann Hueck
 
Arduino 8-step drum sequencer 3 channels
Arduino 8-step drum sequencer 3 channelsArduino 8-step drum sequencer 3 channels
Arduino 8-step drum sequencer 3 channelstomtobback
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++Marco Izzotti
 

Ähnlich wie Python workshop session 6 (20)

Introduction to pcDuino
Introduction to pcDuinoIntroduction to pcDuino
Introduction to pcDuino
 
Cassiopeia Ltd - standard Arduino workshop
Cassiopeia Ltd - standard Arduino workshopCassiopeia Ltd - standard Arduino workshop
Cassiopeia Ltd - standard Arduino workshop
 
Processing - MORE Erasmus+ PAU, 2016 February
Processing - MORE Erasmus+ PAU, 2016 FebruaryProcessing - MORE Erasmus+ PAU, 2016 February
Processing - MORE Erasmus+ PAU, 2016 February
 
Lecture-01-2020J.pptx
Lecture-01-2020J.pptxLecture-01-2020J.pptx
Lecture-01-2020J.pptx
 
Raspberry Pi Using Python
Raspberry Pi Using PythonRaspberry Pi Using Python
Raspberry Pi Using Python
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
pcDuino Presentation at SparkFun
pcDuino Presentation at SparkFunpcDuino Presentation at SparkFun
pcDuino Presentation at SparkFun
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
Introduction to Arduino
Introduction to ArduinoIntroduction to Arduino
Introduction to Arduino
 
arduino
arduinoarduino
arduino
 
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
Build 2016 - B880 - Top 6 Reasons to Move Your C++ Code to Visual Studio 2015
 
Arduino Development For Beginners
Arduino Development For BeginnersArduino Development For Beginners
Arduino Development For Beginners
 
Arduino by bishal bhattarai IOE, Pashchimanchal Campus Pokhara, Nepal
Arduino by bishal bhattarai  IOE, Pashchimanchal Campus Pokhara, NepalArduino by bishal bhattarai  IOE, Pashchimanchal Campus Pokhara, Nepal
Arduino by bishal bhattarai IOE, Pashchimanchal Campus Pokhara, Nepal
 
Arduino
ArduinoArduino
Arduino
 
Embedded L1_notes_unit2_architecture.pptx
Embedded L1_notes_unit2_architecture.pptxEmbedded L1_notes_unit2_architecture.pptx
Embedded L1_notes_unit2_architecture.pptx
 
DeviceHub - First steps using Intel Edison
DeviceHub - First steps using Intel EdisonDeviceHub - First steps using Intel Edison
DeviceHub - First steps using Intel Edison
 
Implementing the IO Monad in Scala
Implementing the IO Monad in ScalaImplementing the IO Monad in Scala
Implementing the IO Monad in Scala
 
Arduino 8-step drum sequencer 3 channels
Arduino 8-step drum sequencer 3 channelsArduino 8-step drum sequencer 3 channels
Arduino 8-step drum sequencer 3 channels
 
Practical basics on c++
Practical basics on c++Practical basics on c++
Practical basics on c++
 
Fp201 unit2 1
Fp201 unit2 1Fp201 unit2 1
Fp201 unit2 1
 

Kürzlich hochgeladen

Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactisticshameyhk98
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the ClassroomPooky Knightsmith
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...Nguyen Thanh Tu Collection
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentationcamerronhm
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 

Kürzlich hochgeladen (20)

Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 

Python workshop session 6

  • 1. Faculty of Engineering Science & Technology(FEST) Hamdard Institute of Engineering Technology(HIET) HAMDARD UNIVERSITY Instructor ABDUL HASEEB HANDS-ON WORKSHOP ON PYTHON PROGRAMMING LANGUAGE Faculty Development Program (Session-10) Python Arduino Interfacing
  • 2. Arduino and MS Excel Interface with Python
  • 4. Firmata • Firmata (Italian word) Library is use to make Arduino board as Slave board for Computer programs like Python, C etc. • Simply it MAKES or ADD IO pins to computer
  • 5. Process of Interfacing Arduino • Configure Arduino with Standard Firmata Program • Interface Arduino through PC or Laptop via PyFirmata package
  • 7. Open Standard Firmata from Example
  • 8. Upload the Standard Firmata program to Arduino Board
  • 9. Complete the Arduino IDE window • Arduino Board is Configure with Firmata. Note the Port name: Tool>>Port>>Port_Name • No need of Arduino Software further, so close it
  • 10. Working on PyFirmata • PyFirmata is not a build-in package for Python IDLE, so first install PyFirmata
  • 11. Initializing PyFirmata 1) Import Module import pyfirmata 2) Initialize Arduino Board and Com Port Name Syntax: board_name_variable = pyfirmata.Arduino_Board(Com Port Name) Example: Arduino Uno board = pyfirmata.Arduino(‘COM4') Arduino Mega board = pyfirmata.ArduinoMega (‘COM4') Arduino Due board = pyfirmata.ArduinoDue (‘COM4') For Raspberry pi the com name will be /dev/ttyACM0 Example: board = pyfirmata.Arduino('/dev/ttyACM0')
  • 12. Setup Pin The get_pin function is used to set pin as Input or Output and also set the Syntax: Pin_name = board_name.get_pin(‘d/a:pin_number:i/o’) Example: • LED = board.get_pin('d:13:o') • switch = board.get_pin('d:4:i') • analog = board.get_pin('a:0:i') • led_PWM = board.get_pin('d:10:p') • servo = board.get_pin('d:11:s') Working Signal Type a (analog) d (digital) i (input)   o (output)   p (PWM)   s (servo)  
  • 13. Digital Output import pyfirmata from time import sleep board = pyfirmata.Arduino("COM4") led = board.get_pin('d:13:o') print("Press Ctrl + c to Exit") try: while True: #Infinite Loop led.write(1) #ON LED sleep(1) #Delay led.write(0) #OFF LED sleep(1) #Delay except: print("Program End!") finally: led.write(0) #Clear LED before close board.exit()
  • 15. Analog Out (PWM) import pyfirmata board = pyfirmata.Arduino("COM4") led_brightness = board.get_pin("d:3:p") print("Press Ctrl + c to Exit") try: while True: duty = int(input("Enter Brightness (0 to 100)= ")) led_brightness.write(duty / 100.0) except: print("Program End!") finally: board.exit()
  • 16. Controlling a Servo Using PyFirmata
  • 17. Controlling a Servo Using PyFirmata import pyfirmata board = pyfirmata.Arduino("COM4") servo_pin = board.get_pin("d:7:s") print("Press Ctrl + c to Exit") try: while True: angle = int(input("Enter Angle (0 to 180):")) servo_pin.write(angle) except: print("Program End!") finally: board.exit()
  • 18. Reading Analog or Digital data from Arduino • PyFirmata uses the concept of an Iterator to monitor the Arduino input pin. The reasons for this are bound up in the implementation of Firmata. it = pyfirmata.util.Iterator(board) it.start() Pin_name.enable_reporting()
  • 19. Digital Input import pyfirmata board = pyfirmata.Arduino("COM4") switch = board.get_pin(“d:4:I”) led = board.get_pin(“d:7:o”) it = pyfirmata.util.Iterator(board) it.start() switch.enable_reporting() print("Press Ctrl + c to Exit") try: while True: if switch.read() == True: led.write(1) #ON LED print('Switch is High') else: led.write(0) #OFF LED print('Switch is Low') except: print("Program End!") finally: led.write(0) #Clear LED before close board.exit()
  • 20. Analog Read import pyfirmata from time import sleep board = pyfirmata.Arduino("COM4") analog = board.get_pin('a:0:i') it = pyfirmata.util.Iterator(board) it.start() analog.enable_reporting() print("Press Ctrl + c to Exit") try: while True: reading = analog.read() print(reading) sleep(1) except: print("Program End!") finally: board.exit()
  • 22. About MS Excel For today`s Workshop participant must know the following about MS Excel • Workbook • Worksheet • Cell • Rows address • Column address • Charts
  • 24. Writing data in MS Excel through Python import openpyxl from openpyxl import Workbook wb = Workbook() ws = wb.active ws1 = wb.create_sheet() ws.title = "Workshop Sheet" ws['A1'] = "Integer" ws['B1'] = "Float" ws['C1'] = "String" ws['A2'] = 1000 ws['B2'] = 50.50 ws['C2'] = "Hamdard" wb.save(r"C:.........workshop.xlsx")
  • 25. Handle the file open Error import openpyxl from openpyxl import Workbook try: wb = Workbook() ws = wb.active wb.save(r"C:.........workshop.xlsx") except PermissionError: print("Please close the MS Excel Workbook")
  • 26. Add Image and Merge Cell import openpyxl from openpyxl import Workbook from openpyxl.drawing.image import Image try: wb = Workbook() ws = wb.active ws.merge_cells('A1:B1') #Merge Cell ws['A1'] = "Pakistan Zindabad" Pak_Flag = Image(r"C:.........Pakistan.PNG") ws.add_image(Pak_Flag, 'A2') wb.save(r"C:.........workshop.xlsx") except PermissionError: print("Please close the MS Excel Workbook")
  • 27. Add Sheet to Workbook import openpyxl from openpyxl import Workbook try: wb = Workbook() ws = wb.active #First Sheet ws.title = "First" ws['A25'] = "First Sheet" ws2 = wb.create_sheet() #New Sheet ws2['A25'] = "Second Sheet" ws2.title = "Second" ws3 = wb.create_sheet() #New Sheet ws3['A25'] = "Third Sheet" ws3.title = "Third" wb.save(r"C:.........workshop.xlsx") except PermissionError: print("Please close the MS Excel Workbook")
  • 28. Accessing Multiple cell import openpyxl from openpyxl import Workbook try: wb = Workbook() ws = wb.active ws['A1'] = "Number" ws['B1'] = "Square" for i in range(10): ws.cell(row = i+2 , column = 1 , value = i) ws.cell(row = i+2 , column = 2 , value = i*i) wb.save(r"C:.........workshop.xlsx") except PermissionError: print("Please close the MS Excel Workbook")
  • 29. Adding Chart to Worksheet
  • 30. Adding Chart to Worksheet import openpyxl from openpyxl import Workbook from openpyxl.chart import BarChart,Reference,Series try: wb = Workbook() ws = wb.active ws['A1'] = "Number" ws['B1'] = "Square" for i in range(1,11): ws.cell(row = i+1 , column = 1 , value = i) ws.cell(row = i+1 , column = 2 , value = i*i) #Working for Chart chart = BarChart() chart.title = "Square Values Chart" chart.style = 13 chart.x_axis.title = 'Number' chart.y_axis.title = 'Square of Number' x_axis = Reference(ws, min_col=1, min_row=2, max_row=i+1) y_axis = Reference(ws, min_col=2, min_row=1, max_col=2, max_row=i+1) chart.add_data(y_axis, titles_from_data=True) chart.set_categories(x_axis) ws.add_chart(chart, "D2") #Save Workbook wb.save(r"C:UsersHomeDesktopworkshop.xlsx") except PermissionError: print("Please close the MS Excel Workbook")
  • 31. Chart
  • 32. Workshop Exercise • Get Analog data from Arduino, Save it in Excel sheet and Generate its chart