ADXL3xx

はじめに

ADXL3xx加速度センサから情報を取得し、シリアルポートに送信します。

アナログ0番から5番まで順に、自己診断、z軸、y軸、x軸、アース、Vccを接続します。

プログラム

定義等

 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
/*
  ADXL3xx

  Reads an Analog Devices ADXL3xx accelerometer and communicates the
  acceleration to the computer. The pins used are designed to be easily
  compatible with the breakout boards from SparkFun, available from:
  https://www.sparkfun.com/categories/80

  The circuit:
  - analog 0: accelerometer self test
  - analog 1: z-axis
  - analog 2: y-axis
  - analog 3: x-axis
  - analog 4: ground
  - analog 5: vcc

  created 2 Jul 2008
  by David A. Mellis
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/ADXL3xx
*/

// these constants describe the pins. They won't change:
const int groundpin = 18;             // analog input pin 4 -- ground
const int powerpin = 19;              // analog input pin 5 -- voltage
const int xpin = A3;                  // x-axis of the accelerometer
const int ypin = A2;                  // y-axis
const int zpin = A1;                  // z-axis (only on 3-axis models)
 

const int型の変数groundpin、powerpin、xpin、ypin、zpinを定義し、初期化します。18と19は、それぞれ、A4とA5と書いても同じです。

setup()

34
35
36
37
38
39
40
41
42
43
44
45
46
47
void setup() {
  // initialize the serial communications:
  Serial.begin(9600);

  // Provide ground and power by using the analog inputs as normal digital pins.
  // This makes it possible to directly connect the breakout board to the
  // Arduino. If you use the normal 5V and GND pins on the Arduino,
  // you can remove these lines.
  pinMode(groundpin, OUTPUT);
  pinMode(powerpin, OUTPUT);
  digitalWrite(groundpin, LOW);
  digitalWrite(powerpin, HIGH);
}
 

Serial.begin()でシリアルポートを初期化します。

pinMode()を使い、groundpinとpowerpinを出力モードにし、digitalWrite()を使って、groundpinをLOWに、powerpinをHIGHに設定します。アナログピンをデジタルピンとして利用しています。

loop()

48
49
50
51
52
53
54
55
56
57
58
59
60
void loop() {
  // print the sensor values:
  Serial.print(analogRead(xpin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(ypin));
  // print a tab between values:
  Serial.print("\t");
  Serial.print(analogRead(zpin));
  Serial.println();
  // delay before next reading:
  delay(100);
}

xpin、ypin、zpinからanalogRead()を使い読み取った値をSerial.print()を使ってシリアルポートに送信します。また、最後に、Serial.println()を使って改行文字を送信します。

最後にdelay()を使い、しばらく待ちます。

バージョン

Hardware:Arduino Uno
Software:Arduino 1.8.16

最終更新日

November 1, 2022

inserted by FC2 system