TMAG5237 incorrect measurement

Hello,

I am using TMAG5273 sensor to measure magnetic field. I use it with ESP32-C6 and ESP-IDF in VScode. My problem is, that results is a one random value which doesn’t change or 0. I think it is an issue with sensor configuration, however I don’t see what lacks.

I attach my code:

#include “tmag5273.h”

#include <stdlib.h>

#include “math.h”

#include “freertos/FreeRTOS.h”

#include “freertos/task.h”

#include “driver/i2c_master.h”

#define TMAG_RANGE

#define I2C_SDA 22

#define I2C_SCL 23

#define PORT_NUM I2C_NUM_0

#define I2C_FREQ 100000

const float scale = 40.0f / 32768.0f;

i2c_master_bus_handle_t bus_handle;

i2c_master_dev_handle_t dev_handle;

void tmag5273_init(void)

{

i2c_master_bus_config_t i2c_mst_config = {

    .clk_source = I2C_CLK_SRC_DEFAULT,

    .i2c_port = PORT_NUM,

    .scl_io_num = I2C_SCL,

    .sda_io_num = I2C_SDA,

    .glitch_ignore_cnt = 7,

    .flags.enable_internal_pullup = true,

};

ESP_ERROR_CHECK(i2c_new_master_bus(&i2c_mst_config, &bus_handle));



i2c_device_config_t dev_cfg = {

.dev_addr_length = I2C_ADDR_BIT_LEN_7,

.device_address = 0x22,

.scl_speed_hz = I2C_FREQ,

};

ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));

}

void tmag5273_measure_magneticField(tmag5273_measurement_t *result)

{

uint8_t reg = {0x12};  

uint8_t data\[6\];

ESP_ERROR_CHECK(i2c_master_transmit_receive(dev_handle, &reg, 1, data, 6, -1));

//ESP_ERROR_CHECK(i2c_master_receive(dev_handle, data, 6, -1));

int16_t x = (int16_t)((data\[0\] << 8) | data\[1\]);

int16_t y = (int16_t)((data\[2\] << 8) | data\[3\]);

int16_t z = (int16_t)((data\[4\] << 8) | data\[5\]);

printf("%02X %02X %02X %02X %02X %02X\\n",

   data\[0\], data\[1\], data\[2\],

   data\[3\], data\[4\], data\[5\]);

float Bx = x \* scale;

float By = y \* scale;

float Bz = z \* scale;

result->Bx = Bx;

result->By = By;

result->Bz = Bz;

result->magneticField = (float)sqrt(Bx \* Bx + By \* By + Bz \* Bz);

}

I will be grateful for any advice.

Hi @Mikee ,

The TMAG5273 has one of four possible I2C addresses, depending on which version it is:

Have you checked your device_address = 0x22 is correct for your device?

Perhaps you need to set the MAG into continuous measure mode? The device defaults to Stand-by mode (the two DEVICE_CONFIG_2 OPERATING_MODE bits default to 0 = Stand-by mode). You may need to replicate this start-up code from the SparkFun library?

I hope this helps,
Paul

What about the connection?