ISSDK  1.7
IoT Sensing Software Development Kit
mma8491q_demo.c
Go to the documentation of this file.
1 /*
2  * The Clear BSD License
3  * Copyright (c) 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 /**
36  * @file mma8491q_demo.c
37  * @brief The mma8491q_demo.c file implements the ISSDK MMA8491Q sensor driver
38  * demo demonstration with polling mode.
39  */
40 
41 //-----------------------------------------------------------------------
42 // SDK Includes
43 //-----------------------------------------------------------------------
44 #include "board.h"
45 #include "pin_mux.h"
46 #include "fsl_lptmr.h"
47 #include "clock_config.h"
48 
49 //-----------------------------------------------------------------------
50 // CMSIS Includes
51 //-----------------------------------------------------------------------
52 #include "Driver_I2C.h"
53 #include "Driver_USART.h"
54 
55 //-----------------------------------------------------------------------
56 // ISSDK Includes
57 //-----------------------------------------------------------------------
58 #include "issdk_hal.h"
59 #include "gpio_driver.h"
60 #include "mma8491q_drv.h"
61 #include "host_io_uart.h"
62 #include "systick_utils.h"
63 #include "auto_detection_service.h"
64 
65 //-----------------------------------------------------------------------
66 // Macros
67 //-----------------------------------------------------------------------
68 /* Timer timeout Callback. */
69 #define mma8491q_en_callback LPTMR0_IRQHandler
70 /* Desired ODR rate in milli seconds (since the example uses LPTMR, this should be >= 10ms for reliable timing). */
71 #define MMA8491Q_T_ODR_ms 100U
72 #define MMA8491Q_STREAM_DATA_SIZE 13 /* The size of Streaming Data in Host Message. */
73 /*! @brief Unique Name for this application which should match the target GUI pkg name. */
74 #define APPLICATION_NAME "MMA8491 Accelerometer Demo"
75 /*! @brief Version to distinguish between instances the same application based on target Shield and updates. */
76 #define APPLICATION_VERSION "2.5"
77 /* The LPTMR Timeout Correction in milliseconds. */
78 #define LPTMR_T_CORRECTION_ms 2
79 
80 //-----------------------------------------------------------------------
81 // Constants
82 //-----------------------------------------------------------------------
83 /*! @brief Address of Status Register. */
85 
86 /*! @brief Address and size of Raw Acceleration Data. */
89 
90 //-----------------------------------------------------------------------
91 // Global Variables
92 //-----------------------------------------------------------------------
95 volatile bool bStreamingEnabled = false, bMma8491qReady = false, bMma849qDataReady = false;
96 gpioConfigKSDK_t gGpioConfigInPins = /* SDK GPIO Config for Tilt Pins. */
97  {
98  .pinConfig = {kGPIO_DigitalInput, 0},
99  .interruptMode = kPORT_InterruptOrDMADisabled,
100  .portPinConfig = {0},
101  .portPinConfig.mux = kPORT_MuxAsGpio,
102 };
103 uint8_t gStreamID; /* The auto assigned Stream ID. */
106 
107 //-----------------------------------------------------------------------
108 // Functions
109 //-----------------------------------------------------------------------
110 /* @brief Block for adding EN delay. */
112 {
113  uint32_t delay, count, systemCoreClock;
114 
115  systemCoreClock = CLOCK_GetCoreSysClkFreq();
116  delay = (int)(0.16*MSEC_TO_COUNT(MMA8491Q_T_ON_TYPICAL, systemCoreClock));
117  for(count=0;count<delay;count++)
118  {
119  __NOP();
120  }
121 }
122 
123 /* LPTMR based EN control Timer Callback function. */
125 {
126  LPTMR_ClearStatusFlags(LPTMR0, kLPTMR_TimerCompareFlag);
127  bMma849qDataReady = true;
128 }
129 
130 /* Function for MMA8491Q specific initialization tasks. */
131 void mma8491q_timer_fwk_init(uint32_t samplingInterval)
132 {
133  lptmr_config_t lptmrConfig;
134  /* Initialize ODR Timer. */
135  LPTMR_GetDefaultConfig(&lptmrConfig);
136  LPTMR_Init(LPTMR0, &lptmrConfig);
137  LPTMR_EnableInterrupts(LPTMR0, kLPTMR_TimerInterruptEnable);
138  EnableIRQ(LPTMR0_IRQn);
139 
140  /* Put the Sensor into Active Mode to enable I2C communication. */
141  LPTMR_SetTimerPeriod(LPTMR0, MSEC_TO_COUNT((samplingInterval-LPTMR_T_CORRECTION_ms), CLOCK_GetFreq(kCLOCK_LpoClk)));
142 }
143 
144 /* Handler for Device Info and Streaming Control Commands. */
146  uint8_t tag, uint8_t *hostCommand, uint8_t *hostResponse, size_t *hostMsgSize, size_t respBufferSize)
147 {
148  bool success = false;
149 
150  /* If it is Host requesting Device Info, send Board Name and Shield Name. */
151  if (tag == HOST_PRO_INT_DEV_TAG)
152  { /* Byte 1 : Payload - Length of APPLICATION_NAME (b)
153  * Bytes=b : Payload Application Name
154  * Byte b+1 : Payload - Length of BOARD_NAME (s)
155  * Bytes=s : Payload Board Name
156  * Byte b+s+2 : Payload - Length of SHIELD_NAME (v)
157  * Bytes=v : Payload Shield Name */
158 
159  size_t appNameLen = strlen(embAppName);
160  size_t boardNameLen = strlen(boardString);
161  size_t shieldNameLen = strlen(shieldString);
162 
163  if (respBufferSize >= boardNameLen + shieldNameLen + appNameLen + 3)
164  { /* We have sufficient buffer. */
165  *hostMsgSize = 0;
166  }
167  else
168  {
169  return false;
170  }
171 
172  hostResponse[*hostMsgSize] = appNameLen;
173  *hostMsgSize += 1;
174 
175  memcpy(hostResponse + *hostMsgSize, embAppName, appNameLen);
176  *hostMsgSize += appNameLen;
177 
178  hostResponse[*hostMsgSize] = boardNameLen;
179  *hostMsgSize += 1;
180 
181  memcpy(hostResponse + *hostMsgSize, boardString, boardNameLen);
182  *hostMsgSize += boardNameLen;
183 
184  hostResponse[*hostMsgSize] = shieldNameLen;
185  *hostMsgSize += 1;
186 
187  memcpy(hostResponse + *hostMsgSize, shieldString, shieldNameLen);
188  *hostMsgSize += shieldNameLen;
189 
190  return true;
191  }
192 
193  /* If it is Host sending Streaming Commands, take necessary actions. */
194  if ((tag == (HOST_PRO_INT_CMD_TAG | HOST_PRO_CMD_W_CFG_TAG)) &&
196  { /* Byte 1 : Payload - Operation Code (Start/Stop Operation Code)
197  * Byte 2 : Payload - Stream ID (Target Stream for carrying out operation) */
198  switch (hostCommand[0]) /* Execute desired operation (Start/Stop) on the requested Stream. */
199  {
200  case HOST_CMD_START:
201  if (hostCommand[1] == gStreamID && bMma8491qReady && bStreamingEnabled == false)
202  {
203  LPTMR_StartTimer(LPTMR0);
205  bStreamingEnabled = true;
206  success = true;
207  }
208  break;
209  case HOST_CMD_STOP:
210  if (hostCommand[1] == gStreamID && bMma8491qReady && bStreamingEnabled == true)
211  {
212  LPTMR_StopTimer(LPTMR0);
213  pGpioDriver->clr_pin(&GREEN_LED);
214  bStreamingEnabled = false;
215  success = true;
216  }
217  break;
218  default:
219  break;
220  }
221  *hostMsgSize = 0; /* Zero payload in response. */
222  }
223 
224  return success;
225 }
226 
227 /*!
228  * @brief Main function
229  */
230 int main(void)
231 {
232  int32_t status;
234 
235  mma8491q_i2c_sensorhandle_t mma8491qDriver;
237 
238  ARM_DRIVER_I2C *pI2cDriver = &I2C_S_DRIVER;
239  ARM_DRIVER_USART *pUartDriver = &HOST_S_DRIVER;
240 
241  /*! Initialize the MCU hardware. */
244 
245  /* Create the Short Application Name String for ADS. */
246  sprintf(embAppName, "%s:%s", APPLICATION_NAME, APPLICATION_VERSION);
247 
248  /* Run ADS. */
250 
251  /* Create the Full Application Name String for Device Info Response. */
253 
254  /* Initialize Tilt Pin IDs. */
255  pGpioDriver->pin_init(&MMA8491_EN, GPIO_DIRECTION_OUT, NULL, NULL, NULL);
256  pGpioDriver->pin_init(&MMA8491_XOUT, GPIO_DIRECTION_IN, &gGpioConfigInPins, NULL, NULL);
257  pGpioDriver->pin_init(&MMA8491_YOUT, GPIO_DIRECTION_IN, &gGpioConfigInPins, NULL, NULL);
258  pGpioDriver->pin_init(&MMA8491_ZOUT, GPIO_DIRECTION_IN, &gGpioConfigInPins, NULL, NULL);
259 
260  /*! Initialize GREEN LED pin used by FRDM board */
261  pGpioDriver->pin_init(&GREEN_LED, GPIO_DIRECTION_OUT, NULL, NULL, NULL);
262 
263  /*! Initialize the I2C driver. */
264  status = pI2cDriver->Initialize(I2C_S_SIGNAL_EVENT);
265  if (ARM_DRIVER_OK != status)
266  {
267  return -1;
268  }
269 
270  /*! Set the I2C Power mode. */
271  status = pI2cDriver->PowerControl(ARM_POWER_FULL);
272  if (ARM_DRIVER_OK != status)
273  {
274  return -1;
275  }
276 
277  /*! Set the I2C bus speed. */
278  status = pI2cDriver->Control(ARM_I2C_BUS_SPEED, ARM_I2C_BUS_SPEED_FAST);
279  if (ARM_DRIVER_OK != status)
280  {
281  return -1;
282  }
283 
284  /*! Initialize the UART driver. */
285  status = pUartDriver->Initialize(HOST_S_SIGNAL_EVENT);
286  if (ARM_DRIVER_OK != status)
287  {
288  return -1;
289  }
290 
291  /*! Set the UART Power mode. */
292  status = pUartDriver->PowerControl(ARM_POWER_FULL);
293  if (ARM_DRIVER_OK != status)
294  {
295  return -1;
296  }
297 
298  /*! Set UART Baud Rate. */
299  status = pUartDriver->Control(ARM_USART_MODE_ASYNCHRONOUS, BOARD_DEBUG_UART_BAUDRATE);
300  if (ARM_DRIVER_OK != status)
301  {
302  return -1;
303  }
304 
305  /* Set EN = 1 to enable I2C communication. */
306  pGpioDriver->set_pin(&MMA8491_EN);
308 
309  /* Initialize the Sensor Driver. */
311  if (SENSOR_ERROR_NONE == status)
312  {
313  /*! Set the task to be executed while waiting for I2C transactions to complete. */
315  bMma8491qReady = true;
316  }
317 
318  /*! Initialize streaming and assign a Stream ID. */
319  gStreamID =
320  Host_IO_Init(pUartDriver, (void *)mma8491qDriver.pCommDrv, &mma8491qDriver.deviceInfo, NULL, MMA8491_I2C_ADDR);
321  /* Confirm if a valid Stream ID has been allocated for this stream. */
322  if (0 == gStreamID)
323  {
324  bMma8491qReady = false;
325  }
326  else
327  { /*! Populate streaming header. */
329  pGpioDriver->clr_pin(&GREEN_LED); /* Set LED to indicate application is ready. */
330  }
331 
332  /*! Initialize MMA8491_ODR Timer framework. */
334  for (;;) /* Forever loop */
335  { /* Call UART Non-Blocking Receive. */
337 
338  /*! Process packets only if streaming has been enabled by Host */
339  if (false == bStreamingEnabled || false == bMma849qDataReady)
340  {
341  SMC_SetPowerModeWait(SMC); /* Power save, wait if nothing to do. */
342  continue;
343  }
344  else
345  {
346  pGpioDriver->toggle_pin(&GREEN_LED);
347  bMma849qDataReady = false;
348  }
349 
350  /* Set EN = 1 to put the Sensor into Active Mode. */
351  pGpioDriver->set_pin(&MMA8491_EN);
353  do
354  { /*! Process packets only when data ready is indicated by the MMA8491Q. */
355  MMA8491Q_I2C_ReadData(&mma8491qDriver, cMma8491qStatus, &dataReady);
356  } while (0 == (dataReady & MMA8491Q_STATUS_ZYXDR_MASK));
357 
358  /*! Read the raw sensor data from the MMA8491Q. */
359  status = MMA8491Q_I2C_ReadData(&mma8491qDriver, cMma8491qOutput, data);
360  if (ARM_DRIVER_OK != status)
361  { /* Loop, if sample read failed. */
362  continue;
363  }
364  /* Set EN = 0 to put the Sensor into Shutdown Mode. */
365  pGpioDriver->clr_pin(&MMA8491_EN);
366 
367  /* Update timestamp from Systick framework. */
369 
370  /* Read Tilt Output */
371  rawData.tilt[0] = pGpioDriver->read_pin(&MMA8491_XOUT);
372  rawData.tilt[1] = pGpioDriver->read_pin(&MMA8491_YOUT);
373  rawData.tilt[2] = pGpioDriver->read_pin(&MMA8491_ZOUT);
374 
375  /*! Process the sample and convert the raw sensor data. */
376  rawData.accel[0] = ((int16_t)data[0] << 8) | (data[1]);
377  rawData.accel[0] /= 4;
378  rawData.accel[1] = ((int16_t)data[2] << 8) | (data[3]);
379  rawData.accel[1] /= 4;
380  rawData.accel[2] = ((int16_t)data[4] << 8) | (data[5]);
381  rawData.accel[2] /= 4;
382 
383  /* Copy Raw samples to Streaming Buffer. */
384  memcpy(streamingPacket + STREAMING_HEADER_LEN, &rawData, MMA8491Q_STREAM_DATA_SIZE);
385  /* Send streaming packet to Host. */
386  Host_IO_Send(streamingPacket, sizeof(streamingPacket), HOST_FORMAT_HDLC);
387  }
388 }
bool process_host_command(uint8_t tag, uint8_t *hostCommand, uint8_t *hostResponse, size_t *hostMsgSize, size_t respBufferSize)
uint32_t BOARD_SystickElapsedTime_us(int32_t *pStart)
Function to compute the Elapsed Time.
Definition: systick_utils.c:99
const registerreadlist_t cMma8491qStatus[]
Address of Status Register.
Definition: mma8491q_demo.c:84
ARM_DRIVER_I2C * pCommDrv
Definition: mma8491q_drv.h:58
char boardString[ADS_MAX_STRING_LENGTH]
Definition: mma8491q_demo.c:93
#define MMA8491Q_STATUS_ZYXDR_MASK
Definition: mma8491q.h:68
#define APPLICATION_NAME
Unique Name for this application which should match the target GUI pkg name.
Definition: mma8491q_demo.c:74
#define HOST_PRO_CMD_W_CFG_TAG
Definition: host_io_uart.h:89
#define LPTMR_T_CORRECTION_ms
Definition: mma8491q_demo.c:78
#define HOST_S_SIGNAL_EVENT
Definition: frdm_k64f.h:120
char shieldString[ADS_MAX_STRING_LENGTH]
Definition: mma8491q_demo.c:93
void Host_IO_Receive(host_cmd_proc_fn_t process_host_command, uint8_t encoding)
Definition: host_io_uart.c:233
void(* pin_init)(pinID_t aPinId, gpio_direction_t dir, void *apPinConfig, gpio_isr_handler_t aIsrHandler, void *apUserData)
Definition: Driver_GPIO.h:67
#define BOARD_BootClockRUN
Definition: clock_config.h:45
int main(void)
Main function.
#define MMA8491Q_DATA_SIZE
Definition: mma8491q_drv.h:89
#define MMA8491_I2C_ADDR
uint8_t data[FXLS8962_DATA_SIZE]
int32_t status
void(* toggle_pin)(pinID_t aPinId)
Definition: Driver_GPIO.h:74
#define SHIELD_NAME
The GPIO Configuration KSDK.
Definition: gpio_driver.h:65
int32_t MMA8491Q_I2C_ReadData(mma8491q_i2c_sensorhandle_t *pSensorHandle, const registerreadlist_t *pReadList, uint8_t *pBuffer)
The interface function to read the sensor data.
Definition: mma8491q_drv.c:90
#define ADS_MAX_STRING_LENGTH
#define HOST_PRO_INT_DEV_TAG
Definition: host_io_uart.h:85
uint8_t streamingPacket[STREAMING_HEADER_LEN+FXLS8962_STREAM_DATA_SIZE]
void(* registeridlefunction_t)(void *userParam)
This is the register idle function type.
Definition: sensor_drv.h:123
void mma8491q_en_delay()
#define HOST_PRO_INT_CMD_TAG
Bit aligned values for Host Protocol Interface IDs (Bits 5-6).
Definition: host_io_uart.h:83
registerDeviceInfo_t deviceInfo
Definition: mma8491q_drv.h:57
#define __END_READ_DATA__
Definition: sensor_drv.h:77
uint32_t(* read_pin)(pinID_t aPinId)
Definition: Driver_GPIO.h:76
#define MMA8491Q_STREAM_DATA_SIZE
Definition: mma8491q_demo.c:72
volatile bool bStreamingEnabled
Definition: mma8491q_demo.c:95
#define APPLICATION_VERSION
Version to distinguish between instances the same application based on target Shield and updates...
Definition: mma8491q_demo.c:76
gpioHandleKSDK_t GREEN_LED
Definition: frdm_k64f.c:214
gpioConfigKSDK_t gGpioConfigInPins
Definition: mma8491q_demo.c:96
int32_t MMA8491Q_I2C_Initialize(mma8491q_i2c_sensorhandle_t *pSensorHandle, ARM_DRIVER_I2C *pBus, uint8_t index, uint16_t sAddress)
The interface function to initialize the sensor.
Definition: mma8491q_drv.c:48
#define mma8491q_en_callback
Definition: mma8491q_demo.c:69
gpio_pin_config_t pinConfig
Definition: gpio_driver.h:67
void Host_IO_Add_ISO_Header(uint8_t streamID, uint8_t *pStreamingPacket, size_t sizePayload)
Definition: host_io_uart.c:112
void Host_IO_Send(uint8_t *pMsg, size_t size, uint8_t encoding)
Definition: host_io_uart.c:162
void(* set_pin)(pinID_t aPinId)
Definition: Driver_GPIO.h:72
void(* clr_pin)(pinID_t aPinId)
Definition: Driver_GPIO.h:73
void mma8491q_timer_fwk_init(uint32_t samplingInterval)
void BOARD_SystickEnable(void)
Function to enable systicks framework.
Definition: systick_utils.c:70
const registerreadlist_t cMma8491qOutput[]
Address and size of Raw Acceleration Data.
Definition: mma8491q_demo.c:87
void MMA8491Q_I2C_SetIdleTask(mma8491q_i2c_sensorhandle_t *pSensorHandle, registeridlefunction_t idleTask, void *userParam)
: The interface function to set the I2C Idle Task.
Definition: mma8491q_drv.c:82
This defines the function pointers and sensor specific information.
Definition: mma8491q_drv.h:55
#define I2C_S_DEVICE_INDEX
Definition: issdk_hal.h:61
GENERIC_DRIVER_GPIO * pGpioDriver
#define I2C_S_DRIVER
Definition: issdk_hal.h:59
The mma8491q_drv.h file describes the MMA8491Q driver interface and structures.
GENERIC_DRIVER_GPIO Driver_GPIO_KSDK
Definition: gpio_driver.c:203
typedef int32_t(DATA_FORMAT_Append_t))(void *pData
The interface function to append the data on the formated stream.
#define BOARD_DEBUG_UART_BAUDRATE
Definition: board.h:57
volatile bool bMma8491qReady
Definition: mma8491q_demo.c:95
#define MMA8491_XOUT
#define MMA8491_YOUT
Access structure of the GPIO Driver.
Definition: Driver_GPIO.h:64
void BOARD_SystickStart(int32_t *pStart)
Function to Record the Start systick.
Definition: systick_utils.c:79
uint8_t gStreamID
ARM Systick Utilities.
#define MMA8491Q_T_ODR_ms
Definition: mma8491q_demo.c:71
void BOARD_RunADS(const char *appName, char *boardString, char *shieldString, size_t bufferLength)
The function to register Application Name and initialte ADS.
fxls8962_acceldataUser_t rawData
uint8_t Host_IO_Init(ARM_DRIVER_USART *pDrv, void *pBus, void *pDevInfo, void *spiSlaveParams, uint16_t slaveAddress)
Definition: host_io_uart.c:126
char embAppName[ADS_MAX_STRING_LENGTH]
Definition: mma8491q_demo.c:94
#define MMA8491Q_T_ON_TYPICAL
Definition: mma8491q.h:30
This structure defines the Read command List.
Definition: sensor_drv.h:104
#define SMC
Definition: lpc54114.h:144
The host_io_uart.h file contains the Host Protocol interface definitions and configuration.
This structure defines the mma8491q data buffer.
Definition: mma8491q_drv.h:64
#define STREAMING_HEADER_LEN
Definition: host_io_uart.h:51
status_t SMC_SetPowerModeWait(void *arg)
Configures the system to WAIT power mode. API name used from Kinetis family to maintain compatibility...
Definition: lpc54114.c:181
volatile bool bMma849qDataReady
Definition: mma8491q_demo.c:95
#define I2C_S_SIGNAL_EVENT
Definition: issdk_hal.h:60
#define MMA8491_EN
#define HOST_S_DRIVER
Definition: frdm_k64f.h:119
#define MMA8491_ZOUT
int32_t gSystick