B4R Tutorial ESP8266 - Getting Started

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

    SS-2016-06-22_17.33.54.png


  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):

    SS-2016-06-23_12.16.05.png
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

  • B4J_ConnectToESP8266.zip
    3.7 KB · Views: 1,828
Last edited:

FrancisB

New Member
Licensed User
I tried your simple example and I'm just not able to connect...

I got what was expected form the ESP8266:
Connected to wireless network.
My ip: 192.168.1.108



I tried a very very small VB.Net test as:

Imports System.Net
...
Dim Sck As New Sockets.TcpClient
Sck.Connect(IPAddress.Parse("192.168.1.108"), 51042)


...
TIMEOUT ERROR

I verified my firewall and the port is open in private and domain...

First try, first strike... :(
 

positrom2

Active Member
Licensed User
While ago Erel's examples on B4R/B4J worked. Not anymore.
The port 51042 is open for ingoing, outgoing, TCP and UDP (all private).
The B4J error reads:
java.net.UnknownHostException: 192,168,178,20
...
 

FrancisB

New Member
Licensed User
Please start with the B4J example. There is no reason to use VB.Net.

Hahahaha
I'm basically a senior .Net programmer. But unrelated to the programming language we use, it should work on any kind of TCP-IP connection.

You know what? I tried also B4J without more success...
java.net.ConnectException: Connection timed out: connect

I used Arduino C/C++ since a few weeks, it works pretty well, the big deal, the OOP is very basic, I have the feeling to return in my old DOS time without the interrupts. Your approach is more OOP (like NodeMcu/Lua). But without a small connection success...

By the way, I use the new Arduino IDE 1.6.13 (looks working well with B4R).

Francis
P.S.: I use the same development board WEMOS D1, it works very well with: Arduino C/C++, NodeMCU, and next, I will look for esp8266basic (who look as my old Vic20 or C=64, with a couple of strong options).
 
Last edited:

Humberto

Active Member
Licensed User
Hi

I´m trying this example and compile and install but I get no message in the log panel

Thanks


B4X:
B4R version: 1.80
Parsing code.    (0.00s)
Compiling code.    (0.04s)
Building project    (0.04s)
Compiling & deploying Ino project (NodeMCU 0.9 (ESP-12 Module) - COM10)    (34.86s)
    Looking for library 'user32'
    Adding paths from jna.library.path: null
    Trying user32.dll
    Found library 'user32' at user32.dll
    Looking for library 'shell32'
    Adding paths from jna.library.path: null
    Trying shell32.dll
    Found library 'shell32' at shell32.dll
    Looking for library 'Ole32'
    Adding paths from jna.library.path: null
    Trying Ole32.dll
    Found library 'Ole32' at Ole32.dll
    O sketch usa 238661 bytes (22%) de espaço de armazenamento para programas. O máximo são 1044464 bytes.
    Variáveis globais usam 33060 bytes (40%) de memória dinâmica, deixando 48860 bytes para variáveis locais. O máximo são 81920 bytes.
   
Completed successfully.
 

Humberto

Active Member
Licensed User
I configure in Arduino IDE and try some examples and works
 

Attachments

  • arduino.png
    arduino.png
    22.5 KB · Views: 566
  • arduino_1.png
    arduino_1.png
    53.9 KB · Views: 532
  • board.png
    board.png
    16.1 KB · Views: 546
  • module.png
    module.png
    383.3 KB · Views: 557

Toley

Active Member
Licensed User
Hi Humberto, the board you are showing is not a WeMos it's a nodeMCU. Don't know if it will solve the problem but it worth a try
 

Humberto

Active Member
Licensed User
I tryed with NodeMCu 0.9 and didn´t work then I change to this WeMos and works with Arduino IDE and now with B4R

Thanks
 

Herbert32

Active Member
Licensed User
as it is from 2016... - is this Tutorial already up to date ?

For usage with ESP8266 we should use Arduino-IDE 1.8.5 or can we also use more actual versions like 1.8.11 ?

is it still recommended to use esp8266 by ESP8266 Community in Version 2.4.2 or can also the actual version 2.6.3 be used ?
 

Peter Simpson

Expert
Licensed User
as it is from 2016... - is this Tutorial already up to date?

For usage with ESP8266 we should use Arduino-IDE 1.8.5 or can we also use more actual versions like 1.8.11 ?

is it still recommended to use esp8266 by ESP8266 Community in Version 2.4.2 or can also the actual version 2.6.3 be used ?

Yes to question 1
You can download and use the latest Arduino IDE if you wish to do so, that's what I do.

You can use any version.
 

KiloBravo

Member
Licensed User
I am little rusty, but I downloaded B4R v3.30 and installed it. Still using Arduino-IDE 1.8.5.
I kept getting comm sync errors. So I updated the Arduino Boards Lib ESP8266 Community Version from 2.4.2 to 2.6.3.
That solved my problem. D1 Mini Pro. It has the older Si Labs CP210x USB to UART chip.
I know WEMOS uses the CH340 for a USB to UART chip now. YMMV :)
 
Top