ラズパイと超音波距離センサーで、距離を計測する。

20180727m5stack1.jpg

 

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ファイル名: distance.py

import os
import time, wiringpi as pi

TRIG_PIN = 26
ECHO_PIN = 19

pi.wiringPiSetupGpio()
pi.pinMode( TRIG_PIN, pi.OUTPUT )
pi.pinMode( ECHO_PIN, pi.INPUT )
pi.digitalWrite( TRIG_PIN, pi.LOW )
time.sleep( 1 )

def mesure():
    pi.digitalWrite( TRIG_PIN, pi.HIGH )
    time.sleep(0.00001)
    pi.digitalWrite( TRIG_PIN, pi.LOW )
    while ( pi.digitalRead( ECHO_PIN ) == pi.LOW ):
        sigoff = time.time()
        #print( 'sigoff:', sigoff )
    while ( pi.digitalRead( ECHO_PIN ) == 1 ):
        sigon = time.time()
        #print ( 'sigon',sigon )
    return (( sigon - sigoff ) * 34000) / 2

while True:
    distance = mesure()
    print ("Distance:", int(distance), "cm" )

    time.sleep(1)

20180727m5stack3.png


コメント欄を読み込み中