溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python多線程并發(fā)讓兩個LED同時亮的方法

發(fā)布時間:2020-08-25 15:37:27 來源:腳本之家 閱讀:137 作者:JensLee 欄目:開發(fā)技術(shù)

在做畢業(yè)設計的過程中,想對多個傳感器讓他們同時并發(fā)執(zhí)行。之前想到

light_red()

light_blue()

分別在兩個shell腳本中同時運行,但是這樣太麻煩了。后來學到了Python多線程,讓程序并發(fā)執(zhí)行。

下面具體介紹步驟:

兩個led燈,一個藍燈,一個紅燈

藍燈正極接13,負極接14

紅燈正極接12,負極接14

下面是代碼:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import RPi.GPIO as GPIO
import threading
import time
 
class led_blue(threading.Thread): #繼承父類threading.Thread
 def __init__(self, threadID, name, counter):
  threading.Thread.__init__(self)
  self.threadID = threadID
  self.name = name
  self.counter = counter
 def run(self):     #把要執(zhí)行的代碼寫到run函數(shù)里面 線程在創(chuàng)建后會直接運行run函數(shù)
  print "Starting " + self.name
  led_blue_on()
  print "Exiting " + self.name
 
class led_red (threading.Thread): #繼承父類threading.Thread
 def __init__(self, threadID, name, counter):
  threading.Thread.__init__(self)
  self.threadID = threadID
  self.name = name
  self.counter = counter
 def run(self):     #把要執(zhí)行的代碼寫到run函數(shù)里面 線程在創(chuàng)建后會直接運行run函數(shù)
  print "Starting " + self.name
  led_red_on()
  print "Exiting " + self.name
 
def led_blue_on():
 PIN_NO=13
 GPIO.setmode(GPIO.BOARD)
 GPIO.setup(PIN_NO, GPIO.OUT)
 GPIO.output(PIN_NO,GPIO.HIGH)
	
def led_red_on():
 PIN=12
 GPIO.setmode(GPIO.BOARD)
 GPIO.setup(PIN, GPIO.OUT)
 GPIO.output(PIN,GPIO.HIGH)
 
# 創(chuàng)建新線程
thread1 = led_blue(1, "light_blue_on_on", 1)
thread2 = led_red(2, "light_red_on", 2)
 
# 開啟線程
thread1.start()
thread2.start()
 
print "Exiting Main Thread"
time.sleep(20)
GPIO.cleanup()

效果圖,像素很渣:

python多線程并發(fā)讓兩個LED同時亮的方法

以上這篇python多線程并發(fā)讓兩個LED同時亮的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI