Wednesday, June 03, 2020

Teensy 3.6 with HC-SR04 Distance Sensor

The HC-SR04 is a low-cost ultrasonic sensor that uses two transducers to measure the distance in front before being blocked by an object or surface. The sensor has four pins GND, VCC, TRIG and ECHO.



Hardware Setup

  • HC-SR04 Ground should be connected to Teensy 3.6 ground. 
  • HC-SR04 VCC should be connected to Vin (which should output 5V if connected to USB). 
  • HC-SR04 TRIG should be connected to Teensy 3.6 digital pin 0. 
  • HC-SR04 ECHO should be connected to one leg of a resistor (1k to 100k). The other leg of the resistor should be connected to Teensy 3.6 digital pin 1. The other leg of the resistor should also be connected to one leg of a second resistor (1k to 100k - same value as the first resistor). The other leg of the second resistor should be connected to ground. 
  • These resistors going to ground and pin 1 form a voltage divider that takes the output voltage from the HC-SR04 from 5V to 2.5V, which is suitable for the Teensy 3.6. 
Here is a photo and layout for the breadboard with and without the sensor connected. Note the connections for the resistors, ground, and digital pins. 









Example 1 - Serial Output

These examples use the HCSR04 library by Martin Sosic, which can be downloaded via the Library Manager tool in Arduino. 

The Arduino Serial monitor will output the measurement as a distance in cm. 






Example 2 - USB MIDI CC

The distance sensor is scaled to a suitable range of 0 - 127 and sent over USB as MIDI CC values, that can be used in Ableton Live and other software to control sound and music parameters.


View the code here: https://github.com/little-scale/arduino-sketches/blob/master/Distance_Sensor_HCSR04_2_USB_MIDI_CC.ino



Example 3 - USB MIDI Pitch with Note On via Push Button

A button is added to the setup, connected to Teensy 3.6 digital pin 32. Pressing the button generates a note on event that uses the distance sensor to set the pitch of the note. Depressing the button generates a note off event.





View the code here: https://github.com/little-scale/arduino-sketches/blob/master/Distance_Sensor_HCSR04_3_USB_MIDI_Pitch.ino



0 comments: