Arrow / Mbed OS sensors-example

Dependencies:   TMP06 FXPQ3115 ADXL345_I2C

Revision:
0:01fccb06cd7c
diff -r 000000000000 -r 01fccb06cd7c main.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Mar 05 13:22:41 2020 +0100
@@ -0,0 +1,101 @@
+#include "mbed.h"
+#include <ADXL345_I2C.h>
+#include <TMP06.h>
+#include <FXPQ3115.h>
+
+#define LOW  0
+#define HIGH 1
+
+#define SUCCESS 0
+#define ERROR   1
+
+// Accelerometer
+ADXL345_I2C acc_sensor(P0_13, P0_14); // I2C_0 pins
+DigitalOut cs_pin(P0_21); // Need to be high during communication
+
+// Temperature
+TMP06 temp_sensor(P0_1);
+float temperature;
+
+// Pressure
+FXPQ3115 pres_sensor(P0_13, P0_14);
+
+/* Accelerometer methods */
+int setup_i2c_acc()
+{
+    cs_pin = HIGH;
+    printf("Device ID is: 0x%02x\n", acc_sensor.getDeviceID());
+    thread_sleep_for(10);
+
+    if (acc_sensor.setPowerControl(0x00)) {
+         printf("didn't intitialize power control\n"); 
+         return ERROR; 
+    }
+    thread_sleep_for(10);
+    
+    // Full resolution, +/-16g, 4mg/LSB
+    if(acc_sensor.setDataFormatControl(0x0B)){
+        printf("didn't set data format\n");
+        return ERROR;  
+    }
+    thread_sleep_for(10);
+
+    // 3.2kHz data rate
+    if(acc_sensor.setDataRate(ADXL345_3200HZ)){
+        printf("didn't set data rate\n");
+        return ERROR;    
+    }
+    thread_sleep_for(10);
+
+    // Measurement mode
+    if(acc_sensor.setPowerControl(MeasurementMode)) {
+        printf("didn't set the power control to measurement\n"); 
+        return ERROR;   
+    } 
+    thread_sleep_for(10);
+    cs_pin = LOW;
+    
+    return SUCCESS;
+}
+
+void i2c_acc_print_xyz(void)
+{
+    int readings[3] = {0, 0, 0};
+    cs_pin = HIGH;
+    acc_sensor.getOutput(readings);
+    cs_pin = LOW;
+    printf("Accelerometer: x:%.02f y:%.02f z:%.02f\r\n", (int16_t)readings[0]*0.004, (int16_t)readings[1]*0.004, 
+                    (int16_t)readings[2]*0.004);
+}
+
+int main()
+{
+    if (setup_i2c_acc() != SUCCESS) {
+        printf("Error while initializing accelerometer\r\n");
+        return ERROR;
+    }
+
+    if (pres_sensor.sensor_init() == SUCCESS) {
+        printf("Pressure sensor is up!\r\n");
+    }
+    else {
+        printf("Error while initializing barometer\r\n");
+        return ERROR;
+    }
+    
+    while (true) {
+        /* Read Accelerometer */
+        i2c_acc_print_xyz();
+        /* Read Temperature */
+        if (temp_sensor.read(&temperature) == SUCCESS) {
+            printf("Temperature: %.01f C\n", temperature);
+        }
+        /* Read Pressure */
+        if (pres_sensor.read_oneshotMode_bar() == SUCCESS) {
+            printf("Pressure in Pascals: %d hPa\n", pres_sensor.print_pressure()/100);
+        }
+        printf("\n");
+        thread_sleep_for(5000);
+    }
+}
+