ISSDK  1.7
IoT Sensing Software Development Kit
main_freertos_agm02_power_cycling.c
Go to the documentation of this file.
1 /*
2  * The Clear BSD License
3  * Copyright (c) 2015 - 2016, Freescale Semiconductor, Inc.
4  * Copyright 2016-2017 NXP
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without modification,
8  * are permitted (subject to the limitations in the disclaimer below) provided
9  * that the following conditions are met:
10  *
11  * o Redistributions of source code must retain the above copyright notice, this list
12  * of conditions and the following disclaimer.
13  *
14  * o Redistributions in binary form must reproduce the above copyright notice, this
15  * list of conditions and the following disclaimer in the documentation and/or
16  * other materials provided with the distribution.
17  *
18  * o Neither the name of the copyright holder nor the names of its
19  * contributors may be used to endorse or promote products derived from this
20  * software without specific prior written permission.
21  *
22  * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE.
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26  * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
27  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
28  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
30  * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
32  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 /*! \file main_freertos_agm02_power_cycling.c
36  \brief FreeRTOS (two task) implementation of sensor fusion on FRDM-K64F/FRDM-FXS-AGM02 with smart power-cycling support.
37 
38  This file shows one recommended way to incorporate sensor fusion capabilities
39  into a FreeRTOS project AND adds intelligent power down of sensors when
40  the DUT is stationary.
41 */
42 
43 /* FreeRTOS kernel includes. */
44 #include "FreeRTOS.h"
45 #include "task.h"
46 #include "queue.h"
47 #include "timers.h"
48 #include "event_groups.h"
49 
50 // KSDK and ISSDK Headers
51 #include "fsl_debug_console.h" // KSDK header file for the debug interface
52 #include "FSL_SMC.H" // KDSK header file for the System Mode Controller Driver
53 #include "board.h" // KSDK header file to define board configuration
54 #include "pin_mux.h" // KSDK header file for pin mux initialization functions
55 #include "clock_config.h" // KSDK header file for clock configuration
56 #include "fsl_port.h" // KSDK header file for Port I/O control
57 #include "fsl_i2c.h" // KSDK header file for I2C interfaces
58 #include "register_io_i2c.h"
59 #include "fsl_i2c_cmsis.h"
60 #include "fsl_dspi_cmsis.h"
61 
62 // Sensor Fusion Headers
63 #include "sensor_fusion.h" // top level magCal and sensor fusion interfaces
64 #include "control.h" // Command/Streaming interface - application specific
65 #include "status.h" // Status indicator interface - application specific
66 #include "drivers.h" // NXP sensor drivers OR customer-supplied drivers
67 #include "fusion.h" // Need lower level function for power management
68 
71  .functionParam = NULL,
72  .idleFunction = NULL
73 };
74 
75 // Global data structures
76 SensorFusionGlobals sfg; ///< This is the primary sensor fusion data structure
77 ControlSubsystem controlSubsystem; ///< used for serial communications
78 StatusSubsystem statusSubsystem; ///< provides visual (usually LED) status indicator
79 struct PhysicalSensor sensors[3]; ///< This implementation uses three physical sensors
80 EventGroupHandle_t event_group = NULL;
82 {
83  // MCU low power modes are not debugged at this point in time
84  //volatile smc_power_state_t state;
85  //SMC_SetPowerModeStop(SMC, kSMC_PartialStop );
86  //state = SMC_GetPowerModeState(SMC);
87  //asm("wfi");
88 }
90 {
91  sfg.queueStatus(&sfg, NORMAL); // assume NORMAL status for next pass through the loop
92 }
93 
94 static void read_task(void *pvParameters);
95 static void fusion_task(void *pvParameters);
96 bool motionCheck( float sample[3],
97  float baseline[3],
98  float tolerance,
99  uint32_t winLength,
100  uint32_t *count); // defined in motionCheck.c
101 /// This is a FreeRTOS (dual task) implementation of the NXP sensor fusion demo build.
102 int main(void)
103 {
104  ARM_DRIVER_I2C* I2Cdrv = &I2C_S_DRIVER; // defined in the <shield>.h file
105  BOARD_InitPins(); // defined in pin_mux.c, initializes pkg pins
106  BOARD_BootClockRUN(); // defined in clock_config.c, initializes clocks
107  BOARD_InitDebugConsole(); // defined in board.c, initializes the OpenSDA port
108 
109  I2Cdrv->Initialize(I2C_S_SIGNAL_EVENT); // Initialize the KSDK driver for the I2C port
110  I2Cdrv->PowerControl(ARM_POWER_FULL); // Set the I2C Power mode.
111  I2Cdrv->Control(ARM_I2C_BUS_SPEED, ARM_I2C_BUS_SPEED_FAST); // Configure the I2C bus speed
112 
113  initializeControlPort(&controlSubsystem); // configure pins and ports for the control sub-system
114  initializeStatusSubsystem(&statusSubsystem); // configure pins and ports for the status sub-system
115  initSensorFusionGlobals(&sfg, &statusSubsystem, &controlSubsystem); // Initialize sensor fusion structures
116  // "install" the sensors we will be using
117  sfg.installSensor(&sfg, &sensors[0], FXLS8952C_I2C_ADDR, 1, (void*) I2Cdrv, &i2cBusInfo, FXLS8952_Init, FXLS8952_Read);
118  sfg.installSensor(&sfg, &sensors[1], FXAS21002_I2C_ADDR, 1, (void*) I2Cdrv, &i2cBusInfo, FXAS21002_Init, FXAS21002_Read);
119  sfg.installSensor(&sfg, &sensors[2], MAG3110_I2C_ADDR, 1, (void*) I2Cdrv, &i2cBusInfo, MAG3110_Init, MAG3110_Read);
120  sfg.initializeFusionEngine(&sfg); // This will initialize sensors and magnetic calibration
121 
122  event_group = xEventGroupCreate();
123  xTaskCreate(read_task, "READ", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 2, NULL);
124  xTaskCreate(fusion_task, "FUSION", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, NULL);
125 
126  sfg.setStatus(&sfg, NORMAL); // If we got this far, let's set status state to NORMAL
127  vTaskStartScheduler(); // Start the RTOS scheduler
128  sfg.setStatus(&sfg, HARD_FAULT); // If we got this far, FreeRTOS does not have enough memory allocated
129  for (;;) ;
130 }
131 
132 static void read_task(void *pvParameters)
133 {
134  uint16_t i=0; // general counter variable
135  portTickType lastWakeTime;
136  const portTickType frequency = 1; // tick counter runs at the read rate
137  lastWakeTime = xTaskGetTickCount();
138  while (1)
139  {
140  for (i=1; i<=OVERSAMPLE_RATE; i++) {
141  vTaskDelayUntil(&lastWakeTime, frequency);
142  sfg.readSensors(&sfg, i); // Reads sensors, applies HAL and does averaging (if applicable)
143  }
144  xEventGroupSetBits(event_group, B0);
145  }
146 }
147 
148 static void fusion_task(void *pvParameters)
149 {
150  uint16_t i=0; // general counter variable
151  float motion_baseline[3] = {0.0, 0.0, 0.0};
152  bool stationary;
153  static bool lastStationary;
154  uint32_t stationaryCount = 0;
155  while (1)
156  {
157  xEventGroupWaitBits(event_group, /* The event group handle. */
158  B0, /* The bit pattern the event group is waiting for. */
159  pdTRUE, /* BIT_0 and BIT_4 will be cleared automatically. */
160  pdFALSE, /* Don't wait for both bits, either bit unblock task. */
161  portMAX_DELAY); /* Block indefinitely to wait for the condition to be met. */
162 
163  // sfg.runFusion(&sfg); // Run the actual fusion algorithms
164  // Rather than call runFusion directly, this example invokes the lower level
165  // calls here. This allows us to check to see if the board is stationary,
166  // and if so, transition to a lower power state.
167  sfg.conditionSensorReadings(&sfg); // magCal is run as part of this
168  stationary = motionCheck(
169  sfg.Accel.fGc, // calibrated accelerometer reading
170  motion_baseline, // baseline to check new values against
171  0.01, // changes less than this are ignored
172  120, // three seconds at 40Hz rate
173  &stationaryCount);
174  if (stationary) {
175  if (!lastStationary) { // suspend some operations
176  FXAS21002_Idle(&(sensors[1]), &sfg);
177  MAG3110_Idle(&(sensors[2]), &sfg);
178  }
179  sfg.clearFIFOs(&sfg);
180  } else {
181  if (lastStationary) { // restart operations
182  FXAS21002_Init(&(sensors[1]), &sfg);
183  MAG3110_Init(&(sensors[2]), &sfg);
184  }
185  // fuse the sensor data
186  sfg.runFusion(&sfg);
187  }
188 
189  sfg.applyPerturbation(&sfg); // apply debug perturbation (testing only)
190 
191  sfg.loopcounter++; // The loop counter is used to "serialize" mag cal operations
192  i=i+1;
193  if (i>=4) { // Some status codes include a "blink" feature. This loop
194  i=0; // should cycle at least four times for that to operate correctly.
195  sfg.updateStatus(&sfg); // This is where pending status updates are made visible
196  }
197  if (stationary) {
198  sfg.queueStatus(&sfg, LOWPOWER); // assume LOWPOWER status for next pass through the loop
199  } else {
200  sfg.queueStatus(&sfg, NORMAL); // assume NORMAL status for next pass through the loop
201  }
202  sfg.pControlSubsystem->stream(&sfg, sUARTOutputBuffer); // Send stream data to the Sensor Fusion Toolbox
203  lastStationary = stationary;
204  }
205 }
206 
207 /// \endcode
void initSensorFusionGlobals(SensorFusionGlobals *sfg, StatusSubsystem *pStatusSubsystem, ControlSubsystem *pControlSubsystem)
utility function to insert default values in the top level structure
Definition: sensor_fusion.c:77
#define OVERSAMPLE_RATE
The register_io_i2c.h file declares low-level interface functions for reading and writing sensor regi...
void vApplicationIdleHook(void)
int8_t FXAS21002_Read(struct PhysicalSensor *sensor, SensorFusionGlobals *sfg)
int8_t MAG3110_Idle(struct PhysicalSensor *sensor, SensorFusionGlobals *sfg)
int8_t FXLS8952_Read(struct PhysicalSensor *sensor, SensorFusionGlobals *sfg)
#define BOARD_BootClockRUN
Definition: clock_config.h:45
Lower level sensor fusion interface.
int main(void)
This is a FreeRTOS (dual task) implementation of the NXP sensor fusion demo build.
bool motionCheck(float sample[3], float baseline[3], float tolerance, uint32_t winLength, uint32_t *count)
Definition: motionCheck.c:49
#define FXLS8952C_I2C_ADDR
struct PhysicalSensor sensors[3]
This implementation uses three physical sensors.
void initializeStatusSubsystem(StatusSubsystem *pStatus)
Definition: status.c:191
installSensor_t * installSensor
function for installing a new sensor into t
EventGroupHandle_t event_group
void BOARD_InitDebugConsole(void)
Definition: board.c:41
SensorFusionGlobals sfg
This is the primary sensor fusion data structure.
updateStatus_t * updateStatus
status=next status
int8_t FXAS21002_Idle(struct PhysicalSensor *sensor, SensorFusionGlobals *sfg)
he ControlSubsystem encapsulates command and data streaming functions.
Definition: control.h:68
void vApplicationTickHook(void)
StatusSubsystem() provides an object-like interface for communicating status to the user...
Definition: status.h:48
The top level fusion structure.
int8_t MAG3110_Read(struct PhysicalSensor *sensor, SensorFusionGlobals *sfg)
#define B0
Definition: sensor_fusion.h:98
applyPerturbation_t * applyPerturbation
apply step function for testing purposes
int8_t FXAS21002_Init(struct PhysicalSensor *sensor, SensorFusionGlobals *sfg)
initializeFusionEngine_t * initializeFusionEngine
set sensor fusion structures to initial values
setStatus_t * setStatus
change status indicator immediately
The sensor_fusion.h file implements the top level programming interface.
registerDeviceInfo_t i2cBusInfo
Running in reduced power mode.
Provides function prototypes for driver level interfaces.
uint8_t sUARTOutputBuffer[256]
main output buffer defined in control.c
Definition: control.c:63
clearFIFOs_t * clearFIFOs
clear sensor FIFOs
#define I2C_S_DEVICE_INDEX
Definition: issdk_hal.h:61
#define FXAS21002_I2C_ADDR
runFusion_t * runFusion
run the fusion routines
ControlSubsystem controlSubsystem
used for serial communications
#define I2C_S_DRIVER
Definition: issdk_hal.h:59
int8_t initializeControlPort(ControlSubsystem *pComm)
Initialize the control subsystem and all related hardware.
Definition: control.c:186
streamData_t * stream
function to create packets for serial stream
Definition: control.h:77
Non-recoverable FAULT = something went very wrong.
Application-specific status subsystem.
readSensors_t * readSensors
read all physical sensors
conditionSensorReadings_t * conditionSensorReadings
preprocessing step for sensor fusion
Defines control sub-system.
struct ControlSubsystem * pControlSubsystem
This structure defines the device specific info required by register I/O.
Definition: sensor_drv.h:128
Operation is Nominal.
void BOARD_InitPins(void)
Configures pin routing and optionally pin electrical features.
Definition: pin_mux.c:73
setStatus_t * queueStatus
queue status change for next regular interval
int8_t MAG3110_Init(struct PhysicalSensor *sensor, SensorFusionGlobals *sfg)
An instance of PhysicalSensor structure type should be allocated for each physical sensors (combo dev...
int8_t FXLS8952_Init(struct PhysicalSensor *sensor, SensorFusionGlobals *sfg)
#define MAG3110_I2C_ADDR
int32_t loopcounter
counter incrementing each iteration of sensor fusion (typically 25Hz)
#define I2C_S_SIGNAL_EVENT
Definition: issdk_hal.h:60
StatusSubsystem statusSubsystem
provides visual (usually LED) status indicator