Testing the HC-SR04 to measuring distances
The accuraccy of the sensor depends greatly on device (chinese, cheap, etc..); in code, I limited the measurement between 3 cm and 100 cm (probably your device can measure larger distance)
Thanks to inline C code, I've used the PulseIn Arduino function, that measures de Echo Pulse Width (the distance is calculated proportionally from this value)
You can use other digitals pins for trigger and echo if you want.
The accuraccy of the sensor depends greatly on device (chinese, cheap, etc..); in code, I limited the measurement between 3 cm and 100 cm (probably your device can measure larger distance)
Thanks to inline C code, I've used the PulseIn Arduino function, that measures de Echo Pulse Width (the distance is calculated proportionally from this value)
You can use other digitals pins for trigger and echo if you want.
B4X:
#Region Project Attributes
#AutoFlushLogs: True
#StackBufferSize: 300
#End Region
Sub Process_Globals
Public Serial1 As Serial
Private triggerpin,echopin As Pin
Dim pulsduration As ULong 'Pulse Width on Echo Pin (High to Low)
Dim distance As Double
Dim Intervalbtmeasures As Int=2 '2 seconds interval measures
Dim SendTriggerTimer As Timer
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
'Configure Pins connection between Arduino and Distance Sensor
triggerpin.Initialize(13,triggerpin.MODE_OUTPUT)
echopin.Initialize(12,echopin.MODE_INPUT)
echopin.DigitalWrite(False)
'Enable trigger with Timer interval
SendTriggerTimer.Initialize("SendTriggerTimer_Tick", Intervalbtmeasures*1000) '1000ms = 1 second
SendTriggerTimer.Enabled = True
End Sub
Private Sub SendTriggerTimer_Tick
'Begin trigger
triggerpin.DigitalWrite(True)
Log("Begin trigger")
'Trigger Off
triggerpin.DigitalWrite(False)
'Distance proportional to pulse duration received on Echo Pin
RunNative("pulseins",echopin.PinNumber)
distance=(0.5*pulsduration)/29.1
'Discard inaccurate distance values (here between 3 and 100 cm)
If (distance> 100) Or (distance<3) Then
Log("Inacurate Distance - place the sensor correctly ")
Else
Log("Distance (cm) =",distance)
End If
End Sub
#if C
void pulseins (B4R::Object* o) {
b4r_main::_pulsduration = pulseIn(o->toULong(),HIGH);
}
#End if
Last edited by a moderator: