Sterowanie LED z GPIO

Sterowanie LED z GPIO na Raspberry Pi



Akcesoria:

W celu podłączenia diody potrzebne jest:
Dioda led
Rezystor
Jumper Kabel
Płytka prototypowa


Należy podłączyc tak jak na rysunku
Należy pamiętać o biegunowości diody led (-) krótsza nóżka (+) dłuższa.

Oprogramowanie

Zanim zaczniemy, należy stworzyc nowy plik i nazwać go:
nano LED.py
Następnie edytujemy plik:

import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18,GPIO.OUT)
print "LED on"
GPIO.output(18,GPIO.HIGH)
time.sleep(1)
print "LED off"
GPIO.output(18,GPIO.LOW)
Kiedy jesteś pewny że wszystko gotowe należy zapisać plik, aby zapisać plik i wyjść z edytora należy wcisnąć “Ctrl + x” następnie “y” i “enter”.

Następnie uruchamiamy nasz plik

Aby uruchomić wydaj komendę:
sudo python LED.py
I widać nasza dioda działa.

Wyjaśnienie poszczególnych linijek kodu programu

import RPi.GPIO as GPIO The first line tells the Python interpreter (the thing that runs the Python code) that it will be using a ‘library’ that will tell it how to work with the Raspberry Pi’s GPIO pins.  A ‘library’ gives a programming language extra commands that can be used to do something different that it previously did not know how to do.  This is like adding a new channel to your TV so you can watch something different.
import time Imports the Time library so that we can pause the script later on.
GPIO.setmode(GPIO.BCM) Each pin on the Pi has several different names, so you need to tell the program which naming convention is to be used.
GPIO.setwarnings(False) This tells Python not to print GPIO warning messages to the screen.
GPIO.setup(18,GPIO.OUT) This line tells the Python interpreter that pin 18 is going to be used for outputting information, which means you are going to be able to turn the pin ‘on’ and ‘off’.
print "LED on" This line prints some information to the terminal.
GPIO.output(18,GPIO.HIGH) This turns the GPIO pin ‘on’. What this actually means is that the pin is made to provide power of 3.3volts.  This is enough to turn the LED in our circuit on.
time.sleep(1) Pauses the Python program for 1 second
print "LED off" This line prints some information to the terminal.
GPIO.output(18,GPIO.LOW) This turns the GPIO pin ‘off’, meaning that the pin is no longer supplying any power.