Why is my magnometer readings not getting updated

109 views Asked by At

Im currently working on a project that uses raspberry pico pi on pico visual studio and I am trying to get my magnometer (GY-511) readings (x, y, z) but it is not updating. Does anyone know what is the issue? This is my current code

#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"

// Define I2C configuration
#define I2C_PORT i2c0
#define I2C_SDA 0
#define I2C_SCL 1
#define MAGNETOMETER_ADDR 0x1E  // Magnometer Address

int main() {
    stdio_init_all();


    i2c_init(I2C_PORT, 100000);  // Initialize I2C with a speed of 100 kHz
    i2c_set_slave_mode(I2C_PORT, false, MAGNETOMETER_ADDR);

    sleep_ms(1000);
    
    // Set pull-up resistors for the I2C pins
    gpio_set_pulls(I2C_SDA, true, false);  // Set SDA with pull-up
    gpio_set_pulls(I2C_SCL, true, false);  // Set SCL with pull-up
    
    i2c_set_baudrate(I2C_PORT, 100000);
    gpio_set_function(I2C_SDA, GPIO_FUNC_I2C);
    gpio_set_function(I2C_SCL, GPIO_FUNC_I2C);

    uint8_t data[6];  // Data buffer for X, Y, Z values
    uint8_t reg = 0x03;  // Register address for X MSB (0x03)

    while (1) {
        // Read data from the magnetometer
        i2c_write_blocking(I2C_PORT, MAGNETOMETER_ADDR, &reg, 1, false);

        int result = i2c_read_blocking(I2C_PORT, MAGNETOMETER_ADDR, data, 6, false);
        if (result == PICO_ERROR_GENERIC) {
            printf("I2C read error\n");
            continue;
        }

        int16_t x = (data[0] << 8) | data[1];
        int16_t y = (data[4] << 8) | data[5];
        int16_t z = (data[2] << 8) | data[3];

        printf("X: %d, Y: %d, Z: %d\n", x, y, z);
        
        // Adjust the refresh rate as needed
        sleep_ms(200);  // Refresh every 1 second
    }

    return 0;
}

Output

X: 277, Y: -77, Z: 139
X: 277, Y: -77, Z: 139
X: 277, Y: -77, Z: 139
0

There are 0 answers