[2022/10/22] First Start.
소나무 기운 , 전자제품 개발/생산
파이선3에서 RPi.GPIO모듈 사용하기
GPIO모듈은 Python과 함께 설치 됩니다. 그러나 설치된 이 모듈은 Python 2.7전용으로 설치되어 있으며 Python 3에서 GPIO를 사용하기 위해서 RPi.GPIO를 import하면 import 에러가 발생합니다.
Python 3용 RPi.GPIO모듈의 설치는 간단합니다.
첫번째로 프로그램을 설치하기전에 apt를 최신상태로 업데이트 하는 것이 좋습니다.
다음을 실행합니다.
sudo apt update
이렇게 하면 Software repository 정보가 없데이트되고 패키지 목록이 최신 상태로 유지됩니다.
이 명령이 완료되면 사용 가능한 업데이트를 설치합니다.
sudo apt upgrade
메세지가 표시되면 Y(Yes)를 입력하여 업그레이드를 확인합니다. 계속 진행합니다. 업데이트 실행이 완료되면 Python 3용 GPIO모듈을 설치해야 합니다.
sudo apt install python3-rpi.gpio
적절한 패키지를 다운로드하여 설치해야 합니다.
완료되면 Python 3를 사용하여 모듈을 가져올 수 있는지 확인합니다.
$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import RPi.GPIO
>>>
보이는 것과 같이 "import RPi.GPIO" 명령을 실행했을 경우에 아무 반응이 없습니다. 이것은 모듈을 성공적으로 가져왔음을 의미합니다. 이제 "quit()"를 입력하여 Python 프롬프트를 종료합니다.
quit()
이제 원하는 경우 Python 3로 GPIO프로젝트를 실행할 수 있습니다.
Python 2와 Python 3의 가장큰 차이점은 print명령어에서 차이가 난다.
아래 코드처럼. 가로가 없다.
$ python
Python 2.7.13 (default, Nov 24 2017, 17:33:09)
[GCC 6.3.0 20170516] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>>
Using Python 3, the same command fails.
$ python3
Python 3.8.2 (default, Jul 16 2020, 14:00:26)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
File "<stdin>", line 1
print "hello world"
^
SyntaxError: Missing parentheses in call to 'print'
>>>
에러메세지는 다음과 같은 뜻입니다. 괄호가 없습니다. Python 3형식에 맞춰서 사용합니다.
>>> print ("hello world")
hello world
>>>
기본적으로 python 3는 다른 함수의 구문과 더 일치하기 위해 인쇄문을 괄호안에 묶여야 합니다. Python 2.7을 사용하더라도 괄호를 사용하세요. Python 2.7에서 Python 3로 변환이 수월합니다.
예제로 제어 스크립트의 천번째 버전으로 돌아갑니다. 제 인쇄명세서는 다음과 같습니니다.
print("Furnace turned on for %d seconds. Cycle %d of %d.") % (ontime, cycle, runcycles)
문제가 보이나요? 전체 인쇄 문구가 괄호로 묶이지 않습니다. python 3호환성을 위해서 다음과 같이 문장을 수정해야 합니다.
print("Furnace turned on for %d seconds. Cycle %d of %d." %(ontime, cycle, runcycles))
아주 간단한 수정이지만 그것이 작동하기 위해 필요한 전부입니다. 현재 전체 스크립트는 다믕과 같습니다.
# Import necessary modules
import RPi.GPIO as GPIO
import time
# Set up GPIO pins
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pins = [17,18]
for pin in pins:
GPIO.setup(pin,GPIO.OUT)
GPIO.output(pin,1)
# Set variables (change these to change behaviour as desired)
runcycles = 2
ontime = 45 # minutes
offtime = 20 # minutes
# Convert run times from minutes to seconds for sleep function
ontime *= 60
offtime *= 60
# Run furnace on cycle
cycle = 0
try:
while cycle < runcycles:
cycle += 1
GPIO.output(17,0)
print("Furnace turned on for %d seconds. Cycle %d of %d." %(ontime, cycle, runcycles))
time.sleep(ontime)
GPIO.output(17,1)
if cycle == runcycles:
break
print("Furnace paused for %s seconds. %s heat cycles remaining." %(offtime, runcycles - cycle))
time.sleep(offtime)
except KeyboardInterrupt: # if Ctrl C is pressed...
GPIO.output(17,1) # shut off the boiler
print("Program stopped and furnace shut off.") # print a clean exit message
print("Heat cycles completed.")
그리고 이제 나는 Python 2또는 Python 3를 사용하여 스크립트를 실행할 수 있고 그것은 어느 쪽이든 차이가 없다.
마무리
참고문헌
틀린 부분이나 질문은 댓글 달아주세요.
즐거운 하루 보내세요. 감사합니다.
'Raspberry Pi (Linux, ubuntu)' 카테고리의 다른 글
라즈베리파이 프로그램 1개만 실행시키기 (먼저 실행된 프로그램 종료하기) (0) | 2023.05.20 |
---|---|
라즈베리파이 부팅 후 터미널 동작하고 쉘 스크립트 실행하기(LXTerminal) (0) | 2022.12.14 |
raspberry pi( 라즈베리파이 ), Virtual Environment( 가상 환경), python3 ( 파이썬 3 ) (0) | 2022.10.04 |
라즈베리파이 디스크 사용량, 남은 용량 확인하기 (Raspberry Pi Disk Usage, Check Capacity Remaining ) (0) | 2022.10.04 |
라즈베리파이 이어폰 젝 오디오 출력하기 (1) | 2022.09.26 |
댓글