B4R Tutorial ESP8266 - Getting Started

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



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

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:
B4X:
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(10) As 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.
B4X:
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", 51042, 0)
   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/
 

Attachments

Last edited:

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:

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:

Erel

Administrator
Staff member
Licensed User
Please start a new thread for this in the questions forum.
 

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)
 

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.
 

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?
 

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
 

Bert Oudshoorn

Member
Licensed User
Just flash a led
B4X:
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(2, led.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
B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region
 
Last edited:

cloner7801

Active Member
Licensed User
Just flash a led
B4X:
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(2, led.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
B4X:
#Region Project Attributes
    #AutoFlushLogs: True
    #CheckArrayBounds: True
    #StackBufferSize: 300
#End Region
can you draw the schematic?
 
Top