0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ESP32: 加速度センサーの値を読む

Posted at

こちらのページを参考にしました。
ESP32で加速度センサの値に応じてモータ制御

プログラム

get_accel.ino
// ---------------------------------------------------------------------
//	get_accel.ino
//
//					Nov/19/2022
// ---------------------------------------------------------------------
#include <Wire.h>
#include <Arduino.h>

// デバイスアドレス(スレーブ)
uint8_t DEVICE_ADDRESS = 0x53;  

// XYZレジスタ用のテーブル(6byte)
uint8_t RegTbl[6];  

void getAccelerationData();

/* 使うピンの定義 */
const int IN1 = 25;
const int IN2 = 26;

/* チャンネルの定義 */
const int CHANNEL_0 = 0;
const int CHANNEL_1 = 1;

// ---------------------------------------------------------------------
void setup() {
	Serial.begin(115200); 

	Serial.println("*** setup start ***");

	// マスタとしてI2Cバスに接続する
	Wire.begin();			 
	// DATA_FORMAT(データ形式の制御) 
	Wire.beginTransmission(DEVICE_ADDRESS);	
		// DATA_FORMATのアドレス		
	Wire.write(0x31);
		// 「最大分解能モード」 及び 「±16g」 (0x0B == 1011)
	Wire.write(0x0B);	
		// 「10bit固定分解能モード」 及び 「±16g」にする場合 (0x03 == 0011)
		// Wire.write(0x03);
	Wire.endTransmission();

	Serial.println("*** setup ddd ***");
}

// ---------------------------------------------------------------------
void loop() {
//	Serial.println("*** loop ***");

	getAccelerationData();

	// データを各XYZの値に変換する(LSB単位)
	int16_t x = (((int16_t)RegTbl[1]) << 8) | RegTbl[0];
	int16_t y = (((int16_t)RegTbl[3]) << 8) | RegTbl[2];
	int16_t z = (((int16_t)RegTbl[5]) << 8) | RegTbl[4];	


	// 各XYZ軸の加速度(m/s^2)を出力する
	Serial.print("X : ");
	Serial.print( x * 0.0392266 );
	Serial.print(" Y : ");
	Serial.print( y * 0.0392266 );
	Serial.print(" Z : ");
	Serial.print( z * 0.0392266 );
	Serial.println(" m/s^2");

	delay(3000);
}

// ---------------------------------------------------------------------
//加速度データ取得
void getAccelerationData(){
	// XYZの先頭アドレスに移動する
	Wire.beginTransmission(DEVICE_ADDRESS);
		Wire.write(0x32);
	Wire.endTransmission();

	// デバイスへ6byteのレジスタデータを要求する
	Wire.requestFrom(DEVICE_ADDRESS, 6);

	// 6byteのデータを取得する
	int i;
	for (i=0; i< 6; i++){
		while (Wire.available() == 0 ){}
		RegTbl[i] = Wire.read();
	}

}

// ---------------------------------------------------------------------
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?