python多线程并发让两个LED同时亮

11 篇文章 0 订阅
3 篇文章 0 订阅

在做毕业设计的过程中,想对多个传感器让他们同时并发执行。之前想到

light_red()

light_blue()

分别在两个shell脚本中同时运行,但是这样太麻烦了。后来学到了Python多线程,让程序并发执行。

下面具体介绍步骤:

两个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):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        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):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        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)

# 创建新线程
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()
效果图,像素很渣:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JensLee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值