Hello world for Kionix KX123 accelerometer sensor. This example application uses kionix-kx123-driver -library to communicate with sensor via i2c-bus. Acceleration values are read for 3 axis and maximum and minimum values for X-axis is printed out when new max/min is reached. Code includes re-connection logic to ease up HW connection debugging.
Dependencies: RegisterWriter kionix-kx123-driver
main.cpp
- Committer:
- MikkoZ
- Date:
- 2016-10-06
- Revision:
- 2:7fe25750b23d
- Parent:
- 0:bb054fb43c57
File content as of revision 2:7fe25750b23d:
/* Copyright 2016 Rohm Semiconductor Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "RegisterWriter/RegisterWriter/rohm_hal2.h" #include "kionix-kx123-driver/kx123_registers.h" #include "kionix-kx123-driver/kx123.h" DigitalOut led1(LED1); DigitalOut led2(LED2); Serial pc(USBTX, USBRX); I2C i2c(I2C_SDA, I2C_SCL); RegisterWriter i2c_rw(i2c); int main() { bool error; KX123 acc(i2c_rw); float xmax = 0, xmin = 0; do{ //init error = acc.set_defaults(); Thread::wait(50); led1 = !led1; //Red led toggle Thread::wait(200); } while (error); led1 = 0; //Red off while (true) { float res[3]; Thread::wait(50); error = acc.getresults_g(&res[0]); if (error){ led2 = 0; //Green off led1 = 1; //Red on xmax = 0; xmin = 0; pc.printf("Reattach sensor. Note that if reconnecting also sensor config pins\r\n"); pc.printf("(f.ex. SPI/I2C selection) connection should be made in correct pin order.\r\n"); while (error){ error = acc.set_defaults(); led1 = !led1; //Red off Thread::wait(100); } led1 = 0; //Red off continue; //loop again if read failed } //else no error, printout values //pc.printf("X[%0.2f], Y[%0.2f], Z[%0.2f]\r\n", res[0], res[1], res[2]); if (xmax < res[0]){ xmax = res[0]; pc.printf("Xmax[%0.2f], Xmin[%0.2f]\r\n", xmax, xmin); } if (xmin > res[0]){ xmin = res[0]; pc.printf("Xmax[%0.2f], Xmin[%0.2f]\r\n", xmax, xmin); } led2 = !led2; //Toggle green after each successfull read } }