Thanks for the reply,
I was able, after some coding with some AI, and some minor corrections from my side, to use the Pin(“SW”) switch, to create a small portion of code that allows the calibration of the accelerometer, after the board is placed on a flat surface, with the Z+ pointing downwards. I was able to calibrate the sensor
This is here I have another question, when this sensor is calibrated, the Z axis is reading almost 2g in one direction, so, to prevent confusion, if the +Z axis is pointing UP to the sky, it should have a value of +1g, meaning is working normal, I was unable to achieve this with a reset to zero of the accelerometer, and I had to apply a correction or bias correction to the sensor, is this normal???
I know the sensor is low cost, but, just wanted to understand if this is normal behavior on the board. ANYWAYS, here is my portion of the code that make this possible, this is just a routine to calibrate the sensor and make the BIAS Correction, after this is applied the sensor now reads close to +1G when Z+ is pointing up, and -1G when Z+ is pointing downwards.
# Accelerometer - By: Dennis Bujan - Mon Mar 17 2025
import machine, time
bus = machine.I2C(2) #Ensure is on the proper bus
# Detects devices on the I2C Bus
devices = bus.scan()
if not devices:
print("Sensor not found on the I2C Bus.")
else:
print(f"Device Detected: {devices}")
if 0x15 not in devices:
print("⚠️ Warning: Sensor not detected on the address 0x15.")
else:
print("✅ Sensor detected correctly on address 0x15.")
def calibrate(): # Takes 500 samples to calibrate
samples = 500
sum_x, sum_y, sum_z = 0, 0, 0
print("Calibrating... Keep sensor stable and do not move it!!!")
for _ in range(samples):
d = bus.readfrom_mem(0x15, 0x03, 7)
z = ((d[4] << 8) | d[5]) >> 4
if z & 0x800: z -= 3048
sum_z += z
time.sleep_ms(1) # Pause between readings
bias_z = sum_z / samples # Average BIAS on Z axis
print(f"Calibration completed. Bias Z: {bias_z:.2f}")
return bias_z
bias_z = calibrate() # Get Z correction on Z axis
# Function to read and make correction to the accelerometer
def read_accel():
d = bus.readfrom_mem(0x15, 0x03, 7)
z = ((d[4] << 8) | d[5]) >> 4
if z & 0x800: z -= 4096
z = (z - bias_z) / 1024.0 # Apply correction
print(f"Z corrected: {z:.2f}g")
while True:
read_accel()
time.sleep(1)