Raspberry pi code for LMS303 get mag.magnetic x,y,z (PYTHON3)

204 Views Asked by At

i am currently doing a project with a raspberry pi 3b+ and some sensors. One of the sensors is adafruit LMS303 Triple-axis Accelerometer+Magnetometer (Compass), i tried doing some basic example codes and everything works fine. What am i trying to do now is to take the values from mag.magnetic and extract the x,y,z value and use them as a digital compass.

from time import sleep
import board
import busio
import adafruit_lsm303_accel
import adafruit_lsm303dlh_mag
import time
import math

i2c = busio.I2C(board.SCL, board.SDA)
time.sleep(1) #tiempo para que alcance a detectar el sensor
mag = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c)
accel = adafruit_lsm303_accel.LSM303_Accel(i2c)
pi = 3.14159
while True:
    print("Acceleration (m/s^2): X=%0.3f Y=%0.3f Z=%0.3f"%accel.acceleration)
    heading=(math.atan2(mag.magnetic.y,mag.magnetic.x)*180)/pi

    if heading <0:
      heading=360+heading
    print("Magnetometer (micro-Teslas)): X=%0.3f Y=%0.3f Z=%0.3f"%mag.magnetic)
    print("Heading: %7.2f"%heading)

    sleep(0.5)

The code is not working because mag.magnetic.x and mag.magnetic.y does not exist (is not the correct way to extract those values). ¿Can someone point out what could be the correct way to extract mag.magnetic.x and mag.magnetic.y?

1

There are 1 best solutions below

4
On

I solve it, i noticed that mag.magnetic was a tuple, so i just add [] to the end of it:

from time import sleep
import board
import busio
import adafruit_lsm303_accel
import adafruit_lsm303dlh_mag
import time
import math

i2c = busio.I2C(board.SCL, board.SDA)
time.sleep(1) #tiempo para que alcance a detectar el sensor
mag = adafruit_lsm303dlh_mag.LSM303DLH_Mag(i2c)
accel = adafruit_lsm303_accel.LSM303_Accel(i2c)
offset=65
pi = 3.14159

while True:
   # print("Acceleration (m/s^2): X=%0.3f Y=%0.3f Z=%0.3f"%accel.acceleration)
    x=mag.magnetic[0]
    y=mag.magnetic[1]
    heading=(math.atan2(x,y)*180)/pi
    heading=heading-offset
    if heading <0:
      heading=360+heading
   # print("Magnetometer (micro-Teslas)): X=%0.3f Y=%0.3f Z=%0.3f"%mag.magnetic)
    print("Heading: %7.2f"%heading)
    print(" ")

    sleep(0.5)