I am trying to write a driver for the ADXL375 accelerometer (https://www.digikey.com/product-detail/ ... ND/4376342) using SPI. I am using Micropython version 1.9.3. I started by writing a simple memory reading function as shown below:
Code: Select all
import micropython import pyb from machine import SPI # Create pin bojects MOSI = pyb.Pin(pyb.Pin.cpu.A7, mode=pyb.Pin.ALT, af = pyb.Pin.AF5_SPI1, pull=pyb.Pin.PULL_UP) MISO = pyb.Pin(pyb.Pin.cpu.A6, mode=pyb.Pin.ALT, af = pyb.Pin.AF5_SPI1, pull=pyb.Pin.PULL_UP) SCK = pyb.Pin(pyb.Pin.cpu.A5, mode=pyb.Pin.ALT, af = pyb.Pin.AF5_SPI1) CS = pyb.Pin(pyb.Pin.cpu.C5, pyb.Pin.OUT) CS.high() spi_1 = SPI(1, baudrate=1000000, polarity=1, phase=1, bits=8, firstbit=SPI.MSB) READ_MASK = micropython.const(0b10000000) buf = bytearray(2) def mem_read(mem_addr): '''This function returns the data stored in the memory address @param mem_addr. ''' # Sets proper bit in order to read data buf = (mem_addr | READ_MASK) CS.low() spi_1.write_readinto(buf, buf) CS.high()
I have then called the mem_read() function from a REPL and tried reading address 0x00 (the address where the device ID is stored). However, after reading this address, the second byte of 'buf' simply contains the value 255. According to the data sheet, the device ID should be 0b11100101 (229 in decimal). When I placed an oscilloscope probe on the MISO line it shows 0b11100101 perfectly.
To keep testing things I tried changing the polarity and phase. When the polarity and phase are both set to 0, 'buf' contains 0b11110010 (242 decimal) after trying to read address 0x00. This matches what is seen on the oscilloscope. This makes sense, for the incorrect polarity and phase offset the clock line and make it read an extra 1. When viewed from the oscilloscope the entirety of the proper data is still there (0b11100101).
So in summary, I am not sure why the proper value is not stored when using the proper polarity and phase, and why when it is changed I am actually able to store a value (albeit the wrong one) in 'buf'. I have tried a couple different boards running micropython (a custom board and a Nucleo L476RG) and I get the same results. The fact that the oscilloscope shows the correct data on the MISO line makes me thing that I have the accelerometer wired up properly. Therefore my thinking is that it must be something with the code.
Any thoughts or ideas are much appreciated!