Sensors Knowledge Base

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Sensors Knowledge Base

Discussions

Sort by:
Hands-on Training using Sensors Development Ecosystem
View full article
Hi Everyone,   I would like to present another example code/demo that reads acceleration data from the Xtrinsic MMA8491Q digital accelerometer and visualizes them using the FreeMASTER tool via USBDM interface. I have used recently released Xtrinsic MEMS sensors board that features three types of Xtrinsic sensors including the MMA8491Q and is fully compatible with the Freescale FRDM-KL25Z platform.   In comparison with other Xtrinsic accelerometers, the MMA8491Q is turned on at the rising edge on the EN pin and acquires only one sample for each of the three axes. It does not have any interrupt pins, instead there are three push-pull logic outputs which provide tilt detection at 45 degrees as the original target application was tamper detection. However, it is possible to read the 14-bit output values through the I2C port as demonstrated in my example below.   According to the User Manual, both SCL and SDA lines are connected through the 4.7K pull-up resistors to the I2C1 module (PTE1 and PTE0 pins) on the KL25Z128 MCU and the EN pin is connected to the PTA13 pin. The EN input needs to be kept high until a new data is ready (max. 900us) and read. In my code I use the PIT module to wait 1ms before reading the output values. This timer is also used to read the output data periodically at a fixed rate. The timeout period of the PIT is set to 500us. The MCU is, therefore, configured as follows:   void MCU_Init(void) {             //I2C1 module initialization             SIM_SCGC4 |= SIM_SCGC4_I2C1_MASK;        // Turn on clock to I2C1 module         SIM_SCGC5 |= SIM_SCGC5_PORTE_MASK;       // Turn on clock to Port E module        PORTE_PCR1 = PORT_PCR_MUX(6);            // PTE1 pin is I2C1 SCL line        PORTE_PCR0 = PORT_PCR_MUX(6);            // PTE0 pin is I2C1 SDA line        I2C1_F  = 0x14;                          // SDA hold time = 2.125us, SCL start hold time = 4.25us, SCL stop hold time = 5.125us         I2C1_C1 = I2C_C1_IICEN_MASK;             // Enable I2C1 module                //Configure the PTA13 pin as an output to drive the EN input of the MMA8491Q        SIM_SCGC5 |= SIM_SCGC5_PORTA_MASK;       // Turn on clock to Port A module        PORTA_PCR13 = PORT_PCR_MUX(1);           // PTA13 is configured as GPIO        GPIOA_PCOR |= 1<<13;                     // Set PTA13 pin low        GPIOA_PDDR |= 1<<13;                     // PTA13 pin is an output                //PIT initialization        SIM_SCGC6 |= SIM_SCGC6_PIT_MASK;         // Turn on clock to to the PIT module        PIT_LDVAL0 = 5240;                       // Timeout period = 500us        PIT_MCR = PIT_MCR_FRZ_MASK;              // Enable clock for PIT, freeze PIT in debug mode        PIT_TCTRL0 = PIT_TCTRL_TIE_MASK |        // Enable PIT interrupt                    PIT_TCTRL_TEN_MASK;          // and PIT                //Enable PIT interrupt on NVIC           NVIC_ICPR |= 1 << ((INT_PIT - 16) % 32);        NVIC_ISER |= 1 << ((INT_PIT - 16) % 32); }   In the PIT interrupt service routine (ISR), there is a variable Counter that is increased by one on every PIT interrupt (500us) and its value is then compared with two preset values. The first preset value EN_HIGH_TIME determines how long the EN pin will remain high to ensure a valid reading of a new set of output data. The second preset value DATA_UPDATE_PERIOD corresponds to the desired output data rate. At the end of the ISR, the PIT interrupt flag is cleared.   void PIT_IRQHandler() {        static int Counter = 0;        Counter++;                                   // Each increment represents 500us        switch (Counter)     {             case 1:             GPIOA_PSOR |= 1<<13;                 // Set EN pin high                      break;             caseEN_HIGH_TIME:                        // 1ms passed             DataReady = 1;                       // Data is ready                      break;             caseDATA_UPDATE_PERIOD:                  // 100ms passed             Counter = 0;                         // Clear Counter at the end of the sample period                      break;             default:                      break;     }        PIT_TFLG0 |= PIT_TFLG_TIF_MASK;              // Clear PIT interrupt flag }   In the main loop, the DataReady variable is periodically checked and if it is set, the accelerometer data registers 0x01 - 0x06 are read and then the acceleration in units of g is calculated. Finally the EN pin is set low to reduce the current consumption and the DataReady variable is cleared.   if (DataReady)                                                                  // Is a new set of data ready? {                  AccData[0] = I2C_ReadRegister(MMA8491Q_I2C_ADDRESS, OUT_X_MSB_REG);         // [7:0] are 8 MSBs of the 14-bit X-axis sample      AccData[1] = I2C_ReadRegister(MMA8491Q_I2C_ADDRESS, OUT_X_LSB_REG);         // [7:2] are the 6 LSB of 14-bit X-axis sample      AccData[2] = I2C_ReadRegister(MMA8491Q_I2C_ADDRESS, OUT_Y_MSB_REG);         // [7:0] are 8 MSBs of the 14-bit Y-axis sample      AccData[3] = I2C_ReadRegister(MMA8491Q_I2C_ADDRESS, OUT_Y_LSB_REG);         // [7:2] are the 6 LSB of 14-bit Y-axis sample      AccData[4] = I2C_ReadRegister(MMA8491Q_I2C_ADDRESS, OUT_Z_MSB_REG);         // [7:0] are 8 MSBs of the 14-bit Z-axis sample      AccData[5] = I2C_ReadRegister(MMA8491Q_I2C_ADDRESS, OUT_Z_LSB_REG);         // [7:2] are the 6 LSB of 14-bit Z-axis sample        Xout_14_bit = ((short) (AccData[0]<<8 | AccData[1])) >> 2;           // Compute 14-bit X-axis output value      Yout_14_bit = ((short) (AccData[2]<<8 | AccData[3])) >> 2;           // Compute 14-bit Y-axis output value      Zout_14_bit = ((short) (AccData[4]<<8 | AccData[5])) >> 2;           // Compute 14-bit Z-axis output value                         Xout_g = ((float) Xout_14_bit) / SENSITIVITY;          // Compute X-axis output value in g's      Yout_g = ((float) Yout_14_bit) / SENSITIVITY;          // Compute Y-axis output value in g's      Zout_g = ((float) Zout_14_bit) / SENSITIVITY;          // Compute Z-axis output value in g's                                              GPIOA_PCOR |= 1<<13;       // Set EN pin low      DataReady = 0;                                                                                                                                 }                       The calculated values can be watched in the "Variables" window on the top right of the Debug perspective or in the FreeMASTER application.       Attached you can find the complete source code written in the CW 10.3 as well as the FreeMASTER project.   If there are any questions regarding this simple application, do not hesitate to ask below. Your feedback or suggestions are also welcome.   Regards, Tomas  
View full article
Hi Everyone,   In this document I would like to go through a simple bare-metal example code I created for the recently released FRDMSTBC-A8471 development board with the NXP FXLS8471Q 3-axis linear accelerometer. This board is compatible with most NXP Freedom development boards and I decided to use one of the most popular - FRDM-KL25Z. The FreeMASTER tool is used to visualize the acceleration data that are read from the FXLS8471Q using an interrupt technique through the SPI interface. I will not cover the Sensor Toolbox software and Intelligent Sensing Framework (ISF) which also support this board.   This example illustrates:   1. Initialization of the MKL25Z128 MCU (mainly SPI and PORT modules). 2. SPI data write and read operations. 3. Initialization of the FXLS8471Q to achieve the highest resolution. 4. Simple offset calibration based on the AN4069. 5. Output data reading using an interrupt technique. 6. Conversion of the output values from registers 0x01 – 0x06 to real acceleration values in g’s. 7. Visualization of the output values in the FreeMASTER tool.     1. As you can see in the FRDMSTBC-A8471​/FRDM-KL25Z​ schematics and the image below, SPI signals are routed to the SPI0 module of the KL25Z MCU and the INT1 output is connected to the PTD4 pin. The PTD0 pin (Chip Select) is not controlled automatically by SPI0 module, hence it is configured as a general-purpose output. The INT1 output of the FXLS8471Q is configured as a push-pull active-low output, so the corresponding PTD4 pin configuration is GPIO with an interrupt on falling edge.The core/system clock frequency is 20.97 MHz and SPI clock is 524.25 kHz.     The MCU is, therefore, configured as follows.   /****************************************************************************** * MCU initialization function ******************************************************************************/   void MCU_Init(void) {   //SPI0 module initialization   SIM_SCGC4 |= SIM_SCGC4_SPI0_MASK; // Turn on clock to SPI0 module   SIM_SCGC5 |= SIM_SCGC5_PORTD_MASK; // Turn on clock to Port D module   PORTD_PCR1 = PORT_PCR_MUX(0x02); // PTD1 pin is SPI0 CLK line   PORTD_PCR2 = PORT_PCR_MUX(0x02); // PTD2 pin is SPI0 MOSI line   PORTD_PCR3 = PORT_PCR_MUX(0x02); // PTD3 pin is SPI0 MISO line   PORTD_PCR0 = PORT_PCR_MUX(0x01); // PTD0 pin is configured as GPIO (CS line driven manually)   GPIOD_PSOR |= GPIO_PSOR_PTSO(0x01); // PTD0 = 1 (CS inactive)   GPIOD_PDDR |= GPIO_PDDR_PDD(0x01); // PTD0 pin is GPIO output     SPI0_C1 = SPI_C1_SPE_MASK | SPI_C1_MSTR_MASK; // Enable SPI0 module, master mode   SPI0_BR = SPI_BR_SPPR(0x04) | SPI_BR_SPR(0x02); // BaudRate = BusClock / ((SPPR+1) * 2^(SPR+1)) = 20970000 / ((4+1) * 2^(2+1)) = 524.25 kHz     //Configure the PTD4 pin (connected to the INT1 of the FXLS8471Q) for falling edge interrupts   PORTD_PCR4 |= (0|PORT_PCR_ISF_MASK| // Clear the interrupt flag                   PORT_PCR_MUX(0x1)| // PTD4 is configured as GPIO                   PORT_PCR_IRQC(0xA)); // PTD4 is configured for falling edge interrupts     //Enable PORTD interrupt on NVIC   NVIC_ICPR |= 1 << ((INT_PORTD - 16)%32);   NVIC_ISER |= 1 << ((INT_PORTD - 16)%32); }     2. The FXLS8471Q uses the ‘Mode 0′ SPI protocol, which means that an inactive state of clock signal is low and data are captured on the leading edge of clock signal and changed on the falling edge.   The falling edge on the CS pin starts the SPI communication. A write operation is initiated by transmitting a 1 for the R/W bit. Then the 8-bit register address, ADDR[7:0] is encoded in the first and second serialized bytes. Data to be written starts in the third serialized byte. The order of the bits is as follows:   Byte 0: R/W, ADDR[6], ADDR[5], ADDR[4], ADDR[3], ADDR[2], ADDR[1], ADDR[0] Byte 1: ADDR[7], X, X, X, X, X, X, X Byte 2: DATA[7], DATA[6], DATA[5], DATA[4], DATA[3], DATA[2], DATA[1], DATA[0]   The rising edge on the CS pin stops the SPI communication.   Below is the write operation which writes the value 0x3D to the CTRL_REG1 (0x3A).   Similarly a read operation is initiated by transmitting a 0 for the R/W bit. Then the 8-bit register address, ADDR[7:0] is encoded in the first and second serialized bytes. The data is read from the MISO pin (MSB first).   The screenshot below shows the read operation which reads the correct value 0x6A from the WHO_AM_I register (0x0D).   Multiple read operations are performed similar to single read except bytes are read in multiples of eight SCLK cycles. The register address is auto incremented so that every eighth next clock edges will latch the MSB of the next register.   A burst read of 6 bytes from registers 0x01 to 0x06 is shown below. It also shows how the INT1 pin is automatically cleared by reading the acceleration output data.     3. The dynamic range is set to ±2g and to achieve the highest resolution, the LNOISE bit is set and the lowest ODR (1.56Hz) and the High Resolution mode are selected (more details in AN4075). The DRDY interrupt is enabled and routed to the INT1 interrupt pin that is configured to be a push-pull, active-low output.   /****************************************************************************** * FXLS8471Q initialization function ******************************************************************************/   void FXLS8471Q_Init (void) {   FXLS8471Q_WriteRegister(CTRL_REG2, 0x02); // High Resolution mode   FXLS8471Q_WriteRegister(CTRL_REG3, 0x00); // Push-pull, active low interrupt   FXLS8471Q_WriteRegister(CTRL_REG4, 0x01); // Enable DRDY interrupt   FXLS8471Q_WriteRegister(CTRL_REG5, 0x01); // DRDY interrupt routed to INT1-PTD4   FXLS8471Q_WriteRegister(CTRL_REG1, 0x3D); // ODR = 1.56Hz, Reduced noise, Active mode   }     4. A simple offset calibration method is implemented according to the AN4069​.   /****************************************************************************** * Simple accelerometer offset calibration ******************************************************************************/   void FXLS8471Q_Calibrate (void) {   unsigned char reg_val = 0;     while (!reg_val) // Wait for a first set of data    {     reg_val = FXLS8471Q_ReadRegister(STATUS_REG) & 0x08;   }      FXLS8471Q_ReadMultiRegisters(OUT_X_MSB_REG, 6, AccData); // Read data output registers 0x01-0x06       Xout_14_bit = ((short) (AccData[0]<<8 | AccData[1])) >> 2; // Compute 14-bit X-axis output value   Yout_14_bit = ((short) (AccData[2]<<8 | AccData[3])) >> 2; // Compute 14-bit Y-axis output value   Zout_14_bit = ((short) (AccData[4]<<8 | AccData[5])) >> 2; // Compute 14-bit Z-axis output value      Xoffset = Xout_14_bit / 8 * (-1); // Compute X-axis offset correction value   Yoffset = Yout_14_bit / 8 * (-1); // Compute Y-axis offset correction value   Zoffset = (Zout_14_bit - SENSITIVITY_2G) / 8 * (-1); // Compute Z-axis offset correction value      FXLS8471Q_WriteRegister(CTRL_REG1, 0x00); // Standby mode to allow writing to the offset registers   FXLS8471Q_WriteRegister(OFF_X_REG, Xoffset);   FXLS8471Q_WriteRegister(OFF_Y_REG, Yoffset);   FXLS8471Q_WriteRegister(OFF_Z_REG, Zoffset);      FXLS8471Q_WriteRegister(CTRL_REG1, 0x3D); // ODR = 1.56Hz, Reduced noise, Active mode }     5. In the ISR, only the interrupt flag is cleared and the DataReady variable is set to indicate the arrival of new data.   /****************************************************************************** * PORT D Interrupt handler ******************************************************************************/   void PORTD_IRQHandler() {   PORTD_PCR4 |= PORT_PCR_ISF_MASK; // Clear the interrupt flag   DataReady = 1; }     6. The output values from accelerometer registers 0x01 – 0x06 are first converted to signed 14-bit values and afterwards to real values in g’s.   if (DataReady)     // Is a new set of data ready? {   DataReady = 0;     FXLS8471Q_ReadMultiRegisters(OUT_X_MSB_REG, 6, AccData); // Read data output registers 0x01-0x06                                                    Xout_14_bit = ((short) (AccData[0]<<8 | AccData[1])) >> 2; // Compute 14-bit X-axis output value   Yout_14_bit = ((short) (AccData[2]<<8 | AccData[3])) >> 2; // Compute 14-bit Y-axis output value   Zout_14_bit = ((short) (AccData[4]<<8 | AccData[5])) >> 2; // Compute 14-bit Z-axis output value                                        Xout_g = ((float) Xout_14_bit) / SENSITIVITY_2G; // Compute X-axis output value in g's   Yout_g = ((float) Yout_14_bit) / SENSITIVITY_2G; // Compute Y-axis output value in g's   Zout_g = ((float) Zout_14_bit) / SENSITIVITY_2G; // Compute Z-axis output value in g's }     7. The calculated values can be watched in the "Variables" window on the top right of the Debug perspective or in the FreeMASTER application. To open and run the FreeMASTER project, install the FreeMASTER 2.0 application and FreeMASTER Communication Driver.         Attached you can find the complete source code written in the CW for MCU's v10.6​ including the FreeMASTER project.   If there are any questions regarding this simple application, please feel free to ask below. Your feedback or suggestions are also welcome.   Regards, Tomas
View full article
Hi Everyone,   I would like to share here another simple bare-metal example code/demo for the Xtrinsic MMA8652FC digital accelerometer that I have created while working with the Freescale FRDM-KL25Z development platform and FRDM-FXS-MULTI(-B) sensor expansion board. To visualize the acceleration data that are read from the MMA8652FC using an interrupt technique through the I 2 C interface, I have used the FreeMASTER tool.   This example illustrates:   1. Initialization of the MKL25Z128 MCU (mainly I 2 C and PORT modules). 2. I 2 C data write and read operations. 3. Initialization of the accelerometer to achieve the highest resolution. 4. Simple offset calibration based on the AN4069. 5. Output data reading using an interrupt technique. 6. Conversion of the output values from registers 0x01 – 0x06 to real acceleration values in g’s. 7. Visualization of the output values in the FreeMASTER tool.   1. As you can see in the FRDM-FXS-MULTI(-B)/FRDM-KL25Z schematics and the image below, I2C signals are routed to the I2C1 module (PTC1 and PTC2 pins) of the KL25Z MCU and the INT1 output is connected to the PTA5 pin (make sure that pin #3 of J4 and pin #2 of J6 connector on the sensor expansion board are connected together). The INT1 output of the MMA8652FC is configured as a push-pull active-low output, so the corresponding PTA5 pin configuration is GPIO with an interrupt on falling edge.     The MCU is, therefore, configured as follows. void MCU_Init(void) {      //I2C1 module initialization      SIM_SCGC4 |= SIM_SCGC4_I2C1_MASK;        // Turn on clock to I2C1 module      SIM_SCGC5 |= SIM_SCGC5_PORTC_MASK;       // Turn on clock to Port C module      PORTC_PCR1 |= PORT_PCR_MUX(0x2);         // PTC1 pin is I2C1 SCL line      PORTC_PCR2 |= PORT_PCR_MUX(0x2);         // PTC2 pin is I2C1 SDA line      I2C1_F  |= I2C_F_ICR(0x14);              // SDA hold time = 2.125us, SCL start hold time = 4.25us, SCL stop hold time = 5.125us      I2C1_C1 |= I2C_C1_IICEN_MASK;            // Enable I2C1 module                      //Configure the PTA5 pin (connected to the INT1 of the MMA8652FC) for falling edge interrupts      SIM_SCGC5 |= SIM_SCGC5_PORTA_MASK;       // Turn on clock to Port A module      PORTA_PCR5 |= (0|PORT_PCR_ISF_MASK|      // Clear the interrupt flag                       PORT_PCR_MUX(0x1)|      // PTA5 is configured as GPIO                       PORT_PCR_IRQC(0xA));    // PTA5 is configured for falling edge interrupts                     //Enable PORTA interrupt on NVIC      NVIC_ICPR |= 1 << ((INT_PORTA - 16)%32);      NVIC_ISER |= 1 << ((INT_PORTA - 16)%32); }   2. The 7-bit I 2 C address of the MMA8652FC is fixed value 0x1D. As shown above, the SCL line is connected to the PTC1 pin and SDA line to the PTC2 pin. The I2C clock frequency is 125 kHz. The screenshot below shows the write operation which writes the value 0x39 to the CTRL_REG1 (0x2A).     And here is the single byte read from the WHO_AM_I register 0x0D. As you can see, it returns the correct value 0x4A.     Multiple bytes of data can be read from sequential registers after each MMA8652FC acknowledgment (AK) is received until a no acknowledge (NAK) occurs from the KL25Z followed by a stop condition (SP) signaling an end of transmission. A burst read of 6 bytes from registers 0x01 to 0x06 is shown below. It also shows how the INT1 pin is automatically deasserted by reading the acceleration output data.       3. At the beginning of the initialization, all registers are reset to their default values by setting the RST bit of the CTRL_REG2 register. The dynamic range is set to ±2g and to achieve the highest resolution, the lowest ODR (1.56Hz) and the High Resolution mode are selected (more details in AN4075). The DRDY interrupt is enabled and routed to the INT1 interrupt pin that is configured to be a push-pull, active-low output. void MMA8652FC_Init (void) {      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG2, 0x40);          // Reset all registers to POR values           Pause(0x631);          // ~1ms delay           I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, XYZ_DATA_CFG_REG, 0x00);   // +/-2g range with ~0.977mg/LSB       I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG2, 0x02);          // High Resolution mode      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG3, 0x00);          // Push-pull, active low interrupt      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG4, 0x01);          // Enable DRDY interrupt      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG5, 0x01);          // DRDY interrupt routed to INT1 - PTA5      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG1, 0x39);          // ODR = 1.56Hz, Active mode       }   4. A simple offset calibration method is implemented according to the AN4069.   void MMA8652FC_Calibration (void) {      char X_offset, Y_offset, Z_offset;           DataReady = 0;                while (!DataReady){}          // Is a first set of data ready?      DataReady = 0;           I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG1, 0x00);          // Standby mode                I2C_ReadMultiRegisters(MMA8652FC_I2C_ADDRESS, OUT_X_MSB_REG, 6, AccelData);          // Read data output registers 0x01-0x06                         Xout_12_bit = ((short) (AccelData[0]<<8 | AccelData[1])) >> 4;             // Compute 12-bit X-axis acceleration output value      Yout_12_bit = ((short) (AccelData[2]<<8 | AccelData[3])) >> 4;             // Compute 12-bit Y-axis acceleration output value      Zout_12_bit = ((short) (AccelData[4]<<8 | AccelData[5])) >> 4;             // Compute 12-bit Z-axis acceleration output value                  X_offset = Xout_12_bit / 2 * (-1);          // Compute X-axis offset correction value      Y_offset = Yout_12_bit / 2 * (-1);          // Compute Y-axis offset correction value      Z_offset = (Zout_12_bit - SENSITIVITY_2G) / 2 * (-1);         // Compute Z-axis offset correction value                  I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, OFF_X_REG, X_offset);                  I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, OFF_Y_REG, Y_offset);            I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, OFF_Z_REG, Z_offset);                        I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG1, 0x39);          // Active mode again }   5. In the ISR, only the interrupt flag is cleared and the DataReady variable is set to indicate the arrival of new data.   void PORTA_IRQHandler() {      PORTA_PCR5 |= PORT_PCR_ISF_MASK;          // Clear the interrupt flag      DataReady = 1;    }   6. The output values from accelerometer registers 0x01 – 0x06 are first converted to signed 12-bit values and afterwards to real values in g’s.   if (DataReady)             // Is a new set of data ready? {                  DataReady = 0;                                                                                                                         I2C_ReadMultiRegisters(MMA8652FC_I2C_ADDRESS, OUT_X_MSB_REG, 6, AccelData);          // Read data output registers 0x01-0x06                    // 12-bit accelerometer data      Xout_12_bit = ((short) (AccelData[0]<<8 | AccelData[1])) >> 4;             // Compute 12-bit X-axis acceleration output value      Yout_12_bit = ((short) (AccelData[2]<<8 | AccelData[3])) >> 4;             // Compute 12-bit Y-axis acceleration output value      Zout_12_bit = ((short) (AccelData[4]<<8 | AccelData[5])) >> 4;             // Compute 12-bit Z-axis acceleration output value                             // Accelerometer data converted to g's      Xout_g = ((float) Xout_12_bit) / SENSITIVITY_2G;              // Compute X-axis output value in g's      Yout_g = ((float) Yout_12_bit) / SENSITIVITY_2G;              // Compute Y-axis output value in g's      Zout_g = ((float) Zout_12_bit) / SENSITIVITY_2G;              // Compute Z-axis output value in g's               }     7. The calculated values can be watched in the "Variables" window on the top right of the Debug perspective or in the FreeMASTER application. To open and run the FreeMASTER project, install the FreeMASTER application and FreeMASTER Communication Driver.       Attached you can find the complete source code written in the CW for MCU's (Eclipse IDE) including the FreeMASTER project.   If there are any questions regarding this simple application, do not hesitate to ask below. Your feedback or suggestions are also welcome.   Regards, Tomas
View full article
Hi Everyone,   As I am often asked for a simple bare metal example code for the Xtrinsic FXOS8700CQ 6-axis sensor, I would like to share here one of my examples I have created for this part while working with the Freescale FRDM-KL25Z platform and FRDM-FXS-MULTI(-B) sensor expansion board that features many of the Xtrinsic sensors including the FXOS8700CQ. The FreeMASTER tool is used to visualize both the acceleration and magnetic data that are read from the FXOS8700CQ using an interrupt technique through the I 2 C interface.   This example illustrates:   1. Initialization of the MKL25Z128 MCU (mainly I2C and PORT modules). 2. I 2 C data write and read operations. 3. Initialization of the FXOS8700CQ. 4. Simple accelerometer offset calibration based on the AN4069. 5. Simple magnetic hard-iron offset calibration. 6. Output data reading using an interrupt technique. 7. Conversion of the output values from registers 0x01 – 0x06 and 0x33 – 0x38 to real values in g’s and µT and simple heading angle calculation. 8. Visualization of the calculated values in the FreeMASTER tool.   1. As you can see in the FRDM-FXS-MULTI(-B)/FRDM-KL25Z schematics and the image below, I2C signals are routed to the I2C1 module (PTC1 and PTC2 pins) of the KL25Z MCU and the INT1 output is connected to the PTD4 pin (make sure that pins 1-2 of J3 on the sensor expansion board are connected together using a jumper). The INT1 output of the FXOS8700CQ is configured as a push-pull active-low output, so the corresponding PTD4 pin configuration is GPIO with an interrupt on falling edge.   The MCU is, therefore, configured as follows.   void MCU_Init(void) {      //I2C1 module initialization      SIM_SCGC4 |= SIM_SCGC4_I2C1_MASK;        // Turn on clock to I2C1 module      SIM_SCGC5 |= SIM_SCGC5_PORTC_MASK;       // Turn on clock to Port C module      PORTC_PCR1 |= PORT_PCR_MUX(0x2);         // PTC1 pin is I2C1 SCL line      PORTC_PCR2 |= PORT_PCR_MUX(0x2);         // PTC2 pin is I2C1 SDA line      I2C1_F  |= I2C_F_ICR(0x14);              // SDA hold time = 2.125us, SCL start hold time = 4.25us, SCL stop hold time = 5.125us      I2C1_C1 |= I2C_C1_IICEN_MASK;            // Enable I2C0 module               //Configure the PTD4 pin (connected to the INT1 of the FXOS8700CQ) for falling edge interrupts      SIM_SCGC5 |= SIM_SCGC5_PORTD_MASK;       // Turn on clock to Port A module      PORTD_PCR4 |= (0|PORT_PCR_ISF_MASK|      // Clear the interrupt flag                      PORT_PCR_MUX(0x1)|       // PTD4 is configured as GPIO                      PORT_PCR_IRQC(0xA));     // PTD4 is configured for falling edge interrupts                   //Enable PORTD interrupt on NVIC      NVIC_ICPR |= 1 << ((INT_PORTD - 16)%32);      NVIC_ISER |= 1 << ((INT_PORTD - 16)%32); }   2. The 7-bit I2C address of the FXOS8700CQ is 0x1E since both SA0 and SA1 lines are shorted to GND using jumpers J21 and J23 on the sensor board. As shown above, the SCL line is connected to the PTC1 pin and SDA line to the PTC2 pin. The I2C clock frequency is 125 kHz.   The screenshot below shows the write operation which writes the value 0x35 to the CTRL_REG1 (0x2A).     And here is the single byte read from the WHO_AM_I register 0x0D. As you can see, it returns the correct value 0xC7.     Multiple bytes of data can be read from sequential registers after each FXOS8700CQ acknowledgment (AK) is received until a no acknowledge (NAK) occurs from the KL25Z followed by a stop condition (SP) signaling an end of transmission. A burst read of 6 bytes from registers 0x33 to 0x38, that is performed in the calibration routine “FXOS8700CQ_Mag_Calibration()”, is shown below. It also shows when the INT1 pin is automatically cleared.     3. At the beginning of the initialization, all registers are reset to their default values by setting the RST bit of the CTRL_REG2 register. Then the FXOS8700CQ is initialized as shown below.   void FXOS8700CQ_Init (void) {      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG2, 0x40);          // Reset all registers to POR values        Pause(0x631);        // ~1ms delay        I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, XYZ_DATA_CFG_REG, 0x00);   // +/-2g range with 0.244mg/LSB          I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, M_CTRL_REG1, 0x1F);        // Hybrid mode (accelerometer + magnetometer), max OSR      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, M_CTRL_REG2, 0x20);        // M_OUT_X_MSB register 0x33 follows the OUT_Z_LSB register 0x06 (used for burst read)                   I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG2, 0x02);          // High Resolution mode      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG3, 0x00);          // Push-pull, active low interrupt      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG4, 0x01);          // Enable DRDY interrupt      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG5, 0x01);          // DRDY interrupt routed to INT1 - PTD4      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG1, 0x35);          // ODR = 3.125Hz, Reduced noise, Active mode   }   4. A simple accelerometer offset calibration method is implemented according to the AN4069.   void FXOS8700CQ_Accel_Calibration (void) {      char X_Accel_offset, Y_Accel_offset, Z_Accel_offset;        DataReady = 0;                while (!DataReady){}       // Is a first set of data ready?      DataReady = 0;        I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG1, 0x00);          // Standby mode             I2C_ReadMultiRegisters(FXOS8700CQ_I2C_ADDRESS, OUT_X_MSB_REG, 6, AccelMagData);          // Read data output registers 0x01-0x06                 Xout_Accel_14_bit = ((short) (AccelMagData[0]<<8 | AccelMagData[1])) >> 2;        // Compute 14-bit X-axis acceleration output value      Yout_Accel_14_bit = ((short) (AccelMagData[2]<<8 | AccelMagData[3])) >> 2;        // Compute 14-bit Y-axis acceleration output value      Zout_Accel_14_bit = ((short) (AccelMagData[4]<<8 | AccelMagData[5])) >> 2;        // Compute 14-bit Z-axis acceleration output value               X_Accel_offset = Xout_Accel_14_bit / 8 * (-1);         // Compute X-axis offset correction value      Y_Accel_offset = Yout_Accel_14_bit / 8 * (-1);         // Compute Y-axis offset correction value      Z_Accel_offset = (Zout_Accel_14_bit - SENSITIVITY_2G) / 8 * (-1);          // Compute Z-axis offset correction value               I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, OFF_X_REG, X_Accel_offset);                  I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, OFF_Y_REG, Y_Accel_offset);           I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, OFF_Z_REG, Z_Accel_offset);                    I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG1, 0x35);          // Active mode again }   5. A simple software calibration of magnetic hard-iron offset consists of recording the minimum and maximum magnetometer readings while rotating the board horizontally and vertically and then computing the calibration values from their average. The calibration time is defined by the number of samples taken during calibration (local variable “i” in the while loop) and selected ODR. In my example I use 94 samples at 3.125Hz, so the calibration routine takes 30s.   void FXOS8700CQ_Mag_Calibration (void) {      short Xout_Mag_16_bit_avg, Yout_Mag_16_bit_avg, Zout_Mag_16_bit_avg;          short Xout_Mag_16_bit_max, Yout_Mag_16_bit_max, Zout_Mag_16_bit_max;          short Xout_Mag_16_bit_min, Yout_Mag_16_bit_min, Zout_Mag_16_bit_min;      char i = 0;        DataReady = 0;            while (i < 94)             // This takes ~30s (94 samples * 1/3.125)      {               if (DataReady)             // Is a new set of data ready?         {                          DataReady = 0;                                                                                                                                                                I2C_ReadMultiRegisters(FXOS8700CQ_I2C_ADDRESS, MOUT_X_MSB_REG, 6, AccelMagData);         // Read data output registers 0x33 - 0x38                                   Xout_Mag_16_bit = (short) (AccelMagData[0]<<8 | AccelMagData[1]);        // Compute 16-bit X-axis magnetic output value              Yout_Mag_16_bit = (short) (AccelMagData[2]<<8 | AccelMagData[3]);        // Compute 16-bit Y-axis magnetic output value              Zout_Mag_16_bit = (short) (AccelMagData[4]<<8 | AccelMagData[5]);        // Compute 16-bit Z-axis magnetic output value                                            // Assign first sample to maximum and minimum values                        if (i == 0)              {                   Xout_Mag_16_bit_max = Xout_Mag_16_bit;                   Xout_Mag_16_bit_min = Xout_Mag_16_bit;                                                Yout_Mag_16_bit_max = Yout_Mag_16_bit;                   Yout_Mag_16_bit_min = Yout_Mag_16_bit;                                                Zout_Mag_16_bit_max = Zout_Mag_16_bit;                   Zout_Mag_16_bit_min = Zout_Mag_16_bit;              }                                       // Check to see if current sample is the maximum or minimum X-axis value                       if (Xout_Mag_16_bit > Xout_Mag_16_bit_max)    {Xout_Mag_16_bit_max = Xout_Mag_16_bit;}                       if (Xout_Mag_16_bit < Xout_Mag_16_bit_min)    {Xout_Mag_16_bit_min = Xout_Mag_16_bit;}                         // Check to see if current sample is the maximum or minimum Y-axis value                       if (Yout_Mag_16_bit > Yout_Mag_16_bit_max)    {Yout_Mag_16_bit_max = Yout_Mag_16_bit;}                       if (Yout_Mag_16_bit < Yout_Mag_16_bit_min)    {Yout_Mag_16_bit_min = Yout_Mag_16_bit;}                                       // Check to see if current sample is the maximum or minimum Z-axis value                       if (Zout_Mag_16_bit > Zout_Mag_16_bit_max)    {Zout_Mag_16_bit_max = Zout_Mag_16_bit;}                       if (Zout_Mag_16_bit < Zout_Mag_16_bit_min)    {Zout_Mag_16_bit_min = Zout_Mag_16_bit;}                              i++;          }           }        Xout_Mag_16_bit_avg = (Xout_Mag_16_bit_max + Xout_Mag_16_bit_min) / 2;            // X-axis hard-iron offset      Yout_Mag_16_bit_avg = (Yout_Mag_16_bit_max + Yout_Mag_16_bit_min) / 2;            // Y-axis hard-iron offset      Zout_Mag_16_bit_avg = (Zout_Mag_16_bit_max + Zout_Mag_16_bit_min) / 2;            // Z-axis hard-iron offset        // Left-shift by one as magnetometer offset registers are 15-bit only, left justified      Xout_Mag_16_bit_avg <<= 1;             Yout_Mag_16_bit_avg <<= 1;       Zout_Mag_16_bit_avg <<= 1;        I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG1, 0x00);          // Standby mode to allow writing to the offset registers        I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, MOFF_X_LSB_REG, (char) (Xout_Mag_16_bit_avg & 0xFF));             I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, MOFF_X_MSB_REG, (char) ((Xout_Mag_16_bit_avg >> 😎 & 0xFF));            I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, MOFF_Y_LSB_REG, (char) (Yout_Mag_16_bit_avg & 0xFF));      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, MOFF_Y_MSB_REG, (char) ((Yout_Mag_16_bit_avg >> 😎 & 0xFF));                   I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, MOFF_Z_LSB_REG, (char) (Zout_Mag_16_bit_avg & 0xFF));      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, MOFF_Z_MSB_REG, (char) ((Zout_Mag_16_bit_avg >> 😎 & 0xFF));              I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG1, 0x35);          // Active mode again       }   6. In the ISR, only the interrupt flag is cleared and the DataReady variable is set to indicate the arrival of new data.   void PORTD_IRQHandler() {      PORTD_PCR4 |= PORT_PCR_ISF_MASK;                // Clear the interrupt flag      DataReady = 1;       }   7. The output values from accelerometer registers 0x01 – 0x06 are first converted to signed 14-bit integer values and afterwards to real values in g’s. Similarly, the output values from magnetometer registers 0x33 – 0x38 are first converted to signed 16-bit integer values and afterwards to real values in microtesla (µT).   If the board remains flat, then the compass heading can be simply computed from the arctangent of the ratio of the two horizontal magnetic field components. I have used the atan2 function which returns the result in radians (-π and π), so I multiply it by 180/π to end up with degrees.   If you are interested in more complex algorithms for a tilt-compensated e-compass with soft-iron calibration, please refer to our eCompass software.   if (DataReady)             // Is a new set of data ready? {                  DataReady = 0;                                                                                                                      I2C_ReadMultiRegisters(FXOS8700CQ_I2C_ADDRESS, OUT_X_MSB_REG, 12, AccelMagData);         // Read data output registers 0x01-0x06 and 0x33 - 0x38                 // 14-bit accelerometer data      Xout_Accel_14_bit = ((short) (AccelMagData[0]<<8 | AccelMagData[1])) >> 2;        // Compute 14-bit X-axis acceleration output value      Yout_Accel_14_bit = ((short) (AccelMagData[2]<<8 | AccelMagData[3])) >> 2;        // Compute 14-bit Y-axis acceleration output value      Zout_Accel_14_bit = ((short) (AccelMagData[4]<<8 | AccelMagData[5])) >> 2;        // Compute 14-bit Z-axis acceleration output value                          // Accelerometer data converted to g's      Xout_g = ((float) Xout_Accel_14_bit) / SENSITIVITY_2G;        // Compute X-axis output value in g's      Yout_g = ((float) Yout_Accel_14_bit) / SENSITIVITY_2G;        // Compute Y-axis output value in g's      Zout_g = ((float) Zout_Accel_14_bit) / SENSITIVITY_2G;        // Compute Z-axis output value in g's                           // 16-bit magnetometer data                   Xout_Mag_16_bit = (short) (AccelMagData[6]<<8 | AccelMagData[7]);          // Compute 16-bit X-axis magnetic output value      Yout_Mag_16_bit = (short) (AccelMagData[8]<<8 | AccelMagData[9]);          // Compute 16-bit Y-axis magnetic output value      Zout_Mag_16_bit = (short) (AccelMagData[10]<<8 | AccelMagData[11]);        // Compute 16-bit Z-axis magnetic output value                                                     // Magnetometer data converted to microteslas      Xout_uT = (float) (Xout_Mag_16_bit) / SENSITIVITY_MAG;        // Compute X-axis output magnetic value in uT      Yout_uT = (float) (Yout_Mag_16_bit) / SENSITIVITY_MAG;        // Compute Y-axis output magnetic value in uT      Zout_uT = (float) (Zout_Mag_16_bit) / SENSITIVITY_MAG;        // Compute Z-axis output magnetic value in uT                      Heading = atan2 (Yout_uT, Xout_uT) * 180 / PI;         // Compute Yaw angle }     8. The calculated values can be watched in the "Variables" window on the top right of the Debug perspective or in the FreeMASTER application. To open and run the FreeMASTER project, install the FreeMASTER 1.4 application and FreeMASTER Communication Driver.       Attached you can find the complete source code written in the CW for MCU's v10.5 including the FreeMASTER project.   If there are any questions regarding this simple application, please feel free to ask below. Your feedback or suggestions are also welcome.   Regards, Tomas Original Attachment has been moved to: FRDM-KL25Z-FXOS8700CQ-Basic-read-using-I2C-and-interrupt.zip Original Attachment has been moved to: FreeMASTER---FRDM-KL25Z-FXOS8700CQ-Basic-read-using-I2C-and-interrupt.zip
View full article
Hi Everyone,   If you are interested in a simple bare metal example code illustrating the use of the accelerometer motion detection function, please find below one of my examples I created for the FXLS8471Q accelerometer while working with the NXP FRDM-KL25Z platform and FRDMSTBC-A8471 board.   The FXLS8471Q is set to detect motion exceeding 315mg for a minimum period of 40 ms on either the X or Y axis. Once an event is triggered, an interrupt will be generated on the INT1 pin:   void FXLS8471Q_Init (void) { FXLS8471Q_WriteRegister(FT_MT_THS_REG, 0x85); // Set threshold to 312.5mg (5 x 62.5mg ) FXLS8471Q_WriteRegister(FF_MT_COUNT_REG, 0x02); // Set debounce timer period to 40ms FXLS8471Q_WriteRegister(FF_MT_CFG_REG, 0xD8); // Latch enabled, motion detection enabled for X and Y axis FXLS8471Q_WriteRegister(CTRL_REG4, 0x04); // Motion interrupt enabled FXLS8471Q_WriteRegister(CTRL_REG5, 0x04); // Route motion interrupt to INT1 - PTD4 FXLS8471Q_WriteRegister(CTRL_REG1, 0x29); // ODR = 12.5Hz, Active mode }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍     In the ISR, only the interrupt flag is cleared and the FF_MT_SRC (0x16) register is read in order to clear the SRC_FFMT flag in the INT_SOURCE register and deassert the INT1 pin, as shown on the screenshot below.   void PORTD_IRQHandler() { PORTD_PCR4 |= PORT_PCR_ISF_MASK; // Clear the interrupt flag IntSource = FXLS8471Q_ReadRegister(FF_MT_SRC_REG); // Read the FF_MT_SRC register to clear the SRC_FFMT flag in the INT_SOURCE register EventCounter++; }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍       Attached you can find the complete source code. If there are any questions regarding this simple example code, please feel free to ask below.    Regards, Tomas
View full article
Hi Everyone,   As I am often asked for a simple bare metal example code illustrating the use of the accelerometer transient detection function, I have decided to share here one of my examples I created for the FXLS8471Q accelerometer while working with the NXP FRDM-KL25Z platform and FRDM-FXS-MULT2-B sensor expansion board.   This example code complements the Python code snippet from the AN4693. The FXLS8471Q is set for detection of an “instantaneous” acceleration change exceeding 315mg for a minimum period of 40 ms on either the X or Y axes. Once an event is triggered, an interrupt will be generated on the INT1 pin:   void FXLS8471Q_Init (void) { FXLS8471Q_WriteRegister(TRANSIENT_THS_REG, 0x85); // Set threshold to 312.5mg (5 x 62.5mg ) FXLS8471Q_WriteRegister(TRANSIENT_COUNT_REG, 0x02); // Set debounce timer period to 40ms FXLS8471Q_WriteRegister(TRANSIENT_CFG_REG, 0x16); // Enable transient detection for X and Y axis, latch enabled FXLS8471Q_WriteRegister(CTRL_REG4, 0x20); // Acceleration transient interrupt enabled FXLS8471Q_WriteRegister(CTRL_REG5, 0x20); // Route acceleration transient interrupt to INT1 - PTA5 FXLS8471Q_WriteRegister(CTRL_REG1, 0x29); // ODR = 12.5Hz, Active mode } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍     In the ISR, only the interrupt flag is cleared and the TRANSIENT_SRC (0x1E) register is read in order to clear the SRC_TRANS status bit and deassert the INT1 pin, as shown on the screenshot below.   void PORTA_IRQHandler() { PORTA_PCR5 |= PORT_PCR_ISF_MASK; // Clear the interrupt flag IntSource = FXLS8471Q_ReadRegister(TRANSIENT_SRC_REG); // Read the TRANSIENT_SRC register to clear the SRC_TRANS flag in the INT_SOURCE register EventCounter++; } ‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍       Attached you can find the complete source code. If there are any questions regarding this simple example code, please feel free to ask below. Your feedback or suggestions are also welcome.   Regards, Tomas
View full article
Hi Everyone,   If you are interested in a simple bare metal example code illustrating the use of the FXLS8471Q orientation detection function, please find below one of my examples I created for the FXLS8471Q accelerometer while working with the NXP FRDM-KL25Z platform and FRDMSTBC-A8471 board.   This example code complements the code snippet from the  AN4068.   void FXLS8471Q_Init (void) { FXLS8471Q_WriteRegister(CTRL_REG1, 0x00); // Standby mode FXLS8471Q_WriteRegister(PL_CFG_REG, 0x40); // Enable orientation detection FXLS8471Q_WriteRegister(PL_BF_ZCOMP_REG, 0x43); // Back/Front trip point set to 75°, Z-lockout angle set to 25° FXLS8471Q_WriteRegister(P_L_THS_REG, 0x14); // Threshold angle = 45°, hysteresis = 14° FXLS8471Q_WriteRegister(PL_COUNT_REG, 0x05); // Debounce counter set to 100ms at 50Hz FXLS8471Q_WriteRegister(CTRL_REG3, 0x00); // Push-pull, active low interrupt FXLS8471Q_WriteRegister(CTRL_REG4, 0x10); // Orientation interrupt enabled FXLS8471Q_WriteRegister(CTRL_REG5, 0x10); // Route orientation interrupt to INT1 - PTD4 FXLS8471Q_WriteRegister(CTRL_REG1, 0x21); // ODR = 50Hz, Active mode }‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍     In the ISR, only the interrupt flag is cleared and the PL_STATUS (0x10) register is read in order to:   - Clear the SRC_LNDPRT flag in the INT_SOURCE register and deassert the INT1 pin, as shown on the screenshot below. - Get orientation information. 0x82 in this example corresponds to "Portrait down" orientation.   void PORTD_IRQHandler() { PORTD_PCR4 |= PORT_PCR_ISF_MASK; // Clear the interrupt flag PL_Status = FXLS8471Q_ReadRegister(PL_STATUS_REG); // Read the PL_STATUS register to clear the SRC_LNDPRT flag in the INT_SOURCE register }‍‍‍‍‍‍‍‍‍‍       Attached you can find the complete source code. If there are any questions regarding this simple example code, please feel free to ask below.    Regards, Tomas
View full article
Hi Everyone,   I would like to share here one of my examples I created for the FXLS8471Q accelerometer while working with the Freescale FRDM-KL25Z platform and FRDM-FXS-MULT2-B sensor expansion board. It illustrates the use of the embedded FIFO buffer to collect the 14-bit acceleration data that are read from the FIFO using an interrupt technique through the SPI interface. For details on the configurations of the FIFO buffer as well as more specific examples and application benefits, please refer to the AN4073.   The FXLS8471Q is initialized as follows:   void FXLS8471Q_Init (void) {/* The software reset does not work properly in SPI mode as described in Appendix A of the FXLS8471Q data sheet. Therefore the following piece of the code is not used. I have shortened R46 on the FRDM-FXS-MULTI-B board to activate a hardware reset. FXLS8471Q_WriteRegister(CTRL_REG2, 0x40); // Reset all registers to POR values */   FXLS8471Q_WriteRegister(CTRL_REG1, 0x00); // Standby mode FXLS8471Q_WriteRegister(F_SETUP_REG, 0xA0); // FIFO Fill mode, 32 samples   FXLS8471Q_WriteRegister(CTRL_REG4, 0x40); // Enable FIFO interrupt, push-pull, active low   FXLS8471Q_WriteRegister(CTRL_REG5, 0x40); // Route the FIFO interrupt to INT1 - PTA5   FXLS8471Q_WriteRegister(CTRL_REG1, 0x19); // ODR = 100Hz, Active mode }       In the ISR, only the interrupt flag is cleared and the FIFO_DataReady variable is set to indicate that the FIFO is full.   void PORTA_IRQHandler() { PORTA_PCR5 |= PORT_PCR_ISF_MASK; // Clear the interrupt flag FIFO_DataReady = 1; }       Once the FIFO_DataReady variable is set, the STATUS register (0x00) is read to clear the FIFO interrupt status bit and deassert the INT1 pin. Afterwars the FIFO is read using a 192-byte (3 x 2 x 32 bytes) burst read starting from the OUT_X_MSB register (0x01). Then the raw acceleration data are converted to signed 14-bit values and real values in g’s.   if (FIFO_DataReady) { FIFO_DataReady = 0; FIFO_Status = FXLS8471Q_ReadRegister(STATUS_REG); // Read the Status register to clear the FIFO interrupt status bit FXLS8471Q_ReadMultiRegisters(OUT_X_MSB_REG, 6*Watermark_Val, AccelData); // Read the FIFO using a burst read     for (i = 0; i < Watermark_Val; i++)   { // 14-bit accelerometer data   Xout_Accel_14_bit[i] = ((short) (AccelData[0 + i*6]<<8 | AccelData[1 + i*6])) >> 2; // Compute 14-bit X-axis acceleration output values   Yout_Accel_14_bit[i] = ((short) (AccelData[2 + i*6]<<8 | AccelData[3 + i*6])) >> 2; // Compute 14-bit Y-axis acceleration output values  Zout_Accel_14_bit[i] = ((short) (AccelData[4 + i*6]<<8 | AccelData[5 + i*6])) >> 2; // Compute 14-bit Z-axis acceleration output values   // Accelerometer data converted to g's   Xout_g[i] = ((float) Xout_Accel_14_bit[i]) / SENSITIVITY_2G; // Compute X-axis output values in g's  Yout_g[i] = ((float) Yout_Accel_14_bit[i]) / SENSITIVITY_2G; // Compute Y-axis output values in g's   Zout_g[i] = ((float) Zout_Accel_14_bit[i]) / SENSITIVITY_2G; // Compute Z-axis output values in g's   } }       Deassertion of the INT1 pin after reading the STATUS register (0x00).       ODR is set to 100Hz, so the FIFO is read every 320 ms (10 ms x 32 samples).       The calculated values can be watched in the "Variables" window on the top right of the Debug perspective.       Attached you can find the complete source code written in the CW for MCU's 10.6. If there are any questions regarding this simple example project, please feel free to ask below. Your feedback or suggestions are also welcome.   Regards, Tomas Original Attachment has been moved to: FRDM-KL25Z-FXLS8471Q-FIFO.rar
View full article
FRDM-STBC-AGM01: 9-Axis Inertial Measurement Sensor Board FRDM-KL25Z FRDM-STBC-AGM01 - Example project in KDS 3.0.0 using KSDK 1.2.0 and Processor Expert FRDM-STBC-AGM01 - Bare metal example project   FRDMSTBC-A8471: 3-Axis Accelerometer Sensor Toolbox Development Board FRDMSTBC-A8471 - Bare metal example project FRDMSTBC-A8471 - Example project in KDS 3.0.2 using KSDK 2.0 FXLS8471Q Auto-sleep with Transient threshold trigger    MPL3115A2: 20 to 110kPa, Absolute Digital (I 2 C) Pressure Sensor MPL3115A2 - Bare metal example project FRDMKL25-P3115 - Example project in KDS 3.0.2 using KSDK 2.0 https://community.nxp.com/docs/DOC-345632    MPL115A1: 50 to 115kPa, Absolute Digital (SPI) Pressure Sensor MPL115A1- Bare metal example project    FXOS8700CQ: Digital (I 2 C/SPI) Sensor - 3-Axis Accelerometer (±2g/±4g/±8g) + 3-Axis Magnetometer FXOS8700CQ - Bare metal example project FXOS8700CQ - Magnetic threshold detection function example code  FXOS8700CQ - Auto-sleep with Magnetic threshold trigger    FXLS8471Q: ±2g/±4g/±8g, 3-Axis, 14-Bit Digital (I 2 C/SPI) Accelerometer FXLS8471Q - Bare metal example project FXLS8471Q - FIFO Fill mode example code FXLS8471Q - Accelerometer vector-magnitude function example code FXLS8471Q - Accelerometer transient detection function example code FXLS8471Q - Accelerometer motion detection function example code  FXLS8471Q - Accelerometer orientation detection function example code    MMA8652FC: ±2g/±4g/±8g, 3-Axis, 12-Bit Digital (I 2 C) Accelerometer MMA8652FC - Bare metal example project MMA8652FC - Auto-WAKE/SLEEP mode   MMA8451Q: ±2g/±4g/±8g, 3-Axis, 14-bit Digital (I 2 C) Accelerometer MMA8451Q - Bare metal example project MMA8451Q - Single Tap Detection Bare metal example project FRDM-KL27Z MMA8451Q - How to build and run an ISSDK based example project    MMA8491Q: ±8g, 3-Axis, 14-bit Digital (I 2 C) Accelerometer/Tilt Sensor MMA8491Q - Acceleration data streaming using the PIT on the Kinetis KL25Z MCU   FXLN83xxQ: 3-Axis, Low-Power, Analog Accelerometer FXLN8371Q - Bare metal example project   FXAS21002C: 3-Axis Digital (I 2 C/SPI) Gyroscope FXAS21000 – Bare metal example project FXAS21002C - Angular rate threshold detection function example code   MAG3110FC: 3-Axis Digital (I 2 C) Magnetometer MAG3110FC – Bare metal example project   LM75A: Digital temperature sensor and thermal watchdog LM75A - Temperature data streaming using the PIT on the Kinetis KL25Z MCU
View full article
Hi Everyone, In this document I would like to go through a simple example code I created for the FRDMKL25-A8471 kit using the KDS 3.0.2 and KSDK 2.0. I will not cover the Sensor Toolbox – CE and Intelligent Sensing Framework (ISF) which primarily support this kit. The FreeMASTER tool is used to visualize the acceleration data that are read from the FXLS8471Q using an interrupt technique through the SPI interface. This example illustrates: 1. Initialization of the MKL25Z128 MCU (mainly PORT and SPI modules). 2. SPI data write and read operations. 3. Initialization of the FXLS8471Q to achieve the highest resolution. 4. Output data reading using an interrupt technique. 5. Conversion of the output values from registers 0x01 – 0x06 to real acceleration values in g’s. 6. Visualization of the output values in the FreeMASTER tool. 1. As you can see in the FRDMSTBC-A8471/FRDM-KL25Z schematics and the image below, SPI signals are routed to the SPI0 module of the KL25Z MCU and the INT1 output is connected to the PTD4 pin. The PTD0 pin (Chip Select) is not controlled automatically by SPI0 module, hence it is configured as a general-purpose output. The INT1 output of the FXLS8471Q is configured as a push-pull active-low output, so the corresponding PTD4 pin configuration is GPIO with an interrupt on falling edge. The configuration is done in the BOARD_InitPins() function using the NXP Pins Tool for Kinetis MCUs. void BOARD_InitPins(void) {    CLOCK_EnableClock(kCLOCK_PortD);                                          /* Port D Clock Gate Control: Clock enabled */    CLOCK_EnableClock(kCLOCK_Spi0);                                           /* SPI0 Clock Gate Control: Clock enabled */    PORT_SetPinMux(PORTD, PIN1_IDX, kPORT_MuxAlt2);                           /* PORTD1 (pin 74) is configured as SPI0_SCK */    PORT_SetPinMux(PORTD, PIN2_IDX, kPORT_MuxAlt2);                           /* PORTD2 (pin 75) is configured as SPI0_MOSI */    PORT_SetPinMux(PORTD, PIN3_IDX, kPORT_MuxAlt2);                           /* PORTD3 (pin 76) is configured as SPI0_MISO */    PORT_SetPinMux(PORTD, PIN0_IDX, kPORT_MuxAsGpio);                         /* PORTD0 (pin 73) is configured as PTD0 */    GPIO_PinInit(GPIOD, PIN0_IDX, &CS_config);                                /* PTD0 = 1 (Chip Select inactive) */       PORT_SetPinMux(PORTD, PIN4_IDX , kPORT_MuxAsGpio);                        /* PORTD4 (pin 77) is configured as PTD4 */    PORT_SetPinInterruptConfig(PORTD, PIN4_IDX, kPORT_InterruptFallingEdge);  /* PTD4 is configured for falling edge interrupts */      NVIC_EnableIRQ(PORTD_IRQn);                                               /* Enable PORTD interrupt on NVIC */ } The SPI_INIT() function is used to enable and configure the SPI0 module. The FXLS8471Q uses the ‘Mode 0′ SPI protocol, which means that an inactive state of clock signal is low and data are captured on the leading edge of clock signal and changed on the falling edge. The SPI clock is 500 kHz. void SPI_Init(void) {    uint32_t sourceClock = 0U;    sourceClock = CLOCK_GetFreq(kCLOCK_BusClk);    spi_master_config_t masterConfig = {    .enableMaster = true,    .enableStopInWaitMode = false,    .polarity = kSPI_ClockPolarityActiveHigh,    .phase = kSPI_ClockPhaseFirstEdge,    .direction = kSPI_MsbFirst,    .outputMode = kSPI_SlaveSelectAsGpio,    .pinMode = kSPI_PinModeNormal,    .baudRate_Bps = 500000U     };    SPI_MasterInit(SPI0, &masterConfig, sourceClock); } 2. The falling edge on the CS pin starts the SPI communication. A write operation is initiated by transmitting a 1 for the R/W bit. Then the 8-bit register address, ADDR[7:0] is encoded in the first and second serialized bytes. Data to be written starts in the third serialized byte. The order of the bits is as follows: Byte 0: R/W, ADDR[6], ADDR[5], ADDR[4], ADDR[3], ADDR[2], ADDR[1], ADDR[0] Byte 1: ADDR[7], X, X, X, X, X, X, X Byte 2: DATA[7], DATA[6], DATA[5], DATA[4], DATA[3], DATA[2], DATA[1], DATA[0] The rising edge on the CS pin stops the SPI communication. Below is the write operation which writes the value 0x3D to the CTRL_REG1 (0x3A). Similarly a read operation is initiated by transmitting a 0 for the R/W bit. Then the 8-bit register address, ADDR[7:0] is encoded in the first and second serialized bytes. The data is read from the MISO pin (MSB first). The screenshot below shows the read operation which reads the correct value 0x6A from the WHO_AM_I register (0x0D). Multiple read operations are performed similar to single read except bytes are read in multiples of eight SCLK cycles. The register address is auto incremented so that every eighth next clock edges will latch the MSB of the next register. A burst read of 6 bytes from registers 0x01 to 0x06 is shown below. It also shows how the INT1 pin is automatically cleared by reading the acceleration output data. 3. At the beginning of the initialization, all FXLS8471Q registers are reset to their default values by setting the RST bit of the CTRL_REG2 register. The dynamic range is set to ±2g and to achieve the highest resolution, the LNOISE bit is set and the lowest ODR (1.56Hz) and the High Resolution mode are selected (more details in AN4075). The DRDY interrupt is enabled and routed to the INT1 interrupt pin that is configured to be a push-pull, active-low output. void FXLS8471Q_Init (void) {    FXLS8471Q_WriteRegister(CTRL_REG2, 0x40);            /* Reset all registers to POR values */    Pause(0xC62);                                        /* ~1ms delay */    FXLS8471Q_WriteRegister(CTRL_REG2, 0x02);            /* High Resolution mode */    FXLS8471Q_WriteRegister(CTRL_REG3, 0x00);            /* Push-pull, active low interrupt */    FXLS8471Q_WriteRegister(CTRL_REG4, 0x01);            /* Enable DRDY interrupt */    FXLS8471Q_WriteRegister(CTRL_REG5, 0x01);            /* DRDY interrupt routed to INT1 - PTD4 */    FXLS8471Q_WriteRegister(CTRL_REG1, 0x3D);            /* ODR = 1.56Hz, Reduced noise, Active mode */ } 4. In the ISR, only the interrupt flag is cleared and the DataReady variable is set to indicate the arrival of new data. void PORTD_IRQHandler(void) {    PORT_ClearPinsInterruptFlags(PORTD, 1<<4);           /* Clear the interrupt flag */    DataReady = 1; } 5. In the main loop, the DataReady variable is periodically checked and if it is set, the accelerometer registers 0x01 – 0x06 are read and then converted to signed 14-bit values and real values in g’s. if (DataReady)                                                        /* Is a new set of data ready? */ {    DataReady = 0;    FXLS8471Q_ReadMultiRegisters(OUT_X_MSB_REG, 6, AccData);           /* Read data output registers 0x01-0x06 */    Xout_14_bit = ((int16_t) (AccData[0]<<8 | AccData[1])) >> 2;       /* Compute 14-bit X-axis output value */    Yout_14_bit = ((int16_t) (AccData[2]<<8 | AccData[3])) >> 2;       /* Compute 14-bit Y-axis output value */    Zout_14_bit = ((int16_t) (AccData[4]<<8 | AccData[5])) >> 2;       /* Compute 14-bit Z-axis output value */    Xout_g = ((float) Xout_14_bit) / SENSITIVITY_2G;                   /* Compute X-axis output value in g's */    Yout_g = ((float) Yout_14_bit) / SENSITIVITY_2G;                   /* Compute Y-axis output value in g's */    Zout_g = ((float) Zout_14_bit) / SENSITIVITY_2G;                   /* Compute Z-axis output value in g's */ } 6. The calculated values can be watched in the Debug perspective or in the FreeMASTER application. To open and run the FreeMASTER project, install the FreeMASTER 2.0 application and FreeMASTER Communication Driver. Attached you can find the complete source code written in the KDS 3.0.2 including the FreeMASTER project. If there are any questions regarding this simple application, do not hesitate to ask below. Your feedback or suggestions are also welcome. Best regards, Tomas
View full article
Hi Everyone, This tutorial is a guide on how to create a simple application in the Kinetis Design Studio that reads the data from both sensors on the FRDM-STBC-AGM01 board​ using an interrupt technique through the I 2 C interface. The Processor Expert is used to configure the I 2 C interface and GPIO on the MKL25Z128 MCU. I will not cover the Sensor Fusion libraryand the ISF​. Before you begin please make sure that both the Kinetis Design Studio (Eclipse based) and the Kinetis SDK are setup and you can already compile and debug code. If not, please refer to Erich's blog: Tutorial: Adafruit WS2812B NeoPixels with the Freescale FRDM-K64F Board – Part 2: Software Tools | MCU on Eclipse http://centaurian.co.uk/2015/05/22/toolchain-ksdk-1-2-0-with-eclipse-4-4-luna-and-gnu-arm-plugin/ 1. Create a new project in KDS Within KDS, click on "File" menu item and select "New" > "Kinetis Project" Name and set location of your project. I use the default location under the workspace area. Click Next. Select the development board used (in my case it is the FRDM-KL25Z) and click Next. Select “KSDK 1.2.0”. Set location to KSDK path, I use an absolute path. The location of my KSDK is in the default location where KSDK would install to. Ensure “Processor Expert” checkbox is checked. Press Next. Make sure that “GNU C Compiler” is selected. Click the "Finish" button. 2. Open Processor Expert Open the Processor Expert perspective, this should be a button on the top right hand side of Eclipse. If it is not there, try clicking on the “Open Perspective” button and then selecting “Processor Expert” in the form that appears. 3. Add I2C component Click on the “Components Library” tab, search for the component “fsl_i2c” and double click on it. Select the "i2cCom1:fsl_i2c" in the Components window. In the "Component Inspector" tab configure the I2C component. As you can see in the FRDM-STBC-AGM01 schematic, with jumpers J6 and J7 in their default position (2-3), the I 2 C signals are routed to the I2C1 module (PTC1 and PTC2 pins) of the KL25Z MCU. The 7-bit I 2 C slave address of the FXOS8700CQ is 0x1E (to enter hex values, switch the format to the ‘H’ mode) since both SA0 and SA1 pins are shorted to GND. The address of the FXAS21002C is 0x20 since SA0 pin is also shorted to GND. The I2C bus clock frequency is set to 400 kHz. 4. Add GPIO component Click on the “Components Library” tab, search for the component “fsl_gpio” and double click on it. Select the "gpio1:fsl_gpio" in the Components window. In the "Component Inspector" tab configure the GPIO component. The INT1_8700 output is connected to the PTD4 pin and the INT1_21002 pin to the PTA5 pin of the KL25Z MCU. These both interrupt pins are configured as push-pull active-low outputs, so the corresponding PTD4/PTA5 pin configuration is GPIO with an interrupt on falling edge. To enable both the PORTA and PORTD interrupts, select the “Events” tab and then select “generate code” next to PORTA IRQ and PORTD IRQ handlers. 5. Add Wait component​ Click on the “Components Library” tab, search for the component “Wait” and double click on it. At this point we have done all we can within Processor Expert. Make sure you save all on the project at this point then on the Components window, click on the "Generate code" button. 6. Add your code Here is the initialization of the FXOS8700CQ and FXAS21002C. /****************************************************************************** * FXOS8700CQ initialization function ******************************************************************************/ void FXOS8700CQ_Init (void) {   FXOS8700CQ_WriteRegister(CTRL_REG2, 0x40); // Reset all registers to POR values   WAIT1_Waitms(1);   FXOS8700CQ_WriteRegister(XYZ_DATA_CFG_REG, 0x00); // +/-2g range with 0.244mg/LSB   FXOS8700CQ_WriteRegister(M_CTRL_REG1, 0x1F); // Hybrid mode (accelerometer + magnetometer), max OSR   FXOS8700CQ_WriteRegister(M_CTRL_REG2, 0x20); // M_OUT_X_MSB register 0x33 follows the OUT_Z_LSB register 0x06 (used for burst read)   FXOS8700CQ_WriteRegister(CTRL_REG2, 0x02); // High Resolution mode   FXOS8700CQ_WriteRegister(CTRL_REG3, 0x00); // Push-pull, active low interrupt   FXOS8700CQ_WriteRegister(CTRL_REG4, 0x01); // Enable DRDY interrupt   FXOS8700CQ_WriteRegister(CTRL_REG5, 0x01); // DRDY interrupt routed to INT1 - PTD4   FXOS8700CQ_WriteRegister(CTRL_REG1, 0x25); // ODR = 25Hz, Reduced noise, Active mode } /****************************************************************************** * FXAS21002C initialization function ******************************************************************************/ void FXAS21002C_Init (void) {   FXAS21002C_WriteRegister(GYRO_CTRL_REG1, 0x40); // Reset all registers to POR values   WAIT1_Waitms(1);   FXAS21002C_WriteRegister(GYRO_CTRL_REG0, 0x03); // High-pass filter disabled, +/-250 dps range -> 7.8125 mdps/LSB = 128 LSB/dps   FXAS21002C_WriteRegister(GYRO_CTRL_REG2, 0x0C); // Enable DRDY interrupt, mapped to INT1 - PTA5, push-pull, active low interrupt   FXAS21002C_WriteRegister(GYRO_CTRL_REG1, 0x16); // ODR = 25Hz, Active mode } In the ISRs (look for the file Events.c), only the interrupt flags are cleared and the DataReady variables are set to indicate the arrival of new data. void PORTA_IRQHandler(void) {   /* Clear interrupt flag.*/   PORT_HAL_ClearPortIntFlag(PORTA_BASE_PTR);   /* Write your code here ... */   FXAS21002C_DataReady = 1; } void PORTD_IRQHandler(void) {   /* Clear interrupt flag.*/   PORT_HAL_ClearPortIntFlag(PORTD_BASE_PTR);   /* Write your code here ... */   FXOS8700CQ_DataReady = 1; } The output values from accelerometer registers 0x01 – 0x06 are first converted to signed 14-bit integer values and afterwards to real values in g’s. Similarly, the output values from magnetometer registers 0x33 – 0x38 are first converted to signed 16-bit integer values and afterwards to real values in microtesla (µT). if (FXOS8700CQ_DataReady)         // Is a new set of accel+mag data ready? {    FXOS8700CQ_DataReady = 0;       FXOS8700CQ_ReadRegisters(OUT_X_MSB_REG, 12, AccelMagData);         // Read FXOS8700CQ data output registers 0x01-0x06 and 0x33 - 0x38       // 14-bit accelerometer data    Xout_Accel_14_bit = ((int16_t) (AccelMagData[0]<<8 | AccelMagData[1])) >> 2;             // Compute 14-bit X-axis acceleration output value    Yout_Accel_14_bit = ((int16_t) (AccelMagData[2]<<8 | AccelMagData[3])) >> 2;             // Compute 14-bit Y-axis acceleration output value    Zout_Accel_14_bit = ((int16_t) (AccelMagData[4]<<8 | AccelMagData[5])) >> 2;             // Compute 14-bit Z-axis acceleration output value       // Accelerometer data converted to g's    Xout_g = ((float) Xout_Accel_14_bit) / SENSITIVITY_2G;         // Compute X-axis output value in g's    Yout_g = ((float) Yout_Accel_14_bit) / SENSITIVITY_2G;         // Compute Y-axis output value in g's    Zout_g = ((float) Zout_Accel_14_bit) / SENSITIVITY_2G;         // Compute Z-axis output value in g's    // 16-bit magnetometer data    Xout_Mag_16_bit = (int16_t) (AccelMagData[6]<<8 | AccelMagData[7]);        // Compute 16-bit X-axis magnetic output value    Yout_Mag_16_bit = (int16_t) (AccelMagData[8]<<8 | AccelMagData[9]);        // Compute 16-bit Y-axis magnetic output value    Zout_Mag_16_bit = (int16_t) (AccelMagData[10]<<8 | AccelMagData[11]);      // Compute 16-bit Z-axis magnetic output value    // Magnetometer data converted to microteslas    Xout_uT = (float) (Xout_Mag_16_bit) / SENSITIVITY_MAG;             // Compute X-axis output magnetic value in uT    Yout_uT = (float) (Yout_Mag_16_bit) / SENSITIVITY_MAG;             // Compute Y-axis output magnetic value in uT    Zout_uT = (float) (Zout_Mag_16_bit) / SENSITIVITY_MAG;             // Compute Z-axis output magnetic value in uT } Similarly, the output values from gyroscope registers 0x01 – 0x06 are first converted to signed 16-bit integer values and afterwards to real values in degrees per second. Temperature is also read out from the 0x12 register. if (FXAS21002C_DataReady)         // Is a new set of gyro data ready? {    FXAS21002C_DataReady = 0;    FXAS21002C_ReadRegisters(GYRO_OUT_X_MSB_REG, 6, GyroData);         // Read FXAS21002C data output registers 0x01-0x06    // 16-bit gyro data    Xout_Gyro_16_bit = (int16_t) (GyroData[0]<<8 | GyroData[1]);         // Compute 16-bit X-axis output value    Yout_Gyro_16_bit = (int16_t) (GyroData[2]<<8 | GyroData[3]);         // Compute 16-bit Y-axis output value    Zout_Gyro_16_bit = (int16_t) (GyroData[4]<<8 | GyroData[5]);         // Compute 16-bit Z-axis output value    // Gyro data converted to dps    Roll = (float) (Xout_Gyro_16_bit) / SENSITIVITY_250;               // Compute X-axis output value in dps    Pitch = (float) (Yout_Gyro_16_bit) / SENSITIVITY_250;              // Compute Y-axis output value in dps    Yaw = (float) (Zout_Gyro_16_bit) / SENSITIVITY_250;                // Compute Z-axis output value in dps    // Temperature data    FXAS21002C_ReadRegisters(GYRO_TEMP_REG, 1, GyroData);    Temp = (int8_t) (GyroData[0]); } The complete project including the I2C communication routines and sensor's header files is attached. 6. Build and debug the project To build the project, select the root folder of the project in the Project Explorer view and click the "Hammer" icon to build it. If everything goes well, no errors are shown in the "Problems" view: The .elf (binary) file has been created inside the "Debug" folder: Connect the SDA port on the FRDM-KL25Z board to a USB port on your computer. To debug the project for the first time, select the root folder of the project in the Project Explorer view and open the "Debug Configurations" window. Select the ""GDB PEMicro Interface Debugging" and click the "New launch configuration" icon. In the "Debugger" tab, select the "OpenSDA Embedded Debug - USB Port" interface and the KL25Z128M4 as a target device. Click the "Debug" button. Click the "Resume" button to run the project. You can pause the execution and look at the data using the "Suspend" button. Now you can edit, build and debug the project again. As we used a debug configuration, it is listed under the "Debug" icon, so you can start it from there. Well done if you managed to follow along and get it all working. As a bonus I have attached the FreeMASTER project that will allow you to visualize the gathered data. If there are any questions regarding this simple project, do not hesitate to ask below. Your feedback or suggestions are also welcome. Regards, Tomas
View full article
Hi Everyone, In my previous tutorial, I demonstrated how to import an ISSDK based example project into MCUXpresso IDE, build and run it on the Freedom board (FRDM-KL27Z). If you want to visualize/log sensor data, easily change sensor settings (ODR, Range, Power Mode) or directly read and write sensor registers, you can use the Freedom Sensor Toolbox-Community Edition (STB-CE) as described below or in the STBCEUG. 1. Connect the SDA port (J13) on the FRDM-KL27Z board to a USB port on your computer. 2. Open STB-CE GUI by double clicking the Freedom Sensor Toolbox (CE) shortcut located on your desktop. 3. Select "Out of Box Sensor Demonstration". 4. Select the Project to be launched and click on Continue. Base Board Name – FRDM-KL27Z Shield Board Name – OnBoard Project Name – MMA8451 Accelerometer Demo 5. The ISSDK-based MMA8451 Accelerometer Demo firmware is loaded to the KL27Z MCU and the MMA8451 Accelerometer Demo v1.0 GUI launched. 6. In the Main screen you can change basic MMA8451Q accelerometer settings (ODR, Range, Power Mode), enable embedded functions (Landsacpe/Portrait, Pulse/Tap, Freefall, Transient), start/stop accelerometer data streaming and/or logging.   7. The Register screen (MMA8451) provides low-level access (R/W) to the MMA8451Q registers along with a detailed description of the selected register. 8. To change the bit value, simply click on the corresponding cell (make sure you selected the Standby mode before writing a new value to the selected register). I hope you find this simple document useful. f there are any questions, please feel free to ask below.  Regards, Tomas
View full article
Hi Everyone, This tutorial is a detailed guide on how to import an ISSDK based example project (e.g. mma845x_interrupt) into MCUXpresso IDE, build and run it on the Freedom board (e.g. FRDM-KL27Z). If you intend to use another ISSDK example project/board, you can always follow this guide. A complete list of MCU boards, sensor kits and sensors supported by ISSDK is available in the ISSDK Release notes. 1. Download the FRDM-KL27Z SDK Open a web browser, navigate to the MCUXpresso homepage and select “Login to view configurations” to start a new configuration. You will be redirected to login to nxp.com. Enter your account information or register for a new account. Back on the MCUXpresso homepage, select the drop-down box to create a New Configuration. Select the board (FRDM-KL27Z) from the list and provide a name for the configuration. Select “Specify Additional Configuration Settings” to choose the Host OS, Toolchain (MCUXpresso IDE) and Middleware (ISSDK). Select Configuration Settings: Host OS (example: Windows) Toolchain/IDE (MCUXpresso IDE) Middleware (ISSDK) Once the configurations are set, select “Go to SDK Builder”.   Select “Request Build” to download the SDK. Once the build request is completed, download the SDK. Agree to Software Terms and Conditions. Unzip SDK to a folder (e.g. SDK_2.2.1_FRDM-KL27Z). 2. Import the SDK_2.1.1_FRDM-KL27Z into MCUXpresso IDE Open MCUXpresso IDE. Set the workspace directory of your choice and click on OK. Switch to the Installed SDKs view within the MCUXpresso IDE window. Open Windows Explorer, and drag and drop the SDK_2.2.1_FRDM-KL27Z (unzipped) file into the installed SDKs view. You will get the following pop-up so click on OK to continue the import.   The installed SDK will appear in the Installed SDKs view. 3. Import and build the ISSDK based mma845x_interrupt example project Find the Quickstart Panel in the lower left hand corner and select Import SDK example(s) Click on the FRDM-KL27Z board and then click on Next. Use the arrow button to expand the issdk_examples category, and then click the checkbox next to mma845x_interrupt to select that project. Then, click on Next. On the next screen, click the checkbox to Redirect printf/scanf to UART so that the terminal output gets sent out the UART instead of using semi-hosting through the debugger. Then click on Finish. Now build the project by clicking on the project name in the Project Explorer view and then click on the Build icon in the Quickstart Panel. You can see the status of the build in the Console view. 4. Run the mma845x_interrupt example project   Now that the project has been compiled, we can flash it to the board and run it. Make sure the FRDM-KL27Z board is plugged in, and click on Debug ‘frdmkl27z_issdk_examples_sensors_mma8451q_mma845x_interrupt’ [Debug] MCUXpresso will probe for connected boards and should find the OpenSDA debug probe that is part of the integrated OpenSDA circuit on the FRDM-KL27Z board. Click on OK to continue. The firmware will be downloaded to the board and the debugger started. Open a Terminal program (e.g. Tera Term) and connect to the FRDM-KL27Z COM port that it enumerated as. Use 115200 baud, 8 data, 1 stop, no parity. Start the application in the MCUXpresso IDE by clicking the "Resume" button. The application is now running and signed 14-bit accelerometer output values are displayed on the terminal. To modify the initial register settings of the MMA8451 accelerometer, find the mma845x_Config_Isr[] structure and change it according to your needs. Well done if you managed to follow along and get it all working. If there are any questions, do not hesitate to ask below. Your feedback or suggestions are also welcome. Regards, Tomas
View full article
Hello Community,   One of the main features of the NXP accelerometers is the Auto-WAKE/SLEEP mode.   I would like to share this project in order to demonstrate the feasibility of using the Low-power and auto-WAKE/SLEEP modes for reducing current consumption in the different NXP accelerometers such as the MMA845x and MMA865x series.   I created this project using the FRDM-KL25Z platform and the MMA8652FC accelerometer (You may find the breakout board files here). The complete source code is written in CodeWarrior v10.x IDE.   This document gives you an introduction of the MMA8652FC accelerometer as well as the different power consumptions and guides you through the initialization process and how to appreciate the demonstration:   Initialization of the MKL25Z128 MCU. Initialization of the MMA8652FC. Auto-WAKE/SLEEP mode. MMA8652FC Embedded functions. Interrupt handlers. Evaluation of the interrupt source. Summarizing the application and Macros definition. Visualization of the current consumption.   1. As you can see in the FRDM-KL25Z schematic and the image below, the I2C signals are routed to the I2C1 module (PTC1 and PTC2 pins) of the KL25Z MCU and the INT1 and INT2 outputs are connected to the PTD5 and PTA5 pins. The INT1 and INT2 outputs of the MMA8652FC are configured as a push-pull active-low outputs, so the corresponding PTD5 and PTA5 pins configuration are GPIOs with an interrupt on falling edge.   The MCU is, therefore, configured as follows:          /* I2C1 module initialization */      SIM_SCGC4 |= SIM_SCGC4_I2C1_MASK;        // Turn on clock to I2C1 module      SIM_SCGC5 |= SIM_SCGC5_PORTC_MASK;       // Turn on clock to Port C module      PORTC_PCR1 |= PORT_PCR_MUX(0x2);         // PTC1 pin is I2C1 SCL line      PORTC_PCR2 |= PORT_PCR_MUX(0x2);         // PTC2 pin is I2C1 SDA line      I2C1_F  |= I2C_F_ICR(0x14);              // SDA hold time = 2.125us, SCL start hold time = 4.25us, SCL stop hold time = 5.125us      I2C1_C1 |= I2C_C1_IICEN_MASK;            // Enable I2C1 module        /*Configure the PTD5 and PTA5 pin (connected to the INT1 and INT2 of the MMA8652FC) for falling edge interrupts */      SIM_SCGC5 |= SIM_SCGC5_PORTD_MASK;       // Turn on clock to Port D module      PORTD_PCR5 |= (0|PORT_PCR_ISF_MASK|      // Clear the interrupt flag                           PORT_PCR_MUX(0x1)|  // PTD5 is configured as GPIO                           PORT_PCR_IRQC(0xA));// PTD5 is configured for falling edge interrupts        SIM_SCGC5 |= SIM_SCGC5_PORTA_MASK;       // Turn on clock to Port A module      PORTA_PCR5 |= (0|PORT_PCR_ISF_MASK|      // Clear the interrupt flag                           PORT_PCR_MUX(0x1)|  // PTA5 is configured as GPIO                           PORT_PCR_IRQC(0xA));// PTA5 is configured for falling edge interrupts        /* Enable PORTD interrupt on NVIC */      NVIC_ICPR |= 1 << ((INT_PORTD - 16)%32);      NVIC_ISER |= 1 << ((INT_PORTD - 16)%32);      /* Enable PORTA interrupt on NVIC */      NVIC_ICPR |= 1 << ((INT_PORTA - 16)%32);      NVIC_ISER |= 1 << ((INT_PORTA - 16)%32);     2. The MMA8652FC is an intelligent, low-power, three-axis, capacitive micromachined accelerometer with 12 bits of resolution.   At the beginning of the initialization, all registers are reset to their default values by setting the RST bit of the CTRL_REG2 register. The Normal and Low Power modes are set in the same register. The MODS[1:0] bits select which Oversampling mode is to be used. The Oversampling modes are available in both WAKE Mode MOD[1:0] and also in the SLEEP Mode SMOD[1:0].   Then the MMA8652FC is initialized as shown below:        I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG2, 0x40);        // Reset all registers to POR values      Pause(0x631);        // ~1ms delay      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, XYZ_DATA_CFG_REG, 0x00); // +/-2g range with ~0.977mg/LSB              /* Power Mode Configuration */      If LOW power mode is selected:      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG2, 0x1B);        // Low Power mode        If NORMAL power mode is selected:      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG2, 0x00);        // Normal mode     3. As I mentioned, one of the main features of the MMA8652FC is the Auto-WAKE/SLEEP mode.   The advantage of using the Auto-WAKE/SLEEP is that the system can automatically transition to a higher sample rate (higher current consumption) when needed, but spends the majority of the time in the SLEEP mode (lower current) when the device does not require higher sampling rates.   • Auto-WAKE refers to the device being triggered by one of the interrupt functions to transition to a higher sample rate. This may also interrupt the processor to transition from a SLEEP mode to a higher power mode. • SLEEP mode occurs after the accelerometer has not detected an interrupt for longer than the user-definable timeout period.       At the ASLP_COUNT register, you can set the minimum time period of inactivity required to switch the part between Wake and Sleep status, in this case, 5 seconds.   The Auto-WAKE/SLEEP mode, therefore, is configured as follow:        read_reg = I2C_ReadRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG2);      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG2, read_reg|0x04);  // Auto-SLEEP enable      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, ASLP_COUNT_REG, 0x10);      // 5 seconds (16 * 320ms)      read_reg = I2C_ReadRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG4);      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG4, read_reg|0x80);  // Enable AutoSleep interrupt, INT2 - PTD5      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG1, 0xC1);           // ODR=800Hz and Sleep mode ODR=1.56Hz, Active mode     4. The device can be configured to generate inertial wake-up interrupt signals from any combination of the configurable embedded functions, enabling the MMA8652FC to monitor inertial events while remaining in a low-power mode during periods of inactivity.   The Interrupts that can WAKE the device from SLEEP are: Tap Detection, Orientation Detection, Motion/Freefall, and Transient Detection.       In this project, the TAP (Pulse) or Transient interrupts are used to wake up the device from the SLEEP. In order to get more information about the TAP detection, please click here.   The MMA8652FC is configured as below:        If Transient interrupt is selected:      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, TRANSIENT_THS_REG, 0x84);         // Set threshold to 252mg (4 x 63mg )      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, TRANSIENT_COUNT_REG, 0x02);       // Set debounce timer period to 40ms (low power mode) / 2.5ms (normal mode)-Table 66      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, TRANSIENT_CFG_REG, 0x17);         // Enable transient detection for X and Y axis, latch enabled         I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG3, 0x40);                 // Wake from Transient interrupt, Push-pull, active low interrupt      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG4, 0x20);                 // Enable Transient detection interrupt      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG5, 0x20);                 // Transient interrupt routed to INT1 - PTA5          If TAP interrupt is selected:      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, PULSE_CFG_REG, 0x15);             // Enable X, Y and Z Single Pulse      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, PULSE_THSX_REG, 0x20);            // Set X Threshold to 2.016g      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, PULSE_THSY_REG, 0x20);            // Set Y Threshold to 2.016g      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, PULSE_THSZ_REG, 0x2A);            // Set Z Threshold to 2.646g      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, PULSE_TMLT_REG, 0x28);            // Set Time Limit for Tap Detection to 25 ms      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, PULSE_LTCY_REG, 0x28);            // Set Latency Time to 50 ms. During this time interval, all pulses are ignored          I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG3, 0x10);                 // Wake from Pulse interrupt, Push-pull, active low interrupt      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG4, 0x08);                 // Pulse detection interrupt enabled      I2C_WriteRegister(MMA8652FC_I2C_ADDRESS, CTRL_REG5, 0x08);                 // Pulse interrupt routed to INT1 - PTA5     5. As I mentioned above, the TAP (Pulse) or Transient interrupts are used to wake up the device from the SLEEP. Besides, if Auto-SLEEP interrupt is enabled, then transitioning from ACTIVE mode to Auto-SLEEP mode (or vice versa) generates an interrupt.   In this project, the Auto-SLEEP, the TAP (Pulse) or the Transient interrupts are enable. The MKL25Z128 responds to these interrupts reading the INT_SOURCE (0x0C) register, in order to determine the appropriate sources of the interrupt.   Every source of interrupt has its own way to clear the interrupt flag. Please refer to the comments of each ISR:        Transient interrupt handler      void PORTA_IRQHandler()      {         PORTA_PCR5 |= PORT_PCR_ISF_MASK;                // Clear the PTC interrupt         int_source = I2C_ReadRegister(MMA8652FC_I2C_ADDRESS, INT_SOURCE_REG); // Clear interrupt Source Register           if(int_source&0x20)  // Transient interrupt ?         {            i = I2C_ReadRegister(MMA8652FC_I2C_ADDRESS, TRANSIENT_SRC_REG); // Read the TRANSIENT_SRC register to clear the SRC_TRANS flag in the INT_SOURCE register             transient_int = 1;         }      }        TAP interrupt handler      void PORTA_IRQHandler()      {         PORTA_PCR5 |= PORT_PCR_ISF_MASK;                // Clear the PTC interrupt flag         int_source = I2C_ReadRegister(MMA8652FC_I2C_ADDRESS, INT_SOURCE_REG); // Clear interrupt Source Register            if(int_source&0x08)  // Pulse interrupt ?         {            i = I2C_ReadRegister(MMA8652FC_I2C_ADDRESS, PULSE_SRC_REG); // Read the PULSE_SRC register to clear the SRC_TRANS flag in the INT_SOURCE register             pulse_int = 1;         }      }        Auto WAKE/SLEEP interrupt handler      void PORTD_IRQHandler()      {          PORTD_PCR5 |= PORT_PCR_ISF_MASK;                // Clear the PTD interrupt flag             int_source = I2C_ReadRegister(MMA8652FC_I2C_ADDRESS, INT_SOURCE_REG); // Clear interrupt Source Register             if (int_source&0x80) // Auto Sleep/Wake interrupt ?          {             i = I2C_ReadRegister(MMA8652FC_I2C_ADDRESS, SYSMOD_REG);      // Read the SYSMOD register to clear the SRC_ASLP flag in the INT_SOURCE register             sleep_int = 1;          }      }     6. At this point, the configuration of the MCU and the accelerometer is done. The RGB LED contained on the FRDM-KL25Z board is configured in order to help showing the behavior of the application. This behavior is configured as follow:        #if TRANSIENT_DETECTION                    if (transient_int){                             transient_int = 0;                 TURN_BLUE_ON(); TURN_RED_OFF();}      #elif TAP_DETECTION                    if (pulse_int){                 pulse_int = 0;                 TURN_BLUE_ON(); TURN_RED_OFF();}      #endif                    if (sleep_int){                  sleep_int = 0;                  TURN_RED_ON(); TURN_BLUE_OFF();}     7. In summary, the FRDM-KL25Z will be interfacing with the MMA8652FC. The power mode will be set and the interrupts will be enabled. The macros at the top of the source code will allow us to select between the different power modes, the different embedded functions and to select the Auto-WAKE/SLEEP function.   If the Auto-WAKE/SLEEP function is enabled, the MMA8652FC will go into the SLEEP mode (ODR=1.56Hz) after 5 seconds of inactivity. The RED LED will be set. When an interrupt from the embedded functions is generated, the MMA8652FC will be awakened (ODR=800Hz) and so on. The BLUE LED will be set.        /* Select the Power Mode - Table 101 from datasheet */      #define NORMAL_MODE        1      #define LOW_POWER_MODE     0         /* Select the Embedded Function */      #define TRANSIENT_DETECTION       1      #define TAP_DETECTION             0        /* Auto-WAKE/SLEEP Function */      #define AUTO_SLEEP   1     8. The Table 5 from the datasheet shows the expected current consumption in regard with the power mode and ODR selected:   As I mentioned before, the Sleep mode allow us to change between different Output Data Rates (ODR) dynamically so we can reduce the current consumption.   In order to verify if the accelerometer is consuming the current mentioned on the datasheet, I measured the MMA8652FC current consumption using the project mentioned.   Please refer to the results below:           9. The advantage of using the Auto-WAKE/SLEEP mode is that the system can automatically transition to a higher sample rate (higher current consumption) when needed, but spends the majority of the time in the SLEEP mode (lower current) when the device does not require higher sampling rates.   In the manner we have come to expect of the MMA8652FC, the current consumption decreases when the ODR is changed from 800Hz to 1.56Hz, in both normal and low power mode.   The information mentioned on the datasheet is now confirmed.     Please find attached the complete source code.   I hope you find useful and funny this sample project. Any suggestion will be appreciated.   You are invited to take part of the NXP community where you can post all your questions and you may find useful material for your projects.   Best Regards, David
View full article
Hello community, As we know, The MMA8451Q has embedded single/double and directional tap detection. This post describes an example project using the Single Tap detection for the MMA8451Q included on the FRDM-KL25Z. Figure 1. Depending on the tapping direction, positive or negative of each axis, the RGB LED will turn into a different color. For more detailed information on how to configure the device for tap detection please refer to NXP application note, AN4072. Configuring the MCU Enable the I2C module of the KL25Z MCU and turn on all the corresponding clocks. In this case, the INT1 output of the MMA8451Q is connected to the PTA14 pin and both SCL and SDA lines are connected to the I2C0 module (PTE24 and PTE25 pins). Please review the FRDM-KL25Z schematic.      //I2C0 module initialization        SIM_SCGC4 |= SIM_SCGC4_I2C0_MASK;        // Turn on clock to I2C0 module        SIM_SCGC5 |= SIM_SCGC5_PORTE_MASK;       // Turn on clock to Port E module        PORTE_PCR24 = PORT_PCR_MUX(5);           // PTE24 pin is I2C0 SCL line        PORTE_PCR25 = PORT_PCR_MUX(5);           // PTE25 pin is I2C0 SDA line        I2C0_F = 0x14;                           // SDA hold time = 2.125us, SCL start hold time = 4.25us, SCL stop hold time = 5.125us *        I2C0_C1 = I2C_C1_IICEN_MASK;             // Enable I2C0 module                   //Configure the PTA14 pin (connected to the INT1 of the MMA8451Q) for falling edge interrupts        SIM_SCGC5 |= SIM_SCGC5_PORTA_MASK;       // Turn on clock to Port A module        PORTA_PCR14 |= (0|PORT_PCR_ISF_MASK|     // Clear the interrupt flag        PORT_PCR_MUX(0x1)|           // PTA14 is configured as GPIO        PORT_PCR_IRQC(0xA));         // PTA14 is configured for falling edge interrupts                   //Enable PORTA interrupt on NVIC        NVIC_ICPR |= 1 << ((INT_PORTA - 16)%32);        NVIC_ISER |= 1 << ((INT_PORTA - 16)%32); Configure the RBG LED of the FRDM-KL25Z Based on FRDM-KL25Z User's Manual , the RGB LED signals are connected as follow: The pins mentioned, are configured as output.      //Configure PTB18, PTB19 and PTD1 as output for the RGB LED        SIM_SCGC5 |= SIM_SCGC5_PORTB_MASK;    // Turn on clock to Port B module        SIM_SCGC5 |= SIM_SCGC5_PORTD_MASK;    // Turn on clock to Port D module                   PORTB_PCR18 |= PORT_PCR_MUX(0x1);     // PTB18 is configured as GPIO        PORTB_PCR19 |= PORT_PCR_MUX(0x1);     // PTB19 is configured as GPIO        PORTD_PCR1 |= PORT_PCR_MUX(0x1);      // PTD1 is configured as GPIO                   GPIOB_PDDR |= (1 << 18);              //Port Data Direction Register (GPIOx_PDDR)        GPIOB_PDDR |= (1 << 19);              //Set GPIO direction set bit corresponding bit on the direction        GPIOD_PDDR |= (1 << 1);               //register for each port, set the bit means OUTPUT Initialize and configure the MMA8451Q for Tap Detection To utilize the single and/or double tap detection the following eight (8) registers must be configured. Register 0x21: PULSE_CFG Pulse Configuration Register Register 0x22: PULSE_SRC Pulse Source Register Register 0x23 - 0x25: PULSE_THSX,Y,Z Pulse Threshold for X, Y and Z Registers Register 0x26: PULSE_TMLT Pulse Time Window 1 Register Register 0x27: PULSE_LTCY Pulse Latency Timer Register Register 0x28: PULSE_WIND Second Pulse Time Window Register Please review the MMA8451Q datasheet in order to get more information about the registers mentioned. For a single tap event, the PULSE_TMLT, PULSE_THSX/Y/Z and PULSE_LTCY registers are key parameters to consider. Note in condition (a) the interrupt is asserted since the acceleration due to a pulse exceeds the specified acceleration threshold (value set in the PULSE_THSX) and crosses up and down before the specified Pulse Time Limit (value set in PULSE_TMLT) expires. Note that in condition (b) the acceleration due to a pulse exceeds the specified acceleration threshold limit, but does not go below the threshold before the specified Pulse Time Limit expires. Therefore, this is an invalid pulse and the interrupt will not be triggered. Also note that the Latency is not shown for this example.              unsigned char reg_val = 0, CTRL_REG1_val = 0;            I2C_WriteRegister(MMA845x_I2C_ADDRESS, CTRL_REG2, 0x40);             // Reset all registers to POR values                 do            // Wait for the RST bit to clear        {               reg_val = I2C_ReadRegister(MMA845x_I2C_ADDRESS, CTRL_REG2) & 0x40;        }      while (reg_val);            I2C_WriteRegister(MMA845x_I2C_ADDRESS, CTRL_REG1, 0x0C);             // ODR = 400Hz, Reduced noise, Standby mode        I2C_WriteRegister(MMA845x_I2C_ADDRESS, XYZ_DATA_CFG_REG, 0x00);      // +/-2g range -> 1g = 16384/4 = 4096 counts        I2C_WriteRegister(MMA845x_I2C_ADDRESS, CTRL_REG2, 0x02);             // High Resolution mode            I2C_WriteRegister(MMA845x_I2C_ADDRESS, PULSE_CFG_REG, 0x15);         //Enable X, Y and Z Single Pulse        I2C_WriteRegister(MMA845x_I2C_ADDRESS, PULSE_THSX_REG, 0x20);        //Set X Threshold to 2.016g        I2C_WriteRegister(MMA845x_I2C_ADDRESS, PULSE_THSY_REG, 0x20);        //Set Y Threshold to 2.016g        I2C_WriteRegister(MMA845x_I2C_ADDRESS, PULSE_THSZ_REG, 0x2A);        //Set Z Threshold to 2.646g        I2C_WriteRegister(MMA845x_I2C_ADDRESS, PULSE_TMLT_REG, 0x28);        //Set Time Limit for Tap Detection to 25 ms        I2C_WriteRegister(MMA845x_I2C_ADDRESS, PULSE_LTCY_REG, 0x28);        //Set Latency Time to 50 ms        I2C_WriteRegister(MMA845x_I2C_ADDRESS, CTRL_REG4, 0x08);             //Pulse detection interrupt enabled        I2C_WriteRegister(MMA845x_I2C_ADDRESS, CTRL_REG5, 0x08);             //Route INT1 to system interrupt            CTRL_REG1_val = I2C_ReadRegister(MMA845x_I2C_ADDRESS, CTRL_REG1);   //Active Mode        CTRL_REG1_val |= 0x01;        I2C_WriteRegister(MMA845x_I2C_ADDRESS, CTRL_REG1, CTRL_REG1_val); Handle the Interrupt The PULSE_SRC register indicates a double or single pulse event has occurred and also which direction. In this case the value of the register mentioned is passed to the PULSE_SRC_val variable and evaluated. Reading the PULSE_SRC register clears all bits. Reading the source register will clear the interrupt.      void PORTA_IRQHandler()      {             PORTA_PCR14 |= PORT_PCR_ISF_MASK;               // Clear the interrupt flag              PULSE_SRC_val = I2C_ReadRegister(MMA845x_I2C_ADDRESS, PULSE_SRC_REG); //Read Pulse Source Register      } Please find attached the complete source code written in the CodeWarrior for Microcontrollers-Eclipse IDE|NXP . As I mentioned before, you can find more detailed information at application note AN4072. Useful information about handling the MMA8451 can be founded in MMA8451Q - Bare metal example project. I hope you find useful and funny this sample project. Regards, David
View full article
The following video shows how to run the FRDM 6DOF Bare Board eCompass using the FRDM-K22. This algorithm uses the FXOS8700 contained on the Freedom Board. In order to get more information about the Sensor Fusion Library for Kinetis MCU's 5.0, please refer to the following link: Sensor Fusion|Freescale I hope this material will be useful for you. David
View full article
This is a step-by-step guide document to set the FRDM-K64F-AGM01 on the Freescale Sensor Fusion Toolbox Software.
View full article
Hi Everyone, In this tutorial I intend to run through my simple bare metal example code I created for the Freescale FRDM-KL25Z platform and the FRDM-STBC-AGM01 board containing a three axis accelerometer + magnetometer (FXOS8700CQ) and a three axis gyroscope (FXAS21002C). I will not cover the Sensor Fusion library and the ISF which also support this board. The FreeMASTER tool is used to visualize all the data that are read from both sensors using an interrupt technique through the I 2 C interface. This example illustrates: 1. Initialization of the MKL25Z128 MCU (mainly I 2 C and PORT modules). 2. I 2 C data write and read operations. 3. Initialization of the FXOS8700CQ and FXAS21002C. 4. Simple accelerometer offset calibration based on the AN4069. 5. Output data reading using an interrupt technique. 6. Conversion of the output raw values to real values in g’s, µT, dps and °C. 7. Visualization of the calculated values in the FreeMASTER tool. 1. As you can see in the FRDM-STBC-AGM01 schematic, both sensors are controlled via I 2 C by default. With jumpers J6 and J7 in their default position (2-3), the I 2 C signals are routed to the I2C1 module (PTC1 and PTC2 pins) of the KL25Z MCU. The INT1_8700 output is connected to the PTD4 pin and the INT1_21002 pin to the PTA5 pin of the KL25Z MCU. These both interrupt pins are configured as push-pull active-low outputs, so the corresponding PTD4/PTA5 pin configuration is GPIO with an interrupt on falling edge. The MCU is, therefore, configured as follows. void MCU_Init(void) {      //I2C1 module initialization      SIM_SCGC4 |= SIM_SCGC4_I2C1_MASK;        // Turn on clock to I2C1 module      SIM_SCGC5 |= SIM_SCGC5_PORTC_MASK;       // Turn on clock to Port C module      PORTC_PCR1 |= PORT_PCR_MUX(0x2);         // PTC1 pin is I2C1 SCL line      PORTC_PCR2 |= PORT_PCR_MUX(0x2);         // PTC2 pin is I2C1 SDA line      I2C1_F  |= I2C_F_ICR(0x14);              // SDA hold time = 2.125us, SCL start hold time = 4.25us, SCL stop hold time = 5.125us      I2C1_C1 |= I2C_C1_IICEN_MASK;            // Enable I2C1 module                       //Configure the PTD4 pin (connected to the INT1 of the FXOS8700CQ) for falling edge interrupts      SIM_SCGC5 |= SIM_SCGC5_PORTD_MASK;       // Turn on clock to Port D module      PORTD_PCR4 |= (0|PORT_PCR_ISF_MASK|      // Clear the interrupt flag                       PORT_PCR_MUX(0x1)|      // PTD4 is configured as GPIO                       PORT_PCR_IRQC(0xA));    // PTD4 is configured for falling edge interrupts                   //Configure the PTA5 pin (connected to the INT1 of the FXAS21002) for falling edge interrupts      SIM_SCGC5 |= SIM_SCGC5_PORTA_MASK;       // Turn on clock to Port A module      PORTA_PCR5 |= (0|PORT_PCR_ISF_MASK|      // Clear the interrupt flag                       PORT_PCR_MUX(0x1)|      // PTA5 is configured as GPIO                       PORT_PCR_IRQC(0xA));    // PTA5 is configured for falling edge interrupts                          //Enable PORTD interrupt on NVIC      NVIC_ICPR |= 1 << ((INT_PORTD - 16)%32);      NVIC_ISER |= 1 << ((INT_PORTD - 16)%32);                //Enable PORTA interrupt on NVIC      NVIC_ICPR |= 1 << ((INT_PORTA - 16)%32);      NVIC_ISER |= 1 << ((INT_PORTA - 16)%32); } 2. The 7-bit I 2 C slave address of the FXOS8700CQ is 0x1E since both SA0 and SA1 pins are shorted to GND. The address of the FXAS21002C is 0x20 since SA0 pin is also shorted to GND. The two screenshots below show the write operation which writes the value 0x25 to the CTRL_REG1 (0x2A) of the FXOS8700CQ and 0x16 to the CTRL_REG1 (0x13) of the FXAS21002C. Here is the single byte read from the WHO_AM_I register. As you can see, it returns the correct value 0xC7 for the FXOS8700CQ and 0xD7 for the FXAS21002C. Finally, a burst read of 12 bytes from the FXOS8700CQ output data registers (0x01 – 0x06 and 0x33 – 0x38) and 6 bytes from the FXAS21002C output data registers (0x01 – 0x06) is shown below. 3. At the beginning of the initialization, all registers are reset to their default values by setting the RST bit of the CTRL_REG2 register. Then the FXOS8700CQ is initialized as shown below. void FXOS8700CQ_Init (void) {      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG2, 0x40);          // Reset all registers to POR values      Pause(0x631);          // ~1ms delay            I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, XYZ_DATA_CFG_REG, 0x00);   // +/-2g range with 0.244mg/LSB              I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, M_CTRL_REG1, 0x1F);        // Hybrid mode (accelerometer + magnetometer), max OSR      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, M_CTRL_REG2, 0x20);        // M_OUT_X_MSB register 0x33 follows the OUT_Z_LSB register 0x06 (burst read)                       I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG2, 0x02);          // High Resolution mode      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG3, 0x00);          // Push-pull, active low interrupt      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG4, 0x01);          // Enable DRDY interrupt      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG5, 0x01);          // DRDY interrupt routed to INT1 - PTD4      I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG1, 0x25);          // ODR = 25Hz, Reduced noise, Active mode   } And here is the initialization of the FXAS21002C. void FXAS21002C_Init (void) {      I2C_WriteRegister(FXAS21002C_I2C_ADDRESS, GYRO_CTRL_REG1, 0x40);     // Reset all registers to POR values      Pause(0x631);        // ~1ms delay            I2C_WriteRegister(FXAS21002C_I2C_ADDRESS, GYRO_CTRL_REG0, 0x03);     // High-pass filter disabled, +/-250 dps range -> 7.8125 mdps/LSB = 128 LSB/dps      I2C_WriteRegister(FXAS21002C_I2C_ADDRESS, GYRO_CTRL_REG2, 0x0C);     // Enable DRDY interrupt, routed to INT1 - PTA5, push-pull, active low interrupt      I2C_WriteRegister(FXAS21002C_I2C_ADDRESS, GYRO_CTRL_REG1, 0x16);     // ODR = 25Hz, Active mode        } 4. A simple accelerometer offset calibration method is implemented according to the AN4069. void FXOS8700CQ_Accel_Calibration (void) {      char X_Accel_offset, Y_Accel_offset, Z_Accel_offset;            FXOS8700CQ_DataReady = 0;           while (!FXOS8700CQ_DataReady){}           // Is a first set of data ready?      FXOS8700CQ_DataReady = 0;            I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG1, 0x00);          // Standby mode                 I2C_ReadMultiRegisters(FXOS8700CQ_I2C_ADDRESS, OUT_X_MSB_REG, 6, AccelMagData);          // Read data output registers 0x01-0x06                     Xout_Accel_14_bit = ((short) (AccelMagData[0]<<8 | AccelMagData[1])) >> 2;          // Compute 14-bit X-axis acceleration output value      Yout_Accel_14_bit = ((short) (AccelMagData[2]<<8 | AccelMagData[3])) >> 2;          // Compute 14-bit Y-axis acceleration output value      Zout_Accel_14_bit = ((short) (AccelMagData[4]<<8 | AccelMagData[5])) >> 2;          // Compute 14-bit Z-axis acceleration output value                   X_Accel_offset = Xout_Accel_14_bit / 8 * (-1);          // Compute X-axis offset correction value      Y_Accel_offset = Yout_Accel_14_bit / 8 * (-1);          // Compute Y-axis offset correction value      Z_Accel_offset = (Zout_Accel_14_bit - SENSITIVITY_2G) / 8 * (-1);          // Compute Z-axis offset correction value                   I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, OFF_X_REG, X_Accel_offset);                  I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, OFF_Y_REG, Y_Accel_offset);           I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, OFF_Z_REG, Z_Accel_offset);                        I2C_WriteRegister(FXOS8700CQ_I2C_ADDRESS, CTRL_REG1, 0x25);          // Active mode again } 5. In the ISRs, only the interrupt flags are cleared and the DataReady variables are set to indicate the arrival of new data. void PORTD_IRQHandler() {      PORTD_PCR4 |= PORT_PCR_ISF_MASK;          // Clear the interrupt flag      FXOS8700CQ_DataReady = 1;  } void PORTA_IRQHandler() {      PORTA_PCR5 |= PORT_PCR_ISF_MASK;          // Clear the interrupt flag      FXAS21002C_DataReady = 1;  } 6. The output values from accelerometer registers 0x01 – 0x06 are first converted to signed 14-bit integer values and afterwards to real values in g’s. Similarly, the output values from magnetometer registers 0x33 – 0x38 are first converted to signed 16-bit integer values and afterwards to real values in microtesla (µT). if (FXOS8700CQ_DataReady)          // Is a new set of accel + mag data ready? {                  FXOS8700CQ_DataReady = 0;                                                                                                                          I2C_ReadMultiRegisters(FXOS8700CQ_I2C_ADDRESS, OUT_X_MSB_REG, 12, AccelMagData);         // Read FXOS8700CQ data output registers 0x01-0x06 and 0x33 - 0x38                     // 14-bit accelerometer data      Xout_Accel_14_bit = ((short) (AccelMagData[0]<<8 | AccelMagData[1])) >> 2;        // Compute 14-bit X-axis acceleration output value      Yout_Accel_14_bit = ((short) (AccelMagData[2]<<8 | AccelMagData[3])) >> 2;        // Compute 14-bit Y-axis acceleration output value      Zout_Accel_14_bit = ((short) (AccelMagData[4]<<8 | AccelMagData[5])) >> 2;        // Compute 14-bit Z-axis acceleration output value                              // Accelerometer data converted to g's      Xout_g = ((float) Xout_Accel_14_bit) / SENSITIVITY_2G;        // Compute X-axis output value in g's      Yout_g = ((float) Yout_Accel_14_bit) / SENSITIVITY_2G;        // Compute Y-axis output value in g's      Zout_g = ((float) Zout_Accel_14_bit) / SENSITIVITY_2G;        // Compute Z-axis output value in g's                               // 16-bit magnetometer data                   Xout_Mag_16_bit = (short) (AccelMagData[6]<<8 | AccelMagData[7]);          // Compute 16-bit X-axis magnetic output value      Yout_Mag_16_bit = (short) (AccelMagData[8]<<8 | AccelMagData[9]);          // Compute 16-bit Y-axis magnetic output value      Zout_Mag_16_bit = (short) (AccelMagData[10]<<8 | AccelMagData[11]);        // Compute 16-bit Z-axis magnetic output value                                                         // Magnetometer data converted to microteslas      Xout_uT = (float) (Xout_Mag_16_bit) / SENSITIVITY_MAG;        // Compute X-axis output magnetic value in uT      Yout_uT = (float) (Yout_Mag_16_bit) / SENSITIVITY_MAG;        // Compute Y-axis output magnetic value in uT      Zout_uT = (float) (Zout_Mag_16_bit) / SENSITIVITY_MAG;        // Compute Z-axis output magnetic value in uT              } Similarly, the output values from gyroscope registers 0x01 – 0x06 are first converted to signed 16-bit integer values and afterwards to real values in degrees per second. Temperature is also read out from the 0x12 register. if (FXAS21002C_DataReady)         // Is a new set of gyro data ready? {                  FXAS21002C_DataReady = 0;                                                                                                                                       I2C_ReadMultiRegisters(FXAS21002C_I2C_ADDRESS, GYRO_OUT_X_MSB_REG, 6, GyroData);         // Read FXAS21002C data output registers 0x01-0x06                                   // 16-bit gyro data      Xout_Gyro_16_bit = (short) (GyroData[0]<<8 | GyroData[1]);           // Compute 16-bit X-axis output value      Yout_Gyro_16_bit = (short) (GyroData[2]<<8 | GyroData[3]);           // Compute 16-bit Y-axis output value      Zout_Gyro_16_bit = (short) (GyroData[4]<<8 | GyroData[5]);           // Compute 16-bit Z-axis output value                                           // Gyro data converted to dps      Roll = (float) (Xout_Gyro_16_bit) / SENSITIVITY_250;          // Compute X-axis output value in dps      Pitch = (float) (Yout_Gyro_16_bit) / SENSITIVITY_250;         // Compute Y-axis output value in dps      Yaw = (float) (Zout_Gyro_16_bit) / SENSITIVITY_250;           // Compute Z-axis output value in dps                               // Temperature data      Temp = I2C_ReadRegister(FXAS21002C_I2C_ADDRESS, GYRO_TEMP_REG);                   }   7. The calculated values can be watched in the "Variables" window on the top right of the Debug perspective or in the FreeMASTER application. To open and run the FreeMASTER project, install the FreeMASTER application​ and FreeMASTER Communication Driver. I guess this is enough to let you start experimenting with the FRDM-STBC-AGM01 board. Attached you can find the complete source code written in the CW for MCU's v10.6 including the FreeMASTER project. If there are any questions regarding this simple application, do not hesitate to ask below. Your feedback or suggestions are also welcome. Regards, Tomas
View full article
Hi Everyone, As I am often asked for a simple bare metal example code illustrating the use of the accelerometer vector-magnitude function, I have decided to share here one of my examples I created for the FXLS8471Q accelerometer while working with the Freescale FRDM-KL25Z platform and FRDM-FXS-MULT2-B sensor expansion board. This example code complements the Python code snippet from the AN4692. The FXLS8471Q is set for detection of a change in tilt angle exceeding 17.25° from the horizontal plane. Once an event is triggered, an interrupt will be generated on the INT1 pin: void FXLS8471Q_Init (void) {      FXLS8471Q_WriteRegister(A_VECM_THS_MSB_REG, 0x84);            // Threshold value set to 300mg or ~17.25°    FXLS8471Q_WriteRegister(A_VECM_THS_LSB_REG, 0xCC);          FXLS8471Q_WriteRegister(A_VECM_CNT_REG, 0x01);                // Debounce timer period set to 80ms          FXLS8471Q_WriteRegister(A_VECM_INITX_MSB_REG, 0x00);    FXLS8471Q_WriteRegister(A_VECM_INITX_LSB_REG, 0x00);    FXLS8471Q_WriteRegister(A_VECM_INITY_MSB_REG, 0x00);    FXLS8471Q_WriteRegister(A_VECM_INITY_LSB_REG, 0x00);    FXLS8471Q_WriteRegister(A_VECM_INITZ_MSB_REG, 0x10);          // Set Z-axis to 1g  as a reference value    FXLS8471Q_WriteRegister(A_VECM_INITZ_LSB_REG, 0x00);          FXLS8471Q_WriteRegister(A_VECM_CFG_REG, 0x78);                // Event latch enabled, A_VECM_INITX/Y/Z used as initial reference, acceleration vector-magnitude detection feature enabled          FXLS8471Q_WriteRegister(CTRL_REG4, 0x02);                     // Acceleration vector-magnitude interrupt enabled    FXLS8471Q_WriteRegister(CTRL_REG5, 0x02);                     // Acceleration vector-magnitude interrupt routed to INT1 - PTA5          FXLS8471Q_WriteRegister(CTRL_REG1, 0x29);                     // ODR = 12.5Hz, Active mode } In the ISR, only the interrupt flag is cleared and the  INT_SOURCE (0x0C) register is read in order to clear the SRC_A_VECM status bit and deassert the INT1 pin, as shown on the screenshot below. void PORTA_IRQHandler() {    PORTA_PCR5 |= PORT_PCR_ISF_MASK;                              // Clear the interrupt flag    IntSource = FXLS8471Q_ReadRegister(INT_SOURCE_REG);           // Read the INT_SOURCE register to clear the SRC_A_VECM bit   } Attached you can find the complete source code. If there are any questions regarding this simple example code, please feel free to ask below. Your feedback or suggestions are also welcome. Regards, Tomas
View full article
clicktaleID