7.4. ReadAccelerometer Arduino Sketch

This sketch is used by Exercise: Read Analog Accelerometer.

7.4.1. Full Source Code

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// 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);
}

Table Of Contents

Previous topic

7.3. ReadSwitchInput Arduino Sketch

Next topic

7.5. SensorFade Arduino Sketch