在此篇[Raspberry Pi學習筆記]Raspberry Pi 3 CentOS 7 - RPi.GPIO已經講解完GPIO安裝與操作,這篇會講解如何使用Python帶參數執行LED控制,首先檢查Raspberry Pi 3 CentOS 7有無檔案要更新,輸入指令
yum -y update
將目錄切換至/etc/python/sample,輸入指令
cd /etc/python/sample
首先寫能帶參數執行的Python,建立cgiOne.py,輸入指令
vi cgiOne.py
程式如下,
import sys,getopt
def main(argv):
input4=''
input17=''
try:
opts,args = getopt.getopt(argv,"hx:y:")
except getopt.GetoptError:
print("cgiOne.py -x <on/off> -y <on/off>")
sys.exit()
for opt,arg in opts:
if opt == '-h':
print("cgiOne.py -x on -y off")
sys.exit()
elif opt in ("-x"):
input4 = arg
elif opt in ("-y"):
input17 = arg
print'input Pin4',input4
print'input Pin17',input17
if __name__ == "__main__":
main(sys.argv[1:])
儲存離開後,輸入下圖指令,可得到相對應的回應
python cgiOne.py -x on -y off
python cgiOne.py -x off -y on
python cgiOne.py -x on -y on
python cgiOne.py -x off -y off
接下來利用這程式,添加RPi.GPIO程式,先建立cgiLed.py,輸入指令
vi cgiLed.py
程式如下,
import RPi.GPIO as GPIO
import sys,getopt
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(4,GPIO.OUT)
GPIO.setup(17,GPIO.OUT)
def main(argv):
input4=''
input17=''
try:
opts,args = getopt.getopt(argv,"hx:y:")
except getopt.GetoptError:
print("cgiOne.py -x <on/off> -y <on/off>")
sys.exit()
for opt,arg in opts:
if opt == '-h':
print("cgiOne.py -x on -y off")
sys.exit()
elif opt in ("-x"):
input4 = arg
elif opt in ("-y"):
input17 = arg
print'input Pin4',input4
print'input Pin17',input17
if input4.upper()=="ON":
print("Pin4 ON")
GPIO.output(4,1)
else:
print("Pin4 OFF")
GPIO.output(4,0)
if input17.upper()=="ON":
print("Pin17 ON")
GPIO.output(17,1)
else:
print("Pin17 OFF")
GPIO.output(17,0)
if __name__ == "__main__":
main(sys.argv[1:])
儲存離開後,輸入下圖指令,可得到相對應的回應
python cgiLed.py -x on -y off
python cgiLed.py -x off -y on
python cgiLed.py -x on -y off
python cgiLed.py -x off -y on
留言列表