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

yipeiwu_com5年前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中Django框架下的staticfiles使用简介

django1.3新加入了一个静态资源管理的app,django.contrib.staticfiles。在以往的django版本中,静态资源的管理一向都是个问题。部分app发布的时候会...

Python代码块及缓存机制原理详解

这篇文章主要介绍了Python代码块及缓存机制原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.相同的字符串在Python中...

python实现图片批量压缩程序

 本文实例为大家分享了python实现图片批量压缩程序的具体代码,供大家参考,具体内容如下 说明 运行环境:Win10 Pycharm 程序没有用到面向对象编程方法,...

python 切换root 执行命令的方法

如下,以创建系统用户举例, 配置文件配置普通用户信息,登入后切换root用户,创建一个指定名字和密码的系统用户: def create_user(root_pwd,username,...

tensorflow 加载部分变量的实例讲解

tensorflow模型保存为saver = tf.train.Saver()函数,saver.save()保存模型,代码如下: import tensorflow as tf...