我想从超声波传感器获得距离和百分比,但我只能设法获得距离

问题描述

我正在尝试获取百分比。根据下面的代码,我还应该做什么?

 - ********#Libraries  
   import RPi.GPIO as GPIO  #Import GPIO library
   import time  #Import time library
    
      GPIO.setmode(GPIO.BCM)                      #GPIO Mode (BOARD / BCM)  
   
    
  GPIO_TRIGGER = 18  
   GPIO_ECHO = 24                        #set GPIO Pins  
     
     
   #set GPIO direction (IN / OUT)  
   GPIO.setup(GPIO_TRIGGER,GPIO.OUT)  
   GPIO.setup(GPIO_ECHO,GPIO.IN)  
    
   def distance():  
        
       GPIO.output(GPIO_TRIGGER,True)   # set Trigger to HIGH 
      
       time.sleep(0.00001)  
       GPIO.output(GPIO_TRIGGER,False)  # set Trigger after 0.01ms to LOW
    
       StartTime = time.time()  
       StopTime = time.time()  
    
         
       while GPIO.input(GPIO_ECHO) == 0:  # save StartTime
           StartTime = time.time()  
    
         
       while GPIO.input(GPIO_ECHO) == 1:  # save time of arrival
           StopTime = time.time()  
    
        
       TimeElapsed = StopTime - StartTime  # time difference between start and arrival
        # multiply with the sonic speed (34300 cm/s)  
       # and divide by 2,because there and back  
       distance = (TimeElapsed * 34300) / 2  
    
       return distance  
   def percentage(temp) :  
       percentage = round(((binheight - temp)/binheight)*100,2)   
       return percentage  
    
   if __name__ == '__main__':  
       try:  
           while True:  
               dist = distance()  
               percent = percentage(dist)  
               print ("Measured distance = %.1f cm" % dist)  
               print ("Percentage",percent,"%")  
               time.sleep(1)  
    
            
       except KeyboardInterrupt:   # Reset by pressing CTRL + C
           print("Measurement stopped by User")  
           GPIO.cleanup()********

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)