B4R Tutorial ESP8266 - Getting Started

Discussion in 'B4R Tutorials' started by Erel, Jul 7, 2016.

  1. Erel

    Erel Administrator Staff Member Licensed User

    B4R v1.20 added support for ESP8266 modules. ESP8266 is a great module for IoT solutions. For a few dollars you get a powerful microcontroller with built-in support for wifi.

    I recommend to develop with a board that includes a USB to serial converter.

    Configuration

    1. Open Arduino IDE - File - Preferences and add the following URL: http://arduino.esp8266.com/stable/package_esp8266com_index.json

      [​IMG]

    2. In Arduino IDE -> Tools - Board - Boards Manager. Search for esp and install esp8266 by ESP8266 community.
    3. Open the boards selector in B4R and select the board type (select the highest UploadSpeed):

      [​IMG]
    B4R includes two ESP8266 specific libraries:
    rESP8266WiFi - Similar to rEthernet library. It includes the following types:
    • ESP8266WiFi - Responsible for connecting or creating the wireless network.
    • WiFiSocket - Equivalent to EthernetSocket.
    • WiFiServerSocket - Equivalent to EthernetServerSocket.
    • WiFiUDP - Equivalent to EthernetUDP
    rESP8266
    • ESP8266 - Currently includes a single method that restarts the board.
    • D1Pins - Maps the pins of WeMos boards.
    Working with ESP8266WiFi is simple and similar to working with the Ethernet shield.
    Example of a socket connection (depends on rESP8266WiFi and rRandomAccessFile).
    Note that it requires B4R v1.50+ as it uses the new B4RSerializator feature:
    Code:
    Sub Process_Globals
      
    Public Serial1 As Serial
      
    Private wifi As ESP8266WiFi
      
    Private server As WiFiServerSocket
      
    Private astream As AsyncStreams
      
    Private timer1 As Timer
      
    Private ser As B4RSerializator
    End Sub

    Private Sub AppStart
      Serial1.Initialize(
    115200)
      
    Log("AppStart")
      
    'ScanNetworks
      If wifi.Connect("dlink"Then 'change to your network SSID (use Connect2 if a password is required).
      Log("Connected to wireless network.")
        
    Log("My ip: ", wifi.LocalIp)
      
    Else
      
    Log("Failed to connect.")
      
    Return
      
    End If
      timer1.Initialize(
    "timer1_Tick"1000)
      timer1.Enabled = 
    True
      
    server.Initialize(51042"server_NewConnection")
      
    server.Listen
    End Sub

    Sub Server_NewConnection (NewSocket As WiFiSocket)
       
    Log("Client connected")
        astream.Initialize(NewSocket.Stream, 
    "astream_NewData""astream_Error")
    End Sub

    Sub Timer1_Tick
      
    If server.Socket.Connected Then
      astream.Write(ser.ConvertArrayToBytes(
    Array("Time here is: ", Millis)))
      
    End If
    End Sub


    Sub AStream_NewData (Buffer() As Byte)
       
    Dim be(10As Object
       
    Dim data() As Object = ser.ConvertBytesToArray(Buffer, be)
       
    Log("Received:")
       
    For Each o As Object In data
         
    Log(o)
       
    Next
    End Sub

    Sub AStream_Error
      
    Log("Error")
      
    server.Listen
    End Sub

    Private Sub ScanNetworks 'ignore
      Dim numberOfNetworks As Byte = wifi.Scan
      
    Log("Found: ", numberOfNetworks, " networks.")
      
    For i = 0 To numberOfNetworks - 1
      
    Log(wifi.ScannedSSID(i))
      
    Next
    End Sub
    B4J code (project is attached):
    Make sure to update the ESP8266 ip address, it will be printed in the logs.
    Code:
    Sub Process_Globals
       
    Private socket As Socket
       
    Private astream As AsyncStreams
       
    Private ser As B4RSerializator
    End Sub

    Sub AppStart (Args() As String)
       
    socket.Initialize("socket")
       
    socket.Connect("192.168.0.43"510420)
       ser.Initialize
       StartMessageLoop
    End Sub

    Sub Socket_Connected (Successful As Boolean)
       
    If Successful Then
         
    If astream.IsInitialized Then astream.Close
         astream.Initialize(
    socket.InputStream, socket.OutputStream, "astream")
       
    End If
    End Sub

    Sub AStream_NewData (Buffer() As Byte)
       
    Dim data() As Object = ser.ConvertBytesToArray(Buffer)
       
    Log("Received:")
       
    For Each o As Object In data
         
    Log(o)
       
    Next
       astream.Write(ser.ConvertArrayToBytes(
    Array("Thank you!""Time here: "DateTime.Time(DateTime.Now))))
    End Sub

    Sub AStream_Error
      
    Log("Error")
    End Sub

    Sub AStream_Terminated
      
    Log("Terminated")
    End Sub
    Notes

    - Under the hood there are many differences between ESP8266 and the Arduinos. One of the differences which can be relevant for developers is that the network stream is buffered. If you are writing directly to WiFiClient.Stream then you will need to call WiFiClient.Stream.Flush or the data will not be sent. This is not required when writing with AsyncStreams (which is the recommended way).
    - Check the board voltage. The WeMos board is 3.3v.
    - Not all libraries are supported.

    Example of configuring the ESP8266 wifi by connecting to its access point: https://www.b4x.com/android/forum/threads/esp8266-wifi-remote-configuration.68596/
     

    Attached Files:

    Last edited: Aug 30, 2017
  2. jarda

    jarda Member Licensed User

    Hi Erel

    I can use this library for WiFi module ESP WROOM 02? (connect on Rx and Tx Pro mini 3,3V)

    thank

    Jarek
     
    Last edited: Jul 16, 2016
  3. Erel

    Erel Administrator Staff Member Licensed User

    It will probably work as it is based on ESP8266.
     
  4. jarda

    jarda Member Licensed User

    Ok Erel..
    thank for answer..

    I need

    1. Wifi connect as Station (I do know)
    2. Connect modules on Pins RX and Tx [I do not know.... open(Rx, Tx) ??? in library is only Wifi.connect ]
    3. Net as Server (I do not know fnc net.CreateServer and fnc net.server:listen) https://nodemcu.readthedocs.io/en/master/en/modules/net/#netserverlisten
    how read and send byte array ?

    How used in B4R ? (implement)

    With PC terminal and COM port do work...

    In ESP wroom 02 is Node MCU last version...

    thanks for examples

    Jarek
     
    Last edited: Jul 17, 2016
  5. Erel

    Erel Administrator Staff Member Licensed User

    Please start a new thread for this in the questions forum.
     
  6. jarda

    jarda Member Licensed User

  7. Bert Oudshoorn

    Bert Oudshoorn Member Licensed User

    Thank you, it works great, made a little UDP server. In Station and Access Point mode. However, after a wifi.StartAccessPoint2(...) the AP mode cannot be switched off anymore. Only, via the Arduino IDE by setting a WiFi.mode(WIFI_STA) which terminates the mode WIFI_AP or WIFI_AP_STA.

    Something else, it is probably not possible to set the channel in AP mode? I used it in the nodemcu firmware, where a configuration structure can be specified: cfg={}, cfg.ssid="...", cfg.psw="...", cfg.channel=8 (1-14, 6 default), wifi.ap.config(cfg)
     
  8. Erel

    Erel Administrator Staff Member Licensed User

    Please start a new thread for this in the questions forum. It is simple to call those methods with inline C.
     
  9. Bert Oudshoorn

    Bert Oudshoorn Member Licensed User

  10. cloner7801

    cloner7801 Active Member Licensed User

    My b4r doesn't show the board in serial port field
    how can I fix this?
     
  11. Erel

    Erel Administrator Staff Member Licensed User

    Which board are you using? Did you install the driver? Is it listed under Device Manager - Ports:

    [​IMG]

    @Bert Oudshoorn please start a new thread for this question and make sure to use code tags.
     
  12. cloner7801

    cloner7801 Active Member Licensed User

    I am using wemos d1
    upload_2016-10-19_22-14-26.png
    how can I install this driver ?
    I searched but I cant found anything

    ---
    solved :
    I download this drive and install and then It fixed
    http://www.wch.cn/download/CH341SER_ZIP.html
     
  13. cloner7801

    cloner7801 Active Member Licensed User

    Sorry...
    How Can I write program directly to esp8266? without wemos D1 ?
    I have FTDI and I connect esp8266 to FTDI like this :
    upload_2016-10-19_23-5-52.png

    is there any code to use?
     
  14. positrom2

    positrom2 Active Member Licensed User

    There is no code to get into programming mode.
    For the bare ESP8266 you have to do the following (on the WEMOS board and others there is additional hardware to overcome this procedure):
    You have to attach one pushbutton between GND- Reset and a second one between GND-GPI00.
    Then for programming:
    Hold down GPI00 button, press and release the reset button and then start programming
    while keeping GPI00 down until programming is finished!!
    Your finger will start getting tired....
    http://www.whatimade.today/esp8266-easiest-way-to-program-so-far/
    https://www.hackster.io/glowascii/esp8266-programming-jig-5afd03
     
  15. Bert Oudshoorn

    Bert Oudshoorn Member Licensed User

    I release the GPIO0 button, after releasing the reset button. Next, I start the programming. No tired fingers :)
     
    inakigarm likes this.
  16. positrom2

    positrom2 Active Member Licensed User

    Good to know, thanks. Seems to be reasonable...why should the ESP continously watch that pin...
     
    Bert Oudshoorn likes this.
  17. cloner7801

    cloner7801 Active Member Licensed User

    :(
     
  18. Bert Oudshoorn

    Bert Oudshoorn Member Licensed User

    Just flash a led
    Code:
    Sub Process_Globals
        
    Public Serial1 As Serial
        
    Private led As Pin
        
    Private count As Byte = 0                                     
    End Sub
    Private Sub AppStart
        Serial1.Initialize(
    115200) : Delay(1000)
        
    Log("AppStart")
        
    led.Initialize(2led.MODE_OUTPUT)     'led on GPIO2
        Do Until count = 10
            
    led.DigitalWrite(True)  : Delay(1000)
            
    led.DigitalWrite(False) : Delay(1000)
            count = count + 
    1
        
    Loop 
    End Sub
    Did you include buttons? See what Positrom2 wrote: Hold down GPI00 button, press and release the reset button and then start programming.
    Include a resistor of 220 ohm between the led and earth.
    Oeps, do not forget on top the generated
    Code:
    #Region Project Attributes
        
    #AutoFlushLogs: True
        
    #CheckArrayBounds: True
        
    #StackBufferSize: 300
    #End Region
     
    Last edited: Oct 27, 2016
    cloner7801 likes this.
  19. cloner7801

    cloner7801 Active Member Licensed User

    can you draw the schematic?
     
  20. Bert Oudshoorn

    Bert Oudshoorn Member Licensed User

Loading...