I am trying to link WS2812 with the HC-SR04 sensor. My aim is to change the color of the leds depending on the distance the sensor measures. I am using the Adafruit Neopixel library for controlling the leds. My problem is as soon as a function linked to the Adafruit library is used in the while loop the readings get very slow. Is there a way to speed the code process time up?
import RPi.GPIO as GPIO import time import signal import sys from neopixel import * import neopixel LED_COUNT = 124 # Number of LED pixels. LED_PIN = 18 # GPIO pin connected to the pixels LED_FREQ_HZ = 800000 LED_DMA = 10 LED_BRIGHTNESS = 255 LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) LED_CHANNEL = 0 # set to '1' for GPIOs 13, 19, 41, 45 or 53 GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) # set GPIO Pins pinTrigger = 16 pinEcho = 12 def TurnOn(strip, color): for i in range(strip.numPixels()): strip.setPixelColor(i, color) strip.show() time.sleep(.5) def close(signal, frame): print("\nTurning off ultrasonic distance detection...\n") GPIO.cleanup() sys.exit(0) signal.signal(signal.SIGINT, close) # set GPIO input and output channels GPIO.setup(pinTrigger, GPIO.OUT) GPIO.setup(pinEcho, GPIO.IN) strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS, LED_CHANNEL) strip.begin() while True: # set Trigger to HIGH GPIO.output(pinTrigger, True) # set Trigger after 0.01ms to LOW time.sleep(0.00001) GPIO.output(pinTrigger, False) startTime = time.time() stopTime = time.time() # save start time while 0 == GPIO.input(pinEcho): startTime = time.time() # save time of arrival while 1 == GPIO.input(pinEcho): stopTime = time.time() # time difference between start and arrival TimeElapsed = stopTime - startTime distance = (TimeElapsed * 34300) / 2 print ("Distance: %.1f cm" % distance) if distance < 8: TurnOn(strip, Color(127, 0, 0)) else: TurnOn(strip, Color(0, 127, 0)) time.sleep(0.02)