ReadAccelerometer Arduino Sketch

This sketch is used by Exercise: Read Analog Accelerometer.

Full Source Code

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

 1// ReadAccelerometer - read a 3-axis analog accelerometer and display the results to the serial port
 2//
 3// Copyright (c) 2016, Garth Zeglin.  All rights reserved. Licensed under the
 4// terms of the BSD 3-clause license as included in LICENSE.
 5//
 6// This program assumes that:
 7//
 8//  1. A three-axis analog accelerometer such as an ADXL335 is attached to A0,
 9//     A1, and A2.  Note: this sensor has buffered voltage outputs and can
10//     simply connect directly to the analog input pins.
11//
12//  2. The serial console on the Arduino IDE is set to 9600 baud communications speed.
13//
14// ================================================================================
15// Configure the hardware once after booting up.  This runs once after pressing
16// reset or powering up the board.
17
18void setup()
19{
20  // Initialize the serial UART at 9600 bits per second.
21  Serial.begin(9600);
22}
23
24// ================================================================================
25// Run one iteration of the main event loop.  The Arduino system will call this
26// function over and over forever.
27void loop()
28{
29  // Read the accelerations as uncalibrated values.
30  int x_raw = analogRead(0);
31  int y_raw = analogRead(1);
32  int z_raw = analogRead(2);
33
34  // The following will rescale the values to be approximately in Earth gravity units.
35  const int OFFSET = 335;
36  const float SCALE = 0.013;
37
38  float x = (x_raw - OFFSET) * SCALE;
39  float y = (y_raw - OFFSET) * SCALE;
40  float z = (z_raw - OFFSET) * SCALE;
41
42  // Print the raw outputs.
43  Serial.print("Raw: X: ");
44  Serial.print(x_raw);
45  Serial.print(" Y: ");
46  Serial.print(y_raw);
47  Serial.print(" Z: ");
48  Serial.print(z_raw);
49  
50  // Print the calibrated outputs.
51  Serial.print("  Calib: X: ");
52  Serial.print(x);
53  Serial.print(" Y: ");
54  Serial.print(y);
55  Serial.print(" Z: ");
56  Serial.println(z);   // println appends an end-of-line character
57
58  // Delay for a short interval to create a periodic sampling rate.
59  delay(50);
60}