Connection
The ultrasonic sensor is connected using four wires. On the sensor we find the VCC (power), Trig, Echo, GND (ground) pins. We connect the VCC pin to the white power rail on the board, which supplies a voltage of 3,3V. We connect the Trig pin to pin 8 (P8), Echo to pin 9 (P9) and finally we ground it by connecting the GND to the black ground rail. For more information, see the assembly instructions.
Recommendation
Program
Basic program
Linear function
The program is a little more complicated. At the beginning of the code, we declare variables. We will write the distance of the object measured by the ultrasonic sensor into the distance variable. The NUM_LEDS constant is used to store the value of the number of LEDs on our LED strip. In our case, the strip has 6 of them. We initialize the strip object representing our LED strip. Finally, we determine the boundaries of our measurement, i.e. the minimum and maximum distance.
The first loop performs the measurement itself. Using a block from the Sonar library, we write the measured value to the distance variable. To convert the measured distance to the number of lit LEDs, we use the map function from the math library. In principle, this function works as a ternary function. However, we must convert the resulting number to integers using the round down (floor) function. However, in order for the number of lit LEDs to increase with the decreasing distance of the measured object from the sensor, we must subtract the value from the maximum possible (number of LEDs on the strip).
In the second loop, we turn on the LED strip. We go through each LED in turn in the for loop. If the order of the given LED is equal to or less than the leds value obtained from the first loop, we assign a certain color to the LED. If the order is higher, we turn off the LED (“assign it to black”). We must not forget the show function so that the entered values of the individual LEDs are reflected. To slow down the changes and prevent flickering, we add a pause at the end of the loop.





