B4R Tutorial ESP8266 + UDP + BMP180 = Simple weather station

Similar threads

B4A Code Snippet [B4X] Convert bitmap to BMP format
B4R Code Snippet Firebase Push Messages (FCM)
B4R Tutorial Arduino + Raspberry Pi
B4R Library BMP180 - Pressure and temperature
B4R Tutorial SD cards

Erel

Administrator
Staff member
Licensed User
This is an example of how UDP can be used to broadcast the current temperature and pressure to one or more clients.

The nice thing about it is that there is no server involved. The ESP8266 just sends the packets to the broadcast address.



RandomAccessFile is used to create the packets. B4R doubles are 4 bytes (equivalent to B4X floats).
It is tempting to send the data as a string. However it is more efficient and actually simpler to deal with binary encoded numeric values.

This is the main code of this example (B4R):
B4X:
Dim buffer(8) As Byte
Dim raf As RandomAccessFile
raf.Initialize(buffer, True)
raf.WriteDouble32(bmp180.LastResult, raf.CurrentPosition)
bmp180.GetPressure(0, bmp180.LastResult)
raf.WriteDouble32(bmp180.LastResult, raf.CurrentPosition)
usocket.BeginPacket(ip, port)
usocket.Write(buffer)
usocket.SendPacket
The clients code:
B4X:
Private Sub usocket_PacketArrived (Packet As UDPPacket)
   If Packet.Length <> 8 Then
     Log("Invalid data")
     Return
   Else
     Dim raf As RandomAccessFile
     raf.Initialize3(Packet.Data, True)
     raf.CurrentPosition = Packet.Offset
     Dim temperature, pressure As Float
     temperature = raf.ReadFloat(raf.CurrentPosition)
     pressure = raf.ReadFloat(raf.CurrentPosition)
     Log($"Temperature: $1.1{temperature}°"$)
     Log($"Pressure: $1.1{pressure} mBar"$)
   End If
End Sub
The broadcast address is usually the network address with 255 as the fourth byte. The B4J program prints it.

BMP180 library is available here: https://www.b4x.com/android/forum/threads/bmp180-pressure-and-temperature.67730/
 

Attachments

Erel

Administrator
Staff member
Licensed User
The B4i client was updated. Fixed a bug where the socket became invalid while the app is in the background.
 

tonga

Member
Licensed User
Hi Erel,

I'm starting to use ESP8266 so I have a board Nodemcu Amica. I try to use this board with BMP180 with this programs but it doesn't work.
There are problems of compatibility? Or other?

Thanks
 

Erel

Administrator
Staff member
Licensed User
As you can see in this example, it does work with ESP8266.

Try to connect the BMP180 to an Arduino and see whether it works.
 

tonga

Member
Licensed User
BMP180 connected to board Nodemcu Amica works on IDE Arduino and I see the read values of temperature and pressure in the serial monitor. Instead I don't read nothing in log of B4R. In the display of Android Phone I see only the label "ESP8266 Weather"
 

Erel

Administrator
Staff member
Licensed User
Please start a new thread in the questions forum. You need to first be able to read the sensor value. Start with this code.
 
Top