B4R Code Snippet HMC5883L interfacing with Wemos...

Dear All,
I was able to interface HMC5883L (Triple-axis Magnetometer (Compass)) with Wemos (ESP8266) with inline C. Here is the complete code. Hope it helps someone!
B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'Public variables can be accessed from all modules.
    Public Serial1 As Serial
    Public timer1 As Timer
    Public HEADING_DEGREES As Double
   
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Log("AppStart")
    RunNative("setup",Null)
    timer1.Initialize("timer1_Tick",1000)
    timer1.Enabled = True
 
End Sub

Private Sub Timer1_Tick
    RunNative("read",Null)
    Log(HEADING_DEGREES)
End Sub


#if C
#include <Wire.h>
#include <HMC5883L.h>
HMC5883L compass;

void setup(B4R::Object* o){
compass.begin();
compass.setRange(HMC5883L_RANGE_1_3GA);
compass.setMeasurementMode(HMC5883L_CONTINOUS);
compass.setDataRate(HMC5883L_DATARATE_30HZ);
compass.setSamples(HMC5883L_SAMPLES_8);
compass.setOffset(0, 0);
}
   
void read (B4R::Object* o) {
Vector norm = compass.readNormalize();
float heading = atan2(norm.YAxis, norm.XAxis);
float declinationAngle = -(0.0 + (21.0 / 60.0)) / (180 / M_PI);
  heading += declinationAngle;
  if (heading < 0)
  {
    heading += 2 * PI;
  }

  if (heading > 2 * PI)
  {
    heading -= 2 * PI;
  }

  float headingDegrees = heading * 180/M_PI;

   b4r_main::_heading_degrees = headingDegrees;
}

#End if
 

Attachments

  • Arduino-HMC5883L.zip
    2.9 KB · Views: 484

rbghongade

Active Member
Licensed User
Longtime User
Dear Derez,
I don't know how I missed it! Seems a more elegant solution than the one posted by me!
regards,
 
Top