B4R Tutorial ESP8266 + UDP + BMP180 = Simple weather station

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.

SS-2016-08-22_11.20.22.jpg


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

  • B4R_Weather.zip
    1.1 KB · Views: 1,583
  • B4J_Weather.zip
    981 bytes · Views: 994
  • B4A_Weather.zip
    7.8 KB · Views: 1,564
  • B4i_Weather.zip
    2.3 KB · Views: 730

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
 

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"
 
Top