In this section we are going to calibrate the sensor and detect the analog voltage value corresponding to 1G and -1G for the x,y and z axes.
Calibration
The values we have obtained in the previous section were variables proportional to the actual acceleration measured by the sensor. We will use gravity as a reliable calibration reference.
The units of acceleration is
In order to determine the sensor output when it is precisely aligned with the axis of gravitational pull, we will repeat the following step for each axis.
- Place the sensor with the X axis oriented upward and press ‘xm’. The analog value will be saved.
- Place the sensor with the X axis oriented downward and press ‘xM’.
- Place the sensor with the Y axis oriented upward and press ‘ym’.
- Place the sensor with the Y axis oriented downward and press ‘yM’.
- Place the sensor with the Z axis oriented upward and press ‘zm’.
- Place the sensor with the Z axis oriented downward and press ‘zM’.
- Press ‘v’ to show the Min and max values for each axes.
We will discuss the main functions of this sketch. Let’s have a look at the code.
Scaling raw values
The analog values are read from 3 analog pins on the Arduino board. The Analog to Digital Converter has a resolution of 0.049 Volts/Unit. It maps input voltages between 0 and 5 volts into values between 0 and 1023. Let’s create a scaleAccs() function that maps the analog values to the corresponding number of G.
float xScaled = map(xRead, xRawMin, xRawMax, -1000, 1000); float yScaled = map(yRead, yRawMin, yRawMax, -1000, 1000); float zScaled = map(zRead, zRawMin, zRawMax, -1000, 1000);
Calibrating the sensor
We can control our program using the serial interface. We would like to store the raw value when the sensor measures one G of acceleration. Using the Serial.read() function we can associate actions to key pressed. The following code reads the char in the serial buffer and saves the current analog value received from the sensor to a variable that will be used for calibration purposes.
if (Serial.available()) { char t = Serial.read(); Serial.println(t); if (t == 'x') { char sec = Serial.read(); if (sec == 'm') { xRawMin = xRead; } else if (sec == 'M') { xRawMax = xRead; } } }
Complete Arduino code
As before we need some code that reads the analog values from the sensor. Then a Serial routine will wait for the right combination of keys to be pressed to store the reference values used for the calibration. And finally the scale function will be called to convert the raw values to acceleration ones.