This seems like a fun project.
The source code I refer to from there is [this])https://github.com/BelaPlatform/Bela/blob/master/examples/06-Sensors/ultrasonic-distance/render.cpp). Wiring instructions are there and in the post you linked.
I understand you are familiar with Puredata and not so comfortable with C++, however I would recommend the following steps for you, which involve minimal tinkering with C++:
#1
remove at least one solenoid from your Bela, wire the sensor as described. Run the project and make sure everything works
#2
This implementation is using an analog out to the HC-SR04, because the latter requires a 5V input in order to work properly. To use the digitals, instead, you could replace the lines
analogWriteOnce(context, n / 2, gTriggerAnalogOutChannel, ...);
with
digitalWriteOnce(context, n, gTriggerDigitalOutChannel, ...);
after having declared and initialized gTriggerDigitalOutChannel
and having called
pinMode(context, 0, gTriggerDigitalOutChannel, OUTPUT);
in setup()
to initialize it as an output.
Once this is done, you could try to connect the sensor's TRIGGER input (which was previously connected to the analog pin ) to the digital pin defined in gTriggerDigitalOutChannel
and check if it works.
#3
If the above does not work, it is probably because the digital out range is 0-3.3V and the TRIGGER input requires 5V. Therefore, you will need a simple amplifier to (e.g.: a transistor and a resistor) to amplify the signal from the digital output pin. Note: if your amplifier is inverting, you may have to swap HIGH
with LOW
in the digitalWrite()
lines.
#4
Once you get it to work with the digital outputs at points #2 or #3, then you are ready to integrate this with PureData. Have a read here to get started, then you need to add the code from the project file you have been editing so far into a custom render.cpp
file with puredata support:
create a new Pd projet in the IDE, called MYPROJECT
get the file in core/default_libpd_render.cpp
and copy it into the project (e.g.: run the following in the terminal at the bottom of the IDE)
cp core/default_libpd_render.cpp projects/MYPROJECT/render.cpp
edit the render.cpp
file in MYPROJECT
by:
- copying the relevant global variables from the modified HC-SR04 example file to the top of
render.cpp
- copying the content of
setup()
from the modified HC-SR04 example file to the top of setup()
in render.cpp
- copying content of
render()
from the modified HC-SR04 example file to the top of render()
in render.cpp
- With the above changes, your
render.cpp
file will do the regular Puredata wrapping duties and also get new distance values from the sensors.
Hopefully all the above should be doable for you: it's a matter of writing/editing 4/5 lines of C++ and then copy/paste them. Let us know how it goes.