Minggu, 02 Oktober 2016

Python GPIO Raspberry Button Input



The GPIO pins on a Raspberry Pi are a great way to interface physical devices like buttons and LEDs with the little Linux processor. If you’re a Python developer, there’s a sweet library called RPi.GPIO that handles interfacing with the pins. In just three lines of code, you can get an LED blinking on one of the GPIO pins.
Not sure if Raspberry Pi is right for you? Make:’s interactive Board Guide lets you dial into the field to find the best board for your needs.

Installation

The newest version of Raspbian has the RPi.GPIO library pre-installed. You’ll probably need to update your library, so using the command line, run:
sudo python
import RPi.GPIO as GPIO
GPIO.VERSION

The current version of RPi.GPIO is 0.5.4 If you need to update to a newer version, run:
sudo apt-get update
sudo apt-get upgrade

If you don’t have the RPi.GPIO library because you’re using an older version of Raspbian, there are great instructions on the Raspberry Pi Spy website on installing the package from scratch.

Using the RPi.GPIO Library

Now that you’ve got the package installed and updated, let’s take a look at some of the functions that come with it. Open the Leafpad text editor and save your sketch as “myInputSketch.py”. From this point forward, we’ll execute this script using the command line:
sudo python myInputSketch.py
All of the following code can be added to this same file. Remember to save before you run the above command. To exit the sketch and make changes, press Ctrl+C.
To add the GPIO library to a Python sketch, you must first import it:
import RPi.GPIO as GPIO
Then we need to declare the type of numbering system we’re going to use for our pins:
#set up GPIO using BCM numbering
GPIO.setmode(GPIO.BCM)
#setup GPIO using Board numbering
GPIO.setmode(GPIO.BOARD)

The main difference between these modes is that the BOARD option uses the pins exactly as they are laid out on the Pi. No matter what revision you’re using, these will always be the same. The BCM option uses the Broadcom SoC numbering, which differs between version 1 and version 2 of the Pi.
GPIO BCM Descriptions
from Meltwater’s Raspberry Pi Hardware
In the image above, you’ll see that Pin 5 is GPIO01/03. This means that a v.1 Pi is GPIO 01, while a v.2 Pi is GPIO 03. The BCM numbering is what I’ll be using for the rest of this entry, because it’s universal across other programming languages.

Building a Circuit

Now we’re going to get into inputs and outputs. In the circuit shown below, two momentary switches are wired to GPIO pins 23 and 24 (pins 16 and 18 on the board). The switch on pin 23 is tied to 3.3V, while the switch on pin 24 is tied to ground. The reason for this is that the Raspberry Pi has internal pull-up and pull-down resistors that can be specified when the pin declarations are made.
Raspberry Pi Circuit
To set up these pins, write:
GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(24, GPIO.IN, pull_up_down=GPIO.PUD_UP)

This will enable a pull-down resistor on pin 23, and a pull-up resistor on pin 24. Now, let’s check to see if we can read them. The Pi is looking for a high voltage on Pin 23 and a low voltage on Pin 24. We’ll also need to put these inside of a loop, so that it is constantly checking the pin voltage. The code so far looks like this:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)
while True:
if(GPIO.input(23) ==1):
print(“Button 1 pressed”)
if(GPIO.input(24) == 0):
print(“Button 2 pressed”)
GPIO.cleanup()

The indents in Python are important when using loops, so be sure to include them. You also must run your script as “sudo” to access the GPIO pins. The GPIO.cleanup() command at the end is necessary to reset the status of any GPIO pins when you exit the program. If you don’t use this, then the GPIO pins will remain at whatever state they were last set to.

The Problem With Polling

This code works, but prints a line for each frame that the button is pressed. This is extremely inconvenient if you want to use that button to trigger an action or command only one time. Luckily, the GPIO library has built in a rising-edge and falling-edge function. A rising-edge is defined by the time the pin changes from low to high, but it only detects the change. Similarly, the falling-edge is the moment the pin changes from high to low. Using this definition, let’s change our code slightly:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)
while True:
GPIO.wait_for_edge(23, GPIO.RISING)
print(“Button 1 Pressed”)
GPIO.wait_for_edge(23, GPIO.FALLING)
print(“Button 1 Released”)
GPIO.wait_for_edge(24, GPIO.FALLING)
print(“Button 2 Pressed”)
GPIO.wait_for_edge(24, GPIO.RISING)
print(“Button 2 Released”)
GPIO.cleanup()

When you run this code, notice how the statement only runs after the edge detection occurs. This is because Python is waiting for this specific edge to occur before proceeding with the rest of the code. What happens if you try to press button 2 before you let go of button 1? What happens if you try to press button 1 twice without pressing button 2? Because the code is written sequentially, the edges must occur in exactly the order written.
Edge Detection is great if you need to wait for an input before continuing with the rest of the code. However, if you need to trigger a function using an input device, then events and callback functions are the best way to do that.

Events and Callback Functions

Let’s say you’ve got the Raspberry Pi camera module, and you’d like it to snap a photo when you press a button. However, you don’t want your code to poll that button constantly, and you certainly don’t want to wait for an edge because you may have other code running simultaneously.
The best way to execute this code is using a callback function. This is a function that is attached to a specific GPIO pin and run whenever that edge is detected. Let’s try one:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP)
def printFunction(channel):
print(“Button 1 pressed!”)
print(“Note how the bouncetime affects the button press”)
GPIO.add_event_detect(23, GPIO.RISING, callback=printFunction, bouncetime=300)
while True:
GPIO.wait_for_edge(24, GPIO.FALLING)
print(“Button 2 Pressed”)
GPIO.wait_for_edge(24, GPIO.RISING)
print(“Button 2 Released”)
GPIO.cleanup()

You’ll notice here that button 1 will consistently trigger the printFunction, even while the main loop is waiting for an edge on button 2. This is because the callback function is in a separate thread. Threads are important in programming because they allow things to happen simultaneously without affecting other functions. Pressing button 1 will not affect what happens in our main loop.
Events are also great, because you can remove them from a pin just as easily as you can add them:
GPIO.remove_event_detect(23)
Now you’re free to add a different function to the same pin!


Reff:
http://makezine.com/projects/tutorial-raspberry-pi-gpio-pins-and-python/

Enabling The I2C Interface On The Raspberry Pi



I2C is a multi-device bus used to connect low-speed peripherals to computers and embedded systems. The Raspberry Pi supports this interface on its GPIO header and it is a great way to connect sensors and devices. Once configured you can connect more than one device without using up additional pins on the header.
Before using I2C it needs to be configured. This technique has changed slightly with the latest version of Raspbian so I’ve updated this article.

Step 1 – Enable i2c using raspi-config utility

From the command line type :
sudo raspi-config
This will launch the raspi-config utility.
Enable SPI Using Raspi-config
Now complete the following steps :
  • Select “Advanced Options”
  • Select “I2C”
The screen will ask if you want the ARM I2C interface to be enabled :
  • Select “Yes”
  • Select “Ok”
  • Select “Finish” to return to the command line
When you next reboot the I2C module will be loaded.

Step 2 – Install Utilities

To help debugging and allow the i2c interface to be used within Python we can install “python-smbus” and “i2c-tools” :
sudo apt-get update
sudo apt-get install -y python-smbus i2c-tools

Step 3 – Shutdown

Shutdown your Pi using :
sudo halt
Wait ten seconds, disconnect the power to your Pi and you are now ready to connect your I2C hardware.

Checking If I2C Is Enabled (Optional)

When you power up or reboot your Pi you can check the i2c module is running by using the following command :
lsmod | grep i2c_
That will list all the modules starting with “i2c_”. If it lists “i2c_bcm2708” then the module is running correctly.

Testing Hardware (Optional)

Once you’ve connected your hardware double check the wiring. Make sure 3.3V is going to the correct pins and you’ve got not short circuits. Power up the Pi and wait for it to boot.
If you’ve got a Model A, B Rev 2 or B+ Pi then type the following command :
sudo i2cdetect -y 1
If you’ve got an original Model B Rev 1 Pi then type the following command :
sudo i2cdetect -y 0
Why the difference? Between the Rev 1 and Rev 2 versions of the Pi they changed the signals that went to Pin 3 and Pin 5 on the GPIO header. This changed the device number that needs to be used with I2C from 0 to 1.
I used a Pi 2 Model B with a sensor connected and my output looked like this :
pi@raspberrypi ~ $ sudo i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: 20 -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
This shows that I’ve got one device connected and its address is 0x20 (32 in decimal).
sehingga saat nantinya di akses python adalah dengan code address sbb:

import smbus
import time

# Define some device parameters
I2C_ADDR  = 0x20 # I2C device address
LCD_WIDTH = 16   # Maximum characters per line

# Define some device constants
LCD_CHR = 1 # Mode - Sending data
LCD_CMD = 0 # Mode - Sending command


reff:
http://www.raspberrypi-spy.co.uk/2014/11/enabling-the-i2c-interface-on-the-raspberry-pi/

Belajar Dasar-Dasar Python Raspberry Pi

Kursus Hari2 Materi2


Konfigurasi hak akses
sudo raspi-config
pilih change_pass menu option & enter a new password

Konfigurasi Keyboard

By default, the Raspian image uses a English UK keyboard setup, which can lead to some confusion. For those in the US, following the following steps to fix the keyboard:

At the terminal, run
sudo raspi-config
Choose the configure_keyboard menu option
Other
English (US)
English (US) - yes, again

Additionally, if you like using the Caps Lock as Ctrl instead, run the following command:
setxkbmap -option "ctrl:nocaps"
Reboot

To make sure things are in order, reboot your RaspberryPi. This is typically only necessary if you alter the video memory setup or use the entire SD card for the Raspian setup.

sudo reboot


INTALL PYTHON


python setup.py install

ketik filenya berikut codenya lalu jalankan
python hello-world.py.


Latihan YUK:

print "Selamat Belajar Python"
print "Sukses!"
#-------------------------------------------------------
nilai = input("Nilai ujian (0-100):")

if nilai >= 60:
    print "Lulus"
else:
    print "Tidak lulus"
#-------------------------------------------------------
tinggi = input("Tinggi segitiga: ")

baris = 1
while baris <= tinggi:
    print "*" * baris
    baris = baris + 1
#-------------------------------------------------------
x = 254

print "%d" % x
print "%8d" % x
print "%10d" % x

x = -254
y = 2.4678e-4

print "Format %%i: %i" % x
print "Format %%d: %d" % x
print "Format %%o: %o" % x
print "Format %%x: %x" % x
print "Format %%X: %X" % x
print "Format %%S: %s" % x

print "Format %%e: %e" % y
print "Format %%E: %E" % y
print "Format %%f: %f" % y
print "Format %%G: %G" % y
print "Format %%g: %g" % y
print "Format %%S: %s" % y

#-------------------------------------------------------
import math

kecepatan = input("Kecepatan: ")
sudut     = input("Sudut (derajat): ");

sudut = math.radians(sudut)
jarak = 2 * kecepatan * kecepatan * \
        math.sin(sudut) * math.cos(sudut) / 9.8

print "Jarak = ", jarak
#-------------------------------------------------------
nilai = input("Nilai ujian (0-100): ")

if nilai >= 90:
    print "A"
elif nilai >= 70:
    print "B"
elif nilai >= 60:
    print "C"
elif nilai >= 50:
    print "D"
else:
    print "E"
#-------------------------------------------------------
print "Menjumlah dua buah bilangan"

x = input("bilangan pertama: ")
y = input("bilangan kedua: ")

print "Jumlah = ",  (x+y)
#-------------------------------------------------------
while True:
    try:
        bil = input("Masukkan bilangan: ")
        break
    except SyntaxError:
        print("Anda salah memasukkan bilangan")
    except KeyboardInterrupt:
        print("\nMaaf jangan menekan tombol Ctrl+C")

print "Anda memasukkan bilangan", bil
#-------------------------------------------------------

while True:
    try:
        bil = input("Masukkan bilangan: ")
        break
    except SyntaxError:
        print("Anda salah memasukkan bilangan")

print "Anda memasukkan bilangan", bil
#-------------------------------------------------------
import time

bulan = ("Januari", "Pebruari", "Maret",
         "April", "Mei", "Juni",
         "Juli", "Agustus", "September",
         "Oktober", "Nopember", "Desember")
hari = ("Minggu", "Senin", "Selasa",
        "rabu", "Kamis", "Jumat", "Sabtu")

sekarang = time.time()
infowaktu = time.localtime(sekarang)
print "Saat sekarang :"
print "Tanggal", infowaktu[2], \
      bulan[infowaktu[1]-1], infowaktu[0]

print "Hari", hari[infowaktu[6]]
print "Jam", str(infowaktu[3]) + ":" + \
             str(infowaktu[4]) + ":" + \
             str(infowaktu[5])
#-------------------------------------------------------
def hitung_luas_lingkaran():
    print "Menghitung luas lingkaran"
    radius = input("Jari-jari = ")
    luas = 3.14 * radius * radius
    print "Luas=", luas

def hitung_luas_persegipanjang():
    print "Menghitung luas persegi panjang"
    panjang = input("Panjang = ")
    lebar   = input("Lebar   = ")
    luas = panjang * lebar
    print "Luas=", luas


# Program utama
print "Menghitung luas"
print "1. Lingkaran"
print "2. Persegipanjang"

pilihan = input("Pilihan (1 atau 2): ")
if pilihan == 1:
    hitung_luas_lingkaran()
elif pilihan == 2:
    hitung_luas_persegipanjang()
else:
    print "Pilihan salah"
#-------------------------------------------------------
daftar = ["1234", 2, "Edi", 1999]
jumlah = 0

for nilai in daftar:
    try:
        bil = int(nilai)
        jumlah = jumlah + 1
    except ValueError:
        pass

print "Jumlah elemen berupa bilangan:", jumlah
#-------------------------------------------------------
kalimat = raw_input("Masukkan suatu kalimat: ")
jumkar = {}
for kar in kalimat:
    jumkar[kar] = jumkar.get(kar,0) + 1

# Tampilkan frekuensi karakter
for kar in jumkar.keys():
    if kar == " ":
        print "Spasi = ",
    else:
        print kar, "=",

    print jumkar[kar]
#-------------------------------------------------------

daftar_nama = [ "Anwar Suadi", "Ahmad Jazuli",
                "Safitri", "Edi Juanedi",
                "Dian Anggraeni", "Rahmat Anwari"]

dicari = raw_input("Penggalan nama yang dicari: ")

indeks = 0
ketemu = False

while indeks <= len(daftar_nama):
    if dicari in daftar_nama[indeks]:
        ketemu = True
        break

    indeks = indeks + 1

if ketemu:
    print "Nama yang Anda cari cocok dengan: "
    print daftar_nama[indeks]
else:
    print "Tak ada yang cocok"
#-------------------------------------------------------
inp = raw_input('Enter Fahrenheit Temperature:')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel
#-------------------------------------------------------
a = False
b = True

print ("a or b = ", a or b)
print ("a and b = ", a and b)
print ("not a = ", not a)
print ("not b = ", not b)
#-------------------------------------------------------
a = 21
b = 10

if ( a == b ):
   print "Baris 1 - a sama dengan b"
else:
   print "Baris 1 - a tidak sama dengan b"

if ( a != b ):
   print "Baris 2 - a tidak sama dengan b"
else:
   print "Baris 2 - a sama dengan b"

if ( a <> b ):
   print "Baris 3 - a tidak sama dengan b"
else:
   print "Baris 3 - a sama dengan b"

if ( a < b ):
   print "Baris 4 - a kurang dari b"
else:
   print "Baris 4 - a tidak kurang dari b"

if ( a > b ):
   print "Baris 5 - a lebih dari b"
else:
   print "Baris 5 - a tidak lebih dari b"

a = 5;
b = 20;
if ( a <= b ):
   print "Baris 6 - a kurang dari atau sama dengan b"
else:
   print "Baris 6 - a tidak kurang dari b"

if ( b >= a ):
   print "Baris 7 - a lebih dari atau sama dengan b"
else:
   print "Baris 7 - a tidak lebih dari b"
#-------------------------------------------------------
a = 15            # 60 = 0011 1100
b = 12            # 13 = 0000 1101
c = 0

c = a & b;        # 12 = 0000 1100
print "Baris 1 - Nilai dari c adalah ", c

c = a | b;        # 61 = 0011 1101
print "Baris 2 - Nilai dari c adalah ", c

c = a ^ b;        # 49 = 0011 0001
print "Baris 3 - Nilai dari c adalah ", c

c = ~a;           # -61 = 1100 0011
print "Baris 4 - Nilai dari c adalah ", c

c = a << 2;       # 240 = 1111 0000
print "Baris 5 - Nilai dari c adalah ", c

c = a >> 2;       # 15 = 0000 1111
print "Baris 6 - Nilai dari c adalah ", c
#-------------------------------------------------------
x = raw_input ('Masukkan nilai x = ')
y = raw_input ('Masukkan nilai y = ')

if x < y:
   print 'x is less than y'
elif x > y:
   print 'x is greater than y'
else:
   print 'x and y are equal'
#-------------------------------------------------------
x = raw_input ('Masukkan nilai x = ')
y = raw_input ('Masukkan nilai y = ')

if x == y:
      print 'x dan y adalah sama'
else:
      if x < y:
            print 'x kurang dari y'
      else:
            print 'x is lebih dari y'

if 0 < x:
   if x < 10:
       print 'x is a positive single-digit number.'
#-------------------------------------------------------
inp = raw_input('Enter Fahrenheit Temperature:')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel


#dengan try-except
inp = raw_input('Enter Fahrenheit Temperature:')
try:
  fahr = float(inp)
  cel = (fahr - 32.0) * 5.0 / 9.0
  print cel
except:
  print 'Please enter a number'
#-------------------------------------------------------
a = raw_input('Data masukan 1 :')
b = raw_input('Data masukan 2 :')

c=max(a)
d=min(b)

print c
print d
#-------------------------------------------------------
def print_sayhello():
     print "Hallo, apa kabar?"
     print "Saya senang Anda dapat memiliki dan menggunkan buku kami ini."


#memanggil fungsi di sini

print_sayhello ()  

#-------------------------------------------------------
def faktorial (a):
  if a == 1 :
      print a
      return 1
  else :
      print a
      return ( a * faktorial(a-1))

#program utama

m=raw_input ('Masukkan angka : ')
try :
  x=int(m)
  hasil=faktorial(x)
  print "Hasil faktorial ",x," adalah ", hasil
except:
  print "Data yang dimasukan salah, ulangi!"
#-------------------------------------------------------
N=raw_input ("jumlah loop N = ")
try :
   m=int(N)
   while m > 0 :
      print m
      m=m-1

   print  "BLASTOFF!"
except :
    print "Salah entry data"
#-------------------------------------------------------
i=1
while 1:
   i +=1
   print i
   if i == 1000:
      i=0
#stop with KeyboardInterrupt: tekan CTRL C di Windwows dan CTRL Z di Raspberry
print 'selesai ...'
#-------------------------------------------------------
i=1
while 1:
   i +=1
   print i
   if i == 1000:
      break
#stop with break
print 'selesai ...'
#-------------------------------------------------------
while True:
   print 'Ketik "done" untuk keluar dari loop ini'
   line = raw_input('> ')
   if line == 'done':
      break
   else :
      continue
   print line

print 'Done!'
 
#-------------------------------------------------------
temantemin = ['Edi', 'Faisal', 'Fajar']
for teman in temantemin:
   print 'Selamat bekerja kawanku,', teman,' !'

print 'SELESAI!'
 
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
count = 0
for itervar in data:
      count = count + 1
      print count,itervar

print 'Count: ', count
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
total = 0
for itervar in data:
      total = total + itervar
      print total
   
print 'Jumlah: ', total
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
total = 0
for itervar in data:
      total = total + itervar
      print total
   
print 'Jumlah: ', total
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
terbesar = None
print 'Sebelum: ', terbesar

for itervar in data:
      if terbesar is None or itervar > terbesar :
          terbesar = itervar
      print 'Loop:', itervar, terbesar

print 'Data terbesar : ', terbesar






#-------------------------------------------------------
wadah = "lp2m"
panjang = len(wadah)
firstletter=wadah[0]
lastletter=wadah[len(wadah)-1]
print "Panjang         : ",len(wadah)
print "Huruf pertama   : ",firstletter
print "Huruf terakhir  : ",lastletter

print "Susunan letter wadah dilooping : ", "\n"
hit=0
for i in wadah :
   print "Letter ke-",hit," adalah ",i
   hit+=1

#-------------------------------------------------------
fruit='manggo'
index = 0
a=len(fruit)
while index < a:
   letter = fruit[index]
   print letter
   index = index + 1

#-------------------------------------------------------
fhand = open('mbox.txt')
count = 0
for line in fhand:
    count = count + 1
print 'Line Count:', count
#-------------------------------------------------------
fhand = open('pesan.txt')
inp = fhand.read()
print len(inp)
print inp[:36]
#-------------------------------------------------------
NIM=['1120329','1120330','1120332','1120333','1120335','1120336']
NAMA=['Udin Suridin','Maman Suherman','Toto Suharto','Leban Pangaribuan','Bonbon Bonjovi','Miseline Adeleide']
NOHP=['628128283344','628128281244','6281358281244','628123456789','62817582812','628535822322']


f = raw_input("Nama file tanpa extention : ")
fon = f + '.csv'
fo=open(fon,"a")
c=0
while c < 6  :
    print '%s ; %20s ; %13s \n' %(NIM[c],str(NAMA[c]),str(NOHP[c]))
    fo.write(str(NIM[c]) + "; " + str(NAMA[c]) + "; " + str(NOHP[c]) + "\n")
    c+=1
fo.close()




def print_sayhello():
     print "Hallo, apa kabar? i'm lp2maray.com"
     print "Saya senang Anda dapat memiliki dan menggunkan buku kami ini."


#memanggil fungsi di sini

print_sayhello ()  

#-------------------------------------------------------
def faktorial (a):
  if a == 1 :
      print a
      return 1
  else :
      print a
      return ( a * faktorial(a-1))

#program utama

m=raw_input ('Masukkan angka : ')
try :
  x=int(m)
  hasil=faktorial(x)
  print "Hasil faktorial ",x," adalah ", hasil
except:
  print "Data yang dimasukan salah, ulangi!"
#-------------------------------------------------------

def hitung_luas_lingkaran():
    print "Menghitung luas lingkaran"
    radius = input("Jari-jari = ")
    luas = 3.14 * radius * radius
    print "Luas=", luas

def hitung_luas_persegipanjang():
    print "Menghitung luas persegi panjang"
    panjang = input("Panjang = ")
    lebar   = input("Lebar   = ")
    luas = panjang * lebar
    print "Luas=", luas


# Program utama
print "Menghitung luas"
print "1. Lingkaran"
print "2. Persegipanjang"

pilihan = input("Pilihan (1 atau 2): ")
if pilihan == 1:
    hitung_luas_lingkaran()
elif pilihan == 2:
    hitung_luas_persegipanjang()
else:
    print "Pilihan salah"
#--------------------------


Selamat Mencoba

Pemrograman pada Raspberry PI

Kursus Hari2 Materi2


Konfigurasi hak akses
sudo raspi-config
pilih change_pass menu option & enter a new password

Konfigurasi Keyboard

By default, the Raspian image uses a English UK keyboard setup, which can lead to some confusion. For those in the US, following the following steps to fix the keyboard:

At the terminal, run
sudo raspi-config
Choose the configure_keyboard menu option
Other
English (US)
English (US) - yes, again

Additionally, if you like using the Caps Lock as Ctrl instead, run the following command:
setxkbmap -option "ctrl:nocaps"
Reboot

To make sure things are in order, reboot your RaspberryPi. This is typically only necessary if you alter the video memory setup or use the entire SD card for the Raspian setup.

sudo reboot


INTALL PYTHON


python setup.py install

ketik filenya berikut codenya lalu jalankan
python hello-world.py.


Latihan YUK:

print "Selamat Belajar Python"
print "Sukses!"
#-------------------------------------------------------
nilai = input("Nilai ujian (0-100):")

if nilai >= 60:
    print "Lulus"
else:
    print "Tidak lulus"
#-------------------------------------------------------
tinggi = input("Tinggi segitiga: ")

baris = 1
while baris <= tinggi:
    print "*" * baris
    baris = baris + 1
#-------------------------------------------------------
x = 254

print "%d" % x
print "%8d" % x
print "%10d" % x

x = -254
y = 2.4678e-4

print "Format %%i: %i" % x
print "Format %%d: %d" % x
print "Format %%o: %o" % x
print "Format %%x: %x" % x
print "Format %%X: %X" % x
print "Format %%S: %s" % x

print "Format %%e: %e" % y
print "Format %%E: %E" % y
print "Format %%f: %f" % y
print "Format %%G: %G" % y
print "Format %%g: %g" % y
print "Format %%S: %s" % y

#-------------------------------------------------------
import math

kecepatan = input("Kecepatan: ")
sudut     = input("Sudut (derajat): ");

sudut = math.radians(sudut)
jarak = 2 * kecepatan * kecepatan * \
        math.sin(sudut) * math.cos(sudut) / 9.8

print "Jarak = ", jarak
#-------------------------------------------------------
nilai = input("Nilai ujian (0-100): ")

if nilai >= 90:
    print "A"
elif nilai >= 70:
    print "B"
elif nilai >= 60:
    print "C"
elif nilai >= 50:
    print "D"
else:
    print "E"
#-------------------------------------------------------
print "Menjumlah dua buah bilangan"

x = input("bilangan pertama: ")
y = input("bilangan kedua: ")

print "Jumlah = ",  (x+y)
#-------------------------------------------------------
while True:
    try:
        bil = input("Masukkan bilangan: ")
        break
    except SyntaxError:
        print("Anda salah memasukkan bilangan")
    except KeyboardInterrupt:
        print("\nMaaf jangan menekan tombol Ctrl+C")

print "Anda memasukkan bilangan", bil
#-------------------------------------------------------

while True:
    try:
        bil = input("Masukkan bilangan: ")
        break
    except SyntaxError:
        print("Anda salah memasukkan bilangan")

print "Anda memasukkan bilangan", bil
#-------------------------------------------------------
import time

bulan = ("Januari", "Pebruari", "Maret",
         "April", "Mei", "Juni",
         "Juli", "Agustus", "September",
         "Oktober", "Nopember", "Desember")
hari = ("Minggu", "Senin", "Selasa",
        "rabu", "Kamis", "Jumat", "Sabtu")

sekarang = time.time()
infowaktu = time.localtime(sekarang)
print "Saat sekarang :"
print "Tanggal", infowaktu[2], \
      bulan[infowaktu[1]-1], infowaktu[0]

print "Hari", hari[infowaktu[6]]
print "Jam", str(infowaktu[3]) + ":" + \
             str(infowaktu[4]) + ":" + \
             str(infowaktu[5])
#-------------------------------------------------------
def hitung_luas_lingkaran():
    print "Menghitung luas lingkaran"
    radius = input("Jari-jari = ")
    luas = 3.14 * radius * radius
    print "Luas=", luas

def hitung_luas_persegipanjang():
    print "Menghitung luas persegi panjang"
    panjang = input("Panjang = ")
    lebar   = input("Lebar   = ")
    luas = panjang * lebar
    print "Luas=", luas


# Program utama
print "Menghitung luas"
print "1. Lingkaran"
print "2. Persegipanjang"

pilihan = input("Pilihan (1 atau 2): ")
if pilihan == 1:
    hitung_luas_lingkaran()
elif pilihan == 2:
    hitung_luas_persegipanjang()
else:
    print "Pilihan salah"
#-------------------------------------------------------
daftar = ["1234", 2, "Edi", 1999]
jumlah = 0

for nilai in daftar:
    try:
        bil = int(nilai)
        jumlah = jumlah + 1
    except ValueError:
        pass

print "Jumlah elemen berupa bilangan:", jumlah
#-------------------------------------------------------
kalimat = raw_input("Masukkan suatu kalimat: ")
jumkar = {}
for kar in kalimat:
    jumkar[kar] = jumkar.get(kar,0) + 1

# Tampilkan frekuensi karakter
for kar in jumkar.keys():
    if kar == " ":
        print "Spasi = ",
    else:
        print kar, "=",

    print jumkar[kar]
#-------------------------------------------------------

daftar_nama = [ "Anwar Suadi", "Ahmad Jazuli",
                "Safitri", "Edi Juanedi",
                "Dian Anggraeni", "Rahmat Anwari"]

dicari = raw_input("Penggalan nama yang dicari: ")

indeks = 0
ketemu = False

while indeks <= len(daftar_nama):
    if dicari in daftar_nama[indeks]:
        ketemu = True
        break

    indeks = indeks + 1

if ketemu:
    print "Nama yang Anda cari cocok dengan: "
    print daftar_nama[indeks]
else:
    print "Tak ada yang cocok"
#-------------------------------------------------------
inp = raw_input('Enter Fahrenheit Temperature:')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel
#-------------------------------------------------------
a = False
b = True

print ("a or b = ", a or b)
print ("a and b = ", a and b)
print ("not a = ", not a)
print ("not b = ", not b)
#-------------------------------------------------------
a = 21
b = 10

if ( a == b ):
   print "Baris 1 - a sama dengan b"
else:
   print "Baris 1 - a tidak sama dengan b"

if ( a != b ):
   print "Baris 2 - a tidak sama dengan b"
else:
   print "Baris 2 - a sama dengan b"

if ( a <> b ):
   print "Baris 3 - a tidak sama dengan b"
else:
   print "Baris 3 - a sama dengan b"

if ( a < b ):
   print "Baris 4 - a kurang dari b"
else:
   print "Baris 4 - a tidak kurang dari b"

if ( a > b ):
   print "Baris 5 - a lebih dari b"
else:
   print "Baris 5 - a tidak lebih dari b"

a = 5;
b = 20;
if ( a <= b ):
   print "Baris 6 - a kurang dari atau sama dengan b"
else:
   print "Baris 6 - a tidak kurang dari b"

if ( b >= a ):
   print "Baris 7 - a lebih dari atau sama dengan b"
else:
   print "Baris 7 - a tidak lebih dari b"
#-------------------------------------------------------
a = 15            # 60 = 0011 1100
b = 12            # 13 = 0000 1101
c = 0

c = a & b;        # 12 = 0000 1100
print "Baris 1 - Nilai dari c adalah ", c

c = a | b;        # 61 = 0011 1101
print "Baris 2 - Nilai dari c adalah ", c

c = a ^ b;        # 49 = 0011 0001
print "Baris 3 - Nilai dari c adalah ", c

c = ~a;           # -61 = 1100 0011
print "Baris 4 - Nilai dari c adalah ", c

c = a << 2;       # 240 = 1111 0000
print "Baris 5 - Nilai dari c adalah ", c

c = a >> 2;       # 15 = 0000 1111
print "Baris 6 - Nilai dari c adalah ", c
#-------------------------------------------------------
x = raw_input ('Masukkan nilai x = ')
y = raw_input ('Masukkan nilai y = ')

if x < y:
   print 'x is less than y'
elif x > y:
   print 'x is greater than y'
else:
   print 'x and y are equal'
#-------------------------------------------------------
x = raw_input ('Masukkan nilai x = ')
y = raw_input ('Masukkan nilai y = ')

if x == y:
      print 'x dan y adalah sama'
else:
      if x < y:
            print 'x kurang dari y'
      else:
            print 'x is lebih dari y'

if 0 < x:
   if x < 10:
       print 'x is a positive single-digit number.'
#-------------------------------------------------------
inp = raw_input('Enter Fahrenheit Temperature:')
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel


#dengan try-except
inp = raw_input('Enter Fahrenheit Temperature:')
try:
  fahr = float(inp)
  cel = (fahr - 32.0) * 5.0 / 9.0
  print cel
except:
  print 'Please enter a number'
#-------------------------------------------------------
a = raw_input('Data masukan 1 :')
b = raw_input('Data masukan 2 :')

c=max(a)
d=min(b)

print c
print d
#-------------------------------------------------------
def print_sayhello():
     print "Hallo, apa kabar?"
     print "Saya senang Anda dapat memiliki dan menggunkan buku kami ini."


#memanggil fungsi di sini

print_sayhello ()  

#-------------------------------------------------------
def faktorial (a):
  if a == 1 :
      print a
      return 1
  else :
      print a
      return ( a * faktorial(a-1))

#program utama

m=raw_input ('Masukkan angka : ')
try :
  x=int(m)
  hasil=faktorial(x)
  print "Hasil faktorial ",x," adalah ", hasil
except:
  print "Data yang dimasukan salah, ulangi!"
#-------------------------------------------------------
N=raw_input ("jumlah loop N = ")
try :
   m=int(N)
   while m > 0 :
      print m
      m=m-1

   print  "BLASTOFF!"
except :
    print "Salah entry data"
#-------------------------------------------------------
i=1
while 1:
   i +=1
   print i
   if i == 1000:
      i=0
#stop with KeyboardInterrupt: tekan CTRL C di Windwows dan CTRL Z di Raspberry
print 'selesai ...'
#-------------------------------------------------------
i=1
while 1:
   i +=1
   print i
   if i == 1000:
      break
#stop with break
print 'selesai ...'
#-------------------------------------------------------
while True:
   print 'Ketik "done" untuk keluar dari loop ini'
   line = raw_input('> ')
   if line == 'done':
      break
   else :
      continue
   print line

print 'Done!'
 
#-------------------------------------------------------
temantemin = ['Edi', 'Faisal', 'Fajar']
for teman in temantemin:
   print 'Selamat bekerja kawanku,', teman,' !'

print 'SELESAI!'
 
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
count = 0
for itervar in data:
      count = count + 1
      print count,itervar

print 'Count: ', count
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
total = 0
for itervar in data:
      total = total + itervar
      print total
   
print 'Jumlah: ', total
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
total = 0
for itervar in data:
      total = total + itervar
      print total
   
print 'Jumlah: ', total
#-------------------------------------------------------
data = [3, 41, 12, 9, 74, 15]
terbesar = None
print 'Sebelum: ', terbesar

for itervar in data:
      if terbesar is None or itervar > terbesar :
          terbesar = itervar
      print 'Loop:', itervar, terbesar

print 'Data terbesar : ', terbesar






#-------------------------------------------------------
wadah = "lp2m"
panjang = len(wadah)
firstletter=wadah[0]
lastletter=wadah[len(wadah)-1]
print "Panjang         : ",len(wadah)
print "Huruf pertama   : ",firstletter
print "Huruf terakhir  : ",lastletter

print "Susunan letter wadah dilooping : ", "\n"
hit=0
for i in wadah :
   print "Letter ke-",hit," adalah ",i
   hit+=1

#-------------------------------------------------------
fruit='manggo'
index = 0
a=len(fruit)
while index < a:
   letter = fruit[index]
   print letter
   index = index + 1

#-------------------------------------------------------
fhand = open('mbox.txt')
count = 0
for line in fhand:
    count = count + 1
print 'Line Count:', count  
#-------------------------------------------------------
fhand = open('pesan.txt')
inp = fhand.read()
print len(inp)
print inp[:36]
#-------------------------------------------------------
NIM=['1120329','1120330','1120332','1120333','1120335','1120336']
NAMA=['Udin Suridin','Maman Suherman','Toto Suharto','Leban Pangaribuan','Bonbon Bonjovi','Miseline Adeleide']
NOHP=['628128283344','628128281244','6281358281244','628123456789','62817582812','628535822322']


f = raw_input("Nama file tanpa extention : ")
fon = f + '.csv'
fo=open(fon,"a")
c=0
while c < 6  :
    print '%s ; %20s ; %13s \n' %(NIM[c],str(NAMA[c]),str(NOHP[c]))
    fo.write(str(NIM[c]) + "; " + str(NAMA[c]) + "; " + str(NOHP[c]) + "\n")
    c+=1
fo.close()




def print_sayhello():
     print "Hallo, apa kabar?"
     print "Saya senang Anda dapat memiliki dan menggunkan buku kami ini."


#memanggil fungsi di sini

print_sayhello ()  

#-------------------------------------------------------
def faktorial (a):
  if a == 1 :
      print a
      return 1
  else :
      print a
      return ( a * faktorial(a-1))

#program utama

m=raw_input ('Masukkan angka : ')
try :
  x=int(m)
  hasil=faktorial(x)
  print "Hasil faktorial ",x," adalah ", hasil
except:
  print "Data yang dimasukan salah, ulangi!"
#-------------------------------------------------------

def hitung_luas_lingkaran():
    print "Menghitung luas lingkaran"
    radius = input("Jari-jari = ")
    luas = 3.14 * radius * radius
    print "Luas=", luas

def hitung_luas_persegipanjang():
    print "Menghitung luas persegi panjang"
    panjang = input("Panjang = ")
    lebar   = input("Lebar   = ")
    luas = panjang * lebar
    print "Luas=", luas


# Program utama
print "Menghitung luas"
print "1. Lingkaran"
print "2. Persegipanjang"

pilihan = input("Pilihan (1 atau 2): ")
if pilihan == 1:
    hitung_luas_lingkaran()
elif pilihan == 2:
    hitung_luas_persegipanjang()
else:
    print "Pilihan salah"
#-------------------------------------------------------

#-------------------------------------------------------
What Are The GPIO Pins on Raspberry Pi?


sudo python
import RPi.GPIO as GPIO
    wget http://pypi.python.org/packages/source/R/RPi.GPIO/RPi.GPIO-0.3.1a.tar.gz
    tar zxf RPi.GPIO-0.3.1a.tar.gz
    cd RPi.GPIO-0.3.1a

//    Install the library
sudo python setup.py install




from time import sleep
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

GPIO.setup(16, GPIO.IN)
GPIO.setup(18, GPIO.IN)

GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(15, GPIO.OUT)
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)

# state - decides what LED should be on and off
state = 0

# increment - the direction of states
inc = 1

while True:

# state toggle button is pressed
        if ( GPIO.input(16) == True ):

if (inc == 1):
state = state + 1;
else:
state = state - 1;

# reached the max state, time to go back (decrement)
if (state == 3):
inc = 0
# reached the min state, go back up (increment)
elif (state == 0):
inc = 1

if (state == 1):
GPIO.output(11, GPIO.HIGH)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)
elif (state == 2):
GPIO.output(11, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
GPIO.output(15, GPIO.LOW)
elif (state == 3):
GPIO.output(11, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
GPIO.output(15, GPIO.HIGH)
else:
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)
print("pressed B1 ", state)

# reset button is pressed
        if ( GPIO.input(18) == True ):

state = 0
inc = 1
GPIO.output(11, GPIO.LOW)
GPIO.output(13, GPIO.LOW)
GPIO.output(15, GPIO.LOW)

print("pressed B2 ", state)

        sleep(0.2);
#-------------------------------------------------------
import smbus
from time import *

# General i2c device class so that other devices can be added easily
class i2c_device:
 def __init__(self, addr, port):
  self.addr = addr
  self.bus = smbus.SMBus(port)

 def write(self, byte):
  self.bus.write_byte(self.addr, byte)

 def read(self):
  return self.bus.read_byte(self.addr)

 def read_nbytes_data(self, data, n): # For sequential reads > 1 byte
  return self.bus.read_i2c_block_data(self.addr, data, n)


class lcd:
 #initializes objects and lcd
 '''
 Reverse Codes:
 0: lower 4 bits of expander are commands bits
 1: top 4 bits of expander are commands bits AND P0-4 P1-5 P2-6
 2: top 4 bits of expander are commands bits AND P0-6 P1-5 P2-4
 '''
 def __init__(self, addr, port, reverse=0):
  self.reverse = reverse
  self.lcd_device = i2c_device(addr, port)
  if self.reverse:
   self.lcd_device.write(0x30)
   self.lcd_strobe()
   sleep(0.0005)
   self.lcd_strobe()
   sleep(0.0005)
   self.lcd_strobe()
   sleep(0.0005)
   self.lcd_device.write(0x20)
   self.lcd_strobe()
   sleep(0.0005)
  else:
   self.lcd_device.write(0x03)
   self.lcd_strobe()
   sleep(0.0005)
   self.lcd_strobe()
   sleep(0.0005)
   self.lcd_strobe()
   sleep(0.0005)
   self.lcd_device.write(0x02)
   self.lcd_strobe()
   sleep(0.0005)

  self.lcd_write(0x28)
  self.lcd_write(0x08)
  self.lcd_write(0x01)
  self.lcd_write(0x06)
  self.lcd_write(0x0C)
  self.lcd_write(0x0F)

 # clocks EN to latch command
 def lcd_strobe(self):
  if self.reverse == 1:
   self.lcd_device.write((self.lcd_device.read() | 0x04))
   self.lcd_device.write((self.lcd_device.read() & 0xFB))
  if self.reverse == 2:
   self.lcd_device.write((self.lcd_device.read() | 0x01))
   self.lcd_device.write((self.lcd_device.read() & 0xFE))
  else:
   self.lcd_device.write((self.lcd_device.read() | 0x10))
   self.lcd_device.write((self.lcd_device.read() & 0xEF))

 # write a command to lcd
 def lcd_write(self, cmd):
  if self.reverse:
   self.lcd_device.write((cmd >> 4)<<4)
   self.lcd_strobe()
   self.lcd_device.write((cmd & 0x0F)<<4)
   self.lcd_strobe()
   self.lcd_device.write(0x0)
  else:
   self.lcd_device.write((cmd >> 4))
   self.lcd_strobe()
   self.lcd_device.write((cmd & 0x0F))
   self.lcd_strobe()
   self.lcd_device.write(0x0)

 # write a character to lcd (or character rom)
 def lcd_write_char(self, charvalue):
  if self.reverse == 1:
   self.lcd_device.write((0x01 | (charvalue >> 4)<<4))
   self.lcd_strobe()
   self.lcd_device.write((0x01 | (charvalue & 0x0F)<<4))
   self.lcd_strobe()
   self.lcd_device.write(0x0)
  if self.reverse == 2:
   self.lcd_device.write((0x04 | (charvalue >> 4)<<4))
   self.lcd_strobe()
   self.lcd_device.write((0x04 | (charvalue & 0x0F)<<4))
   self.lcd_strobe()
   self.lcd_device.write(0x0)
  else:
   self.lcd_device.write((0x40 | (charvalue >> 4)))
   self.lcd_strobe()
   self.lcd_device.write((0x40 | (charvalue & 0x0F)))
   self.lcd_strobe()
   self.lcd_device.write(0x0)

 # put char function
 def lcd_putc(self, char):
  self.lcd_write_char(ord(char))

 # put string function
 def lcd_puts(self, string, line):
  if line == 1:
   self.lcd_write(0x80)
  if line == 2:
   self.lcd_write(0xC0)
  if line == 3:
   self.lcd_write(0x94)
  if line == 4:
   self.lcd_write(0xD4)

  for char in string:
   self.lcd_putc(char)

 # clear lcd and set to home
 def lcd_clear(self):
  self.lcd_write(0x1)
  self.lcd_write(0x2)

 # add custom characters (0 - 7)
 def lcd_load_custon_chars(self, fontdata):
  self.lcd_device.bus.write(0x40);
  for char in fontdata:
   for line in char:
    self.lcd_write_char(line)

#-------------------------------------------------------
import pylcdlib
lcd = pylcdlib.lcd(0x21,0)
lcd.lcd_puts("Raspberry Pi",1)  #display "Raspberry Pi" on line 1
lcd.lcd_puts("  Take a byte!",2)  #display "Take a byte!" on line 2













Membuat Lampu Blink Raspberry PI 3

Lighting Up An Led Using Your Raspberry Pi and Python

Once you've setup your Raspberry Pi according to my getting started tutorial, you are ready for your first real project. Let's light up an led using the Python programming language and the GPIO pins on your Raspberry Pi, hereafter called RPi.

What You Will Learn:

  • You will construct a basic electrical circuit and attach it to your RPi GPIO pins
  • You will write a simple Python program to control the circuit using IDLE IDE

What You Will Need:

  • Raspberry Pi configured with the GPIO library
  • 1 - small led, any color
  • 1 - 50 ohm resistor
  • Some small-gauge solid core wire
  • Breadboard and/or alligator clips to hold connections

Let There Be Light

Before we get around to writing any code, let's first get acquainted with the pin numbering of our RPi and create a simple circuit. We'll start by simply lighting our led using the 3.3v pin and the ground pin on our RPi. We will use the following schematic for our circuit:
Before starting, unplug your RPi. You wouldn't want to risk shorting it out while working with it 'powered on', especially since this is our first project.
  • Using your assortment of materials, create the circuit on either your breadboard, or using your alligator clips.
  • Pin 1 (+3.3 volts) should go to the longer leg of your led. This pin provides a steady supply of 3.3v. Unlike the GPIO pins on your RPi, this pin is not programmable, and cannot be controlled by software.
  • Attach the shorter leg of the led to the resistor. Finally, attach the other end of the resistor to Pin 6 (- ground) on your RPi.
Double-check your connections. When you are done, your circuit should look like this:
Power on your RPi - the led should immediately turn on.

Controlling The Led With Python

Now that we've tested our basic circuit, it's time to move the positive lead from the 'always on' 3.3v pin to one of the programmable GPIO pins. Here is what our circuit will look like:
  • Power-off your RPi again before making any changes to your wiring.
  • Move the positive lead from pin 1 to pin 7.
When you are done, your circuit should look like this:

Writing The Code

I like to write my python scripts using the IDLE IDE because it comes packaged with the Raspbian distribution, it's free, and it makes writing and debugging code a bit simpler than when using Python command line or a text editor. It's important to note that when writing python scripts that utilize the GPIO pins, you must run them as a superuser or your scripts will not run properly.
  • Power on your RPi and boot all the way into the operating system GUI
  • Open the terminal and launch the IDLE IDE as a superuser:
    sudo idle
  • Wait for IDLE to open, then click File > New to open a new window (Ctrl + N)
  • Type the following code into the window:
    import RPi.GPIO as GPIO ## Import GPIO library
    GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
    GPIO.setup(7, GPIO.OUT) ## Setup GPIO Pin 7 to OUT
    GPIO.output(7,True) ## Turn on GPIO pin 7
  • Click File > Save when you are done (Ctrl + S).
  • To run your program, click Run > Run (Ctrl + F5). You should see your led light up! We just told the RPi to supply voltage (+3.3v) to our circuit using GPIO pin 7.
If you are having trouble getting the led to light up, double-check your wiring, and make sure you have installed the GPIO Python library according to my instructions. You can download the completed script here.

Extra Credit: Blinking Light

Here is a slightly more advanced script that blinks the led on and off. The only real difference is that we are gathering user input and using the sleep function to set the amount of time the light is on or off.
  • Type the following code into the window:
    import RPi.GPIO as GPIO ## Import GPIO library
    import time ## Import 'time' library. Allows us to use 'sleep'

    GPIO.setmode(GPIO.BOARD) ## Use board pin numbering
    GPIO.setup(7, GPIO.OUT) ## Setup GPIO Pin 7 to OUT

    ##Define a function named Blink()
    def Blink(numTimes,speed):
    for i in range(0,numTimes):## Run loop numTimes
    print "Iteration " + str(i+1)## Print current loop
    GPIO.output(7,True)## Switch on pin 7
    time.sleep(speed)## Wait
    GPIO.output(7,False)## Switch off pin 7
    time.sleep(speed)## Wait
    print "Done" ## When loop is complete, print "Done"
    GPIO.cleanup()

    ## Ask user for total number of blinks and length of each blink
    iterations = raw_input("Enter total number of times to blink: ")
    speed = raw_input("Enter length of each blink(seconds): ")

    ## Start Blink() function. Convert user input from strings to numeric data types and pass to Blink() as parameters
    Blink(int(iterations),float(speed))
...or you may download the completed script here.
Keep in mind that indentation is very important when writing Python code. Use the TAB key to match the formatting of the above code as you write it.

Something a Little More Complicated...

If you really want to get your feet wet with a more advanced project with a real-world application, check out my irrigation rain bypass project.


Reff:
http://www.thirdeyevis.com/pi-page-2.php

RASPBERRY PI 3 to i2c LCD







Using An I2C Enabled LCD Screen With The Raspberry Pi



In previous posts I’ve covered using 16×2 and 20×4 LCD screens with the Raspberry Pi using Python. These are relatively easy to use but require a number of connections to be made to the Pi’s GPIO header. This setup can be simplified with the use of an I2C enabled LCD screen.

These can either be purchased as a complete unit or you can attach an I2C backpack to a standard screen.
Here is an I2C backpack :
I2C LCD Backpack
and here is a backpack soldered to the back of a standard 16×2 LCD screen :I2C LCD Backpack
This is a great way to add an I2C enabled LCD screen to your Pi with only four wires!

Step 1 – Connect Screen to the Pi

i2c Level ShifterThe I2c module can be powered with either 5V or 3.3V but the screen works best if it provided with 5V. However the Pi’s GPIO pins aren’t 5V tolerant so the I2C signals need to be level shifted. To do this I used an I2C level shifter.
This requires a high level voltage (5V) and a low level voltage (3.3V) which the device uses as a reference. The HV pins can be connected to the screen and two of the LV pins to the Pi’s I2C interface.
Level Shifter Pi I2C Backpack
LV 3.3V (pin 1)
LV1 SDA (pin 3)
LV2 SCL (pin 5)
GND GND (pin 6) GND
HV 5V (pin 2) VCC
HV1
SDA
HV2
SCL
While experimenting I found that it worked fine without the level shifting but I couldn’t be certain this wasn’t going to damage the Pi at some point. So it’s probably best to play it safe!

Step 2 – Download the Example Script

The example script will allow you to send text to the screen via I2C. It is very similar to my scripts for the normal 16×2 screen. To download the script directly to your Pi you can use :
wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/lcd_i2c.py

Step 3 – Enable the I2C Interface

In order to use I2C devices you must enable the interface on your Raspberry Pi. This can be done by following my “Enabling The I2C Interface On The Raspberry Pi” tutorial. By default the I2C backpack will show up on address 0x27.

Step 4 – Run Script

Running the script can be done using :
sudo python lcd_i2c.py
Hopefully you will see something like this :
I2C 16x2 LCD Screen

Troubleshooting

If you are having problems then :
  • Double check your wiring
  • Start from a fresh Raspbian image
  • Make sure you set up I2C as mentioned in “Enabling The I2C Interface On The Raspberry Pi” tutorial
  • Check the screen is detected when you follow the “Testing hardware” section in the above tutorial
  • Ensure SDA and SCL are correctly wired to Pins 3 and 5 on the Pi via the level shifter
  • Adjust the contrast ratio using the trimmer on the i2c backpack
CODE:
https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/python/lcd_i2c.py

import smbus
import time

# Define some device parameters
I2C_ADDR  = 0x27 # I2C device address
LCD_WIDTH = 16   # Maximum characters per line

# Define some device constants
LCD_CHR = 1 # Mode - Sending data
LCD_CMD = 0 # Mode - Sending command

LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line
LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line
LCD_LINE_3 = 0x94 # LCD RAM address for the 3rd line
LCD_LINE_4 = 0xD4 # LCD RAM address for the 4th line

LCD_BACKLIGHT  = 0x08  # On
#LCD_BACKLIGHT = 0x00  # Off

ENABLE = 0b00000100 # Enable bit

# Timing constants
E_PULSE = 0.0005
E_DELAY = 0.0005

#Open I2C interface
#bus = smbus.SMBus(0)  # Rev 1 Pi uses 0
bus = smbus.SMBus(1) # Rev 2 Pi uses 1

def lcd_init():
  # Initialise display
  lcd_byte(0x33,LCD_CMD) # 110011 Initialise
  lcd_byte(0x32,LCD_CMD) # 110010 Initialise
  lcd_byte(0x06,LCD_CMD) # 000110 Cursor move direction
  lcd_byte(0x0C,LCD_CMD) # 001100 Display On,Cursor Off, Blink Off 
  lcd_byte(0x28,LCD_CMD) # 101000 Data length, number of lines, font size
  lcd_byte(0x01,LCD_CMD) # 000001 Clear display
  time.sleep(E_DELAY)

def lcd_byte(bits, mode):
  # Send byte to data pins
  # bits = the data
  # mode = 1 for data
  #        0 for command

  bits_high = mode | (bits & 0xF0) | LCD_BACKLIGHT
  bits_low = mode | ((bits<<4 0xf0="" bits="" bits_high="" bits_low="" block="" bus.write_byte="" def="" display="" enable="" for="" high="" i="" in="" initialise="" ispy="" lcd="" lcd_backlight="" lcd_byte="" lcd_cmd="" lcd_init="" lcd_string="" lcd_toggle_enable="" line="" low="" main="" message="" more="" ord="" program="" range="" send="" some="" string="" test="" text="" time.sleep="" to="" toggle="" true:="" while="">         RPiSpy",LCD_LINE_1)
    lcd_string(">        I2C LCD",LCD_LINE_2)

    time.sleep(3)

if __name__ == '__main__':

  try:
    main()
  except KeyboardInterrupt:
    pass
  finally:
    lcd_byte(0x01, LCD_CMD)


REFF: http://www.raspberrypi-spy.co.uk/2015/05/using-an-i2c-enabled-lcd-screen-with-the-raspberry-pi/



Sabtu, 01 Oktober 2016

Share OS windows on Raspberry SAMBA

How to install Samba

To install samba on Rasberry Pi simply run the following commands
pi@raspberrypi:~ $ sudo apt update
pi@raspberrypi:~ $ sudo apt-get install samba

Configuring Samba

Edit the samba configuration file /etc/samba/smb.conf
pi@raspberrypi:~ $ sudo nano /etc/samba/smb.conf
Change the workgroup name to the name of your workgroup. To find out the workgroup name on Windows 7 PC go to Control Panel → System. On a system running Windows 10 you can find this onSettings → System → About
You can also enable your Raspberry Pi as a WINS server by changing the entry wins support to yes
workgroup = MYWORKGROUP
wins support = yes
Replace MYWORKGROUP with the name of your workgroup. Save and exit the file.

Create shared folder

Create the folder that you want to share and setup appropriate permission. In this example we will create a folder and give read, write, execute permissions to owner, group and other users.
pi@raspberrypi:~ $ mkdir /home/pi/shared
pi@raspberrypi:~ $ chmod 777 /home/pi/shared
Edit the /etc/samba/smb.conf file and add the following lines. These lines define the behaviour of the shared folder so you can call them share definition.
[pishare]
  comment = Pi Shared Folder
  path = /home/pi/shared
 browsable = yes
 guest ok = yes
 writable = yes
Save and exit the file. The following table explains the meaning of each entry in the share definition.
[pishare]This is the name of the share
comment = Pi Shared FolderThe text Pi Shared FOlder is the text that is displayed as Comments in shares detail view
path = /home/pi/sharedSpecifies the folder that contains the files to be shared
browsable = yesSet this share to be visible when you run the net view command and also when you browse the network shares.
writable = yesAllows user to add/modify files and folders in this share. By the default samba shares are readonly
guest ok = yesAllows non authenticated users access the share

Accessing the shares from a Windows machine

  • Open File Explorer.
  • Click network from the left-hand menu.
  • From the list of computers double click RASPBERRYPI (if you haven't change the default hostname)
  • You will be see the shared folder pishare. As is it writeable share you can add files to this shared folder from both Windows and Raspberry Pi.


reff: http://www.opentechguides.com/how-to/article/raspberry-pi/86/shared-folder-windows.html