diff --git a/bmp180/bmp180.go b/bmp180/bmp180.go index 4d48863..af93ee3 100644 --- a/bmp180/bmp180.go +++ b/bmp180/bmp180.go @@ -6,6 +6,7 @@ package bmp180 // import "tinygo.org/x/drivers/bmp180" import ( + "math" "time" "tinygo.org/x/drivers" @@ -123,6 +124,21 @@ func (d *Device) ReadPressure() (pressure int32, err error) { return 1000 * (p + ((x1 + x2 + 3791) >> 4)), nil } +// ReadAltitude returns the current altitude in meters based on the +// current barometric pressure and estimated pressure at sea level. +// Calculation is based on code from Adafruit BME280 library +// +// https://github.com/adafruit/Adafruit_BME280_Library +func (d *Device) ReadAltitude() (int32, error) { + mPa, err := d.ReadPressure() + if err != nil { + return 0, err + } + atmP := float32(mPa) / 100000 + + return int32(44330.0 * (1.0 - math.Pow(float64(atmP/SEALEVEL_PRESSURE), 0.1903))), nil +} + // rawTemp returns the sensor's raw values of the temperature func (d *Device) rawTemp() (int32, error) { d.bus.WriteRegister(uint8(d.Address), REG_CTRL, []byte{CMD_TEMP}) diff --git a/bmp180/registers.go b/bmp180/registers.go index e108ca1..fef2c5e 100644 --- a/bmp180/registers.go +++ b/bmp180/registers.go @@ -28,3 +28,7 @@ const ( // ULTRAHIGHRESOLUTION is the highest oversampling mode of the pressure measurement. ULTRAHIGHRESOLUTION ) + +const ( + SEALEVEL_PRESSURE float32 = 1013.25 // in hPa +) diff --git a/examples/bmp180/main.go b/examples/bmp180/main.go index 9b4e34d..b20e0a3 100644 --- a/examples/bmp180/main.go +++ b/examples/bmp180/main.go @@ -27,6 +27,9 @@ func main() { pressure, _ := sensor.ReadPressure() println("Pressure", float32(pressure)/100000, "hPa") + altitude, _ := sensor.ReadAltitude() + println("Altitude", altitude, "meters") + time.Sleep(2 * time.Second) } }