12 May, 2019

Today on the bench, I have the HC-SR04 Ultrasonic Range Sensor connected to a Raspberry Pi 3 Model B running DietPi.



The HC-SR04 sensor has four pins (VCC, Trig, Echo, Gnd) that need to be connected to the Raspberry Pi. VCC gets connected to one of the 5v pins and Gnd (ground) gets connected to on the of the ground pins on the Rasberry Pi. This leaves Trig (Trigger) and Echo to be connected to the Rasberry Pi.

There is a minor point that needs to be considered before connecting the Trig and Echo pins to the Raspberry Pi. The GPIO headers on the Raspberry Pi can only safely handle 3.3v. The sensor is going to send the signal back using 5v. I need a way to bring 5 volts down to something under 3.3 volts. One way to do this is with a voltage divider. All I need is a couple of resistors, jumper wires, and some math. The math will be handled by the Voltage Divider Calculator. In my stock of resistors, I can see that I have a lot of 1K resistors. I will use one of those. Into the voltage divider calculator goes 5v for the voltage source, 3.3v for the output voltage, and 1K for resistance 1. The results of the calculation gave me a value of just under 2K for resistance 2.

I connected the Trig pin on the sensor to one of the open BCM pins. Now for the tricky part, I connected ground to one leg of the 2K resistor. The other leg connects to a jumper wire going to an open BCM pin on the Raspberry Pi. I then connected the Echo pin of the sensor to one leg of the 1K resistor. The other leg of the 1K resistor gets connected to the jumper wire that I connected the 2K resistor to.





This takes care of the wiring up of the sensor. Now we get to move on to writing some code.

Over in GitHub, I created a repo named go_rpi. In the devices folder, there is a file named 'hcsr04.go'. This code file contains the code for interacting with the HC-SR04 sensor. I am taking advantage of the go-rpio library from Stian Eikeland to access the GPIO-pins. The heart of the code is the 'measure' function. This function coordinates the actions for initializing the pins to a low state, triggering the pulse, capturing the time it takes the signal to go out and back, and calculating the distance.

Resources

Datasheet on HC-SR04

Voltage Divider

Blog Posts

GitHub







No comments:

Challenging myself to learn something new

I have recently set a big challenge for myself. I want to know about Machine Learning . To add to the challenge, I am trying out usin...