Anda di halaman 1dari 13

JOB SHEET P3

ANTARMUKA ARDUINO DAN PYTHON

1 Tujuan Praktek :
Mahasiswa mampu membuat aplikasi antarmuka Arduino dan Python.

2 Daftar Perangkat/Komponen :
No Perangkat/Komponen Jumlah No Perangkat/Komponen Jumlah

1 Komputer/Laptop 1 5 Push button switch 1

2 Board Arduino Uno 1 6 PIR sensor 1

3 Kabel USB A-B 1 7 Protoboard 1

4 Potensiometer 1 8 Kabel jumper secukupnya

Page 1 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


3 Kegiatan Praktek (Uji coba dan Analisis Program)

3.1. Persiapan (instalasi program Python dan pendukungnya)


a. Download dan Install Python 2.7.x (python-2.7.12.msi).
b. Download dan Install Pyserial 2.7 (pyserial-2.7.win32.exe),
c. Download dan install VIDLE (VPython-Win-32-Py2.7-6.11.exe).
d. Download, ekstrak, dan install pyFirmata (pyFirmata.zip).
(Folder hasil ekstrak):\> python setup.py install
e. Download dan install matplotlib (matplotlib-1.2.0.win32-py2.7.exe).
f. Download, ekstrak, dan install drawnow (drawnow-0.71.2.zip).
(Folder hasil ekstrak):\> python setup.py install

3.2. Program sederhana antarmuka Arduino ke Python


Arduino PC

Ketik dan upload sketch berikut ini. a. Ketik dan jalankan source code di bawah ini di VIDLE.
b. Lihat dan analisis hasilnya.

int counter=0; import serial #Import Serial Library


void setup()
{ #Create Serial port object called arduinoSerialData
Serial.begin(9600); arduinoSerialData = serial.Serial('COMx',9600)

Page 2 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


}
while (1==1):
void loop() if (arduinoSerialData.inWaiting()>0):
{ myData = arduinoSerialData.readline()
Serial.print("I am Counting to : "); print myData
Serial.print(counter);
Serial.println(" Mississippi.");
counter = counter + 1;
delay(1000);
}

3.3. Firmata
Firmata merupakan salah satu protokol komunikasi serial antara mikrokontroler (termasuk Arduino) dan software di
komputer. Firmata dapat mengakses Arduino secara langsuing melalui software dan menghilangkan proses modifikasi
dan uploading sketch.

Arduino PC

Buka dan upload sketch StandardFirmata.ino : a. Jalankan file firmata_test.exe lalu pilih port serial yang
File -> Examples -> Firmata -> StandardFirmata sesuai, misalnya Port -> COM3.
b. Atur konfigurasi pin Arduino melalui window Firmata
Test dan lihat hasilnya.

Page 3 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


3.4. Penggunaan PySerial secara Interaktif di Python Shell
pySerial merupakan library Python untuk komunikasi melalui port serial. Library ini menydiakan akses ke setting port
serial melalui Python properties dan mengkonfigurasi port serial secara langsung melalui interpreter python.

Arduino PC

Buka dan upload sketch DigitalReadSerial,ino : a. Jalankan Python shell

Page 4 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


File -> Examples -> 01 Basics -> DigitalReadSerial

/*
DigitalReadSerial
Reads a digital input on pin 2, prints the result to the
serial monitor

This example code is in the public domain.


*/

// digital pin 2 has a pushbutton attached to it. Give it a name: b. Ketik :


int pushButton = 2;
>>> import serial
// the setup routine runs once when you press reset: >>> s = serial.Serial('COMx',9600)
void setup() {
>>> while True:
// initialize serial communication at 9600 bits per second:
Serial.begin(9600); print s.readline()
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
} c. Operasikan push button di pin 2 Arduino dan lihat
hasilnya di Python shell.
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(1); // delay in between reads for stability
}

Page 5 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


3.5. Menghubungkan pySerial dan Firmata dengan pyFirmata
pyFirmata merupakan library Python yang dibuat pada pySerial untuk mendukung protokol Firmata. Selain pyFirmata,
Python memiliki beberapa library lain yang bisa mendukung Firmata.

Arduino PC

Buka dan upload sketch StandardFirmata.ino .: a. Jalankan Python shell.

File -> Examples -> Firmata -> StandardFirmata B. Ketik dan analisis hasilnya.
>>> import pyfirmata
>>> pin= 13
>>> port = “COMx”
>>> board = pyfirmata.Arduino(port)
>>> board.digital[pin].write(1)
>>> board.digital[pin].write(0)
>>> board.digital[pin].read()

3.6. Plotting grafik dengan matplotlib


matplotlib : python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and
interactive environments across platforms. matplotlib can be used in python scripts, the python and ipython shell (ala
MATLAB or Mathematica), web application servers, and six graphical user interface toolkits.
Page 6 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python
Pengujian matplotlib
3.6.1. Sinusoida 3.6.2. Sinusoida dan Cosinusoida

a. Ketik dan jalankan di VIDLE. a. Ketik dan jalankan di VIDLE.


b. Analisis hasilnya. b. Analisis hasilnya.

import numpy as np import numpy as np #import numpy library


import matplotlib.pyplot as plt import matplotlib.pyplot as plt #import matplotlib

x=[] x= np.linspace( 0, 2*np.pi, 50)#create your x array


y=[] y= np.sin(x) #create y array
z= np.cos(x) #create z array
for i in np.arange(0,2*np.pi,2*np.pi/1000): plt.plot(x,y, 'b-d', linewidth=2, label='sinx') #plot y
x.append(i) plt.plot(x,z, 'r-o', linewidth=2, label='cosx') #plot z
y.append(np.sin(i)) plt.grid(True) #display background grid
plt.axis([0,2*np.pi,-1.5,1.5]) #set range on axis
plt.plot(x,y, 'b-', linewidth=2) plt.title('My Sin and Cos Waves') #chart title
plt.grid(True) plt.xlabel('Time in Seconds') #label x axis
plt.axis([0,2*np.pi,-1.5,1.5]) plt.ylabel('My Waves') #label y axis
plt.title('My Sine Wave') plt.legend() #show legend
plt.xlabel('Time in Seconds') plt.show() #show the plot
plt.ylabel('Sin(t)')
plt.show()

Page 7 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


3.7. Plot Live Data dari Arduino ke Python dengan matplotlib dan drawnow

Arduino PC

a. Buka dan upload Modifikasi source code berikut supaya bisa menampilkan secara live nilai potensiometer
sketch yang diatur di Arduino.
AnalogOutSerial.ino .:
import serial # import Serial Library
File -> Examples -> import numpy # Import numpy
03 Analog -> import matplotlib.pyplot as plt #import matplotlib library
AnalogOutSerial from drawnow import *

b. Analisis sketch-nya. tempF= []


pressure=[]
arduinoData = serial.Serial('com11', 115200) #Creating our serial object named
#arduinoData
plt.ion() #Tell matplotlib you want interactive mode to plot live data
cnt=0
def makeFig(): #Create a function that makes our desired plot
plt.ylim(80,90) #Set y min and max values
plt.title('My Live Streaming Sensor Data') #Plot the title
plt.grid(True) #Turn the grid on
plt.ylabel('Temp F') #Set ylabels
plt.plot(tempF, 'ro-', label='Degrees F') #plot the temperature
plt.legend(loc='upper left') #plot the legend
plt2=plt.twinx() #Create a second y axis

Page 8 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


plt.ylim(93450,93525) #Set limits of second y axis- adjust to readings you are getting
plt2.plot(pressure, 'b^-', label='Pressure (Pa)') #plot pressure data
plt2.set_ylabel('Pressrue (Pa)') #label second y axis
plt2.ticklabel_format(useOffset=False) #Force matplotlib to NOT autoscale y axis
plt2.legend(loc='upper right') #plot the legend
while True: # While loop that loops forever
while (arduinoData.inWaiting()==0): #Wait here until there is data
pass #do nothing
arduinoString = arduinoData.readline() #read the line of text from the serial port
dataArray = arduinoString.split(',') #Split it into an array called dataArray
temp = float( dataArray[0]) #Convert 1st element to floating number and put in temp
P = float( dataArray[1]) #Convert second element to floating number and put in P
tempF.append(temp) #Build our tempF array by appending temp readings
pressure.append(P) #Building our pressure array by appending P readings
drawnow(makeFig) #Call drawnow to update our live graph
plt.pause(.000001) #Pause Briefly. Important to keep drawnow from crashing
cnt=cnt+1
if(cnt>50): #If you have 50 or more points, delete the first one from the array
tempF.pop(0) #This allows us to just see the last 50 data points
pressure.pop(0)

Page 9 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


3.8. Motion-triggered LEDs

Tujuan :
Menghasilkan alert berupa nyala LED merah jika terdeteksi ada gerakan dan menampilkan kondisi normal dengan
nyala LED hijau.

Deskripsi :
a. Mendeteksi setiap gerakan dengan passive infrared (PIR) sensor
b. Menghasilkan blink LED merah jika ada gerakan.
c. Selain dari pada itu, LED hijau blinking
d. Sistem tetap dalam kondisi looping dalam mendeteksi gerakan.

Flow Chart :

Page 10 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


Arduino PC

Buka dan upload sketch StandardFirmata.ino .: a. Buka VIDLE dan ketik :


b. Jalankan, amati, dan analisis hasilnya.
File -> Examples -> Firmata -> StandardFirmata
#!/usr/bin/python

# Import required libraries


import pyfirmata
from time import sleep

# Define custom function to perform Blink action


def blinkLED(pin, message):
print message
board.digital[pin].write(1)
sleep(1)
board.digital[pin].write(0)
sleep(1)

# Associate port and board with pyFirmata


port = “COMx”
board = pyfirmata.Arduino(port)

# Use iterator thread to avoid buffer overflow


it = pyfirmata.util.Iterator(board)
it.start()

Page 11 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


# Define pins
pirPin = board.get_pin('d:7:i')
redPin = 12
greenPin = 13

# Check for PIR sensor input


while True:
# Ignore case when receiving None value from pin
value = pirPin.read()
while value is None:
pass

if value is True:
# Perform Blink using custom function
blinkLED(redPin, "Motion Detected")
else:
# Perform Blink using custom function
blinkLED(greenPin, "No motion Detected")

# Release the board


board.exit()

Page 12 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python


4 DIY-P3
Buatlah sendiri satu aplikasi antarmuka Arduino dan Python.
Jelaskan cara kerja alat, gambarkan skematik dan flow chart, serta tulis sketch-nya.

awagyana@gmail.com

Page 13 of 13 | Job Sheet P3 : Antarmuka Arduino dan Python

Anda mungkin juga menyukai