树莓派:python多线程(驱动PCF8591和超声波测距)

文件里分别有三个文件: main.py 、PCF8591.py 和 chaoshengbo.py.。以及一小段报警声音。

首先是PCF8591.py  (之前发表的博客有介绍到)

import smbus

import time

address = 0x48
A0 = 0x40
A1 = 0x41
A2 = 0X42
A3 = 0X43

bus = smbus.SMBus(1)

def AD():
    while True:
        bus.write_byte(address,A3)
        value = bus.read_byte(address)
        print(value)
        time.sleep(1)

 

然后是chaoshengbo.py(之前发表的博客也介绍到)

import RPi.GPIO as GPIO
import time
import os 
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#print( "Measuring Distance")
GPIO.setup(23,GPIO.OUT)
GPIO.setup(24,GPIO.IN)
time.sleep(0.2)
GPIO.output(23,False)
#print( "Setting Trigger pin to zero by default")
#time.sleep(1)

def distance():
    while True:
        GPIO.output(23,True)
        time.sleep(0.00001)
        GPIO.output(23,False)
        while GPIO.input(24) == 0:
            start_time = time.time()
        while GPIO.input(24) == 1:
            end_time = time.time()
        Time = end_time - start_time
        distance = Time * 17150 
        print("Measired Distance is:",distance,"cm.")
        time.sleep(1)
    

 

最后是main.py文件

import threading
import time
import queue
import chaoshengbo
import PCF8591



def main():
    chao_thread = threading.Thread(target=chaoshengbo.distance)
    PCF8591_thread = threading.Thread(target=PCF8591.AD)
    chao_thread.start()
    PCF8591_thread.start()
    
    chao_thread.join()
    PCF8591_thread.join()


if __name__ == "__main__":
    main()
    
    

 

 

测试效果:

在树莓派上不太好截图,只好用手机拍照,255是读取可调电阻的值,下一行是距离。

  • 2
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值