Hello,
I am trying to make the grove ultrasonic distance sensor work, but still get no data from the sensor. Since I am very new to bela, I stayed close to Sensors/ultrasonic-distance-sensor/render.cpp.
giuliomoro This looks like a HC-SR04 but using a single pin. Can be used from Bela, but needs some adaptations of the existing code. Namely, it needs to call pinMode() before and after each write to the trigger pin.
I tried to call pinMode()
before and after writing on the gTrigDigitalOutPin
, which is set to the same pin as gEchoDigitalInPin.
bool setup(BelaContext *context, void *userData)
{
// Set the mode of digital pins
pinMode(context, 0, gTrigDigitalOutPin, OUTPUT); // writing to TRIGGER pin
pinMode(context, 0, gEchoDigitalInPin, INPUT); // reading from ECHO pin
pulseIn.setup(context, gEchoDigitalInPin, HIGH); //detect HIGH pulses on the ECHO pin
scope.setup(2, context->digitalSampleRate);
return true;
}
void render(BelaContext *context, void *userData)
{
for(unsigned int n = 0; n < context->digitalFrames; ++n){
gTriggerCount++;
bool state;
if(gTriggerCount == gTriggerInterval){
gTriggerCount = 0;
state = HIGH;
} else {
state = LOW;
}
pinMode(context, 0, gTrigDigitalOutPin, OUTPUT);
digitalWrite(context, n, gTrigDigitalOutPin, state); //write the state to the trig pin
pinMode(context, 0, gEchoDigitalInPin, INPUT);
int pulseLength = pulseIn.hasPulsed(context, n); // will return the pulse duration(in samples) if a pulse just ended
float duration = 1e6 * pulseLength / context->digitalSampleRate; // pulse duration in microseconds
static float distance = 0;
if(pulseLength >= gMinPulseLength){
// rescaling according to the datasheet
distance = duration / gRescale;
}
static int count = 0;
if(count > 5000){ // we do not want to print the value every time we read it
rt_printf("pulseLength: %d, distance: %fcm\n", pulseLength, distance);
count = 0;
}
++count;
// Logging to the scope the pulse inputs (gEchoDigitalInPin) and the distance
scope.log(digitalRead(context, n, gEchoDigitalInPin) * 0.5, distance/100);
}
}
Is there something else I could try?