Integrating HC SR-04 ultrasonic sensor into pixhawk

Hi, I am a beginner here. I am trying to install a rangefinder to my pixhawk so that it can determine the altitude much precise below 2m range. The sonar sensor I am using is HC SR-04 ultrasonic sensor. The other rangefinder sensors that are supported by arducopter are too expensive for me. Since I am a beginner, I want to experiment with the cheaper rangefinder sensor. However, my problem is I dunno where to start or where should I alter or add codes to the arducopter codes that I cloned from the GitHub. I am planning to connect the sensor through i2c port. Anyone has any experience in getting this to work or know the solution to this, please guide me and point me in the right direction. I have studied the arducopter codes for a week but I am still lost. I really appreciate your help.


how about emulating one of the supported sonar protocols with a small Arduino instead? For example , an Arduino Pro Mini with an SR-04 can emulate one of Maxbotix i2c sonars without any modification to the ArduCopter.

Hi, thank you for your help. May I know how can I emulate it? So, I have to configure my arduino so that the signal it sends out matches the supported sonar protocol?

You can implement the i2c protocol described here in the datasheet. It’s just 3 simple commands that you could implement using the Arduino Wire library (if there are no incompatibilities between Arduino TWI interface and autopilot’s i2c port).

Basically, you receive the “Take a range reading” command, perform the measure and store the data in a variable, then send it as soon as “Report the last range value” arrives.

The code to measure the distance with SR04 should be easy to find.

1 Like

Hi, thank you so much for your help. I am a real beginner here. May I know which 3 commands are you referring to? As far as I know, the pixhawk is preprogrammed to be the master.

Thank you.

I’m referring to the 3 i2c commands that are specified in the datasheet on page 3: “Take a range reading”, “Report the last range value” and “Change the sensor address”.

You’re right, the Pixhawk is the master and the Arduino should be the slave with default address 112, as specified on page 2.

When the Pixhawk writes 81 to address 112, you should trigger the measurement. When the Pixhawk reads from that address, you should respond with a 2 byte measurement value in cm, MSB then LSB.

As for the “Change the sensor address” command, it doesn’t seem to be used by Ardupilot code.

Disclaimer: I didn’t try this myself, but this is the way I’d solve it.