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

yipeiwu_com6年前Python基础

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

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

效果图,像素很渣:

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

以上这篇python多线程并发让两个LED同时亮的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python环形单链表的约瑟夫问题详解

题目: 一个环形单链表,从头结点开始向后,指针每移动一个结点,就计数加1,当数到第m个节点时,就把该结点删除,然后继续从下一个节点开始从1计数,循环往复,直到环形单链表中只剩下了一个...

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

一、用默认设置绘制折线图 import matplotlib.pyplot as plt x_values=list(range(11)) #x轴的数字是0到10这11个整数 y...

pytorch .detach() .detach_() 和 .data用于切断反向传播的实现

当我们再训练网络的时候可能希望保持一部分的网络参数不变,只对其中一部分的参数进行调整;或者值训练部分分支网络,并不让其梯度对主网络的梯度造成影响,这时候我们就需要使用detach()函数...

Django+JS 实现点击头像即可更改头像的方法示例

Django+JS 实现点击头像即可更改头像的方法示例

首先,在models.py中创建UserModels类 from django.db import models from django.contrib.auth.models im...

Python实用库 PrettyTable 学习笔记

本文实例讲述了Python实用库 PrettyTable。分享给大家供大家参考,具体如下: PrettyTable安装 使用pip即可十分方便的安装PrettyTable,如下: p...