Arduino Sketch Read Accelerometer

This sketch is used by Exercise: Read Analog Accelerometer.

Full Source Code

The full code is all in one file ReadAccelerometer.ino.

// ReadAccelerometer - read a 3-axis analog accelerometer and display the results to the serial port
//
// Copyright (c) 2016, Garth Zeglin.  All rights reserved. Licensed under the
// terms of the BSD 3-clause license as included in LICENSE.
//
// This program assumes that:
//
//  1. A three-axis analog accelerometer such as an ADXL335 is attached to A0,
//     A1, and A2.  Note: this sensor has buffered voltage outputs and can
//     simply connect directly to the analog input pins.
//
//  2. The serial console on the Arduino IDE is set to 9600 baud communications speed.
//
// ================================================================================
// Configure the hardware once after booting up.  This runs once after pressing
// reset or powering up the board.

void setup()
{
  // Initialize the serial UART at 9600 bits per second.
  Serial.begin(9600);
}

// ================================================================================
// Run one iteration of the main event loop.  The Arduino system will call this
// function over and over forever.
void loop()
{
  // Read the accelerations as uncalibrated values.
  int x_raw = analogRead(0);
  int y_raw = analogRead(1);
  int z_raw = analogRead(2);

  // The following will rescale the values to be approximately in Earth gravity units.
  const int OFFSET = 335;
  const float SCALE = 0.013;

  float x = (x_raw - OFFSET) * SCALE;
  float y = (y_raw - OFFSET) * SCALE;
  float z = (z_raw - OFFSET) * SCALE;

  // Print the raw outputs.
  Serial.print("Raw: X: ");
  Serial.print(x_raw);
  Serial.print(" Y: ");
  Serial.print(y_raw);
  Serial.print(" Z: ");
  Serial.print(z_raw);
  
  // Print the calibrated outputs.
  Serial.print("  Calib: X: ");
  Serial.print(x);
  Serial.print(" Y: ");
  Serial.print(y);
  Serial.print(" Z: ");
  Serial.println(z);   // println appends an end-of-line character

  // Delay for a short interval to create a periodic sampling rate.
  delay(50);
}

Source: Arduino Sketch ReadAccelerometer


About The Author

Muhammad Bilal

I am a highly skilled and motivated individual with a Master's degree in Computer Science. I have extensive experience in technical writing and a deep understanding of SEO practices.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top