B4R Question Unable to connect HC-SR04 to WeMos D1 Mini R3

hatzisn

Well-Known Member
Licensed User
Longtime User
Hi everyone,

I tried to connect an HC-SR04 sensor to a WeMos D1 R3 but I cannot get it to work. Here is my materialization and the code follows. Do you see any errors?
The values of the resistors in the Fritzing picture are 4,7kΩ, 10kΩ and 100Ω from left to right (there are only fixed values). Mine are respectively (measured with the resistor setting in the voltometer) : 5,5kΩ, 9,86kΩ and 110Ω from left to right. No echo signal is returned from the sensor. The 5V pin gives 4.79V which I do not know if it is enough. The code follows:


1595751153102.png



B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'Public variables can be accessed from all modules.

    Private SendTriggerTimer As Timer
 
    Public Serial1 As Serial
    Private wifi As ESP8266WiFi

    Private d1 As D1Pins
 
 
    Private pin2 As Pin
    Private pinSend As Pin
    Private pinReceive As Pin
 
    Private distance As Double
    Private pulseduration As Long
End Sub





Private Sub AppStart
    Serial1.Initialize(9600)
    Log("AppStart")
 
 
    pin2.Initialize(d1.D0, pin2.MODE_OUTPUT)
    pinSend.Initialize(d1.D7, pinSend.MODE_OUTPUT)
    pinReceive.Initialize(d1.D8, pinReceive.MODE_INPUT)
 
    SendTriggerTimer.Initialize("SendTriggerTimer_Tick", 500)
    SendTriggerTimer.Enabled = False
 
    FlashGreenLight3Times
 
    If wifi.Connect2("SSID", "Password") Then
        Log("Connected to router.")
        pin2.DigitalWrite(True)
        SendTriggerTimer.Enabled = True
    Else
        Log("Failed to connect to router.")
        Return
    End If
 
 
 
 
End Sub

Private Sub SendTriggerTimer_Tick

    If CheckDistance Then
        Log("Ok, measured")
    End If
 
End Sub


Private Sub CheckDistance As Boolean
 
    'Begin trigger
    pinSend.DigitalWrite(True)

    Log("Begin trigger")

    'Trigger Off
    pinSend.DigitalWrite(False)
    Log("End trigger")
 
    'Distance proportional to pulse duration received on Echo Pin
    RunNative("pulseins", pinReceive.PinNumber)
    'distance=(0.5*pulsduration)/29.1
    Log("Pulse duration: ", pulseduration)
    distance=(0.5*pulseduration/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 ")
        Return False
    Else
        Log("Distance (cm) =",distance)
        Return True
    End If
End Sub




#if C
void pulseins (B4R::Object* o) {
   b4r_main::_pulseduration = pulseIn(o->toULong(),HIGH);
}
#End if

Sub FlashGreenLight3Times
 
    For ii = 1 To 3
        pin2.DigitalWrite(True)
        Delay(500)
        pin2.DigitalWrite(False)
        Delay(500)
    Next
 
End Sub
 

Attachments

  • WeMos-to-HCSR04.zip
    7 KB · Views: 246
Last edited:

hatzisn

Well-Known Member
Licensed User
Longtime User
A thorough search in the internet revealed that there is an HC-SR04+ sensor (notice the +) which works from 3 to 5V. I may buy it but for tomorrow I am thinking of powering it with an arduino.
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
If I might suggest, take out the resisitors on the Echo line and connect directly to the Wemos (Link). This code works for me, you can try it.

B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region

Sub Process_Globals
    'HC-SR04 Ultrasonic Sensor
    'Libraries required: rCore, rESP8266
    Public Serial1 As Serial
    Private wemos As D1Pins
    Private trigPin, echoPin As Pin
    Private timer1 As Timer
    Private pulsduration As ULong  'ignore
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Log("AppStart")
    timer1.Initialize("timer1_Tick", 1000)
    trigPin.Initialize(wemos.D6, trigPin.MODE_OUTPUT)
    echoPin.Initialize(wemos.D7, echoPin.MODE_INPUT)
    timer1.Enabled = True
End Sub

Private Sub Timer1_Tick
    trigPin.DigitalWrite(False)
    DelayMicroseconds(2)
    trigPin.DigitalWrite(True)
    DelayMicroseconds(10)
    trigPin.DigitalWrite(False)
    RunNative("pulseins", echoPin.PinNumber)
    Dim duration As Long = pulsduration
    Dim distance As Long = duration / 58.2
    Log(distance)
End Sub


#if C
void pulseins (B4R::Object* o) {
  b4r_main::_pulsduration = pulseIn(o->toULong(),HIGH);
}
#End if
 
Upvote 0

hatzisn

Well-Known Member
Licensed User
Longtime User
I 've done some progress but yet no success. Here is what I've done:

1) I powered the HC-SR04 with an Arduino Mega's 5V (5,02 V) and I bridged the Grounds of the Mega and Wemos. --> No success in detecting but the sensor works now because if I disconnect the Echo from the WeMos and check it with the Voltometer I get readings in the intervals anticipated but the pulse is very brief and there is not enough time for the Voltometer to adapt.
2) I changed the small resistor of the voltage divider from 5,5k to 3,85k (Voltometer's measurement) getting now from the voltage devider the 72% of the Echo --> No success
3) I removed the voltage divider at all and decided to take the risk by connecting the echo pin directly to the Wemos --> No success
4) I tried to get readings in other pins of WeMos --> No success

Here is what I ended up with. Any suggestions for something I may have missed?
WeMos_HC-SR04_20200727_130246_Small.jpg
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
If you look at my code and your code, you will see after setting the trigger to high, a delay of 10 microseconds is required. Another link for you. Look at post #2.
 
Upvote 0

hatzisn

Well-Known Member
Licensed User
Longtime User
@mark35at thanks a lot for your responses. I forgot to add to the steps that I copied your code and already tried that. It seems that it's related to the board and not to the materialization. Here is what I 've done. I created this B4R program to check each of the pins as input both without anything connected to them and if I connect them to the 3,3V output of the WeMos. Here is the sketch and what I see in the video that follows (nothing is connected to the Input pins - What can you make out of this?)

B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'Public variables can be accessed from all modules.
    Public Serial1 As Serial
    
    Dim p(9) As Pin
    Dim d1 As D1Pins
End Sub

Private Sub AppStart
    Serial1.Initialize(9600)
    Log("AppStart")
    
    p(0).Initialize(d1.D0, p(0).MODE_INPUT)
    p(1).Initialize(d1.D1, p(1).MODE_INPUT)
    p(2).Initialize(d1.D2, p(2).MODE_INPUT)
    p(3).Initialize(d1.D3, p(3).MODE_INPUT)
    p(4).Initialize(d1.D4, p(4).MODE_INPUT)
    p(5).Initialize(d1.D5, p(5).MODE_INPUT)
    p(6).Initialize(d1.D6, p(6).MODE_INPUT)
    p(7).Initialize(d1.D7, p(7).MODE_INPUT)
    p(8).Initialize(d1.D8, p(8).MODE_INPUT)
    
    AddLooper("CheckInp")
End Sub


Private Sub CheckInp
    
    For ii = 0 To 8
        Dim b As Boolean
        b = p(ii).DigitalRead
        If b = True Then
            Log("Arduino Pin: ", p(ii).PinNumber, " - WeMos D", ii, "-", Micros)
        End If
    Next
End Sub

What I see - nothing is connected to the Input pins - Maximize the size of the video to see clearly.

 
Upvote 0

f0raster0

Well-Known Member
Licensed User
Longtime User
Can you show the schematic for your tests?
Have you tried the @mark35at 's test using D7, D6?
in your fisrt post you are using D8
 
Last edited:
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
I have no idea why you did this but in Google, Pin D8 is used to flash the Wemos. I am not sure about D2. As per previous post #7, try the pins D7 and D6.

Also upload your schematic (as requested by f0raster0) and the code you are using. Power the Wemos via the USB. Where did you get the HC-SR04?
 
Upvote 0

hatzisn

Well-Known Member
Licensed User
Longtime User
Can you show the schematic for your last tests
Have you tried the @mark35at 's test using D7, D6?
in your fisrt post you are using D8

Hi @f0raster0, I tried with D7 (trigger) and D6 (echo) but with no chance. In post #4 there is an analytical description of what I 've tried after the initial failure.


I have no idea why you did this but in Google, Pin D8 is used to flash the Wemos. I am not sure about D2. As per previous post #7, try the pins D7 and D6.
Also upload your schematic (as requested by f0raster0) and the code you are using. Power the Wemos via the USB. Where did you get the HC-SR04?

@f0raster0 and @mark35at there is no schematic for the last test shown in the video and for the previous post the schematic is shown above. Nothing is connected to the WeMos but the USB that powers it. Yet all the pins "reply" with a true/HIGH on the digital read as it can be seen in the video and by checking the code. I check the solderings with the magnifier to see if there is any short-cirquit but I only see single paths/leads to the solderings. The sensor is bought from Banggood and the WeMos from a local electronic's maker store.
 
Last edited:
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
One last thing to try. Use your code from post #1 and connect the led "
FlashGreenLight3Times". Test that it blinks on each DIO. That way you know that the Wemos is okay and probably the HC-SR04 is faulty.
 
Upvote 0

hatzisn

Well-Known Member
Licensed User
Longtime User
I searched a lot in the Internet and I 've noticed that it 's a known issue generally on esp8266 boards that some pins start high. The suggested solution was to set to low in setup/AppStart. I did so but the pins D3, D4, D7 remained high. Further more when I connected the 3,3V to the pin D6 its state changed and was detected but remained high when I removed the jumper wire. I tested the sketch into two wemos's with the same result but I was tired enough to call it a day. Now that I 've searched some more I've found that D3 & D4 have Pull Up resistors but D7 is MOSI(should it stay high since it is a communication pin?). Take a look at this:


For the going HIGH and staying high they suggest pull down resistors. I will try it tomorrow.
 
Upvote 0

Mark Read

Well-Known Member
Licensed User
Longtime User
I am going to make one last suggestion to you.

Put your voltmeter or multimeter aside, out of reach!

In post #4 you are showing a Mega (so you must have one). It is 5V compatible. Take my code, which is also from the forum, modify it for the Mega and try it - does the HC-SR04 work without any resistors?

Take your test Wemos and try turning on and off a LED with each digital IO pin to check your soldering (I think you have probably soldered well) - does it work on each IO?

If both of the above work, then something is wrong elsewhere but I don't know where. Throughout the whole of this thread you have said " No success " but no further error information. It is difficlut to help without log information: code, log info, schematic etc.

Sorry. :)
 
Upvote 0

hatzisn

Well-Known Member
Licensed User
Longtime User
.
.
Take your test Wemos and try turning on and off a LED with each digital IO pin to check your soldering (I think you have probably soldered well) - does it work on each IO?
.
.

I tried to check the solderings of the WeMos and all the solderings work perfect. I did it with the following program using the immediately following schematic (I was removing from each pin the jumper wire and moving it to the next):

B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'Public variables can be accessed from all modules.
    Public Serial1 As Serial
   
    Dim p(9) As Pin
    Dim d1 As D1Pins
   
    Dim ii As Int = 0
End Sub

Private Sub AppStart
    Serial1.Initialize(9600)
    Log("AppStart")
   
    p(0).Initialize(d1.D0, p(0).MODE_OUTPUT)
    p(0).DigitalWrite(False)
   
    p(1).Initialize(d1.D1, p(1).MODE_OUTPUT)
    p(1).DigitalWrite(False)
   
    p(2).Initialize(d1.D2, p(2).MODE_OUTPUT)
    p(2).DigitalWrite(False)
   
    p(3).Initialize(d1.D3, p(3).MODE_OUTPUT)
    p(3).DigitalWrite(False)
   
    p(4).Initialize(d1.D4, p(4).MODE_OUTPUT)
    p(4).DigitalWrite(False)
   
    p(5).Initialize(d1.D5, p(5).MODE_OUTPUT)
    p(5).DigitalWrite(False)
   
    p(6).Initialize(d1.D6, p(6).MODE_OUTPUT)
    p(6).DigitalWrite(False)
   
    p(7).Initialize(d1.D7, p(7).MODE_OUTPUT)
    p(7).DigitalWrite(False)
   
    p(8).Initialize(d1.D8, p(8).MODE_OUTPUT)
    p(8).DigitalWrite(False)
   
    AddLooper("FlashGreenLight2Times")
End Sub



Sub FlashGreenLight2Times
    ii = ii + 1
    If ii = 9 Then ii = 0
    Log("D", ii)
   
    For jj = 0 To 1
        p(ii).DigitalWrite(True)
        Delay(200)
        p(ii).DigitalWrite(False)
        Delay(200)
    Next
End Sub


1596010105090.png


.
.
If both of the above work, then something is wrong elsewhere but I don't know where. Throughout the whole of this thread you have said " No success " but no further error information. It is difficlut to help without log information: code, log info, schematic etc.

A test with the Sensor showed that it works fine but it needs a minimum of 5V (it is obvious that for use with a WeMos the HC-SR04+ is needed which accepts 3V-5V Vcc and trigger and echo with corresponding levels of signals).
When I wrote no success it meant that I did not manage to measure the distance - I was not able to get the pulseIns measurement. The schematic was posted in the 1st post and in the 4th post all I did was to remove the voltage devider and connect directly the pin (yellow wire) to the echo pin (but you are right - it isn't totally visible in the picture). The problem though seems to be a general flaw in the esp8266 cirquits. After boot, their GPIO pins except from those that are pulled down (i.e. D8 in WeMos) start HIGH and thus I couldn't measure. What one has to do is set them low in the beginning and then change their pinMode to Input. But that is not enough because with the first input signal they go in high impedance mode and to return in low there has to be a pull-down resistor present. I will try it in the afternoon and post my results here.
 

Attachments

  • 1596007696667.png
    1596007696667.png
    128.1 KB · Views: 205
Last edited:
Upvote 0

hatzisn

Well-Known Member
Licensed User
Longtime User
Almost solved. I've managed to get it working with the following schematic. The HC-SR04 is powered by an arduino and the grounds of the two boards are bridged. The trigger (orange wire) gets the signal (3,3V) from D6 and the echo is returned to D7 which is connected to a pull down resistor (10kΩ). I get though pulseduration constantly 4 or 6 regardless of the distance of the obstacle. That is an issue I 'll have to address. The sensor when it is connected to Arduino gives proper readings and correct. The code follows.

1596052882011.png


B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'Public variables can be accessed from all modules.
    Public Serial1 As Serial

    Dim p(9) As Pin
    Dim d1 As D1Pins

    Private SendTriggerTimer As Timer

    Public Serial1 As Serial
    Private wifi As ESP8266WiFi

    Private d1 As D1Pins

    Private distance As Double
    Private pulseduration As Long
End Sub

Private Sub AppStart
    Serial1.Initialize(9600)
    Log("AppStart")

    p(0).Initialize(d1.D0, p(0).MODE_OUTPUT)
    p(0).DigitalWrite(False)


    p(1).Initialize(d1.D1, p(1).MODE_OUTPUT)
    p(1).DigitalWrite(False)


    p(2).Initialize(d1.D2, p(2).MODE_OUTPUT)
    p(2).DigitalWrite(False)


    p(3).Initialize(d1.D3, p(3).MODE_OUTPUT)
    p(3).DigitalWrite(False)


    p(4).Initialize(d1.D4, p(4).MODE_OUTPUT)
    p(4).DigitalWrite(False)


    p(5).Initialize(d1.D5, p(5).MODE_OUTPUT)
    p(5).DigitalWrite(False)


    p(6).Initialize(d1.D6, p(6).MODE_OUTPUT)
    p(6).DigitalWrite(False)


    p(7).Initialize(d1.D7, p(7).MODE_OUTPUT)
    p(7).DigitalWrite(False)
    p(7).Mode = p(7).MODE_INPUT

    p(8).Initialize(d1.D8, p(8).MODE_OUTPUT)
    p(8).DigitalWrite(False)



    SendTriggerTimer.Initialize("SendTriggerTimer_Tick", 500)
    SendTriggerTimer.Enabled = False

    FlashGreenLight3Times

    If wifi.Connect2("SSID", "Password") Then
        Log("Connected to router.")
        p(0).DigitalWrite(True)
        SendTriggerTimer.Enabled = True
    Else
        Log("Failed to connect to router.")
        Return
    End If



End Sub


Private Sub SendTriggerTimer_Tick

    If CheckDistance Then
        Log("Ok, Measured correctly")
    End If

End Sub


Private Sub CheckDistance As Boolean

    'Begin trigger
    p(6).DigitalWrite(False)
    DelayMicroseconds(2)

    p(6).DigitalWrite(True)

    Log("Begin trigger")

    DelayMicroseconds(10)

    'Trigger Off
    p(6).DigitalWrite(False)
    Log("End trigger")

    'Distance proportional to pulse duration received on Echo Pin
    Log(p(7).PinNumber)
    RunNative("pulseins", p(7).PinNumber)
    'distance=(0.5*pulsduration)/29.1
    Log("Pulse duration: ", pulseduration)
    distance=(0.5*pulseduration/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 ")
        Return False
    Else
        Log("Distance (cm) =",distance)
        Return True
    End If
End Sub




#if C
void pulseins (B4R::Object* o) {
   b4r_main::_pulseduration = pulseIn(o->toULong(),HIGH);
}
#End if

Sub FlashGreenLight3Times

    For ii = 1 To 3
        p(0).DigitalWrite(True)
        Delay(500)
        p(0).DigitalWrite(False)
        Delay(500)
    Next

End Sub
 
Last edited:
Upvote 0
Top