2017년 1월 12일 목요일

Setting up your Raspberry PI for Python GPIO Projects



>>

Setting Up Your Raspberry Pi For Python GPIO Projects

The Raspberry Pi is a great tool to get started with electronic tinkering projects. 
It's inexpensive, runs a full-fledged Linux operating system, 
and has I/O pins that can be used to control other electronic devices. 
This quick guide will walk you through the initial setup 
from unboxing your Raspberry Pi, to installing the Python GPIO library.
라즈베리파이는 a 훌륭한 툴이다. to 시작하는데 with 전자 tinkering 프로젝트들을.
저렴하다. 동작하며 a 환벽한-fledged 리눅스 OS, 
and 갖고있다. I/O핀들을 that can be 사용되는 to 제어하는데 다른 전자 장비들을.
이 퀵가이드는 will 예행연습시킬것이다. 널 through the 초기 setup을 통해
from 언박싱하면서부터 네 Raspberry Pi를 to 설치하기위해 the Python GPIO 라이프러리를

This guide assumes that you are using Linux to setup your Raspberry Pi
(hereafter called RPi). 
The RPi itself runs Linux, and the basic skills and commands you learn 
will become very valuable later once you are up and running.
이 가이드는 가정한다. that 네가 사용하고있다고 Linux를 to setup하기위해 네 Raspberry Pi를 
(여기이하 부른다. RPi라고)
그 RPi 그 자체는 돌린다. Linux를, and the 기초 skills & commands... 네가 배우는
...will 될것이다. 매우 가치있게 나중에 once 일단 네가 갖추고 나아간다면.




>>

What You'll Need:


●A Raspberry Pi model A or B


●Micro SD Card with capacity of at least 4GB. Make sure you have an adapter that will allow you to plug it into the USB port on your computer.


An internet connection via ethernet cable, or a micro-usb WiFi adapter such as the Trendnet TEW-648UBM

A working computer with an internet connection. I will be using a computer running Ubuntu Linux for this guide. If you have trouble with these steps, or are using an OS other than Linux, you may find detailed installation instructions in this quick start guide. Return here after you have installed the Raspbian image onto you SD card, and proceed with Step 2.


An HDMI or composite cable to plug the Raspberry Pi into your TV or monitor.

A keyboard and mouse




The first step to setting up you Raspberry Pi 
is to install the Raspbian OS image from the Raspberry Pi website onto your MicroSD card.
첫 단계... to 세팅업하기위한 네 Raspberry Pi를
...는 to 설치하기이다. the Raspbian OS 이미지를 from 웹사이트로부터 onto 네 MicroSD카드상에.
Before starting, 
be sure that your Micro SD card is clean with no existing partitions. 
시작하기전에,
확인해라. that 네 MicroSD 카드가 깨끗한지 with no 남아있는 파티션들 없이.
If you have trouble with these steps, or are using an OS other than Linux, 
you may find detailed installation instructions in this quick start guide. Return here after you have installed the Raspbian image onto you SD card.
만약 네가 갖고있다면 문제를 with 이 단계에서 or 사용중이라면 an OS를 리눅스 이외에.
넌 아마 찾아야한다. 자세한 설치 법을.

Go to the Raspberry Pi Download site and download the latest Raspbian release. 
A the time of this writing, the most recent version is "Wheezy". 
I use the direct download link for sake of simplicity.


When the download is complete, 
open up the terminal and use the cd command to change directories to the folder where you downloaded the distribution, for example:

cd Downloads

Run unzip to extract pi image. Remember, the filename of the distribution may have changed since the time of this writing:

unzip 2012-12-16-wheezy-raspbian.zip

Now change directory to the directory where you unzipped the Raspbian distribution

cd 2012-12-16-wheezy-raspbian

Insert your blank SD card into your computer using a card reader or adapter. 
Run the command df in the terminal to determine the name and location of your SD card.

df -h

From this command, I was able to determine that my usb card was called /dev/sdc1 by looking for the disk that matched the capacity of my SD card

Be aware that some SD cards come pre-formatted with a filesystem. 
This may interfere with the installation of the Raspbian OS image. 
You will want to delete any existing partitions prior to copying the Raspbian image on your SD card. 
To do this, we will use the fdisk utility. 
Run fdisk as a superuser (prefix the command with the word sudo) using the disk name you discovered in the previous step

sudo fdisk /dev/sdc1

You should see a command prompt that looks like this:

Command (m for help):

Type p to see all the partitions on the list. Type d to delete each partition on the card (you may need to do this several times). Once you've deleted all partitions, enter w at the command prompt to save your changes and exit.

Run the df -h command again to list all connected disks. Again, make note of your SD card's name. 
The name may have changed if you deleted any partitions using fdisk. 
For example, my disk name changed to /dev/sdc.

Copy the Raspbian image to your SD card using the dd command as a superuser. 
This action may appear to hang, be patient and wait until you see the command prompt. 
You may need to change the /dev/sdc or the name of the Raspberry Pi image depending on the type of card you are using, and the current Raspberry Pi distribution.

sudo dd bs=4M if=2012-12-16-wheezy-raspbian.img of=/dev/sdc

Run the sync command as superuser

sudo sync

Once the image is written onto the SD card, it's safe to remove the card from your system.




>>

Step 2: First Boot - Configuration Options

Insert the SD card into your Raspberry Pi along with an ethernet cable/WiFi adapter, keyboard, and mouse.
Connect the HDMI or composite cable to your TV/monitor, and turn it on.
Make sure that your TV/monitor is set to the correct input.
Finally plug in the RPi into the AC adapter to power it up.
On the first boot, you will be confronted with a configuration screen. 
You may want to make the following changes, at a minimum:
삽입해라. the SD카드를 into 네 Raspberry Pi에 (나머지를 차례로 연결하고 turn it ON).
확인해라. that 네 TV/monitor가 set되있는지 to the 올바른 입력으로.
마지막으로 플러그인해라. the RPi를 into the AC 어답터에 to 파워업하기위해.
첫 부팅에서, 넌 will be confronted될것이다. with a 구성 화면과 함께.
넌 may 원할지모른다. to make the 따라오는 변화들을, 최소한.

System Password: You may want to chang the administrator password on the RPi. 
By default, it is set to username pi and password raspberry.

Keyboard Language: Change the keyboard setting to your language and locale

Expand the partition: This option will expand the size of your primary partition to the maximum size of your SD card during the next boot. 
Keep in mind that this will take a long time. It takes over 10 minutes to do this on an 8GB card.

Boot to GUI: You may want to have your RPi boot directly into the Graphical User Interface(GUI) rather than to the command line. 
If you leave this option disabled, you can always launch the OS GUI by typing startx on the command line.

If you ever need to re-run the configuration options panel, 
use the following command: sudo raspi-config


>>
Step 3: Optional - Setting Up Your WiFi Adapter
If you are planning to connect to the Internet using an ethernet cable, 
you can skip this section. 
This section will walk you through the process of connecting to your WiFi network 
using a WiFi adapter. 
Please note that you will need to purchase a separate WiFi adapter such as the ... 
The RPi does not have a built-in WiFi adapter.
만약 네가 계획하고있다면 to 연결하기위해 the Internet을 사용하며 an 이더넷 케이블을,
넌 can skip할수있다. 이 섹션을.
이 섹션은 will 예행연습케할것이다. 널 through the 과정을통해 of 연결하는 to 네 WiFi 네트워크에
사용하며 a WiFi 어답터를.
기억해라. that 넌 will need to 구입할필요가있다. a 개별 WiFi 어답터를. such as the...
The RPi는 갖고있지않다. 내장 WiFi 어답터를.

From the GUI, double-click the WiFi Config icon on the desktop

On the Manage Networks tab, click the Scan button.

Double-click the name of the network you wish to connect to. 
You may be prompted to enter security settings for your network.





>>
Step 4: Installing The Python GPIO Library
If you're like me, you bought your RPi to "control things" using the I/O pins on the RPi. 
Using Python and the RPi GPIO library, 
you can do just that. 
Python should already be installed on your RPi, 
and it takes just a minute to install the GPIO library:
만약 네가 나와 같았다면, 넌 샀을것이다. 네 RPi를 to 제어하기위해 뭔가를 사용하여 the I/O 핀들을 on the RPi상의
사용하기 Python을 and the RPi GPIO 라이브러리를
넌 can 할수있다. 이런걸
Python은 should already be 설치되야만한다. on 네 RPi상에
그리고 몇분 걸린다. to 설치하는데 the GPIO 라이브러리를:

Open the terminal on your RPi. Double-click the icon on the desktop named LXTerminal
열어라. 터미널을.

Type the following command to download the GPIO library as a tarball:
타이핑해라. 따라오는 명령어를 to 다운로드하기위해 the GPIO라이브러리를

wget http://raspberry-gpio-python.googlecode.com/files/RPi.GPIO-0.4.1a.tar.gz


Unzip the tarball:
압축해제해라.

tar zxvf RPi.GPIO-0.4.1a.tar.gz


Change to the directory where tarball was inflated:
바꿔라. to the 디렉토리로 where tarball이 부풀어오른곳으로

cd RPi.GPIO-0.4.1a


Install the GPIO library in Python:
설치해라. the GPIO라이브러리를

sudo python setup.py install
Important: You must be a superuser to run scripts that control the GPIO pins on your RPi.
If you are using the IDLE IDE to write your Python scripts,
be sure to launch it as a superuser.
Open the terminal and type sudo idle to launch the IDLE IDE as a superuser,
otherwise any scripts that utilize the GPIO library
will not work.
중요: 네가 반드시 되야한다. a superuser가 to 동작시키기위해 scripts를 that 제어하는 the GPIO핀들을
만약 네가 사용중이면 the IDLE IDE를 to 쓰기위해 네 Python scripts를,
확실히해라. to launch하는걸 it을 as a superuser로써.
열어라. the 터미널을 and type해라. sudo idle이라고 to launch하기위해 the IDLE IDE를 as a superuser로
그렇지않으면 어느 scripts든... that utilize하는 the GPIO 라이브러리를
...will not 동작하지않을것이다.


>>
Time For Your First Project
Now that you have everything setup, you are ready for your first project
Click here to for a very easy tutorial that will teach you how to turn an led on and off using Python.





>>
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.
일단 네가 setup하면 네 Raspberry Pi를 according to 내 시작 튜토리얼에 따라서,
넌 준비됬다. for 네 첫 real project를 위해.
켜보자. an LED를 사용하여 the Python 프로그래밍 언어를.
and the GPIO핀들 상에서.


>>
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


.
.
.




>>
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.
난 쓰고싶다. 내 python scripts를 사용하여 the IDLE IDE를
왜냐면 이건 온다. packaged되서 with the Raspbian 배포와함께, 공짜다.

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.

댓글 없음:

댓글 쓰기