I am totally new to the field, don't really know what I'm doing and in need of help. I'm trying to read an absolute angle using an MT6816 14-bit magnetic encoder via SPI connection using Python on Raspberry Pi.

I have the following question:

  1. On the hardware side, is it simply just wiring up the necessary connections (3.3V, MOSI, MISO, SCK, GND, CE0)?
  2. For the coding part, I'm using Thonny and it seems like spidev library is pre-installed as the 'Raspberry Pi SPI loopback test code'(https://gist.github.com/fnishio/b2063941b82f2cf1b935) ran without any error. Thus, I assumed no other setup is needed other that enabling SPI in raspi-config. Am I right? Or are there ways to test if SPI connection works?
  3. To my understanding according to the MT6816 datasheet(https://www.compel.ru/item-pdf/c51a62edcf72a97fdb3c3d9108c3c3d5/pn/magntek~mt6816ct-std.pdf : page 23), what I need (i.e. the 14-bit angle data) is stored in the register addresses 0x03 and 0x04[7:2]. I have no idea how to access into said addresses and read those values.

I wired up the 6 wires and played around with the code(again didn't really know what I was doing). I moved the magnet around the sensor expecting swinging range of values, the output just seems to randomly cycle through 0.00, 179.27, 269.27, and 359.27.

Here's my code so far:

import spidev
import time

# Function to read data from MT6816 magnetic encoder
def read_mt6816():
    # Initialize SPI
    spi = spidev.Spidev()
    spi.open(0, 0)  # Open SPI port 0, device 0
    spi.threewire = False
    spi.mode = 0b11  # Set SPI mode

    tx_data1 = [0x03, 0x00]
    rx_data1 = spi.xfer2(tx_data1)
    tx_data2 = [0x04, 0x00]
    rx_data2 = spi.xfer2(tx_data2)

    angle = (rx_data[1] << 6) | (rx_data2[1] >> 2)
    angle_degrees = (angle * 360) / 16384


    return angle_degrees

    while True:
        angle = read_mt6816()
        print("Angle: {:.2f} degrees".format(angle))
except KeyboardInterrupt:
    print("Program terminated by user.")

I'll appreciate any help you can offer.

  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
    – Community Bot
    Commented Apr 22 at 17:27


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.