Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Dependencies: X_NUCLEO_IKS01A3
main.cpp
- Committer:
- martlefebvre94
- Date:
- 2019-09-23
- Revision:
- 15:913ecebcc7ed
- Parent:
- 14:abc98c6982b5
File content as of revision 15:913ecebcc7ed:
/**
******************************************************************************
* @file main.cpp
* @author SRA
* @version V1.0.0
* @date 5-March-2019
* @brief Simple Example application for using the X_NUCLEO_IKS01A3
* MEMS Inertial & Environmental Sensor Nucleo expansion board.
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT(c) 2019 STMicroelectronics</center></h2>
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/*
LELEC2811 Altimeter LPS22HH Project
M. Lefebvre - 2019-2020
*/
/* Includes */
#include <stdlib.h>
#include <time.h>
#include "mbed.h"
#include "XNucleoIKS01A3.h"
#include "stm32l073xx.h"
#include "stm32l0xx_hal_flash.h"
/* Defines */
#define FS 10.0 // Readout frequency (Hz)
// LPS22HH Pressure sensor
#define P0 1013.26 // Sea level pressure (hPa)
#define LPS22HH_ODR 10.0 // Output data rate (one-shot, 1, 10, 25, 50, 75, 100, 200 Hz)
#define LPS22HH_LOW_NOISE_EN 1 // Low-noise (0 disabled, 1 enabled)
#define LPS22HH_LPF_CFG 3 // Device bandwidth (0 for ODR/2, 2 for ODR/9, 3 for ODR/20)
#define LPS22HH_DATA_SIZE 8 // Number of bytes for LPS22HH pressure sensor data
/* Functions definition */
bool acquisition_task(bool verbose);
void read_task();
void print_flash_info();
bool erase_flash(bool verbose);
bool write_flash(uint32_t Flash_addr, uint32_t* Flash_wdata, int32_t n_words, bool verbose);
void read_flash(uint32_t Flash_addr, uint32_t* Flash_rdata, uint32_t n_bytes);
void button1_enabled_cb(void);
void button1_onpressed_cb(void);
static char *print_double(char *str, double v);
float pressure_to_altitude(double pressure);
uint32_t FloatToUint(float n);
float UintToFloat(uint32_t n);
/* Serial link */
Serial pc(SERIAL_TX, SERIAL_RX);
/* Button */
InterruptIn button1(USER_BUTTON);
volatile bool button1_pressed = false; // Used in the main loop
volatile bool button1_enabled = true; // Used for debouncing
Timeout button1_timeout; // Used for debouncing
/* Instantiate the expansion board */
static XNucleoIKS01A3 *mems_expansion_board = XNucleoIKS01A3::instance(D14, D15, D4, D5, A3, D6, A4);
/* Retrieve the composing elements of the expansion board */
static LIS2MDLSensor *magnetometer = mems_expansion_board->magnetometer;
static HTS221Sensor *hum_temp = mems_expansion_board->ht_sensor;
static LPS22HHSensor *press_temp = mems_expansion_board->pt_sensor;
static LSM6DSOSensor *acc_gyro = mems_expansion_board->acc_gyro;
static LIS2DW12Sensor *accelerometer = mems_expansion_board->accelerometer;
static STTS751Sensor *temp = mems_expansion_board->t_sensor;
/* Main */
int main()
{
uint8_t id;
float read_reg, read_reg_1;
uint8_t read_reg_int, read_reg_int_1, read_reg_int_2;
bool save_data = false;
uint32_t Flash_addr = FLASH_BANK2_BASE;
/* Serial link configuration */
pc.baud(115200);
/* Button configuration */
button1.fall(callback(button1_onpressed_cb)); // Attach ISR to handle button press event
/* Reset message */
printf("\n\r**************************************************\n\r");
printf("LELEC2811 LPS22HH Altimeter Program\n\r");
printf("**************************************************\n\r");
/* LPS22HH pressure sensor configuration */
press_temp->enable();
printf("/***** LPS22HH pressure sensor configuration *****/\r\n");
press_temp->read_id(&id);
printf("LPS22HH pressure = 0x%X\r\n", id);
press_temp->set_odr(LPS22HH_ODR, LPS22HH_LOW_NOISE_EN);
press_temp->get_odr(&read_reg, &read_reg_int);
printf("LPS22HH ODR = %1.1f [Hz]\r\n", read_reg);
printf("LPS22HH LOW_NOISE_EN = %1d\r\n", read_reg_int);
press_temp->set_lpfp_cfg(LPS22HH_LPF_CFG);
press_temp->get_lpfp_cfg(&read_reg_int);
printf("LPS22HH LPF_CFG = %1d\r\n", read_reg_int);
/* Print Flash memory information */
print_flash_info();
/* Information for the user */
printf("Press blue button to start data acquisition\r\n");
printf("Press 'R' to read previously measured data\r\n");
/* Acquisition loop */
while(1) {
// Start saving data when button is pushed
if (button1_pressed) {
button1_pressed = false;
save_data = true;
erase_flash(false);
printf("Acquiring data...\r\n");
printf("Press blue button to stop data acquisition\r\n");
Flash_addr = FLASH_BANK2_BASE;
}
if (save_data) {
// Acquisition task
save_data = acquisition_task(false);
}
else {
// Read task
read_task();
}
}
}
/* Acquisition task */
bool acquisition_task(bool verbose)
{
float pressure_value, alt_value;
uint32_t buffer_size = FLASH_PAGE_SIZE/4;
uint32_t data_ind = 0;
uint32_t data_buffer[buffer_size];
uint32_t Flash_addr = FLASH_BANK2_BASE;
while (Flash_addr <= FLASH_BANK2_END-FLASH_PAGE_SIZE+1) {
// Read sensors data
press_temp->get_pressure(&pressure_value);
alt_value = pressure_to_altitude(pressure_value);
// Write page in Flash memory
if (data_ind >= buffer_size) {
write_flash(Flash_addr, &data_buffer[0], buffer_size, false);
Flash_addr += FLASH_PAGE_SIZE;
data_ind = 0;
}
// Write data to buffer
data_buffer[data_ind] = FloatToUint(pressure_value);
data_buffer[data_ind+1] = FloatToUint(alt_value);
data_ind = data_ind+2;
// Print data in terminal
if (verbose) {
printf("LPS22HH: [press/mbar] %1.6f, [alt/m] %1.6f\r\n", pressure_value, alt_value);
}
// Wait for acquisition period
wait(1/FS);
// Stop saving data when button is pushed
if (button1_pressed) {
button1_pressed = false;
// Save remaining data to Flash memory
write_flash(Flash_addr, &data_buffer[0], data_ind, false);
printf("Data acquisition stopped\r\n");
printf("Press 'R' to read the data\r\n");
return false;
}
}
printf("Data acquisition stopped\r\n");
printf("Press 'R' to read the data\r\n");
return false;
}
/* Read task */
void read_task()
{
char pc_input;
uint32_t Flash_rdata[2];
bool flash_empty = false;
// Read terminal input
if (pc.readable()) {
pc_input = pc.getc();
}
else {
pc_input = ' ';
}
// Read Flash memory if 'R' is pressed
if ((pc_input == 'r') || (pc_input == 'R')) {
// Data labels
printf("press\talt\r\n");
// Read 1st Flash data
uint32_t Flash_addr_temp = FLASH_BANK2_BASE;
read_flash(Flash_addr_temp, &Flash_rdata[0], LPS22HH_DATA_SIZE);
// Read Flash data
while ((Flash_addr_temp <= FLASH_BANK2_END-LPS22HH_DATA_SIZE+1) && !flash_empty) {
// Print read data in the terminal
printf("%1.6f\t%1.6f\r\n", UintToFloat(Flash_rdata[0]), UintToFloat(Flash_rdata[1]));
Flash_addr_temp += LPS22HH_DATA_SIZE;
// Check if the next address is not empty (erased Flash only contains 0)
if (Flash_addr_temp <= FLASH_BANK2_END-LPS22HH_DATA_SIZE+1) {
read_flash(Flash_addr_temp, &Flash_rdata[0], LPS22HH_DATA_SIZE);
if ((Flash_rdata[0] == 0) && (Flash_rdata[1] == 0)) {
flash_empty = true;
}
}
}
}
}
/* Print Flash memory info */
void print_flash_info()
{
printf("**************************************************\n\r");
printf("/***** Flash memory info *****/\r\n");
printf("Flash size: %d [B]\r\n", FLASH_SIZE);
printf("Flash page size: %d [B]\r\n", FLASH_PAGE_SIZE);
printf("Flash nb of pages: %d \r\n", FLASH_SIZE/FLASH_PAGE_SIZE);
printf("Flash bank 1 base address: 0x%X\r\n", FLASH_BASE);
printf("Flash bank 1 end address: 0x%X\r\n", FLASH_BANK1_END);
printf("Flash bank 2 base address: 0x%X\r\n", FLASH_BANK2_BASE);
printf("Flash bank 2 end address: 0x%X\r\n", FLASH_BANK2_END);
printf("**************************************************\n\r");
}
/* Erase content of Flash memory */
bool erase_flash(bool verbose)
{
printf("Erasing Flash memory...\r\n");
// Unlock Flash memory
HAL_FLASH_Unlock();
// Erase Flash memory
FLASH_EraseInitTypeDef eraser;
uint32_t Flash_addr = FLASH_BANK2_BASE;
uint32_t page_error = 0;
int32_t page = 1;
while (Flash_addr < FLASH_BANK2_END) {
eraser.TypeErase = FLASH_TYPEERASE_PAGES;
eraser.PageAddress = Flash_addr;
eraser.NbPages = 1;
if(HAL_OK != HAL_FLASHEx_Erase(&eraser, &page_error)) {
if (verbose) {printf("Flash erase failed!\r\n");}
printf("Error 0x%X\r\n", page_error);
HAL_FLASH_Lock();
return false;
}
if (verbose) {printf("Erased page %d at address: 0x%X\r\n", page, Flash_addr);}
Flash_addr += FLASH_PAGE_SIZE;
page++;
}
if (verbose) {printf("Flash erase succesful!\r\n");}
return true;
}
/* Write Flash memory */
bool write_flash(uint32_t Flash_addr, uint32_t* Flash_wdata, int32_t n_words, bool verbose)
{
clock_t time;
if (verbose) {time = clock();}
// Unlock Flash memory
HAL_FLASH_Unlock();
// Write Flash memory
for (int i=0; i<n_words; i++) {
if (HAL_OK != HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Flash_addr, Flash_wdata[i])) {
if (verbose) {printf("Flash write failed!\r\n");}
HAL_FLASH_Lock();
return false;
}
Flash_addr += 4;
}
if (verbose) {printf("Flash write succesful!\r\n");}
HAL_FLASH_Lock();
if (verbose) {
time = clock() - time;
printf("Time to write: %1.6f [s]\r\n", (((double) time)/CLOCKS_PER_SEC));
}
return true;
}
/* Read Flash memory */
void read_flash(uint32_t Flash_addr, uint32_t* Flash_rdata, uint32_t n_bytes)
{
memcpy(Flash_rdata, (uint32_t*) Flash_addr, n_bytes);
}
/* Enables button when bouncing is over */
void button1_enabled_cb(void)
{
button1_enabled = true;
}
/* ISR handling button pressed event */
void button1_onpressed_cb(void)
{
if (button1_enabled) { // Disabled while the button is bouncing
button1_enabled = false;
button1_pressed = true; // To be read by the main loop
button1_timeout.attach(callback(button1_enabled_cb), 0.3); // Debounce time 300 ms
}
}
/* Helper function for printing floats & doubles */
static char *print_double(char *str, double v)
{
int decimalDigits = 6;
int i = 1;
int intPart, fractPart;
int len;
char *ptr;
/* prepare decimal digits multiplicator */
for (; decimalDigits != 0; i *= 10, decimalDigits--);
/* calculate integer & fractinal parts */
intPart = (int)v;
fractPart = (int)((v - (double)(int)v) * i);
/* fill in integer part */
sprintf(str, "%i.", intPart);
/* prepare fill in of fractional part */
len = strlen(str);
ptr = &str[len];
/* fill in leading fractional zeros */
for (i /= 10; i > 1; i /= 10, ptr++) {
if (fractPart >= i) {
break;
}
*ptr = '0';
}
/* fill in (rest of) fractional part */
sprintf(ptr, "%i", fractPart);
return str;
}
/* Pressure to altitude conversion */
float pressure_to_altitude(double pressure)
{
return 44330.77 * (1-pow(pressure/P0, 0.1902632));
}
uint32_t FloatToUint(float n)
{
return (uint32_t)(*(uint32_t*)&n);
}
float UintToFloat(uint32_t n)
{
return (float)(*(float*)&n);
}