ESP8266-Arduino编程实例-MMA8452加速度计驱动

MMA8452加速度计驱动

1、MMA8452介绍

MMA8452Q 是一款智能、低功耗、三轴、电容式微加工加速度计,具有 12 位分辨率。 该加速度计具有嵌入式功能,具有灵活的用户可编程选项,可配置为两个中断引脚。 嵌入式中断功能可实现整体节能,从而使主机处理器免于连续轮询数据。

MMA8452Q 具有用户可选的 ±2 g/±4 g/±8 g 满量程,具有实时可用的高通滤波数据和非滤波数据。 该器件可配置为从可配置嵌入式功能的任意组合生成惯性唤醒中断信号,从而允许 MMA8452Q 监控事件并在不活动期间保持低功耗模式

在这里插入图片描述

2、硬件准备

  • ESP8266 NodeMCU开发板一块
  • MMA8452传感器模块一个
  • 面板板一个
  • 杜邦线若干
  • 数据线一条

硬件接线如下:

传感器引脚 ESP8266开发板引脚
Vin 5v
Gnd Gnd
SCL D1
SDA D2

3、软件准备

  • Arduino IDE或VSCode + PlatformIO

在前面的文章中,对如何搭建ESP8266开发环境做了详细的介绍,请参考:

ESP8266 NodeMCU的引脚介绍在前面的文章中做了详细的介绍,请参考:

4、代码实现

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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <Wire.h>

// MMA8452Q I2C address is 0x1C(28)
#define Addr 0x1C

void setup()
{
// Initialise I2C communication as MASTER
Wire.begin();
// Initialise Serial Communication, set baud rate = 9600
Serial.begin(9600);

// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select control register
Wire.write(0x2A);
// StandBy mode
Wire.write((byte)0x00);
// Stop I2C Transmission
Wire.endTransmission();

// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select control register
Wire.write(0x2A);
// Active mode
Wire.write(0x01);
// Stop I2C Transmission
Wire.endTransmission();

// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select control register
Wire.write(0x0E);
// Set range to +/- 2g
Wire.write((byte)0x00);
// Stop I2C Transmission
Wire.endTransmission();
delay(300);
}

void loop()
{
unsigned int data[7];

// Request 7 bytes of data
Wire.requestFrom(Addr, 7);

// Read 7 bytes of data
// staus, xAccl lsb, xAccl msb, yAccl lsb, yAccl msb, zAccl lsb, zAccl msb
if(Wire.available() == 7)
{
data[0] = Wire.read();
data[1] = Wire.read();
data[2] = Wire.read();
data[3] = Wire.read();
data[4] = Wire.read();
data[5] = Wire.read();
data[6] = Wire.read();
}

// Convert the data to 12-bits
int xAccl = ((data[1] \* 256) + data[2]) / 16;
if (xAccl > 2047)
{
xAccl -= 4096;
}

int yAccl = ((data[3] \* 256) + data[4]) / 16;
if (yAccl > 2047)
{
yAccl -= 4096;
}

int zAccl = ((data[5] \* 256) + data[6]) / 16;
if (zAccl > 2047)
{
zAccl -= 4096;
}

// Output data to serial monitor
Serial.print("Acceleration in X-Axis : ");
Serial.println(xAccl);
Serial.print("Acceleration in Y-Axis : ");
Serial.println(yAccl);
Serial.print("Acceleration in Z-Axis : ");
Serial.println(zAccl);
delay(500);
}

文章来源: https://iotsmart.blog.csdn.net/article/details/126770348