Hi, I am working on my school project and I am trying to interface 4 HC-SR04 Sonar Sensors but I am not sure if it’s possible since the board only has two SPI ports. My plan is to expand one port then connect 3 sonars to the I/O expander MCP23S17, However, I have no idea how to instantiate a sonar object with the pins from the expander in the codes. Any help will be greatly appreciated.
Hi there,
probably some additional info is required because I don’t understand it, sorry.
- The HC-SR04 Sonar Sensor is a analog device with trigger and echo signals without a SPI so why you need the SPI for it?
- The SPI is not like an UART so you can connect many devices on one SPI.
- How far you are with an implementation?
So 4x Sonar x2 pins(trigger and echo) = 8 pins for control + power supply ofc. Some projects also use linked trigger so total used pins can be 5.
However, for use the expander you will probably need modify the library of sensor.
BR, Jan
Hi, I imported the codes and the library on this link HC-SR04 | Mbed , And to use successfully use the Sonar, I had to declare an object as seen below.
ultrasonic mu(p6, p7, .1, 1, &dist); //Set the trigger pin to D8 and the echo pin to D9
//have updates every .1 seconds and a timeout after 1
//second, and call dist when the distance changes
I thought the module uses SPI because of p6 and p7. Thanks for the clarification.
Now, I want to use the library on this link below.
HCSR04 usensor(pX,pY), which pin should be written to or read from? and how can I modify this library or the other one so that I can acomodate the three sonors on the expander? A couple of line of codes on how to do this will be helpful.
Thanks in advance.
The library show you a working solution for one sensor and when you study it you can found how the sensor works.
For the start you can declare 4 objects of the HCSR04 library on different pins, that is probably simplest.
Also you can try make a simple code without a library (for example, based on a timer, like is on page what you posted), by your self, for one sensor and then add another sensors.
Also there are variants of implementation. You can connect all sensors separately or use common trigger or common echo. You can also manage it via interrupts.
When you connect all sensors to your board directly, you will spend 8 pins (You wanted use 2x SPIs before so it were also 8 pins) or with the common variant of trigger or echo only 5 pins, which is only one more then 4 pins what you need for your expander via SPI.
If do you still think it is necessary, for the expander you need also a library, and when you again check the components page you can found a MCP23S17 page.
BR, Jan
Thank you very much Jan, I think I will exclude the IO expander. Can I use p5,p6,p7,p8,p9 with 9 being the common echo?
If you not need the alternate peripherals of these pins, so why not, Digital pins can be set everywhere.
BR, Jan
I appreciate you help.