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: 2,696
Last edited:

FrancisB

New Member
Licensed User
Longtime 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
Longtime 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
Longtime 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:

FrancisB

New Member
Licensed User
Longtime User
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.
...

Finally... I has been able to connect, seems to be a Tomato router firmware limitation... Done!
 

Humberto

Active Member
Licensed User
Longtime 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
Longtime User
I configure in Arduino IDE and try some examples and works
 

Attachments

  • arduino.png
    arduino.png
    22.5 KB · Views: 924
  • arduino_1.png
    arduino_1.png
    53.9 KB · Views: 882
  • board.png
    board.png
    16.1 KB · Views: 896
  • module.png
    module.png
    383.3 KB · Views: 913

Toley

Active Member
Licensed User
Longtime 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
Longtime 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
Longtime 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
Longtime 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.
 

hatzisn

Expert
Licensed User
Longtime User
Herbert32 see also the B4R version 3 release notes for the Esp8266 library you can install in your Arduino IDE to cooperate with B4R.
 

KiloBravo

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

Johan Hormaza

Well-Known Member
Licensed User
Longtime User
Help!!!
I try connect Android (b4A) and B4r (esp8266 01s), but not working.
B4r:
Sub Process_Globals
    Public Serial1 As Serial
    Private wifi As ESP8266WiFi
    Private mqtt As MqttClient
    Private socket As WiFiSocket
    Private Timer1 As Timer
    Private Led As Pin
End Sub

Private Sub AppStart
    Serial1.Initialize(9600)
    Log("AppStart")
    Timer1.Initialize("Timer1_Tick", 500)
    Led.Initialize(3,Led.MODE_OUTPUT)
    If wifi.Connect2("WIFISSID", "Password") = False Then
        Log("Error connecting to router!")
        Return
    Else
        Log("Conectado a red WIFI")
    End If
    'IP AS: Byte(192, 168, 0, 1)
        mqtt.Initialize(socket.Stream,"192.168.4.2",51042, "esp", "Mqtt_MessageArrived", "Mqtt_Disconnected")
    Dim options As MqttConnectOptions
    options.Initialize("WIFISSID", "password") 'If your mqtt server don't use user and password, use mqtt.Connect
    mqtt.Connect2(options)
    Connect(0)
   
End Sub

Sub Connect(unused As Byte)
    If mqtt.Connect = False Then
        Log("trying to connect again")
        CallSubPlus("Connect", 500, 0)
        Return
    End If
    Log("Connected to broker")
    mqtt.Subscribe("esp", 0)
End Sub


Sub Mqtt_MessageArrived (Topic As String, Payload() As Byte)
    Log("Message arrived. Topic=",  " payload: ", Payload)
If Topic = "esp" Then
    If Payload = "nhay" Then
'        Led.DigitalWrite(False)
            Timer1.Enabled = True
'            Dim b() As Byte = "nhay"
'            mqtt.Publish("nhay", b)
'            Log("Publicada apertura")
        Else
    End If
End If
End Sub

Sub Mqtt_Disconnected
    Log("Disconnected mqtt")
    mqtt.Close
    Connect(0)
End Sub

Private Sub Timer1_Tick
    Dim currentState As Boolean = Led.DigitalRead
    Log("CurrentState: ", currentState)
    Dim NewState As Boolean = Not(currentState)
    Log("NewState: ", NewState)
    Led.DigitalWrite(NewState)
End Sub

B4A:
B4A:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Public client As MqttClient
    Public rp As RuntimePermissions
    Public connected As Boolean
    End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    Private btnConnect As Button
    Private txtIP As EditText
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("Layout")
    connected = False
End Sub

Sub Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
End Sub

Sub ConnectMQTT
    client.Initialize("client", "tcp://" & "192.168.4.2" & ":51042", "android")
    Dim options As MqttConnectOptions
    options.Initialize("user", "password")
    client.Connect2(options)
   
End Sub


Sub client_Connected (Success As Boolean)
    connected = Success
End Sub

Sub client_Disconnected
    connected = False
    Log("Disconnected mqtt")
    End Sub


Private Sub btnConnect_Click
    OpenNhay("nhay")
End Sub


Public Sub OpenNhay(Nhay As String)
    Log("Nhay: " & Nhay)
        If Not (connected) Then
        ConnectMQTT
        Log("Waiting connection")
        Wait For client_Connected (Success As Boolean)
        If Success Then
            Log("Mqtt connected")
            client.Publish("esp", Nhay.GetBytes("UTF8"))
            ToastMessageShow("OpenNhay " & Nhay, True)
        Else
            ToastMessageShow("There was an error connecting to mqtt: " & LastException, True)
        End If
    Else
        client.Publish("esp", Nhay.GetBytes("UTF8"))
        ToastMessageShow("OpenNhay " & Nhay, True)
    End If
End Sub


Help Me. THanks
What message do you get when using this code?
Both clients for both the ESP8266 and the Android App connected to the Brocker MQTT successfully?
 

Johan Hormaza

Well-Known Member
Licensed User
Longtime User
Ok, I see that you have no connection to the MQTT server.
Are you running the MQTT broker on your local computer?
And if so, keep in mind that all clients must be connected to the same local network
 
Top