aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorBen V. Brown <[email protected]>2021-01-17 10:48:52 +1100
committerBen V. Brown <[email protected]>2021-01-17 10:48:52 +1100
commitf786901da0800f6071c3fccaa75e85848268c58b (patch)
tree231d2ca379af65e62bd89c9e6c780a8379ae485b
parentaa6194b83288b76988200e9b586becc1a9a47861 (diff)
downloadIronOS-f786901da0800f6071c3fccaa75e85848268c58b.tar.gz
IronOS-f786901da0800f6071c3fccaa75e85848268c58b.zip
Formatting the C/C++ files
-rw-r--r--source/Core/BSP/Miniware/BSP.cpp555
-rw-r--r--source/Core/BSP/Miniware/BSP_PD.c10
-rw-r--r--source/Core/BSP/Miniware/I2C_Wrapper.cpp124
-rw-r--r--source/Core/BSP/Miniware/IRQ.cpp47
-rw-r--r--source/Core/BSP/Miniware/Power.cpp39
-rw-r--r--source/Core/BSP/Miniware/QC_GPIO.cpp86
-rw-r--r--source/Core/BSP/Miniware/Setup.c750
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c608
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c1684
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c1173
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c460
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c577
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash.c703
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash_ex.c780
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio.c433
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio_ex.c69
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c3440
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_iwdg.c85
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_pwr.c569
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c915
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c776
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c5058
-rw-r--r--source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c1271
-rw-r--r--source/Core/BSP/Miniware/flash.c59
-rw-r--r--source/Core/BSP/Miniware/fusb302b.cpp335
-rw-r--r--source/Core/BSP/Miniware/logo.cpp17
-rw-r--r--source/Core/BSP/Miniware/port.c948
-rw-r--r--source/Core/BSP/Miniware/postRTOS.cpp12
-rw-r--r--source/Core/BSP/Miniware/preRTOS.cpp24
-rw-r--r--source/Core/BSP/Miniware/stm32f1xx_hal_msp.c237
-rw-r--r--source/Core/BSP/Miniware/stm32f1xx_hal_timebase_TIM.c96
-rw-r--r--source/Core/BSP/Miniware/stm32f1xx_it.c90
-rw-r--r--source/Core/BSP/Miniware/system_stm32f1xx.c313
-rw-r--r--source/Core/Drivers/BMA223.cpp91
-rw-r--r--source/Core/Drivers/Buttons.cpp186
-rw-r--r--source/Core/Drivers/FUSB302/fusbpd.cpp20
-rw-r--r--source/Core/Drivers/FUSB302/int_n.cpp88
-rw-r--r--source/Core/Drivers/FUSB302/policy_engine.cpp1140
-rw-r--r--source/Core/Drivers/FUSB302/policy_engine_user.cpp346
-rw-r--r--source/Core/Drivers/FUSB302/protocol_rx.cpp240
-rw-r--r--source/Core/Drivers/FUSB302/protocol_tx.cpp403
-rw-r--r--source/Core/Drivers/I2CBB.cpp487
-rw-r--r--source/Core/Drivers/LIS2DH12.cpp46
-rw-r--r--source/Core/Drivers/MMA8652FC.cpp68
-rw-r--r--source/Core/Drivers/MSA301.cpp60
-rw-r--r--source/Core/Drivers/OLED.cpp742
-rw-r--r--source/Core/Drivers/SC7A20.cpp91
-rw-r--r--source/Core/Drivers/Si7210.cpp281
-rw-r--r--source/Core/Drivers/TipThermoModel.cpp354
-rw-r--r--source/Core/Src/FreeRTOSHooks.c29
-rw-r--r--source/Core/Src/QC3.cpp269
-rw-r--r--source/Core/Src/Settings.cpp120
-rw-r--r--source/Core/Src/freertos.c92
-rw-r--r--source/Core/Src/gui.cpp1417
-rw-r--r--source/Core/Src/main.cpp75
-rw-r--r--source/Core/Src/power.cpp88
-rw-r--r--source/Core/Src/syscalls.c17
-rw-r--r--source/Core/Threads/GUIThread.cpp1640
-rw-r--r--source/Core/Threads/MOVThread.cpp200
-rw-r--r--source/Core/Threads/PIDThread.cpp197
-rw-r--r--source/Core/Threads/POWThread.cpp10
-rw-r--r--source/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS/cmsis_os.c1460
-rw-r--r--source/Middlewares/Third_Party/FreeRTOS/Source/croutine.c474
-rw-r--r--source/Middlewares/Third_Party/FreeRTOS/Source/event_groups.c1126
-rw-r--r--source/Middlewares/Third_Party/FreeRTOS/Source/list.c260
-rw-r--r--source/Middlewares/Third_Party/FreeRTOS/Source/queue.c4627
-rw-r--r--source/Middlewares/Third_Party/FreeRTOS/Source/tasks.c8488
-rw-r--r--source/Middlewares/Third_Party/FreeRTOS/Source/timers.c1544
68 files changed, 22233 insertions, 26886 deletions
diff --git a/source/Core/BSP/Miniware/BSP.cpp b/source/Core/BSP/Miniware/BSP.cpp
index 9d309abe..51f8211c 100644
--- a/source/Core/BSP/Miniware/BSP.cpp
+++ b/source/Core/BSP/Miniware/BSP.cpp
@@ -1,159 +1,156 @@
-//BSP mapping functions
+// BSP mapping functions
-#include <IRQ.h>
#include "BSP.h"
+#include "I2C_Wrapper.hpp"
+#include "Model_Config.h"
+#include "Pins.h"
#include "Setup.h"
#include "history.hpp"
-#include "Pins.h"
#include "main.hpp"
-#include "history.hpp"
-#include "Model_Config.h"
-#include "I2C_Wrapper.hpp"
+#include <IRQ.h>
volatile uint16_t PWMSafetyTimer = 0;
-volatile uint8_t pendingPWM = 0;
+volatile uint8_t pendingPWM = 0;
-const uint16_t powerPWM = 255;
-static const uint8_t holdoffTicks = 14; // delay of 8 ms
+const uint16_t powerPWM = 255;
+static const uint8_t holdoffTicks = 14; // delay of 8 ms
static const uint8_t tempMeasureTicks = 14;
-uint16_t totalPWM; //htim2.Init.Period, the full PWM cycle
+uint16_t totalPWM; // htim2.Init.Period, the full PWM cycle
static bool fastPWM;
-//2 second filter (ADC is PID_TIM_HZ Hz)
-history<uint16_t, PID_TIM_HZ> rawTempFilter = { { 0 }, 0, 0 };
-void resetWatchdog() {
- HAL_IWDG_Refresh(&hiwdg);
-}
+// 2 second filter (ADC is PID_TIM_HZ Hz)
+history<uint16_t, PID_TIM_HZ> rawTempFilter = {{0}, 0, 0};
+void resetWatchdog() { HAL_IWDG_Refresh(&hiwdg); }
#ifdef TEMP_NTC
-//Lookup table for the NTC
-//Stored as ADCReading,Temp in degC
+// Lookup table for the NTC
+// Stored as ADCReading,Temp in degC
static const uint16_t NTCHandleLookup[] = {
-//ADC Reading , Temp in C
- 29189, 0, //
- 29014, 1, //
- 28832, 2, //
- 28644, 3, //
- 28450, 4, //
- 28249, 5, //
- 28042, 6, //
- 27828, 7, //
- 27607, 8, //
- 27380, 9, //
- 27146, 10, //
- 26906, 11, //
- 26660, 12, //
- 26407, 13, //
- 26147, 14, //
- 25882, 15, //
- 25610, 16, //
- 25332, 17, //
- 25049, 18, //
- 24759, 19, //
- 24465, 20, //
- 24164, 21, //
- 23859, 22, //
- 23549, 23, //
- 23234, 24, //
- 22915, 25, //
- 22591, 26, //
- 22264, 27, //
- 21933, 28, //
- 21599, 29, //
- 21261, 30, //
- 20921, 31, //
- 20579, 32, //
- 20234, 33, //
- 19888, 34, //
- 19541, 35, //
- 19192, 36, //
- 18843, 37, //
- 18493, 38, //
- 18143, 39, //
- 17793, 40, //
- 17444, 41, //
- 17096, 42, //
- 16750, 43, //
- 16404, 44, //
- 16061, 45, //
- // 15719, 46, //
- // 15380, 47, //
- // 15044, 48, //
- // 14710, 49, //
- // 14380, 50, //
- // 14053, 51, //
- // 13729, 52, //
- // 13410, 53, //
- // 13094, 54, //
- // 12782, 55, //
- // 12475, 56, //
- // 12172, 57, //
- // 11874, 58, //
- // 11580, 59, //
- // 11292, 60, //
- };
+ // ADC Reading , Temp in C
+ 29189, 0, //
+ 29014, 1, //
+ 28832, 2, //
+ 28644, 3, //
+ 28450, 4, //
+ 28249, 5, //
+ 28042, 6, //
+ 27828, 7, //
+ 27607, 8, //
+ 27380, 9, //
+ 27146, 10, //
+ 26906, 11, //
+ 26660, 12, //
+ 26407, 13, //
+ 26147, 14, //
+ 25882, 15, //
+ 25610, 16, //
+ 25332, 17, //
+ 25049, 18, //
+ 24759, 19, //
+ 24465, 20, //
+ 24164, 21, //
+ 23859, 22, //
+ 23549, 23, //
+ 23234, 24, //
+ 22915, 25, //
+ 22591, 26, //
+ 22264, 27, //
+ 21933, 28, //
+ 21599, 29, //
+ 21261, 30, //
+ 20921, 31, //
+ 20579, 32, //
+ 20234, 33, //
+ 19888, 34, //
+ 19541, 35, //
+ 19192, 36, //
+ 18843, 37, //
+ 18493, 38, //
+ 18143, 39, //
+ 17793, 40, //
+ 17444, 41, //
+ 17096, 42, //
+ 16750, 43, //
+ 16404, 44, //
+ 16061, 45, //
+ // 15719, 46, //
+ // 15380, 47, //
+ // 15044, 48, //
+ // 14710, 49, //
+ // 14380, 50, //
+ // 14053, 51, //
+ // 13729, 52, //
+ // 13410, 53, //
+ // 13094, 54, //
+ // 12782, 55, //
+ // 12475, 56, //
+ // 12172, 57, //
+ // 11874, 58, //
+ // 11580, 59, //
+ // 11292, 60, //
+};
#endif
uint16_t getHandleTemperature() {
#ifdef TEMP_NTC
- //TS80P uses 100k NTC resistors instead
- //NTCG104EF104FT1X from TDK
- //For now not doing interpolation
- int32_t result = getADC(0);
- for (uint32_t i = 0; i < (sizeof(NTCHandleLookup) / (2 * sizeof(uint16_t))); i++) {
- if (result > NTCHandleLookup[(i * 2) + 0]) {
- return NTCHandleLookup[(i * 2) + 1] * 10;
- }
- }
- return 45 * 10;
+ // TS80P uses 100k NTC resistors instead
+ // NTCG104EF104FT1X from TDK
+ // For now not doing interpolation
+ int32_t result = getADC(0);
+ for (uint32_t i = 0; i < (sizeof(NTCHandleLookup) / (2 * sizeof(uint16_t))); i++) {
+ if (result > NTCHandleLookup[(i * 2) + 0]) {
+ return NTCHandleLookup[(i * 2) + 1] * 10;
+ }
+ }
+ return 45 * 10;
#endif
#ifdef TEMP_TMP36
- // We return the current handle temperature in X10 C
- // TMP36 in handle, 0.5V offset and then 10mV per deg C (0.75V @ 25C for
- // example) STM32 = 4096 count @ 3.3V input -> But We oversample by 32/(2^2) =
- // 8 times oversampling Therefore 32768 is the 3.3V input, so 0.1007080078125
- // mV per count So we need to subtract an offset of 0.5V to center on 0C
- // (4964.8 counts)
- //
- int32_t result = getADC(0);
- result -= 4965; // remove 0.5V offset
- // 10mV per C
- // 99.29 counts per Deg C above 0C. Tends to read a tad over across all of my sample units
- result *= 100;
- result /= 994;
- return result;
+ // We return the current handle temperature in X10 C
+ // TMP36 in handle, 0.5V offset and then 10mV per deg C (0.75V @ 25C for
+ // example) STM32 = 4096 count @ 3.3V input -> But We oversample by 32/(2^2) =
+ // 8 times oversampling Therefore 32768 is the 3.3V input, so 0.1007080078125
+ // mV per count So we need to subtract an offset of 0.5V to center on 0C
+ // (4964.8 counts)
+ //
+ int32_t result = getADC(0);
+ result -= 4965; // remove 0.5V offset
+ // 10mV per C
+ // 99.29 counts per Deg C above 0C. Tends to read a tad over across all of my sample units
+ result *= 100;
+ result /= 994;
+ return result;
#endif
}
uint16_t getTipInstantTemperature() {
- uint16_t sum = 0; // 12 bit readings * 8 -> 15 bits
- uint16_t readings[8];
- //Looking to reject the highest outlier readings.
- //As on some hardware these samples can run into the op-amp recovery time
- //Once this time is up the signal stabilises quickly, so no need to reject minimums
- readings[0] = hadc1.Instance->JDR1;
- readings[1] = hadc1.Instance->JDR2;
- readings[2] = hadc1.Instance->JDR3;
- readings[3] = hadc1.Instance->JDR4;
- readings[4] = hadc2.Instance->JDR1;
- readings[5] = hadc2.Instance->JDR2;
- readings[6] = hadc2.Instance->JDR3;
- readings[7] = hadc2.Instance->JDR4;
-
- for (int i = 0; i < 8; i++) {
- sum += readings[i];
- }
- return sum; // 8x over sample
+ uint16_t sum = 0; // 12 bit readings * 8 -> 15 bits
+ uint16_t readings[8];
+ // Looking to reject the highest outlier readings.
+ // As on some hardware these samples can run into the op-amp recovery time
+ // Once this time is up the signal stabilises quickly, so no need to reject minimums
+ readings[0] = hadc1.Instance->JDR1;
+ readings[1] = hadc1.Instance->JDR2;
+ readings[2] = hadc1.Instance->JDR3;
+ readings[3] = hadc1.Instance->JDR4;
+ readings[4] = hadc2.Instance->JDR1;
+ readings[5] = hadc2.Instance->JDR2;
+ readings[6] = hadc2.Instance->JDR3;
+ readings[7] = hadc2.Instance->JDR4;
+
+ for (int i = 0; i < 8; i++) {
+ sum += readings[i];
+ }
+ return sum; // 8x over sample
}
uint16_t getTipRawTemp(uint8_t refresh) {
- if (refresh) {
- uint16_t lastSample = getTipInstantTemperature();
- rawTempFilter.update(lastSample);
- return lastSample;
- } else {
- return rawTempFilter.average();
- }
+ if (refresh) {
+ uint16_t lastSample = getTipInstantTemperature();
+ rawTempFilter.update(lastSample);
+ return lastSample;
+ } else {
+ return rawTempFilter.average();
+ }
}
uint16_t getInputVoltageX10(uint16_t divisor, uint8_t sample) {
@@ -167,187 +164,177 @@ uint16_t getInputVoltageX10(uint16_t divisor, uint8_t sample) {
#define BATTFILTERDEPTH 8
#endif
- static uint8_t preFillneeded = 10;
- static uint32_t samples[BATTFILTERDEPTH];
- static uint8_t index = 0;
- if (preFillneeded) {
- for (uint8_t i = 0; i < BATTFILTERDEPTH; i++)
- samples[i] = getADC(1);
- preFillneeded--;
- }
- if (sample) {
- samples[index] = getADC(1);
- index = (index + 1) % BATTFILTERDEPTH;
- }
- uint32_t sum = 0;
-
- for (uint8_t i = 0; i < BATTFILTERDEPTH; i++)
- sum += samples[i];
-
- sum /= BATTFILTERDEPTH;
- if (divisor == 0) {
- divisor = 1;
- }
- return sum * 4 / divisor;
+ static uint8_t preFillneeded = 10;
+ static uint32_t samples[BATTFILTERDEPTH];
+ static uint8_t index = 0;
+ if (preFillneeded) {
+ for (uint8_t i = 0; i < BATTFILTERDEPTH; i++)
+ samples[i] = getADC(1);
+ preFillneeded--;
+ }
+ if (sample) {
+ samples[index] = getADC(1);
+ index = (index + 1) % BATTFILTERDEPTH;
+ }
+ uint32_t sum = 0;
+
+ for (uint8_t i = 0; i < BATTFILTERDEPTH; i++)
+ sum += samples[i];
+
+ sum /= BATTFILTERDEPTH;
+ if (divisor == 0) {
+ divisor = 1;
+ }
+ return sum * 4 / divisor;
}
void setTipPWM(uint8_t pulse) {
- PWMSafetyTimer = 10; // This is decremented in the handler for PWM so that the tip pwm is
- // disabled if the PID task is not scheduled often enough.
+ PWMSafetyTimer = 10; // This is decremented in the handler for PWM so that the tip pwm is
+ // disabled if the PID task is not scheduled often enough.
- pendingPWM = pulse;
+ pendingPWM = pulse;
}
static void switchToFastPWM(void) {
- fastPWM = true;
- totalPWM = powerPWM + tempMeasureTicks * 2 + holdoffTicks;
- htim2.Instance->ARR = totalPWM;
- // ~3.5 Hz rate
- htim2.Instance->CCR1 = powerPWM + holdoffTicks * 2;
- // 2 MHz timer clock/2000 = 1 kHz tick rate
- htim2.Instance->PSC = 2000;
+ fastPWM = true;
+ totalPWM = powerPWM + tempMeasureTicks * 2 + holdoffTicks;
+ htim2.Instance->ARR = totalPWM;
+ // ~3.5 Hz rate
+ htim2.Instance->CCR1 = powerPWM + holdoffTicks * 2;
+ // 2 MHz timer clock/2000 = 1 kHz tick rate
+ htim2.Instance->PSC = 2000;
}
static void switchToSlowPWM(void) {
- fastPWM = false;
- totalPWM = powerPWM + tempMeasureTicks + holdoffTicks;
- htim2.Instance->ARR = totalPWM;
- // ~1.84 Hz rate
- htim2.Instance->CCR1 = powerPWM + holdoffTicks;
- // 2 MHz timer clock/4000 = 500 Hz tick rate
- htim2.Instance->PSC = 4000;
+ fastPWM = false;
+ totalPWM = powerPWM + tempMeasureTicks + holdoffTicks;
+ htim2.Instance->ARR = totalPWM;
+ // ~1.84 Hz rate
+ htim2.Instance->CCR1 = powerPWM + holdoffTicks;
+ // 2 MHz timer clock/4000 = 500 Hz tick rate
+ htim2.Instance->PSC = 4000;
}
bool tryBetterPWM(uint8_t pwm) {
- if (fastPWM && pwm == powerPWM) {
- // maximum power for fast PWM reached, need to go slower to get more
- switchToSlowPWM();
- return true;
- } else if (!fastPWM && pwm < 230) {
- // 254 in fast PWM mode gives the same power as 239 in slow
- // allow for some reasonable hysteresis by switching only when it goes
- // below 230 (equivalent to 245 in fast mode)
- switchToFastPWM();
- return true;
- }
- return false;
+ if (fastPWM && pwm == powerPWM) {
+ // maximum power for fast PWM reached, need to go slower to get more
+ switchToSlowPWM();
+ return true;
+ } else if (!fastPWM && pwm < 230) {
+ // 254 in fast PWM mode gives the same power as 239 in slow
+ // allow for some reasonable hysteresis by switching only when it goes
+ // below 230 (equivalent to 245 in fast mode)
+ switchToFastPWM();
+ return true;
+ }
+ return false;
}
// These are called by the HAL after the corresponding events from the system
// timers.
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
- // Period has elapsed
- if (htim->Instance == TIM2) {
- // we want to turn on the output again
- PWMSafetyTimer--;
- // We decrement this safety value so that lockups in the
- // scheduler will not cause the PWM to become locked in an
- // active driving state.
- // While we could assume this could never happen, its a small price for
- // increased safety
- htim2.Instance->CCR4 = pendingPWM;
- if (htim2.Instance->CCR4 && PWMSafetyTimer) {
- HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
- } else {
- HAL_TIM_PWM_Stop(&htim3, TIM_CHANNEL_1);
- }
- } else if (htim->Instance == TIM1) {
- // STM uses this for internal functions as a counter for timeouts
- HAL_IncTick();
- }
+ // Period has elapsed
+ if (htim->Instance == TIM2) {
+ // we want to turn on the output again
+ PWMSafetyTimer--;
+ // We decrement this safety value so that lockups in the
+ // scheduler will not cause the PWM to become locked in an
+ // active driving state.
+ // While we could assume this could never happen, its a small price for
+ // increased safety
+ htim2.Instance->CCR4 = pendingPWM;
+ if (htim2.Instance->CCR4 && PWMSafetyTimer) {
+ HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
+ } else {
+ HAL_TIM_PWM_Stop(&htim3, TIM_CHANNEL_1);
+ }
+ } else if (htim->Instance == TIM1) {
+ // STM uses this for internal functions as a counter for timeouts
+ HAL_IncTick();
+ }
}
void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) {
- // This was a when the PWM for the output has timed out
- if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4) {
- HAL_TIM_PWM_Stop(&htim3, TIM_CHANNEL_1);
- }
+ // This was a when the PWM for the output has timed out
+ if (htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4) {
+ HAL_TIM_PWM_Stop(&htim3, TIM_CHANNEL_1);
+ }
}
void unstick_I2C() {
- GPIO_InitTypeDef GPIO_InitStruct;
- int timeout = 100;
- int timeout_cnt = 0;
-
- // 1. Clear PE bit.
- hi2c1.Instance->CR1 &= ~(0x0001);
- /**I2C1 GPIO Configuration
- PB6 ------> I2C1_SCL
- PB7 ------> I2C1_SDA
- */
- // 2. Configure the SCL and SDA I/Os as General Purpose Output Open-Drain, High level (Write 1 to GPIOx_ODR).
- GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
- GPIO_InitStruct.Pull = GPIO_PULLUP;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
-
- GPIO_InitStruct.Pin = SCL_Pin;
- HAL_GPIO_Init(SCL_GPIO_Port, &GPIO_InitStruct);
- HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET);
-
- GPIO_InitStruct.Pin = SDA_Pin;
- HAL_GPIO_Init(SDA_GPIO_Port, &GPIO_InitStruct);
- HAL_GPIO_WritePin(SDA_GPIO_Port, SDA_Pin, GPIO_PIN_SET);
-
- while (GPIO_PIN_SET != HAL_GPIO_ReadPin(SDA_GPIO_Port, SDA_Pin)) {
- //Move clock to release I2C
- HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_RESET);
- asm("nop");
- asm("nop");
- asm("nop");
- asm("nop");
- HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET);
-
- timeout_cnt++;
- if (timeout_cnt > timeout)
- return;
- }
-
- // 12. Configure the SCL and SDA I/Os as Alternate function Open-Drain.
- GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
- GPIO_InitStruct.Pull = GPIO_PULLUP;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
-
- GPIO_InitStruct.Pin = SCL_Pin;
- HAL_GPIO_Init(SCL_GPIO_Port, &GPIO_InitStruct);
-
- GPIO_InitStruct.Pin = SDA_Pin;
- HAL_GPIO_Init(SDA_GPIO_Port, &GPIO_InitStruct);
-
- HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET);
- HAL_GPIO_WritePin(SDA_GPIO_Port, SDA_Pin, GPIO_PIN_SET);
-
- // 13. Set SWRST bit in I2Cx_CR1 register.
- hi2c1.Instance->CR1 |= 0x8000;
-
- asm("nop");
-
- // 14. Clear SWRST bit in I2Cx_CR1 register.
- hi2c1.Instance->CR1 &= ~0x8000;
-
- asm("nop");
-
- // 15. Enable the I2C peripheral by setting the PE bit in I2Cx_CR1 register
- hi2c1.Instance->CR1 |= 0x0001;
-
- // Call initialization function.
- HAL_I2C_Init(&hi2c1);
+ GPIO_InitTypeDef GPIO_InitStruct;
+ int timeout = 100;
+ int timeout_cnt = 0;
+
+ // 1. Clear PE bit.
+ hi2c1.Instance->CR1 &= ~(0x0001);
+ /**I2C1 GPIO Configuration
+ PB6 ------> I2C1_SCL
+ PB7 ------> I2C1_SDA
+ */
+ // 2. Configure the SCL and SDA I/Os as General Purpose Output Open-Drain, High level (Write 1 to GPIOx_ODR).
+ GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
+ GPIO_InitStruct.Pull = GPIO_PULLUP;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
+
+ GPIO_InitStruct.Pin = SCL_Pin;
+ HAL_GPIO_Init(SCL_GPIO_Port, &GPIO_InitStruct);
+ HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET);
+
+ GPIO_InitStruct.Pin = SDA_Pin;
+ HAL_GPIO_Init(SDA_GPIO_Port, &GPIO_InitStruct);
+ HAL_GPIO_WritePin(SDA_GPIO_Port, SDA_Pin, GPIO_PIN_SET);
+
+ while (GPIO_PIN_SET != HAL_GPIO_ReadPin(SDA_GPIO_Port, SDA_Pin)) {
+ // Move clock to release I2C
+ HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_RESET);
+ asm("nop");
+ asm("nop");
+ asm("nop");
+ asm("nop");
+ HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET);
+
+ timeout_cnt++;
+ if (timeout_cnt > timeout)
+ return;
+ }
+
+ // 12. Configure the SCL and SDA I/Os as Alternate function Open-Drain.
+ GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
+ GPIO_InitStruct.Pull = GPIO_PULLUP;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
+
+ GPIO_InitStruct.Pin = SCL_Pin;
+ HAL_GPIO_Init(SCL_GPIO_Port, &GPIO_InitStruct);
+
+ GPIO_InitStruct.Pin = SDA_Pin;
+ HAL_GPIO_Init(SDA_GPIO_Port, &GPIO_InitStruct);
+
+ HAL_GPIO_WritePin(SCL_GPIO_Port, SCL_Pin, GPIO_PIN_SET);
+ HAL_GPIO_WritePin(SDA_GPIO_Port, SDA_Pin, GPIO_PIN_SET);
+
+ // 13. Set SWRST bit in I2Cx_CR1 register.
+ hi2c1.Instance->CR1 |= 0x8000;
+
+ asm("nop");
+
+ // 14. Clear SWRST bit in I2Cx_CR1 register.
+ hi2c1.Instance->CR1 &= ~0x8000;
+
+ asm("nop");
+
+ // 15. Enable the I2C peripheral by setting the PE bit in I2Cx_CR1 register
+ hi2c1.Instance->CR1 |= 0x0001;
+
+ // Call initialization function.
+ HAL_I2C_Init(&hi2c1);
}
-uint8_t getButtonA() {
- return HAL_GPIO_ReadPin(KEY_A_GPIO_Port, KEY_A_Pin) == GPIO_PIN_RESET ? 1 : 0;
-}
-uint8_t getButtonB() {
- return HAL_GPIO_ReadPin(KEY_B_GPIO_Port, KEY_B_Pin) == GPIO_PIN_RESET ? 1 : 0;
-}
+uint8_t getButtonA() { return HAL_GPIO_ReadPin(KEY_A_GPIO_Port, KEY_A_Pin) == GPIO_PIN_RESET ? 1 : 0; }
+uint8_t getButtonB() { return HAL_GPIO_ReadPin(KEY_B_GPIO_Port, KEY_B_Pin) == GPIO_PIN_RESET ? 1 : 0; }
-void BSPInit(void) {
- switchToFastPWM();
-}
+void BSPInit(void) { switchToFastPWM(); }
-void reboot() {
- NVIC_SystemReset();
-}
+void reboot() { NVIC_SystemReset(); }
-void delay_ms(uint16_t count) {
- HAL_Delay(count);
-}
+void delay_ms(uint16_t count) { HAL_Delay(count); }
diff --git a/source/Core/BSP/Miniware/BSP_PD.c b/source/Core/BSP/Miniware/BSP_PD.c
index 0b3c2af9..0083caeb 100644
--- a/source/Core/BSP/Miniware/BSP_PD.c
+++ b/source/Core/BSP/Miniware/BSP_PD.c
@@ -12,11 +12,11 @@
* An array of all of the desired voltages & minimum currents in preferred order
*/
const uint16_t USB_PD_Desired_Levels[] = {
-//mV desired input, mA minimum required current
- 12000, 2400, //12V @ 2.4A
- 9000, 2000, //9V @ 2A
- 5000, 100, //5V @ whatever
+ // mV desired input, mA minimum required current
+ 12000, 2400, // 12V @ 2.4A
+ 9000, 2000, // 9V @ 2A
+ 5000, 100, // 5V @ whatever
- };
+};
const uint8_t USB_PD_Desired_Levels_Len = 3;
#endif
diff --git a/source/Core/BSP/Miniware/I2C_Wrapper.cpp b/source/Core/BSP/Miniware/I2C_Wrapper.cpp
index e4fc3307..37d521c1 100644
--- a/source/Core/BSP/Miniware/I2C_Wrapper.cpp
+++ b/source/Core/BSP/Miniware/I2C_Wrapper.cpp
@@ -11,97 +11,81 @@ SemaphoreHandle_t FRToSI2C::I2CSemaphore = nullptr;
StaticSemaphore_t FRToSI2C::xSemaphoreBuffer;
void FRToSI2C::CpltCallback() {
- hi2c1.State = HAL_I2C_STATE_READY; // Force state reset (even if tx error)
- if (I2CSemaphore) {
- xSemaphoreGiveFromISR(I2CSemaphore, NULL);
- }
+ hi2c1.State = HAL_I2C_STATE_READY; // Force state reset (even if tx error)
+ if (I2CSemaphore) {
+ xSemaphoreGiveFromISR(I2CSemaphore, NULL);
+ }
}
-bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t MemAddress,
- uint8_t *pData, uint16_t Size) {
+bool FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) {
- if (!lock())
- return false;
- if (HAL_I2C_Mem_Read(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT,
- pData, Size, 500) != HAL_OK) {
+ if (!lock())
+ return false;
+ if (HAL_I2C_Mem_Read(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 500) != HAL_OK) {
- I2C_Unstick();
- unlock();
- return false;
- }
+ I2C_Unstick();
+ unlock();
+ return false;
+ }
- unlock();
- return true;
-}
-bool FRToSI2C::I2C_RegisterWrite(uint8_t address, uint8_t reg, uint8_t data) {
- return Mem_Write(address, reg, &data, 1);
+ unlock();
+ return true;
}
+bool FRToSI2C::I2C_RegisterWrite(uint8_t address, uint8_t reg, uint8_t data) { return Mem_Write(address, reg, &data, 1); }
uint8_t FRToSI2C::I2C_RegisterRead(uint8_t add, uint8_t reg) {
- uint8_t tx_data[1];
- Mem_Read(add, reg, tx_data, 1);
- return tx_data[0];
+ uint8_t tx_data[1];
+ Mem_Read(add, reg, tx_data, 1);
+ return tx_data[0];
}
-bool FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress,
- uint8_t *pData, uint16_t Size) {
+bool FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) {
- if (!lock())
- return false;
- if (HAL_I2C_Mem_Write(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT,
- pData, Size, 500) != HAL_OK) {
+ if (!lock())
+ return false;
+ if (HAL_I2C_Mem_Write(&hi2c1, DevAddress, MemAddress, I2C_MEMADD_SIZE_8BIT, pData, Size, 500) != HAL_OK) {
- I2C_Unstick();
- unlock();
- return false;
- }
+ I2C_Unstick();
+ unlock();
+ return false;
+ }
- unlock();
- return true;
+ unlock();
+ return true;
}
bool FRToSI2C::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) {
- if (!lock())
- return false;
- if (HAL_I2C_Master_Transmit_DMA(&hi2c1, DevAddress, pData, Size)
- != HAL_OK) {
- I2C_Unstick();
- unlock();
- return false;
- }
- return true;
+ if (!lock())
+ return false;
+ if (HAL_I2C_Master_Transmit_DMA(&hi2c1, DevAddress, pData, Size) != HAL_OK) {
+ I2C_Unstick();
+ unlock();
+ return false;
+ }
+ return true;
}
bool FRToSI2C::probe(uint16_t DevAddress) {
- if (!lock())
- return false;
- uint8_t buffer[1];
- bool worked = HAL_I2C_Mem_Read(&hi2c1, DevAddress, 0x0F,
- I2C_MEMADD_SIZE_8BIT, buffer, 1, 1000) == HAL_OK;
- unlock();
- return worked;
+ if (!lock())
+ return false;
+ uint8_t buffer[1];
+ bool worked = HAL_I2C_Mem_Read(&hi2c1, DevAddress, 0x0F, I2C_MEMADD_SIZE_8BIT, buffer, 1, 1000) == HAL_OK;
+ unlock();
+ return worked;
}
-void FRToSI2C::I2C_Unstick() {
- unstick_I2C();
-}
+void FRToSI2C::I2C_Unstick() { unstick_I2C(); }
-void FRToSI2C::unlock() {
- xSemaphoreGive(I2CSemaphore);
-}
+void FRToSI2C::unlock() { xSemaphoreGive(I2CSemaphore); }
-bool FRToSI2C::lock() {
- return xSemaphoreTake(I2CSemaphore, (TickType_t)50) == pdTRUE;
-}
+bool FRToSI2C::lock() { return xSemaphoreTake(I2CSemaphore, (TickType_t)50) == pdTRUE; }
-bool FRToSI2C::writeRegistersBulk(const uint8_t address,
- const I2C_REG *registers, const uint8_t registersLength) {
- for (int index = 0; index < registersLength; index++) {
- if (!I2C_RegisterWrite(address, registers[index].reg,
- registers[index].val)) {
- return false;
- }
- if (registers[index].pause_ms)
- delay_ms(registers[index].pause_ms);
- }
- return true;
+bool FRToSI2C::writeRegistersBulk(const uint8_t address, const I2C_REG *registers, const uint8_t registersLength) {
+ for (int index = 0; index < registersLength; index++) {
+ if (!I2C_RegisterWrite(address, registers[index].reg, registers[index].val)) {
+ return false;
+ }
+ if (registers[index].pause_ms)
+ delay_ms(registers[index].pause_ms);
+ }
+ return true;
}
diff --git a/source/Core/BSP/Miniware/IRQ.cpp b/source/Core/BSP/Miniware/IRQ.cpp
index e480c2ba..5a5ffd0e 100644
--- a/source/Core/BSP/Miniware/IRQ.cpp
+++ b/source/Core/BSP/Miniware/IRQ.cpp
@@ -13,37 +13,22 @@
* runs again
*/
void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) {
- BaseType_t xHigherPriorityTaskWoken = pdFALSE;
- if (hadc == &hadc1) {
- if (pidTaskNotification) {
- vTaskNotifyGiveFromISR(pidTaskNotification,
- &xHigherPriorityTaskWoken);
- portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
- }
- }
-}
-void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) {
- FRToSI2C::CpltCallback();
-}
-void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) {
- FRToSI2C::CpltCallback();
-}
-void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) {
- FRToSI2C::CpltCallback();
-}
-void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c __unused) {
-
- FRToSI2C::CpltCallback();
-}
-void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c __unused) {
-
- FRToSI2C::CpltCallback();
-}
-void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) {
- FRToSI2C::CpltCallback();
-}
+ BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+ if (hadc == &hadc1) {
+ if (pidTaskNotification) {
+ vTaskNotifyGiveFromISR(pidTaskNotification, &xHigherPriorityTaskWoken);
+ portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
+ }
+ }
+}
+void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); }
+void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); }
+void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); }
+void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); }
+void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); }
+void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c __unused) { FRToSI2C::CpltCallback(); }
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
- (void) GPIO_Pin;
- InterruptHandler::irqCallback();
+ (void)GPIO_Pin;
+ InterruptHandler::irqCallback();
}
diff --git a/source/Core/BSP/Miniware/Power.cpp b/source/Core/BSP/Miniware/Power.cpp
index 95fc916a..f2f23534 100644
--- a/source/Core/BSP/Miniware/Power.cpp
+++ b/source/Core/BSP/Miniware/Power.cpp
@@ -1,49 +1,48 @@
#include "BSP.h"
#include "BSP_Power.h"
+#include "Model_Config.h"
+#include "Pins.h"
#include "QC3.h"
#include "Settings.h"
-#include "Pins.h"
#include "fusbpd.h"
-#include "Model_Config.h"
-#include "policy_engine.h"
#include "int_n.h"
+#include "policy_engine.h"
bool FUSB302_present = false;
void power_check() {
#ifdef POW_PD
- if (FUSB302_present) {
- //Cant start QC until either PD works or fails
- if (PolicyEngine::setupCompleteOrTimedOut() == false) {
- return;
- }
- if (PolicyEngine::pdHasNegotiated()) {
- return;
- }
- }
+ if (FUSB302_present) {
+ // Cant start QC until either PD works or fails
+ if (PolicyEngine::setupCompleteOrTimedOut() == false) {
+ return;
+ }
+ if (PolicyEngine::pdHasNegotiated()) {
+ return;
+ }
+ }
#endif
#ifdef POW_QC
- QC_resync();
+ QC_resync();
#endif
}
uint8_t usb_pd_detect() {
#ifdef POW_PD
- FUSB302_present = fusb302_detect();
- return FUSB302_present;
+ FUSB302_present = fusb302_detect();
+ return FUSB302_present;
#endif
- return false;
+ return false;
}
bool getIsPoweredByDCIN() {
#ifdef MODEL_TS80
- return false;
+ return false;
#endif
#ifdef MODEL_TS80P
- return false;
+ return false;
#endif
#ifdef MODEL_TS100
- return true;
+ return true;
#endif
}
-
diff --git a/source/Core/BSP/Miniware/QC_GPIO.cpp b/source/Core/BSP/Miniware/QC_GPIO.cpp
index 6dcb333c..b48ba1f3 100644
--- a/source/Core/BSP/Miniware/QC_GPIO.cpp
+++ b/source/Core/BSP/Miniware/QC_GPIO.cpp
@@ -5,74 +5,72 @@
* Author: Ralim
*/
#include "BSP.h"
+#include "Model_Config.h"
#include "Pins.h"
#include "QC3.h"
#include "Settings.h"
#include "stm32f1xx_hal.h"
-#include "Model_Config.h"
#ifdef POW_QC
void QC_DPlusZero_Six() {
- HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_RESET); // pull down D+
+ HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_RESET); // pull down D+
}
void QC_DNegZero_Six() {
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET);
+ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);
+ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET);
}
void QC_DPlusThree_Three() {
- HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_SET); // pull up D+
+ HAL_GPIO_WritePin(GPIOB, GPIO_PIN_3, GPIO_PIN_SET); // pull up D+
}
void QC_DNegThree_Three() {
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
+ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, GPIO_PIN_SET);
+ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET);
}
void QC_DM_PullDown() {
- GPIO_InitTypeDef GPIO_InitStruct;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
- GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
- GPIO_InitStruct.Pull = GPIO_PULLDOWN;
- GPIO_InitStruct.Pin = GPIO_PIN_11;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
+ GPIO_InitTypeDef GPIO_InitStruct;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
+ GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
+ GPIO_InitStruct.Pull = GPIO_PULLDOWN;
+ GPIO_InitStruct.Pin = GPIO_PIN_11;
+ HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
void QC_DM_No_PullDown() {
- GPIO_InitTypeDef GPIO_InitStruct;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
- GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
- GPIO_InitStruct.Pull = GPIO_NOPULL;
- GPIO_InitStruct.Pin = GPIO_PIN_11;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
+ GPIO_InitTypeDef GPIO_InitStruct;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
+ GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
+ GPIO_InitStruct.Pull = GPIO_NOPULL;
+ GPIO_InitStruct.Pin = GPIO_PIN_11;
+ HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
void QC_Init_GPIO() {
- // Setup any GPIO into the right states for QC
- GPIO_InitTypeDef GPIO_InitStruct;
- GPIO_InitStruct.Pin = GPIO_PIN_3;
- GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
- HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
- GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
- GPIO_InitStruct.Pull = GPIO_NOPULL;
- GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_10;
- HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
- // Turn off output mode on pins that we can
- GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
- GPIO_InitStruct.Pull = GPIO_NOPULL;
- GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_14 | GPIO_PIN_13;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
+ // Setup any GPIO into the right states for QC
+ GPIO_InitTypeDef GPIO_InitStruct;
+ GPIO_InitStruct.Pin = GPIO_PIN_3;
+ GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
+ HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
+ GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
+ GPIO_InitStruct.Pull = GPIO_NOPULL;
+ GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_10;
+ HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
+ // Turn off output mode on pins that we can
+ GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
+ GPIO_InitStruct.Pull = GPIO_NOPULL;
+ GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_14 | GPIO_PIN_13;
+ HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
void QC_Post_Probe_En() {
- GPIO_InitTypeDef GPIO_InitStruct;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
- GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_10;
- GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
+ GPIO_InitTypeDef GPIO_InitStruct;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
+ GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_10;
+ GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
+ HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
-uint8_t QC_DM_PulledDown() {
- return HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_11) == GPIO_PIN_RESET ? 1 : 0;
-}
+uint8_t QC_DM_PulledDown() { return HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_11) == GPIO_PIN_RESET ? 1 : 0; }
#endif
void QC_resync() {
#ifdef POW_QC
- seekQC((systemSettings.QCIdealVoltage) ? 120 : 90,
- systemSettings.voltageDiv); // Run the QC seek again if we have drifted too much
+ seekQC((systemSettings.QCIdealVoltage) ? 120 : 90,
+ systemSettings.voltageDiv); // Run the QC seek again if we have drifted too much
#endif
}
diff --git a/source/Core/BSP/Miniware/Setup.c b/source/Core/BSP/Miniware/Setup.c
index 0c368c30..dcdf796f 100644
--- a/source/Core/BSP/Miniware/Setup.c
+++ b/source/Core/BSP/Miniware/Setup.c
@@ -15,11 +15,11 @@ DMA_HandleTypeDef hdma_i2c1_rx;
DMA_HandleTypeDef hdma_i2c1_tx;
IWDG_HandleTypeDef hiwdg;
-TIM_HandleTypeDef htim2;
-TIM_HandleTypeDef htim3;
+TIM_HandleTypeDef htim2;
+TIM_HandleTypeDef htim3;
#define ADC_CHANNELS 2
-#define ADC_SAMPLES 16
-uint32_t ADCReadings[ADC_SAMPLES * ADC_CHANNELS]; // room for 32 lots of the pair of readings
+#define ADC_SAMPLES 16
+uint32_t ADCReadings[ADC_SAMPLES * ADC_CHANNELS]; // room for 32 lots of the pair of readings
// Functions
static void SystemClock_Config(void);
@@ -31,358 +31,352 @@ static void MX_TIM2_Init(void);
static void MX_DMA_Init(void);
static void MX_GPIO_Init(void);
static void MX_ADC2_Init(void);
-void Setup_HAL() {
- SystemClock_Config();
+void Setup_HAL() {
+ SystemClock_Config();
#ifndef SWD_ENABLE
- __HAL_AFIO_REMAP_SWJ_DISABLE();
+ __HAL_AFIO_REMAP_SWJ_DISABLE();
#else
- __HAL_AFIO_REMAP_SWJ_NOJTAG();
+ __HAL_AFIO_REMAP_SWJ_NOJTAG();
#endif
- MX_GPIO_Init();
- MX_DMA_Init();
- MX_I2C1_Init();
- MX_ADC1_Init();
- MX_ADC2_Init();
- MX_TIM3_Init();
- MX_TIM2_Init();
- MX_IWDG_Init();
- HAL_ADC_Start(&hadc2);
- HAL_ADCEx_MultiModeStart_DMA(&hadc1, ADCReadings, (ADC_SAMPLES * ADC_CHANNELS)); // start DMA of normal readings
- HAL_ADCEx_InjectedStart(&hadc1); // enable injected readings
- HAL_ADCEx_InjectedStart(&hadc2); // enable injected readings
+ MX_GPIO_Init();
+ MX_DMA_Init();
+ MX_I2C1_Init();
+ MX_ADC1_Init();
+ MX_ADC2_Init();
+ MX_TIM3_Init();
+ MX_TIM2_Init();
+ MX_IWDG_Init();
+ HAL_ADC_Start(&hadc2);
+ HAL_ADCEx_MultiModeStart_DMA(&hadc1, ADCReadings, (ADC_SAMPLES * ADC_CHANNELS)); // start DMA of normal readings
+ HAL_ADCEx_InjectedStart(&hadc1); // enable injected readings
+ HAL_ADCEx_InjectedStart(&hadc2); // enable injected readings
}
// channel 0 -> temperature sensor, 1-> VIN
uint16_t getADC(uint8_t channel) {
- uint32_t sum = 0;
- for (uint8_t i = 0; i < ADC_SAMPLES; i++) {
- uint16_t adc1Sample = ADCReadings[channel + (i * ADC_CHANNELS)];
- uint16_t adc2Sample = ADCReadings[channel + (i * ADC_CHANNELS)] >> 16;
-
- sum += (adc1Sample + adc2Sample);
- }
- return sum >> 2;
+ uint32_t sum = 0;
+ for (uint8_t i = 0; i < ADC_SAMPLES; i++) {
+ uint16_t adc1Sample = ADCReadings[channel + (i * ADC_CHANNELS)];
+ uint16_t adc2Sample = ADCReadings[channel + (i * ADC_CHANNELS)] >> 16;
+
+ sum += (adc1Sample + adc2Sample);
+ }
+ return sum >> 2;
}
/** System Clock Configuration
*/
void SystemClock_Config(void) {
- RCC_OscInitTypeDef RCC_OscInitStruct;
- RCC_ClkInitTypeDef RCC_ClkInitStruct;
- RCC_PeriphCLKInitTypeDef PeriphClkInit;
-
- /**Initializes the CPU, AHB and APB busses clocks
- */
- RCC_OscInitStruct.OscillatorType =
- RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI;
- RCC_OscInitStruct.HSIState = RCC_HSI_ON;
- RCC_OscInitStruct.HSICalibrationValue = 16;
- RCC_OscInitStruct.LSIState = RCC_LSI_ON;
- RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
- RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
- RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16; // 64MHz
- HAL_RCC_OscConfig(&RCC_OscInitStruct);
-
- /**Initializes the CPU, AHB and APB busses clocks
- */
- RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK |
- RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
- RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
- RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
- RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV16; // TIM
- // 2,3,4,5,6,7,12,13,14
- RCC_ClkInitStruct.APB2CLKDivider =
- RCC_HCLK_DIV1; // 64 mhz to some peripherals and adc
-
- HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2);
-
- PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
- PeriphClkInit.AdcClockSelection =
- RCC_ADCPCLK2_DIV6; // 6 or 8 are the only non overclocked options
- HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
-
- /**Configure the Systick interrupt time
- */
- HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000);
-
- /**Configure the Systick
- */
- HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
-
- /* SysTick_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0);
+ RCC_OscInitTypeDef RCC_OscInitStruct;
+ RCC_ClkInitTypeDef RCC_ClkInitStruct;
+ RCC_PeriphCLKInitTypeDef PeriphClkInit;
+
+ /**Initializes the CPU, AHB and APB busses clocks
+ */
+ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSI;
+ RCC_OscInitStruct.HSIState = RCC_HSI_ON;
+ RCC_OscInitStruct.HSICalibrationValue = 16;
+ RCC_OscInitStruct.LSIState = RCC_LSI_ON;
+ RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
+ RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI_DIV2;
+ RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16; // 64MHz
+ HAL_RCC_OscConfig(&RCC_OscInitStruct);
+
+ /**Initializes the CPU, AHB and APB busses clocks
+ */
+ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
+ RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
+ RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
+ RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV16; // TIM
+ // 2,3,4,5,6,7,12,13,14
+ RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 64 mhz to some peripherals and adc
+
+ HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2);
+
+ PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
+ PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6; // 6 or 8 are the only non overclocked options
+ HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit);
+
+ /**Configure the Systick interrupt time
+ */
+ HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000);
+
+ /**Configure the Systick
+ */
+ HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
+
+ /* SysTick_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0);
}
/* ADC1 init function */
static void MX_ADC1_Init(void) {
- ADC_MultiModeTypeDef multimode;
-
- ADC_ChannelConfTypeDef sConfig;
- ADC_InjectionConfTypeDef sConfigInjected;
- /**Common config
- */
- hadc1.Instance = ADC1;
- hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
- hadc1.Init.ContinuousConvMode = ENABLE;
- hadc1.Init.DiscontinuousConvMode = DISABLE;
- hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
- hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
- hadc1.Init.NbrOfConversion = ADC_CHANNELS;
- HAL_ADC_Init(&hadc1);
-
- /**Configure the ADC multi-mode
- */
- multimode.Mode = ADC_DUALMODE_REGSIMULT_INJECSIMULT;
- HAL_ADCEx_MultiModeConfigChannel(&hadc1, &multimode);
-
- /**Configure Regular Channel
- */
- sConfig.Channel = TMP36_ADC1_CHANNEL;
- sConfig.Rank = ADC_REGULAR_RANK_1;
- sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5;
- HAL_ADC_ConfigChannel(&hadc1, &sConfig);
-
- /**Configure Regular Channel
- */
- sConfig.Channel = VIN_ADC1_CHANNEL;
- sConfig.Rank = ADC_REGULAR_RANK_2;
- HAL_ADC_ConfigChannel(&hadc1, &sConfig);
-
- /**Configure Injected Channel
- */
- // F in = 10.66 MHz
- /*
- * Injected time is 1 delay clock + (12 adc cycles*4)+4*sampletime =~217
- * clocks = 0.2ms Charge time is 0.016 uS ideally So Sampling time must be >=
- * 0.016uS 1/10.66MHz is 0.09uS, so 1 CLK is *should* be enough
- * */
- sConfigInjected.InjectedChannel = TIP_TEMP_ADC1_CHANNEL;
- sConfigInjected.InjectedRank = 1;
- sConfigInjected.InjectedNbrOfConversion = 4;
- sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
- sConfigInjected.ExternalTrigInjecConv = ADC_EXTERNALTRIGINJECCONV_T2_CC1;
- sConfigInjected.AutoInjectedConv = DISABLE;
- sConfigInjected.InjectedDiscontinuousConvMode = DISABLE;
- sConfigInjected.InjectedOffset = 0;
-
- HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
- sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
-
- sConfigInjected.InjectedRank = 2;
- HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
- sConfigInjected.InjectedRank = 3;
- HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
- sConfigInjected.InjectedRank = 4;
- HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
- SET_BIT(hadc1.Instance->CR1, (ADC_CR1_JEOCIE)); // Enable end of injected conv irq
- // Run ADC internal calibration
- while (HAL_ADCEx_Calibration_Start(&hadc1) != HAL_OK)
- ;
+ ADC_MultiModeTypeDef multimode;
+
+ ADC_ChannelConfTypeDef sConfig;
+ ADC_InjectionConfTypeDef sConfigInjected;
+ /**Common config
+ */
+ hadc1.Instance = ADC1;
+ hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
+ hadc1.Init.ContinuousConvMode = ENABLE;
+ hadc1.Init.DiscontinuousConvMode = DISABLE;
+ hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
+ hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
+ hadc1.Init.NbrOfConversion = ADC_CHANNELS;
+ HAL_ADC_Init(&hadc1);
+
+ /**Configure the ADC multi-mode
+ */
+ multimode.Mode = ADC_DUALMODE_REGSIMULT_INJECSIMULT;
+ HAL_ADCEx_MultiModeConfigChannel(&hadc1, &multimode);
+
+ /**Configure Regular Channel
+ */
+ sConfig.Channel = TMP36_ADC1_CHANNEL;
+ sConfig.Rank = ADC_REGULAR_RANK_1;
+ sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5;
+ HAL_ADC_ConfigChannel(&hadc1, &sConfig);
+
+ /**Configure Regular Channel
+ */
+ sConfig.Channel = VIN_ADC1_CHANNEL;
+ sConfig.Rank = ADC_REGULAR_RANK_2;
+ HAL_ADC_ConfigChannel(&hadc1, &sConfig);
+
+ /**Configure Injected Channel
+ */
+ // F in = 10.66 MHz
+ /*
+ * Injected time is 1 delay clock + (12 adc cycles*4)+4*sampletime =~217
+ * clocks = 0.2ms Charge time is 0.016 uS ideally So Sampling time must be >=
+ * 0.016uS 1/10.66MHz is 0.09uS, so 1 CLK is *should* be enough
+ * */
+ sConfigInjected.InjectedChannel = TIP_TEMP_ADC1_CHANNEL;
+ sConfigInjected.InjectedRank = 1;
+ sConfigInjected.InjectedNbrOfConversion = 4;
+ sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
+ sConfigInjected.ExternalTrigInjecConv = ADC_EXTERNALTRIGINJECCONV_T2_CC1;
+ sConfigInjected.AutoInjectedConv = DISABLE;
+ sConfigInjected.InjectedDiscontinuousConvMode = DISABLE;
+ sConfigInjected.InjectedOffset = 0;
+
+ HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
+ sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
+
+ sConfigInjected.InjectedRank = 2;
+ HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
+ sConfigInjected.InjectedRank = 3;
+ HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
+ sConfigInjected.InjectedRank = 4;
+ HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
+ SET_BIT(hadc1.Instance->CR1, (ADC_CR1_JEOCIE)); // Enable end of injected conv irq
+ // Run ADC internal calibration
+ while (HAL_ADCEx_Calibration_Start(&hadc1) != HAL_OK)
+ ;
}
/* ADC2 init function */
static void MX_ADC2_Init(void) {
- ADC_ChannelConfTypeDef sConfig;
- ADC_InjectionConfTypeDef sConfigInjected;
-
- /**Common config
- */
- hadc2.Instance = ADC2;
- hadc2.Init.ScanConvMode = ADC_SCAN_ENABLE;
- hadc2.Init.ContinuousConvMode = ENABLE;
- hadc2.Init.DiscontinuousConvMode = DISABLE;
- hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
- hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
- hadc2.Init.NbrOfConversion = ADC_CHANNELS;
- HAL_ADC_Init(&hadc2);
-
- /**Configure Regular Channel
- */
- sConfig.Channel = TMP36_ADC2_CHANNEL;
- sConfig.Rank = ADC_REGULAR_RANK_1;
- sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5;
- HAL_ADC_ConfigChannel(&hadc2, &sConfig);
-
- sConfig.Channel = VIN_ADC2_CHANNEL;
- sConfig.Rank = ADC_REGULAR_RANK_2;
- HAL_ADC_ConfigChannel(&hadc2, &sConfig);
-
- /**Configure Injected Channel
- */
- sConfigInjected.InjectedChannel = TIP_TEMP_ADC2_CHANNEL;
- sConfigInjected.InjectedRank = ADC_INJECTED_RANK_1;
- sConfigInjected.InjectedNbrOfConversion = 4;
- sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
- sConfigInjected.ExternalTrigInjecConv = ADC_EXTERNALTRIGINJECCONV_T2_CC1;
- sConfigInjected.AutoInjectedConv = DISABLE;
- sConfigInjected.InjectedDiscontinuousConvMode = DISABLE;
- sConfigInjected.InjectedOffset = 0;
- HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected);
- sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
-
- sConfigInjected.InjectedRank = ADC_INJECTED_RANK_2;
- HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected);
- sConfigInjected.InjectedRank = ADC_INJECTED_RANK_3;
- HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected);
- sConfigInjected.InjectedRank = ADC_INJECTED_RANK_4;
- HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected);
-
- // Run ADC internal calibration
- while (HAL_ADCEx_Calibration_Start(&hadc2) != HAL_OK)
- ;
+ ADC_ChannelConfTypeDef sConfig;
+ ADC_InjectionConfTypeDef sConfigInjected;
+
+ /**Common config
+ */
+ hadc2.Instance = ADC2;
+ hadc2.Init.ScanConvMode = ADC_SCAN_ENABLE;
+ hadc2.Init.ContinuousConvMode = ENABLE;
+ hadc2.Init.DiscontinuousConvMode = DISABLE;
+ hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
+ hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
+ hadc2.Init.NbrOfConversion = ADC_CHANNELS;
+ HAL_ADC_Init(&hadc2);
+
+ /**Configure Regular Channel
+ */
+ sConfig.Channel = TMP36_ADC2_CHANNEL;
+ sConfig.Rank = ADC_REGULAR_RANK_1;
+ sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5;
+ HAL_ADC_ConfigChannel(&hadc2, &sConfig);
+
+ sConfig.Channel = VIN_ADC2_CHANNEL;
+ sConfig.Rank = ADC_REGULAR_RANK_2;
+ HAL_ADC_ConfigChannel(&hadc2, &sConfig);
+
+ /**Configure Injected Channel
+ */
+ sConfigInjected.InjectedChannel = TIP_TEMP_ADC2_CHANNEL;
+ sConfigInjected.InjectedRank = ADC_INJECTED_RANK_1;
+ sConfigInjected.InjectedNbrOfConversion = 4;
+ sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
+ sConfigInjected.ExternalTrigInjecConv = ADC_EXTERNALTRIGINJECCONV_T2_CC1;
+ sConfigInjected.AutoInjectedConv = DISABLE;
+ sConfigInjected.InjectedDiscontinuousConvMode = DISABLE;
+ sConfigInjected.InjectedOffset = 0;
+ HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected);
+ sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
+
+ sConfigInjected.InjectedRank = ADC_INJECTED_RANK_2;
+ HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected);
+ sConfigInjected.InjectedRank = ADC_INJECTED_RANK_3;
+ HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected);
+ sConfigInjected.InjectedRank = ADC_INJECTED_RANK_4;
+ HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected);
+
+ // Run ADC internal calibration
+ while (HAL_ADCEx_Calibration_Start(&hadc2) != HAL_OK)
+ ;
}
/* I2C1 init function */
static void MX_I2C1_Init(void) {
- hi2c1.Instance = I2C1;
- hi2c1.Init.ClockSpeed = 75000;
- // OLED doesnt handle >100k when its asleep (off).
- hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
- hi2c1.Init.OwnAddress1 = 0;
- hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
- hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
- hi2c1.Init.OwnAddress2 = 0;
- hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
- hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
- HAL_I2C_Init(&hi2c1);
+ hi2c1.Instance = I2C1;
+ hi2c1.Init.ClockSpeed = 75000;
+ // OLED doesnt handle >100k when its asleep (off).
+ hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
+ hi2c1.Init.OwnAddress1 = 0;
+ hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
+ hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
+ hi2c1.Init.OwnAddress2 = 0;
+ hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
+ hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
+ HAL_I2C_Init(&hi2c1);
}
/* IWDG init function */
static void MX_IWDG_Init(void) {
- hiwdg.Instance = IWDG;
- hiwdg.Init.Prescaler = IWDG_PRESCALER_256;
- hiwdg.Init.Reload = 100;
+ hiwdg.Instance = IWDG;
+ hiwdg.Init.Prescaler = IWDG_PRESCALER_256;
+ hiwdg.Init.Reload = 100;
#ifndef SWD_ENABLE
- HAL_IWDG_Init(&hiwdg);
+ HAL_IWDG_Init(&hiwdg);
#endif
}
/* TIM3 init function */
static void MX_TIM3_Init(void) {
- TIM_ClockConfigTypeDef sClockSourceConfig;
- TIM_MasterConfigTypeDef sMasterConfig;
- TIM_OC_InitTypeDef sConfigOC;
-
- htim3.Instance = TIM3;
- htim3.Init.Prescaler = 8;
- htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
- htim3.Init.Period = 100; // 5 Khz PWM freq
- htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV4; // 4mhz before div
- htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE; //Preload the ARR register (though we dont use this)
- HAL_TIM_Base_Init(&htim3);
-
- sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
- HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig);
-
- HAL_TIM_PWM_Init(&htim3);
-
- HAL_TIM_OC_Init(&htim3);
-
- sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
- sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
- HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig);
-
- sConfigOC.OCMode = TIM_OCMODE_PWM1;
- sConfigOC.Pulse = 50; //50% duty cycle, that is AC coupled through the cap
- sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
- sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
- HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, PWM_Out_CHANNEL);
-
- GPIO_InitTypeDef GPIO_InitStruct;
-
- /**TIM3 GPIO Configuration
- PWM_Out_Pin ------> TIM3_CH1
- */
- GPIO_InitStruct.Pin = PWM_Out_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; //We would like sharp rising edges
- HAL_GPIO_Init(PWM_Out_GPIO_Port, &GPIO_InitStruct);
+ TIM_ClockConfigTypeDef sClockSourceConfig;
+ TIM_MasterConfigTypeDef sMasterConfig;
+ TIM_OC_InitTypeDef sConfigOC;
+
+ htim3.Instance = TIM3;
+ htim3.Init.Prescaler = 8;
+ htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
+ htim3.Init.Period = 100; // 5 Khz PWM freq
+ htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV4; // 4mhz before div
+ htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE; // Preload the ARR register (though we dont use this)
+ HAL_TIM_Base_Init(&htim3);
+
+ sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
+ HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig);
+
+ HAL_TIM_PWM_Init(&htim3);
+
+ HAL_TIM_OC_Init(&htim3);
+
+ sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
+ sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
+ HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig);
+
+ sConfigOC.OCMode = TIM_OCMODE_PWM1;
+ sConfigOC.Pulse = 50; // 50% duty cycle, that is AC coupled through the cap
+ sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
+ sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
+ HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, PWM_Out_CHANNEL);
+
+ GPIO_InitTypeDef GPIO_InitStruct;
+
+ /**TIM3 GPIO Configuration
+ PWM_Out_Pin ------> TIM3_CH1
+ */
+ GPIO_InitStruct.Pin = PWM_Out_Pin;
+ GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; // We would like sharp rising edges
+ HAL_GPIO_Init(PWM_Out_GPIO_Port, &GPIO_InitStruct);
#ifdef MODEL_TS100
- // Remap TIM3_CH1 to be on PB4
- __HAL_AFIO_REMAP_TIM3_PARTIAL()
- ;
+ // Remap TIM3_CH1 to be on PB4
+ __HAL_AFIO_REMAP_TIM3_PARTIAL();
#else
- // No re-map required
+ // No re-map required
#endif
- HAL_TIM_PWM_Start(&htim3, PWM_Out_CHANNEL);
+ HAL_TIM_PWM_Start(&htim3, PWM_Out_CHANNEL);
}
/* TIM3 init function */
static void MX_TIM2_Init(void) {
- /*
- * We use the channel 1 to trigger the ADC at end of PWM period
- * And we use the channel 4 as the PWM modulation source using Interrupts
- * */
- TIM_ClockConfigTypeDef sClockSourceConfig;
- TIM_MasterConfigTypeDef sMasterConfig;
- TIM_OC_InitTypeDef sConfigOC;
-
- // Timer 2 is fairly slow as its being used to run the PWM and trigger the ADC
- // in the PWM off time.
- htim2.Instance = TIM2;
- // dummy value, will be reconfigured by BSPInit()
- htim2.Init.Prescaler = 2000; // 2 MHz timer clock/2000 = 1 kHz tick rate
-
- // pwm out is 10k from tim3, we want to run our PWM at around 10hz or slower on the output stage
- // These values give a rate of around 3.5 Hz for "fast" mode and 1.84 Hz for "slow"
- htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
- // dummy value, will be reconfigured by BSPInit()
- htim2.Init.Period = 255 + 17 * 2;
- htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV4; // 8 MHz (x2 APB1) before divide
- htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
- htim2.Init.RepetitionCounter = 0;
- HAL_TIM_Base_Init(&htim2);
-
- sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
- HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig);
-
- HAL_TIM_PWM_Init(&htim2);
- HAL_TIM_OC_Init(&htim2);
-
- sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
- sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
- HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig);
-
- sConfigOC.OCMode = TIM_OCMODE_PWM1;
- // dummy value, will be reconfigured by BSPInit() in the BSP.cpp
- sConfigOC.Pulse = 255 + 13 * 2; // 13 -> Delay of 7 ms
- //255 is the largest time period of the drive signal, and then offset ADC sample to be a bit delayed after this
- /*
- * It takes 4 milliseconds for output to be stable after PWM turns off.
- * Assume ADC samples in 0.5ms
- * We need to set this to 100% + 4.5ms
- * */
- sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
- sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
- HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);
- sConfigOC.Pulse = 0; //default to entirely off
- HAL_TIM_OC_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_4);
-
- HAL_TIM_Base_Start_IT(&htim2);
- HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
- HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_4);
- HAL_NVIC_SetPriority(TIM2_IRQn, 15, 0);
- HAL_NVIC_EnableIRQ(TIM2_IRQn);
+ /*
+ * We use the channel 1 to trigger the ADC at end of PWM period
+ * And we use the channel 4 as the PWM modulation source using Interrupts
+ * */
+ TIM_ClockConfigTypeDef sClockSourceConfig;
+ TIM_MasterConfigTypeDef sMasterConfig;
+ TIM_OC_InitTypeDef sConfigOC;
+
+ // Timer 2 is fairly slow as its being used to run the PWM and trigger the ADC
+ // in the PWM off time.
+ htim2.Instance = TIM2;
+ // dummy value, will be reconfigured by BSPInit()
+ htim2.Init.Prescaler = 2000; // 2 MHz timer clock/2000 = 1 kHz tick rate
+
+ // pwm out is 10k from tim3, we want to run our PWM at around 10hz or slower on the output stage
+ // These values give a rate of around 3.5 Hz for "fast" mode and 1.84 Hz for "slow"
+ htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
+ // dummy value, will be reconfigured by BSPInit()
+ htim2.Init.Period = 255 + 17 * 2;
+ htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV4; // 8 MHz (x2 APB1) before divide
+ htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
+ htim2.Init.RepetitionCounter = 0;
+ HAL_TIM_Base_Init(&htim2);
+
+ sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
+ HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig);
+
+ HAL_TIM_PWM_Init(&htim2);
+ HAL_TIM_OC_Init(&htim2);
+
+ sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
+ sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
+ HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig);
+
+ sConfigOC.OCMode = TIM_OCMODE_PWM1;
+ // dummy value, will be reconfigured by BSPInit() in the BSP.cpp
+ sConfigOC.Pulse = 255 + 13 * 2; // 13 -> Delay of 7 ms
+ // 255 is the largest time period of the drive signal, and then offset ADC sample to be a bit delayed after this
+ /*
+ * It takes 4 milliseconds for output to be stable after PWM turns off.
+ * Assume ADC samples in 0.5ms
+ * We need to set this to 100% + 4.5ms
+ * */
+ sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
+ sConfigOC.OCFastMode = TIM_OCFAST_ENABLE;
+ HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1);
+ sConfigOC.Pulse = 0; // default to entirely off
+ HAL_TIM_OC_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_4);
+
+ HAL_TIM_Base_Start_IT(&htim2);
+ HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
+ HAL_TIM_PWM_Start_IT(&htim2, TIM_CHANNEL_4);
+ HAL_NVIC_SetPriority(TIM2_IRQn, 15, 0);
+ HAL_NVIC_EnableIRQ(TIM2_IRQn);
}
/**
* Enable DMA controller clock
*/
static void MX_DMA_Init(void) {
- /* DMA controller clock enable */
- __HAL_RCC_DMA1_CLK_ENABLE()
- ;
-
- /* DMA interrupt init */
- /* DMA1_Channel1_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 5, 0);
- HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
- /* DMA1_Channel6_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(DMA1_Channel6_IRQn, 5, 0);
- HAL_NVIC_EnableIRQ(DMA1_Channel6_IRQn);
- /* DMA1_Channel7_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(DMA1_Channel7_IRQn, 5, 0);
- HAL_NVIC_EnableIRQ(DMA1_Channel7_IRQn);
+ /* DMA controller clock enable */
+ __HAL_RCC_DMA1_CLK_ENABLE();
+
+ /* DMA interrupt init */
+ /* DMA1_Channel1_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 5, 0);
+ HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
+ /* DMA1_Channel6_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(DMA1_Channel6_IRQn, 5, 0);
+ HAL_NVIC_EnableIRQ(DMA1_Channel6_IRQn);
+ /* DMA1_Channel7_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(DMA1_Channel7_IRQn, 5, 0);
+ HAL_NVIC_EnableIRQ(DMA1_Channel7_IRQn);
}
/** Configure pins as
@@ -396,90 +390,80 @@ static void MX_DMA_Init(void) {
PB1 ------> ADCx_IN9
*/
static void MX_GPIO_Init(void) {
- GPIO_InitTypeDef GPIO_InitStruct;
-
- /* GPIO Ports Clock Enable */
- __HAL_RCC_GPIOD_CLK_ENABLE()
- ;
- __HAL_RCC_GPIOA_CLK_ENABLE()
- ;
- __HAL_RCC_GPIOB_CLK_ENABLE()
- ;
-
- /*Configure GPIO pin Output Level */
- HAL_GPIO_WritePin(OLED_RESET_GPIO_Port, OLED_RESET_Pin, GPIO_PIN_RESET);
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
- /*Configure GPIO pins : PD0 PD1 */
- GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1;
- GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
- HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
- /*Configure peripheral I/O remapping */
- __HAL_AFIO_REMAP_PD01_ENABLE()
- ;
- //^ remap XTAL so that pins can be analog (all input buffers off).
- // reduces power consumption
-
- /*
- * Configure All pins as analog by default
- */
- GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 |
- GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 |
- GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_15;
- GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
- GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 |
+ GPIO_InitTypeDef GPIO_InitStruct;
+
+ /* GPIO Ports Clock Enable */
+ __HAL_RCC_GPIOD_CLK_ENABLE();
+ __HAL_RCC_GPIOA_CLK_ENABLE();
+ __HAL_RCC_GPIOB_CLK_ENABLE();
+
+ /*Configure GPIO pin Output Level */
+ HAL_GPIO_WritePin(OLED_RESET_GPIO_Port, OLED_RESET_Pin, GPIO_PIN_RESET);
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
+ /*Configure GPIO pins : PD0 PD1 */
+ GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1;
+ GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
+ HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
+ /*Configure peripheral I/O remapping */
+ __HAL_AFIO_REMAP_PD01_ENABLE();
+ //^ remap XTAL so that pins can be analog (all input buffers off).
+ // reduces power consumption
+
+ /*
+ * Configure All pins as analog by default
+ */
+ GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_15;
+ GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
+ HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
+ GPIO_InitStruct.Pin = GPIO_PIN_0 | GPIO_PIN_1 | GPIO_PIN_2 |
#ifdef MODEL_TS100
- GPIO_PIN_3 |
+ GPIO_PIN_3 |
#endif
- GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 |
- GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 |
- GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15;
- HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
+ GPIO_PIN_4 | GPIO_PIN_5 | GPIO_PIN_6 | GPIO_PIN_7 | GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15;
+ HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
#ifdef MODEL_TS100
#ifndef SWD_ENABLE
- /* Pull USB and SWD lines low to prevent enumeration attempts and EMI affecting
- * the debug core */
- GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14;
- GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11, GPIO_PIN_RESET);
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, GPIO_PIN_RESET);
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_13, GPIO_PIN_RESET);
- HAL_GPIO_WritePin(GPIOA, GPIO_PIN_14, GPIO_PIN_RESET);
+ /* Pull USB and SWD lines low to prevent enumeration attempts and EMI affecting
+ * the debug core */
+ GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14;
+ GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
+ HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
+ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11, GPIO_PIN_RESET);
+ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, GPIO_PIN_RESET);
+ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_13, GPIO_PIN_RESET);
+ HAL_GPIO_WritePin(GPIOA, GPIO_PIN_14, GPIO_PIN_RESET);
#else
- /* Make all lines affecting SWD floating to allow debugging */
- GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_14 | GPIO_PIN_13;
- GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
+ /* Make all lines affecting SWD floating to allow debugging */
+ GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_14 | GPIO_PIN_13;
+ GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
+ HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
#endif
#else
- /* TS80 */
- /* Leave USB lines open circuit*/
+ /* TS80 */
+ /* Leave USB lines open circuit*/
#endif
- /*Configure GPIO pins : KEY_B_Pin KEY_A_Pin */
- GPIO_InitStruct.Pin = KEY_B_Pin | KEY_A_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
- GPIO_InitStruct.Pull = GPIO_PULLUP;
- HAL_GPIO_Init(KEY_B_GPIO_Port, &GPIO_InitStruct);
-
- /*Configure GPIO pin : OLED_RESET_Pin */
- GPIO_InitStruct.Pin = OLED_RESET_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
- HAL_GPIO_Init(OLED_RESET_GPIO_Port, &GPIO_InitStruct);
- HAL_GPIO_WritePin(OLED_RESET_GPIO_Port, OLED_RESET_Pin, GPIO_PIN_RESET);
-
- // Pull down LCD reset
- HAL_GPIO_WritePin(OLED_RESET_GPIO_Port, OLED_RESET_Pin, GPIO_PIN_RESET);
- HAL_Delay(30);
- HAL_GPIO_WritePin(OLED_RESET_GPIO_Port, OLED_RESET_Pin, GPIO_PIN_SET);
-}
-#ifdef USE_FULL_ASSERT
-void assert_failed(uint8_t* file, uint32_t line){
- asm("bkpt");
+ /*Configure GPIO pins : KEY_B_Pin KEY_A_Pin */
+ GPIO_InitStruct.Pin = KEY_B_Pin | KEY_A_Pin;
+ GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
+ GPIO_InitStruct.Pull = GPIO_PULLUP;
+ HAL_GPIO_Init(KEY_B_GPIO_Port, &GPIO_InitStruct);
+
+ /*Configure GPIO pin : OLED_RESET_Pin */
+ GPIO_InitStruct.Pin = OLED_RESET_Pin;
+ GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
+ HAL_GPIO_Init(OLED_RESET_GPIO_Port, &GPIO_InitStruct);
+ HAL_GPIO_WritePin(OLED_RESET_GPIO_Port, OLED_RESET_Pin, GPIO_PIN_RESET);
+
+ // Pull down LCD reset
+ HAL_GPIO_WritePin(OLED_RESET_GPIO_Port, OLED_RESET_Pin, GPIO_PIN_RESET);
+ HAL_Delay(30);
+ HAL_GPIO_WritePin(OLED_RESET_GPIO_Port, OLED_RESET_Pin, GPIO_PIN_SET);
}
+#ifdef USE_FULL_ASSERT
+void assert_failed(uint8_t *file, uint32_t line) { asm("bkpt"); }
#endif
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c
index a449258b..4e8304d1 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal.c
@@ -52,13 +52,13 @@
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup HAL HAL
- * @brief HAL module driver.
- * @{
- */
+ * @brief HAL module driver.
+ * @{
+ */
#ifdef HAL_MODULE_ENABLED
@@ -66,44 +66,41 @@
/* Private define ------------------------------------------------------------*/
/** @defgroup HAL_Private_Constants HAL Private Constants
- * @{
- */
+ * @{
+ */
/**
* @brief STM32F1xx HAL Driver version number V1.1.3
- */
-#define __STM32F1xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */
-#define __STM32F1xx_HAL_VERSION_SUB1 (0x01U) /*!< [23:16] sub1 version */
-#define __STM32F1xx_HAL_VERSION_SUB2 (0x03U) /*!< [15:8] sub2 version */
-#define __STM32F1xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */
-#define __STM32F1xx_HAL_VERSION ((__STM32F1xx_HAL_VERSION_MAIN << 24)\
- |(__STM32F1xx_HAL_VERSION_SUB1 << 16)\
- |(__STM32F1xx_HAL_VERSION_SUB2 << 8 )\
- |(__STM32F1xx_HAL_VERSION_RC))
+ */
+#define __STM32F1xx_HAL_VERSION_MAIN (0x01U) /*!< [31:24] main version */
+#define __STM32F1xx_HAL_VERSION_SUB1 (0x01U) /*!< [23:16] sub1 version */
+#define __STM32F1xx_HAL_VERSION_SUB2 (0x03U) /*!< [15:8] sub2 version */
+#define __STM32F1xx_HAL_VERSION_RC (0x00U) /*!< [7:0] release candidate */
+#define __STM32F1xx_HAL_VERSION ((__STM32F1xx_HAL_VERSION_MAIN << 24) | (__STM32F1xx_HAL_VERSION_SUB1 << 16) | (__STM32F1xx_HAL_VERSION_SUB2 << 8) | (__STM32F1xx_HAL_VERSION_RC))
-#define IDCODE_DEVID_MASK 0x00000FFFU
+#define IDCODE_DEVID_MASK 0x00000FFFU
/**
- * @}
- */
+ * @}
+ */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/** @defgroup HAL_Private_Variables HAL Private Variables
- * @{
- */
-__IO uint32_t uwTick;
-uint32_t uwTickPrio = (1UL << __NVIC_PRIO_BITS); /* Invalid PRIO */
-HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */
-/**
- * @}
- */
+ * @{
+ */
+__IO uint32_t uwTick;
+uint32_t uwTickPrio = (1UL << __NVIC_PRIO_BITS); /* Invalid PRIO */
+HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */
+/**
+ * @}
+ */
/* Private function prototypes -----------------------------------------------*/
/* Exported functions ---------------------------------------------------------*/
/** @defgroup HAL_Exported_Functions HAL Exported Functions
- * @{
- */
+ * @{
+ */
/** @defgroup HAL_Exported_Functions_Group1 Initialization and de-initialization Functions
* @brief Initialization and de-initialization functions
@@ -139,30 +136,27 @@ HAL_TickFreqTypeDef uwTickFreq = HAL_TICK_FREQ_DEFAULT; /* 1KHz */
*/
/**
- * @brief This function is used to initialize the HAL Library; it must be the first
- * instruction to be executed in the main program (before to call any other
- * HAL function), it performs the following:
- * Configure the Flash prefetch.
- * Configures the SysTick to generate an interrupt each 1 millisecond,
- * which is clocked by the HSI (at this stage, the clock is not yet
- * configured and thus the system is running from the internal HSI at 16 MHz).
- * Set NVIC Group Priority to 4.
- * Calls the HAL_MspInit() callback function defined in user file
- * "stm32f1xx_hal_msp.c" to do the global low level hardware initialization
- *
- * @note SysTick is used as time base for the HAL_Delay() function, the application
- * need to ensure that the SysTick time base is always set to 1 millisecond
- * to have correct HAL operation.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_Init(void)
-{
+ * @brief This function is used to initialize the HAL Library; it must be the first
+ * instruction to be executed in the main program (before to call any other
+ * HAL function), it performs the following:
+ * Configure the Flash prefetch.
+ * Configures the SysTick to generate an interrupt each 1 millisecond,
+ * which is clocked by the HSI (at this stage, the clock is not yet
+ * configured and thus the system is running from the internal HSI at 16 MHz).
+ * Set NVIC Group Priority to 4.
+ * Calls the HAL_MspInit() callback function defined in user file
+ * "stm32f1xx_hal_msp.c" to do the global low level hardware initialization
+ *
+ * @note SysTick is used as time base for the HAL_Delay() function, the application
+ * need to ensure that the SysTick time base is always set to 1 millisecond
+ * to have correct HAL operation.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_Init(void) {
/* Configure Flash prefetch */
#if (PREFETCH_ENABLE != 0)
-#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || \
- defined(STM32F102x6) || defined(STM32F102xB) || \
- defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || \
- defined(STM32F105xC) || defined(STM32F107xC)
+#if defined(STM32F101x6) || defined(STM32F101xB) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) \
+ || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
/* Prefetch buffer is not available on value line devices */
__HAL_FLASH_PREFETCH_BUFFER_ENABLE();
@@ -183,13 +177,12 @@ HAL_StatusTypeDef HAL_Init(void)
}
/**
- * @brief This function de-Initializes common part of the HAL and stops the systick.
- * of time base.
- * @note This function is optional.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DeInit(void)
-{
+ * @brief This function de-Initializes common part of the HAL and stops the systick.
+ * of time base.
+ * @note This function is optional.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DeInit(void) {
/* Reset of all peripherals */
__HAL_RCC_APB1_FORCE_RESET();
__HAL_RCC_APB1_RELEASE_RESET();
@@ -210,59 +203,52 @@ HAL_StatusTypeDef HAL_DeInit(void)
}
/**
- * @brief Initialize the MSP.
- * @retval None
- */
-__weak void HAL_MspInit(void)
-{
+ * @brief Initialize the MSP.
+ * @retval None
+ */
+__weak void HAL_MspInit(void) {
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_MspInit could be implemented in the user file
*/
}
/**
- * @brief DeInitializes the MSP.
- * @retval None
- */
-__weak void HAL_MspDeInit(void)
-{
+ * @brief DeInitializes the MSP.
+ * @retval None
+ */
+__weak void HAL_MspDeInit(void) {
/* NOTE : This function should not be modified, when the callback is needed,
the HAL_MspDeInit could be implemented in the user file
*/
}
/**
- * @brief This function configures the source of the time base.
- * The time source is configured to have 1ms time base with a dedicated
- * Tick interrupt priority.
- * @note This function is called automatically at the beginning of program after
- * reset by HAL_Init() or at any time when clock is reconfigured by HAL_RCC_ClockConfig().
- * @note In the default implementation, SysTick timer is the source of time base.
- * It is used to generate interrupts at regular time intervals.
- * Care must be taken if HAL_Delay() is called from a peripheral ISR process,
- * The SysTick interrupt must have higher priority (numerically lower)
- * than the peripheral interrupt. Otherwise the caller ISR process will be blocked.
- * The function is declared as __weak to be overwritten in case of other
- * implementation in user file.
- * @param TickPriority Tick interrupt priority.
- * @retval HAL status
- */
-__weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
-{
+ * @brief This function configures the source of the time base.
+ * The time source is configured to have 1ms time base with a dedicated
+ * Tick interrupt priority.
+ * @note This function is called automatically at the beginning of program after
+ * reset by HAL_Init() or at any time when clock is reconfigured by HAL_RCC_ClockConfig().
+ * @note In the default implementation, SysTick timer is the source of time base.
+ * It is used to generate interrupts at regular time intervals.
+ * Care must be taken if HAL_Delay() is called from a peripheral ISR process,
+ * The SysTick interrupt must have higher priority (numerically lower)
+ * than the peripheral interrupt. Otherwise the caller ISR process will be blocked.
+ * The function is declared as __weak to be overwritten in case of other
+ * implementation in user file.
+ * @param TickPriority Tick interrupt priority.
+ * @retval HAL status
+ */
+__weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) {
/* Configure the SysTick to have interrupt in 1ms time basis*/
- if (HAL_SYSTICK_Config(SystemCoreClock / (1000U / uwTickFreq)) > 0U)
- {
+ if (HAL_SYSTICK_Config(SystemCoreClock / (1000U / uwTickFreq)) > 0U) {
return HAL_ERROR;
}
/* Configure the SysTick IRQ priority */
- if (TickPriority < (1UL << __NVIC_PRIO_BITS))
- {
+ if (TickPriority < (1UL << __NVIC_PRIO_BITS)) {
HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority, 0U);
uwTickPrio = TickPriority;
- }
- else
- {
+ } else {
return HAL_ERROR;
}
@@ -271,8 +257,8 @@ __weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup HAL_Exported_Functions_Group2 HAL Control functions
* @brief HAL Control functions
@@ -298,50 +284,39 @@ __weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority)
*/
/**
- * @brief This function is called to increment a global variable "uwTick"
- * used as application time base.
- * @note In the default implementation, this variable is incremented each 1ms
- * in SysTick ISR.
- * @note This function is declared as __weak to be overwritten in case of other
- * implementations in user file.
- * @retval None
- */
-__weak void HAL_IncTick(void)
-{
- uwTick += uwTickFreq;
-}
+ * @brief This function is called to increment a global variable "uwTick"
+ * used as application time base.
+ * @note In the default implementation, this variable is incremented each 1ms
+ * in SysTick ISR.
+ * @note This function is declared as __weak to be overwritten in case of other
+ * implementations in user file.
+ * @retval None
+ */
+__weak void HAL_IncTick(void) { uwTick += uwTickFreq; }
/**
- * @brief Provides a tick value in millisecond.
- * @note This function is declared as __weak to be overwritten in case of other
- * implementations in user file.
- * @retval tick value
- */
-__weak uint32_t HAL_GetTick(void)
-{
- return uwTick;
-}
+ * @brief Provides a tick value in millisecond.
+ * @note This function is declared as __weak to be overwritten in case of other
+ * implementations in user file.
+ * @retval tick value
+ */
+__weak uint32_t HAL_GetTick(void) { return uwTick; }
/**
- * @brief This function returns a tick priority.
- * @retval tick priority
- */
-uint32_t HAL_GetTickPrio(void)
-{
- return uwTickPrio;
-}
+ * @brief This function returns a tick priority.
+ * @retval tick priority
+ */
+uint32_t HAL_GetTickPrio(void) { return uwTickPrio; }
/**
- * @brief Set new tick Freq.
- * @retval Status
- */
-HAL_StatusTypeDef HAL_SetTickFreq(HAL_TickFreqTypeDef Freq)
-{
- HAL_StatusTypeDef status = HAL_OK;
+ * @brief Set new tick Freq.
+ * @retval Status
+ */
+HAL_StatusTypeDef HAL_SetTickFreq(HAL_TickFreqTypeDef Freq) {
+ HAL_StatusTypeDef status = HAL_OK;
assert_param(IS_TICKFREQ(Freq));
- if (uwTickFreq != Freq)
- {
+ if (uwTickFreq != Freq) {
uwTickFreq = Freq;
/* Apply the new tick Freq */
@@ -352,244 +327,207 @@ HAL_StatusTypeDef HAL_SetTickFreq(HAL_TickFreqTypeDef Freq)
}
/**
- * @brief Return tick frequency.
- * @retval tick period in Hz
- */
-HAL_TickFreqTypeDef HAL_GetTickFreq(void)
-{
- return uwTickFreq;
-}
+ * @brief Return tick frequency.
+ * @retval tick period in Hz
+ */
+HAL_TickFreqTypeDef HAL_GetTickFreq(void) { return uwTickFreq; }
/**
- * @brief This function provides minimum delay (in milliseconds) based
- * on variable incremented.
- * @note In the default implementation , SysTick timer is the source of time base.
- * It is used to generate interrupts at regular time intervals where uwTick
- * is incremented.
- * @note This function is declared as __weak to be overwritten in case of other
- * implementations in user file.
- * @param Delay specifies the delay time length, in milliseconds.
- * @retval None
- */
-__weak void HAL_Delay(uint32_t Delay)
-{
+ * @brief This function provides minimum delay (in milliseconds) based
+ * on variable incremented.
+ * @note In the default implementation , SysTick timer is the source of time base.
+ * It is used to generate interrupts at regular time intervals where uwTick
+ * is incremented.
+ * @note This function is declared as __weak to be overwritten in case of other
+ * implementations in user file.
+ * @param Delay specifies the delay time length, in milliseconds.
+ * @retval None
+ */
+__weak void HAL_Delay(uint32_t Delay) {
uint32_t tickstart = HAL_GetTick();
- uint32_t wait = Delay;
+ uint32_t wait = Delay;
/* Add a freq to guarantee minimum wait */
- if (wait < HAL_MAX_DELAY)
- {
+ if (wait < HAL_MAX_DELAY) {
wait += (uint32_t)(uwTickFreq);
}
- while ((HAL_GetTick() - tickstart) < wait)
- {
- }
+ while ((HAL_GetTick() - tickstart) < wait) {}
}
/**
- * @brief Suspend Tick increment.
- * @note In the default implementation , SysTick timer is the source of time base. It is
- * used to generate interrupts at regular time intervals. Once HAL_SuspendTick()
- * is called, the SysTick interrupt will be disabled and so Tick increment
- * is suspended.
- * @note This function is declared as __weak to be overwritten in case of other
- * implementations in user file.
- * @retval None
- */
-__weak void HAL_SuspendTick(void)
-{
+ * @brief Suspend Tick increment.
+ * @note In the default implementation , SysTick timer is the source of time base. It is
+ * used to generate interrupts at regular time intervals. Once HAL_SuspendTick()
+ * is called, the SysTick interrupt will be disabled and so Tick increment
+ * is suspended.
+ * @note This function is declared as __weak to be overwritten in case of other
+ * implementations in user file.
+ * @retval None
+ */
+__weak void HAL_SuspendTick(void) {
/* Disable SysTick Interrupt */
CLEAR_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk);
}
/**
- * @brief Resume Tick increment.
- * @note In the default implementation , SysTick timer is the source of time base. It is
- * used to generate interrupts at regular time intervals. Once HAL_ResumeTick()
- * is called, the SysTick interrupt will be enabled and so Tick increment
- * is resumed.
- * @note This function is declared as __weak to be overwritten in case of other
- * implementations in user file.
- * @retval None
- */
-__weak void HAL_ResumeTick(void)
-{
+ * @brief Resume Tick increment.
+ * @note In the default implementation , SysTick timer is the source of time base. It is
+ * used to generate interrupts at regular time intervals. Once HAL_ResumeTick()
+ * is called, the SysTick interrupt will be enabled and so Tick increment
+ * is resumed.
+ * @note This function is declared as __weak to be overwritten in case of other
+ * implementations in user file.
+ * @retval None
+ */
+__weak void HAL_ResumeTick(void) {
/* Enable SysTick Interrupt */
SET_BIT(SysTick->CTRL, SysTick_CTRL_TICKINT_Msk);
}
/**
- * @brief Returns the HAL revision
- * @retval version 0xXYZR (8bits for each decimal, R for RC)
- */
-uint32_t HAL_GetHalVersion(void)
-{
- return __STM32F1xx_HAL_VERSION;
-}
-
-/**
- * @brief Returns the device revision identifier.
- * Note: On devices STM32F10xx8 and STM32F10xxB,
- * STM32F101xC/D/E and STM32F103xC/D/E,
- * STM32F101xF/G and STM32F103xF/G
- * STM32F10xx4 and STM32F10xx6
- * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
- * debug mode (not accessible by the user software in normal mode).
- * Refer to errata sheet of these devices for more details.
- * @retval Device revision identifier
- */
-uint32_t HAL_GetREVID(void)
-{
- return ((DBGMCU->IDCODE) >> DBGMCU_IDCODE_REV_ID_Pos);
-}
-
-/**
- * @brief Returns the device identifier.
- * Note: On devices STM32F10xx8 and STM32F10xxB,
- * STM32F101xC/D/E and STM32F103xC/D/E,
- * STM32F101xF/G and STM32F103xF/G
- * STM32F10xx4 and STM32F10xx6
- * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
- * debug mode (not accessible by the user software in normal mode).
- * Refer to errata sheet of these devices for more details.
- * @retval Device identifier
- */
-uint32_t HAL_GetDEVID(void)
-{
- return ((DBGMCU->IDCODE) & IDCODE_DEVID_MASK);
-}
-
-/**
- * @brief Enable the Debug Module during SLEEP mode
- * @retval None
- */
-void HAL_DBGMCU_EnableDBGSleepMode(void)
-{
- SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP);
-}
-
-/**
- * @brief Disable the Debug Module during SLEEP mode
- * Note: On devices STM32F10xx8 and STM32F10xxB,
- * STM32F101xC/D/E and STM32F103xC/D/E,
- * STM32F101xF/G and STM32F103xF/G
- * STM32F10xx4 and STM32F10xx6
- * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
- * debug mode (not accessible by the user software in normal mode).
- * Refer to errata sheet of these devices for more details.
- * @retval None
- */
-void HAL_DBGMCU_DisableDBGSleepMode(void)
-{
- CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP);
-}
-
-/**
- * @brief Enable the Debug Module during STOP mode
- * Note: On devices STM32F10xx8 and STM32F10xxB,
- * STM32F101xC/D/E and STM32F103xC/D/E,
- * STM32F101xF/G and STM32F103xF/G
- * STM32F10xx4 and STM32F10xx6
- * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
- * debug mode (not accessible by the user software in normal mode).
- * Refer to errata sheet of these devices for more details.
- * Note: On all STM32F1 devices:
- * If the system tick timer interrupt is enabled during the Stop mode
- * debug (DBG_STOP bit set in the DBGMCU_CR register ), it will wakeup
- * the system from Stop mode.
- * Workaround: To debug the Stop mode, disable the system tick timer
- * interrupt.
- * Refer to errata sheet of these devices for more details.
- * Note: On all STM32F1 devices:
- * If the system tick timer interrupt is enabled during the Stop mode
- * debug (DBG_STOP bit set in the DBGMCU_CR register ), it will wakeup
- * the system from Stop mode.
- * Workaround: To debug the Stop mode, disable the system tick timer
- * interrupt.
- * Refer to errata sheet of these devices for more details.
- * @retval None
- */
-void HAL_DBGMCU_EnableDBGStopMode(void)
-{
- SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP);
-}
-
-/**
- * @brief Disable the Debug Module during STOP mode
- * Note: On devices STM32F10xx8 and STM32F10xxB,
- * STM32F101xC/D/E and STM32F103xC/D/E,
- * STM32F101xF/G and STM32F103xF/G
- * STM32F10xx4 and STM32F10xx6
- * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
- * debug mode (not accessible by the user software in normal mode).
- * Refer to errata sheet of these devices for more details.
- * @retval None
- */
-void HAL_DBGMCU_DisableDBGStopMode(void)
-{
- CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP);
-}
-
-/**
- * @brief Enable the Debug Module during STANDBY mode
- * Note: On devices STM32F10xx8 and STM32F10xxB,
- * STM32F101xC/D/E and STM32F103xC/D/E,
- * STM32F101xF/G and STM32F103xF/G
- * STM32F10xx4 and STM32F10xx6
- * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
- * debug mode (not accessible by the user software in normal mode).
- * Refer to errata sheet of these devices for more details.
- * @retval None
- */
-void HAL_DBGMCU_EnableDBGStandbyMode(void)
-{
- SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY);
-}
-
-/**
- * @brief Disable the Debug Module during STANDBY mode
- * Note: On devices STM32F10xx8 and STM32F10xxB,
- * STM32F101xC/D/E and STM32F103xC/D/E,
- * STM32F101xF/G and STM32F103xF/G
- * STM32F10xx4 and STM32F10xx6
- * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
- * debug mode (not accessible by the user software in normal mode).
- * Refer to errata sheet of these devices for more details.
- * @retval None
- */
-void HAL_DBGMCU_DisableDBGStandbyMode(void)
-{
- CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY);
-}
-
-/**
- * @brief Return the unique device identifier (UID based on 96 bits)
- * @param UID pointer to 3 words array.
- * @retval Device identifier
- */
-void HAL_GetUID(uint32_t *UID)
-{
+ * @brief Returns the HAL revision
+ * @retval version 0xXYZR (8bits for each decimal, R for RC)
+ */
+uint32_t HAL_GetHalVersion(void) { return __STM32F1xx_HAL_VERSION; }
+
+/**
+ * @brief Returns the device revision identifier.
+ * Note: On devices STM32F10xx8 and STM32F10xxB,
+ * STM32F101xC/D/E and STM32F103xC/D/E,
+ * STM32F101xF/G and STM32F103xF/G
+ * STM32F10xx4 and STM32F10xx6
+ * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
+ * debug mode (not accessible by the user software in normal mode).
+ * Refer to errata sheet of these devices for more details.
+ * @retval Device revision identifier
+ */
+uint32_t HAL_GetREVID(void) { return ((DBGMCU->IDCODE) >> DBGMCU_IDCODE_REV_ID_Pos); }
+
+/**
+ * @brief Returns the device identifier.
+ * Note: On devices STM32F10xx8 and STM32F10xxB,
+ * STM32F101xC/D/E and STM32F103xC/D/E,
+ * STM32F101xF/G and STM32F103xF/G
+ * STM32F10xx4 and STM32F10xx6
+ * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
+ * debug mode (not accessible by the user software in normal mode).
+ * Refer to errata sheet of these devices for more details.
+ * @retval Device identifier
+ */
+uint32_t HAL_GetDEVID(void) { return ((DBGMCU->IDCODE) & IDCODE_DEVID_MASK); }
+
+/**
+ * @brief Enable the Debug Module during SLEEP mode
+ * @retval None
+ */
+void HAL_DBGMCU_EnableDBGSleepMode(void) { SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP); }
+
+/**
+ * @brief Disable the Debug Module during SLEEP mode
+ * Note: On devices STM32F10xx8 and STM32F10xxB,
+ * STM32F101xC/D/E and STM32F103xC/D/E,
+ * STM32F101xF/G and STM32F103xF/G
+ * STM32F10xx4 and STM32F10xx6
+ * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
+ * debug mode (not accessible by the user software in normal mode).
+ * Refer to errata sheet of these devices for more details.
+ * @retval None
+ */
+void HAL_DBGMCU_DisableDBGSleepMode(void) { CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP); }
+
+/**
+ * @brief Enable the Debug Module during STOP mode
+ * Note: On devices STM32F10xx8 and STM32F10xxB,
+ * STM32F101xC/D/E and STM32F103xC/D/E,
+ * STM32F101xF/G and STM32F103xF/G
+ * STM32F10xx4 and STM32F10xx6
+ * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
+ * debug mode (not accessible by the user software in normal mode).
+ * Refer to errata sheet of these devices for more details.
+ * Note: On all STM32F1 devices:
+ * If the system tick timer interrupt is enabled during the Stop mode
+ * debug (DBG_STOP bit set in the DBGMCU_CR register ), it will wakeup
+ * the system from Stop mode.
+ * Workaround: To debug the Stop mode, disable the system tick timer
+ * interrupt.
+ * Refer to errata sheet of these devices for more details.
+ * Note: On all STM32F1 devices:
+ * If the system tick timer interrupt is enabled during the Stop mode
+ * debug (DBG_STOP bit set in the DBGMCU_CR register ), it will wakeup
+ * the system from Stop mode.
+ * Workaround: To debug the Stop mode, disable the system tick timer
+ * interrupt.
+ * Refer to errata sheet of these devices for more details.
+ * @retval None
+ */
+void HAL_DBGMCU_EnableDBGStopMode(void) { SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP); }
+
+/**
+ * @brief Disable the Debug Module during STOP mode
+ * Note: On devices STM32F10xx8 and STM32F10xxB,
+ * STM32F101xC/D/E and STM32F103xC/D/E,
+ * STM32F101xF/G and STM32F103xF/G
+ * STM32F10xx4 and STM32F10xx6
+ * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
+ * debug mode (not accessible by the user software in normal mode).
+ * Refer to errata sheet of these devices for more details.
+ * @retval None
+ */
+void HAL_DBGMCU_DisableDBGStopMode(void) { CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP); }
+
+/**
+ * @brief Enable the Debug Module during STANDBY mode
+ * Note: On devices STM32F10xx8 and STM32F10xxB,
+ * STM32F101xC/D/E and STM32F103xC/D/E,
+ * STM32F101xF/G and STM32F103xF/G
+ * STM32F10xx4 and STM32F10xx6
+ * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
+ * debug mode (not accessible by the user software in normal mode).
+ * Refer to errata sheet of these devices for more details.
+ * @retval None
+ */
+void HAL_DBGMCU_EnableDBGStandbyMode(void) { SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY); }
+
+/**
+ * @brief Disable the Debug Module during STANDBY mode
+ * Note: On devices STM32F10xx8 and STM32F10xxB,
+ * STM32F101xC/D/E and STM32F103xC/D/E,
+ * STM32F101xF/G and STM32F103xF/G
+ * STM32F10xx4 and STM32F10xx6
+ * Debug registers DBGMCU_IDCODE and DBGMCU_CR are accessible only in
+ * debug mode (not accessible by the user software in normal mode).
+ * Refer to errata sheet of these devices for more details.
+ * @retval None
+ */
+void HAL_DBGMCU_DisableDBGStandbyMode(void) { CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY); }
+
+/**
+ * @brief Return the unique device identifier (UID based on 96 bits)
+ * @param UID pointer to 3 words array.
+ * @retval Device identifier
+ */
+void HAL_GetUID(uint32_t *UID) {
UID[0] = (uint32_t)(READ_REG(*((uint32_t *)UID_BASE)));
UID[1] = (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE + 4U))));
UID[2] = (uint32_t)(READ_REG(*((uint32_t *)(UID_BASE + 8U))));
}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c
index de1ba752..4b829588 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc.c
@@ -2,7 +2,7 @@
******************************************************************************
* @file stm32f1xx_hal_adc.c
* @author MCD Application Team
- * @brief This file provides firmware functions to manage the following
+ * @brief This file provides firmware functions to manage the following
* functionalities of the Analog to Digital Convertor (ADC)
* peripheral:
* + Initialization and de-initialization functions
@@ -17,7 +17,7 @@
* + State functions
* ++ ADC state machine management
* ++ Interrupts and flags management
- * Other functions (extended functions) are available in file
+ * Other functions (extended functions) are available in file
* "stm32f1xx_hal_adc_ex.c".
*
@verbatim
@@ -29,36 +29,36 @@
(+) Interrupt generation at the end of regular conversion, end of injected
conversion, and in case of analog watchdog or overrun events.
-
+
(+) Single and continuous conversion modes.
-
+
(+) Scan mode for conversion of several channels sequentially.
-
+
(+) Data alignment with in-built data coherency.
-
+
(+) Programmable sampling time (channel wise)
-
+
(+) ADC conversion of regular group and injected group.
- (+) External trigger (timer or EXTI)
+ (+) External trigger (timer or EXTI)
for both regular and injected groups.
(+) DMA request generation for transfer of conversions data of regular group.
(+) Multimode Dual mode (available on devices with 2 ADCs or more).
-
+
(+) Configurable DMA data storage in Multimode Dual mode (available on devices
with 2 DCs or more).
-
- (+) Configurable delay between conversions in Dual interleaved mode (available
+
+ (+) Configurable delay between conversions in Dual interleaved mode (available
on devices with 2 DCs or more).
-
+
(+) ADC calibration
- (+) ADC supply requirements: 2.4 V to 3.6 V at full speed and down to 1.8 V at
+ (+) ADC supply requirements: 2.4 V to 3.6 V at full speed and down to 1.8 V at
slower speed.
-
- (+) ADC input range: from Vref- (connected to Vssa) to Vref+ (connected to
+
+ (+) ADC input range: from Vref- (connected to Vssa) to Vref+ (connected to
Vdda or to an external voltage reference).
@@ -74,7 +74,7 @@
(++) As prerequisite, ADC clock must be configured at RCC top level.
Caution: On STM32F1, ADC clock frequency max is 14MHz (refer
to device datasheet).
- Therefore, ADC clock prescaler must be configured in
+ Therefore, ADC clock prescaler must be configured in
function of ADC clock source frequency to remain below
this maximum frequency.
(++) One clock setting is mandatory:
@@ -97,8 +97,8 @@
(#) Optionally, in case of usage of ADC with interruptions:
(++) Configure the NVIC for ADC
using function HAL_NVIC_EnableIRQ(ADCx_IRQn)
- (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
- into the function of corresponding ADC interruption vector
+ (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
+ into the function of corresponding ADC interruption vector
ADCx_IRQHandler().
(#) Optionally, in case of usage of DMA:
@@ -106,8 +106,8 @@
using function HAL_DMA_Init().
(++) Configure the NVIC for DMA
using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
- (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
- into the function of corresponding DMA interruption vector
+ (++) Insert the ADC interruption handler function HAL_ADC_IRQHandler()
+ into the function of corresponding DMA interruption vector
DMAx_Channelx_IRQHandler().
*** Configuration of ADC, groups regular/injected, channels parameters ***
@@ -118,13 +118,13 @@
and regular group parameters (conversion trigger, sequencer, ...)
using function HAL_ADC_Init().
- (#) Configure the channels for regular group parameters (channel number,
+ (#) Configure the channels for regular group parameters (channel number,
channel rank into sequencer, ..., into regular group)
using function HAL_ADC_ConfigChannel().
- (#) Optionally, configure the injected group parameters (conversion trigger,
+ (#) Optionally, configure the injected group parameters (conversion trigger,
sequencer, ..., of injected group)
- and the channels for injected group parameters (channel number,
+ and the channels for injected group parameters (channel number,
channel rank into sequencer, ..., into injected group)
using function HAL_ADCEx_InjectedConfigChannel().
@@ -132,7 +132,7 @@
monitored, thresholds, ...)
using function HAL_ADC_AnalogWDGConfig().
- (#) Optionally, for devices with several ADC instances: configure the
+ (#) Optionally, for devices with several ADC instances: configure the
multimode parameters
using function HAL_ADCEx_MultiModeConfigChannel().
@@ -150,26 +150,26 @@
(++) ADC conversion by polling:
(+++) Activate the ADC peripheral and start conversions
using function HAL_ADC_Start()
- (+++) Wait for ADC conversion completion
+ (+++) Wait for ADC conversion completion
using function HAL_ADC_PollForConversion()
(or for injected group: HAL_ADCEx_InjectedPollForConversion() )
- (+++) Retrieve conversion results
+ (+++) Retrieve conversion results
using function HAL_ADC_GetValue()
(or for injected group: HAL_ADCEx_InjectedGetValue() )
- (+++) Stop conversion and disable the ADC peripheral
+ (+++) Stop conversion and disable the ADC peripheral
using function HAL_ADC_Stop()
- (++) ADC conversion by interruption:
+ (++) ADC conversion by interruption:
(+++) Activate the ADC peripheral and start conversions
using function HAL_ADC_Start_IT()
(+++) Wait for ADC conversion completion by call of function
HAL_ADC_ConvCpltCallback()
(this function must be implemented in user program)
(or for injected group: HAL_ADCEx_InjectedConvCpltCallback() )
- (+++) Retrieve conversion results
+ (+++) Retrieve conversion results
using function HAL_ADC_GetValue()
(or for injected group: HAL_ADCEx_InjectedGetValue() )
- (+++) Stop conversion and disable the ADC peripheral
+ (+++) Stop conversion and disable the ADC peripheral
using function HAL_ADC_Stop_IT()
(++) ADC conversion with transfer by DMA:
@@ -180,10 +180,10 @@
(these functions must be implemented in user program)
(+++) Conversion results are automatically transferred by DMA into
destination variable address.
- (+++) Stop conversion and disable the ADC peripheral
+ (+++) Stop conversion and disable the ADC peripheral
using function HAL_ADC_Stop_DMA()
- (++) For devices with several ADCs: ADC multimode conversion
+ (++) For devices with several ADCs: ADC multimode conversion
with transfer by DMA:
(+++) Activate the ADC peripheral (slave) and start conversions
using function HAL_ADC_Start()
@@ -240,7 +240,7 @@
using function HAL_NVIC_EnableIRQ(DMAx_Channelx_IRQn)
[..]
-
+
@endverbatim
******************************************************************************
* @attention
@@ -269,77 +269,77 @@
* 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.
*
- ******************************************************************************
+ ******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup ADC ADC
- * @brief ADC HAL module driver
- * @{
- */
+ * @brief ADC HAL module driver
+ * @{
+ */
#ifdef HAL_ADC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup ADC_Private_Constants ADC Private Constants
- * @{
- */
-
- /* Timeout values for ADC enable and disable settling time. */
- /* Values defined to be higher than worst cases: low clocks freq, */
- /* maximum prescaler. */
- /* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock */
- /* prescaler 4, sampling time 12.5 ADC clock cycles, resolution 12 bits. */
- /* Unit: ms */
- #define ADC_ENABLE_TIMEOUT 2U
- #define ADC_DISABLE_TIMEOUT 2U
-
- /* Delay for ADC stabilization time. */
- /* Maximum delay is 1us (refer to device datasheet, parameter tSTAB). */
- /* Unit: us */
- #define ADC_STAB_DELAY_US 1U
-
- /* Delay for temperature sensor stabilization time. */
- /* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */
- /* Unit: us */
- #define ADC_TEMPSENSOR_DELAY_US 10U
+ * @{
+ */
+
+/* Timeout values for ADC enable and disable settling time. */
+/* Values defined to be higher than worst cases: low clocks freq, */
+/* maximum prescaler. */
+/* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock */
+/* prescaler 4, sampling time 12.5 ADC clock cycles, resolution 12 bits. */
+/* Unit: ms */
+#define ADC_ENABLE_TIMEOUT 2U
+#define ADC_DISABLE_TIMEOUT 2U
+
+/* Delay for ADC stabilization time. */
+/* Maximum delay is 1us (refer to device datasheet, parameter tSTAB). */
+/* Unit: us */
+#define ADC_STAB_DELAY_US 1U
+
+/* Delay for temperature sensor stabilization time. */
+/* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */
+/* Unit: us */
+#define ADC_TEMPSENSOR_DELAY_US 10U
/**
- * @}
- */
+ * @}
+ */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup ADC_Private_Functions ADC Private Functions
- * @{
- */
+ * @{
+ */
/**
- * @}
- */
+ * @}
+ */
/* Exported functions --------------------------------------------------------*/
/** @defgroup ADC_Exported_Functions ADC Exported Functions
- * @{
- */
+ * @{
+ */
-/** @defgroup ADC_Exported_Functions_Group1 Initialization/de-initialization functions
+/** @defgroup ADC_Exported_Functions_Group1 Initialization/de-initialization functions
* @brief Initialization and Configuration functions
*
-@verbatim
+@verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
[..] This section provides functions allowing to:
- (+) Initialize and configure the ADC.
+ (+) Initialize and configure the ADC.
(+) De-initialize the ADC.
@endverbatim
@@ -347,58 +347,54 @@
*/
/**
- * @brief Initializes the ADC peripheral and regular group according to
- * parameters specified in structure "ADC_InitTypeDef".
- * @note As prerequisite, ADC clock must be configured at RCC top level
- * (clock source APB2).
- * See commented example code below that can be copied and uncommented
- * into HAL_ADC_MspInit().
- * @note Possibility to update parameters on the fly:
- * This function initializes the ADC MSP (HAL_ADC_MspInit()) only when
- * coming from ADC state reset. Following calls to this function can
- * be used to reconfigure some parameters of ADC_InitTypeDef
- * structure on the fly, without modifying MSP configuration. If ADC
- * MSP has to be modified again, HAL_ADC_DeInit() must be called
- * before HAL_ADC_Init().
- * The setting of these parameters is conditioned to ADC state.
- * For parameters constraints, see comments of structure
- * "ADC_InitTypeDef".
- * @note This function configures the ADC within 2 scopes: scope of entire
- * ADC and scope of regular group. For parameters details, see comments
- * of structure "ADC_InitTypeDef".
- * @param hadc: ADC handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc)
-{
+ * @brief Initializes the ADC peripheral and regular group according to
+ * parameters specified in structure "ADC_InitTypeDef".
+ * @note As prerequisite, ADC clock must be configured at RCC top level
+ * (clock source APB2).
+ * See commented example code below that can be copied and uncommented
+ * into HAL_ADC_MspInit().
+ * @note Possibility to update parameters on the fly:
+ * This function initializes the ADC MSP (HAL_ADC_MspInit()) only when
+ * coming from ADC state reset. Following calls to this function can
+ * be used to reconfigure some parameters of ADC_InitTypeDef
+ * structure on the fly, without modifying MSP configuration. If ADC
+ * MSP has to be modified again, HAL_ADC_DeInit() must be called
+ * before HAL_ADC_Init().
+ * The setting of these parameters is conditioned to ADC state.
+ * For parameters constraints, see comments of structure
+ * "ADC_InitTypeDef".
+ * @note This function configures the ADC within 2 scopes: scope of entire
+ * ADC and scope of regular group. For parameters details, see comments
+ * of structure "ADC_InitTypeDef".
+ * @param hadc: ADC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
- uint32_t tmp_cr1 = 0U;
- uint32_t tmp_cr2 = 0U;
- uint32_t tmp_sqr1 = 0U;
-
+ uint32_t tmp_cr1 = 0U;
+ uint32_t tmp_cr2 = 0U;
+ uint32_t tmp_sqr1 = 0U;
+
/* Check ADC handle */
- if(hadc == NULL)
- {
+ if (hadc == NULL) {
return HAL_ERROR;
}
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign));
assert_param(IS_ADC_SCAN_MODE(hadc->Init.ScanConvMode));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
assert_param(IS_ADC_EXTTRIG(hadc->Init.ExternalTrigConv));
-
- if(hadc->Init.ScanConvMode != ADC_SCAN_DISABLE)
- {
+
+ if (hadc->Init.ScanConvMode != ADC_SCAN_DISABLE) {
assert_param(IS_ADC_REGULAR_NB_CONV(hadc->Init.NbrOfConversion));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode));
- if(hadc->Init.DiscontinuousConvMode != DISABLE)
- {
+ if (hadc->Init.DiscontinuousConvMode != DISABLE) {
assert_param(IS_ADC_REGULAR_DISCONT_NUMBER(hadc->Init.NbrOfDiscConversion));
}
}
-
+
/* As prerequisite, into HAL_ADC_MspInit(), ADC clock must be configured */
/* at RCC top level. */
/* Refer to header of this file for more details on clock enabling */
@@ -406,38 +402,32 @@ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc)
/* Actions performed only if ADC is coming from state reset: */
/* - Initialization of ADC MSP */
- if (hadc->State == HAL_ADC_STATE_RESET)
- {
+ if (hadc->State == HAL_ADC_STATE_RESET) {
/* Initialize ADC error code */
ADC_CLEAR_ERRORCODE(hadc);
-
+
/* Allocate lock resource and initialize it */
hadc->Lock = HAL_UNLOCKED;
-
+
/* Init the low level hardware */
HAL_ADC_MspInit(hadc);
}
-
+
/* Stop potential conversion on going, on regular and injected groups */
/* Disable ADC peripheral */
/* Note: In case of ADC already enabled, precaution to not launch an */
/* unwanted conversion while modifying register CR2 by writing 1 to */
/* bit ADON. */
tmp_hal_status = ADC_ConversionStop_Disable(hadc);
-
-
- /* Configuration of ADC parameters if previous preliminary actions are */
+
+ /* Configuration of ADC parameters if previous preliminary actions are */
/* correctly completed. */
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL) &&
- (tmp_hal_status == HAL_OK) )
- {
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL) && (tmp_hal_status == HAL_OK)) {
/* Set ADC state */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
- HAL_ADC_STATE_BUSY_INTERNAL);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_BUSY_INTERNAL);
+
/* Set ADC parameters */
-
+
/* Configuration of ADC: */
/* - data alignment */
/* - external trigger to start conversion */
@@ -448,55 +438,39 @@ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc)
/* HAL_ADC_Start_xxx functions because if set in this function, */
/* a conversion on injected group would start a conversion also on */
/* regular group after ADC enabling. */
- tmp_cr2 |= (hadc->Init.DataAlign |
- ADC_CFGR_EXTSEL(hadc, hadc->Init.ExternalTrigConv) |
- ADC_CR2_CONTINUOUS(hadc->Init.ContinuousConvMode) );
-
+ tmp_cr2 |= (hadc->Init.DataAlign | ADC_CFGR_EXTSEL(hadc, hadc->Init.ExternalTrigConv) | ADC_CR2_CONTINUOUS(hadc->Init.ContinuousConvMode));
+
/* Configuration of ADC: */
/* - scan mode */
/* - discontinuous mode disable/enable */
/* - discontinuous mode number of conversions */
tmp_cr1 |= (ADC_CR1_SCAN_SET(hadc->Init.ScanConvMode));
-
+
/* Enable discontinuous mode only if continuous mode is disabled */
/* Note: If parameter "Init.ScanConvMode" is set to disable, parameter */
/* discontinuous is set anyway, but will have no effect on ADC HW. */
- if (hadc->Init.DiscontinuousConvMode == ENABLE)
- {
- if (hadc->Init.ContinuousConvMode == DISABLE)
- {
+ if (hadc->Init.DiscontinuousConvMode == ENABLE) {
+ if (hadc->Init.ContinuousConvMode == DISABLE) {
/* Enable the selected ADC regular discontinuous mode */
/* Set the number of channels to be converted in discontinuous mode */
- SET_BIT(tmp_cr1, ADC_CR1_DISCEN |
- ADC_CR1_DISCONTINUOUS_NUM(hadc->Init.NbrOfDiscConversion) );
- }
- else
- {
+ SET_BIT(tmp_cr1, ADC_CR1_DISCEN | ADC_CR1_DISCONTINUOUS_NUM(hadc->Init.NbrOfDiscConversion));
+ } else {
/* ADC regular group settings continuous and sequencer discontinuous*/
/* cannot be enabled simultaneously. */
-
+
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
+
/* Set ADC error code to ADC IP internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
}
}
-
+
/* Update ADC configuration register CR1 with previous settings */
- MODIFY_REG(hadc->Instance->CR1,
- ADC_CR1_SCAN |
- ADC_CR1_DISCEN |
- ADC_CR1_DISCNUM ,
- tmp_cr1 );
-
+ MODIFY_REG(hadc->Instance->CR1, ADC_CR1_SCAN | ADC_CR1_DISCEN | ADC_CR1_DISCNUM, tmp_cr1);
+
/* Update ADC configuration register CR2 with previous settings */
- MODIFY_REG(hadc->Instance->CR2,
- ADC_CR2_ALIGN |
- ADC_CR2_EXTSEL |
- ADC_CR2_EXTTRIG |
- ADC_CR2_CONT ,
- tmp_cr2 );
+ MODIFY_REG(hadc->Instance->CR2, ADC_CR2_ALIGN | ADC_CR2_EXTSEL | ADC_CR2_EXTTRIG | ADC_CR2_CONT, tmp_cr2);
/* Configuration of regular group sequencer: */
/* - if scan mode is disabled, regular channels sequence length is set to */
@@ -507,126 +481,93 @@ HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc)
/* conversions is forced to 0x00 for alignment over all STM32 devices. */
/* - if scan mode is enabled, regular channels sequence length is set to */
/* parameter "NbrOfConversion" */
- if (ADC_CR1_SCAN_SET(hadc->Init.ScanConvMode) == ADC_SCAN_ENABLE)
- {
+ if (ADC_CR1_SCAN_SET(hadc->Init.ScanConvMode) == ADC_SCAN_ENABLE) {
tmp_sqr1 = ADC_SQR1_L_SHIFT(hadc->Init.NbrOfConversion);
}
-
- MODIFY_REG(hadc->Instance->SQR1,
- ADC_SQR1_L ,
- tmp_sqr1 );
-
+
+ MODIFY_REG(hadc->Instance->SQR1, ADC_SQR1_L, tmp_sqr1);
+
/* Check back that ADC registers have effectively been configured to */
/* ensure of no potential problem of ADC core IP clocking. */
/* Check through register CR2 (excluding bits set in other functions: */
/* execution control bits (ADON, JSWSTART, SWSTART), regular group bits */
/* (DMA), injected group bits (JEXTTRIG and JEXTSEL), channel internal */
/* measurement path bit (TSVREFE). */
- if (READ_BIT(hadc->Instance->CR2, ~(ADC_CR2_ADON | ADC_CR2_DMA |
- ADC_CR2_SWSTART | ADC_CR2_JSWSTART |
- ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL |
- ADC_CR2_TSVREFE ))
- == tmp_cr2)
- {
+ if (READ_BIT(hadc->Instance->CR2, ~(ADC_CR2_ADON | ADC_CR2_DMA | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_TSVREFE)) == tmp_cr2) {
/* Set ADC error code to none */
ADC_CLEAR_ERRORCODE(hadc);
-
+
/* Set the ADC state */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_BUSY_INTERNAL,
- HAL_ADC_STATE_READY);
- }
- else
- {
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_READY);
+ } else {
/* Update ADC state machine to error */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_BUSY_INTERNAL,
- HAL_ADC_STATE_ERROR_INTERNAL);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_ERROR_INTERNAL);
+
/* Set ADC error code to ADC IP internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
-
+
tmp_hal_status = HAL_ERROR;
}
-
- }
- else
- {
+
+ } else {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
-
+
tmp_hal_status = HAL_ERROR;
}
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Deinitialize the ADC peripheral registers to their default reset
- * values, with deinitialization of the ADC MSP.
- * If needed, the example code can be copied and uncommented into
- * function HAL_ADC_MspDeInit().
- * @param hadc: ADC handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc)
-{
+ * @brief Deinitialize the ADC peripheral registers to their default reset
+ * values, with deinitialization of the ADC MSP.
+ * If needed, the example code can be copied and uncommented into
+ * function HAL_ADC_MspDeInit().
+ * @param hadc: ADC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check ADC handle */
- if(hadc == NULL)
- {
- return HAL_ERROR;
+ if (hadc == NULL) {
+ return HAL_ERROR;
}
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
-
+
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL);
-
+
/* Stop potential conversion on going, on regular and injected groups */
/* Disable ADC peripheral */
tmp_hal_status = ADC_ConversionStop_Disable(hadc);
-
-
- /* Configuration of ADC parameters if previous preliminary actions are */
+
+ /* Configuration of ADC parameters if previous preliminary actions are */
/* correctly completed. */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* ========== Reset ADC registers ========== */
-
-
-
/* Reset register SR */
- __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_JEOC | ADC_FLAG_EOC |
- ADC_FLAG_JSTRT | ADC_FLAG_STRT));
-
+ __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_JEOC | ADC_FLAG_EOC | ADC_FLAG_JSTRT | ADC_FLAG_STRT));
+
/* Reset register CR1 */
- CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM |
- ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO |
- ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE |
- ADC_CR1_AWDIE | ADC_CR1_EOCIE | ADC_CR1_AWDCH ));
-
+ CLEAR_BIT(hadc->Instance->CR1, (ADC_CR1_AWDEN | ADC_CR1_JAWDEN | ADC_CR1_DISCNUM | ADC_CR1_JDISCEN | ADC_CR1_DISCEN | ADC_CR1_JAUTO | ADC_CR1_AWDSGL | ADC_CR1_SCAN | ADC_CR1_JEOCIE | ADC_CR1_AWDIE
+ | ADC_CR1_EOCIE | ADC_CR1_AWDCH));
+
/* Reset register CR2 */
- CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART |
- ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG |
- ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA |
- ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT |
- ADC_CR2_ADON ));
-
+ CLEAR_BIT(hadc->Instance->CR2, (ADC_CR2_TSVREFE | ADC_CR2_SWSTART | ADC_CR2_JSWSTART | ADC_CR2_EXTTRIG | ADC_CR2_EXTSEL | ADC_CR2_JEXTTRIG | ADC_CR2_JEXTSEL | ADC_CR2_ALIGN | ADC_CR2_DMA
+ | ADC_CR2_RSTCAL | ADC_CR2_CAL | ADC_CR2_CONT | ADC_CR2_ADON));
+
/* Reset register SMPR1 */
- CLEAR_BIT(hadc->Instance->SMPR1, (ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16 | ADC_SMPR1_SMP15 |
- ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13 | ADC_SMPR1_SMP12 |
- ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10 ));
-
+ CLEAR_BIT(hadc->Instance->SMPR1, (ADC_SMPR1_SMP17 | ADC_SMPR1_SMP16 | ADC_SMPR1_SMP15 | ADC_SMPR1_SMP14 | ADC_SMPR1_SMP13 | ADC_SMPR1_SMP12 | ADC_SMPR1_SMP11 | ADC_SMPR1_SMP10));
+
/* Reset register SMPR2 */
- CLEAR_BIT(hadc->Instance->SMPR2, (ADC_SMPR2_SMP9 | ADC_SMPR2_SMP8 | ADC_SMPR2_SMP7 |
- ADC_SMPR2_SMP6 | ADC_SMPR2_SMP5 | ADC_SMPR2_SMP4 |
- ADC_SMPR2_SMP3 | ADC_SMPR2_SMP2 | ADC_SMPR2_SMP1 |
- ADC_SMPR2_SMP0 ));
+ CLEAR_BIT(hadc->Instance->SMPR2,
+ (ADC_SMPR2_SMP9 | ADC_SMPR2_SMP8 | ADC_SMPR2_SMP7 | ADC_SMPR2_SMP6 | ADC_SMPR2_SMP5 | ADC_SMPR2_SMP4 | ADC_SMPR2_SMP3 | ADC_SMPR2_SMP2 | ADC_SMPR2_SMP1 | ADC_SMPR2_SMP0));
/* Reset register JOFR1 */
CLEAR_BIT(hadc->Instance->JOFR1, ADC_JOFR1_JOFFSET1);
@@ -636,46 +577,36 @@ HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc)
CLEAR_BIT(hadc->Instance->JOFR3, ADC_JOFR3_JOFFSET3);
/* Reset register JOFR4 */
CLEAR_BIT(hadc->Instance->JOFR4, ADC_JOFR4_JOFFSET4);
-
+
/* Reset register HTR */
CLEAR_BIT(hadc->Instance->HTR, ADC_HTR_HT);
/* Reset register LTR */
CLEAR_BIT(hadc->Instance->LTR, ADC_LTR_LT);
-
+
/* Reset register SQR1 */
- CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_L |
- ADC_SQR1_SQ16 | ADC_SQR1_SQ15 |
- ADC_SQR1_SQ14 | ADC_SQR1_SQ13 );
-
+ CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_L | ADC_SQR1_SQ16 | ADC_SQR1_SQ15 | ADC_SQR1_SQ14 | ADC_SQR1_SQ13);
+
/* Reset register SQR1 */
- CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_L |
- ADC_SQR1_SQ16 | ADC_SQR1_SQ15 |
- ADC_SQR1_SQ14 | ADC_SQR1_SQ13 );
-
+ CLEAR_BIT(hadc->Instance->SQR1, ADC_SQR1_L | ADC_SQR1_SQ16 | ADC_SQR1_SQ15 | ADC_SQR1_SQ14 | ADC_SQR1_SQ13);
+
/* Reset register SQR2 */
- CLEAR_BIT(hadc->Instance->SQR2, ADC_SQR2_SQ12 | ADC_SQR2_SQ11 | ADC_SQR2_SQ10 |
- ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7 );
-
+ CLEAR_BIT(hadc->Instance->SQR2, ADC_SQR2_SQ12 | ADC_SQR2_SQ11 | ADC_SQR2_SQ10 | ADC_SQR2_SQ9 | ADC_SQR2_SQ8 | ADC_SQR2_SQ7);
+
/* Reset register SQR3 */
- CLEAR_BIT(hadc->Instance->SQR3, ADC_SQR3_SQ6 | ADC_SQR3_SQ5 | ADC_SQR3_SQ4 |
- ADC_SQR3_SQ3 | ADC_SQR3_SQ2 | ADC_SQR3_SQ1 );
-
+ CLEAR_BIT(hadc->Instance->SQR3, ADC_SQR3_SQ6 | ADC_SQR3_SQ5 | ADC_SQR3_SQ4 | ADC_SQR3_SQ3 | ADC_SQR3_SQ2 | ADC_SQR3_SQ1);
+
/* Reset register JSQR */
- CLEAR_BIT(hadc->Instance->JSQR, ADC_JSQR_JL |
- ADC_JSQR_JSQ4 | ADC_JSQR_JSQ3 |
- ADC_JSQR_JSQ2 | ADC_JSQR_JSQ1 );
-
+ CLEAR_BIT(hadc->Instance->JSQR, ADC_JSQR_JL | ADC_JSQR_JSQ4 | ADC_JSQR_JSQ3 | ADC_JSQR_JSQ2 | ADC_JSQR_JSQ1);
+
/* Reset register JSQR */
- CLEAR_BIT(hadc->Instance->JSQR, ADC_JSQR_JL |
- ADC_JSQR_JSQ4 | ADC_JSQR_JSQ3 |
- ADC_JSQR_JSQ2 | ADC_JSQR_JSQ1 );
-
+ CLEAR_BIT(hadc->Instance->JSQR, ADC_JSQR_JL | ADC_JSQR_JSQ4 | ADC_JSQR_JSQ3 | ADC_JSQR_JSQ2 | ADC_JSQR_JSQ1);
+
/* Reset register DR */
/* bits in access mode read only, no direct reset applicable*/
-
+
/* Reset registers JDR1, JDR2, JDR3, JDR4 */
/* bits in access mode read only, no direct reset applicable*/
-
+
/* ========== Hard reset ADC peripheral ========== */
/* Performs a global reset of the entire ADC peripheral: ADC state is */
/* forced to a similar state after device power-on. */
@@ -684,61 +615,58 @@ HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc)
/* */
/* __HAL_RCC_ADC1_FORCE_RESET() */
/* __HAL_RCC_ADC1_RELEASE_RESET() */
-
+
/* DeInit the low level hardware */
HAL_ADC_MspDeInit(hadc);
-
+
/* Set ADC error code to none */
ADC_CLEAR_ERRORCODE(hadc);
-
+
/* Set ADC state */
- hadc->State = HAL_ADC_STATE_RESET;
-
+ hadc->State = HAL_ADC_STATE_RESET;
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Initializes the ADC MSP.
- * @param hadc: ADC handle
- * @retval None
- */
-__weak void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)
-{
+ * @brief Initializes the ADC MSP.
+ * @param hadc: ADC handle
+ * @retval None
+ */
+__weak void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADC_MspInit must be implemented in the user file.
- */
+ */
}
/**
- * @brief DeInitializes the ADC MSP.
- * @param hadc: ADC handle
- * @retval None
- */
-__weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
-{
+ * @brief DeInitializes the ADC MSP.
+ * @param hadc: ADC handle
+ * @retval None
+ */
+__weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef *hadc) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
function HAL_ADC_MspDeInit must be implemented in the user file.
- */
+ */
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup ADC_Exported_Functions_Group2 IO operation functions
* @brief Input and Output operation functions
*
-@verbatim
+@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
@@ -758,197 +686,173 @@ __weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
*/
/**
- * @brief Enables ADC, starts conversion of regular group.
- * Interruptions enabled in this function: None.
- * @param hadc: ADC handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc)
-{
+ * @brief Enables ADC, starts conversion of regular group.
+ * Interruptions enabled in this function: None.
+ * @param hadc: ADC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
-
+
/* Start conversion if ADC is effectively enabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state */
/* - Clear state bitfield related to regular group conversion results */
/* - Set state bitfield related to regular operation */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC,
- HAL_ADC_STATE_REG_BUSY);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC, HAL_ADC_STATE_REG_BUSY);
+
/* Set group injected state (from auto-injection) and multimode state */
/* for all cases of multimode: independent mode, multimode ADC master */
/* or multimode ADC slave (for devices with several ADCs): */
- if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc))
- {
+ if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc)) {
/* Set ADC state (ADC independent or master) */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
-
+
/* If conversions on group regular are also triggering group injected, */
/* update ADC state. */
- if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET)
- {
- ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
+ if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET) {
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
}
- }
- else
- {
+ } else {
/* Set ADC state (ADC slave) */
SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
-
+
/* If conversions on group regular are also triggering group injected, */
/* update ADC state. */
- if (ADC_MULTIMODE_AUTO_INJECTED(hadc))
- {
+ if (ADC_MULTIMODE_AUTO_INJECTED(hadc)) {
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
}
}
-
+
/* State machine update: Check if an injected conversion is ongoing */
- if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY))
- {
+ if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY)) {
/* Reset ADC error code fields related to conversions on group regular */
- CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
- }
- else
- {
+ CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
+ } else {
/* Reset ADC all error code fields */
ADC_CLEAR_ERRORCODE(hadc);
}
-
+
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
-
+
/* Clear regular group conversion flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC);
-
+
/* Enable conversion of regular group. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
- /* Case of multimode enabled: */
+ /* Case of multimode enabled: */
/* - if ADC is slave, ADC is enabled only (conversion is not started). */
/* - if ADC is master, ADC is enabled and conversion is started. */
/* If ADC is master, ADC is enabled and conversion is started. */
/* Note: Alternate trigger for single conversion could be to force an */
/* additional set of bit ADON "hadc->Instance->CR2 |= ADC_CR2_ADON;"*/
- if (ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
- ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc) )
- {
+ if (ADC_IS_SOFTWARE_START_REGULAR(hadc) && ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc)) {
/* Start ADC conversion on regular group with SW start */
SET_BIT(hadc->Instance->CR2, (ADC_CR2_SWSTART | ADC_CR2_EXTTRIG));
- }
- else
- {
+ } else {
/* Start ADC conversion on regular group with external trigger */
SET_BIT(hadc->Instance->CR2, ADC_CR2_EXTTRIG);
}
- }
- else
- {
+ } else {
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Stop ADC conversion of regular group (and injected channels in
- * case of auto_injection mode), disable ADC peripheral.
- * @note: ADC peripheral disable is forcing stop of potential
- * conversion on injected group. If injected group is under use, it
- * should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
- * @param hadc: ADC handle
- * @retval HAL status.
- */
-HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc)
-{
+ * @brief Stop ADC conversion of regular group (and injected channels in
+ * case of auto_injection mode), disable ADC peripheral.
+ * @note: ADC peripheral disable is forcing stop of potential
+ * conversion on injected group. If injected group is under use, it
+ * should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
+ * @param hadc: ADC handle
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Stop potential conversion on going, on regular and injected groups */
/* Disable ADC peripheral */
tmp_hal_status = ADC_ConversionStop_Disable(hadc);
-
+
/* Check if ADC is effectively disabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
- HAL_ADC_STATE_READY);
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY);
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Wait for regular group conversion to be completed.
- * @note This function cannot be used in a particular setup: ADC configured
- * in DMA mode.
- * In this case, DMA resets the flag EOC and polling cannot be
- * performed on each conversion.
- * @note On STM32F1 devices, limitation in case of sequencer enabled
- * (several ranks selected): polling cannot be done on each
- * conversion inside the sequence. In this case, polling is replaced by
- * wait for maximum conversion time.
- * @param hadc: ADC handle
- * @param Timeout: Timeout value in millisecond.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout)
-{
+ * @brief Wait for regular group conversion to be completed.
+ * @note This function cannot be used in a particular setup: ADC configured
+ * in DMA mode.
+ * In this case, DMA resets the flag EOC and polling cannot be
+ * performed on each conversion.
+ * @note On STM32F1 devices, limitation in case of sequencer enabled
+ * (several ranks selected): polling cannot be done on each
+ * conversion inside the sequence. In this case, polling is replaced by
+ * wait for maximum conversion time.
+ * @param hadc: ADC handle
+ * @param Timeout: Timeout value in millisecond.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout) {
uint32_t tickstart = 0U;
-
+
/* Variables for polling in case of scan mode enabled and polling for each */
/* conversion. */
- __IO uint32_t Conversion_Timeout_CPU_cycles = 0U;
- uint32_t Conversion_Timeout_CPU_cycles_max = 0U;
-
+ __IO uint32_t Conversion_Timeout_CPU_cycles = 0U;
+ uint32_t Conversion_Timeout_CPU_cycles_max = 0U;
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
-
+
/* Get tick count */
tickstart = HAL_GetTick();
-
+
/* Verification that ADC configuration is compliant with polling for */
/* each conversion: */
/* Particular case is ADC configured in DMA mode */
- if (HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_DMA))
- {
+ if (HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_DMA)) {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_ERROR;
}
-
+
/* Polling for end of conversion: differentiation if single/sequence */
/* conversion. */
/* - If single conversion for regular group (Scan mode disabled or enabled */
@@ -963,590 +867,509 @@ HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Ti
/* settings, conversion time range can be from 28 to 32256 CPU cycles). */
/* As flag EOC is not set after each conversion, no timeout status can */
/* be set. */
- if (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_SCAN) &&
- HAL_IS_BIT_CLR(hadc->Instance->SQR1, ADC_SQR1_L) )
- {
+ if (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_SCAN) && HAL_IS_BIT_CLR(hadc->Instance->SQR1, ADC_SQR1_L)) {
/* Wait until End of Conversion flag is raised */
- while(HAL_IS_BIT_CLR(hadc->Instance->SR, ADC_FLAG_EOC))
- {
+ while (HAL_IS_BIT_CLR(hadc->Instance->SR, ADC_FLAG_EOC)) {
/* Check if timeout is disabled (set to infinite wait) */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U) || ((HAL_GetTick() - tickstart ) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) {
/* Update ADC state machine to timeout */
SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_TIMEOUT;
}
}
}
- }
- else
- {
+ } else {
/* Replace polling by wait for maximum conversion time */
/* - Computation of CPU clock cycles corresponding to ADC clock cycles */
/* and ADC maximum conversion cycles on all channels. */
/* - Wait for the expected ADC clock cycles delay */
- Conversion_Timeout_CPU_cycles_max = ((SystemCoreClock
- / HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_ADC))
- * ADC_CONVCYCLES_MAX_RANGE(hadc) );
-
- while(Conversion_Timeout_CPU_cycles < Conversion_Timeout_CPU_cycles_max)
- {
+ Conversion_Timeout_CPU_cycles_max = ((SystemCoreClock / HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_ADC)) * ADC_CONVCYCLES_MAX_RANGE(hadc));
+
+ while (Conversion_Timeout_CPU_cycles < Conversion_Timeout_CPU_cycles_max) {
/* Check if timeout is disabled (set to infinite wait) */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) {
/* Update ADC state machine to timeout */
SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_TIMEOUT;
}
}
- Conversion_Timeout_CPU_cycles ++;
+ Conversion_Timeout_CPU_cycles++;
}
}
-
+
/* Clear regular group conversion flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC);
-
+
/* Update ADC state machine */
SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
-
+
/* Determine whether any further conversion upcoming on group regular */
/* by external trigger, continuous mode or scan sequence on going. */
/* Note: On STM32F1 devices, in case of sequencer enabled */
/* (several ranks selected), end of conversion flag is raised */
/* at the end of the sequence. */
- if(ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
- (hadc->Init.ContinuousConvMode == DISABLE) )
- {
+ if (ADC_IS_SOFTWARE_START_REGULAR(hadc) && (hadc->Init.ContinuousConvMode == DISABLE)) {
/* Set ADC state */
- CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
+ CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY))
- {
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY)) {
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
-
+
/* Return ADC state */
return HAL_OK;
}
/**
- * @brief Poll for conversion event.
- * @param hadc: ADC handle
- * @param EventType: the ADC event type.
- * This parameter can be one of the following values:
- * @arg ADC_AWD_EVENT: ADC Analog watchdog event.
- * @param Timeout: Timeout value in millisecond.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout)
-{
- uint32_t tickstart = 0U;
+ * @brief Poll for conversion event.
+ * @param hadc: ADC handle
+ * @param EventType: the ADC event type.
+ * This parameter can be one of the following values:
+ * @arg ADC_AWD_EVENT: ADC Analog watchdog event.
+ * @param Timeout: Timeout value in millisecond.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef *hadc, uint32_t EventType, uint32_t Timeout) {
+ uint32_t tickstart = 0U;
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_EVENT_TYPE(EventType));
-
+
/* Get tick count */
tickstart = HAL_GetTick();
-
+
/* Check selected event flag */
- while(__HAL_ADC_GET_FLAG(hadc, EventType) == RESET)
- {
+ while (__HAL_ADC_GET_FLAG(hadc, EventType) == RESET) {
/* Check if timeout is disabled (set to infinite wait) */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U) || ((HAL_GetTick() - tickstart ) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) {
/* Update ADC state machine to timeout */
SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_TIMEOUT;
}
}
}
-
+
/* Analog watchdog (level out of window) event */
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
-
+
/* Clear ADC analog watchdog flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD);
-
+
/* Return ADC state */
return HAL_OK;
}
/**
- * @brief Enables ADC, starts conversion of regular group with interruption.
- * Interruptions enabled in this function:
- * - EOC (end of conversion of regular group)
- * Each of these interruptions has its dedicated callback function.
- * @param hadc: ADC handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc)
-{
+ * @brief Enables ADC, starts conversion of regular group with interruption.
+ * Interruptions enabled in this function:
+ * - EOC (end of conversion of regular group)
+ * Each of these interruptions has its dedicated callback function.
+ * @param hadc: ADC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
-
+
/* Start conversion if ADC is effectively enabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state */
/* - Clear state bitfield related to regular group conversion results */
/* - Set state bitfield related to regular operation */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
- HAL_ADC_STATE_REG_BUSY);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP, HAL_ADC_STATE_REG_BUSY);
+
/* Set group injected state (from auto-injection) and multimode state */
/* for all cases of multimode: independent mode, multimode ADC master */
/* or multimode ADC slave (for devices with several ADCs): */
- if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc))
- {
+ if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc)) {
/* Set ADC state (ADC independent or master) */
CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
-
+
/* If conversions on group regular are also triggering group injected, */
/* update ADC state. */
- if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET)
- {
- ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
+ if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET) {
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
}
- }
- else
- {
+ } else {
/* Set ADC state (ADC slave) */
SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
-
+
/* If conversions on group regular are also triggering group injected, */
/* update ADC state. */
- if (ADC_MULTIMODE_AUTO_INJECTED(hadc))
- {
+ if (ADC_MULTIMODE_AUTO_INJECTED(hadc)) {
ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
}
}
-
+
/* State machine update: Check if an injected conversion is ongoing */
- if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY))
- {
+ if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY)) {
/* Reset ADC error code fields related to conversions on group regular */
- CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
- }
- else
- {
+ CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
+ } else {
/* Reset ADC all error code fields */
ADC_CLEAR_ERRORCODE(hadc);
}
-
+
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
-
+
/* Clear regular group conversion flag and overrun flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC);
-
+
/* Enable end of conversion interrupt for regular group */
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOC);
-
+
/* Enable conversion of regular group. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
- /* Case of multimode enabled: */
+ /* Case of multimode enabled: */
/* - if ADC is slave, ADC is enabled only (conversion is not started). */
/* - if ADC is master, ADC is enabled and conversion is started. */
- if (ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
- ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc) )
- {
+ if (ADC_IS_SOFTWARE_START_REGULAR(hadc) && ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc)) {
/* Start ADC conversion on regular group with SW start */
SET_BIT(hadc->Instance->CR2, (ADC_CR2_SWSTART | ADC_CR2_EXTTRIG));
- }
- else
- {
+ } else {
/* Start ADC conversion on regular group with external trigger */
SET_BIT(hadc->Instance->CR2, ADC_CR2_EXTTRIG);
}
- }
- else
- {
+ } else {
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Stop ADC conversion of regular group (and injected group in
- * case of auto_injection mode), disable interrution of
- * end-of-conversion, disable ADC peripheral.
- * @param hadc: ADC handle
- * @retval None
- */
-HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc)
-{
+ * @brief Stop ADC conversion of regular group (and injected group in
+ * case of auto_injection mode), disable interrution of
+ * end-of-conversion, disable ADC peripheral.
+ * @param hadc: ADC handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Stop potential conversion on going, on regular and injected groups */
/* Disable ADC peripheral */
tmp_hal_status = ADC_ConversionStop_Disable(hadc);
-
+
/* Check if ADC is effectively disabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Disable ADC end of conversion interrupt for regular group */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
-
+
/* Set ADC state */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
- HAL_ADC_STATE_READY);
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY);
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Enables ADC, starts conversion of regular group and transfers result
- * through DMA.
- * Interruptions enabled in this function:
- * - DMA transfer complete
- * - DMA half transfer
- * Each of these interruptions has its dedicated callback function.
- * @note For devices with several ADCs: This function is for single-ADC mode
- * only. For multimode, use the dedicated MultimodeStart function.
- * @note On STM32F1 devices, only ADC1 and ADC3 (ADC availability depending
- * on devices) have DMA capability.
- * ADC2 converted data can be transferred in dual ADC mode using DMA
- * of ADC1 (ADC master in multimode).
- * In case of using ADC1 with DMA on a device featuring 2 ADC
- * instances: ADC1 conversion register DR contains ADC1 conversion
- * result (ADC1 register DR bits 0 to 11) and, additionally, ADC2 last
- * conversion result (ADC1 register DR bits 16 to 27). Therefore, to
- * have DMA transferring the conversion results of ADC1 only, DMA must
- * be configured to transfer size: half word.
- * @param hadc: ADC handle
- * @param pData: The destination Buffer address.
- * @param Length: The length of data to be transferred from ADC peripheral to memory.
- * @retval None
- */
-HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length)
-{
+ * @brief Enables ADC, starts conversion of regular group and transfers result
+ * through DMA.
+ * Interruptions enabled in this function:
+ * - DMA transfer complete
+ * - DMA half transfer
+ * Each of these interruptions has its dedicated callback function.
+ * @note For devices with several ADCs: This function is for single-ADC mode
+ * only. For multimode, use the dedicated MultimodeStart function.
+ * @note On STM32F1 devices, only ADC1 and ADC3 (ADC availability depending
+ * on devices) have DMA capability.
+ * ADC2 converted data can be transferred in dual ADC mode using DMA
+ * of ADC1 (ADC master in multimode).
+ * In case of using ADC1 with DMA on a device featuring 2 ADC
+ * instances: ADC1 conversion register DR contains ADC1 conversion
+ * result (ADC1 register DR bits 0 to 11) and, additionally, ADC2 last
+ * conversion result (ADC1 register DR bits 16 to 27). Therefore, to
+ * have DMA transferring the conversion results of ADC1 only, DMA must
+ * be configured to transfer size: half word.
+ * @param hadc: ADC handle
+ * @param pData: The destination Buffer address.
+ * @param Length: The length of data to be transferred from ADC peripheral to memory.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_DMA_CAPABILITY_INSTANCE(hadc->Instance));
-
+
/* Verification if multimode is disabled (for devices with several ADC) */
/* If multimode is enabled, dedicated function multimode conversion */
/* start DMA must be used. */
- if(ADC_MULTIMODE_IS_ENABLE(hadc) == RESET)
- {
+ if (ADC_MULTIMODE_IS_ENABLE(hadc) == RESET) {
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
-
+
/* Start conversion if ADC is effectively enabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state */
/* - Clear state bitfield related to regular group conversion results */
/* - Set state bitfield related to regular operation */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP,
- HAL_ADC_STATE_REG_BUSY);
-
- /* Set group injected state (from auto-injection) and multimode state */
- /* for all cases of multimode: independent mode, multimode ADC master */
- /* or multimode ADC slave (for devices with several ADCs): */
- if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc))
- {
- /* Set ADC state (ADC independent or master) */
- CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
-
- /* If conversions on group regular are also triggering group injected, */
- /* update ADC state. */
- if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET)
- {
- ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
- }
- }
- else
- {
- /* Set ADC state (ADC slave) */
- SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
-
- /* If conversions on group regular are also triggering group injected, */
- /* update ADC state. */
- if (ADC_MULTIMODE_AUTO_INJECTED(hadc))
- {
- ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_REG_OVR | HAL_ADC_STATE_REG_EOSMP, HAL_ADC_STATE_REG_BUSY);
+
+ /* Set group injected state (from auto-injection) and multimode state */
+ /* for all cases of multimode: independent mode, multimode ADC master */
+ /* or multimode ADC slave (for devices with several ADCs): */
+ if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc)) {
+ /* Set ADC state (ADC independent or master) */
+ CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
+
+ /* If conversions on group regular are also triggering group injected, */
+ /* update ADC state. */
+ if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET) {
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
+ }
+ } else {
+ /* Set ADC state (ADC slave) */
+ SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
+
+ /* If conversions on group regular are also triggering group injected, */
+ /* update ADC state. */
+ if (ADC_MULTIMODE_AUTO_INJECTED(hadc)) {
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
+ }
}
- }
-
+
/* State machine update: Check if an injected conversion is ongoing */
- if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY))
- {
+ if (HAL_IS_BIT_SET(hadc->State, HAL_ADC_STATE_INJ_BUSY)) {
/* Reset ADC error code fields related to conversions on group regular */
- CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
- }
- else
- {
+ CLEAR_BIT(hadc->ErrorCode, (HAL_ADC_ERROR_OVR | HAL_ADC_ERROR_DMA));
+ } else {
/* Reset ADC all error code fields */
ADC_CLEAR_ERRORCODE(hadc);
}
-
+
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
-
+
/* Set the DMA transfer complete callback */
hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
/* Set the DMA half transfer complete callback */
hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
-
+
/* Set the DMA error callback */
hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;
-
/* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */
/* start (in case of SW start): */
-
+
/* Clear regular group conversion flag and overrun flag */
/* (To ensure of no unknown state from potential previous ADC */
/* operations) */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC);
-
+
/* Enable ADC DMA mode */
SET_BIT(hadc->Instance->CR2, ADC_CR2_DMA);
-
+
/* Start the DMA channel */
HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
-
+
/* Enable conversion of regular group. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
- if (ADC_IS_SOFTWARE_START_REGULAR(hadc))
- {
+ if (ADC_IS_SOFTWARE_START_REGULAR(hadc)) {
/* Start ADC conversion on regular group with SW start */
SET_BIT(hadc->Instance->CR2, (ADC_CR2_SWSTART | ADC_CR2_EXTTRIG));
- }
- else
- {
+ } else {
/* Start ADC conversion on regular group with external trigger */
SET_BIT(hadc->Instance->CR2, ADC_CR2_EXTTRIG);
}
- }
- else
- {
+ } else {
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
- }
- else
- {
+ } else {
tmp_hal_status = HAL_ERROR;
}
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Stop ADC conversion of regular group (and injected group in
- * case of auto_injection mode), disable ADC DMA transfer, disable
- * ADC peripheral.
- * @note: ADC peripheral disable is forcing stop of potential
- * conversion on injected group. If injected group is under use, it
- * should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
- * @note For devices with several ADCs: This function is for single-ADC mode
- * only. For multimode, use the dedicated MultimodeStop function.
- * @note On STM32F1 devices, only ADC1 and ADC3 (ADC availability depending
- * on devices) have DMA capability.
- * @param hadc: ADC handle
- * @retval HAL status.
- */
-HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc)
-{
+ * @brief Stop ADC conversion of regular group (and injected group in
+ * case of auto_injection mode), disable ADC DMA transfer, disable
+ * ADC peripheral.
+ * @note: ADC peripheral disable is forcing stop of potential
+ * conversion on injected group. If injected group is under use, it
+ * should be preliminarily stopped using HAL_ADCEx_InjectedStop function.
+ * @note For devices with several ADCs: This function is for single-ADC mode
+ * only. For multimode, use the dedicated MultimodeStop function.
+ * @note On STM32F1 devices, only ADC1 and ADC3 (ADC availability depending
+ * on devices) have DMA capability.
+ * @param hadc: ADC handle
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_DMA_CAPABILITY_INSTANCE(hadc->Instance));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Stop potential conversion on going, on regular and injected groups */
/* Disable ADC peripheral */
tmp_hal_status = ADC_ConversionStop_Disable(hadc);
-
+
/* Check if ADC is effectively disabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Disable ADC DMA mode */
CLEAR_BIT(hadc->Instance->CR2, ADC_CR2_DMA);
-
+
/* Disable the DMA channel (in case of DMA in circular mode or stop while */
/* DMA transfer is on going) */
tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
-
+
/* Check if DMA channel effectively disabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
- HAL_ADC_STATE_READY);
- }
- else
- {
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY);
+ } else {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
}
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Get ADC regular group conversion result.
- * @note Reading register DR automatically clears ADC flag EOC
- * (ADC group regular end of unitary conversion).
- * @note This function does not clear ADC flag EOS
- * (ADC group regular end of sequence conversion).
- * Occurrence of flag EOS rising:
- * - If sequencer is composed of 1 rank, flag EOS is equivalent
- * to flag EOC.
- * - If sequencer is composed of several ranks, during the scan
- * sequence flag EOC only is raised, at the end of the scan sequence
- * both flags EOC and EOS are raised.
- * To clear this flag, either use function:
- * in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
- * model polling: @ref HAL_ADC_PollForConversion()
- * or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_EOS).
- * @param hadc: ADC handle
- * @retval ADC group regular conversion data
- */
-uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc)
-{
+ * @brief Get ADC regular group conversion result.
+ * @note Reading register DR automatically clears ADC flag EOC
+ * (ADC group regular end of unitary conversion).
+ * @note This function does not clear ADC flag EOS
+ * (ADC group regular end of sequence conversion).
+ * Occurrence of flag EOS rising:
+ * - If sequencer is composed of 1 rank, flag EOS is equivalent
+ * to flag EOC.
+ * - If sequencer is composed of several ranks, during the scan
+ * sequence flag EOC only is raised, at the end of the scan sequence
+ * both flags EOC and EOS are raised.
+ * To clear this flag, either use function:
+ * in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
+ * model polling: @ref HAL_ADC_PollForConversion()
+ * or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_EOS).
+ * @param hadc: ADC handle
+ * @retval ADC group regular conversion data
+ */
+uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef *hadc) {
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Note: EOC flag is not cleared here by software because automatically */
/* cleared by hardware when reading register DR. */
-
- /* Return ADC converted value */
+
+ /* Return ADC converted value */
return hadc->Instance->DR;
}
/**
- * @brief Handles ADC interrupt request
- * @param hadc: ADC handle
- * @retval None
- */
-void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc)
-{
+ * @brief Handles ADC interrupt request
+ * @param hadc: ADC handle
+ * @retval None
+ */
+void HAL_ADC_IRQHandler(ADC_HandleTypeDef *hadc) {
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
assert_param(IS_ADC_REGULAR_NB_CONV(hadc->Init.NbrOfConversion));
-
-
+
/* ========== Check End of Conversion flag for regular group ========== */
- if(__HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOC))
- {
- if(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC) )
- {
+ if (__HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOC)) {
+ if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC)) {
/* Update state machine on conversion status if not in error state */
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL))
- {
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL)) {
/* Set ADC state */
- SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
+ SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
}
-
+
/* Determine whether any further conversion upcoming on group regular */
/* by external trigger, continuous mode or scan sequence on going. */
/* Note: On STM32F1 devices, in case of sequencer enabled */
/* (several ranks selected), end of conversion flag is raised */
/* at the end of the sequence. */
- if(ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
- (hadc->Init.ContinuousConvMode == DISABLE) )
- {
+ if (ADC_IS_SOFTWARE_START_REGULAR(hadc) && (hadc->Init.ContinuousConvMode == DISABLE)) {
/* Disable ADC end of conversion interrupt on group regular */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC);
-
+
/* Set ADC state */
- CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
-
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY))
- {
+ CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
+
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY)) {
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
/* Conversion complete callback */
HAL_ADC_ConvCpltCallback(hadc);
-
+
/* Clear regular group conversion flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_STRT | ADC_FLAG_EOC);
}
}
-
+
/* ========== Check End of Conversion flag for injected group ========== */
- if(__HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_JEOC))
- {
- if(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOC))
- {
+ if (__HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_JEOC)) {
+ if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOC)) {
/* Update state machine on conversion status if not in error state */
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL))
- {
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL)) {
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_INJ_EOC);
}
@@ -1558,56 +1381,47 @@ void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc)
/* Note: On STM32F1 devices, in case of sequencer enabled */
/* (several ranks selected), end of conversion flag is raised */
/* at the end of the sequence. */
- if(ADC_IS_SOFTWARE_START_INJECTED(hadc) ||
- (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) &&
- (ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
- (hadc->Init.ContinuousConvMode == DISABLE) ) ) )
- {
+ if (ADC_IS_SOFTWARE_START_INJECTED(hadc) || (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) && (ADC_IS_SOFTWARE_START_REGULAR(hadc) && (hadc->Init.ContinuousConvMode == DISABLE)))) {
/* Disable ADC end of conversion interrupt on group injected */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
-
+
/* Set ADC state */
- CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
+ CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY))
- {
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY)) {
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
- /* Conversion complete callback */
+ /* Conversion complete callback */
HAL_ADCEx_InjectedConvCpltCallback(hadc);
-
+
/* Clear injected group conversion flag */
__HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_JSTRT | ADC_FLAG_JEOC));
}
}
-
+
/* ========== Check Analog watchdog flags ========== */
- if(__HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_AWD))
- {
- if(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_AWD))
- {
+ if (__HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_AWD)) {
+ if (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_AWD)) {
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_AWD1);
-
- /* Level out of window callback */
+
+ /* Level out of window callback */
HAL_ADC_LevelOutOfWindowCallback(hadc);
-
+
/* Clear the ADC analog watchdog flag */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD);
}
}
-
}
/**
- * @brief Conversion complete callback in non blocking mode
- * @param hadc: ADC handle
- * @retval None
- */
-__weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
-{
+ * @brief Conversion complete callback in non blocking mode
+ * @param hadc: ADC handle
+ * @retval None
+ */
+__weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
@@ -1616,12 +1430,11 @@ __weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
}
/**
- * @brief Conversion DMA half-transfer callback in non blocking mode
- * @param hadc: ADC handle
- * @retval None
- */
-__weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
-{
+ * @brief Conversion DMA half-transfer callback in non blocking mode
+ * @param hadc: ADC handle
+ * @retval None
+ */
+__weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
@@ -1630,12 +1443,11 @@ __weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc)
}
/**
- * @brief Analog watchdog callback in non blocking mode.
- * @param hadc: ADC handle
- * @retval None
- */
-__weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc)
-{
+ * @brief Analog watchdog callback in non blocking mode.
+ * @param hadc: ADC handle
+ * @retval None
+ */
+__weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef *hadc) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
@@ -1644,13 +1456,12 @@ __weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc)
}
/**
- * @brief ADC error callback in non blocking mode
- * (ADC conversion with interruption or transfer by DMA)
- * @param hadc: ADC handle
- * @retval None
- */
-__weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
-{
+ * @brief ADC error callback in non blocking mode
+ * (ADC conversion with interruption or transfer by DMA)
+ * @param hadc: ADC handle
+ * @retval None
+ */
+__weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function should not be modified. When the callback is needed,
@@ -1658,219 +1469,178 @@ __weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc)
*/
}
-
/**
- * @}
- */
+ * @}
+ */
/** @defgroup ADC_Exported_Functions_Group3 Peripheral Control functions
* @brief Peripheral Control functions
*
-@verbatim
+@verbatim
===============================================================================
##### Peripheral Control functions #####
- ===============================================================================
+ ===============================================================================
[..] This section provides functions allowing to:
(+) Configure channels on regular group
(+) Configure the analog watchdog
-
+
@endverbatim
* @{
*/
/**
- * @brief Configures the the selected channel to be linked to the regular
- * group.
- * @note In case of usage of internal measurement channels:
- * Vbat/VrefInt/TempSensor.
- * These internal paths can be be disabled using function
- * HAL_ADC_DeInit().
- * @note Possibility to update parameters on the fly:
- * This function initializes channel into regular group, following
- * calls to this function can be used to reconfigure some parameters
- * of structure "ADC_ChannelConfTypeDef" on the fly, without reseting
- * the ADC.
- * The setting of these parameters is conditioned to ADC state.
- * For parameters constraints, see comments of structure
- * "ADC_ChannelConfTypeDef".
- * @param hadc: ADC handle
- * @param sConfig: Structure of ADC channel for regular group.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig)
-{
- HAL_StatusTypeDef tmp_hal_status = HAL_OK;
- __IO uint32_t wait_loop_index = 0U;
-
+ * @brief Configures the the selected channel to be linked to the regular
+ * group.
+ * @note In case of usage of internal measurement channels:
+ * Vbat/VrefInt/TempSensor.
+ * These internal paths can be be disabled using function
+ * HAL_ADC_DeInit().
+ * @note Possibility to update parameters on the fly:
+ * This function initializes channel into regular group, following
+ * calls to this function can be used to reconfigure some parameters
+ * of structure "ADC_ChannelConfTypeDef" on the fly, without reseting
+ * the ADC.
+ * The setting of these parameters is conditioned to ADC state.
+ * For parameters constraints, see comments of structure
+ * "ADC_ChannelConfTypeDef".
+ * @param hadc: ADC handle
+ * @param sConfig: Structure of ADC channel for regular group.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef *hadc, ADC_ChannelConfTypeDef *sConfig) {
+ HAL_StatusTypeDef tmp_hal_status = HAL_OK;
+ __IO uint32_t wait_loop_index = 0U;
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_CHANNEL(sConfig->Channel));
assert_param(IS_ADC_REGULAR_RANK(sConfig->Rank));
assert_param(IS_ADC_SAMPLE_TIME(sConfig->SamplingTime));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
-
+
/* Regular sequence configuration */
/* For Rank 1 to 6 */
- if (sConfig->Rank < 7U)
- {
- MODIFY_REG(hadc->Instance->SQR3 ,
- ADC_SQR3_RK(ADC_SQR3_SQ1, sConfig->Rank) ,
- ADC_SQR3_RK(sConfig->Channel, sConfig->Rank) );
+ if (sConfig->Rank < 7U) {
+ MODIFY_REG(hadc->Instance->SQR3, ADC_SQR3_RK(ADC_SQR3_SQ1, sConfig->Rank), ADC_SQR3_RK(sConfig->Channel, sConfig->Rank));
}
/* For Rank 7 to 12 */
- else if (sConfig->Rank < 13U)
- {
- MODIFY_REG(hadc->Instance->SQR2 ,
- ADC_SQR2_RK(ADC_SQR2_SQ7, sConfig->Rank) ,
- ADC_SQR2_RK(sConfig->Channel, sConfig->Rank) );
+ else if (sConfig->Rank < 13U) {
+ MODIFY_REG(hadc->Instance->SQR2, ADC_SQR2_RK(ADC_SQR2_SQ7, sConfig->Rank), ADC_SQR2_RK(sConfig->Channel, sConfig->Rank));
}
/* For Rank 13 to 16 */
- else
- {
- MODIFY_REG(hadc->Instance->SQR1 ,
- ADC_SQR1_RK(ADC_SQR1_SQ13, sConfig->Rank) ,
- ADC_SQR1_RK(sConfig->Channel, sConfig->Rank) );
+ else {
+ MODIFY_REG(hadc->Instance->SQR1, ADC_SQR1_RK(ADC_SQR1_SQ13, sConfig->Rank), ADC_SQR1_RK(sConfig->Channel, sConfig->Rank));
}
-
-
+
/* Channel sampling time configuration */
/* For channels 10 to 17 */
- if (sConfig->Channel >= ADC_CHANNEL_10)
- {
- MODIFY_REG(hadc->Instance->SMPR1 ,
- ADC_SMPR1(ADC_SMPR1_SMP10, sConfig->Channel) ,
- ADC_SMPR1(sConfig->SamplingTime, sConfig->Channel) );
- }
- else /* For channels 0 to 9 */
+ if (sConfig->Channel >= ADC_CHANNEL_10) {
+ MODIFY_REG(hadc->Instance->SMPR1, ADC_SMPR1(ADC_SMPR1_SMP10, sConfig->Channel), ADC_SMPR1(sConfig->SamplingTime, sConfig->Channel));
+ } else /* For channels 0 to 9 */
{
- MODIFY_REG(hadc->Instance->SMPR2 ,
- ADC_SMPR2(ADC_SMPR2_SMP0, sConfig->Channel) ,
- ADC_SMPR2(sConfig->SamplingTime, sConfig->Channel) );
+ MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfig->Channel), ADC_SMPR2(sConfig->SamplingTime, sConfig->Channel));
}
-
+
/* If ADC1 Channel_16 or Channel_17 is selected, enable Temperature sensor */
/* and VREFINT measurement path. */
- if ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) ||
- (sConfig->Channel == ADC_CHANNEL_VREFINT) )
- {
+ if ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) || (sConfig->Channel == ADC_CHANNEL_VREFINT)) {
/* For STM32F1 devices with several ADC: Only ADC1 can access internal */
/* measurement channels (VrefInt/TempSensor). If these channels are */
/* intended to be set on other ADC instances, an error is reported. */
- if (hadc->Instance == ADC1)
- {
- if (READ_BIT(hadc->Instance->CR2, ADC_CR2_TSVREFE) == RESET)
- {
+ if (hadc->Instance == ADC1) {
+ if (READ_BIT(hadc->Instance->CR2, ADC_CR2_TSVREFE) == RESET) {
SET_BIT(hadc->Instance->CR2, ADC_CR2_TSVREFE);
-
- if ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR))
- {
+
+ if ((sConfig->Channel == ADC_CHANNEL_TEMPSENSOR)) {
/* Delay for temperature sensor stabilization time */
/* Compute number of CPU cycles to wait for */
wait_loop_index = (ADC_TEMPSENSOR_DELAY_US * (SystemCoreClock / 1000000U));
- while(wait_loop_index != 0U)
- {
+ while (wait_loop_index != 0U) {
wait_loop_index--;
}
}
}
- }
- else
- {
+ } else {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
+
tmp_hal_status = HAL_ERROR;
}
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Configures the analog watchdog.
- * @note Analog watchdog thresholds can be modified while ADC conversion
- * is on going.
- * In this case, some constraints must be taken into account:
- * the programmed threshold values are effective from the next
- * ADC EOC (end of unitary conversion).
- * Considering that registers write delay may happen due to
- * bus activity, this might cause an uncertainty on the
- * effective timing of the new programmed threshold values.
- * @param hadc: ADC handle
- * @param AnalogWDGConfig: Structure of ADC analog watchdog configuration
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig)
-{
+ * @brief Configures the analog watchdog.
+ * @note Analog watchdog thresholds can be modified while ADC conversion
+ * is on going.
+ * In this case, some constraints must be taken into account:
+ * the programmed threshold values are effective from the next
+ * ADC EOC (end of unitary conversion).
+ * Considering that registers write delay may happen due to
+ * bus activity, this might cause an uncertainty on the
+ * effective timing of the new programmed threshold values.
+ * @param hadc: ADC handle
+ * @param AnalogWDGConfig: Structure of ADC analog watchdog configuration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef *hadc, ADC_AnalogWDGConfTypeDef *AnalogWDGConfig) {
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_ANALOG_WATCHDOG_MODE(AnalogWDGConfig->WatchdogMode));
assert_param(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode));
assert_param(IS_ADC_RANGE(AnalogWDGConfig->HighThreshold));
assert_param(IS_ADC_RANGE(AnalogWDGConfig->LowThreshold));
-
- if((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) ||
- (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC) ||
- (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC) )
- {
+
+ if ((AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REG) || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_INJEC)
+ || (AnalogWDGConfig->WatchdogMode == ADC_ANALOGWATCHDOG_SINGLE_REGINJEC)) {
assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel));
}
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Analog watchdog configuration */
/* Configure ADC Analog watchdog interrupt */
- if(AnalogWDGConfig->ITMode == ENABLE)
- {
+ if (AnalogWDGConfig->ITMode == ENABLE) {
/* Enable the ADC Analog watchdog interrupt */
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_AWD);
- }
- else
- {
+ } else {
/* Disable the ADC Analog watchdog interrupt */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_AWD);
}
-
+
/* Configuration of analog watchdog: */
/* - Set the analog watchdog enable mode: regular and/or injected groups, */
/* one or all channels. */
/* - Set the Analog watchdog channel (is not used if watchdog */
/* mode "all channels": ADC_CFGR_AWD1SGL=0). */
- MODIFY_REG(hadc->Instance->CR1 ,
- ADC_CR1_AWDSGL |
- ADC_CR1_JAWDEN |
- ADC_CR1_AWDEN |
- ADC_CR1_AWDCH ,
- AnalogWDGConfig->WatchdogMode |
- AnalogWDGConfig->Channel );
-
+ MODIFY_REG(hadc->Instance->CR1, ADC_CR1_AWDSGL | ADC_CR1_JAWDEN | ADC_CR1_AWDEN | ADC_CR1_AWDCH, AnalogWDGConfig->WatchdogMode | AnalogWDGConfig->Channel);
+
/* Set the high threshold */
WRITE_REG(hadc->Instance->HTR, AnalogWDGConfig->HighThreshold);
-
+
/* Set the low threshold */
WRITE_REG(hadc->Instance->LTR, AnalogWDGConfig->LowThreshold);
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return HAL_OK;
}
-
/**
- * @}
- */
-
+ * @}
+ */
/** @defgroup ADC_Exported_Functions_Group4 Peripheral State functions
* @brief Peripheral State functions
@@ -1878,9 +1648,9 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDG
@verbatim
===============================================================================
##### Peripheral State and Errors functions #####
- ===============================================================================
+ ===============================================================================
[..]
- This subsection provides functions to get in run-time the status of the
+ This subsection provides functions to get in run-time the status of the
peripheral.
(+) Check the ADC state
(+) Check the ADC error code
@@ -1890,221 +1660,199 @@ HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDG
*/
/**
- * @brief return the ADC state
- * @param hadc: ADC handle
- * @retval HAL state
- */
-uint32_t HAL_ADC_GetState(ADC_HandleTypeDef* hadc)
-{
+ * @brief return the ADC state
+ * @param hadc: ADC handle
+ * @retval HAL state
+ */
+uint32_t HAL_ADC_GetState(ADC_HandleTypeDef *hadc) {
/* Return ADC state */
return hadc->State;
}
/**
- * @brief Return the ADC error code
- * @param hadc: ADC handle
- * @retval ADC Error Code
- */
-uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc)
-{
- return hadc->ErrorCode;
-}
+ * @brief Return the ADC error code
+ * @param hadc: ADC handle
+ * @retval ADC Error Code
+ */
+uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc) { return hadc->ErrorCode; }
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/** @defgroup ADC_Private_Functions ADC Private Functions
- * @{
- */
+ * @{
+ */
/**
- * @brief Enable the selected ADC.
- * @note Prerequisite condition to use this function: ADC must be disabled
- * and voltage regulator must be enabled (done into HAL_ADC_Init()).
- * @param hadc: ADC handle
- * @retval HAL status.
- */
-HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc)
-{
- uint32_t tickstart = 0U;
+ * @brief Enable the selected ADC.
+ * @note Prerequisite condition to use this function: ADC must be disabled
+ * and voltage regulator must be enabled (done into HAL_ADC_Init()).
+ * @param hadc: ADC handle
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef *hadc) {
+ uint32_t tickstart = 0U;
__IO uint32_t wait_loop_index = 0U;
-
+
/* ADC enable and wait for ADC ready (in case of ADC is disabled or */
/* enabling phase not yet completed: flag ADC ready not yet set). */
/* Timeout implemented to not be stuck if ADC cannot be enabled (possible */
/* causes: ADC clock not running, ...). */
- if (ADC_IS_ENABLE(hadc) == RESET)
- {
+ if (ADC_IS_ENABLE(hadc) == RESET) {
/* Enable the Peripheral */
__HAL_ADC_ENABLE(hadc);
-
+
/* Delay for ADC stabilization time */
/* Compute number of CPU cycles to wait for */
wait_loop_index = (ADC_STAB_DELAY_US * (SystemCoreClock / 1000000U));
- while(wait_loop_index != 0U)
- {
+ while (wait_loop_index != 0U) {
wait_loop_index--;
}
-
+
/* Get tick count */
tickstart = HAL_GetTick();
/* Wait for ADC effectively enabled */
- while(ADC_IS_ENABLE(hadc) == RESET)
- {
- if((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT)
- {
+ while (ADC_IS_ENABLE(hadc) == RESET) {
+ if ((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT) {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
-
+
/* Set ADC error code to ADC IP internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_ERROR;
}
}
}
-
+
/* Return HAL status */
return HAL_OK;
}
/**
- * @brief Stop ADC conversion and disable the selected ADC
- * @note Prerequisite condition to use this function: ADC conversions must be
- * stopped to disable the ADC.
- * @param hadc: ADC handle
- * @retval HAL status.
- */
-HAL_StatusTypeDef ADC_ConversionStop_Disable(ADC_HandleTypeDef* hadc)
-{
+ * @brief Stop ADC conversion and disable the selected ADC
+ * @note Prerequisite condition to use this function: ADC conversions must be
+ * stopped to disable the ADC.
+ * @param hadc: ADC handle
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef ADC_ConversionStop_Disable(ADC_HandleTypeDef *hadc) {
uint32_t tickstart = 0U;
-
+
/* Verification if ADC is not already disabled */
- if (ADC_IS_ENABLE(hadc) != RESET)
- {
+ if (ADC_IS_ENABLE(hadc) != RESET) {
/* Disable the ADC peripheral */
__HAL_ADC_DISABLE(hadc);
-
+
/* Get tick count */
tickstart = HAL_GetTick();
-
+
/* Wait for ADC effectively disabled */
- while(ADC_IS_ENABLE(hadc) != RESET)
- {
- if((HAL_GetTick() - tickstart) > ADC_DISABLE_TIMEOUT)
- {
+ while (ADC_IS_ENABLE(hadc) != RESET) {
+ if ((HAL_GetTick() - tickstart) > ADC_DISABLE_TIMEOUT) {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
-
+
/* Set ADC error code to ADC IP internal error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_INTERNAL);
-
+
return HAL_ERROR;
}
}
}
-
+
/* Return HAL status */
return HAL_OK;
}
/**
- * @brief DMA transfer complete callback.
- * @param hdma: pointer to DMA handle.
- * @retval None
- */
-void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma)
-{
+ * @brief DMA transfer complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma) {
/* Retrieve ADC handle corresponding to current DMA handle */
- ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
-
+ ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
+
/* Update state machine on conversion status if not in error state */
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA))
- {
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL | HAL_ADC_STATE_ERROR_DMA)) {
/* Update ADC state machine */
SET_BIT(hadc->State, HAL_ADC_STATE_REG_EOC);
-
+
/* Determine whether any further conversion upcoming on group regular */
/* by external trigger, continuous mode or scan sequence on going. */
/* Note: On STM32F1 devices, in case of sequencer enabled */
/* (several ranks selected), end of conversion flag is raised */
/* at the end of the sequence. */
- if(ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
- (hadc->Init.ContinuousConvMode == DISABLE) )
- {
+ if (ADC_IS_SOFTWARE_START_REGULAR(hadc) && (hadc->Init.ContinuousConvMode == DISABLE)) {
/* Set ADC state */
- CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
-
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY))
- {
+ CLEAR_BIT(hadc->State, HAL_ADC_STATE_REG_BUSY);
+
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_INJ_BUSY)) {
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
-
+
/* Conversion complete callback */
- HAL_ADC_ConvCpltCallback(hadc);
- }
- else
- {
+ HAL_ADC_ConvCpltCallback(hadc);
+ } else {
/* Call DMA error callback */
hadc->DMA_Handle->XferErrorCallback(hdma);
}
}
/**
- * @brief DMA half transfer complete callback.
- * @param hdma: pointer to DMA handle.
- * @retval None
- */
-void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma)
-{
+ * @brief DMA half transfer complete callback.
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma) {
/* Retrieve ADC handle corresponding to current DMA handle */
- ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
-
+ ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
+
/* Half conversion callback */
- HAL_ADC_ConvHalfCpltCallback(hadc);
+ HAL_ADC_ConvHalfCpltCallback(hadc);
}
/**
- * @brief DMA error callback
- * @param hdma: pointer to DMA handle.
- * @retval None
- */
-void ADC_DMAError(DMA_HandleTypeDef *hdma)
-{
+ * @brief DMA error callback
+ * @param hdma: pointer to DMA handle.
+ * @retval None
+ */
+void ADC_DMAError(DMA_HandleTypeDef *hdma) {
/* Retrieve ADC handle corresponding to current DMA handle */
- ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
-
+ ADC_HandleTypeDef *hadc = (ADC_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
+
/* Set ADC state */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_DMA);
-
+
/* Set ADC error code to DMA error */
SET_BIT(hadc->ErrorCode, HAL_ADC_ERROR_DMA);
-
+
/* Error callback */
- HAL_ADC_ErrorCallback(hadc);
+ HAL_ADC_ErrorCallback(hadc);
}
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_ADC_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c
index 5619d38a..893b798d 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_adc_ex.c
@@ -2,7 +2,7 @@
******************************************************************************
* @file stm32f1xx_hal_adc_ex.c
* @author MCD Application Team
- * @brief This file provides firmware functions to manage the following
+ * @brief This file provides firmware functions to manage the following
* functionalities of the Analog to Digital Convertor (ADC)
* peripheral:
* + Operation functions
@@ -12,11 +12,11 @@
* ++ Calibration (ADC automatic self-calibration)
* + Control functions
* ++ Channels configuration on injected group
- * Other functions (generic functions) are available in file
+ * Other functions (generic functions) are available in file
* "stm32f1xx_hal_adc.c".
*
@verbatim
- [..]
+ [..]
(@) Sections "ADC peripheral features" and "How to use this driver" are
available in file of generic functions "stm32f1xx_hal_adc.c".
[..]
@@ -48,51 +48,51 @@
* 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.
*
- ******************************************************************************
+ ******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup ADCEx ADCEx
- * @brief ADC Extension HAL module driver
- * @{
- */
+ * @brief ADC Extension HAL module driver
+ * @{
+ */
#ifdef HAL_ADC_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup ADCEx_Private_Constants ADCEx Private Constants
- * @{
- */
+ * @{
+ */
+
+/* Delay for ADC calibration: */
+/* Hardware prerequisite before starting a calibration: the ADC must have */
+/* been in power-on state for at least two ADC clock cycles. */
+/* Unit: ADC clock cycles */
+#define ADC_PRECALIBRATION_DELAY_ADCCLOCKCYCLES 2U
- /* Delay for ADC calibration: */
- /* Hardware prerequisite before starting a calibration: the ADC must have */
- /* been in power-on state for at least two ADC clock cycles. */
- /* Unit: ADC clock cycles */
- #define ADC_PRECALIBRATION_DELAY_ADCCLOCKCYCLES 2U
-
- /* Timeout value for ADC calibration */
- /* Value defined to be higher than worst cases: low clocks freq, */
- /* maximum prescaler. */
- /* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock */
- /* prescaler 4, sampling time 12.5 ADC clock cycles, resolution 12 bits. */
- /* Unit: ms */
- #define ADC_CALIBRATION_TIMEOUT 10U
-
- /* Delay for temperature sensor stabilization time. */
- /* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */
- /* Unit: us */
- #define ADC_TEMPSENSOR_DELAY_US 10U
+/* Timeout value for ADC calibration */
+/* Value defined to be higher than worst cases: low clocks freq, */
+/* maximum prescaler. */
+/* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock */
+/* prescaler 4, sampling time 12.5 ADC clock cycles, resolution 12 bits. */
+/* Unit: ms */
+#define ADC_CALIBRATION_TIMEOUT 10U
+
+/* Delay for temperature sensor stabilization time. */
+/* Maximum delay is 10us (refer to device datasheet, parameter tSTART). */
+/* Unit: us */
+#define ADC_TEMPSENSOR_DELAY_US 10U
/**
- * @}
- */
+ * @}
+ */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
@@ -100,13 +100,13 @@
/* Private functions ---------------------------------------------------------*/
/** @defgroup ADCEx_Exported_Functions ADCEx Exported Functions
- * @{
- */
+ * @{
+ */
/** @defgroup ADCEx_Exported_Functions_Group1 Extended Extended IO operation functions
* @brief Extended Extended Input and Output operation functions
*
-@verbatim
+@verbatim
===============================================================================
##### IO operation functions #####
===============================================================================
@@ -125,179 +125,153 @@
(+) Perform the ADC self-calibration for single or differential ending.
(+) Get calibration factors for single or differential ending.
(+) Set calibration factors for single or differential ending.
-
+
@endverbatim
* @{
*/
/**
- * @brief Perform an ADC automatic self-calibration
- * Calibration prerequisite: ADC must be disabled (execute this
- * function before HAL_ADC_Start() or after HAL_ADC_Stop() ).
- * During calibration process, ADC is enabled. ADC is let enabled at
- * the completion of this function.
- * @param hadc: ADC handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef* hadc)
-{
+ * @brief Perform an ADC automatic self-calibration
+ * Calibration prerequisite: ADC must be disabled (execute this
+ * function before HAL_ADC_Start() or after HAL_ADC_Stop() ).
+ * During calibration process, ADC is enabled. ADC is let enabled at
+ * the completion of this function.
+ * @param hadc: ADC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
- uint32_t tickstart;
- __IO uint32_t wait_loop_index = 0U;
-
+ uint32_t tickstart;
+ __IO uint32_t wait_loop_index = 0U;
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* 1. Calibration prerequisite: */
/* - ADC must be disabled for at least two ADC clock cycles in disable */
/* mode before ADC enable */
/* Stop potential conversion on going, on regular and injected groups */
/* Disable ADC peripheral */
tmp_hal_status = ADC_ConversionStop_Disable(hadc);
-
+
/* Check if ADC is effectively disabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
- HAL_ADC_STATE_BUSY_INTERNAL);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_BUSY_INTERNAL);
+
/* Hardware prerequisite: delay before starting the calibration. */
/* - Computation of CPU clock cycles corresponding to ADC clock cycles. */
/* - Wait for the expected ADC clock cycles delay */
- wait_loop_index = ((SystemCoreClock
- / HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_ADC))
- * ADC_PRECALIBRATION_DELAY_ADCCLOCKCYCLES );
+ wait_loop_index = ((SystemCoreClock / HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_ADC)) * ADC_PRECALIBRATION_DELAY_ADCCLOCKCYCLES);
- while(wait_loop_index != 0U)
- {
+ while (wait_loop_index != 0U) {
wait_loop_index--;
}
-
+
/* 2. Enable the ADC peripheral */
ADC_Enable(hadc);
-
- /* 3. Resets ADC calibration registers */
+
+ /* 3. Resets ADC calibration registers */
SET_BIT(hadc->Instance->CR2, ADC_CR2_RSTCAL);
-
- tickstart = HAL_GetTick();
+
+ tickstart = HAL_GetTick();
/* Wait for calibration reset completion */
- while(HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_RSTCAL))
- {
- if((HAL_GetTick() - tickstart) > ADC_CALIBRATION_TIMEOUT)
- {
+ while (HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_RSTCAL)) {
+ if ((HAL_GetTick() - tickstart) > ADC_CALIBRATION_TIMEOUT) {
/* Update ADC state machine to error */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_BUSY_INTERNAL,
- HAL_ADC_STATE_ERROR_INTERNAL);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_ERROR_INTERNAL);
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_ERROR;
}
}
-
-
+
/* 4. Start ADC calibration */
SET_BIT(hadc->Instance->CR2, ADC_CR2_CAL);
-
- tickstart = HAL_GetTick();
+
+ tickstart = HAL_GetTick();
/* Wait for calibration completion */
- while(HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_CAL))
- {
- if((HAL_GetTick() - tickstart) > ADC_CALIBRATION_TIMEOUT)
- {
+ while (HAL_IS_BIT_SET(hadc->Instance->CR2, ADC_CR2_CAL)) {
+ if ((HAL_GetTick() - tickstart) > ADC_CALIBRATION_TIMEOUT) {
/* Update ADC state machine to error */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_BUSY_INTERNAL,
- HAL_ADC_STATE_ERROR_INTERNAL);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_ERROR_INTERNAL);
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_ERROR;
}
}
-
+
/* Set ADC state */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_BUSY_INTERNAL,
- HAL_ADC_STATE_READY);
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_BUSY_INTERNAL, HAL_ADC_STATE_READY);
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Enables ADC, starts conversion of injected group.
- * Interruptions enabled in this function: None.
- * @param hadc: ADC handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc)
-{
+ * @brief Enables ADC, starts conversion of injected group.
+ * Interruptions enabled in this function: None.
+ * @param hadc: ADC handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
-
+
/* Start conversion if ADC is effectively enabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state */
/* - Clear state bitfield related to injected group conversion results */
/* - Set state bitfield related to injected operation */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC,
- HAL_ADC_STATE_INJ_BUSY);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
+
/* Case of independent mode or multimode (for devices with several ADCs): */
/* Set multimode state. */
- if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc))
- {
+ if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc)) {
CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
- }
- else
- {
+ } else {
SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
}
-
+
/* Check if a regular conversion is ongoing */
/* Note: On this device, there is no ADC error code fields related to */
/* conversions on group injected only. In case of conversion on */
/* going on group regular, no error code is reset. */
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY))
- {
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY)) {
/* Reset ADC all error code fields */
ADC_CLEAR_ERRORCODE(hadc);
}
-
+
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
-
+
/* Clear injected group conversion flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC);
-
+
/* Enable conversion of injected group. */
/* If software start has been selected, conversion starts immediately. */
/* If external trigger has been selected, conversion will start at next */
@@ -307,111 +281,95 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc)
/* Case of multimode enabled (for devices with several ADCs): if ADC is */
/* slave, ADC is enabled only (conversion is not started). If ADC is */
/* master, ADC is enabled and conversion is started. */
- if (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO))
- {
- if (ADC_IS_SOFTWARE_START_INJECTED(hadc) &&
- ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc) )
- {
+ if (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO)) {
+ if (ADC_IS_SOFTWARE_START_INJECTED(hadc) && ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc)) {
/* Start ADC conversion on injected group with SW start */
SET_BIT(hadc->Instance->CR2, (ADC_CR2_JSWSTART | ADC_CR2_JEXTTRIG));
- }
- else
- {
+ } else {
/* Start ADC conversion on injected group with external trigger */
SET_BIT(hadc->Instance->CR2, ADC_CR2_JEXTTRIG);
}
}
- }
- else
- {
+ } else {
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Stop conversion of injected channels. Disable ADC peripheral if
- * no regular conversion is on going.
- * @note If ADC must be disabled and if conversion is on going on
- * regular group, function HAL_ADC_Stop must be used to stop both
- * injected and regular groups, and disable the ADC.
- * @note If injected group mode auto-injection is enabled,
- * function HAL_ADC_Stop must be used.
- * @note In case of auto-injection mode, HAL_ADC_Stop must be used.
- * @param hadc: ADC handle
- * @retval None
- */
-HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef* hadc)
-{
+ * @brief Stop conversion of injected channels. Disable ADC peripheral if
+ * no regular conversion is on going.
+ * @note If ADC must be disabled and if conversion is on going on
+ * regular group, function HAL_ADC_Stop must be used to stop both
+ * injected and regular groups, and disable the ADC.
+ * @note If injected group mode auto-injection is enabled,
+ * function HAL_ADC_Stop must be used.
+ * @note In case of auto-injection mode, HAL_ADC_Stop must be used.
+ * @param hadc: ADC handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Stop potential conversion and disable ADC peripheral */
/* Conditioned to: */
/* - No conversion on the other group (regular group) is intended to */
/* continue (injected and regular groups stop conversion and ADC disable */
/* are common) */
/* - In case of auto-injection mode, HAL_ADC_Stop must be used. */
- if(((hadc->State & HAL_ADC_STATE_REG_BUSY) == RESET) &&
- HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) )
- {
+ if (((hadc->State & HAL_ADC_STATE_REG_BUSY) == RESET) && HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO)) {
/* Stop potential conversion on going, on regular and injected groups */
/* Disable ADC peripheral */
tmp_hal_status = ADC_ConversionStop_Disable(hadc);
-
+
/* Check if ADC is effectively disabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
- HAL_ADC_STATE_READY);
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY);
}
- }
- else
- {
+ } else {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
+
tmp_hal_status = HAL_ERROR;
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Wait for injected group conversion to be completed.
- * @param hadc: ADC handle
- * @param Timeout: Timeout value in millisecond.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout)
-{
+ * @brief Wait for injected group conversion to be completed.
+ * @param hadc: ADC handle
+ * @param Timeout: Timeout value in millisecond.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef *hadc, uint32_t Timeout) {
uint32_t tickstart;
/* Variables for polling in case of scan mode enabled and polling for each */
/* conversion. */
- __IO uint32_t Conversion_Timeout_CPU_cycles = 0U;
- uint32_t Conversion_Timeout_CPU_cycles_max = 0U;
-
+ __IO uint32_t Conversion_Timeout_CPU_cycles = 0U;
+ uint32_t Conversion_Timeout_CPU_cycles_max = 0U;
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Get timeout */
- tickstart = HAL_GetTick();
-
+ tickstart = HAL_GetTick();
+
/* Polling for end of conversion: differentiation if single/sequence */
/* conversion. */
/* For injected group, flag JEOC is set only at the end of the sequence, */
@@ -428,54 +386,43 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, u
/* settings, conversion time range can be from 28 to 32256 CPU cycles). */
/* As flag JEOC is not set after each conversion, no timeout status can */
/* be set. */
- if ((hadc->Instance->JSQR & ADC_JSQR_JL) == RESET)
- {
+ if ((hadc->Instance->JSQR & ADC_JSQR_JL) == RESET) {
/* Wait until End of Conversion flag is raised */
- while(HAL_IS_BIT_CLR(hadc->Instance->SR, ADC_FLAG_JEOC))
- {
+ while (HAL_IS_BIT_CLR(hadc->Instance->SR, ADC_FLAG_JEOC)) {
/* Check if timeout is disabled (set to infinite wait) */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U) || ((HAL_GetTick() - tickstart ) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) {
/* Update ADC state machine to timeout */
SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_TIMEOUT;
}
}
}
- }
- else
- {
+ } else {
/* Replace polling by wait for maximum conversion time */
/* - Computation of CPU clock cycles corresponding to ADC clock cycles */
/* and ADC maximum conversion cycles on all channels. */
/* - Wait for the expected ADC clock cycles delay */
- Conversion_Timeout_CPU_cycles_max = ((SystemCoreClock
- / HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_ADC))
- * ADC_CONVCYCLES_MAX_RANGE(hadc) );
-
- while(Conversion_Timeout_CPU_cycles < Conversion_Timeout_CPU_cycles_max)
- {
+ Conversion_Timeout_CPU_cycles_max = ((SystemCoreClock / HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_ADC)) * ADC_CONVCYCLES_MAX_RANGE(hadc));
+
+ while (Conversion_Timeout_CPU_cycles < Conversion_Timeout_CPU_cycles_max) {
/* Check if timeout is disabled (set to infinite wait) */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0) || ((HAL_GetTick() - tickstart) > Timeout)) {
/* Update ADC state machine to timeout */
SET_BIT(hadc->State, HAL_ADC_STATE_TIMEOUT);
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_TIMEOUT;
}
}
- Conversion_Timeout_CPU_cycles ++;
+ Conversion_Timeout_CPU_cycles++;
}
}
@@ -483,351 +430,306 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, u
/* Note: On STM32F1 ADC, clear regular conversion flag raised */
/* simultaneously. */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JSTRT | ADC_FLAG_JEOC | ADC_FLAG_EOC);
-
+
/* Update ADC state machine */
SET_BIT(hadc->State, HAL_ADC_STATE_INJ_EOC);
-
+
/* Determine whether any further conversion upcoming on group injected */
/* by external trigger or by automatic injected conversion */
/* from group regular. */
- if(ADC_IS_SOFTWARE_START_INJECTED(hadc) ||
- (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) &&
- (ADC_IS_SOFTWARE_START_REGULAR(hadc) &&
- (hadc->Init.ContinuousConvMode == DISABLE) ) ) )
- {
+ if (ADC_IS_SOFTWARE_START_INJECTED(hadc) || (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) && (ADC_IS_SOFTWARE_START_REGULAR(hadc) && (hadc->Init.ContinuousConvMode == DISABLE)))) {
/* Set ADC state */
- CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
-
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY))
- {
+ CLEAR_BIT(hadc->State, HAL_ADC_STATE_INJ_BUSY);
+
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY)) {
SET_BIT(hadc->State, HAL_ADC_STATE_READY);
}
}
-
+
/* Return ADC state */
return HAL_OK;
}
/**
- * @brief Enables ADC, starts conversion of injected group with interruption.
- * - JEOC (end of conversion of injected group)
- * Each of these interruptions has its dedicated callback function.
- * @param hadc: ADC handle
- * @retval HAL status.
- */
-HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc)
-{
+ * @brief Enables ADC, starts conversion of injected group with interruption.
+ * - JEOC (end of conversion of injected group)
+ * Each of these interruptions has its dedicated callback function.
+ * @param hadc: ADC handle
+ * @retval HAL status.
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Enable the ADC peripheral */
tmp_hal_status = ADC_Enable(hadc);
-
+
/* Start conversion if ADC is effectively enabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state */
/* - Clear state bitfield related to injected group conversion results */
/* - Set state bitfield related to injected operation */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC,
- HAL_ADC_STATE_INJ_BUSY);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
+
/* Case of independent mode or multimode (for devices with several ADCs): */
/* Set multimode state. */
- if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc))
- {
+ if (ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc)) {
CLEAR_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
- }
- else
- {
+ } else {
SET_BIT(hadc->State, HAL_ADC_STATE_MULTIMODE_SLAVE);
}
-
+
/* Check if a regular conversion is ongoing */
/* Note: On this device, there is no ADC error code fields related to */
/* conversions on group injected only. In case of conversion on */
/* going on group regular, no error code is reset. */
- if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY))
- {
+ if (HAL_IS_BIT_CLR(hadc->State, HAL_ADC_STATE_REG_BUSY)) {
/* Reset ADC all error code fields */
ADC_CLEAR_ERRORCODE(hadc);
}
-
+
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
-
+
/* Clear injected group conversion flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_JEOC);
-
+
/* Enable end of conversion interrupt for injected channels */
__HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC);
-
+
/* Start conversion of injected group if software start has been selected */
/* and if automatic injected conversion is disabled. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
/* If automatic injected conversion is enabled, conversion will start */
/* after next regular group conversion. */
- if (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO))
- {
- if (ADC_IS_SOFTWARE_START_INJECTED(hadc) &&
- ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc) )
- {
+ if (HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO)) {
+ if (ADC_IS_SOFTWARE_START_INJECTED(hadc) && ADC_NONMULTIMODE_OR_MULTIMODEMASTER(hadc)) {
/* Start ADC conversion on injected group with SW start */
SET_BIT(hadc->Instance->CR2, (ADC_CR2_JSWSTART | ADC_CR2_JEXTTRIG));
- }
- else
- {
+ } else {
/* Start ADC conversion on injected group with external trigger */
SET_BIT(hadc->Instance->CR2, ADC_CR2_JEXTTRIG);
}
}
- }
- else
- {
+ } else {
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Stop conversion of injected channels, disable interruption of
- * end-of-conversion. Disable ADC peripheral if no regular conversion
- * is on going.
- * @note If ADC must be disabled and if conversion is on going on
- * regular group, function HAL_ADC_Stop must be used to stop both
- * injected and regular groups, and disable the ADC.
- * @note If injected group mode auto-injection is enabled,
- * function HAL_ADC_Stop must be used.
- * @param hadc: ADC handle
- * @retval None
- */
-HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc)
-{
+ * @brief Stop conversion of injected channels, disable interruption of
+ * end-of-conversion. Disable ADC peripheral if no regular conversion
+ * is on going.
+ * @note If ADC must be disabled and if conversion is on going on
+ * regular group, function HAL_ADC_Stop must be used to stop both
+ * injected and regular groups, and disable the ADC.
+ * @note If injected group mode auto-injection is enabled,
+ * function HAL_ADC_Stop must be used.
+ * @param hadc: ADC handle
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Stop potential conversion and disable ADC peripheral */
/* Conditioned to: */
/* - No conversion on the other group (regular group) is intended to */
/* continue (injected and regular groups stop conversion and ADC disable */
/* are common) */
- /* - In case of auto-injection mode, HAL_ADC_Stop must be used. */
- if(((hadc->State & HAL_ADC_STATE_REG_BUSY) == RESET) &&
- HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO) )
- {
+ /* - In case of auto-injection mode, HAL_ADC_Stop must be used. */
+ if (((hadc->State & HAL_ADC_STATE_REG_BUSY) == RESET) && HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO)) {
/* Stop potential conversion on going, on regular and injected groups */
/* Disable ADC peripheral */
tmp_hal_status = ADC_ConversionStop_Disable(hadc);
-
+
/* Check if ADC is effectively disabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Disable ADC end of conversion interrupt for injected channels */
__HAL_ADC_DISABLE_IT(hadc, ADC_IT_JEOC);
-
+
/* Set ADC state */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
- HAL_ADC_STATE_READY);
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY);
}
- }
- else
- {
+ } else {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
+
tmp_hal_status = HAL_ERROR;
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
-#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG)
+#if defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F105xC) || defined(STM32F107xC) || defined(STM32F103xE) || defined(STM32F103xG)
/**
- * @brief Enables ADC, starts conversion of regular group and transfers result
- * through DMA.
- * Multimode must have been previously configured using
- * HAL_ADCEx_MultiModeConfigChannel() function.
- * Interruptions enabled in this function:
- * - DMA transfer complete
- * - DMA half transfer
- * Each of these interruptions has its dedicated callback function.
- * @note: On STM32F1 devices, ADC slave regular group must be configured
- * with conversion trigger ADC_SOFTWARE_START.
- * @note: ADC slave can be enabled preliminarily using single-mode
- * HAL_ADC_Start() function.
- * @param hadc: ADC handle of ADC master (handle of ADC slave must not be used)
- * @param pData: The destination Buffer address.
- * @param Length: The length of data to be transferred from ADC peripheral to memory.
- * @retval None
- */
-HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length)
-{
+ * @brief Enables ADC, starts conversion of regular group and transfers result
+ * through DMA.
+ * Multimode must have been previously configured using
+ * HAL_ADCEx_MultiModeConfigChannel() function.
+ * Interruptions enabled in this function:
+ * - DMA transfer complete
+ * - DMA half transfer
+ * Each of these interruptions has its dedicated callback function.
+ * @note: On STM32F1 devices, ADC slave regular group must be configured
+ * with conversion trigger ADC_SOFTWARE_START.
+ * @note: ADC slave can be enabled preliminarily using single-mode
+ * HAL_ADC_Start() function.
+ * @param hadc: ADC handle of ADC master (handle of ADC slave must not be used)
+ * @param pData: The destination Buffer address.
+ * @param Length: The length of data to be transferred from ADC peripheral to memory.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef *hadc, uint32_t *pData, uint32_t Length) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
ADC_HandleTypeDef tmphadcSlave;
/* Check the parameters */
assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode));
-
+
/* Process locked */
__HAL_LOCK(hadc);
/* Set a temporary handle of the ADC slave associated to the ADC master */
ADC_MULTI_SLAVE(hadc, &tmphadcSlave);
-
+
/* On STM32F1 devices, ADC slave regular group must be configured with */
/* conversion trigger ADC_SOFTWARE_START. */
/* Note: External trigger of ADC slave must be enabled, it is already done */
/* into function "HAL_ADC_Init()". */
- if(!ADC_IS_SOFTWARE_START_REGULAR(&tmphadcSlave))
- {
+ if (!ADC_IS_SOFTWARE_START_REGULAR(&tmphadcSlave)) {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
return HAL_ERROR;
}
-
+
/* Enable the ADC peripherals: master and slave (in case if not already */
/* enabled previously) */
tmp_hal_status = ADC_Enable(hadc);
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
tmp_hal_status = ADC_Enable(&tmphadcSlave);
}
-
+
/* Start conversion if all ADCs of multimode are effectively enabled */
- if (tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set ADC state (ADC master) */
/* - Clear state bitfield related to regular group conversion results */
/* - Set state bitfield related to regular operation */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_MULTIMODE_SLAVE,
- HAL_ADC_STATE_REG_BUSY);
-
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_READY | HAL_ADC_STATE_REG_EOC | HAL_ADC_STATE_MULTIMODE_SLAVE, HAL_ADC_STATE_REG_BUSY);
+
/* If conversions on group regular are also triggering group injected, */
/* update ADC state. */
- if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET)
- {
- ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
+ if (READ_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO) != RESET) {
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_INJ_EOC, HAL_ADC_STATE_INJ_BUSY);
}
-
+
/* Process unlocked */
/* Unlock before starting ADC conversions: in case of potential */
/* interruption, to let the process to ADC IRQ Handler. */
__HAL_UNLOCK(hadc);
-
+
/* Set ADC error code to none */
ADC_CLEAR_ERRORCODE(hadc);
-
-
+
/* Set the DMA transfer complete callback */
hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt;
-
+
/* Set the DMA half transfer complete callback */
hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt;
-
+
/* Set the DMA error callback */
hadc->DMA_Handle->XferErrorCallback = ADC_DMAError;
-
/* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */
/* start (in case of SW start): */
-
+
/* Clear regular group conversion flag and overrun flag */
/* (To ensure of no unknown state from potential previous ADC operations) */
__HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_EOC);
-
+
/* Enable ADC DMA mode of ADC master */
SET_BIT(hadc->Instance->CR2, ADC_CR2_DMA);
-
+
/* Start the DMA channel */
HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length);
-
+
/* Start conversion of regular group if software start has been selected. */
/* If external trigger has been selected, conversion will start at next */
/* trigger event. */
/* Note: Alternate trigger for single conversion could be to force an */
/* additional set of bit ADON "hadc->Instance->CR2 |= ADC_CR2_ADON;"*/
- if (ADC_IS_SOFTWARE_START_REGULAR(hadc))
- {
+ if (ADC_IS_SOFTWARE_START_REGULAR(hadc)) {
/* Start ADC conversion on regular group with SW start */
SET_BIT(hadc->Instance->CR2, (ADC_CR2_SWSTART | ADC_CR2_EXTTRIG));
- }
- else
- {
+ } else {
/* Start ADC conversion on regular group with external trigger */
SET_BIT(hadc->Instance->CR2, ADC_CR2_EXTTRIG);
}
- }
- else
- {
+ } else {
/* Process unlocked */
__HAL_UNLOCK(hadc);
}
-
+
/* Return function status */
return tmp_hal_status;
}
/**
- * @brief Stop ADC conversion of regular group (and injected channels in
- * case of auto_injection mode), disable ADC DMA transfer, disable
- * ADC peripheral.
- * @note Multimode is kept enabled after this function. To disable multimode
- * (set with HAL_ADCEx_MultiModeConfigChannel(), ADC must be
- * reinitialized using HAL_ADC_Init() or HAL_ADC_ReInit().
- * @note In case of DMA configured in circular mode, function
- * HAL_ADC_Stop_DMA must be called after this function with handle of
- * ADC slave, to properly disable the DMA channel.
- * @param hadc: ADC handle of ADC master (handle of ADC slave must not be used)
- * @retval None
- */
-HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc)
-{
+ * @brief Stop ADC conversion of regular group (and injected channels in
+ * case of auto_injection mode), disable ADC DMA transfer, disable
+ * ADC peripheral.
+ * @note Multimode is kept enabled after this function. To disable multimode
+ * (set with HAL_ADCEx_MultiModeConfigChannel(), ADC must be
+ * reinitialized using HAL_ADC_Init() or HAL_ADC_ReInit().
+ * @note In case of DMA configured in circular mode, function
+ * HAL_ADC_Stop_DMA must be called after this function with handle of
+ * ADC slave, to properly disable the DMA channel.
+ * @param hadc: ADC handle of ADC master (handle of ADC slave must not be used)
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef *hadc) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
ADC_HandleTypeDef tmphadcSlave;
-
+
/* Check the parameters */
assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
-
+
/* Stop potential conversion on going, on regular and injected groups */
/* Disable ADC master peripheral */
tmp_hal_status = ADC_ConversionStop_Disable(hadc);
-
+
/* Check if ADC is effectively disabled */
- if(tmp_hal_status == HAL_OK)
- {
+ if (tmp_hal_status == HAL_OK) {
/* Set a temporary handle of the ADC slave associated to the ADC master */
ADC_MULTI_SLAVE(hadc, &tmphadcSlave);
@@ -835,8 +737,7 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc)
tmp_hal_status = ADC_ConversionStop_Disable(&tmphadcSlave);
/* Check if ADC is effectively disabled */
- if(tmp_hal_status != HAL_OK)
- {
+ if (tmp_hal_status != HAL_OK) {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_INTERNAL);
@@ -848,127 +749,120 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc)
/* Disable ADC DMA mode */
CLEAR_BIT(hadc->Instance->CR2, ADC_CR2_DMA);
-
+
/* Reset configuration of ADC DMA continuous request for dual mode */
CLEAR_BIT(hadc->Instance->CR1, ADC_CR1_DUALMOD);
-
+
/* Disable the DMA channel (in case of DMA in circular mode or stop while */
/* while DMA transfer is on going) */
tmp_hal_status = HAL_DMA_Abort(hadc->DMA_Handle);
/* Change ADC state (ADC master) */
- ADC_STATE_CLR_SET(hadc->State,
- HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY,
- HAL_ADC_STATE_READY);
+ ADC_STATE_CLR_SET(hadc->State, HAL_ADC_STATE_REG_BUSY | HAL_ADC_STATE_INJ_BUSY, HAL_ADC_STATE_READY);
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */
/**
- * @brief Get ADC injected group conversion result.
- * @note Reading register JDRx automatically clears ADC flag JEOC
- * (ADC group injected end of unitary conversion).
- * @note This function does not clear ADC flag JEOS
- * (ADC group injected end of sequence conversion)
- * Occurrence of flag JEOS rising:
- * - If sequencer is composed of 1 rank, flag JEOS is equivalent
- * to flag JEOC.
- * - If sequencer is composed of several ranks, during the scan
- * sequence flag JEOC only is raised, at the end of the scan sequence
- * both flags JEOC and EOS are raised.
- * Flag JEOS must not be cleared by this function because
- * it would not be compliant with low power features
- * (feature low power auto-wait, not available on all STM32 families).
- * To clear this flag, either use function:
- * in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
- * model polling: @ref HAL_ADCEx_InjectedPollForConversion()
- * or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_JEOS).
- * @param hadc: ADC handle
- * @param InjectedRank: the converted ADC injected rank.
- * This parameter can be one of the following values:
- * @arg ADC_INJECTED_RANK_1: Injected Channel1 selected
- * @arg ADC_INJECTED_RANK_2: Injected Channel2 selected
- * @arg ADC_INJECTED_RANK_3: Injected Channel3 selected
- * @arg ADC_INJECTED_RANK_4: Injected Channel4 selected
- * @retval ADC group injected conversion data
- */
-uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank)
-{
+ * @brief Get ADC injected group conversion result.
+ * @note Reading register JDRx automatically clears ADC flag JEOC
+ * (ADC group injected end of unitary conversion).
+ * @note This function does not clear ADC flag JEOS
+ * (ADC group injected end of sequence conversion)
+ * Occurrence of flag JEOS rising:
+ * - If sequencer is composed of 1 rank, flag JEOS is equivalent
+ * to flag JEOC.
+ * - If sequencer is composed of several ranks, during the scan
+ * sequence flag JEOC only is raised, at the end of the scan sequence
+ * both flags JEOC and EOS are raised.
+ * Flag JEOS must not be cleared by this function because
+ * it would not be compliant with low power features
+ * (feature low power auto-wait, not available on all STM32 families).
+ * To clear this flag, either use function:
+ * in programming model IT: @ref HAL_ADC_IRQHandler(), in programming
+ * model polling: @ref HAL_ADCEx_InjectedPollForConversion()
+ * or @ref __HAL_ADC_CLEAR_FLAG(&hadc, ADC_FLAG_JEOS).
+ * @param hadc: ADC handle
+ * @param InjectedRank: the converted ADC injected rank.
+ * This parameter can be one of the following values:
+ * @arg ADC_INJECTED_RANK_1: Injected Channel1 selected
+ * @arg ADC_INJECTED_RANK_2: Injected Channel2 selected
+ * @arg ADC_INJECTED_RANK_3: Injected Channel3 selected
+ * @arg ADC_INJECTED_RANK_4: Injected Channel4 selected
+ * @retval ADC group injected conversion data
+ */
+uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef *hadc, uint32_t InjectedRank) {
uint32_t tmp_jdr = 0U;
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_INJECTED_RANK(InjectedRank));
-
- /* Get ADC converted value */
- switch(InjectedRank)
- {
- case ADC_INJECTED_RANK_4:
- tmp_jdr = hadc->Instance->JDR4;
- break;
- case ADC_INJECTED_RANK_3:
- tmp_jdr = hadc->Instance->JDR3;
- break;
- case ADC_INJECTED_RANK_2:
- tmp_jdr = hadc->Instance->JDR2;
- break;
- case ADC_INJECTED_RANK_1:
- default:
- tmp_jdr = hadc->Instance->JDR1;
- break;
+
+ /* Get ADC converted value */
+ switch (InjectedRank) {
+ case ADC_INJECTED_RANK_4:
+ tmp_jdr = hadc->Instance->JDR4;
+ break;
+ case ADC_INJECTED_RANK_3:
+ tmp_jdr = hadc->Instance->JDR3;
+ break;
+ case ADC_INJECTED_RANK_2:
+ tmp_jdr = hadc->Instance->JDR2;
+ break;
+ case ADC_INJECTED_RANK_1:
+ default:
+ tmp_jdr = hadc->Instance->JDR1;
+ break;
}
-
- /* Return ADC converted value */
+
+ /* Return ADC converted value */
return tmp_jdr;
}
-#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG)
+#if defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F105xC) || defined(STM32F107xC) || defined(STM32F103xE) || defined(STM32F103xG)
/**
- * @brief Returns the last ADC Master&Slave regular conversions results data
- * in the selected multi mode.
- * @param hadc: ADC handle of ADC master (handle of ADC slave must not be used)
- * @retval The converted data value.
- */
-uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc)
-{
+ * @brief Returns the last ADC Master&Slave regular conversions results data
+ * in the selected multi mode.
+ * @param hadc: ADC handle of ADC master (handle of ADC slave must not be used)
+ * @retval The converted data value.
+ */
+uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef *hadc) {
uint32_t tmpDR = 0U;
-
+
/* Check the parameters */
assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
-
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
/* Note: EOC flag is not cleared here by software because automatically */
/* cleared by hardware when reading register DR. */
-
+
/* On STM32F1 devices, ADC1 data register DR contains ADC2 conversions */
/* only if ADC1 DMA mode is enabled. */
tmpDR = hadc->Instance->DR;
- if (HAL_IS_BIT_CLR(ADC1->CR2, ADC_CR2_DMA))
- {
+ if (HAL_IS_BIT_CLR(ADC1->CR2, ADC_CR2_DMA)) {
tmpDR |= (ADC2->DR << 16U);
}
-
- /* Return ADC converted value */
+
+ /* Return ADC converted value */
return tmpDR;
}
#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */
/**
- * @brief Injected conversion complete callback in non blocking mode
- * @param hadc: ADC handle
- * @retval None
- */
-__weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc)
-{
+ * @brief Injected conversion complete callback in non blocking mode
+ * @param hadc: ADC handle
+ * @retval None
+ */
+__weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef *hadc) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hadc);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -977,16 +871,16 @@ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc)
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup ADCEx_Exported_Functions_Group2 Extended Peripheral Control functions
* @brief Extended Peripheral Control functions
*
-@verbatim
+@verbatim
===============================================================================
##### Peripheral Control functions #####
- ===============================================================================
+ ===============================================================================
[..] This section provides functions allowing to:
(+) Configure channels on injected group
(+) Configure multimode
@@ -996,24 +890,23 @@ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc)
*/
/**
- * @brief Configures the ADC injected group and the selected channel to be
- * linked to the injected group.
- * @note Possibility to update parameters on the fly:
- * This function initializes injected group, following calls to this
- * function can be used to reconfigure some parameters of structure
- * "ADC_InjectionConfTypeDef" on the fly, without reseting the ADC.
- * The setting of these parameters is conditioned to ADC state:
- * this function must be called when ADC is not under conversion.
- * @param hadc: ADC handle
- * @param sConfigInjected: Structure of ADC injected group and ADC channel for
- * injected group.
- * @retval None
- */
-HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_InjectionConfTypeDef* sConfigInjected)
-{
- HAL_StatusTypeDef tmp_hal_status = HAL_OK;
- __IO uint32_t wait_loop_index = 0U;
-
+ * @brief Configures the ADC injected group and the selected channel to be
+ * linked to the injected group.
+ * @note Possibility to update parameters on the fly:
+ * This function initializes injected group, following calls to this
+ * function can be used to reconfigure some parameters of structure
+ * "ADC_InjectionConfTypeDef" on the fly, without reseting the ADC.
+ * The setting of these parameters is conditioned to ADC state:
+ * this function must be called when ADC is not under conversion.
+ * @param hadc: ADC handle
+ * @param sConfigInjected: Structure of ADC injected group and ADC channel for
+ * injected group.
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef *hadc, ADC_InjectionConfTypeDef *sConfigInjected) {
+ HAL_StatusTypeDef tmp_hal_status = HAL_OK;
+ __IO uint32_t wait_loop_index = 0U;
+
/* Check the parameters */
assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));
assert_param(IS_ADC_CHANNEL(sConfigInjected->InjectedChannel));
@@ -1021,17 +914,16 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_I
assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->AutoInjectedConv));
assert_param(IS_ADC_EXTTRIGINJEC(sConfigInjected->ExternalTrigInjecConv));
assert_param(IS_ADC_RANGE(sConfigInjected->InjectedOffset));
-
- if(hadc->Init.ScanConvMode != ADC_SCAN_DISABLE)
- {
+
+ if (hadc->Init.ScanConvMode != ADC_SCAN_DISABLE) {
assert_param(IS_ADC_INJECTED_RANK(sConfigInjected->InjectedRank));
assert_param(IS_ADC_INJECTED_NB_CONV(sConfigInjected->InjectedNbrOfConversion));
assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->InjectedDiscontinuousConvMode));
}
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Configuration of injected group sequencer: */
/* - if scan mode is disabled, injected channels sequence length is set to */
/* 0x00: 1 channel converted (channel on regular rank 1) */
@@ -1041,66 +933,55 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_I
/* conversions is forced to 0x00 for alignment over all STM32 devices. */
/* - if scan mode is enabled, injected channels sequence length is set to */
/* parameter "InjectedNbrOfConversion". */
-// if (hadc->Init.ScanConvMode == ADC_SCAN_DISABLE)
-// {
-// if (sConfigInjected->InjectedRank == ADC_INJECTED_RANK_1)
-// {
-// /* Clear the old SQx bits for all injected ranks */
-// MODIFY_REG(hadc->Instance->JSQR ,
-// ADC_JSQR_JL |
-// ADC_JSQR_JSQ4 |
-// ADC_JSQR_JSQ3 |
-// ADC_JSQR_JSQ2 |
-// ADC_JSQR_JSQ1 ,
-// ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel,
-// ADC_INJECTED_RANK_1,
-// 0x01U));
-// }
-// /* If another injected rank than rank1 was intended to be set, and could */
-// /* not due to ScanConvMode disabled, error is reported. */
-// else
-// {
-// /* Update ADC state machine to error */
-// SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-//
-// tmp_hal_status = HAL_ERROR;
-// }
-// }
-// else
+ // if (hadc->Init.ScanConvMode == ADC_SCAN_DISABLE)
+ // {
+ // if (sConfigInjected->InjectedRank == ADC_INJECTED_RANK_1)
+ // {
+ // /* Clear the old SQx bits for all injected ranks */
+ // MODIFY_REG(hadc->Instance->JSQR ,
+ // ADC_JSQR_JL |
+ // ADC_JSQR_JSQ4 |
+ // ADC_JSQR_JSQ3 |
+ // ADC_JSQR_JSQ2 |
+ // ADC_JSQR_JSQ1 ,
+ // ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel,
+ // ADC_INJECTED_RANK_1,
+ // 0x01U));
+ // }
+ // /* If another injected rank than rank1 was intended to be set, and could */
+ // /* not due to ScanConvMode disabled, error is reported. */
+ // else
+ // {
+ // /* Update ADC state machine to error */
+ // SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
+ //
+ // tmp_hal_status = HAL_ERROR;
+ // }
+ // }
+ // else
{
/* Since injected channels rank conv. order depends on total number of */
/* injected conversions, selected rank must be below or equal to total */
/* number of injected conversions to be updated. */
- if (sConfigInjected->InjectedRank <= sConfigInjected->InjectedNbrOfConversion)
- {
+ if (sConfigInjected->InjectedRank <= sConfigInjected->InjectedNbrOfConversion) {
/* Clear the old SQx bits for the selected rank */
/* Set the SQx bits for the selected rank */
- MODIFY_REG(hadc->Instance->JSQR ,
-
- ADC_JSQR_JL |
- ADC_JSQR_RK_JL(ADC_JSQR_JSQ1,
- sConfigInjected->InjectedRank,
- sConfigInjected->InjectedNbrOfConversion) ,
-
- ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion) |
- ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel,
- sConfigInjected->InjectedRank,
- sConfigInjected->InjectedNbrOfConversion) );
- }
- else
- {
+ MODIFY_REG(hadc->Instance->JSQR,
+
+ ADC_JSQR_JL | ADC_JSQR_RK_JL(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion),
+
+ ADC_JSQR_JL_SHIFT(sConfigInjected->InjectedNbrOfConversion)
+ | ADC_JSQR_RK_JL(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion));
+ } else {
/* Clear the old SQx bits for the selected rank */
- MODIFY_REG(hadc->Instance->JSQR ,
-
- ADC_JSQR_JL |
- ADC_JSQR_RK_JL(ADC_JSQR_JSQ1,
- sConfigInjected->InjectedRank,
- sConfigInjected->InjectedNbrOfConversion) ,
-
+ MODIFY_REG(hadc->Instance->JSQR,
+
+ ADC_JSQR_JL | ADC_JSQR_RK_JL(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank, sConfigInjected->InjectedNbrOfConversion),
+
0x00000000U);
}
- }
-
+ }
+
/* Configuration of injected group */
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated only when ADC is disabled: */
@@ -1110,181 +991,140 @@ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_I
/* - Injected discontinuous mode */
/* Note: In case of ADC already enabled, caution to not launch an unwanted */
/* conversion while modifying register CR2 by writing 1 to bit ADON. */
- if (ADC_IS_ENABLE(hadc) == RESET)
- {
- MODIFY_REG(hadc->Instance->CR2 ,
- ADC_CR2_JEXTSEL |
- ADC_CR2_ADON ,
- ADC_CFGR_JEXTSEL(hadc, sConfigInjected->ExternalTrigInjecConv) );
+ if (ADC_IS_ENABLE(hadc) == RESET) {
+ MODIFY_REG(hadc->Instance->CR2, ADC_CR2_JEXTSEL | ADC_CR2_ADON, ADC_CFGR_JEXTSEL(hadc, sConfigInjected->ExternalTrigInjecConv));
}
-
-
+
/* Configuration of injected group */
/* - Automatic injected conversion */
/* - Injected discontinuous mode */
-
- /* Automatic injected conversion can be enabled if injected group */
- /* external triggers are disabled. */
- if (sConfigInjected->AutoInjectedConv == ENABLE)
- {
- if (sConfigInjected->ExternalTrigInjecConv == ADC_INJECTED_SOFTWARE_START)
- {
- SET_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO);
- }
- else
- {
- /* Update ADC state machine to error */
- SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
- tmp_hal_status = HAL_ERROR;
- }
- }
-
- /* Injected discontinuous can be enabled only if auto-injected mode is */
- /* disabled. */
- if (sConfigInjected->InjectedDiscontinuousConvMode == ENABLE)
- {
- if (sConfigInjected->AutoInjectedConv == DISABLE)
- {
- SET_BIT(hadc->Instance->CR1, ADC_CR1_JDISCEN);
- }
- else
- {
- /* Update ADC state machine to error */
- SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
- tmp_hal_status = HAL_ERROR;
- }
+
+ /* Automatic injected conversion can be enabled if injected group */
+ /* external triggers are disabled. */
+ if (sConfigInjected->AutoInjectedConv == ENABLE) {
+ if (sConfigInjected->ExternalTrigInjecConv == ADC_INJECTED_SOFTWARE_START) {
+ SET_BIT(hadc->Instance->CR1, ADC_CR1_JAUTO);
+ } else {
+ /* Update ADC state machine to error */
+ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
+
+ tmp_hal_status = HAL_ERROR;
}
+ }
+ /* Injected discontinuous can be enabled only if auto-injected mode is */
+ /* disabled. */
+ if (sConfigInjected->InjectedDiscontinuousConvMode == ENABLE) {
+ if (sConfigInjected->AutoInjectedConv == DISABLE) {
+ SET_BIT(hadc->Instance->CR1, ADC_CR1_JDISCEN);
+ } else {
+ /* Update ADC state machine to error */
+ SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
+
+ tmp_hal_status = HAL_ERROR;
+ }
+ }
/* InjectedChannel sampling time configuration */
/* For channels 10 to 17 */
- if (sConfigInjected->InjectedChannel >= ADC_CHANNEL_10)
- {
- MODIFY_REG(hadc->Instance->SMPR1 ,
- ADC_SMPR1(ADC_SMPR1_SMP10, sConfigInjected->InjectedChannel) ,
- ADC_SMPR1(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel) );
- }
- else /* For channels 0 to 9 */
+ if (sConfigInjected->InjectedChannel >= ADC_CHANNEL_10) {
+ MODIFY_REG(hadc->Instance->SMPR1, ADC_SMPR1(ADC_SMPR1_SMP10, sConfigInjected->InjectedChannel), ADC_SMPR1(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel));
+ } else /* For channels 0 to 9 */
{
- MODIFY_REG(hadc->Instance->SMPR2 ,
- ADC_SMPR2(ADC_SMPR2_SMP0, sConfigInjected->InjectedChannel) ,
- ADC_SMPR2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel) );
+ MODIFY_REG(hadc->Instance->SMPR2, ADC_SMPR2(ADC_SMPR2_SMP0, sConfigInjected->InjectedChannel), ADC_SMPR2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel));
}
-
+
/* If ADC1 InjectedChannel_16 or InjectedChannel_17 is selected, enable Temperature sensor */
/* and VREFINT measurement path. */
- if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR) ||
- (sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT) )
- {
+ if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR) || (sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT)) {
SET_BIT(hadc->Instance->CR2, ADC_CR2_TSVREFE);
}
-
-
+
/* Configure the offset: offset enable/disable, InjectedChannel, offset value */
- switch(sConfigInjected->InjectedRank)
- {
- case 1:
- /* Set injected channel 1 offset */
- MODIFY_REG(hadc->Instance->JOFR1,
- ADC_JOFR1_JOFFSET1,
- sConfigInjected->InjectedOffset);
- break;
- case 2:
- /* Set injected channel 2 offset */
- MODIFY_REG(hadc->Instance->JOFR2,
- ADC_JOFR2_JOFFSET2,
- sConfigInjected->InjectedOffset);
- break;
- case 3:
- /* Set injected channel 3 offset */
- MODIFY_REG(hadc->Instance->JOFR3,
- ADC_JOFR3_JOFFSET3,
- sConfigInjected->InjectedOffset);
- break;
- case 4:
- default:
- MODIFY_REG(hadc->Instance->JOFR4,
- ADC_JOFR4_JOFFSET4,
- sConfigInjected->InjectedOffset);
- break;
+ switch (sConfigInjected->InjectedRank) {
+ case 1:
+ /* Set injected channel 1 offset */
+ MODIFY_REG(hadc->Instance->JOFR1, ADC_JOFR1_JOFFSET1, sConfigInjected->InjectedOffset);
+ break;
+ case 2:
+ /* Set injected channel 2 offset */
+ MODIFY_REG(hadc->Instance->JOFR2, ADC_JOFR2_JOFFSET2, sConfigInjected->InjectedOffset);
+ break;
+ case 3:
+ /* Set injected channel 3 offset */
+ MODIFY_REG(hadc->Instance->JOFR3, ADC_JOFR3_JOFFSET3, sConfigInjected->InjectedOffset);
+ break;
+ case 4:
+ default:
+ MODIFY_REG(hadc->Instance->JOFR4, ADC_JOFR4_JOFFSET4, sConfigInjected->InjectedOffset);
+ break;
}
-
+
/* If ADC1 Channel_16 or Channel_17 is selected, enable Temperature sensor */
/* and VREFINT measurement path. */
- if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR) ||
- (sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT) )
- {
+ if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR) || (sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT)) {
/* For STM32F1 devices with several ADC: Only ADC1 can access internal */
/* measurement channels (VrefInt/TempSensor). If these channels are */
/* intended to be set on other ADC instances, an error is reported. */
- if (hadc->Instance == ADC1)
- {
- if (READ_BIT(hadc->Instance->CR2, ADC_CR2_TSVREFE) == RESET)
- {
+ if (hadc->Instance == ADC1) {
+ if (READ_BIT(hadc->Instance->CR2, ADC_CR2_TSVREFE) == RESET) {
SET_BIT(hadc->Instance->CR2, ADC_CR2_TSVREFE);
-
- if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR))
- {
+
+ if ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR)) {
/* Delay for temperature sensor stabilization time */
/* Compute number of CPU cycles to wait for */
wait_loop_index = (ADC_TEMPSENSOR_DELAY_US * (SystemCoreClock / 1000000U));
- while(wait_loop_index != 0U)
- {
+ while (wait_loop_index != 0U) {
wait_loop_index--;
}
}
}
- }
- else
- {
+ } else {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
+
tmp_hal_status = HAL_ERROR;
}
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
}
-#if defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F105xC) || defined (STM32F107xC) || defined (STM32F103xE) || defined (STM32F103xG)
+#if defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F105xC) || defined(STM32F107xC) || defined(STM32F103xE) || defined(STM32F103xG)
/**
- * @brief Enable ADC multimode and configure multimode parameters
- * @note Possibility to update parameters on the fly:
- * This function initializes multimode parameters, following
- * calls to this function can be used to reconfigure some parameters
- * of structure "ADC_MultiModeTypeDef" on the fly, without reseting
- * the ADCs (both ADCs of the common group).
- * The setting of these parameters is conditioned to ADC state.
- * For parameters constraints, see comments of structure
- * "ADC_MultiModeTypeDef".
- * @note To change back configuration from multimode to single mode, ADC must
- * be reset (using function HAL_ADC_Init() ).
- * @param hadc: ADC handle
- * @param multimode: Structure of ADC multimode configuration
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_MultiModeTypeDef* multimode)
-{
+ * @brief Enable ADC multimode and configure multimode parameters
+ * @note Possibility to update parameters on the fly:
+ * This function initializes multimode parameters, following
+ * calls to this function can be used to reconfigure some parameters
+ * of structure "ADC_MultiModeTypeDef" on the fly, without reseting
+ * the ADCs (both ADCs of the common group).
+ * The setting of these parameters is conditioned to ADC state.
+ * For parameters constraints, see comments of structure
+ * "ADC_MultiModeTypeDef".
+ * @note To change back configuration from multimode to single mode, ADC must
+ * be reset (using function HAL_ADC_Init() ).
+ * @param hadc: ADC handle
+ * @param multimode: Structure of ADC multimode configuration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef *hadc, ADC_MultiModeTypeDef *multimode) {
HAL_StatusTypeDef tmp_hal_status = HAL_OK;
ADC_HandleTypeDef tmphadcSlave;
-
+
/* Check the parameters */
assert_param(IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance));
assert_param(IS_ADC_MODE(multimode->Mode));
-
+
/* Process locked */
__HAL_LOCK(hadc);
-
+
/* Set a temporary handle of the ADC slave associated to the ADC master */
ADC_MULTI_SLAVE(hadc, &tmphadcSlave);
-
+
/* Parameters update conditioned to ADC state: */
/* Parameters that can be updated when ADC is disabled or enabled without */
/* conversion on going on regular group: */
@@ -1293,47 +1133,40 @@ HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_
/* - Multimode mode selection */
/* To optimize code, all multimode settings can be set when both ADCs of */
/* the common group are in state: disabled. */
- if ((ADC_IS_ENABLE(hadc) == RESET) &&
- (ADC_IS_ENABLE(&tmphadcSlave) == RESET) &&
- (IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance)) )
- {
- MODIFY_REG(hadc->Instance->CR1,
- ADC_CR1_DUALMOD ,
- multimode->Mode );
+ if ((ADC_IS_ENABLE(hadc) == RESET) && (ADC_IS_ENABLE(&tmphadcSlave) == RESET) && (IS_ADC_MULTIMODE_MASTER_INSTANCE(hadc->Instance))) {
+ MODIFY_REG(hadc->Instance->CR1, ADC_CR1_DUALMOD, multimode->Mode);
}
/* If one of the ADC sharing the same common group is enabled, no update */
/* could be done on neither of the multimode structure parameters. */
- else
- {
+ else {
/* Update ADC state machine to error */
SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);
-
+
tmp_hal_status = HAL_ERROR;
}
-
-
+
/* Process unlocked */
__HAL_UNLOCK(hadc);
-
+
/* Return function status */
return tmp_hal_status;
-}
+}
#endif /* defined STM32F103x6 || defined STM32F103xB || defined STM32F105xC || defined STM32F107xC || defined STM32F103xE || defined STM32F103xG */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_ADC_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c
index ba8bb631..e1f9b4e4 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_cortex.c
@@ -3,43 +3,43 @@
* @file stm32f1xx_hal_cortex.c
* @author MCD Application Team
* @brief CORTEX HAL module driver.
- * This file provides firmware functions to manage the following
+ * This file provides firmware functions to manage the following
* functionalities of the CORTEX:
* + Initialization and de-initialization functions
- * + Peripheral Control functions
+ * + Peripheral Control functions
*
- @verbatim
+ @verbatim
==============================================================================
##### How to use this driver #####
==============================================================================
- [..]
+ [..]
*** How to configure Interrupts using CORTEX HAL driver ***
===========================================================
- [..]
+ [..]
This section provides functions allowing to configure the NVIC interrupts (IRQ).
The Cortex-M3 exceptions are managed by CMSIS functions.
-
+
(#) Configure the NVIC Priority Grouping using HAL_NVIC_SetPriorityGrouping()
function according to the following table.
- (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority().
+ (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority().
(#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ().
- (#) please refer to programming manual for details in how to configure priority.
-
- -@- When the NVIC_PRIORITYGROUP_0 is selected, IRQ preemption is no more possible.
+ (#) please refer to programming manual for details in how to configure priority.
+
+ -@- When the NVIC_PRIORITYGROUP_0 is selected, IRQ preemption is no more possible.
The pending IRQ priority will be managed only by the sub priority.
-
+
-@- IRQ priority order (sorted by highest to lowest priority):
(+@) Lowest preemption priority
(+@) Lowest sub priority
(+@) Lowest hardware priority (IRQ number)
-
- [..]
+
+ [..]
*** How to configure Systick using CORTEX HAL driver ***
========================================================
[..]
Setup SysTick Timer for time base.
-
+
(+) The HAL_SYSTICK_Config()function calls the SysTick_Config() function which
is a CMSIS function that:
(++) Configures the SysTick Reload register with value passed as function parameter.
@@ -48,22 +48,22 @@
(++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK).
(++) Enables the SysTick Interrupt.
(++) Starts the SysTick Counter.
-
+
(+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro
__HAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the
HAL_SYSTICK_Config() function call. The __HAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined
inside the stm32f1xx_hal_cortex.h file.
(+) You can change the SysTick IRQ priority by calling the
- HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function
+ HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function
call. The HAL_NVIC_SetPriority() call the NVIC_SetPriority() function which is a CMSIS function.
(+) To adjust the SysTick time base, use the following formula:
-
+
Reload Value = SysTick Counter Clock (Hz) x Desired Time base (s)
(++) Reload Value is the parameter to be passed for HAL_SYSTICK_Config() function
(++) Reload Value should not exceed 0xFFFFFF
-
+
@endverbatim
******************************************************************************
* @attention
@@ -99,13 +99,13 @@
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup CORTEX CORTEX
- * @brief CORTEX HAL module driver
- * @{
- */
+ * @brief CORTEX HAL module driver
+ * @{
+ */
#ifdef HAL_CORTEX_MODULE_ENABLED
@@ -117,91 +117,86 @@
/* Exported functions --------------------------------------------------------*/
/** @defgroup CORTEX_Exported_Functions CORTEX Exported Functions
- * @{
- */
-
+ * @{
+ */
/** @defgroup CORTEX_Exported_Functions_Group1 Initialization and de-initialization functions
- * @brief Initialization and Configuration functions
+ * @brief Initialization and Configuration functions
*
-@verbatim
+@verbatim
==============================================================================
##### Initialization and de-initialization functions #####
==============================================================================
[..]
This section provides the CORTEX HAL driver functions allowing to configure Interrupts
- Systick functionalities
+ Systick functionalities
@endverbatim
* @{
*/
-
/**
- * @brief Sets the priority grouping field (preemption priority and subpriority)
- * using the required unlock sequence.
- * @param PriorityGroup: The priority grouping bits length.
- * This parameter can be one of the following values:
- * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority
- * 4 bits for subpriority
- * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority
- * 3 bits for subpriority
- * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority
- * 2 bits for subpriority
- * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority
- * 1 bits for subpriority
- * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority
- * 0 bits for subpriority
- * @note When the NVIC_PriorityGroup_0 is selected, IRQ preemption is no more possible.
- * The pending IRQ priority will be managed only by the subpriority.
- * @retval None
- */
-void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup)
-{
+ * @brief Sets the priority grouping field (preemption priority and subpriority)
+ * using the required unlock sequence.
+ * @param PriorityGroup: The priority grouping bits length.
+ * This parameter can be one of the following values:
+ * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority
+ * 4 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority
+ * 3 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority
+ * 2 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority
+ * 1 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority
+ * 0 bits for subpriority
+ * @note When the NVIC_PriorityGroup_0 is selected, IRQ preemption is no more possible.
+ * The pending IRQ priority will be managed only by the subpriority.
+ * @retval None
+ */
+void HAL_NVIC_SetPriorityGrouping(uint32_t PriorityGroup) {
/* Check the parameters */
assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup));
-
+
/* Set the PRIGROUP[10:8] bits according to the PriorityGroup parameter value */
NVIC_SetPriorityGrouping(PriorityGroup);
}
/**
- * @brief Sets the priority of an interrupt.
- * @param IRQn: External interrupt number.
- * This parameter can be an enumerator of IRQn_Type enumeration
- * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xx.h))
- * @param PreemptPriority: The preemption priority for the IRQn channel.
- * This parameter can be a value between 0 and 15
- * A lower priority value indicates a higher priority
- * @param SubPriority: the subpriority level for the IRQ channel.
- * This parameter can be a value between 0 and 15
- * A lower priority value indicates a higher priority.
- * @retval None
- */
-void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority)
-{
+ * @brief Sets the priority of an interrupt.
+ * @param IRQn: External interrupt number.
+ * This parameter can be an enumerator of IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xx.h))
+ * @param PreemptPriority: The preemption priority for the IRQn channel.
+ * This parameter can be a value between 0 and 15
+ * A lower priority value indicates a higher priority
+ * @param SubPriority: the subpriority level for the IRQ channel.
+ * This parameter can be a value between 0 and 15
+ * A lower priority value indicates a higher priority.
+ * @retval None
+ */
+void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) {
uint32_t prioritygroup = 0x00U;
-
+
/* Check the parameters */
assert_param(IS_NVIC_SUB_PRIORITY(SubPriority));
assert_param(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority));
-
+
prioritygroup = NVIC_GetPriorityGrouping();
-
+
NVIC_SetPriority(IRQn, NVIC_EncodePriority(prioritygroup, PreemptPriority, SubPriority));
}
/**
- * @brief Enables a device specific interrupt in the NVIC interrupt controller.
- * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig()
- * function should be called before.
- * @param IRQn External interrupt number.
- * This parameter can be an enumerator of IRQn_Type enumeration
- * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
- * @retval None
- */
-void HAL_NVIC_EnableIRQ(IRQn_Type IRQn)
-{
+ * @brief Enables a device specific interrupt in the NVIC interrupt controller.
+ * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig()
+ * function should be called before.
+ * @param IRQn External interrupt number.
+ * This parameter can be an enumerator of IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
+ * @retval None
+ */
+void HAL_NVIC_EnableIRQ(IRQn_Type IRQn) {
/* Check the parameters */
assert_param(IS_NVIC_DEVICE_IRQ(IRQn));
@@ -210,14 +205,13 @@ void HAL_NVIC_EnableIRQ(IRQn_Type IRQn)
}
/**
- * @brief Disables a device specific interrupt in the NVIC interrupt controller.
- * @param IRQn External interrupt number.
- * This parameter can be an enumerator of IRQn_Type enumeration
- * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
- * @retval None
- */
-void HAL_NVIC_DisableIRQ(IRQn_Type IRQn)
-{
+ * @brief Disables a device specific interrupt in the NVIC interrupt controller.
+ * @param IRQn External interrupt number.
+ * This parameter can be an enumerator of IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
+ * @retval None
+ */
+void HAL_NVIC_DisableIRQ(IRQn_Type IRQn) {
/* Check the parameters */
assert_param(IS_NVIC_DEVICE_IRQ(IRQn));
@@ -226,95 +220,88 @@ void HAL_NVIC_DisableIRQ(IRQn_Type IRQn)
}
/**
- * @brief Initiates a system reset request to reset the MCU.
- * @retval None
- */
-void HAL_NVIC_SystemReset(void)
-{
+ * @brief Initiates a system reset request to reset the MCU.
+ * @retval None
+ */
+void HAL_NVIC_SystemReset(void) {
/* System Reset */
NVIC_SystemReset();
}
/**
- * @brief Initializes the System Timer and its interrupt, and starts the System Tick Timer.
- * Counter is in free running mode to generate periodic interrupts.
- * @param TicksNumb: Specifies the ticks Number of ticks between two interrupts.
- * @retval status: - 0 Function succeeded.
- * - 1 Function failed.
- */
-uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb)
-{
- return SysTick_Config(TicksNumb);
-}
+ * @brief Initializes the System Timer and its interrupt, and starts the System Tick Timer.
+ * Counter is in free running mode to generate periodic interrupts.
+ * @param TicksNumb: Specifies the ticks Number of ticks between two interrupts.
+ * @retval status: - 0 Function succeeded.
+ * - 1 Function failed.
+ */
+uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb) { return SysTick_Config(TicksNumb); }
/**
- * @}
- */
+ * @}
+ */
/** @defgroup CORTEX_Exported_Functions_Group2 Peripheral Control functions
- * @brief Cortex control functions
+ * @brief Cortex control functions
*
-@verbatim
+@verbatim
==============================================================================
##### Peripheral Control functions #####
==============================================================================
[..]
This subsection provides a set of functions allowing to control the CORTEX
- (NVIC, SYSTICK, MPU) functionalities.
-
-
+ (NVIC, SYSTICK, MPU) functionalities.
+
+
@endverbatim
* @{
*/
#if (__MPU_PRESENT == 1U)
/**
- * @brief Disables the MPU
- * @retval None
- */
-void HAL_MPU_Disable(void)
-{
+ * @brief Disables the MPU
+ * @retval None
+ */
+void HAL_MPU_Disable(void) {
/* Make sure outstanding transfers are done */
__DMB();
/* Disable fault exceptions */
SCB->SHCSR &= ~SCB_SHCSR_MEMFAULTENA_Msk;
-
+
/* Disable the MPU and clear the control register*/
MPU->CTRL = 0U;
}
/**
- * @brief Enable the MPU.
- * @param MPU_Control: Specifies the control mode of the MPU during hard fault,
- * NMI, FAULTMASK and privileged access to the default memory
- * This parameter can be one of the following values:
- * @arg MPU_HFNMI_PRIVDEF_NONE
- * @arg MPU_HARDFAULT_NMI
- * @arg MPU_PRIVILEGED_DEFAULT
- * @arg MPU_HFNMI_PRIVDEF
- * @retval None
- */
-void HAL_MPU_Enable(uint32_t MPU_Control)
-{
+ * @brief Enable the MPU.
+ * @param MPU_Control: Specifies the control mode of the MPU during hard fault,
+ * NMI, FAULTMASK and privileged access to the default memory
+ * This parameter can be one of the following values:
+ * @arg MPU_HFNMI_PRIVDEF_NONE
+ * @arg MPU_HARDFAULT_NMI
+ * @arg MPU_PRIVILEGED_DEFAULT
+ * @arg MPU_HFNMI_PRIVDEF
+ * @retval None
+ */
+void HAL_MPU_Enable(uint32_t MPU_Control) {
/* Enable the MPU */
MPU->CTRL = MPU_Control | MPU_CTRL_ENABLE_Msk;
-
+
/* Enable fault exceptions */
SCB->SHCSR |= SCB_SHCSR_MEMFAULTENA_Msk;
-
+
/* Ensure MPU setting take effects */
__DSB();
__ISB();
}
/**
- * @brief Initializes and configures the Region and the memory to be protected.
- * @param MPU_Init: Pointer to a MPU_Region_InitTypeDef structure that contains
- * the initialization and configuration information.
- * @retval None
- */
-void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init)
-{
+ * @brief Initializes and configures the Region and the memory to be protected.
+ * @param MPU_Init: Pointer to a MPU_Region_InitTypeDef structure that contains
+ * the initialization and configuration information.
+ * @retval None
+ */
+void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init) {
/* Check the parameters */
assert_param(IS_MPU_REGION_NUMBER(MPU_Init->Number));
assert_param(IS_MPU_REGION_ENABLE(MPU_Init->Enable));
@@ -322,8 +309,7 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init)
/* Set the Region number */
MPU->RNR = MPU_Init->Number;
- if ((MPU_Init->Enable) != RESET)
- {
+ if ((MPU_Init->Enable) != RESET) {
/* Check the parameters */
assert_param(IS_MPU_INSTRUCTION_ACCESS(MPU_Init->DisableExec));
assert_param(IS_MPU_REGION_PERMISSION_ATTRIBUTE(MPU_Init->AccessPermission));
@@ -333,20 +319,12 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init)
assert_param(IS_MPU_ACCESS_BUFFERABLE(MPU_Init->IsBufferable));
assert_param(IS_MPU_SUB_REGION_DISABLE(MPU_Init->SubRegionDisable));
assert_param(IS_MPU_REGION_SIZE(MPU_Init->Size));
-
+
MPU->RBAR = MPU_Init->BaseAddress;
- MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) |
- ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) |
- ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos) |
- ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) |
- ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) |
- ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos) |
- ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) |
- ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) |
- ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos);
- }
- else
- {
+ MPU->RASR = ((uint32_t)MPU_Init->DisableExec << MPU_RASR_XN_Pos) | ((uint32_t)MPU_Init->AccessPermission << MPU_RASR_AP_Pos) | ((uint32_t)MPU_Init->TypeExtField << MPU_RASR_TEX_Pos)
+ | ((uint32_t)MPU_Init->IsShareable << MPU_RASR_S_Pos) | ((uint32_t)MPU_Init->IsCacheable << MPU_RASR_C_Pos) | ((uint32_t)MPU_Init->IsBufferable << MPU_RASR_B_Pos)
+ | ((uint32_t)MPU_Init->SubRegionDisable << MPU_RASR_SRD_Pos) | ((uint32_t)MPU_Init->Size << MPU_RASR_SIZE_Pos) | ((uint32_t)MPU_Init->Enable << MPU_RASR_ENABLE_Pos);
+ } else {
MPU->RBAR = 0x00U;
MPU->RASR = 0x00U;
}
@@ -354,71 +332,67 @@ void HAL_MPU_ConfigRegion(MPU_Region_InitTypeDef *MPU_Init)
#endif /* __MPU_PRESENT */
/**
- * @brief Gets the priority grouping field from the NVIC Interrupt Controller.
- * @retval Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field)
- */
-uint32_t HAL_NVIC_GetPriorityGrouping(void)
-{
+ * @brief Gets the priority grouping field from the NVIC Interrupt Controller.
+ * @retval Priority grouping field (SCB->AIRCR [10:8] PRIGROUP field)
+ */
+uint32_t HAL_NVIC_GetPriorityGrouping(void) {
/* Get the PRIGROUP[10:8] field value */
return NVIC_GetPriorityGrouping();
}
/**
- * @brief Gets the priority of an interrupt.
- * @param IRQn: External interrupt number.
- * This parameter can be an enumerator of IRQn_Type enumeration
- * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
- * @param PriorityGroup: the priority grouping bits length.
- * This parameter can be one of the following values:
- * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority
- * 4 bits for subpriority
- * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority
- * 3 bits for subpriority
- * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority
- * 2 bits for subpriority
- * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority
- * 1 bits for subpriority
- * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority
- * 0 bits for subpriority
- * @param pPreemptPriority: Pointer on the Preemptive priority value (starting from 0).
- * @param pSubPriority: Pointer on the Subpriority value (starting from 0).
- * @retval None
- */
-void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t *pPreemptPriority, uint32_t *pSubPriority)
-{
+ * @brief Gets the priority of an interrupt.
+ * @param IRQn: External interrupt number.
+ * This parameter can be an enumerator of IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
+ * @param PriorityGroup: the priority grouping bits length.
+ * This parameter can be one of the following values:
+ * @arg NVIC_PRIORITYGROUP_0: 0 bits for preemption priority
+ * 4 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_1: 1 bits for preemption priority
+ * 3 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_2: 2 bits for preemption priority
+ * 2 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_3: 3 bits for preemption priority
+ * 1 bits for subpriority
+ * @arg NVIC_PRIORITYGROUP_4: 4 bits for preemption priority
+ * 0 bits for subpriority
+ * @param pPreemptPriority: Pointer on the Preemptive priority value (starting from 0).
+ * @param pSubPriority: Pointer on the Subpriority value (starting from 0).
+ * @retval None
+ */
+void HAL_NVIC_GetPriority(IRQn_Type IRQn, uint32_t PriorityGroup, uint32_t *pPreemptPriority, uint32_t *pSubPriority) {
/* Check the parameters */
assert_param(IS_NVIC_PRIORITY_GROUP(PriorityGroup));
- /* Get priority for Cortex-M system or device specific interrupts */
+ /* Get priority for Cortex-M system or device specific interrupts */
NVIC_DecodePriority(NVIC_GetPriority(IRQn), PriorityGroup, pPreemptPriority, pSubPriority);
}
/**
- * @brief Sets Pending bit of an external interrupt.
- * @param IRQn External interrupt number
- * This parameter can be an enumerator of IRQn_Type enumeration
- * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
- * @retval None
- */
-void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn)
-{
+ * @brief Sets Pending bit of an external interrupt.
+ * @param IRQn External interrupt number
+ * This parameter can be an enumerator of IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
+ * @retval None
+ */
+void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn) {
/* Check the parameters */
assert_param(IS_NVIC_DEVICE_IRQ(IRQn));
-
+
/* Set interrupt pending */
NVIC_SetPendingIRQ(IRQn);
}
/**
- * @brief Gets Pending Interrupt (reads the pending register in the NVIC
- * and returns the pending bit for the specified interrupt).
- * @param IRQn External interrupt number.
- * This parameter can be an enumerator of IRQn_Type enumeration
- * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
- * @retval status: - 0 Interrupt status is not pending.
- * - 1 Interrupt status is pending.
- */
-uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn)
-{
+ * @brief Gets Pending Interrupt (reads the pending register in the NVIC
+ * and returns the pending bit for the specified interrupt).
+ * @param IRQn External interrupt number.
+ * This parameter can be an enumerator of IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
+ * @retval status: - 0 Interrupt status is not pending.
+ * - 1 Interrupt status is pending.
+ */
+uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn) {
/* Check the parameters */
assert_param(IS_NVIC_DEVICE_IRQ(IRQn));
@@ -427,14 +401,13 @@ uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn)
}
/**
- * @brief Clears the pending bit of an external interrupt.
- * @param IRQn External interrupt number.
- * This parameter can be an enumerator of IRQn_Type enumeration
- * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
- * @retval None
- */
-void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn)
-{
+ * @brief Clears the pending bit of an external interrupt.
+ * @param IRQn External interrupt number.
+ * This parameter can be an enumerator of IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
+ * @retval None
+ */
+void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn) {
/* Check the parameters */
assert_param(IS_NVIC_DEVICE_IRQ(IRQn));
@@ -443,15 +416,14 @@ void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn)
}
/**
- * @brief Gets active interrupt ( reads the active register in NVIC and returns the active bit).
- * @param IRQn External interrupt number
- * This parameter can be an enumerator of IRQn_Type enumeration
- * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
- * @retval status: - 0 Interrupt status is not pending.
- * - 1 Interrupt status is pending.
- */
-uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn)
-{
+ * @brief Gets active interrupt ( reads the active register in NVIC and returns the active bit).
+ * @param IRQn External interrupt number
+ * This parameter can be an enumerator of IRQn_Type enumeration
+ * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f10xxx.h))
+ * @retval status: - 0 Interrupt status is not pending.
+ * - 1 Interrupt status is pending.
+ */
+uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn) {
/* Check the parameters */
assert_param(IS_NVIC_DEVICE_IRQ(IRQn));
@@ -460,62 +432,54 @@ uint32_t HAL_NVIC_GetActive(IRQn_Type IRQn)
}
/**
- * @brief Configures the SysTick clock source.
- * @param CLKSource: specifies the SysTick clock source.
- * This parameter can be one of the following values:
- * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source.
- * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source.
- * @retval None
- */
-void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource)
-{
+ * @brief Configures the SysTick clock source.
+ * @param CLKSource: specifies the SysTick clock source.
+ * This parameter can be one of the following values:
+ * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source.
+ * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source.
+ * @retval None
+ */
+void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource) {
/* Check the parameters */
assert_param(IS_SYSTICK_CLK_SOURCE(CLKSource));
- if (CLKSource == SYSTICK_CLKSOURCE_HCLK)
- {
+ if (CLKSource == SYSTICK_CLKSOURCE_HCLK) {
SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK;
- }
- else
- {
+ } else {
SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK;
}
}
/**
- * @brief This function handles SYSTICK interrupt request.
- * @retval None
- */
-void HAL_SYSTICK_IRQHandler(void)
-{
- HAL_SYSTICK_Callback();
-}
+ * @brief This function handles SYSTICK interrupt request.
+ * @retval None
+ */
+void HAL_SYSTICK_IRQHandler(void) { HAL_SYSTICK_Callback(); }
/**
- * @brief SYSTICK callback.
- * @retval None
- */
-__weak void HAL_SYSTICK_Callback(void)
-{
+ * @brief SYSTICK callback.
+ * @retval None
+ */
+__weak void HAL_SYSTICK_Callback(void) {
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_SYSTICK_Callback could be implemented in the user file
*/
}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_CORTEX_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c
index d3989c2e..c12ba6a6 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_dma.c
@@ -14,7 +14,7 @@
==============================================================================
[..]
(#) Enable and configure the peripheral to be connected to the DMA Channel
- (except for internal SRAM / FLASH memories: no initialization is
+ (except for internal SRAM / FLASH memories: no initialization is
necessary). Please refer to the Reference manual for connection between peripherals
and DMA requests.
@@ -23,11 +23,11 @@
Circular or Normal mode, Channel Priority level, Source and Destination Increment mode
using HAL_DMA_Init() function.
- (#) Use HAL_DMA_GetState() function to return the DMA state and HAL_DMA_GetError() in case of error
+ (#) Use HAL_DMA_GetState() function to return the DMA state and HAL_DMA_GetError() in case of error
detection.
-
+
(#) Use HAL_DMA_Abort() function to abort the current transfer
-
+
-@- In Memory-to-Memory transfer mode, Circular mode is not allowed.
*** Polling mode IO operation ***
=================================
@@ -51,7 +51,7 @@
XferErrorCallback (i.e. a member of DMA handle structure).
*** DMA HAL driver macros list ***
- =============================================
+ =============================================
[..]
Below the list of most used macros in DMA HAL driver.
@@ -61,10 +61,10 @@
(+) __HAL_DMA_CLEAR_FLAG: Clear the DMA Channel pending flags.
(+) __HAL_DMA_ENABLE_IT: Enable the specified DMA Channel interrupts.
(+) __HAL_DMA_DISABLE_IT: Disable the specified DMA Channel interrupts.
- (+) __HAL_DMA_GET_IT_SOURCE: Check whether the specified DMA Channel interrupt has occurred or not.
+ (+) __HAL_DMA_GET_IT_SOURCE: Check whether the specified DMA Channel interrupt has occurred or not.
- [..]
- (@) You can refer to the DMA HAL driver header file for more useful macros
+ [..]
+ (@) You can refer to the DMA HAL driver header file for more useful macros
@endverbatim
******************************************************************************
@@ -101,13 +101,13 @@
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup DMA DMA
- * @brief DMA HAL module driver
- * @{
- */
+ * @brief DMA HAL module driver
+ * @{
+ */
#ifdef HAL_DMA_MODULE_ENABLED
@@ -117,21 +117,21 @@
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup DMA_Private_Functions DMA Private Functions
- * @{
- */
+ * @{
+ */
static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength);
/**
- * @}
- */
+ * @}
+ */
/* Exported functions ---------------------------------------------------------*/
/** @defgroup DMA_Exported_Functions DMA Exported Functions
- * @{
- */
+ * @{
+ */
/** @defgroup DMA_Exported_Functions_Group1 Initialization and de-initialization functions
- * @brief Initialization and de-initialization functions
+ * @brief Initialization and de-initialization functions
*
@verbatim
===============================================================================
@@ -139,30 +139,28 @@ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t
===============================================================================
[..]
This section provides functions allowing to initialize the DMA Channel source
- and destination addresses, incrementation and data sizes, transfer direction,
+ and destination addresses, incrementation and data sizes, transfer direction,
circular/normal mode selection, memory-to-memory mode selection and Channel priority value.
[..]
The HAL_DMA_Init() function follows the DMA configuration procedures as described in
- reference manual.
+ reference manual.
@endverbatim
* @{
*/
/**
- * @brief Initialize the DMA according to the specified
- * parameters in the DMA_InitTypeDef and initialize the associated handle.
- * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma)
-{
+ * @brief Initialize the DMA according to the specified
+ * parameters in the DMA_InitTypeDef and initialize the associated handle.
+ * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) {
uint32_t tmp = 0U;
/* Check the DMA handle allocation */
- if(hdma == NULL)
- {
+ if (hdma == NULL) {
return HAL_ERROR;
}
@@ -176,23 +174,20 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma)
assert_param(IS_DMA_MODE(hdma->Init.Mode));
assert_param(IS_DMA_PRIORITY(hdma->Init.Priority));
-#if defined (STM32F101xE) || defined (STM32F101xG) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F100xE) || defined (STM32F105xC) || defined (STM32F107xC)
+#if defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F100xE) || defined(STM32F105xC) || defined(STM32F107xC)
/* calculation of the channel index */
- if ((uint32_t)(hdma->Instance) < (uint32_t)(DMA2_Channel1))
- {
+ if ((uint32_t)(hdma->Instance) < (uint32_t)(DMA2_Channel1)) {
/* DMA1 */
- hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2;
+ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2;
hdma->DmaBaseAddress = DMA1;
- }
- else
- {
+ } else {
/* DMA2 */
- hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA2_Channel1) / ((uint32_t)DMA2_Channel2 - (uint32_t)DMA2_Channel1)) << 2;
+ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA2_Channel1) / ((uint32_t)DMA2_Channel2 - (uint32_t)DMA2_Channel1)) << 2;
hdma->DmaBaseAddress = DMA2;
}
#else
/* DMA1 */
- hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2;
+ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2;
hdma->DmaBaseAddress = DMA1;
#endif /* STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG || STM32F100xE || STM32F105xC || STM32F107xC */
@@ -203,15 +198,10 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma)
tmp = hdma->Instance->CCR;
/* Clear PL, MSIZE, PSIZE, MINC, PINC, CIRC and DIR bits */
- tmp &= ((uint32_t)~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | \
- DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | \
- DMA_CCR_DIR));
+ tmp &= ((uint32_t) ~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | DMA_CCR_DIR));
/* Prepare the DMA Channel configuration */
- tmp |= hdma->Init.Direction |
- hdma->Init.PeriphInc | hdma->Init.MemInc |
- hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment |
- hdma->Init.Mode | hdma->Init.Priority;
+ tmp |= hdma->Init.Direction | hdma->Init.PeriphInc | hdma->Init.MemInc | hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment | hdma->Init.Mode | hdma->Init.Priority;
/* Write to DMA Channel CR register */
hdma->Instance->CCR = tmp;
@@ -228,16 +218,14 @@ HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma)
}
/**
- * @brief DeInitialize the DMA peripheral.
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma)
-{
+ * @brief DeInitialize the DMA peripheral.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma) {
/* Check the DMA handle allocation */
- if(hdma == NULL)
- {
+ if (hdma == NULL) {
return HAL_ERROR;
}
@@ -248,34 +236,31 @@ HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma)
__HAL_DMA_DISABLE(hdma);
/* Reset DMA Channel control register */
- hdma->Instance->CCR = 0U;
+ hdma->Instance->CCR = 0U;
/* Reset DMA Channel Number of Data to Transfer register */
hdma->Instance->CNDTR = 0U;
/* Reset DMA Channel peripheral address register */
- hdma->Instance->CPAR = 0U;
+ hdma->Instance->CPAR = 0U;
/* Reset DMA Channel memory address register */
hdma->Instance->CMAR = 0U;
-#if defined (STM32F101xE) || defined (STM32F101xG) || defined (STM32F103xE) || defined (STM32F103xG) || defined (STM32F100xE) || defined (STM32F105xC) || defined (STM32F107xC)
+#if defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F100xE) || defined(STM32F105xC) || defined(STM32F107xC)
/* calculation of the channel index */
- if ((uint32_t)(hdma->Instance) < (uint32_t)(DMA2_Channel1))
- {
+ if ((uint32_t)(hdma->Instance) < (uint32_t)(DMA2_Channel1)) {
/* DMA1 */
- hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2;
+ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2;
hdma->DmaBaseAddress = DMA1;
- }
- else
- {
+ } else {
/* DMA2 */
- hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA2_Channel1) / ((uint32_t)DMA2_Channel2 - (uint32_t)DMA2_Channel1)) << 2;
+ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA2_Channel1) / ((uint32_t)DMA2_Channel2 - (uint32_t)DMA2_Channel1)) << 2;
hdma->DmaBaseAddress = DMA2;
}
#else
/* DMA1 */
- hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2;
+ hdma->ChannelIndex = (((uint32_t)hdma->Instance - (uint32_t)DMA1_Channel1) / ((uint32_t)DMA1_Channel2 - (uint32_t)DMA1_Channel1)) << 2;
hdma->DmaBaseAddress = DMA1;
#endif /* STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG || STM32F100xE || STM32F105xC || STM32F107xC */
@@ -283,10 +268,10 @@ HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma)
hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << (hdma->ChannelIndex));
/* Clean all callbacks */
- hdma->XferCpltCallback = NULL;
+ hdma->XferCpltCallback = NULL;
hdma->XferHalfCpltCallback = NULL;
- hdma->XferErrorCallback = NULL;
- hdma->XferAbortCallback = NULL;
+ hdma->XferErrorCallback = NULL;
+ hdma->XferAbortCallback = NULL;
/* Reset the error code */
hdma->ErrorCode = HAL_DMA_ERROR_NONE;
@@ -301,8 +286,8 @@ HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma)
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup DMA_Exported_Functions_Group2 Input and Output operation functions
* @brief Input and Output operation functions
@@ -324,16 +309,15 @@ HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma)
*/
/**
- * @brief Start the DMA Transfer.
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @param SrcAddress: The source memory Buffer address
- * @param DstAddress: The destination memory Buffer address
- * @param DataLength: The length of data to be transferred from source to destination
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
-{
+ * @brief Start the DMA Transfer.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @param SrcAddress: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param DataLength: The length of data to be transferred from source to destination
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) {
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
@@ -342,41 +326,37 @@ HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, ui
/* Process locked */
__HAL_LOCK(hdma);
- if(HAL_DMA_STATE_READY == hdma->State)
- {
+ if (HAL_DMA_STATE_READY == hdma->State) {
/* Change DMA peripheral state */
- hdma->State = HAL_DMA_STATE_BUSY;
+ hdma->State = HAL_DMA_STATE_BUSY;
hdma->ErrorCode = HAL_DMA_ERROR_NONE;
-
+
/* Disable the peripheral */
__HAL_DMA_DISABLE(hdma);
-
+
/* Configure the source, destination address and the data length & clear flags*/
DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength);
-
+
/* Enable the Peripheral */
__HAL_DMA_ENABLE(hdma);
+ } else {
+ /* Process Unlocked */
+ __HAL_UNLOCK(hdma);
+ status = HAL_BUSY;
}
- else
- {
- /* Process Unlocked */
- __HAL_UNLOCK(hdma);
- status = HAL_BUSY;
- }
return status;
}
/**
- * @brief Start the DMA Transfer with interrupt enabled.
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @param SrcAddress: The source memory Buffer address
- * @param DstAddress: The destination memory Buffer address
- * @param DataLength: The length of data to be transferred from source to destination
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
-{
+ * @brief Start the DMA Transfer with interrupt enabled.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @param SrcAddress: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param DataLength: The length of data to be transferred from source to destination
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) {
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
@@ -384,61 +364,54 @@ HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress,
/* Process locked */
__HAL_LOCK(hdma);
-
- if(HAL_DMA_STATE_READY == hdma->State)
- {
+
+ if (HAL_DMA_STATE_READY == hdma->State) {
/* Change DMA peripheral state */
- hdma->State = HAL_DMA_STATE_BUSY;
+ hdma->State = HAL_DMA_STATE_BUSY;
hdma->ErrorCode = HAL_DMA_ERROR_NONE;
-
+
/* Disable the peripheral */
__HAL_DMA_DISABLE(hdma);
-
+
/* Configure the source, destination address and the data length & clear flags*/
DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength);
-
+
/* Enable the transfer complete interrupt */
/* Enable the transfer Error interrupt */
- if(NULL != hdma->XferHalfCpltCallback)
- {
+ if (NULL != hdma->XferHalfCpltCallback) {
/* Enable the Half transfer complete interrupt as well */
__HAL_DMA_ENABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE));
- }
- else
- {
+ } else {
__HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT);
__HAL_DMA_ENABLE_IT(hdma, (DMA_IT_TC | DMA_IT_TE));
}
/* Enable the Peripheral */
__HAL_DMA_ENABLE(hdma);
- }
- else
- {
+ } else {
/* Process Unlocked */
- __HAL_UNLOCK(hdma);
+ __HAL_UNLOCK(hdma);
/* Remain BUSY */
status = HAL_BUSY;
- }
+ }
return status;
}
/**
- * @brief Abort the DMA Transfer.
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma)
-{
+ * @brief Abort the DMA Transfer.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma) {
HAL_StatusTypeDef status = HAL_OK;
/* Disable DMA IT */
__HAL_DMA_DISABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE));
-
+
/* Disable the channel */
__HAL_DMA_DISABLE(hdma);
-
+
/* Clear all flags */
hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << hdma->ChannelIndex);
@@ -446,30 +419,26 @@ HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma)
hdma->State = HAL_DMA_STATE_READY;
/* Process Unlocked */
- __HAL_UNLOCK(hdma);
-
- return status;
+ __HAL_UNLOCK(hdma);
+
+ return status;
}
/**
- * @brief Aborts the DMA Transfer in Interrupt mode.
- * @param hdma : pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma)
-{
+ * @brief Aborts the DMA Transfer in Interrupt mode.
+ * @param hdma : pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma) {
HAL_StatusTypeDef status = HAL_OK;
-
- if(HAL_DMA_STATE_BUSY != hdma->State)
- {
+
+ if (HAL_DMA_STATE_BUSY != hdma->State) {
/* no transfer ongoing */
hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER;
-
+
status = HAL_ERROR;
- }
- else
- {
+ } else {
/* Disable DMA IT */
__HAL_DMA_DISABLE_IT(hdma, (DMA_IT_TC | DMA_IT_HT | DMA_IT_TE));
@@ -486,29 +455,26 @@ HAL_StatusTypeDef HAL_DMA_Abort_IT(DMA_HandleTypeDef *hdma)
__HAL_UNLOCK(hdma);
/* Call User Abort callback */
- if(hdma->XferAbortCallback != NULL)
- {
+ if (hdma->XferAbortCallback != NULL) {
hdma->XferAbortCallback(hdma);
- }
+ }
}
return status;
}
/**
- * @brief Polling for transfer complete.
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @param CompleteLevel: Specifies the DMA level complete.
- * @param Timeout: Timeout duration.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout)
-{
+ * @brief Polling for transfer complete.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @param CompleteLevel: Specifies the DMA level complete.
+ * @param Timeout: Timeout duration.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout) {
uint32_t temp;
uint32_t tickstart = 0U;
- if(HAL_DMA_STATE_BUSY != hdma->State)
- {
+ if (HAL_DMA_STATE_BUSY != hdma->State) {
/* no transfer ongoing */
hdma->ErrorCode = HAL_DMA_ERROR_NO_XFER;
__HAL_UNLOCK(hdma);
@@ -516,20 +482,16 @@ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t Comp
}
/* Polling mode not supported in circular mode */
- if (RESET != (hdma->Instance->CCR & DMA_CCR_CIRC))
- {
+ if (RESET != (hdma->Instance->CCR & DMA_CCR_CIRC)) {
hdma->ErrorCode = HAL_DMA_ERROR_NOT_SUPPORTED;
return HAL_ERROR;
}
-
+
/* Get the level transfer complete flag */
- if(CompleteLevel == HAL_DMA_FULL_TRANSFER)
- {
+ if (CompleteLevel == HAL_DMA_FULL_TRANSFER) {
/* Transfer Complete flag */
temp = __HAL_DMA_GET_TC_FLAG_INDEX(hdma);
- }
- else
- {
+ } else {
/* Half Transfer Complete flag */
temp = __HAL_DMA_GET_HT_FLAG_INDEX(hdma);
}
@@ -537,10 +499,8 @@ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t Comp
/* Get tick */
tickstart = HAL_GetTick();
- while(__HAL_DMA_GET_FLAG(hdma, temp) == RESET)
- {
- if((__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET))
- {
+ while (__HAL_DMA_GET_FLAG(hdma, temp) == RESET) {
+ if ((__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET)) {
/* When a DMA transfer error occurs */
/* A hardware clear of its EN bits is performed */
/* Clear all flags */
@@ -550,7 +510,7 @@ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t Comp
SET_BIT(hdma->ErrorCode, HAL_DMA_ERROR_TE);
/* Change the DMA state */
- hdma->State= HAL_DMA_STATE_READY;
+ hdma->State = HAL_DMA_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hdma);
@@ -558,10 +518,8 @@ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t Comp
return HAL_ERROR;
}
/* Check for the Timeout */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) {
/* Update error code */
SET_BIT(hdma->ErrorCode, HAL_DMA_ERROR_TIMEOUT);
@@ -576,21 +534,18 @@ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t Comp
}
}
- if(CompleteLevel == HAL_DMA_FULL_TRANSFER)
- {
+ if (CompleteLevel == HAL_DMA_FULL_TRANSFER) {
/* Clear the transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
/* The selected Channelx EN bit is cleared (DMA is disabled and
all transfers are complete) */
hdma->State = HAL_DMA_STATE_READY;
- }
- else
- {
+ } else {
/* Clear the half transfer complete flag */
__HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma));
}
-
+
/* Process unlocked */
__HAL_UNLOCK(hdma);
@@ -598,22 +553,19 @@ HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t Comp
}
/**
- * @brief Handles DMA interrupt request.
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @retval None
- */
-void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma)
-{
- uint32_t flag_it = hdma->DmaBaseAddress->ISR;
+ * @brief Handles DMA interrupt request.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @retval None
+ */
+void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) {
+ uint32_t flag_it = hdma->DmaBaseAddress->ISR;
uint32_t source_it = hdma->Instance->CCR;
-
+
/* Half Transfer Complete Interrupt management ******************************/
- if (((flag_it & (DMA_FLAG_HT1 << hdma->ChannelIndex)) != RESET) && ((source_it & DMA_IT_HT) != RESET))
- {
+ if (((flag_it & (DMA_FLAG_HT1 << hdma->ChannelIndex)) != RESET) && ((source_it & DMA_IT_HT) != RESET)) {
/* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */
- if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U)
- {
+ if ((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) {
/* Disable the half transfer interrupt */
__HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT);
}
@@ -623,40 +575,35 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma)
/* DMA peripheral state is not updated in Half Transfer */
/* but in Transfer Complete case */
- if(hdma->XferHalfCpltCallback != NULL)
- {
+ if (hdma->XferHalfCpltCallback != NULL) {
/* Half transfer callback */
hdma->XferHalfCpltCallback(hdma);
}
}
/* Transfer Complete Interrupt management ***********************************/
- else if (((flag_it & (DMA_FLAG_TC1 << hdma->ChannelIndex)) != RESET) && ((source_it & DMA_IT_TC) != RESET))
- {
- if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U)
- {
+ else if (((flag_it & (DMA_FLAG_TC1 << hdma->ChannelIndex)) != RESET) && ((source_it & DMA_IT_TC) != RESET)) {
+ if ((hdma->Instance->CCR & DMA_CCR_CIRC) == 0U) {
/* Disable the transfer complete and error interrupt */
- __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TE | DMA_IT_TC);
+ __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TE | DMA_IT_TC);
/* Change the DMA state */
hdma->State = HAL_DMA_STATE_READY;
}
/* Clear the transfer complete flag */
- __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
+ __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma));
/* Process Unlocked */
__HAL_UNLOCK(hdma);
- if(hdma->XferCpltCallback != NULL)
- {
+ if (hdma->XferCpltCallback != NULL) {
/* Transfer complete callback */
hdma->XferCpltCallback(hdma);
}
}
/* Transfer Error Interrupt management **************************************/
- else if (( RESET != (flag_it & (DMA_FLAG_TE1 << hdma->ChannelIndex))) && (RESET != (source_it & DMA_IT_TE)))
- {
+ else if ((RESET != (flag_it & (DMA_FLAG_TE1 << hdma->ChannelIndex))) && (RESET != (source_it & DMA_IT_TE))) {
/* When a DMA transfer error occurs */
/* A hardware clear of its EN bits is performed */
/* Disable ALL DMA IT */
@@ -674,8 +621,7 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma)
/* Process Unlocked */
__HAL_UNLOCK(hdma);
- if (hdma->XferErrorCallback != NULL)
- {
+ if (hdma->XferErrorCallback != NULL) {
/* Transfer error callback */
hdma->XferErrorCallback(hdma);
}
@@ -684,119 +630,109 @@ void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma)
}
/**
- * @brief Register callbacks
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @param CallbackID: User Callback identifer
- * a HAL_DMA_CallbackIDTypeDef ENUM as parameter.
- * @param pCallback: pointer to private callbacsk function which has pointer to
- * a DMA_HandleTypeDef structure as parameter.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DMA_RegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID, void (* pCallback)( DMA_HandleTypeDef * _hdma))
-{
+ * @brief Register callbacks
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @param CallbackID: User Callback identifer
+ * a HAL_DMA_CallbackIDTypeDef ENUM as parameter.
+ * @param pCallback: pointer to private callbacsk function which has pointer to
+ * a DMA_HandleTypeDef structure as parameter.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_RegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID, void (*pCallback)(DMA_HandleTypeDef *_hdma)) {
HAL_StatusTypeDef status = HAL_OK;
-
+
/* Process locked */
__HAL_LOCK(hdma);
-
- if(HAL_DMA_STATE_READY == hdma->State)
- {
- switch (CallbackID)
- {
- case HAL_DMA_XFER_CPLT_CB_ID:
+
+ if (HAL_DMA_STATE_READY == hdma->State) {
+ switch (CallbackID) {
+ case HAL_DMA_XFER_CPLT_CB_ID:
hdma->XferCpltCallback = pCallback;
break;
-
- case HAL_DMA_XFER_HALFCPLT_CB_ID:
+
+ case HAL_DMA_XFER_HALFCPLT_CB_ID:
hdma->XferHalfCpltCallback = pCallback;
- break;
+ break;
- case HAL_DMA_XFER_ERROR_CB_ID:
+ case HAL_DMA_XFER_ERROR_CB_ID:
hdma->XferErrorCallback = pCallback;
- break;
-
- case HAL_DMA_XFER_ABORT_CB_ID:
+ break;
+
+ case HAL_DMA_XFER_ABORT_CB_ID:
hdma->XferAbortCallback = pCallback;
- break;
-
+ break;
+
default:
status = HAL_ERROR;
- break;
+ break;
}
- }
- else
- {
+ } else {
status = HAL_ERROR;
- }
-
+ }
+
/* Release Lock */
__HAL_UNLOCK(hdma);
-
+
return status;
}
/**
- * @brief UnRegister callbacks
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @param CallbackID: User Callback identifer
- * a HAL_DMA_CallbackIDTypeDef ENUM as parameter.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID)
-{
+ * @brief UnRegister callbacks
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @param CallbackID: User Callback identifer
+ * a HAL_DMA_CallbackIDTypeDef ENUM as parameter.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_CallbackIDTypeDef CallbackID) {
HAL_StatusTypeDef status = HAL_OK;
/* Process locked */
__HAL_LOCK(hdma);
-
- if(HAL_DMA_STATE_READY == hdma->State)
- {
- switch (CallbackID)
- {
- case HAL_DMA_XFER_CPLT_CB_ID:
+
+ if (HAL_DMA_STATE_READY == hdma->State) {
+ switch (CallbackID) {
+ case HAL_DMA_XFER_CPLT_CB_ID:
hdma->XferCpltCallback = NULL;
break;
- case HAL_DMA_XFER_HALFCPLT_CB_ID:
+ case HAL_DMA_XFER_HALFCPLT_CB_ID:
hdma->XferHalfCpltCallback = NULL;
- break;
+ break;
- case HAL_DMA_XFER_ERROR_CB_ID:
+ case HAL_DMA_XFER_ERROR_CB_ID:
hdma->XferErrorCallback = NULL;
- break;
+ break;
- case HAL_DMA_XFER_ABORT_CB_ID:
+ case HAL_DMA_XFER_ABORT_CB_ID:
hdma->XferAbortCallback = NULL;
- break;
+ break;
- case HAL_DMA_XFER_ALL_CB_ID:
- hdma->XferCpltCallback = NULL;
+ case HAL_DMA_XFER_ALL_CB_ID:
+ hdma->XferCpltCallback = NULL;
hdma->XferHalfCpltCallback = NULL;
- hdma->XferErrorCallback = NULL;
- hdma->XferAbortCallback = NULL;
- break;
+ hdma->XferErrorCallback = NULL;
+ hdma->XferAbortCallback = NULL;
+ break;
default:
status = HAL_ERROR;
break;
}
- }
- else
- {
+ } else {
status = HAL_ERROR;
- }
-
+ }
+
/* Release Lock */
__HAL_UNLOCK(hdma);
-
+
return status;
}
-
+
/**
- * @}
- */
+ * @}
+ */
/** @defgroup DMA_Exported_Functions_Group3 Peripheral State and Errors functions
* @brief Peripheral State and Errors functions
@@ -804,7 +740,7 @@ HAL_StatusTypeDef HAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_Ca
@verbatim
===============================================================================
##### Peripheral State and Errors functions #####
- ===============================================================================
+ ===============================================================================
[..]
This subsection provides functions allowing to
(+) Check the DMA state
@@ -815,51 +751,46 @@ HAL_StatusTypeDef HAL_DMA_UnRegisterCallback(DMA_HandleTypeDef *hdma, HAL_DMA_Ca
*/
/**
- * @brief Return the DMA hande state.
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @retval HAL state
- */
-HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma)
-{
+ * @brief Return the DMA hande state.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @retval HAL state
+ */
+HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma) {
/* Return DMA handle state */
return hdma->State;
}
/**
- * @brief Return the DMA error code.
- * @param hdma : pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @retval DMA Error Code
- */
-uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma)
-{
- return hdma->ErrorCode;
-}
+ * @brief Return the DMA error code.
+ * @param hdma : pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @retval DMA Error Code
+ */
+uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma) { return hdma->ErrorCode; }
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/** @addtogroup DMA_Private_Functions
- * @{
- */
+ * @{
+ */
/**
- * @brief Sets the DMA Transfer parameter.
- * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
- * the configuration information for the specified DMA Channel.
- * @param SrcAddress: The source memory Buffer address
- * @param DstAddress: The destination memory Buffer address
- * @param DataLength: The length of data to be transferred from source to destination
- * @retval HAL status
- */
-static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength)
-{
+ * @brief Sets the DMA Transfer parameter.
+ * @param hdma: pointer to a DMA_HandleTypeDef structure that contains
+ * the configuration information for the specified DMA Channel.
+ * @param SrcAddress: The source memory Buffer address
+ * @param DstAddress: The destination memory Buffer address
+ * @param DataLength: The length of data to be transferred from source to destination
+ * @retval HAL status
+ */
+static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) {
/* Clear all flags */
hdma->DmaBaseAddress->IFCR = (DMA_ISR_GIF1 << hdma->ChannelIndex);
@@ -867,8 +798,7 @@ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t
hdma->Instance->CNDTR = DataLength;
/* Memory to Peripheral */
- if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH)
- {
+ if ((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH) {
/* Configure DMA Channel destination address */
hdma->Instance->CPAR = DstAddress;
@@ -876,8 +806,7 @@ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t
hdma->Instance->CMAR = SrcAddress;
}
/* Peripheral to Memory */
- else
- {
+ else {
/* Configure DMA Channel source address */
hdma->Instance->CPAR = SrcAddress;
@@ -887,16 +816,16 @@ static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t
}
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_DMA_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash.c
index ea723908..f4ed595a 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash.c
@@ -3,22 +3,22 @@
* @file stm32f1xx_hal_flash.c
* @author MCD Application Team
* @brief FLASH HAL module driver.
- * This file provides firmware functions to manage the following
+ * This file provides firmware functions to manage the following
* functionalities of the internal FLASH memory:
* + Program operations functions
- * + Memory Control functions
+ * + Memory Control functions
* + Peripheral State functions
- *
+ *
@verbatim
==============================================================================
##### FLASH peripheral features #####
==============================================================================
- [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses
- to the Flash memory. It implements the erase and program Flash memory operations
+ [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses
+ to the Flash memory. It implements the erase and program Flash memory operations
and the read and write protection mechanisms.
[..] The Flash memory interface accelerates code execution with a system of instruction
- prefetch.
+ prefetch.
[..] The FLASH main features are:
(+) Flash memory read operations
@@ -30,10 +30,10 @@
##### How to use this driver #####
==============================================================================
- [..]
- This driver provides functions and macros to configure and program the FLASH
+ [..]
+ This driver provides functions and macros to configure and program the FLASH
memory of all STM32F1xx devices.
-
+
(#) FLASH Memory I/O Programming functions: this group includes all needed
functions to erase and program the main memory:
(++) Lock and Unlock the FLASH interface
@@ -50,8 +50,8 @@
(++) Program the data Option Bytes
(++) Get the Write protection.
(++) Get the user option bytes.
-
- (#) Interrupts and flags management functions : this group
+
+ (#) Interrupts and flags management functions : this group
includes all needed functions to:
(++) Handle FLASH interrupts
(++) Wait for last FLASH operation according to its status
@@ -59,13 +59,13 @@
[..] In addition to these function, this driver includes a set of macros allowing
to handle the following operations:
-
+
(+) Set/Get the latency
(+) Enable/Disable the prefetch buffer
(+) Enable/Disable the half cycle access
(+) Enable/Disable the FLASH interrupts
(+) Monitor the FLASH flags status
-
+
@endverbatim
******************************************************************************
* @attention
@@ -94,99 +94,98 @@
* 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.
*
- ******************************************************************************
+ ******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
#ifdef HAL_FLASH_MODULE_ENABLED
/** @defgroup FLASH FLASH
- * @brief FLASH HAL module driver
- * @{
- */
+ * @brief FLASH HAL module driver
+ * @{
+ */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup FLASH_Private_Constants FLASH Private Constants
- * @{
- */
+ * @{
+ */
/**
- * @}
- */
+ * @}
+ */
/* Private macro ---------------------------- ---------------------------------*/
/** @defgroup FLASH_Private_Macros FLASH Private Macros
- * @{
- */
-
+ * @{
+ */
+
/**
- * @}
- */
+ * @}
+ */
/* Private variables ---------------------------------------------------------*/
/** @defgroup FLASH_Private_Variables FLASH Private Variables
- * @{
- */
+ * @{
+ */
/* Variables used for Erase pages under interruption*/
FLASH_ProcessTypeDef pFlash;
/**
- * @}
- */
+ * @}
+ */
/* Private function prototypes -----------------------------------------------*/
/** @defgroup FLASH_Private_Functions FLASH Private Functions
- * @{
- */
-static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data);
-static void FLASH_SetErrorCode(void);
-extern void FLASH_PageErase(uint32_t PageAddress);
+ * @{
+ */
+static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data);
+static void FLASH_SetErrorCode(void);
+extern void FLASH_PageErase(uint32_t PageAddress);
/**
- * @}
- */
+ * @}
+ */
/* Exported functions ---------------------------------------------------------*/
/** @defgroup FLASH_Exported_Functions FLASH Exported Functions
- * @{
- */
-
-/** @defgroup FLASH_Exported_Functions_Group1 Programming operation functions
- * @brief Programming operation functions
+ * @{
+ */
+
+/** @defgroup FLASH_Exported_Functions_Group1 Programming operation functions
+ * @brief Programming operation functions
*
-@verbatim
+@verbatim
@endverbatim
* @{
*/
/**
- * @brief Program halfword, word or double word at a specified address
- * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
- * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
- *
- * @note If an erase and a program operations are requested simultaneously,
- * the erase operation is performed before the program one.
- *
- * @note FLASH should be previously erased before new programmation (only exception to this
- * is when 0x0000 is programmed)
- *
- * @param TypeProgram: Indicate the way to program at a specified address.
- * This parameter can be a value of @ref FLASH_Type_Program
- * @param Address: Specifies the address to be programmed.
- * @param Data: Specifies the data to be programmed
- *
- * @retval HAL_StatusTypeDef HAL Status
- */
-HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
-{
- HAL_StatusTypeDef status = HAL_ERROR;
- uint8_t index = 0;
- uint8_t nbiterations = 0;
-
+ * @brief Program halfword, word or double word at a specified address
+ * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
+ * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
+ *
+ * @note If an erase and a program operations are requested simultaneously,
+ * the erase operation is performed before the program one.
+ *
+ * @note FLASH should be previously erased before new programmation (only exception to this
+ * is when 0x0000 is programmed)
+ *
+ * @param TypeProgram: Indicate the way to program at a specified address.
+ * This parameter can be a value of @ref FLASH_Type_Program
+ * @param Address: Specifies the address to be programmed.
+ * @param Data: Specifies the data to be programmed
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data) {
+ HAL_StatusTypeDef status = HAL_ERROR;
+ uint8_t index = 0;
+ uint8_t nbiterations = 0;
+
/* Process Locked */
__HAL_LOCK(&pFlash);
@@ -195,65 +194,51 @@ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint
assert_param(IS_FLASH_PROGRAM_ADDRESS(Address));
#if defined(FLASH_BANK2_END)
- if(Address <= FLASH_BANK1_END)
- {
+ if (Address <= FLASH_BANK1_END) {
#endif /* FLASH_BANK2_END */
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
#if defined(FLASH_BANK2_END)
- }
- else
- {
+ } else {
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperationBank2(FLASH_TIMEOUT_VALUE);
}
#endif /* FLASH_BANK2_END */
-
- if(status == HAL_OK)
- {
- if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD)
- {
+
+ if (status == HAL_OK) {
+ if (TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) {
/* Program halfword (16-bit) at a specified address. */
nbiterations = 1U;
- }
- else if(TypeProgram == FLASH_TYPEPROGRAM_WORD)
- {
+ } else if (TypeProgram == FLASH_TYPEPROGRAM_WORD) {
/* Program word (32-bit = 2*16-bit) at a specified address. */
nbiterations = 2U;
- }
- else
- {
+ } else {
/* Program double word (64-bit = 4*16-bit) at a specified address. */
nbiterations = 4U;
}
- for (index = 0U; index < nbiterations; index++)
- {
- FLASH_Program_HalfWord((Address + (2U*index)), (uint16_t)(Data >> (16U*index)));
+ for (index = 0U; index < nbiterations; index++) {
+ FLASH_Program_HalfWord((Address + (2U * index)), (uint16_t)(Data >> (16U * index)));
#if defined(FLASH_BANK2_END)
- if(Address <= FLASH_BANK1_END)
- {
+ if (Address <= FLASH_BANK1_END) {
#endif /* FLASH_BANK2_END */
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
-
+
/* If the program operation is completed, disable the PG Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_PG);
#if defined(FLASH_BANK2_END)
- }
- else
- {
+ } else {
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperationBank2(FLASH_TIMEOUT_VALUE);
-
+
/* If the program operation is completed, disable the PG Bit */
CLEAR_BIT(FLASH->CR2, FLASH_CR2_PG);
}
#endif /* FLASH_BANK2_END */
/* In case of error, stop programation procedure */
- if (status != HAL_OK)
- {
+ if (status != HAL_OK) {
break;
}
}
@@ -266,24 +251,23 @@ HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint
}
/**
- * @brief Program halfword, word or double word at a specified address with interrupt enabled.
- * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
- * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
- *
- * @note If an erase and a program operations are requested simultaneously,
- * the erase operation is performed before the program one.
- *
- * @param TypeProgram: Indicate the way to program at a specified address.
- * This parameter can be a value of @ref FLASH_Type_Program
- * @param Address: Specifies the address to be programmed.
- * @param Data: Specifies the data to be programmed
- *
- * @retval HAL_StatusTypeDef HAL Status
- */
-HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data)
-{
+ * @brief Program halfword, word or double word at a specified address with interrupt enabled.
+ * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
+ * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface
+ *
+ * @note If an erase and a program operations are requested simultaneously,
+ * the erase operation is performed before the program one.
+ *
+ * @param TypeProgram: Indicate the way to program at a specified address.
+ * This parameter can be a value of @ref FLASH_Type_Program
+ * @param Address: Specifies the address to be programmed.
+ * @param Data: Specifies the data to be programmed
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data) {
HAL_StatusTypeDef status = HAL_OK;
-
+
/* Process Locked */
__HAL_LOCK(&pFlash);
@@ -293,18 +277,15 @@ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, u
#if defined(FLASH_BANK2_END)
/* If procedure already ongoing, reject the next one */
- if (pFlash.ProcedureOnGoing != FLASH_PROC_NONE)
- {
+ if (pFlash.ProcedureOnGoing != FLASH_PROC_NONE) {
return HAL_ERROR;
}
-
- if(Address <= FLASH_BANK1_END)
- {
+
+ if (Address <= FLASH_BANK1_END) {
/* Enable End of FLASH Operation and Error source interrupts */
__HAL_FLASH_ENABLE_IT(FLASH_IT_EOP_BANK1 | FLASH_IT_ERR_BANK1);
- }else
- {
+ } else {
/* Enable End of FLASH Operation and Error source interrupts */
__HAL_FLASH_ENABLE_IT(FLASH_IT_EOP_BANK2 | FLASH_IT_ERR_BANK2);
}
@@ -312,24 +293,19 @@ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, u
/* Enable End of FLASH Operation and Error source interrupts */
__HAL_FLASH_ENABLE_IT(FLASH_IT_EOP | FLASH_IT_ERR);
#endif /* FLASH_BANK2_END */
-
+
pFlash.Address = Address;
- pFlash.Data = Data;
+ pFlash.Data = Data;
- if(TypeProgram == FLASH_TYPEPROGRAM_HALFWORD)
- {
+ if (TypeProgram == FLASH_TYPEPROGRAM_HALFWORD) {
pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMHALFWORD;
/* Program halfword (16-bit) at a specified address. */
pFlash.DataRemaining = 1U;
- }
- else if(TypeProgram == FLASH_TYPEPROGRAM_WORD)
- {
+ } else if (TypeProgram == FLASH_TYPEPROGRAM_WORD) {
pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMWORD;
/* Program word (32-bit : 2*16-bit) at a specified address. */
pFlash.DataRemaining = 2U;
- }
- else
- {
+ } else {
pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMDOUBLEWORD;
/* Program double word (64-bit : 4*16-bit) at a specified address. */
pFlash.DataRemaining = 4U;
@@ -342,29 +318,27 @@ HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, u
}
/**
- * @brief This function handles FLASH interrupt request.
- * @retval None
- */
-void HAL_FLASH_IRQHandler(void)
-{
+ * @brief This function handles FLASH interrupt request.
+ * @retval None
+ */
+void HAL_FLASH_IRQHandler(void) {
uint32_t addresstmp = 0U;
-
+
/* Check FLASH operation error flags */
#if defined(FLASH_BANK2_END)
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR_BANK1) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR_BANK1) || \
- (__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR_BANK2) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR_BANK2)))
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR_BANK1) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR_BANK1) || (__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR_BANK2) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR_BANK2)))
#else
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) ||__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
#endif /* FLASH_BANK2_END */
{
/* Return the faulty address */
addresstmp = pFlash.Address;
/* Reset address */
pFlash.Address = 0xFFFFFFFFU;
-
+
/* Save the Error code */
FLASH_SetErrorCode();
-
+
/* FLASH error interrupt user callback */
HAL_FLASH_OperationErrorCallback(addresstmp);
@@ -374,60 +348,50 @@ void HAL_FLASH_IRQHandler(void)
/* Check FLASH End of Operation flag */
#if defined(FLASH_BANK2_END)
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP_BANK1))
- {
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP_BANK1)) {
/* Clear FLASH End of Operation pending bit */
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP_BANK1);
#else
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP))
- {
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP)) {
/* Clear FLASH End of Operation pending bit */
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
#endif /* FLASH_BANK2_END */
-
+
/* Process can continue only if no error detected */
- if(pFlash.ProcedureOnGoing != FLASH_PROC_NONE)
- {
- if(pFlash.ProcedureOnGoing == FLASH_PROC_PAGEERASE)
- {
+ if (pFlash.ProcedureOnGoing != FLASH_PROC_NONE) {
+ if (pFlash.ProcedureOnGoing == FLASH_PROC_PAGEERASE) {
/* Nb of pages to erased can be decreased */
pFlash.DataRemaining--;
/* Check if there are still pages to erase */
- if(pFlash.DataRemaining != 0U)
- {
+ if (pFlash.DataRemaining != 0U) {
addresstmp = pFlash.Address;
/*Indicate user which sector has been erased */
HAL_FLASH_EndOfOperationCallback(addresstmp);
/*Increment sector number*/
- addresstmp = pFlash.Address + FLASH_PAGE_SIZE;
+ addresstmp = pFlash.Address + FLASH_PAGE_SIZE;
pFlash.Address = addresstmp;
/* If the erase operation is completed, disable the PER Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_PER);
FLASH_PageErase(addresstmp);
- }
- else
- {
+ } else {
/* No more pages to Erase, user callback can be called. */
/* Reset Sector and stop Erase pages procedure */
pFlash.Address = addresstmp = 0xFFFFFFFFU;
- pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
+ pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
/* FLASH EOP interrupt user callback */
HAL_FLASH_EndOfOperationCallback(addresstmp);
}
- }
- else if(pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE)
- {
+ } else if (pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE) {
/* Operation is completed, disable the MER Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_MER);
#if defined(FLASH_BANK2_END)
/* Stop Mass Erase procedure if no pending mass erase on other bank */
- if (HAL_IS_BIT_CLR(FLASH->CR2, FLASH_CR2_MER))
- {
+ if (HAL_IS_BIT_CLR(FLASH->CR2, FLASH_CR2_MER)) {
#endif /* FLASH_BANK2_END */
/* MassErase ended. Return the selected bank */
/* FLASH EOP interrupt user callback */
@@ -439,73 +403,60 @@ void HAL_FLASH_IRQHandler(void)
#if defined(FLASH_BANK2_END)
}
#endif /* FLASH_BANK2_END */
- else
- {
+ else {
/* Nb of 16-bit data to program can be decreased */
pFlash.DataRemaining--;
-
+
/* Check if there are still 16-bit data to program */
- if(pFlash.DataRemaining != 0U)
- {
+ if (pFlash.DataRemaining != 0U) {
/* Increment address to 16-bit */
pFlash.Address += 2U;
addresstmp = pFlash.Address;
-
+
/* Shift to have next 16-bit data */
pFlash.Data = (pFlash.Data >> 16U);
-
+
/* Operation is completed, disable the PG Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_PG);
/*Program halfword (16-bit) at a specified address.*/
FLASH_Program_HalfWord(addresstmp, (uint16_t)pFlash.Data);
- }
- else
- {
+ } else {
/* Program ended. Return the selected address */
/* FLASH EOP interrupt user callback */
- if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMHALFWORD)
- {
+ if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMHALFWORD) {
HAL_FLASH_EndOfOperationCallback(pFlash.Address);
- }
- else if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMWORD)
- {
+ } else if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMWORD) {
HAL_FLASH_EndOfOperationCallback(pFlash.Address - 2U);
- }
- else
- {
+ } else {
HAL_FLASH_EndOfOperationCallback(pFlash.Address - 6U);
}
-
+
/* Reset Address and stop Program procedure */
- pFlash.Address = 0xFFFFFFFFU;
+ pFlash.Address = 0xFFFFFFFFU;
pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
}
}
}
}
-
+
#if defined(FLASH_BANK2_END)
/* Check FLASH End of Operation flag */
- if(__HAL_FLASH_GET_FLAG( FLASH_FLAG_EOP_BANK2))
- {
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP_BANK2)) {
/* Clear FLASH End of Operation pending bit */
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP_BANK2);
-
+
/* Process can continue only if no error detected */
- if(pFlash.ProcedureOnGoing != FLASH_PROC_NONE)
- {
- if(pFlash.ProcedureOnGoing == FLASH_PROC_PAGEERASE)
- {
+ if (pFlash.ProcedureOnGoing != FLASH_PROC_NONE) {
+ if (pFlash.ProcedureOnGoing == FLASH_PROC_PAGEERASE) {
/* Nb of pages to erased can be decreased */
pFlash.DataRemaining--;
-
+
/* Check if there are still pages to erase*/
- if(pFlash.DataRemaining != 0U)
- {
+ if (pFlash.DataRemaining != 0U) {
/* Indicate user which page address has been erased*/
HAL_FLASH_EndOfOperationCallback(pFlash.Address);
-
+
/* Increment page address to next page */
pFlash.Address += FLASH_PAGE_SIZE;
addresstmp = pFlash.Address;
@@ -514,87 +465,71 @@ void HAL_FLASH_IRQHandler(void)
CLEAR_BIT(FLASH->CR2, FLASH_CR2_PER);
FLASH_PageErase(addresstmp);
- }
- else
- {
+ } else {
/*No more pages to Erase*/
-
+
/*Reset Address and stop Erase pages procedure*/
- pFlash.Address = 0xFFFFFFFFU;
+ pFlash.Address = 0xFFFFFFFFU;
pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
/* FLASH EOP interrupt user callback */
HAL_FLASH_EndOfOperationCallback(pFlash.Address);
}
- }
- else if(pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE)
- {
+ } else if (pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE) {
/* Operation is completed, disable the MER Bit */
CLEAR_BIT(FLASH->CR2, FLASH_CR2_MER);
- if (HAL_IS_BIT_CLR(FLASH->CR, FLASH_CR_MER))
- {
+ if (HAL_IS_BIT_CLR(FLASH->CR, FLASH_CR_MER)) {
/* MassErase ended. Return the selected bank*/
/* FLASH EOP interrupt user callback */
HAL_FLASH_EndOfOperationCallback(0U);
-
+
pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
}
- }
- else
- {
+ } else {
/* Nb of 16-bit data to program can be decreased */
pFlash.DataRemaining--;
-
+
/* Check if there are still 16-bit data to program */
- if(pFlash.DataRemaining != 0U)
- {
+ if (pFlash.DataRemaining != 0U) {
/* Increment address to 16-bit */
pFlash.Address += 2U;
addresstmp = pFlash.Address;
-
+
/* Shift to have next 16-bit data */
pFlash.Data = (pFlash.Data >> 16U);
-
+
/* Operation is completed, disable the PG Bit */
CLEAR_BIT(FLASH->CR2, FLASH_CR2_PG);
/*Program halfword (16-bit) at a specified address.*/
FLASH_Program_HalfWord(addresstmp, (uint16_t)pFlash.Data);
- }
- else
- {
+ } else {
/*Program ended. Return the selected address*/
/* FLASH EOP interrupt user callback */
- if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMHALFWORD)
- {
+ if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMHALFWORD) {
HAL_FLASH_EndOfOperationCallback(pFlash.Address);
+ } else if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMWORD) {
+ HAL_FLASH_EndOfOperationCallback(pFlash.Address - 2U);
+ } else {
+ HAL_FLASH_EndOfOperationCallback(pFlash.Address - 6U);
}
- else if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMWORD)
- {
- HAL_FLASH_EndOfOperationCallback(pFlash.Address-2U);
- }
- else
- {
- HAL_FLASH_EndOfOperationCallback(pFlash.Address-6U);
- }
-
+
/* Reset Address and stop Program procedure*/
- pFlash.Address = 0xFFFFFFFFU;
+ pFlash.Address = 0xFFFFFFFFU;
pFlash.ProcedureOnGoing = FLASH_PROC_NONE;
}
}
}
}
-#endif
+#endif
- if(pFlash.ProcedureOnGoing == FLASH_PROC_NONE)
- {
+ if (pFlash.ProcedureOnGoing == FLASH_PROC_NONE) {
#if defined(FLASH_BANK2_END)
/* Operation is completed, disable the PG, PER and MER Bits for both bank */
CLEAR_BIT(FLASH->CR, (FLASH_CR_PG | FLASH_CR_PER | FLASH_CR_MER));
- CLEAR_BIT(FLASH->CR2, (FLASH_CR2_PG | FLASH_CR2_PER | FLASH_CR2_MER));
-
+ CLEAR_BIT(FLASH->CR2, (FLASH_CR2_PG | FLASH_CR2_PER | FLASH_CR2_MER));
+
/* Disable End of FLASH Operation and Error source interrupts for both banks */
__HAL_FLASH_DISABLE_IT(FLASH_IT_EOP_BANK1 | FLASH_IT_ERR_BANK1 | FLASH_IT_EOP_BANK2 | FLASH_IT_ERR_BANK2);
#else
@@ -611,55 +546,53 @@ void HAL_FLASH_IRQHandler(void)
}
/**
- * @brief FLASH end of operation interrupt callback
- * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
- * - Mass Erase: No return value expected
- * - Pages Erase: Address of the page which has been erased
- * (if 0xFFFFFFFF, it means that all the selected pages have been erased)
- * - Program: Address which was selected for data program
- * @retval none
- */
-__weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue)
-{
+ * @brief FLASH end of operation interrupt callback
+ * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
+ * - Mass Erase: No return value expected
+ * - Pages Erase: Address of the page which has been erased
+ * (if 0xFFFFFFFF, it means that all the selected pages have been erased)
+ * - Program: Address which was selected for data program
+ * @retval none
+ */
+__weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue) {
/* Prevent unused argument(s) compilation warning */
UNUSED(ReturnValue);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FLASH_EndOfOperationCallback could be implemented in the user file
- */
+ */
}
/**
- * @brief FLASH operation error interrupt callback
- * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
- * - Mass Erase: No return value expected
- * - Pages Erase: Address of the page which returned an error
- * - Program: Address which was selected for data program
- * @retval none
- */
-__weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue)
-{
+ * @brief FLASH operation error interrupt callback
+ * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure
+ * - Mass Erase: No return value expected
+ * - Pages Erase: Address of the page which returned an error
+ * - Program: Address which was selected for data program
+ * @retval none
+ */
+__weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue) {
/* Prevent unused argument(s) compilation warning */
UNUSED(ReturnValue);
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_FLASH_OperationErrorCallback could be implemented in the user file
- */
+ */
}
/**
- * @}
- */
+ * @}
+ */
-/** @defgroup FLASH_Exported_Functions_Group2 Peripheral Control functions
- * @brief management functions
+/** @defgroup FLASH_Exported_Functions_Group2 Peripheral Control functions
+ * @brief management functions
*
-@verbatim
+@verbatim
===============================================================================
##### Peripheral Control functions #####
- ===============================================================================
+ ===============================================================================
[..]
- This subsection provides a set of functions allowing to control the FLASH
+ This subsection provides a set of functions allowing to control the FLASH
memory operations.
@endverbatim
@@ -667,35 +600,30 @@ __weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue)
*/
/**
- * @brief Unlock the FLASH control register access
- * @retval HAL Status
- */
-HAL_StatusTypeDef HAL_FLASH_Unlock(void)
-{
+ * @brief Unlock the FLASH control register access
+ * @retval HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_Unlock(void) {
HAL_StatusTypeDef status = HAL_OK;
- if(READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET)
- {
+ if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET) {
/* Authorize the FLASH Registers access */
WRITE_REG(FLASH->KEYR, FLASH_KEY1);
WRITE_REG(FLASH->KEYR, FLASH_KEY2);
/* Verify Flash is unlocked */
- if(READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET)
- {
+ if (READ_BIT(FLASH->CR, FLASH_CR_LOCK) != RESET) {
status = HAL_ERROR;
}
}
#if defined(FLASH_BANK2_END)
- if(READ_BIT(FLASH->CR2, FLASH_CR2_LOCK) != RESET)
- {
+ if (READ_BIT(FLASH->CR2, FLASH_CR2_LOCK) != RESET) {
/* Authorize the FLASH BANK2 Registers access */
WRITE_REG(FLASH->KEYR2, FLASH_KEY1);
WRITE_REG(FLASH->KEYR2, FLASH_KEY2);
-
+
/* Verify Flash BANK2 is unlocked */
- if(READ_BIT(FLASH->CR2, FLASH_CR2_LOCK) != RESET)
- {
+ if (READ_BIT(FLASH->CR2, FLASH_CR2_LOCK) != RESET) {
status = HAL_ERROR;
}
}
@@ -705,76 +633,69 @@ HAL_StatusTypeDef HAL_FLASH_Unlock(void)
}
/**
- * @brief Locks the FLASH control register access
- * @retval HAL Status
- */
-HAL_StatusTypeDef HAL_FLASH_Lock(void)
-{
+ * @brief Locks the FLASH control register access
+ * @retval HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_Lock(void) {
/* Set the LOCK Bit to lock the FLASH Registers access */
SET_BIT(FLASH->CR, FLASH_CR_LOCK);
-
+
#if defined(FLASH_BANK2_END)
/* Set the LOCK Bit to lock the FLASH BANK2 Registers access */
SET_BIT(FLASH->CR2, FLASH_CR2_LOCK);
#endif /* FLASH_BANK2_END */
- return HAL_OK;
+ return HAL_OK;
}
/**
- * @brief Unlock the FLASH Option Control Registers access.
- * @retval HAL Status
- */
-HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void)
-{
- if (HAL_IS_BIT_CLR(FLASH->CR, FLASH_CR_OPTWRE))
- {
+ * @brief Unlock the FLASH Option Control Registers access.
+ * @retval HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void) {
+ if (HAL_IS_BIT_CLR(FLASH->CR, FLASH_CR_OPTWRE)) {
/* Authorizes the Option Byte register programming */
WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY1);
WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY2);
- }
- else
- {
+ } else {
return HAL_ERROR;
- }
-
- return HAL_OK;
+ }
+
+ return HAL_OK;
}
/**
- * @brief Lock the FLASH Option Control Registers access.
- * @retval HAL Status
- */
-HAL_StatusTypeDef HAL_FLASH_OB_Lock(void)
-{
+ * @brief Lock the FLASH Option Control Registers access.
+ * @retval HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASH_OB_Lock(void) {
/* Clear the OPTWRE Bit to lock the FLASH Option Byte Registers access */
CLEAR_BIT(FLASH->CR, FLASH_CR_OPTWRE);
-
- return HAL_OK;
+
+ return HAL_OK;
}
-
+
/**
- * @brief Launch the option byte loading.
- * @note This function will reset automatically the MCU.
- * @retval None
- */
-void HAL_FLASH_OB_Launch(void)
-{
+ * @brief Launch the option byte loading.
+ * @note This function will reset automatically the MCU.
+ * @retval None
+ */
+void HAL_FLASH_OB_Launch(void) {
/* Initiates a system reset request to launch the option byte loading */
HAL_NVIC_SystemReset();
}
/**
- * @}
- */
+ * @}
+ */
-/** @defgroup FLASH_Exported_Functions_Group3 Peripheral errors functions
- * @brief Peripheral errors functions
+/** @defgroup FLASH_Exported_Functions_Group3 Peripheral errors functions
+ * @brief Peripheral errors functions
*
-@verbatim
+@verbatim
===============================================================================
##### Peripheral Errors functions #####
- ===============================================================================
+ ===============================================================================
[..]
This subsection permit to get in run-time errors of the FLASH peripheral.
@@ -783,92 +704,77 @@ void HAL_FLASH_OB_Launch(void)
*/
/**
- * @brief Get the specific FLASH error flag.
- * @retval FLASH_ErrorCode The returned value can be:
- * @ref FLASH_Error_Codes
- */
-uint32_t HAL_FLASH_GetError(void)
-{
- return pFlash.ErrorCode;
-}
+ * @brief Get the specific FLASH error flag.
+ * @retval FLASH_ErrorCode The returned value can be:
+ * @ref FLASH_Error_Codes
+ */
+uint32_t HAL_FLASH_GetError(void) { return pFlash.ErrorCode; }
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/** @addtogroup FLASH_Private_Functions
* @{
*/
/**
- * @brief Program a half-word (16-bit) at a specified address.
- * @param Address specify the address to be programmed.
- * @param Data specify the data to be programmed.
- * @retval None
- */
-static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data)
-{
+ * @brief Program a half-word (16-bit) at a specified address.
+ * @param Address specify the address to be programmed.
+ * @param Data specify the data to be programmed.
+ * @retval None
+ */
+static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data) {
/* Clean the error context */
pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
-
+
#if defined(FLASH_BANK2_END)
- if(Address <= FLASH_BANK1_END)
- {
+ if (Address <= FLASH_BANK1_END) {
#endif /* FLASH_BANK2_END */
/* Proceed to program the new data */
SET_BIT(FLASH->CR, FLASH_CR_PG);
#if defined(FLASH_BANK2_END)
- }
- else
- {
+ } else {
/* Proceed to program the new data */
SET_BIT(FLASH->CR2, FLASH_CR2_PG);
}
#endif /* FLASH_BANK2_END */
/* Write data in the address */
- *(__IO uint16_t*)Address = Data;
+ *(__IO uint16_t *)Address = Data;
}
/**
- * @brief Wait for a FLASH operation to complete.
- * @param Timeout maximum flash operation timeout
- * @retval HAL Status
- */
-HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout)
-{
+ * @brief Wait for a FLASH operation to complete.
+ * @param Timeout maximum flash operation timeout
+ * @retval HAL Status
+ */
+HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) {
/* Wait for the FLASH operation to complete by polling on BUSY flag to be reset.
Even if the FLASH operation fails, the BUSY flag will be reset and an error
flag will be set */
-
+
uint32_t tickstart = HAL_GetTick();
-
- while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY))
- {
- if (Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout))
- {
+
+ while (__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY)) {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) {
return HAL_TIMEOUT;
}
}
}
-
+
/* Check FLASH End of Operation flag */
- if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP))
- {
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP)) {
/* Clear FLASH End of Operation pending bit */
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP);
}
-
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) ||
- __HAL_FLASH_GET_FLAG(FLASH_FLAG_OPTVERR) ||
- __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
- {
+
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_OPTVERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR)) {
/*Save the error code*/
FLASH_SetErrorCode();
return HAL_ERROR;
@@ -880,38 +786,32 @@ HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout)
#if defined(FLASH_BANK2_END)
/**
- * @brief Wait for a FLASH BANK2 operation to complete.
- * @param Timeout maximum flash operation timeout
- * @retval HAL_StatusTypeDef HAL Status
- */
-HAL_StatusTypeDef FLASH_WaitForLastOperationBank2(uint32_t Timeout)
-{
+ * @brief Wait for a FLASH BANK2 operation to complete.
+ * @param Timeout maximum flash operation timeout
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef FLASH_WaitForLastOperationBank2(uint32_t Timeout) {
/* Wait for the FLASH BANK2 operation to complete by polling on BUSY flag to be reset.
Even if the FLASH BANK2 operation fails, the BUSY flag will be reset and an error
flag will be set */
-
+
uint32_t tickstart = HAL_GetTick();
-
- while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY_BANK2))
- {
- if (Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U) || ((HAL_GetTick()-tickstart) > Timeout))
- {
+
+ while (__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY_BANK2)) {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) {
return HAL_TIMEOUT;
}
}
}
-
+
/* Check FLASH End of Operation flag */
- if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP_BANK2))
- {
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP_BANK2)) {
/* Clear FLASH End of Operation pending bit */
__HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP_BANK2);
}
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR_BANK2) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR_BANK2))
- {
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR_BANK2) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR_BANK2)) {
/*Save the error code*/
FLASH_SetErrorCode();
return HAL_ERROR;
@@ -919,22 +819,20 @@ HAL_StatusTypeDef FLASH_WaitForLastOperationBank2(uint32_t Timeout)
/* If there is an error flag set */
return HAL_OK;
-
}
#endif /* FLASH_BANK2_END */
/**
- * @brief Set the specific FLASH error flag.
- * @retval None
- */
-static void FLASH_SetErrorCode(void)
-{
+ * @brief Set the specific FLASH error flag.
+ * @retval None
+ */
+static void FLASH_SetErrorCode(void) {
uint32_t flags = 0U;
-
+
#if defined(FLASH_BANK2_END)
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR_BANK2))
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR_BANK2))
#else
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR))
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR))
#endif /* FLASH_BANK2_END */
{
pFlash.ErrorCode |= HAL_FLASH_ERROR_WRP;
@@ -945,9 +843,9 @@ static void FLASH_SetErrorCode(void)
#endif /* FLASH_BANK2_END */
}
#if defined(FLASH_BANK2_END)
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR_BANK2))
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR_BANK2))
#else
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR))
#endif /* FLASH_BANK2_END */
{
pFlash.ErrorCode |= HAL_FLASH_ERROR_PROG;
@@ -957,27 +855,26 @@ static void FLASH_SetErrorCode(void)
flags |= FLASH_FLAG_PGERR;
#endif /* FLASH_BANK2_END */
}
- if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_OPTVERR))
- {
+ if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_OPTVERR)) {
pFlash.ErrorCode |= HAL_FLASH_ERROR_OPTV;
- __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);
+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR);
}
/* Clear FLASH error pending bits */
__HAL_FLASH_CLEAR_FLAG(flags);
-}
+}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_FLASH_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash_ex.c
index b83fbc6a..d3fd2140 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash_ex.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_flash_ex.c
@@ -3,27 +3,27 @@
* @file stm32f1xx_hal_flash_ex.c
* @author MCD Application Team
* @brief Extended FLASH HAL module driver.
- *
- * This file provides firmware functions to manage the following
+ *
+ * This file provides firmware functions to manage the following
* functionalities of the FLASH peripheral:
* + Extended Initialization/de-initialization functions
* + Extended I/O operation functions
- * + Extended Peripheral Control functions
- *
+ * + Extended Peripheral Control functions
+ *
@verbatim
==============================================================================
##### Flash peripheral extended features #####
==============================================================================
-
+
##### How to use this driver #####
==============================================================================
- [..] This driver provides functions to configure and program the FLASH memory
+ [..] This driver provides functions to configure and program the FLASH memory
of all STM32F1xxx devices. It includes
-
+
(++) Set/Reset the write protection
(++) Program the user Option Bytes
(++) Get the Read protection Level
-
+
@endverbatim
******************************************************************************
* @attention
@@ -52,57 +52,57 @@
* 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.
*
- ******************************************************************************
+ ******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
#ifdef HAL_FLASH_MODULE_ENABLED
/** @addtogroup FLASH
- * @{
- */
+ * @{
+ */
/** @addtogroup FLASH_Private_Variables
* @{
*/
/* Variables used for Erase pages under interruption*/
extern FLASH_ProcessTypeDef pFlash;
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
-
+ * @}
+ */
+
/** @defgroup FLASHEx FLASHEx
- * @brief FLASH HAL Extension module driver
- * @{
- */
+ * @brief FLASH HAL Extension module driver
+ * @{
+ */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup FLASHEx_Private_Constants FLASHEx Private Constants
* @{
*/
-#define FLASH_POSITION_IWDGSW_BIT FLASH_OBR_IWDG_SW_Pos
-#define FLASH_POSITION_OB_USERDATA0_BIT FLASH_OBR_DATA0_Pos
-#define FLASH_POSITION_OB_USERDATA1_BIT FLASH_OBR_DATA1_Pos
+#define FLASH_POSITION_IWDGSW_BIT FLASH_OBR_IWDG_SW_Pos
+#define FLASH_POSITION_OB_USERDATA0_BIT FLASH_OBR_DATA0_Pos
+#define FLASH_POSITION_OB_USERDATA1_BIT FLASH_OBR_DATA1_Pos
/**
- * @}
- */
+ * @}
+ */
/* Private macro -------------------------------------------------------------*/
/** @defgroup FLASHEx_Private_Macros FLASHEx Private Macros
- * @{
- */
+ * @{
+ */
/**
- * @}
- */
+ * @}
+ */
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
@@ -110,8 +110,8 @@ extern FLASH_ProcessTypeDef pFlash;
* @{
*/
/* Erase operations */
-static void FLASH_MassErase(uint32_t Banks);
-void FLASH_PageErase(uint32_t PageAddress);
+static void FLASH_MassErase(uint32_t Banks);
+void FLASH_PageErase(uint32_t PageAddress);
/* Option bytes control */
static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage);
@@ -124,58 +124,56 @@ static uint32_t FLASH_OB_GetRDP(void);
static uint8_t FLASH_OB_GetUser(void);
/**
- * @}
- */
+ * @}
+ */
/* Exported functions ---------------------------------------------------------*/
/** @defgroup FLASHEx_Exported_Functions FLASHEx Exported Functions
- * @{
- */
-
+ * @{
+ */
+
/** @defgroup FLASHEx_Exported_Functions_Group1 FLASHEx Memory Erasing functions
* @brief FLASH Memory Erasing functions
*
-@verbatim
+@verbatim
==============================================================================
- ##### FLASH Erasing Programming functions #####
+ ##### FLASH Erasing Programming functions #####
==============================================================================
[..] The FLASH Memory Erasing functions, includes the following functions:
(+) @ref HAL_FLASHEx_Erase: return only when erase has been done
- (+) @ref HAL_FLASHEx_Erase_IT: end of erase is done when @ref HAL_FLASH_EndOfOperationCallback
+ (+) @ref HAL_FLASHEx_Erase_IT: end of erase is done when @ref HAL_FLASH_EndOfOperationCallback
is called with parameter 0xFFFFFFFF
[..] Any operation of erase should follow these steps:
- (#) Call the @ref HAL_FLASH_Unlock() function to enable the flash control register and
+ (#) Call the @ref HAL_FLASH_Unlock() function to enable the flash control register and
program memory access.
(#) Call the desired function to erase page.
- (#) Call the @ref HAL_FLASH_Lock() to disable the flash program memory access
+ (#) Call the @ref HAL_FLASH_Lock() to disable the flash program memory access
(recommended to protect the FLASH memory against possible unwanted operation).
@endverbatim
* @{
*/
-
/**
- * @brief Perform a mass erase or erase the specified FLASH memory pages
- * @note To correctly run this function, the @ref HAL_FLASH_Unlock() function
- * must be called before.
- * Call the @ref HAL_FLASH_Lock() to disable the flash memory access
- * (recommended to protect the FLASH memory against possible unwanted operation)
- * @param[in] pEraseInit pointer to an FLASH_EraseInitTypeDef structure that
- * contains the configuration information for the erasing.
- *
- * @param[out] PageError pointer to variable that
- * contains the configuration information on faulty page in case of error
- * (0xFFFFFFFF means that all the pages have been correctly erased)
- *
- * @retval HAL_StatusTypeDef HAL Status
- */
-HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError)
-{
- HAL_StatusTypeDef status = HAL_ERROR;
- uint32_t address = 0U;
+ * @brief Perform a mass erase or erase the specified FLASH memory pages
+ * @note To correctly run this function, the @ref HAL_FLASH_Unlock() function
+ * must be called before.
+ * Call the @ref HAL_FLASH_Lock() to disable the flash memory access
+ * (recommended to protect the FLASH memory against possible unwanted operation)
+ * @param[in] pEraseInit pointer to an FLASH_EraseInitTypeDef structure that
+ * contains the configuration information for the erasing.
+ *
+ * @param[out] PageError pointer to variable that
+ * contains the configuration information on faulty page in case of error
+ * (0xFFFFFFFF means that all the pages have been correctly erased)
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError) {
+ HAL_StatusTypeDef status = HAL_ERROR;
+ uint32_t address = 0U;
/* Process Locked */
__HAL_LOCK(&pFlash);
@@ -183,129 +181,104 @@ HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t
/* Check the parameters */
assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase));
- if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE)
- {
+ if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) {
#if defined(FLASH_BANK2_END)
- if (pEraseInit->Banks == FLASH_BANK_BOTH)
- {
+ if (pEraseInit->Banks == FLASH_BANK_BOTH) {
/* Mass Erase requested for Bank1 and Bank2 */
/* Wait for last operation to be completed */
- if ((FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK) && \
- (FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK))
- {
+ if ((FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK) && (FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK)) {
/*Mass erase to be done*/
FLASH_MassErase(FLASH_BANK_BOTH);
-
+
/* Wait for last operation to be completed */
- if ((FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK) && \
- (FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK))
- {
+ if ((FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK) && (FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK)) {
status = HAL_OK;
}
-
+
/* If the erase operation is completed, disable the MER Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_MER);
CLEAR_BIT(FLASH->CR2, FLASH_CR2_MER);
}
- }
- else if (pEraseInit->Banks == FLASH_BANK_2)
- {
+ } else if (pEraseInit->Banks == FLASH_BANK_2) {
/* Mass Erase requested for Bank2 */
/* Wait for last operation to be completed */
- if (FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK)
- {
+ if (FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK) {
/*Mass erase to be done*/
FLASH_MassErase(FLASH_BANK_2);
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE);
-
+
/* If the erase operation is completed, disable the MER Bit */
CLEAR_BIT(FLASH->CR2, FLASH_CR2_MER);
}
- }
- else
+ } else
#endif /* FLASH_BANK2_END */
{
/* Mass Erase requested for Bank1 */
/* Wait for last operation to be completed */
- if (FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK)
- {
+ if (FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK) {
/*Mass erase to be done*/
FLASH_MassErase(FLASH_BANK_1);
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
-
+
/* If the erase operation is completed, disable the MER Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_MER);
}
}
- }
- else
- {
+ } else {
/* Page Erase is requested */
/* Check the parameters */
assert_param(IS_FLASH_PROGRAM_ADDRESS(pEraseInit->PageAddress));
assert_param(IS_FLASH_NB_PAGES(pEraseInit->PageAddress, pEraseInit->NbPages));
-
+
#if defined(FLASH_BANK2_END)
/* Page Erase requested on address located on bank2 */
- if(pEraseInit->PageAddress > FLASH_BANK1_END)
- {
+ if (pEraseInit->PageAddress > FLASH_BANK1_END) {
/* Wait for last operation to be completed */
- if (FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK)
- {
+ if (FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK) {
/*Initialization of PageError variable*/
*PageError = 0xFFFFFFFFU;
-
+
/* Erase by page by page to be done*/
- for(address = pEraseInit->PageAddress;
- address < (pEraseInit->PageAddress + (pEraseInit->NbPages)*FLASH_PAGE_SIZE);
- address += FLASH_PAGE_SIZE)
- {
+ for (address = pEraseInit->PageAddress; address < (pEraseInit->PageAddress + (pEraseInit->NbPages) * FLASH_PAGE_SIZE); address += FLASH_PAGE_SIZE) {
FLASH_PageErase(address);
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperationBank2((uint32_t)FLASH_TIMEOUT_VALUE);
-
+
/* If the erase operation is completed, disable the PER Bit */
CLEAR_BIT(FLASH->CR2, FLASH_CR2_PER);
-
- if (status != HAL_OK)
- {
+
+ if (status != HAL_OK) {
/* In case of error, stop erase procedure and return the faulty address */
*PageError = address;
break;
}
}
}
- }
- else
+ } else
#endif /* FLASH_BANK2_END */
- {
+ {
/* Page Erase requested on address located on bank1 */
/* Wait for last operation to be completed */
- if (FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK)
- {
+ if (FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE) == HAL_OK) {
/*Initialization of PageError variable*/
*PageError = 0xFFFFFFFFU;
-
+
/* Erase page by page to be done*/
- for(address = pEraseInit->PageAddress;
- address < ((pEraseInit->NbPages * FLASH_PAGE_SIZE) + pEraseInit->PageAddress);
- address += FLASH_PAGE_SIZE)
- {
+ for (address = pEraseInit->PageAddress; address < ((pEraseInit->NbPages * FLASH_PAGE_SIZE) + pEraseInit->PageAddress); address += FLASH_PAGE_SIZE) {
FLASH_PageErase(address);
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
-
+
/* If the erase operation is completed, disable the PER Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_PER);
-
- if (status != HAL_OK)
- {
+
+ if (status != HAL_OK) {
/* In case of error, stop erase procedure and return the faulty address */
*PageError = address;
break;
@@ -322,29 +295,27 @@ HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t
}
/**
- * @brief Perform a mass erase or erase the specified FLASH memory pages with interrupt enabled
- * @note To correctly run this function, the @ref HAL_FLASH_Unlock() function
- * must be called before.
- * Call the @ref HAL_FLASH_Lock() to disable the flash memory access
- * (recommended to protect the FLASH memory against possible unwanted operation)
- * @param pEraseInit pointer to an FLASH_EraseInitTypeDef structure that
- * contains the configuration information for the erasing.
- *
- * @retval HAL_StatusTypeDef HAL Status
- */
-HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit)
-{
+ * @brief Perform a mass erase or erase the specified FLASH memory pages with interrupt enabled
+ * @note To correctly run this function, the @ref HAL_FLASH_Unlock() function
+ * must be called before.
+ * Call the @ref HAL_FLASH_Lock() to disable the flash memory access
+ * (recommended to protect the FLASH memory against possible unwanted operation)
+ * @param pEraseInit pointer to an FLASH_EraseInitTypeDef structure that
+ * contains the configuration information for the erasing.
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit) {
HAL_StatusTypeDef status = HAL_OK;
/* Process Locked */
__HAL_LOCK(&pFlash);
/* If procedure already ongoing, reject the next one */
- if (pFlash.ProcedureOnGoing != FLASH_PROC_NONE)
- {
+ if (pFlash.ProcedureOnGoing != FLASH_PROC_NONE) {
return HAL_ERROR;
}
-
+
/* Check the parameters */
assert_param(IS_FLASH_TYPEERASE(pEraseInit->TypeErase));
@@ -354,16 +325,13 @@ HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit)
#if defined(FLASH_BANK2_END)
/* Enable End of FLASH Operation and Error source interrupts */
__HAL_FLASH_ENABLE_IT(FLASH_IT_EOP_BANK2 | FLASH_IT_ERR_BANK2);
-
+
#endif
- if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE)
- {
+ if (pEraseInit->TypeErase == FLASH_TYPEERASE_MASSERASE) {
/*Mass erase to be done*/
pFlash.ProcedureOnGoing = FLASH_PROC_MASSERASE;
- FLASH_MassErase(pEraseInit->Banks);
- }
- else
- {
+ FLASH_MassErase(pEraseInit->Banks);
+ } else {
/* Erase by page to be done*/
/* Check the parameters */
@@ -371,8 +339,8 @@ HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit)
assert_param(IS_FLASH_NB_PAGES(pEraseInit->PageAddress, pEraseInit->NbPages));
pFlash.ProcedureOnGoing = FLASH_PROC_PAGEERASE;
- pFlash.DataRemaining = pEraseInit->NbPages;
- pFlash.Address = pEraseInit->PageAddress;
+ pFlash.DataRemaining = pEraseInit->NbPages;
+ pFlash.Address = pEraseInit->PageAddress;
/*Erase 1st page and wait for IT*/
FLASH_PageErase(pEraseInit->PageAddress);
@@ -382,18 +350,18 @@ HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit)
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup FLASHEx_Exported_Functions_Group2 Option Bytes Programming functions
* @brief Option Bytes Programming functions
*
-@verbatim
+@verbatim
+ ==============================================================================
+ ##### Option Bytes Programming functions #####
==============================================================================
- ##### Option Bytes Programming functions #####
- ==============================================================================
[..]
- This subsection provides a set of functions allowing to control the FLASH
+ This subsection provides a set of functions allowing to control the FLASH
option bytes operations.
@endverbatim
@@ -401,18 +369,17 @@ HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit)
*/
/**
- * @brief Erases the FLASH option bytes.
- * @note This functions erases all option bytes except the Read protection (RDP).
- * The function @ref HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
- * The function @ref HAL_FLASH_OB_Unlock() should be called before to unlock the options bytes
- * The function @ref HAL_FLASH_OB_Launch() should be called after to force the reload of the options bytes
- * (system reset will occur)
- * @retval HAL status
- */
+ * @brief Erases the FLASH option bytes.
+ * @note This functions erases all option bytes except the Read protection (RDP).
+ * The function @ref HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
+ * The function @ref HAL_FLASH_OB_Unlock() should be called before to unlock the options bytes
+ * The function @ref HAL_FLASH_OB_Launch() should be called after to force the reload of the options bytes
+ * (system reset will occur)
+ * @retval HAL status
+ */
-HAL_StatusTypeDef HAL_FLASHEx_OBErase(void)
-{
- uint8_t rdptmp = OB_RDP_LEVEL_0;
+HAL_StatusTypeDef HAL_FLASHEx_OBErase(void) {
+ uint8_t rdptmp = OB_RDP_LEVEL_0;
HAL_StatusTypeDef status = HAL_ERROR;
/* Get the actual read protection Option Byte value */
@@ -421,8 +388,7 @@ HAL_StatusTypeDef HAL_FLASHEx_OBErase(void)
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
- if(status == HAL_OK)
- {
+ if (status == HAL_OK) {
/* Clean the error context */
pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
@@ -436,8 +402,7 @@ HAL_StatusTypeDef HAL_FLASHEx_OBErase(void)
/* If the erase operation is completed, disable the OPTER Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_OPTER);
- if(status == HAL_OK)
- {
+ if (status == HAL_OK) {
/* Restore the last read protection Option Byte value */
status = FLASH_OB_RDP_LevelConfig(rdptmp);
}
@@ -448,19 +413,18 @@ HAL_StatusTypeDef HAL_FLASHEx_OBErase(void)
}
/**
- * @brief Program option bytes
- * @note The function @ref HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
- * The function @ref HAL_FLASH_OB_Unlock() should be called before to unlock the options bytes
- * The function @ref HAL_FLASH_OB_Launch() should be called after to force the reload of the options bytes
- * (system reset will occur)
- *
- * @param pOBInit pointer to an FLASH_OBInitStruct structure that
- * contains the configuration information for the programming.
- *
- * @retval HAL_StatusTypeDef HAL Status
- */
-HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit)
-{
+ * @brief Program option bytes
+ * @note The function @ref HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
+ * The function @ref HAL_FLASH_OB_Unlock() should be called before to unlock the options bytes
+ * The function @ref HAL_FLASH_OB_Launch() should be called after to force the reload of the options bytes
+ * (system reset will occur)
+ *
+ * @param pOBInit pointer to an FLASH_OBInitStruct structure that
+ * contains the configuration information for the programming.
+ *
+ * @retval HAL_StatusTypeDef HAL Status
+ */
+HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit) {
HAL_StatusTypeDef status = HAL_ERROR;
/* Process Locked */
@@ -470,21 +434,16 @@ HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit)
assert_param(IS_OPTIONBYTE(pOBInit->OptionType));
/* Write protection configuration */
- if((pOBInit->OptionType & OPTIONBYTE_WRP) == OPTIONBYTE_WRP)
- {
+ if ((pOBInit->OptionType & OPTIONBYTE_WRP) == OPTIONBYTE_WRP) {
assert_param(IS_WRPSTATE(pOBInit->WRPState));
- if (pOBInit->WRPState == OB_WRPSTATE_ENABLE)
- {
+ if (pOBInit->WRPState == OB_WRPSTATE_ENABLE) {
/* Enable of Write protection on the selected page */
status = FLASH_OB_EnableWRP(pOBInit->WRPPage);
- }
- else
- {
+ } else {
/* Disable of Write protection on the selected page */
status = FLASH_OB_DisableWRP(pOBInit->WRPPage);
}
- if (status != HAL_OK)
- {
+ if (status != HAL_OK) {
/* Process Unlocked */
__HAL_UNLOCK(&pFlash);
return status;
@@ -492,11 +451,9 @@ HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit)
}
/* Read protection configuration */
- if((pOBInit->OptionType & OPTIONBYTE_RDP) == OPTIONBYTE_RDP)
- {
+ if ((pOBInit->OptionType & OPTIONBYTE_RDP) == OPTIONBYTE_RDP) {
status = FLASH_OB_RDP_LevelConfig(pOBInit->RDPLevel);
- if (status != HAL_OK)
- {
+ if (status != HAL_OK) {
/* Process Unlocked */
__HAL_UNLOCK(&pFlash);
return status;
@@ -504,11 +461,9 @@ HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit)
}
/* USER configuration */
- if((pOBInit->OptionType & OPTIONBYTE_USER) == OPTIONBYTE_USER)
- {
+ if ((pOBInit->OptionType & OPTIONBYTE_USER) == OPTIONBYTE_USER) {
status = FLASH_OB_UserConfig(pOBInit->USERConfig);
- if (status != HAL_OK)
- {
+ if (status != HAL_OK) {
/* Process Unlocked */
__HAL_UNLOCK(&pFlash);
return status;
@@ -516,11 +471,9 @@ HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit)
}
/* DATA configuration*/
- if((pOBInit->OptionType & OPTIONBYTE_DATA) == OPTIONBYTE_DATA)
- {
+ if ((pOBInit->OptionType & OPTIONBYTE_DATA) == OPTIONBYTE_DATA) {
status = FLASH_OB_ProgramData(pOBInit->DATAAddress, pOBInit->DATAData);
- if (status != HAL_OK)
- {
+ if (status != HAL_OK) {
/* Process Unlocked */
__HAL_UNLOCK(&pFlash);
return status;
@@ -534,14 +487,13 @@ HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit)
}
/**
- * @brief Get the Option byte configuration
- * @param pOBInit pointer to an FLASH_OBInitStruct structure that
- * contains the configuration information for the programming.
- *
- * @retval None
- */
-void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit)
-{
+ * @brief Get the Option byte configuration
+ * @param pOBInit pointer to an FLASH_OBInitStruct structure that
+ * contains the configuration information for the programming.
+ *
+ * @retval None
+ */
+void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit) {
pOBInit->OptionType = OPTIONBYTE_WRP | OPTIONBYTE_RDP | OPTIONBYTE_USER;
/*Get WRP*/
@@ -555,45 +507,41 @@ void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit)
}
/**
- * @brief Get the Option byte user data
- * @param DATAAdress Address of the option byte DATA
- * This parameter can be one of the following values:
- * @arg @ref OB_DATA_ADDRESS_DATA0
- * @arg @ref OB_DATA_ADDRESS_DATA1
- * @retval Value programmed in USER data
- */
-uint32_t HAL_FLASHEx_OBGetUserData(uint32_t DATAAdress)
-{
+ * @brief Get the Option byte user data
+ * @param DATAAdress Address of the option byte DATA
+ * This parameter can be one of the following values:
+ * @arg @ref OB_DATA_ADDRESS_DATA0
+ * @arg @ref OB_DATA_ADDRESS_DATA1
+ * @retval Value programmed in USER data
+ */
+uint32_t HAL_FLASHEx_OBGetUserData(uint32_t DATAAdress) {
uint32_t value = 0;
-
- if (DATAAdress == OB_DATA_ADDRESS_DATA0)
- {
+
+ if (DATAAdress == OB_DATA_ADDRESS_DATA0) {
/* Get value programmed in OB USER Data0 */
value = READ_BIT(FLASH->OBR, FLASH_OBR_DATA0) >> FLASH_POSITION_OB_USERDATA0_BIT;
- }
- else
- {
+ } else {
/* Get value programmed in OB USER Data1 */
value = READ_BIT(FLASH->OBR, FLASH_OBR_DATA1) >> FLASH_POSITION_OB_USERDATA1_BIT;
}
-
+
return value;
}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/** @addtogroup FLASHEx_Private_Functions
* @{
*/
/**
- * @brief Full erase of FLASH memory Bank
+ * @brief Full erase of FLASH memory Bank
* @param Banks Banks to be erased
* This parameter can be one of the following values:
* @arg @ref FLASH_BANK_1 Bank1 to be erased
@@ -608,8 +556,7 @@ uint32_t HAL_FLASHEx_OBGetUserData(uint32_t DATAAdress)
*
* @retval None
*/
-static void FLASH_MassErase(uint32_t Banks)
-{
+static void FLASH_MassErase(uint32_t Banks) {
/* Check the parameters */
assert_param(IS_FLASH_BANK(Banks));
@@ -617,27 +564,22 @@ static void FLASH_MassErase(uint32_t Banks)
pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
#if defined(FLASH_BANK2_END)
- if(Banks == FLASH_BANK_BOTH)
- {
+ if (Banks == FLASH_BANK_BOTH) {
/* bank1 & bank2 will be erased*/
SET_BIT(FLASH->CR, FLASH_CR_MER);
SET_BIT(FLASH->CR2, FLASH_CR2_MER);
SET_BIT(FLASH->CR, FLASH_CR_STRT);
SET_BIT(FLASH->CR2, FLASH_CR2_STRT);
- }
- else if(Banks == FLASH_BANK_2)
- {
+ } else if (Banks == FLASH_BANK_2) {
/*Only bank2 will be erased*/
SET_BIT(FLASH->CR2, FLASH_CR2_MER);
SET_BIT(FLASH->CR2, FLASH_CR2_STRT);
- }
- else
- {
+ } else {
#endif /* FLASH_BANK2_END */
#if !defined(FLASH_BANK2_END)
- /* Prevent unused argument(s) compilation warning */
- UNUSED(Banks);
-#endif /* FLASH_BANK2_END */
+ /* Prevent unused argument(s) compilation warning */
+ UNUSED(Banks);
+#endif /* FLASH_BANK2_END */
/* Only bank1 will be erased*/
SET_BIT(FLASH->CR, FLASH_CR_MER);
SET_BIT(FLASH->CR, FLASH_CR_STRT);
@@ -647,20 +589,19 @@ static void FLASH_MassErase(uint32_t Banks)
}
/**
- * @brief Enable the write protection of the desired pages
- * @note An option byte erase is done automatically in this function.
- * @note When the memory read protection level is selected (RDP level = 1),
- * it is not possible to program or erase the flash page i if
- * debug features are connected or boot code is executed in RAM, even if nWRPi = 1
- *
- * @param WriteProtectPage specifies the page(s) to be write protected.
- * The value of this parameter depend on device used within the same series
- * @retval HAL status
- */
-static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage)
-{
- HAL_StatusTypeDef status = HAL_OK;
- uint16_t WRP0_Data = 0xFFFF;
+ * @brief Enable the write protection of the desired pages
+ * @note An option byte erase is done automatically in this function.
+ * @note When the memory read protection level is selected (RDP level = 1),
+ * it is not possible to program or erase the flash page i if
+ * debug features are connected or boot code is executed in RAM, even if nWRPi = 1
+ *
+ * @param WriteProtectPage specifies the page(s) to be write protected.
+ * The value of this parameter depend on device used within the same series
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage) {
+ HAL_StatusTypeDef status = HAL_OK;
+ uint16_t WRP0_Data = 0xFFFF;
#if defined(FLASH_WRP1_WRP1)
uint16_t WRP1_Data = 0xFFFF;
#endif /* FLASH_WRP1_WRP1 */
@@ -670,25 +611,25 @@ static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage)
#if defined(FLASH_WRP3_WRP3)
uint16_t WRP3_Data = 0xFFFF;
#endif /* FLASH_WRP3_WRP3 */
-
+
/* Check the parameters */
assert_param(IS_OB_WRP(WriteProtectPage));
-
+
/* Get current write protected pages and the new pages to be protected ******/
WriteProtectPage = (uint32_t)(~((~FLASH_OB_GetWRP()) | WriteProtectPage));
-
+
#if defined(OB_WRP_PAGES0TO15MASK)
WRP0_Data = (uint16_t)(WriteProtectPage & OB_WRP_PAGES0TO15MASK);
#elif defined(OB_WRP_PAGES0TO31MASK)
WRP0_Data = (uint16_t)(WriteProtectPage & OB_WRP_PAGES0TO31MASK);
#endif /* OB_WRP_PAGES0TO31MASK */
-
+
#if defined(OB_WRP_PAGES16TO31MASK)
WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES16TO31MASK) >> 8U);
#elif defined(OB_WRP_PAGES32TO63MASK)
WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO63MASK) >> 8U);
#endif /* OB_WRP_PAGES32TO63MASK */
-
+
#if defined(OB_WRP_PAGES64TO95MASK)
WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES64TO95MASK) >> 16U);
#endif /* OB_WRP_PAGES64TO95MASK */
@@ -697,65 +638,59 @@ static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage)
#endif /* OB_WRP_PAGES32TO47MASK */
#if defined(OB_WRP_PAGES96TO127MASK)
- WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES96TO127MASK) >> 24U);
+ WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES96TO127MASK) >> 24U);
#elif defined(OB_WRP_PAGES48TO255MASK)
- WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO255MASK) >> 24U);
+ WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO255MASK) >> 24U);
#elif defined(OB_WRP_PAGES48TO511MASK)
- WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO511MASK) >> 24U);
+ WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO511MASK) >> 24U);
#elif defined(OB_WRP_PAGES48TO127MASK)
- WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO127MASK) >> 24U);
+ WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO127MASK) >> 24U);
#endif /* OB_WRP_PAGES96TO127MASK */
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
- if(status == HAL_OK)
- {
+ if (status == HAL_OK) {
/* Clean the error context */
pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
/* To be able to write again option byte, need to perform a option byte erase */
status = HAL_FLASHEx_OBErase();
- if (status == HAL_OK)
- {
+ if (status == HAL_OK) {
/* Enable write protection */
SET_BIT(FLASH->CR, FLASH_CR_OPTPG);
#if defined(FLASH_WRP0_WRP0)
- if(WRP0_Data != 0xFFU)
- {
+ if (WRP0_Data != 0xFFU) {
OB->WRP0 &= WRP0_Data;
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
}
#endif /* FLASH_WRP0_WRP0 */
#if defined(FLASH_WRP1_WRP1)
- if((status == HAL_OK) && (WRP1_Data != 0xFFU))
- {
+ if ((status == HAL_OK) && (WRP1_Data != 0xFFU)) {
OB->WRP1 &= WRP1_Data;
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
}
#endif /* FLASH_WRP1_WRP1 */
#if defined(FLASH_WRP2_WRP2)
- if((status == HAL_OK) && (WRP2_Data != 0xFFU))
- {
+ if ((status == HAL_OK) && (WRP2_Data != 0xFFU)) {
OB->WRP2 &= WRP2_Data;
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
}
#endif /* FLASH_WRP2_WRP2 */
#if defined(FLASH_WRP3_WRP3)
- if((status == HAL_OK) && (WRP3_Data != 0xFFU))
- {
+ if ((status == HAL_OK) && (WRP3_Data != 0xFFU)) {
OB->WRP3 &= WRP3_Data;
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
}
@@ -765,25 +700,24 @@ static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage)
CLEAR_BIT(FLASH->CR, FLASH_CR_OPTPG);
}
}
-
+
return status;
}
/**
- * @brief Disable the write protection of the desired pages
- * @note An option byte erase is done automatically in this function.
- * @note When the memory read protection level is selected (RDP level = 1),
- * it is not possible to program or erase the flash page i if
- * debug features are connected or boot code is executed in RAM, even if nWRPi = 1
- *
- * @param WriteProtectPage specifies the page(s) to be write unprotected.
- * The value of this parameter depend on device used within the same series
- * @retval HAL status
- */
-static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage)
-{
- HAL_StatusTypeDef status = HAL_OK;
- uint16_t WRP0_Data = 0xFFFF;
+ * @brief Disable the write protection of the desired pages
+ * @note An option byte erase is done automatically in this function.
+ * @note When the memory read protection level is selected (RDP level = 1),
+ * it is not possible to program or erase the flash page i if
+ * debug features are connected or boot code is executed in RAM, even if nWRPi = 1
+ *
+ * @param WriteProtectPage specifies the page(s) to be write unprotected.
+ * The value of this parameter depend on device used within the same series
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage) {
+ HAL_StatusTypeDef status = HAL_OK;
+ uint16_t WRP0_Data = 0xFFFF;
#if defined(FLASH_WRP1_WRP1)
uint16_t WRP1_Data = 0xFFFF;
#endif /* FLASH_WRP1_WRP1 */
@@ -793,7 +727,7 @@ static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage)
#if defined(FLASH_WRP3_WRP3)
uint16_t WRP3_Data = 0xFFFF;
#endif /* FLASH_WRP3_WRP3 */
-
+
/* Check the parameters */
assert_param(IS_OB_WRP(WriteProtectPage));
@@ -805,13 +739,13 @@ static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage)
#elif defined(OB_WRP_PAGES0TO31MASK)
WRP0_Data = (uint16_t)(WriteProtectPage & OB_WRP_PAGES0TO31MASK);
#endif /* OB_WRP_PAGES0TO31MASK */
-
+
#if defined(OB_WRP_PAGES16TO31MASK)
WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES16TO31MASK) >> 8U);
#elif defined(OB_WRP_PAGES32TO63MASK)
WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO63MASK) >> 8U);
#endif /* OB_WRP_PAGES32TO63MASK */
-
+
#if defined(OB_WRP_PAGES64TO95MASK)
WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES64TO95MASK) >> 16U);
#endif /* OB_WRP_PAGES64TO95MASK */
@@ -820,65 +754,58 @@ static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage)
#endif /* OB_WRP_PAGES32TO47MASK */
#if defined(OB_WRP_PAGES96TO127MASK)
- WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES96TO127MASK) >> 24U);
+ WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES96TO127MASK) >> 24U);
#elif defined(OB_WRP_PAGES48TO255MASK)
- WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO255MASK) >> 24U);
+ WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO255MASK) >> 24U);
#elif defined(OB_WRP_PAGES48TO511MASK)
- WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO511MASK) >> 24U);
+ WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO511MASK) >> 24U);
#elif defined(OB_WRP_PAGES48TO127MASK)
- WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO127MASK) >> 24U);
+ WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO127MASK) >> 24U);
#endif /* OB_WRP_PAGES96TO127MASK */
-
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
- if(status == HAL_OK)
- {
+ if (status == HAL_OK) {
/* Clean the error context */
pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
/* To be able to write again option byte, need to perform a option byte erase */
status = HAL_FLASHEx_OBErase();
- if (status == HAL_OK)
- {
+ if (status == HAL_OK) {
SET_BIT(FLASH->CR, FLASH_CR_OPTPG);
#if defined(FLASH_WRP0_WRP0)
- if(WRP0_Data != 0xFFU)
- {
+ if (WRP0_Data != 0xFFU) {
OB->WRP0 |= WRP0_Data;
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
}
#endif /* FLASH_WRP0_WRP0 */
#if defined(FLASH_WRP1_WRP1)
- if((status == HAL_OK) && (WRP1_Data != 0xFFU))
- {
+ if ((status == HAL_OK) && (WRP1_Data != 0xFFU)) {
OB->WRP1 |= WRP1_Data;
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
}
#endif /* FLASH_WRP1_WRP1 */
#if defined(FLASH_WRP2_WRP2)
- if((status == HAL_OK) && (WRP2_Data != 0xFFU))
- {
+ if ((status == HAL_OK) && (WRP2_Data != 0xFFU)) {
OB->WRP2 |= WRP2_Data;
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
}
#endif /* FLASH_WRP2_WRP2 */
#if defined(FLASH_WRP3_WRP3)
- if((status == HAL_OK) && (WRP3_Data != 0xFFU))
- {
+ if ((status == HAL_OK) && (WRP3_Data != 0xFFU)) {
OB->WRP3 |= WRP3_Data;
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
}
@@ -892,28 +819,26 @@ static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage)
}
/**
- * @brief Set the read protection level.
- * @param ReadProtectLevel specifies the read protection level.
- * This parameter can be one of the following values:
- * @arg @ref OB_RDP_LEVEL_0 No protection
- * @arg @ref OB_RDP_LEVEL_1 Read protection of the memory
- * @retval HAL status
- */
-static HAL_StatusTypeDef FLASH_OB_RDP_LevelConfig(uint8_t ReadProtectLevel)
-{
+ * @brief Set the read protection level.
+ * @param ReadProtectLevel specifies the read protection level.
+ * This parameter can be one of the following values:
+ * @arg @ref OB_RDP_LEVEL_0 No protection
+ * @arg @ref OB_RDP_LEVEL_1 Read protection of the memory
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef FLASH_OB_RDP_LevelConfig(uint8_t ReadProtectLevel) {
HAL_StatusTypeDef status = HAL_OK;
-
+
/* Check the parameters */
assert_param(IS_OB_RDP_LEVEL(ReadProtectLevel));
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
-
- if(status == HAL_OK)
- {
+
+ if (status == HAL_OK) {
/* Clean the error context */
pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
-
+
/* If the previous operation is completed, proceed to erase the option bytes */
SET_BIT(FLASH->CR, FLASH_CR_OPTER);
SET_BIT(FLASH->CR, FLASH_CR_STRT);
@@ -924,55 +849,52 @@ static HAL_StatusTypeDef FLASH_OB_RDP_LevelConfig(uint8_t ReadProtectLevel)
/* If the erase operation is completed, disable the OPTER Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_OPTER);
- if(status == HAL_OK)
- {
+ if (status == HAL_OK) {
/* Enable the Option Bytes Programming operation */
SET_BIT(FLASH->CR, FLASH_CR_OPTPG);
-
+
WRITE_REG(OB->RDP, ReadProtectLevel);
-
+
/* Wait for last operation to be completed */
- status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
-
+ status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
+
/* if the program operation is completed, disable the OPTPG Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_OPTPG);
}
}
-
+
return status;
}
/**
- * @brief Program the FLASH User Option Byte.
- * @note Programming of the OB should be performed only after an erase (otherwise PGERR occurs)
- * @param UserConfig The FLASH User Option Bytes values FLASH_OBR_IWDG_SW(Bit2),
- * FLASH_OBR_nRST_STOP(Bit3),FLASH_OBR_nRST_STDBY(Bit4).
- * And BFBF2(Bit5) for STM32F101xG and STM32F103xG .
- * @retval HAL status
- */
-static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t UserConfig)
-{
+ * @brief Program the FLASH User Option Byte.
+ * @note Programming of the OB should be performed only after an erase (otherwise PGERR occurs)
+ * @param UserConfig The FLASH User Option Bytes values FLASH_OBR_IWDG_SW(Bit2),
+ * FLASH_OBR_nRST_STOP(Bit3),FLASH_OBR_nRST_STDBY(Bit4).
+ * And BFBF2(Bit5) for STM32F101xG and STM32F103xG .
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t UserConfig) {
HAL_StatusTypeDef status = HAL_OK;
/* Check the parameters */
- assert_param(IS_OB_IWDG_SOURCE((UserConfig&OB_IWDG_SW)));
- assert_param(IS_OB_STOP_SOURCE((UserConfig&OB_STOP_NO_RST)));
- assert_param(IS_OB_STDBY_SOURCE((UserConfig&OB_STDBY_NO_RST)));
+ assert_param(IS_OB_IWDG_SOURCE((UserConfig & OB_IWDG_SW)));
+ assert_param(IS_OB_STOP_SOURCE((UserConfig & OB_STOP_NO_RST)));
+ assert_param(IS_OB_STDBY_SOURCE((UserConfig & OB_STDBY_NO_RST)));
#if defined(FLASH_BANK2_END)
- assert_param(IS_OB_BOOT1((UserConfig&OB_BOOT1_SET)));
+ assert_param(IS_OB_BOOT1((UserConfig & OB_BOOT1_SET)));
#endif /* FLASH_BANK2_END */
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
-
- if(status == HAL_OK)
- {
+
+ if (status == HAL_OK) {
/* Clean the error context */
pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
/* Enable the Option Bytes Programming operation */
- SET_BIT(FLASH->CR, FLASH_CR_OPTPG);
-
+ SET_BIT(FLASH->CR, FLASH_CR_OPTPG);
+
#if defined(FLASH_BANK2_END)
OB->USER = (UserConfig | 0xF0U);
#else
@@ -985,44 +907,42 @@ static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t UserConfig)
/* if the program operation is completed, disable the OPTPG Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_OPTPG);
}
-
- return status;
+
+ return status;
}
/**
- * @brief Programs a half word at a specified Option Byte Data address.
- * @note The function @ref HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
- * The function @ref HAL_FLASH_OB_Unlock() should be called before to unlock the options bytes
- * The function @ref HAL_FLASH_OB_Launch() should be called after to force the reload of the options bytes
- * (system reset will occur)
- * Programming of the OB should be performed only after an erase (otherwise PGERR occurs)
- * @param Address specifies the address to be programmed.
- * This parameter can be 0x1FFFF804 or 0x1FFFF806.
- * @param Data specifies the data to be programmed.
- * @retval HAL status
- */
-static HAL_StatusTypeDef FLASH_OB_ProgramData(uint32_t Address, uint8_t Data)
-{
+ * @brief Programs a half word at a specified Option Byte Data address.
+ * @note The function @ref HAL_FLASH_Unlock() should be called before to unlock the FLASH interface
+ * The function @ref HAL_FLASH_OB_Unlock() should be called before to unlock the options bytes
+ * The function @ref HAL_FLASH_OB_Launch() should be called after to force the reload of the options bytes
+ * (system reset will occur)
+ * Programming of the OB should be performed only after an erase (otherwise PGERR occurs)
+ * @param Address specifies the address to be programmed.
+ * This parameter can be 0x1FFFF804 or 0x1FFFF806.
+ * @param Data specifies the data to be programmed.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef FLASH_OB_ProgramData(uint32_t Address, uint8_t Data) {
HAL_StatusTypeDef status = HAL_ERROR;
-
+
/* Check the parameters */
assert_param(IS_OB_DATA_ADDRESS(Address));
-
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
-
- if(status == HAL_OK)
- {
+
+ if (status == HAL_OK) {
/* Clean the error context */
pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
/* Enables the Option Bytes Programming operation */
- SET_BIT(FLASH->CR, FLASH_CR_OPTPG);
- *(__IO uint16_t*)Address = Data;
-
+ SET_BIT(FLASH->CR, FLASH_CR_OPTPG);
+ *(__IO uint16_t *)Address = Data;
+
/* Wait for last operation to be completed */
status = FLASH_WaitForLastOperation((uint32_t)FLASH_TIMEOUT_VALUE);
-
+
/* If the program operation is completed, disable the OPTPG Bit */
CLEAR_BIT(FLASH->CR, FLASH_CR_OPTPG);
}
@@ -1031,36 +951,31 @@ static HAL_StatusTypeDef FLASH_OB_ProgramData(uint32_t Address, uint8_t Data)
}
/**
- * @brief Return the FLASH Write Protection Option Bytes value.
- * @retval The FLASH Write Protection Option Bytes value
- */
-static uint32_t FLASH_OB_GetWRP(void)
-{
+ * @brief Return the FLASH Write Protection Option Bytes value.
+ * @retval The FLASH Write Protection Option Bytes value
+ */
+static uint32_t FLASH_OB_GetWRP(void) {
/* Return the FLASH write protection Register value */
return (uint32_t)(READ_REG(FLASH->WRPR));
}
/**
- * @brief Returns the FLASH Read Protection level.
- * @retval FLASH RDP level
- * This parameter can be one of the following values:
- * @arg @ref OB_RDP_LEVEL_0 No protection
- * @arg @ref OB_RDP_LEVEL_1 Read protection of the memory
- */
-static uint32_t FLASH_OB_GetRDP(void)
-{
+ * @brief Returns the FLASH Read Protection level.
+ * @retval FLASH RDP level
+ * This parameter can be one of the following values:
+ * @arg @ref OB_RDP_LEVEL_0 No protection
+ * @arg @ref OB_RDP_LEVEL_1 Read protection of the memory
+ */
+static uint32_t FLASH_OB_GetRDP(void) {
uint32_t readstatus = OB_RDP_LEVEL_0;
- uint32_t tmp_reg = 0U;
-
+ uint32_t tmp_reg = 0U;
+
/* Read RDP level bits */
tmp_reg = READ_BIT(FLASH->OBR, FLASH_OBR_RDPRT);
- if (tmp_reg == FLASH_OBR_RDPRT)
- {
+ if (tmp_reg == FLASH_OBR_RDPRT) {
readstatus = OB_RDP_LEVEL_1;
- }
- else
- {
+ } else {
readstatus = OB_RDP_LEVEL_0;
}
@@ -1068,55 +983,50 @@ static uint32_t FLASH_OB_GetRDP(void)
}
/**
- * @brief Return the FLASH User Option Byte value.
- * @retval The FLASH User Option Bytes values: FLASH_OBR_IWDG_SW(Bit2),
- * FLASH_OBR_nRST_STOP(Bit3),FLASH_OBR_nRST_STDBY(Bit4).
- * And FLASH_OBR_BFB2(Bit5) for STM32F101xG and STM32F103xG .
- */
-static uint8_t FLASH_OB_GetUser(void)
-{
+ * @brief Return the FLASH User Option Byte value.
+ * @retval The FLASH User Option Bytes values: FLASH_OBR_IWDG_SW(Bit2),
+ * FLASH_OBR_nRST_STOP(Bit3),FLASH_OBR_nRST_STDBY(Bit4).
+ * And FLASH_OBR_BFB2(Bit5) for STM32F101xG and STM32F103xG .
+ */
+static uint8_t FLASH_OB_GetUser(void) {
/* Return the User Option Byte */
return (uint8_t)((READ_REG(FLASH->OBR) & FLASH_OBR_USER) >> FLASH_POSITION_IWDGSW_BIT);
}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/** @addtogroup FLASH
- * @{
- */
+ * @{
+ */
/** @addtogroup FLASH_Private_Functions
* @{
*/
/**
- * @brief Erase the specified FLASH memory page
- * @param PageAddress FLASH page to erase
- * The value of this parameter depend on device used within the same series
- *
- * @retval None
- */
-void FLASH_PageErase(uint32_t PageAddress)
-{
+ * @brief Erase the specified FLASH memory page
+ * @param PageAddress FLASH page to erase
+ * The value of this parameter depend on device used within the same series
+ *
+ * @retval None
+ */
+void FLASH_PageErase(uint32_t PageAddress) {
/* Clean the error context */
pFlash.ErrorCode = HAL_FLASH_ERROR_NONE;
#if defined(FLASH_BANK2_END)
- if(PageAddress > FLASH_BANK1_END)
- {
+ if (PageAddress > FLASH_BANK1_END) {
/* Proceed to erase the page */
SET_BIT(FLASH->CR2, FLASH_CR2_PER);
WRITE_REG(FLASH->AR2, PageAddress);
SET_BIT(FLASH->CR2, FLASH_CR2_STRT);
- }
- else
- {
+ } else {
#endif /* FLASH_BANK2_END */
/* Proceed to erase the page */
SET_BIT(FLASH->CR, FLASH_CR_PER);
@@ -1128,16 +1038,16 @@ void FLASH_PageErase(uint32_t PageAddress)
}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_FLASH_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio.c
index 2d569515..0dd8003c 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio.c
@@ -121,52 +121,52 @@
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup GPIO GPIO
- * @brief GPIO HAL module driver
- * @{
- */
+ * @brief GPIO HAL module driver
+ * @{
+ */
#ifdef HAL_GPIO_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup GPIO_Private_Constants GPIO Private Constants
- * @{
- */
-#define GPIO_MODE 0x00000003U
-#define EXTI_MODE 0x10000000U
-#define GPIO_MODE_IT 0x00010000U
-#define GPIO_MODE_EVT 0x00020000U
-#define RISING_EDGE 0x00100000U
-#define FALLING_EDGE 0x00200000U
-#define GPIO_OUTPUT_TYPE 0x00000010U
-
-#define GPIO_NUMBER 16U
+ * @{
+ */
+#define GPIO_MODE 0x00000003U
+#define EXTI_MODE 0x10000000U
+#define GPIO_MODE_IT 0x00010000U
+#define GPIO_MODE_EVT 0x00020000U
+#define RISING_EDGE 0x00100000U
+#define FALLING_EDGE 0x00200000U
+#define GPIO_OUTPUT_TYPE 0x00000010U
+
+#define GPIO_NUMBER 16U
/* Definitions for bit manipulation of CRL and CRH register */
-#define GPIO_CR_MODE_INPUT 0x00000000U /*!< 00: Input mode (reset state) */
-#define GPIO_CR_CNF_ANALOG 0x00000000U /*!< 00: Analog mode */
-#define GPIO_CR_CNF_INPUT_FLOATING 0x00000004U /*!< 01: Floating input (reset state) */
-#define GPIO_CR_CNF_INPUT_PU_PD 0x00000008U /*!< 10: Input with pull-up / pull-down */
-#define GPIO_CR_CNF_GP_OUTPUT_PP 0x00000000U /*!< 00: General purpose output push-pull */
-#define GPIO_CR_CNF_GP_OUTPUT_OD 0x00000004U /*!< 01: General purpose output Open-drain */
-#define GPIO_CR_CNF_AF_OUTPUT_PP 0x00000008U /*!< 10: Alternate function output Push-pull */
-#define GPIO_CR_CNF_AF_OUTPUT_OD 0x0000000CU /*!< 11: Alternate function output Open-drain */
+#define GPIO_CR_MODE_INPUT 0x00000000U /*!< 00: Input mode (reset state) */
+#define GPIO_CR_CNF_ANALOG 0x00000000U /*!< 00: Analog mode */
+#define GPIO_CR_CNF_INPUT_FLOATING 0x00000004U /*!< 01: Floating input (reset state) */
+#define GPIO_CR_CNF_INPUT_PU_PD 0x00000008U /*!< 10: Input with pull-up / pull-down */
+#define GPIO_CR_CNF_GP_OUTPUT_PP 0x00000000U /*!< 00: General purpose output push-pull */
+#define GPIO_CR_CNF_GP_OUTPUT_OD 0x00000004U /*!< 01: General purpose output Open-drain */
+#define GPIO_CR_CNF_AF_OUTPUT_PP 0x00000008U /*!< 10: Alternate function output Push-pull */
+#define GPIO_CR_CNF_AF_OUTPUT_OD 0x0000000CU /*!< 11: Alternate function output Open-drain */
/**
- * @}
- */
+ * @}
+ */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/** @defgroup GPIO_Exported_Functions GPIO Exported Functions
- * @{
- */
+ * @{
+ */
/** @defgroup GPIO_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
@@ -183,23 +183,21 @@
* @{
*/
-
/**
- * @brief Initializes the GPIOx peripheral according to the specified parameters in the GPIO_Init.
- * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
- * @param GPIO_Init: pointer to a GPIO_InitTypeDef structure that contains
- * the configuration information for the specified GPIO peripheral.
- * @retval None
- */
-void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init)
-{
+ * @brief Initializes the GPIOx peripheral according to the specified parameters in the GPIO_Init.
+ * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
+ * @param GPIO_Init: pointer to a GPIO_InitTypeDef structure that contains
+ * the configuration information for the specified GPIO peripheral.
+ * @retval None
+ */
+void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) {
uint32_t position;
uint32_t ioposition = 0x00U;
- uint32_t iocurrent = 0x00U;
- uint32_t temp = 0x00U;
- uint32_t config = 0x00U;
- __IO uint32_t *configregister; /* Store the address of CRL or CRH register based on pin number */
- uint32_t registeroffset = 0U; /* offset used during computation of CNF and MODE bits placement inside CRL or CRH register */
+ uint32_t iocurrent = 0x00U;
+ uint32_t temp = 0x00U;
+ uint32_t config = 0x00U;
+ __IO uint32_t *configregister; /* Store the address of CRL or CRH register based on pin number */
+ uint32_t registeroffset = 0U; /* offset used during computation of CNF and MODE bits placement inside CRL or CRH register */
/* Check the parameters */
assert_param(IS_GPIO_ALL_INSTANCE(GPIOx));
@@ -207,93 +205,86 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init)
assert_param(IS_GPIO_MODE(GPIO_Init->Mode));
/* Configure the port pins */
- for (position = 0U; position < GPIO_NUMBER; position++)
- {
+ for (position = 0U; position < GPIO_NUMBER; position++) {
/* Get the IO position */
ioposition = (0x01U << position);
/* Get the current IO position */
iocurrent = (uint32_t)(GPIO_Init->Pin) & ioposition;
- if (iocurrent == ioposition)
- {
+ if (iocurrent == ioposition) {
/* Check the Alternate function parameters */
assert_param(IS_GPIO_AF_INSTANCE(GPIOx));
/* Based on the required mode, filling config variable with MODEy[1:0] and CNFy[3:2] corresponding bits */
- switch (GPIO_Init->Mode)
- {
- /* If we are configuring the pin in OUTPUT push-pull mode */
- case GPIO_MODE_OUTPUT_PP:
- /* Check the GPIO speed parameter */
- assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
- config = GPIO_Init->Speed + GPIO_CR_CNF_GP_OUTPUT_PP;
- break;
-
- /* If we are configuring the pin in OUTPUT open-drain mode */
- case GPIO_MODE_OUTPUT_OD:
- /* Check the GPIO speed parameter */
- assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
- config = GPIO_Init->Speed + GPIO_CR_CNF_GP_OUTPUT_OD;
- break;
-
- /* If we are configuring the pin in ALTERNATE FUNCTION push-pull mode */
- case GPIO_MODE_AF_PP:
- /* Check the GPIO speed parameter */
- assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
- config = GPIO_Init->Speed + GPIO_CR_CNF_AF_OUTPUT_PP;
- break;
-
- /* If we are configuring the pin in ALTERNATE FUNCTION open-drain mode */
- case GPIO_MODE_AF_OD:
- /* Check the GPIO speed parameter */
- assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
- config = GPIO_Init->Speed + GPIO_CR_CNF_AF_OUTPUT_OD;
- break;
-
- /* If we are configuring the pin in INPUT (also applicable to EVENT and IT mode) */
- case GPIO_MODE_INPUT:
- case GPIO_MODE_IT_RISING:
- case GPIO_MODE_IT_FALLING:
- case GPIO_MODE_IT_RISING_FALLING:
- case GPIO_MODE_EVT_RISING:
- case GPIO_MODE_EVT_FALLING:
- case GPIO_MODE_EVT_RISING_FALLING:
- /* Check the GPIO pull parameter */
- assert_param(IS_GPIO_PULL(GPIO_Init->Pull));
- if (GPIO_Init->Pull == GPIO_NOPULL)
- {
- config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_INPUT_FLOATING;
- }
- else if (GPIO_Init->Pull == GPIO_PULLUP)
- {
- config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_INPUT_PU_PD;
-
- /* Set the corresponding ODR bit */
- GPIOx->BSRR = ioposition;
- }
- else /* GPIO_PULLDOWN */
- {
- config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_INPUT_PU_PD;
-
- /* Reset the corresponding ODR bit */
- GPIOx->BRR = ioposition;
- }
- break;
-
- /* If we are configuring the pin in INPUT analog mode */
- case GPIO_MODE_ANALOG:
- config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_ANALOG;
- break;
-
- /* Parameters are checked with assert_param */
- default:
- break;
+ switch (GPIO_Init->Mode) {
+ /* If we are configuring the pin in OUTPUT push-pull mode */
+ case GPIO_MODE_OUTPUT_PP:
+ /* Check the GPIO speed parameter */
+ assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
+ config = GPIO_Init->Speed + GPIO_CR_CNF_GP_OUTPUT_PP;
+ break;
+
+ /* If we are configuring the pin in OUTPUT open-drain mode */
+ case GPIO_MODE_OUTPUT_OD:
+ /* Check the GPIO speed parameter */
+ assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
+ config = GPIO_Init->Speed + GPIO_CR_CNF_GP_OUTPUT_OD;
+ break;
+
+ /* If we are configuring the pin in ALTERNATE FUNCTION push-pull mode */
+ case GPIO_MODE_AF_PP:
+ /* Check the GPIO speed parameter */
+ assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
+ config = GPIO_Init->Speed + GPIO_CR_CNF_AF_OUTPUT_PP;
+ break;
+
+ /* If we are configuring the pin in ALTERNATE FUNCTION open-drain mode */
+ case GPIO_MODE_AF_OD:
+ /* Check the GPIO speed parameter */
+ assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
+ config = GPIO_Init->Speed + GPIO_CR_CNF_AF_OUTPUT_OD;
+ break;
+
+ /* If we are configuring the pin in INPUT (also applicable to EVENT and IT mode) */
+ case GPIO_MODE_INPUT:
+ case GPIO_MODE_IT_RISING:
+ case GPIO_MODE_IT_FALLING:
+ case GPIO_MODE_IT_RISING_FALLING:
+ case GPIO_MODE_EVT_RISING:
+ case GPIO_MODE_EVT_FALLING:
+ case GPIO_MODE_EVT_RISING_FALLING:
+ /* Check the GPIO pull parameter */
+ assert_param(IS_GPIO_PULL(GPIO_Init->Pull));
+ if (GPIO_Init->Pull == GPIO_NOPULL) {
+ config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_INPUT_FLOATING;
+ } else if (GPIO_Init->Pull == GPIO_PULLUP) {
+ config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_INPUT_PU_PD;
+
+ /* Set the corresponding ODR bit */
+ GPIOx->BSRR = ioposition;
+ } else /* GPIO_PULLDOWN */
+ {
+ config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_INPUT_PU_PD;
+
+ /* Reset the corresponding ODR bit */
+ GPIOx->BRR = ioposition;
+ }
+ break;
+
+ /* If we are configuring the pin in INPUT analog mode */
+ case GPIO_MODE_ANALOG:
+ config = GPIO_CR_MODE_INPUT + GPIO_CR_CNF_ANALOG;
+ break;
+
+ /* Parameters are checked with assert_param */
+ default:
+ break;
}
/* Check if the current bit belongs to first half or last half of the pin count number
in order to address CRH or CRL register*/
- configregister = (iocurrent < GPIO_PIN_8) ? &GPIOx->CRL : &GPIOx->CRH;
+ configregister = (iocurrent < GPIO_PIN_8) ? &GPIOx->CRL : &GPIOx->CRH;
registeroffset = (iocurrent < GPIO_PIN_8) ? (position << 2U) : ((position - 8U) << 2U);
/* Apply the new configuration of the pin to the register */
@@ -301,8 +292,7 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init)
/*--------------------- EXTI Mode Configuration ------------------------*/
/* Configure the External Interrupt or event for the current IO */
- if ((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE)
- {
+ if ((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE) {
/* Enable AFIO Clock */
__HAL_RCC_AFIO_CLK_ENABLE();
temp = AFIO->EXTICR[position >> 2U];
@@ -310,44 +300,31 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init)
SET_BIT(temp, (GPIO_GET_INDEX(GPIOx)) << (4U * (position & 0x03U)));
AFIO->EXTICR[position >> 2U] = temp;
-
/* Configure the interrupt mask */
- if ((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT)
- {
+ if ((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT) {
SET_BIT(EXTI->IMR, iocurrent);
- }
- else
- {
+ } else {
CLEAR_BIT(EXTI->IMR, iocurrent);
}
/* Configure the event mask */
- if ((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT)
- {
+ if ((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT) {
SET_BIT(EXTI->EMR, iocurrent);
- }
- else
- {
+ } else {
CLEAR_BIT(EXTI->EMR, iocurrent);
}
/* Enable or disable the rising trigger */
- if ((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE)
- {
+ if ((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE) {
SET_BIT(EXTI->RTSR, iocurrent);
- }
- else
- {
+ } else {
CLEAR_BIT(EXTI->RTSR, iocurrent);
}
/* Enable or disable the falling trigger */
- if ((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE)
- {
+ if ((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE) {
SET_BIT(EXTI->FTSR, iocurrent);
- }
- else
- {
+ } else {
CLEAR_BIT(EXTI->FTSR, iocurrent);
}
}
@@ -356,36 +333,33 @@ void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init)
}
/**
- * @brief De-initializes the GPIOx peripheral registers to their default reset values.
- * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
- * @param GPIO_Pin: specifies the port bit to be written.
- * This parameter can be one of GPIO_PIN_x where x can be (0..15).
- * @retval None
- */
-void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin)
-{
- uint32_t position = 0x00U;
+ * @brief De-initializes the GPIOx peripheral registers to their default reset values.
+ * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
+ * @param GPIO_Pin: specifies the port bit to be written.
+ * This parameter can be one of GPIO_PIN_x where x can be (0..15).
+ * @retval None
+ */
+void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) {
+ uint32_t position = 0x00U;
uint32_t iocurrent = 0x00U;
- uint32_t tmp = 0x00U;
+ uint32_t tmp = 0x00U;
__IO uint32_t *configregister; /* Store the address of CRL or CRH register based on pin number */
- uint32_t registeroffset = 0U;
+ uint32_t registeroffset = 0U;
/* Check the parameters */
assert_param(IS_GPIO_ALL_INSTANCE(GPIOx));
assert_param(IS_GPIO_PIN(GPIO_Pin));
/* Configure the port pins */
- while ((GPIO_Pin >> position) != 0U)
- {
+ while ((GPIO_Pin >> position) != 0U) {
/* Get current io position */
iocurrent = (GPIO_Pin) & (1U << position);
- if (iocurrent)
- {
+ if (iocurrent) {
/*------------------------- GPIO Mode Configuration --------------------*/
/* Check if the current bit belongs to first half or last half of the pin count number
in order to address CRH or CRL register */
- configregister = (iocurrent < GPIO_PIN_8) ? &GPIOx->CRL : &GPIOx->CRH;
+ configregister = (iocurrent < GPIO_PIN_8) ? &GPIOx->CRL : &GPIOx->CRH;
registeroffset = (iocurrent < GPIO_PIN_8) ? (position << 2U) : ((position - 8U) << 2U);
/* CRL/CRH default value is floating input(0x04) shifted to correct position */
@@ -399,8 +373,7 @@ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin)
tmp = AFIO->EXTICR[position >> 2U];
tmp &= 0x0FU << (4U * (position & 0x03U));
- if (tmp == (GPIO_GET_INDEX(GPIOx) << (4U * (position & 0x03U))))
- {
+ if (tmp == (GPIO_GET_INDEX(GPIOx) << (4U * (position & 0x03U)))) {
tmp = 0x0FU << (4U * (position & 0x03U));
CLEAR_BIT(AFIO->EXTICR[position >> 2U], tmp);
@@ -419,8 +392,8 @@ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin)
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup GPIO_Exported_Functions_Group2 IO operation functions
* @brief GPIO Read and Write
@@ -437,70 +410,61 @@ void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin)
*/
/**
- * @brief Reads the specified input port pin.
- * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
- * @param GPIO_Pin: specifies the port bit to read.
- * This parameter can be GPIO_PIN_x where x can be (0..15).
- * @retval The input port pin value.
- */
-GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
-{
+ * @brief Reads the specified input port pin.
+ * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
+ * @param GPIO_Pin: specifies the port bit to read.
+ * This parameter can be GPIO_PIN_x where x can be (0..15).
+ * @retval The input port pin value.
+ */
+GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) {
GPIO_PinState bitstatus;
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Pin));
- if ((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET)
- {
+ if ((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET) {
bitstatus = GPIO_PIN_SET;
- }
- else
- {
+ } else {
bitstatus = GPIO_PIN_RESET;
}
return bitstatus;
}
/**
- * @brief Sets or clears the selected data port bit.
- *
- * @note This function uses GPIOx_BSRR register to allow atomic read/modify
- * accesses. In this way, there is no risk of an IRQ occurring between
- * the read and the modify access.
- *
- * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
- * @param GPIO_Pin: specifies the port bit to be written.
- * This parameter can be one of GPIO_PIN_x where x can be (0..15).
- * @param PinState: specifies the value to be written to the selected bit.
- * This parameter can be one of the GPIO_PinState enum values:
- * @arg GPIO_PIN_RESET: to clear the port pin
- * @arg GPIO_PIN_SET: to set the port pin
- * @retval None
- */
-void HAL_GPIO_WritePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState)
-{
+ * @brief Sets or clears the selected data port bit.
+ *
+ * @note This function uses GPIOx_BSRR register to allow atomic read/modify
+ * accesses. In this way, there is no risk of an IRQ occurring between
+ * the read and the modify access.
+ *
+ * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
+ * @param GPIO_Pin: specifies the port bit to be written.
+ * This parameter can be one of GPIO_PIN_x where x can be (0..15).
+ * @param PinState: specifies the value to be written to the selected bit.
+ * This parameter can be one of the GPIO_PinState enum values:
+ * @arg GPIO_PIN_RESET: to clear the port pin
+ * @arg GPIO_PIN_SET: to set the port pin
+ * @retval None
+ */
+void HAL_GPIO_WritePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState) {
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Pin));
assert_param(IS_GPIO_PIN_ACTION(PinState));
- if (PinState != GPIO_PIN_RESET)
- {
+ if (PinState != GPIO_PIN_RESET) {
GPIOx->BSRR = GPIO_Pin;
- }
- else
- {
+ } else {
GPIOx->BSRR = (uint32_t)GPIO_Pin << 16U;
}
}
/**
- * @brief Toggles the specified GPIO pin
- * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
- * @param GPIO_Pin: Specifies the pins to be toggled.
- * @retval None
- */
-void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
-{
+ * @brief Toggles the specified GPIO pin
+ * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
+ * @param GPIO_Pin: Specifies the pins to be toggled.
+ * @retval None
+ */
+void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) {
/* Check the parameters */
assert_param(IS_GPIO_PIN(GPIO_Pin));
@@ -508,17 +472,16 @@ void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
}
/**
-* @brief Locks GPIO Pins configuration registers.
-* @note The locking mechanism allows the IO configuration to be frozen. When the LOCK sequence
-* has been applied on a port bit, it is no longer possible to modify the value of the port bit until
-* the next reset.
-* @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
-* @param GPIO_Pin: specifies the port bit to be locked.
-* This parameter can be any combination of GPIO_Pin_x where x can be (0..15).
-* @retval None
-*/
-HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
-{
+ * @brief Locks GPIO Pins configuration registers.
+ * @note The locking mechanism allows the IO configuration to be frozen. When the LOCK sequence
+ * has been applied on a port bit, it is no longer possible to modify the value of the port bit until
+ * the next reset.
+ * @param GPIOx: where x can be (A..G depending on device used) to select the GPIO peripheral
+ * @param GPIO_Pin: specifies the port bit to be locked.
+ * This parameter can be any combination of GPIO_Pin_x where x can be (0..15).
+ * @retval None
+ */
+HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin) {
__IO uint32_t tmp = GPIO_LCKR_LCKK;
/* Check the parameters */
@@ -536,38 +499,32 @@ HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
/* Read LCKK bit*/
tmp = GPIOx->LCKR;
- if ((uint32_t)(GPIOx->LCKR & GPIO_LCKR_LCKK))
- {
+ if ((uint32_t)(GPIOx->LCKR & GPIO_LCKR_LCKK)) {
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_ERROR;
}
}
/**
- * @brief This function handles EXTI interrupt request.
- * @param GPIO_Pin: Specifies the pins connected EXTI line
- * @retval None
- */
-void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin)
-{
+ * @brief This function handles EXTI interrupt request.
+ * @param GPIO_Pin: Specifies the pins connected EXTI line
+ * @retval None
+ */
+void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin) {
/* EXTI line interrupt detected */
- if (__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != RESET)
- {
+ if (__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != RESET) {
__HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin);
HAL_GPIO_EXTI_Callback(GPIO_Pin);
}
}
/**
- * @brief EXTI line detection callbacks.
- * @param GPIO_Pin: Specifies the pins connected EXTI line
- * @retval None
- */
-__weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
-{
+ * @brief EXTI line detection callbacks.
+ * @param GPIO_Pin: Specifies the pins connected EXTI line
+ * @retval None
+ */
+__weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) {
/* Prevent unused argument(s) compilation warning */
UNUSED(GPIO_Pin);
/* NOTE: This function Should not be modified, when the callback is needed,
@@ -576,20 +533,20 @@ __weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_GPIO_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio_ex.c
index 551333bb..945205bb 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio_ex.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_gpio_ex.c
@@ -56,19 +56,19 @@
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup GPIOEx GPIOEx
- * @brief GPIO HAL module driver
- * @{
- */
+ * @brief GPIO HAL module driver
+ * @{
+ */
#ifdef HAL_GPIO_MODULE_ENABLED
/** @defgroup GPIOEx_Exported_Functions GPIOEx Exported Functions
- * @{
- */
+ * @{
+ */
/** @defgroup GPIOEx_Exported_Functions_Group1 Extended features functions
* @brief Extended features functions
@@ -87,15 +87,14 @@
*/
/**
- * @brief Configures the port and pin on which the EVENTOUT Cortex signal will be connected.
- * @param GPIO_PortSource Select the port used to output the Cortex EVENTOUT signal.
- * This parameter can be a value of @ref GPIOEx_EVENTOUT_PORT.
- * @param GPIO_PinSource Select the pin used to output the Cortex EVENTOUT signal.
- * This parameter can be a value of @ref GPIOEx_EVENTOUT_PIN.
- * @retval None
- */
-void HAL_GPIOEx_ConfigEventout(uint32_t GPIO_PortSource, uint32_t GPIO_PinSource)
-{
+ * @brief Configures the port and pin on which the EVENTOUT Cortex signal will be connected.
+ * @param GPIO_PortSource Select the port used to output the Cortex EVENTOUT signal.
+ * This parameter can be a value of @ref GPIOEx_EVENTOUT_PORT.
+ * @param GPIO_PinSource Select the pin used to output the Cortex EVENTOUT signal.
+ * This parameter can be a value of @ref GPIOEx_EVENTOUT_PIN.
+ * @retval None
+ */
+void HAL_GPIOEx_ConfigEventout(uint32_t GPIO_PortSource, uint32_t GPIO_PinSource) {
/* Verify the parameters */
assert_param(IS_AFIO_EVENTOUT_PORT(GPIO_PortSource));
assert_param(IS_AFIO_EVENTOUT_PIN(GPIO_PinSource));
@@ -105,39 +104,33 @@ void HAL_GPIOEx_ConfigEventout(uint32_t GPIO_PortSource, uint32_t GPIO_PinSource
}
/**
- * @brief Enables the Event Output.
- * @retval None
- */
-void HAL_GPIOEx_EnableEventout(void)
-{
- SET_BIT(AFIO->EVCR, AFIO_EVCR_EVOE);
-}
+ * @brief Enables the Event Output.
+ * @retval None
+ */
+void HAL_GPIOEx_EnableEventout(void) { SET_BIT(AFIO->EVCR, AFIO_EVCR_EVOE); }
/**
- * @brief Disables the Event Output.
- * @retval None
- */
-void HAL_GPIOEx_DisableEventout(void)
-{
- CLEAR_BIT(AFIO->EVCR, AFIO_EVCR_EVOE);
-}
+ * @brief Disables the Event Output.
+ * @retval None
+ */
+void HAL_GPIOEx_DisableEventout(void) { CLEAR_BIT(AFIO->EVCR, AFIO_EVCR_EVOE); }
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_GPIO_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c
index 4f839a3f..dd7ab849 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_i2c.c
@@ -33,13 +33,13 @@
(+++) Configure the DMA handle parameters
(+++) Configure the DMA Tx or Rx channel
(+++) Associate the initialized DMA handle to the hi2c DMA Tx or Rx handle
- (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on
+ (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on
the DMA Tx or Rx channel
(#) Configure the Communication Speed, Duty cycle, Addressing mode, Own Address1,
Dual Addressing mode, Own Address2, General call and Nostretch mode in the hi2c Init structure.
- (#) Initialize the I2C registers by calling the HAL_I2C_Init(), configures also the low level Hardware
+ (#) Initialize the I2C registers by calling the HAL_I2C_Init(), configures also the low level Hardware
(GPIO, CLOCK, NVIC...etc) by calling the customized HAL_I2C_MspInit(&hi2c) API.
(#) To check if target device is ready for communication, use the function HAL_I2C_IsDeviceReady()
@@ -90,7 +90,7 @@
[..]
(+) A specific option field manage the different steps of a sequential transfer
(+) Option field values are defined through @ref I2C_XFEROPTIONS and are listed below:
- (++) I2C_FIRST_AND_LAST_FRAME: No sequential usage, functionnal is same as associated interfaces in no sequential mode
+ (++) I2C_FIRST_AND_LAST_FRAME: No sequential usage, functionnal is same as associated interfaces in no sequential mode
(++) I2C_FIRST_FRAME: Sequential usage, this option allow to manage a sequence with start condition, address
and data to transfer without a final stop condition
(++) I2C_NEXT_FRAME: Sequential usage, this option allow to manage a sequence with a restart condition, address
@@ -202,14 +202,14 @@
(#) Workarounds Implemented inside I2C HAL Driver
(##) Wrong data read into data register (Polling and Interrupt mode)
(##) Start cannot be generated after a misplaced Stop
- (##) Some software events must be managed before the current byte is being transferred:
+ (##) Some software events must be managed before the current byte is being transferred:
Workaround: Use DMA in general, except when the Master is receiving a single byte.
For Interupt mode, I2C should have the highest priority in the application.
(##) Mismatch on the "Setup time for a repeated Start condition" timing parameter:
- Workaround: Reduce the frequency down to 88 kHz or use the I2C Fast-mode if
+ Workaround: Reduce the frequency down to 88 kHz or use the I2C Fast-mode if
supported by the slave.
(##) Data valid time (tVD;DAT) violated without the OVR flag being set:
- Workaround: If the slave device allows it, use the clock stretching mechanism
+ Workaround: If the slave device allows it, use the clock stretching mechanism
by programming NoStretchMode = I2C_NOSTRETCH_DISABLE in HAL_I2C_Init.
@endverbatim
@@ -247,43 +247,43 @@
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup I2C I2C
- * @brief I2C HAL module driver
- * @{
- */
+ * @brief I2C HAL module driver
+ * @{
+ */
#ifdef HAL_I2C_MODULE_ENABLED
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @addtogroup I2C_Private_Define
- * @{
- */
-#define I2C_TIMEOUT_FLAG 35U /*!< Timeout 35 ms */
-#define I2C_TIMEOUT_BUSY_FLAG 25U /*!< Timeout 25 ms */
-#define I2C_NO_OPTION_FRAME 0xFFFF0000U /*!< XferOptions default value */
+ * @{
+ */
+#define I2C_TIMEOUT_FLAG 35U /*!< Timeout 35 ms */
+#define I2C_TIMEOUT_BUSY_FLAG 25U /*!< Timeout 25 ms */
+#define I2C_NO_OPTION_FRAME 0xFFFF0000U /*!< XferOptions default value */
/* Private define for @ref PreviousState usage */
-#define I2C_STATE_MSK ((uint32_t)((HAL_I2C_STATE_BUSY_TX | HAL_I2C_STATE_BUSY_RX) & (~(uint32_t)HAL_I2C_STATE_READY))) /*!< Mask State define, keep only RX and TX bits */
-#define I2C_STATE_NONE ((uint32_t)(HAL_I2C_MODE_NONE)) /*!< Default Value */
-#define I2C_STATE_MASTER_BUSY_TX ((uint32_t)((HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | HAL_I2C_MODE_MASTER)) /*!< Master Busy TX, combinaison of State LSB and Mode enum */
-#define I2C_STATE_MASTER_BUSY_RX ((uint32_t)((HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | HAL_I2C_MODE_MASTER)) /*!< Master Busy RX, combinaison of State LSB and Mode enum */
-#define I2C_STATE_SLAVE_BUSY_TX ((uint32_t)((HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | HAL_I2C_MODE_SLAVE)) /*!< Slave Busy TX, combinaison of State LSB and Mode enum */
-#define I2C_STATE_SLAVE_BUSY_RX ((uint32_t)((HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | HAL_I2C_MODE_SLAVE)) /*!< Slave Busy RX, combinaison of State LSB and Mode enum */
+#define I2C_STATE_MSK ((uint32_t)((HAL_I2C_STATE_BUSY_TX | HAL_I2C_STATE_BUSY_RX) & (~(uint32_t)HAL_I2C_STATE_READY))) /*!< Mask State define, keep only RX and TX bits */
+#define I2C_STATE_NONE ((uint32_t)(HAL_I2C_MODE_NONE)) /*!< Default Value */
+#define I2C_STATE_MASTER_BUSY_TX ((uint32_t)((HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | HAL_I2C_MODE_MASTER)) /*!< Master Busy TX, combinaison of State LSB and Mode enum */
+#define I2C_STATE_MASTER_BUSY_RX ((uint32_t)((HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | HAL_I2C_MODE_MASTER)) /*!< Master Busy RX, combinaison of State LSB and Mode enum */
+#define I2C_STATE_SLAVE_BUSY_TX ((uint32_t)((HAL_I2C_STATE_BUSY_TX & I2C_STATE_MSK) | HAL_I2C_MODE_SLAVE)) /*!< Slave Busy TX, combinaison of State LSB and Mode enum */
+#define I2C_STATE_SLAVE_BUSY_RX ((uint32_t)((HAL_I2C_STATE_BUSY_RX & I2C_STATE_MSK) | HAL_I2C_MODE_SLAVE)) /*!< Slave Busy RX, combinaison of State LSB and Mode enum */
/**
- * @}
- */
+ * @}
+ */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @addtogroup I2C_Private_Functions
- * @{
- */
+ * @{
+ */
/* Private functions to handle DMA transfer */
static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma);
static void I2C_DMAError(DMA_HandleTypeDef *hdma);
@@ -320,13 +320,13 @@ static HAL_StatusTypeDef I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c);
static HAL_StatusTypeDef I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c);
static HAL_StatusTypeDef I2C_Slave_AF(I2C_HandleTypeDef *hi2c);
/**
- * @}
- */
+ * @}
+ */
/* Exported functions --------------------------------------------------------*/
/** @defgroup I2C_Exported_Functions I2C Exported Functions
- * @{
- */
+ * @{
+ */
/** @defgroup I2C_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and Configuration functions
@@ -360,20 +360,18 @@ static HAL_StatusTypeDef I2C_Slave_AF(I2C_HandleTypeDef *hi2c);
*/
/**
- * @brief Initializes the I2C according to the specified parameters
- * in the I2C_InitTypeDef and create the associated handle.
- * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Initializes the I2C according to the specified parameters
+ * in the I2C_InitTypeDef and create the associated handle.
+ * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c) {
uint32_t freqrange = 0U;
- uint32_t pclk1 = 0U;
+ uint32_t pclk1 = 0U;
/* Check the I2C handle allocation */
- if(hi2c == NULL)
- {
+ if (hi2c == NULL) {
return HAL_ERROR;
}
@@ -388,8 +386,7 @@ HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c)
assert_param(IS_I2C_GENERAL_CALL(hi2c->Init.GeneralCallMode));
assert_param(IS_I2C_NO_STRETCH(hi2c->Init.NoStretchMode));
- if(hi2c->State == HAL_I2C_STATE_RESET)
- {
+ if (hi2c->State == HAL_I2C_STATE_RESET) {
/* Allocate lock resource and initialize it */
hi2c->Lock = HAL_UNLOCKED;
/* Init the low level hardware : GPIO, CLOCK, NVIC */
@@ -405,8 +402,7 @@ HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c)
pclk1 = HAL_RCC_GetPCLK1Freq();
/* Check the minimum allowed PCLK1 frequency */
- if (I2C_MIN_PCLK_FREQ(pclk1, hi2c->Init.ClockSpeed) == 1U)
- {
+ if (I2C_MIN_PCLK_FREQ(pclk1, hi2c->Init.ClockSpeed) == 1U) {
return HAL_ERROR;
}
@@ -440,25 +436,23 @@ HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c)
/* Enable the selected I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
- hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
- hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+ hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
return HAL_OK;
}
/**
- * @brief DeInitializes the I2C peripheral.
- * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c)
-{
+ * @brief DeInitializes the I2C peripheral.
+ * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c) {
/* Check the I2C handle allocation */
- if(hi2c == NULL)
- {
+ if (hi2c == NULL) {
return HAL_ERROR;
}
@@ -485,13 +479,12 @@ HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief I2C MSP Init.
- * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval None
- */
- __weak void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c)
-{
+ * @brief I2C MSP Init.
+ * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval None
+ */
+__weak void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -500,13 +493,12 @@ HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief I2C MSP DeInit
- * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval None
- */
- __weak void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c)
-{
+ * @brief I2C MSP DeInit
+ * @param hi2c: pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval None
+ */
+__weak void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -515,8 +507,8 @@ HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c)
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup I2C_Exported_Functions_Group2 IO operation functions
* @brief Data transfers functions
@@ -583,28 +575,25 @@ HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c)
*/
/**
- * @brief Transmits in master mode an amount of data in blocking mode.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param Timeout Timeout duration
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout)
-{
+ * @brief Transmits in master mode an amount of data in blocking mode.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param Timeout Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) {
uint32_t tickstart = 0x00U;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) {
return HAL_BUSY;
}
@@ -612,8 +601,7 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevA
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -632,16 +620,12 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevA
hi2c->XferSize = hi2c->XferCount;
/* Send Slave Address */
- if(I2C_MasterRequestWrite(hi2c, DevAddress, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_MasterRequestWrite(hi2c, DevAddress, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
- }
- else
- {
+ } else {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_TIMEOUT;
@@ -651,19 +635,14 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevA
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
- while(hi2c->XferSize > 0U)
- {
+ while (hi2c->XferSize > 0U) {
/* Wait until TXE flag is set */
- if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -673,25 +652,20 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevA
hi2c->XferCount--;
hi2c->XferSize--;
- if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U))
- {
+ if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) {
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferCount--;
hi2c->XferSize--;
}
-
+
/* Wait until BTF flag is set */
- if(I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -701,42 +675,37 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevA
hi2c->Instance->CR1 |= I2C_CR1_STOP;
hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
-
+ hi2c->Mode = HAL_I2C_MODE_NONE;
+
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Receives in master mode an amount of data in blocking mode.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param Timeout Timeout duration
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout)
-{
+ * @brief Receives in master mode an amount of data in blocking mode.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param Timeout Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) {
uint32_t tickstart = 0x00U;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) {
return HAL_BUSY;
}
@@ -744,8 +713,7 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -753,9 +721,9 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
/* Disable Pos */
hi2c->Instance->CR1 &= ~I2C_CR1_POS;
- hi2c->State = HAL_I2C_STATE_BUSY_RX;
- hi2c->Mode = HAL_I2C_MODE_MASTER;
- hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+ hi2c->State = HAL_I2C_STATE_BUSY_RX;
+ hi2c->Mode = HAL_I2C_MODE_MASTER;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
@@ -764,32 +732,25 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
hi2c->XferSize = hi2c->XferCount;
/* Send Slave Address */
- if(I2C_MasterRequestRead(hi2c, DevAddress, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_MasterRequestRead(hi2c, DevAddress, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
- }
- else
- {
+ } else {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_TIMEOUT;
}
}
- if(hi2c->XferSize == 0U)
- {
+ if (hi2c->XferSize == 0U) {
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
- }
- else if(hi2c->XferSize == 1U)
- {
+ } else if (hi2c->XferSize == 1U) {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
@@ -804,10 +765,8 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
hi2c->Instance->CR1 |= I2C_CR1_STOP;
/* Re-enable IRQs */
- __enable_irq();
- }
- else if(hi2c->XferSize == 2U)
- {
+ __enable_irq();
+ } else if (hi2c->XferSize == 2U) {
/* Enable Pos */
hi2c->Instance->CR1 |= I2C_CR1_POS;
@@ -822,10 +781,8 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
/* Re-enable IRQs */
- __enable_irq();
- }
- else
- {
+ __enable_irq();
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
@@ -833,22 +790,15 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
}
- while(hi2c->XferSize > 0U)
- {
- if(hi2c->XferSize <= 3U)
- {
+ while (hi2c->XferSize > 0U) {
+ if (hi2c->XferSize <= 3U) {
/* One byte */
- if(hi2c->XferSize == 1U)
- {
+ if (hi2c->XferSize == 1U) {
/* Wait until RXNE flag is set */
- if(I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT)
- {
+ if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) {
return HAL_TIMEOUT;
- }
- else
- {
+ } else {
return HAL_ERROR;
}
}
@@ -859,17 +809,15 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
hi2c->XferCount--;
}
/* Two bytes */
- else if(hi2c->XferSize == 2U)
- {
+ else if (hi2c->XferSize == 2U) {
/* Wait until BTF flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
/* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3
software sequence must complete before the current byte end of transfer */
- __disable_irq();
+ __disable_irq();
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
@@ -888,11 +836,9 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
hi2c->XferCount--;
}
/* 3 Last bytes */
- else
- {
+ else {
/* Wait until BTF flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -909,8 +855,7 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
hi2c->XferCount--;
/* Wait until BTF flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -923,25 +868,19 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
hi2c->XferCount--;
/* Re-enable IRQs */
- __enable_irq();
+ __enable_irq();
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferSize--;
hi2c->XferCount--;
}
- }
- else
- {
+ } else {
/* Wait until RXNE flag is set */
- if(I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT)
- {
+ if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) {
return HAL_TIMEOUT;
- }
- else
- {
+ } else {
return HAL_ERROR;
}
}
@@ -951,8 +890,7 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
hi2c->XferSize--;
hi2c->XferCount--;
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferSize--;
@@ -962,48 +900,42 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAd
}
hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Transmits in slave mode an amount of data in blocking mode.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param Timeout Timeout duration
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout)
-{
+ * @brief Transmits in slave mode an amount of data in blocking mode.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param Timeout Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) {
uint32_t tickstart = 0x00U;
-
+
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
-
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
- if((pData == NULL) || (Size == 0U))
- {
- return HAL_ERROR;
+
+ if (hi2c->State == HAL_I2C_STATE_READY) {
+ if ((pData == NULL) || (Size == 0U)) {
+ return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
-
+
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1011,9 +943,9 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData
/* Disable Pos */
hi2c->Instance->CR1 &= ~I2C_CR1_POS;
- hi2c->State = HAL_I2C_STATE_BUSY_TX;
- hi2c->Mode = HAL_I2C_MODE_SLAVE;
- hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+ hi2c->State = HAL_I2C_STATE_BUSY_TX;
+ hi2c->Mode = HAL_I2C_MODE_SLAVE;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
@@ -1025,8 +957,7 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData
hi2c->Instance->CR1 |= I2C_CR1_ACK;
/* Wait until ADDR flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -1034,11 +965,9 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
/* If 10bit addressing mode is selected */
- if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)
- {
+ if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) {
/* Wait until ADDR flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -1046,20 +975,15 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
}
- while(hi2c->XferSize > 0U)
- {
+ while (hi2c->XferSize > 0U) {
/* Wait until TXE flag is set */
- if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
/* Disable Address Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -1069,8 +993,7 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData
hi2c->XferCount--;
hi2c->XferSize--;
- if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U))
- {
+ if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) {
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferCount--;
@@ -1079,8 +1002,7 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData
}
/* Wait until AF flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_AF, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -1091,48 +1013,42 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Receive in slave mode an amount of data in blocking mode
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param Timeout Timeout duration
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout)
-{
+ * @brief Receive in slave mode an amount of data in blocking mode
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param Timeout Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) {
uint32_t tickstart = 0x00U;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
- if((pData == NULL) || (Size == 0U))
- {
- return HAL_ERROR;
+ if (hi2c->State == HAL_I2C_STATE_READY) {
+ if ((pData == NULL) || (Size == 0U)) {
+ return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1140,9 +1056,9 @@ HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData,
/* Disable Pos */
hi2c->Instance->CR1 &= ~I2C_CR1_POS;
- hi2c->State = HAL_I2C_STATE_BUSY_RX;
- hi2c->Mode = HAL_I2C_MODE_SLAVE;
- hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+ hi2c->State = HAL_I2C_STATE_BUSY_RX;
+ hi2c->Mode = HAL_I2C_MODE_SLAVE;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
@@ -1154,28 +1070,22 @@ HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData,
hi2c->Instance->CR1 |= I2C_CR1_ACK;
/* Wait until ADDR flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
- while(hi2c->XferSize > 0U)
- {
+ while (hi2c->XferSize > 0U) {
/* Wait until RXNE flag is set */
- if(I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
/* Disable Address Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
- if(hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT)
- {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) {
return HAL_TIMEOUT;
- }
- else
- {
+ } else {
return HAL_ERROR;
}
}
@@ -1185,27 +1095,22 @@ HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData,
hi2c->XferSize--;
hi2c->XferCount--;
- if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U))
- {
+ if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) {
/* Read data from DR */
- (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
- hi2c->XferSize--;
- hi2c->XferCount--;
+ (*hi2c->pBuffPtr++) = hi2c->Instance->DR;
+ hi2c->XferSize--;
+ hi2c->XferCount--;
}
}
/* Wait until STOP flag is set */
- if(I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnSTOPFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
/* Disable Address Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -1217,58 +1122,50 @@ HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData,
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Transmit in master mode an amount of data in non-blocking mode with Interrupt
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
-{
+ * @brief Transmit in master mode an amount of data in non-blocking mode with Interrupt
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
-
+
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1300,52 +1197,44 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t D
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Receive in master mode an amount of data in non-blocking mode with Interrupt
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
-{
+ * @brief Receive in master mode an amount of data in non-blocking mode with Interrupt
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
-
+
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1381,62 +1270,53 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t De
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Sequential transmit in master mode an amount of data in non-blocking mode with Interrupt
- * @note This interface allow to manage repeated start condition when a direction change during transfer
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Master_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions)
-{
+ * @brief Sequential transmit in master mode an amount of data in non-blocking mode with Interrupt
+ * @note This interface allow to manage repeated start condition when a direction change during transfer
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) {
__IO uint32_t Prev_State = 0x00U;
__IO uint32_t count = 0x00U;
-
+
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Check Busy Flag only if FIRST call of Master interface */
- if((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME))
- {
+ if ((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
-
+ hi2c->State = HAL_I2C_STATE_READY;
+
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
-
- return HAL_TIMEOUT;
+
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1456,18 +1336,14 @@ HAL_StatusTypeDef HAL_I2C_Master_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c,
hi2c->Devaddress = DevAddress;
Prev_State = hi2c->PreviousState;
-
- /* Generate Start */
- if((Prev_State == I2C_STATE_MASTER_BUSY_RX) || (Prev_State == I2C_STATE_NONE))
- {
+
+ /* Generate Start */
+ if ((Prev_State == I2C_STATE_MASTER_BUSY_RX) || (Prev_State == I2C_STATE_NONE)) {
/* Generate Start condition if first transfer */
- if((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME))
- {
+ if ((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) {
/* Generate Start */
hi2c->Instance->CR1 |= I2C_CR1_START;
- }
- else
- {
+ } else {
/* Generate ReStart */
hi2c->Instance->CR1 |= I2C_CR1_START;
}
@@ -1484,61 +1360,52 @@ HAL_StatusTypeDef HAL_I2C_Master_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c,
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Sequential receive in master mode an amount of data in non-blocking mode with Interrupt
- * @note This interface allow to manage repeated start condition when a direction change during transfer
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Master_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions)
-{
+ * @brief Sequential receive in master mode an amount of data in non-blocking mode with Interrupt
+ * @note This interface allow to manage repeated start condition when a direction change during transfer
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) {
__IO uint32_t count = 0U;
-
+
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Check Busy Flag only if FIRST call of Master interface */
- if((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME))
- {
+ if ((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME)) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1551,28 +1418,24 @@ HAL_StatusTypeDef HAL_I2C_Master_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c,
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
- hi2c->pBuffPtr = pData;
- hi2c->XferCount = Size;
+ hi2c->pBuffPtr = pData;
+ hi2c->XferCount = Size;
hi2c->XferOptions = XferOptions;
hi2c->XferSize = hi2c->XferCount;
- hi2c->Devaddress = DevAddress;
-
- if((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) || (hi2c->PreviousState == I2C_STATE_NONE))
- {
+ hi2c->Devaddress = DevAddress;
+
+ if ((hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) || (hi2c->PreviousState == I2C_STATE_NONE)) {
/* Generate Start condition if first transfer */
- if((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME) || (XferOptions == I2C_NO_OPTION_FRAME))
- {
+ if ((XferOptions == I2C_FIRST_AND_LAST_FRAME) || (XferOptions == I2C_FIRST_FRAME) || (XferOptions == I2C_NO_OPTION_FRAME)) {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
-
+
/* Generate Start */
hi2c->Instance->CR1 |= I2C_CR1_START;
- }
- else
- {
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
-
+
/* Generate ReStart */
hi2c->Instance->CR1 |= I2C_CR1_START;
}
@@ -1589,55 +1452,46 @@ HAL_StatusTypeDef HAL_I2C_Master_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c,
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Transmit in slave mode an amount of data in non-blocking mode with Interrupt
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
-{
+ * @brief Transmit in slave mode an amount of data in non-blocking mode with Interrupt
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
- if((pData == NULL) || (Size == 0U))
- {
- return HAL_ERROR;
+ if (hi2c->State == HAL_I2C_STATE_READY) {
+ if ((pData == NULL) || (Size == 0U)) {
+ return HAL_ERROR;
}
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1669,55 +1523,46 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pD
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Receive in slave mode an amount of data in non-blocking mode with Interrupt
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
-{
+ * @brief Receive in slave mode an amount of data in non-blocking mode with Interrupt
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
- if((pData == NULL) || (Size == 0U))
- {
- return HAL_ERROR;
+ if (hi2c->State == HAL_I2C_STATE_READY) {
+ if ((pData == NULL) || (Size == 0U)) {
+ return HAL_ERROR;
}
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1730,9 +1575,9 @@ HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pDa
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
- hi2c->pBuffPtr = pData;
- hi2c->XferSize = Size;
- hi2c->XferCount = Size;
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
/* Enable Address Acknowledge */
@@ -1749,41 +1594,35 @@ HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pDa
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Sequential transmit in slave mode an amount of data in no-blocking mode with Interrupt
- * @note This interface allow to manage repeated start condition when a direction change during transfer
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions)
-{
+ * @brief Sequential transmit in slave mode an amount of data in no-blocking mode with Interrupt
+ * @note This interface allow to manage repeated start condition when a direction change during transfer
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) {
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
- if(hi2c->State == HAL_I2C_STATE_LISTEN)
- {
- if((pData == NULL) || (Size == 0U))
- {
- return HAL_ERROR;
+ if (hi2c->State == HAL_I2C_STATE_LISTEN) {
+ if ((pData == NULL) || (Size == 0U)) {
+ return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1815,41 +1654,35 @@ HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Transmit_IT(I2C_HandleTypeDef *hi2c,
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Sequential receive in slave mode an amount of data in non-blocking mode with Interrupt
- * @note This interface allow to manage repeated start condition when a direction change during transfer
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions)
-{
+ * @brief Sequential receive in slave mode an amount of data in non-blocking mode with Interrupt
+ * @note This interface allow to manage repeated start condition when a direction change during transfer
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param XferOptions Options of Transfer, value of @ref I2C_XferOptions_definition
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t XferOptions) {
/* Check the parameters */
assert_param(IS_I2C_TRANSFER_OPTIONS_REQUEST(XferOptions));
- if(hi2c->State == HAL_I2C_STATE_LISTEN)
- {
- if((pData == NULL) || (Size == 0U))
- {
- return HAL_ERROR;
+ if (hi2c->State == HAL_I2C_STATE_LISTEN) {
+ if ((pData == NULL) || (Size == 0U)) {
+ return HAL_ERROR;
}
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1862,7 +1695,7 @@ HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, u
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
- hi2c->pBuffPtr = pData;
+ hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = XferOptions;
hi2c->XferSize = hi2c->XferCount;
@@ -1881,28 +1714,23 @@ HAL_StatusTypeDef HAL_I2C_Slave_Sequential_Receive_IT(I2C_HandleTypeDef *hi2c, u
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Enable the Address listen mode with Interrupt.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c)
-{
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ * @brief Enable the Address listen mode with Interrupt.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c) {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
hi2c->State = HAL_I2C_STATE_LISTEN;
-
+
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -1914,85 +1742,73 @@ HAL_StatusTypeDef HAL_I2C_EnableListen_IT(I2C_HandleTypeDef *hi2c)
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Disable the Address listen mode with Interrupt.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Disable the Address listen mode with Interrupt.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_DisableListen_IT(I2C_HandleTypeDef *hi2c) {
/* Declaration of tmp to prevent undefined behavior of volatile usage */
uint32_t tmp;
/* Disable Address listen mode only if a transfer is not ongoing */
- if(hi2c->State == HAL_I2C_STATE_LISTEN)
- {
- tmp = (uint32_t)(hi2c->State) & I2C_STATE_MSK;
+ if (hi2c->State == HAL_I2C_STATE_LISTEN) {
+ tmp = (uint32_t)(hi2c->State) & I2C_STATE_MSK;
hi2c->PreviousState = tmp | (uint32_t)(hi2c->Mode);
- hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
/* Disable Address Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
/* Disable EVT and ERR interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR);
-
+
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Transmit in master mode an amount of data in non-blocking mode with DMA
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
-{
+ * @brief Transmit in master mode an amount of data in non-blocking mode with DMA
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -2011,17 +1827,16 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t
hi2c->XferSize = hi2c->XferCount;
hi2c->Devaddress = DevAddress;
- if(hi2c->XferSize > 0U)
- {
+ if (hi2c->XferSize > 0U) {
/* Set the I2C DMA transfer complete callback */
hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt;
- /* Set the DMA error callback */
+ /* Set the DMA error callback */
hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmatx->XferHalfCpltCallback = NULL;
- hi2c->hdmatx->XferAbortCallback = NULL;
+ hi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA channel */
HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize);
@@ -2044,9 +1859,7 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t
/* Enable DMA Request */
hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
- }
- else
- {
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
@@ -2060,77 +1873,68 @@ HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t
to avoid the risk of I2C interrupt handle execution before current
process unlock */
- /* Enable EVT, BUF and ERR interrupt */
- __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
+ /* Enable EVT, BUF and ERR interrupt */
+ __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
}
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Receive in master mode an amount of data in non-blocking mode with DMA
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size)
-{
+ * @brief Receive in master mode an amount of data in non-blocking mode with DMA
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
-
+
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
/* Disable Pos */
hi2c->Instance->CR1 &= ~I2C_CR1_POS;
-
+
hi2c->State = HAL_I2C_STATE_BUSY_RX;
hi2c->Mode = HAL_I2C_MODE_MASTER;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
-
+
/* Prepare transfer parameters */
hi2c->pBuffPtr = pData;
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferSize = hi2c->XferCount;
hi2c->Devaddress = DevAddress;
-
- if(hi2c->XferSize > 0U)
- {
+
+ if (hi2c->XferSize > 0U) {
/* Set the I2C DMA transfer complete callback */
hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt;
@@ -2139,7 +1943,7 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t D
/* Set the unused DMA callbacks to NULL */
hi2c->hdmarx->XferHalfCpltCallback = NULL;
- hi2c->hdmarx->XferAbortCallback = NULL;
+ hi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA channel */
HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize);
@@ -2162,9 +1966,7 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t D
/* Enable DMA Request */
hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
- }
- else
- {
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
@@ -2181,37 +1983,33 @@ HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t D
/* Enable EVT, BUF and ERR interrupt */
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
}
-
+
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Abort a master I2C process communication with Interrupt.
- * @note This abort can be called only if state is ready
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress)
-{
+ * @brief Abort a master I2C process communication with Interrupt.
+ * @note This abort can be called only if state is ready
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress) {
/* Prevent unused argument(s) compilation warning */
UNUSED(DevAddress);
/* Abort Master transfer during Receive or Transmit process */
- if(hi2c->Mode == HAL_I2C_MODE_MASTER)
- {
+ if (hi2c->Mode == HAL_I2C_MODE_MASTER) {
/* Process Locked */
__HAL_LOCK(hi2c);
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State = HAL_I2C_STATE_ABORT;
+ hi2c->State = HAL_I2C_STATE_ABORT;
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
@@ -2231,9 +2029,7 @@ HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevA
I2C_ITError(hi2c);
return HAL_OK;
- }
- else
- {
+ } else {
/* Wrong usage of abort function */
/* This function should be used only in case of abort monitored by master device */
return HAL_ERROR;
@@ -2241,47 +2037,40 @@ HAL_StatusTypeDef HAL_I2C_Master_Abort_IT(I2C_HandleTypeDef *hi2c, uint16_t DevA
}
/**
- * @brief Transmit in slave mode an amount of data in non-blocking mode with DMA
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
-{
+ * @brief Transmit in slave mode an amount of data in non-blocking mode with DMA
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
-
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
- if((pData == NULL) || (Size == 0U))
- {
- return HAL_ERROR;
+
+ if (hi2c->State == HAL_I2C_STATE_READY) {
+ if ((pData == NULL) || (Size == 0U)) {
+ return HAL_ERROR;
}
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -2301,13 +2090,13 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *p
/* Set the I2C DMA transfer complete callback */
hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt;
-
+
/* Set the DMA error callback */
hi2c->hdmatx->XferErrorCallback = I2C_DMAError;
/* Set the unused DMA callbacks to NULL */
hi2c->hdmatx->XferHalfCpltCallback = NULL;
- hi2c->hdmatx->XferAbortCallback = NULL;
+ hi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA channel */
HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize);
@@ -2318,9 +2107,9 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *p
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- /* Note : The I2C interrupts must be enabled after unlocking current process
- to avoid the risk of I2C interrupt handle execution before current
- process unlock */
+ /* Note : The I2C interrupts must be enabled after unlocking current process
+ to avoid the risk of I2C interrupt handle execution before current
+ process unlock */
/* Enable EVT and ERR interrupt */
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR);
@@ -2328,55 +2117,46 @@ HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *p
hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Receive in slave mode an amount of data in non-blocking mode with DMA
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size)
-{
+ * @brief Receive in slave mode an amount of data in non-blocking mode with DMA
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
- if((pData == NULL) || (Size == 0U))
- {
- return HAL_ERROR;
+ if (hi2c->State == HAL_I2C_STATE_READY) {
+ if ((pData == NULL) || (Size == 0U)) {
+ return HAL_ERROR;
}
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -2402,7 +2182,7 @@ HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pD
/* Set the unused DMA callbacks to NULL */
hi2c->hdmarx->XferHalfCpltCallback = NULL;
- hi2c->hdmarx->XferAbortCallback = NULL;
+ hi2c->hdmarx->XferAbortCallback = NULL;
/* Enable the DMA channel */
HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize);
@@ -2423,49 +2203,43 @@ HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pD
hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Write an amount of data in blocking mode to a specific memory address
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param MemAddress Internal memory address
- * @param MemAddSize Size of internal memory address
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param Timeout Timeout duration
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)
-{
+ * @brief Write an amount of data in blocking mode to a specific memory address
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param MemAddress Internal memory address
+ * @param MemAddSize Size of internal memory address
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param Timeout Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) {
uint32_t tickstart = 0x00U;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
-
+
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) {
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
-
+
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -2482,37 +2256,28 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress
hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferSize = hi2c->XferCount;
-
+
/* Send Slave Address and Memory Address */
- if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
- }
- else
- {
+ } else {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_TIMEOUT;
}
}
- while(hi2c->XferSize > 0U)
- {
+ while (hi2c->XferSize > 0U) {
/* Wait until TXE flag is set */
- if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -2522,26 +2287,21 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress
hi2c->XferSize--;
hi2c->XferCount--;
- if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U))
- {
+ if ((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) && (hi2c->XferSize != 0U)) {
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferSize--;
hi2c->XferCount--;
}
}
-
+
/* Wait until BTF flag is set */
- if(I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnBTFFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -2550,56 +2310,50 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress
hi2c->Instance->CR1 |= I2C_CR1_STOP;
hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
-
+ hi2c->Mode = HAL_I2C_MODE_NONE;
+
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Read an amount of data in blocking mode from a specific memory address
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param MemAddress Internal memory address
- * @param MemAddSize Size of internal memory address
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @param Timeout Timeout duration
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout)
-{
+ * @brief Read an amount of data in blocking mode from a specific memory address
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param MemAddress Internal memory address
+ * @param MemAddSize Size of internal memory address
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @param Timeout Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) {
uint32_t tickstart = 0x00U;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
-
+
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) {
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
-
+
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -2618,32 +2372,25 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
hi2c->XferSize = hi2c->XferCount;
/* Send Slave Address and Memory Address */
- if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
- }
- else
- {
+ } else {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_TIMEOUT;
}
}
- if(hi2c->XferSize == 0U)
- {
+ if (hi2c->XferSize == 0U) {
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
-
+
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
- }
- else if(hi2c->XferSize == 1U)
- {
+ } else if (hi2c->XferSize == 1U) {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
@@ -2659,9 +2406,7 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
/* Re-enable IRQs */
__enable_irq();
- }
- else if(hi2c->XferSize == 2U)
- {
+ } else if (hi2c->XferSize == 2U) {
/* Enable Pos */
hi2c->Instance->CR1 |= I2C_CR1_POS;
@@ -2671,15 +2416,13 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
-
+
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
-
- /* Re-enable IRQs */
- __enable_irq();
- }
- else
- {
+
+ /* Re-enable IRQs */
+ __enable_irq();
+ } else {
/* Enable Acknowledge */
SET_BIT(hi2c->Instance->CR1, I2C_CR1_ACK);
@@ -2687,22 +2430,15 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
}
- while(hi2c->XferSize > 0U)
- {
- if(hi2c->XferSize <= 3U)
- {
+ while (hi2c->XferSize > 0U) {
+ if (hi2c->XferSize <= 3U) {
/* One byte */
- if(hi2c->XferSize== 1U)
- {
+ if (hi2c->XferSize == 1U) {
/* Wait until RXNE flag is set */
- if(I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT)
- {
+ if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) {
return HAL_TIMEOUT;
- }
- else
- {
+ } else {
return HAL_ERROR;
}
}
@@ -2713,17 +2449,15 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
hi2c->XferCount--;
}
/* Two bytes */
- else if(hi2c->XferSize == 2U)
- {
+ else if (hi2c->XferSize == 2U) {
/* Wait until BTF flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
/* Disable all active IRQs around ADDR clearing and STOP programming because the EV6_3
software sequence must complete before the current byte end of transfer */
- __disable_irq();
+ __disable_irq();
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
@@ -2742,11 +2476,9 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
hi2c->XferCount--;
}
/* 3 Last bytes */
- else
- {
+ else {
/* Wait until BTF flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -2763,8 +2495,7 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
hi2c->XferCount--;
/* Wait until BTF flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BTF, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -2784,18 +2515,12 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
hi2c->XferSize--;
hi2c->XferCount--;
}
- }
- else
- {
+ } else {
/* Wait until RXNE flag is set */
- if(I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT)
- {
+ if (I2C_WaitOnRXNEFlagUntilTimeout(hi2c, Timeout, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_TIMEOUT) {
return HAL_TIMEOUT;
- }
- else
- {
+ } else {
return HAL_ERROR;
}
}
@@ -2805,8 +2530,7 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
hi2c->XferSize--;
hi2c->XferCount--;
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferSize--;
@@ -2816,63 +2540,55 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress,
}
hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
-
+ hi2c->Mode = HAL_I2C_MODE_NONE;
+
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Write an amount of data in non-blocking mode with Interrupt to a specific memory address
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param MemAddress Internal memory address
- * @param MemAddSize Size of internal memory address
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
-{
+ * @brief Write an amount of data in non-blocking mode with Interrupt to a specific memory address
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param MemAddress Internal memory address
+ * @param MemAddSize Size of internal memory address
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -2880,19 +2596,19 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddr
/* Disable Pos */
hi2c->Instance->CR1 &= ~I2C_CR1_POS;
- hi2c->State = HAL_I2C_STATE_BUSY_TX;
- hi2c->Mode = HAL_I2C_MODE_MEM;
+ hi2c->State = HAL_I2C_STATE_BUSY_TX;
+ hi2c->Mode = HAL_I2C_MODE_MEM;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
- hi2c->pBuffPtr = pData;
- hi2c->XferSize = Size;
- hi2c->XferCount = Size;
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
- hi2c->Devaddress = DevAddress;
- hi2c->Memaddress = MemAddress;
- hi2c->MemaddSize = MemAddSize;
- hi2c->EventCount = 0U;
+ hi2c->Devaddress = DevAddress;
+ hi2c->Memaddress = MemAddress;
+ hi2c->MemaddSize = MemAddSize;
+ hi2c->EventCount = 0U;
/* Generate Start */
hi2c->Instance->CR1 |= I2C_CR1_START;
@@ -2908,57 +2624,49 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddr
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Read an amount of data in non-blocking mode with Interrupt from a specific memory address
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param MemAddress Internal memory address
- * @param MemAddSize Size of internal memory address
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
-{
+ * @brief Read an amount of data in non-blocking mode with Interrupt from a specific memory address
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param MemAddress Internal memory address
+ * @param MemAddSize Size of internal memory address
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -2966,19 +2674,19 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddre
/* Disable Pos */
hi2c->Instance->CR1 &= ~I2C_CR1_POS;
- hi2c->State = HAL_I2C_STATE_BUSY_RX;
- hi2c->Mode = HAL_I2C_MODE_MEM;
+ hi2c->State = HAL_I2C_STATE_BUSY_RX;
+ hi2c->Mode = HAL_I2C_MODE_MEM;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
- hi2c->pBuffPtr = pData;
- hi2c->XferSize = Size;
- hi2c->XferCount = Size;
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
- hi2c->Devaddress = DevAddress;
- hi2c->Memaddress = MemAddress;
- hi2c->MemaddSize = MemAddSize;
- hi2c->EventCount = 0U;
+ hi2c->Devaddress = DevAddress;
+ hi2c->Memaddress = MemAddress;
+ hi2c->MemaddSize = MemAddSize;
+ hi2c->EventCount = 0U;
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
@@ -2989,72 +2697,63 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddre
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- if(hi2c->XferSize > 0U)
- {
+ if (hi2c->XferSize > 0U) {
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
-
+
/* Enable EVT, BUF and ERR interrupt */
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
}
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Write an amount of data in non-blocking mode with DMA to a specific memory address
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param MemAddress Internal memory address
- * @param MemAddSize Size of internal memory address
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be sent
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
-{
+ * @brief Write an amount of data in non-blocking mode with DMA to a specific memory address
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param MemAddress Internal memory address
+ * @param MemAddSize Size of internal memory address
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be sent
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) {
__IO uint32_t count = 0U;
uint32_t tickstart = 0x00U;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
-
+
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -3067,13 +2766,12 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
- hi2c->pBuffPtr = pData;
- hi2c->XferSize = Size;
- hi2c->XferCount = Size;
+ hi2c->pBuffPtr = pData;
+ hi2c->XferSize = Size;
+ hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
- if(hi2c->XferSize > 0U)
- {
+ if (hi2c->XferSize > 0U) {
/* Set the I2C DMA transfer complete callback */
hi2c->hdmatx->XferCpltCallback = I2C_DMAXferCplt;
@@ -3082,22 +2780,18 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
/* Set the unused DMA callbacks to NULL */
hi2c->hdmatx->XferHalfCpltCallback = NULL;
- hi2c->hdmatx->XferAbortCallback = NULL;
+ hi2c->hdmatx->XferAbortCallback = NULL;
/* Enable the DMA channel */
HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->DR, hi2c->XferSize);
/* Send Slave Address and Memory Address */
- if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
- }
- else
- {
+ } else {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_TIMEOUT;
@@ -3106,10 +2800,10 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
-
+
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
-
+
/* Note : The I2C interrupts must be enabled after unlocking current process
to avoid the risk of I2C interrupt handle execution before current
process unlock */
@@ -3120,29 +2814,26 @@ HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
}
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Reads an amount of data in non-blocking mode with DMA from a specific memory address.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param MemAddress Internal memory address
- * @param MemAddSize Size of internal memory address
- * @param pData Pointer to data buffer
- * @param Size Amount of data to be read
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size)
-{
- uint32_t tickstart = 0x00U;
- __IO uint32_t count = 0U;
+ * @brief Reads an amount of data in non-blocking mode with DMA from a specific memory address.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param MemAddress Internal memory address
+ * @param MemAddSize Size of internal memory address
+ * @param pData Pointer to data buffer
+ * @param Size Amount of data to be read
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) {
+ uint32_t tickstart = 0x00U;
+ __IO uint32_t count = 0U;
/* Init tickstart for timeout management*/
tickstart = HAL_GetTick();
@@ -3150,31 +2841,26 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddr
/* Check the parameters */
assert_param(IS_I2C_MEMADD_SIZE(MemAddSize));
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock /25U /1000U);
- do
- {
- if(count-- == 0U)
- {
+ count = I2C_TIMEOUT_BUSY_FLAG * (SystemCoreClock / 25U / 1000U);
+ do {
+ if (count-- == 0U) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
- return HAL_TIMEOUT;
+ return HAL_TIMEOUT;
}
- }
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
+ } while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) != RESET);
/* Process Locked */
__HAL_LOCK(hi2c);
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -3187,13 +2873,12 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddr
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Prepare transfer parameters */
- hi2c->pBuffPtr = pData;
- hi2c->XferCount = Size;
+ hi2c->pBuffPtr = pData;
+ hi2c->XferCount = Size;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->XferSize = hi2c->XferCount;
- if(hi2c->XferSize > 0U)
- {
+ if (hi2c->XferSize > 0U) {
/* Set the I2C DMA transfer complete callback */
hi2c->hdmarx->XferCpltCallback = I2C_DMAXferCplt;
@@ -3207,29 +2892,22 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddr
HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->DR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize);
/* Send Slave Address and Memory Address */
- if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
- }
- else
- {
+ } else {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_TIMEOUT;
}
}
- if(Size == 1U)
- {
+ if (Size == 1U) {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
- }
- else
- {
+ } else {
/* Enable Last DMA bit */
hi2c->Instance->CR2 |= I2C_CR2_LAST;
}
@@ -3245,23 +2923,17 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddr
process unlock */
/* Enable ERR interrupt */
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_ERR);
-
- /* Enable DMA Request */
+
+ /* Enable DMA Request */
hi2c->Instance->CR2 |= I2C_CR2_DMAEN;
- }
- else
- {
+ } else {
/* Send Slave Address and Memory Address */
- if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG, tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
- }
- else
- {
+ } else {
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
return HAL_TIMEOUT;
@@ -3281,45 +2953,39 @@ HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddr
}
return HAL_OK;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief Checks if target device is ready for communication.
- * @note This function is used with Memory devices
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param Trials Number of trials
- * @param Timeout Timeout duration
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout)
-{
+ * @brief Checks if target device is ready for communication.
+ * @note This function is used with Memory devices
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param Trials Number of trials
+ * @param Timeout Timeout duration
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) {
uint32_t tickstart = 0U, tmp1 = 0U, tmp2 = 0U, tmp3 = 0U, I2C_Trials = 1U;
/* Get tick */
tickstart = HAL_GetTick();
- if(hi2c->State == HAL_I2C_STATE_READY)
- {
+ if (hi2c->State == HAL_I2C_STATE_READY) {
/* Wait until BUSY flag is reset */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) {
return HAL_BUSY;
}
/* Process Locked */
__HAL_LOCK(hi2c);
-
+
/* Check if the I2C is already enabled */
- if((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE)
- {
+ if ((hi2c->Instance->CR1 & I2C_CR1_PE) != I2C_CR1_PE) {
/* Enable I2C peripheral */
__HAL_I2C_ENABLE(hi2c);
}
@@ -3327,18 +2993,16 @@ HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
/* Disable Pos */
hi2c->Instance->CR1 &= ~I2C_CR1_POS;
- hi2c->State = HAL_I2C_STATE_BUSY;
- hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+ hi2c->State = HAL_I2C_STATE_BUSY;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
-
- do
- {
+
+ do {
/* Generate Start */
hi2c->Instance->CR1 |= I2C_CR1_START;
/* Wait until SB flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -3352,10 +3016,8 @@ HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR);
tmp2 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF);
tmp3 = hi2c->State;
- while((tmp1 == RESET) && (tmp2 == RESET) && (tmp3 != HAL_I2C_STATE_TIMEOUT))
- {
- if((Timeout == 0U)||((HAL_GetTick() - tickstart ) > Timeout))
- {
+ while ((tmp1 == RESET) && (tmp2 == RESET) && (tmp3 != HAL_I2C_STATE_TIMEOUT)) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - tickstart) > Timeout)) {
hi2c->State = HAL_I2C_STATE_TIMEOUT;
}
tmp1 = __HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR);
@@ -3366,8 +3028,7 @@ HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
hi2c->State = HAL_I2C_STATE_READY;
/* Check if the ADDR flag has been set */
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
@@ -3375,8 +3036,7 @@ HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
/* Wait until BUSY flag is reset */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -3386,9 +3046,7 @@ HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
__HAL_UNLOCK(hi2c);
return HAL_OK;
- }
- else
- {
+ } else {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
@@ -3396,12 +3054,11 @@ HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
/* Wait until BUSY flag is reset */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY_FLAG, tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
}
- }while(I2C_Trials++ < Trials);
+ } while (I2C_Trials++ < Trials);
hi2c->State = HAL_I2C_STATE_READY;
@@ -3409,71 +3066,58 @@ HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAdd
__HAL_UNLOCK(hi2c);
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_BUSY;
}
}
/**
- * @brief This function handles I2C event interrupt request.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c)
-{
- uint32_t sr2itflags = READ_REG(hi2c->Instance->SR2);
- uint32_t sr1itflags = READ_REG(hi2c->Instance->SR1);
- uint32_t itsources = READ_REG(hi2c->Instance->CR2);
+ * @brief This function handles I2C event interrupt request.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c) {
+ uint32_t sr2itflags = READ_REG(hi2c->Instance->SR2);
+ uint32_t sr1itflags = READ_REG(hi2c->Instance->SR1);
+ uint32_t itsources = READ_REG(hi2c->Instance->CR2);
- uint32_t CurrentMode = hi2c->Mode;
+ uint32_t CurrentMode = hi2c->Mode;
/* Master or Memory mode selected */
- if((CurrentMode == HAL_I2C_MODE_MASTER) || (CurrentMode == HAL_I2C_MODE_MEM))
- {
+ if ((CurrentMode == HAL_I2C_MODE_MASTER) || (CurrentMode == HAL_I2C_MODE_MEM)) {
/* SB Set ----------------------------------------------------------------*/
- if(((sr1itflags & I2C_FLAG_SB) != RESET) && ((itsources & I2C_IT_EVT) != RESET))
- {
+ if (((sr1itflags & I2C_FLAG_SB) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) {
I2C_Master_SB(hi2c);
}
/* ADD10 Set -------------------------------------------------------------*/
- else if(((sr1itflags & I2C_FLAG_ADD10) != RESET) && ((itsources & I2C_IT_EVT) != RESET))
- {
+ else if (((sr1itflags & I2C_FLAG_ADD10) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) {
I2C_Master_ADD10(hi2c);
}
/* ADDR Set --------------------------------------------------------------*/
- else if(((sr1itflags & I2C_FLAG_ADDR) != RESET) && ((itsources & I2C_IT_EVT) != RESET))
- {
+ else if (((sr1itflags & I2C_FLAG_ADDR) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) {
I2C_Master_ADDR(hi2c);
}
/* I2C in mode Transmitter -----------------------------------------------*/
- if((sr2itflags & I2C_FLAG_TRA) != RESET)
- {
+ if ((sr2itflags & I2C_FLAG_TRA) != RESET) {
/* TXE set and BTF reset -----------------------------------------------*/
- if(((sr1itflags & I2C_FLAG_TXE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET))
- {
+ if (((sr1itflags & I2C_FLAG_TXE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET)) {
I2C_MasterTransmit_TXE(hi2c);
}
/* BTF set -------------------------------------------------------------*/
- else if(((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET))
- {
+ else if (((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) {
I2C_MasterTransmit_BTF(hi2c);
}
}
/* I2C in mode Receiver --------------------------------------------------*/
- else
- {
+ else {
/* RXNE set and BTF reset -----------------------------------------------*/
- if(((sr1itflags & I2C_FLAG_RXNE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET))
- {
+ if (((sr1itflags & I2C_FLAG_RXNE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET)) {
I2C_MasterReceive_RXNE(hi2c);
}
/* BTF set -------------------------------------------------------------*/
- else if(((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET))
- {
+ else if (((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET)) {
I2C_MasterReceive_BTF(hi2c);
}
}
@@ -3525,20 +3169,18 @@ void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief This function handles I2C error interrupt request.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c)
-{
+ * @brief This function handles I2C error interrupt request.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) {
uint32_t tmp1 = 0U, tmp2 = 0U, tmp3 = 0U, tmp4 = 0U;
uint32_t sr1itflags = READ_REG(hi2c->Instance->SR1);
uint32_t itsources = READ_REG(hi2c->Instance->CR2);
/* I2C Bus error interrupt occurred ----------------------------------------*/
- if(((sr1itflags & I2C_FLAG_BERR) != RESET) && ((itsources & I2C_IT_ERR) != RESET))
- {
+ if (((sr1itflags & I2C_FLAG_BERR) != RESET) && ((itsources & I2C_IT_ERR) != RESET)) {
hi2c->ErrorCode |= HAL_I2C_ERROR_BERR;
/* Clear BERR flag */
@@ -3549,8 +3191,7 @@ void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c)
}
/* I2C Arbitration Loss error interrupt occurred ---------------------------*/
- if(((sr1itflags & I2C_FLAG_ARLO) != RESET) && ((itsources & I2C_IT_ERR) != RESET))
- {
+ if (((sr1itflags & I2C_FLAG_ARLO) != RESET) && ((itsources & I2C_IT_ERR) != RESET)) {
hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO;
/* Clear ARLO flag */
@@ -3558,27 +3199,21 @@ void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c)
}
/* I2C Acknowledge failure error interrupt occurred ------------------------*/
- if(((sr1itflags & I2C_FLAG_AF) != RESET) && ((itsources & I2C_IT_ERR) != RESET))
- {
+ if (((sr1itflags & I2C_FLAG_AF) != RESET) && ((itsources & I2C_IT_ERR) != RESET)) {
tmp1 = hi2c->Mode;
tmp2 = hi2c->XferCount;
tmp3 = hi2c->State;
tmp4 = hi2c->PreviousState;
- if((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U) && \
- ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || \
- ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX))))
- {
+ if ((tmp1 == HAL_I2C_MODE_SLAVE) && (tmp2 == 0U)
+ && ((tmp3 == HAL_I2C_STATE_BUSY_TX) || (tmp3 == HAL_I2C_STATE_BUSY_TX_LISTEN) || ((tmp3 == HAL_I2C_STATE_LISTEN) && (tmp4 == I2C_STATE_SLAVE_BUSY_TX)))) {
I2C_Slave_AF(hi2c);
- }
- else
- {
+ } else {
hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
/* Do not generate a STOP in case of Slave receive non acknowledge during transfer (mean not at the end of transfer) */
- if(hi2c->Mode == HAL_I2C_MODE_MASTER)
- {
+ if (hi2c->Mode == HAL_I2C_MODE_MASTER) {
/* Generate Stop */
- SET_BIT(hi2c->Instance->CR1,I2C_CR1_STOP);
+ SET_BIT(hi2c->Instance->CR1, I2C_CR1_STOP);
}
/* Clear AF flag */
@@ -3587,28 +3222,25 @@ void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c)
}
/* I2C Over-Run/Under-Run interrupt occurred -------------------------------*/
- if(((sr1itflags & I2C_FLAG_OVR) != RESET) && ((itsources & I2C_IT_ERR) != RESET))
- {
+ if (((sr1itflags & I2C_FLAG_OVR) != RESET) && ((itsources & I2C_IT_ERR) != RESET)) {
hi2c->ErrorCode |= HAL_I2C_ERROR_OVR;
/* Clear OVR flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR);
}
/* Call the Error Callback in case of Error detected -----------------------*/
- if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
- {
+ if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) {
I2C_ITError(hi2c);
}
}
/**
- * @brief Master Tx Transfer completed callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-__weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Master Tx Transfer completed callback.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
@@ -3618,13 +3250,12 @@ __weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Master Rx Transfer completed callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-__weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Master Rx Transfer completed callback.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
@@ -3634,12 +3265,11 @@ __weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c)
}
/** @brief Slave Tx Transfer completed callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-__weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c)
-{
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
@@ -3649,13 +3279,12 @@ __weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Slave Rx Transfer completed callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-__weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Slave Rx Transfer completed callback.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
@@ -3665,15 +3294,14 @@ __weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Slave Address Match callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref I2C_XferOptions_definition
- * @param AddrMatchCode Address Match Code
- * @retval None
- */
-__weak void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode)
-{
+ * @brief Slave Address Match callback.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param TransferDirection Master request Transfer Direction (Write/Read), value of @ref I2C_XferOptions_definition
+ * @param AddrMatchCode Address Match Code
+ * @retval None
+ */
+__weak void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirection, uint16_t AddrMatchCode) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
UNUSED(TransferDirection);
@@ -3685,29 +3313,27 @@ __weak void HAL_I2C_AddrCallback(I2C_HandleTypeDef *hi2c, uint8_t TransferDirect
}
/**
- * @brief Listen Complete callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-__weak void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Listen Complete callback.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_ListenCpltCallback(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
- /* NOTE : This function should not be modified, when the callback is needed,
- the HAL_I2C_ListenCpltCallback can be implemented in the user file
- */
+ /* NOTE : This function should not be modified, when the callback is needed,
+ the HAL_I2C_ListenCpltCallback can be implemented in the user file
+ */
}
/**
- * @brief Memory Tx Transfer completed callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-__weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Memory Tx Transfer completed callback.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
@@ -3717,13 +3343,12 @@ __weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Memory Rx Transfer completed callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-__weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Memory Rx Transfer completed callback.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
@@ -3733,13 +3358,12 @@ __weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief I2C error callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-__weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c)
-{
+ * @brief I2C error callback.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
@@ -3749,13 +3373,12 @@ __weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief I2C abort callback.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval None
- */
-__weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c)
-{
+ * @brief I2C abort callback.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval None
+ */
+__weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c) {
/* Prevent unused argument(s) compilation warning */
UNUSED(hi2c);
@@ -3765,8 +3388,8 @@ __weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c)
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup I2C_Exported_Functions_Group3 Peripheral State, Mode and Error functions
* @brief Peripheral State and Errors functions
@@ -3784,70 +3407,59 @@ __weak void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c)
*/
/**
- * @brief Return the I2C handle state.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval HAL state
- */
-HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Return the I2C handle state.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL state
+ */
+HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c) {
/* Return I2C handle state */
return hi2c->State;
}
/**
- * @brief Return the I2C Master, Slave, Memory or no mode.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL mode
- */
-HAL_I2C_ModeTypeDef HAL_I2C_GetMode(I2C_HandleTypeDef *hi2c)
-{
- return hi2c->Mode;
-}
+ * @brief Return the I2C Master, Slave, Memory or no mode.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL mode
+ */
+HAL_I2C_ModeTypeDef HAL_I2C_GetMode(I2C_HandleTypeDef *hi2c) { return hi2c->Mode; }
/**
- * @brief Return the I2C error code
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval I2C Error Code
- */
-uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c)
-{
- return hi2c->ErrorCode;
-}
+ * @brief Return the I2C error code
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval I2C Error Code
+ */
+uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c) { return hi2c->ErrorCode; }
/**
- * @}
- */
+ * @}
+ */
/**
- * @brief Handle TXE flag for Master
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Handle TXE flag for Master
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c) {
/* Declaration of temporary variables to prevent undefined behavior of volatile usage */
uint32_t CurrentState = hi2c->State;
uint32_t CurrentMode = hi2c->Mode;
uint32_t CurrentXferOptions = hi2c->XferOptions;
- if((hi2c->XferSize == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_TX))
- {
+ if ((hi2c->XferSize == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_TX)) {
/* Call TxCpltCallback() directly if no stop mode is set */
- if((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME))
- {
+ if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) {
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX;
- hi2c->Mode = HAL_I2C_MODE_NONE;
- hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->State = HAL_I2C_STATE_READY;
HAL_I2C_MasterTxCpltCallback(hi2c);
- }
- else /* Generate Stop condition then Call TxCpltCallback() */
+ } else /* Generate Stop condition then Call TxCpltCallback() */
{
/* Disable EVT, BUF and ERR interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
@@ -3856,75 +3468,53 @@ static HAL_StatusTypeDef I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c)
hi2c->Instance->CR1 |= I2C_CR1_STOP;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
- if(hi2c->Mode == HAL_I2C_MODE_MEM)
- {
+ if (hi2c->Mode == HAL_I2C_MODE_MEM) {
hi2c->Mode = HAL_I2C_MODE_NONE;
HAL_I2C_MemTxCpltCallback(hi2c);
- }
- else
- {
+ } else {
hi2c->Mode = HAL_I2C_MODE_NONE;
HAL_I2C_MasterTxCpltCallback(hi2c);
}
}
- }
- else if((CurrentState == HAL_I2C_STATE_BUSY_TX) || \
- ((CurrentMode == HAL_I2C_MODE_MEM) && (CurrentState == HAL_I2C_STATE_BUSY_RX)))
- {
- if(hi2c->XferCount == 0U)
- {
+ } else if ((CurrentState == HAL_I2C_STATE_BUSY_TX) || ((CurrentMode == HAL_I2C_MODE_MEM) && (CurrentState == HAL_I2C_STATE_BUSY_RX))) {
+ if (hi2c->XferCount == 0U) {
/* Disable BUF interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF);
- }
- else
- {
- if(hi2c->Mode == HAL_I2C_MODE_MEM)
- {
- if(hi2c->EventCount == 0)
- {
+ } else {
+ if (hi2c->Mode == HAL_I2C_MODE_MEM) {
+ if (hi2c->EventCount == 0) {
/* If Memory address size is 8Bit */
- if(hi2c->MemaddSize == I2C_MEMADD_SIZE_8BIT)
- {
+ if (hi2c->MemaddSize == I2C_MEMADD_SIZE_8BIT) {
/* Send Memory Address */
hi2c->Instance->DR = I2C_MEM_ADD_LSB(hi2c->Memaddress);
-
+
hi2c->EventCount += 2;
}
/* If Memory address size is 16Bit */
- else
- {
+ else {
/* Send MSB of Memory Address */
hi2c->Instance->DR = I2C_MEM_ADD_MSB(hi2c->Memaddress);
-
+
hi2c->EventCount++;
}
- }
- else if(hi2c->EventCount == 1)
- {
+ } else if (hi2c->EventCount == 1) {
/* Send LSB of Memory Address */
hi2c->Instance->DR = I2C_MEM_ADD_LSB(hi2c->Memaddress);
-
+
hi2c->EventCount++;
- }
- else if(hi2c->EventCount == 2)
- {
- if(hi2c->State == HAL_I2C_STATE_BUSY_RX)
- {
+ } else if (hi2c->EventCount == 2) {
+ if (hi2c->State == HAL_I2C_STATE_BUSY_RX) {
/* Generate Restart */
hi2c->Instance->CR1 |= I2C_CR1_START;
- }
- else if(hi2c->State == HAL_I2C_STATE_BUSY_TX)
- {
+ } else if (hi2c->State == HAL_I2C_STATE_BUSY_TX) {
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferCount--;
}
}
- }
- else
- {
+ } else {
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferCount--;
@@ -3935,58 +3525,48 @@ static HAL_StatusTypeDef I2C_MasterTransmit_TXE(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle BTF flag for Master transmitter
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Handle BTF flag for Master transmitter
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c) {
/* Declaration of temporary variables to prevent undefined behavior of volatile usage */
uint32_t CurrentXferOptions = hi2c->XferOptions;
- if(hi2c->State == HAL_I2C_STATE_BUSY_TX)
- {
- if(hi2c->XferCount != 0U)
- {
+ if (hi2c->State == HAL_I2C_STATE_BUSY_TX) {
+ if (hi2c->XferCount != 0U) {
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferCount--;
- }
- else
- {
+ } else {
/* Call TxCpltCallback() directly if no stop mode is set */
- if((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME))
- {
+ if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) {
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
-
+
hi2c->PreviousState = I2C_STATE_MASTER_BUSY_TX;
- hi2c->Mode = HAL_I2C_MODE_NONE;
- hi2c->State = HAL_I2C_STATE_READY;
-
+ hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->State = HAL_I2C_STATE_READY;
+
HAL_I2C_MasterTxCpltCallback(hi2c);
- }
- else /* Generate Stop condition then Call TxCpltCallback() */
+ } else /* Generate Stop condition then Call TxCpltCallback() */
{
/* Disable EVT, BUF and ERR interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
-
+
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
-
+
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State = HAL_I2C_STATE_READY;
-
- if(hi2c->Mode == HAL_I2C_MODE_MEM)
- {
+ hi2c->State = HAL_I2C_STATE_READY;
+
+ if (hi2c->Mode == HAL_I2C_MODE_MEM) {
hi2c->Mode = HAL_I2C_MODE_NONE;
-
+
HAL_I2C_MemTxCpltCallback(hi2c);
- }
- else
- {
+ } else {
hi2c->Mode = HAL_I2C_MODE_NONE;
-
+
HAL_I2C_MasterTxCpltCallback(hi2c);
}
}
@@ -3996,73 +3576,57 @@ static HAL_StatusTypeDef I2C_MasterTransmit_BTF(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle RXNE flag for Master
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c)
-{
- if(hi2c->State == HAL_I2C_STATE_BUSY_RX)
- {
+ * @brief Handle RXNE flag for Master
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c) {
+ if (hi2c->State == HAL_I2C_STATE_BUSY_RX) {
uint32_t tmp = 0U;
-
+
tmp = hi2c->XferCount;
- if(tmp > 3U)
- {
+ if (tmp > 3U) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferCount--;
- }
- else if((tmp == 2U) || (tmp == 3U))
- {
- if(hi2c->XferOptions != I2C_NEXT_FRAME)
- {
+ } else if ((tmp == 2U) || (tmp == 3U)) {
+ if (hi2c->XferOptions != I2C_NEXT_FRAME) {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
-
+
/* Enable Pos */
hi2c->Instance->CR1 |= I2C_CR1_POS;
- }
- else
- {
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
}
-
+
/* Disable BUF interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF);
- }
- else
- {
- if(hi2c->XferOptions != I2C_NEXT_FRAME)
- {
+ } else {
+ if (hi2c->XferOptions != I2C_NEXT_FRAME) {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
- }
- else
- {
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
}
/* Disable EVT, BUF and ERR interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
-
+
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferCount--;
- hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
- if(hi2c->Mode == HAL_I2C_MODE_MEM)
- {
+ if (hi2c->Mode == HAL_I2C_MODE_MEM) {
hi2c->Mode = HAL_I2C_MODE_NONE;
HAL_I2C_MemRxCpltCallback(hi2c);
- }
- else
- {
+ } else {
hi2c->Mode = HAL_I2C_MODE_NONE;
HAL_I2C_MasterRxCpltCallback(hi2c);
}
@@ -4072,20 +3636,17 @@ static HAL_StatusTypeDef I2C_MasterReceive_RXNE(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle BTF flag for Master receiver
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Handle BTF flag for Master receiver
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c) {
/* Declaration of temporary variables to prevent undefined behavior of volatile usage */
uint32_t CurrentXferOptions = hi2c->XferOptions;
- if(hi2c->XferCount == 3U)
- {
- if((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME))
- {
+ if (hi2c->XferCount == 3U) {
+ if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
}
@@ -4093,31 +3654,23 @@ static HAL_StatusTypeDef I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c)
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferCount--;
- }
- else if(hi2c->XferCount == 2U)
- {
+ } else if (hi2c->XferCount == 2U) {
/* Prepare next transfer or stop current transfer */
- if((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME))
- {
- if(CurrentXferOptions != I2C_NEXT_FRAME)
- {
+ if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (CurrentXferOptions != I2C_NO_OPTION_FRAME)) {
+ if (CurrentXferOptions != I2C_NEXT_FRAME) {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
- }
- else
- {
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
}
/* Disable EVT and ERR interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR);
- }
- else
- {
+ } else {
/* Disable EVT and ERR interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR);
-
+
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
}
@@ -4130,24 +3683,19 @@ static HAL_StatusTypeDef I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c)
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferCount--;
- hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
hi2c->PreviousState = I2C_STATE_NONE;
- if(hi2c->Mode == HAL_I2C_MODE_MEM)
- {
+ if (hi2c->Mode == HAL_I2C_MODE_MEM) {
hi2c->Mode = HAL_I2C_MODE_NONE;
HAL_I2C_MemRxCpltCallback(hi2c);
- }
- else
- {
+ } else {
hi2c->Mode = HAL_I2C_MODE_NONE;
HAL_I2C_MasterRxCpltCallback(hi2c);
}
- }
- else
- {
+ } else {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferCount--;
@@ -4156,48 +3704,32 @@ static HAL_StatusTypeDef I2C_MasterReceive_BTF(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle SB flag for Master
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_Master_SB(I2C_HandleTypeDef *hi2c)
-{
- if(hi2c->Mode == HAL_I2C_MODE_MEM)
- {
- if(hi2c->EventCount == 0U)
- {
+ * @brief Handle SB flag for Master
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_Master_SB(I2C_HandleTypeDef *hi2c) {
+ if (hi2c->Mode == HAL_I2C_MODE_MEM) {
+ if (hi2c->EventCount == 0U) {
/* Send slave address */
hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(hi2c->Devaddress);
- }
- else
- {
+ } else {
hi2c->Instance->DR = I2C_7BIT_ADD_READ(hi2c->Devaddress);
}
- }
- else
- {
- if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT)
- {
+ } else {
+ if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) {
/* Send slave 7 Bits address */
- if(hi2c->State == HAL_I2C_STATE_BUSY_TX)
- {
+ if (hi2c->State == HAL_I2C_STATE_BUSY_TX) {
hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(hi2c->Devaddress);
- }
- else
- {
+ } else {
hi2c->Instance->DR = I2C_7BIT_ADD_READ(hi2c->Devaddress);
}
- }
- else
- {
- if(hi2c->EventCount == 0U)
- {
+ } else {
+ if (hi2c->EventCount == 0U) {
/* Send header of slave address */
hi2c->Instance->DR = I2C_10BIT_HEADER_WRITE(hi2c->Devaddress);
- }
- else if(hi2c->EventCount == 1U)
- {
+ } else if (hi2c->EventCount == 1U) {
/* Send header of slave address */
hi2c->Instance->DR = I2C_10BIT_HEADER_READ(hi2c->Devaddress);
}
@@ -4208,13 +3740,12 @@ static HAL_StatusTypeDef I2C_Master_SB(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle ADD10 flag for Master
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_Master_ADD10(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Handle ADD10 flag for Master
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_Master_ADD10(I2C_HandleTypeDef *hi2c) {
/* Send slave address */
hi2c->Instance->DR = I2C_10BIT_ADDRESS(hi2c->Devaddress);
@@ -4222,62 +3753,48 @@ static HAL_StatusTypeDef I2C_Master_ADD10(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle ADDR flag for Master
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_Master_ADDR(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Handle ADDR flag for Master
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_Master_ADDR(I2C_HandleTypeDef *hi2c) {
/* Declaration of temporary variable to prevent undefined behavior of volatile usage */
uint32_t CurrentMode = hi2c->Mode;
uint32_t CurrentXferOptions = hi2c->XferOptions;
uint32_t Prev_State = hi2c->PreviousState;
- if(hi2c->State == HAL_I2C_STATE_BUSY_RX)
- {
- if((hi2c->EventCount == 0U) && (CurrentMode == HAL_I2C_MODE_MEM))
- {
+ if (hi2c->State == HAL_I2C_STATE_BUSY_RX) {
+ if ((hi2c->EventCount == 0U) && (CurrentMode == HAL_I2C_MODE_MEM)) {
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
- }
- else if((hi2c->EventCount == 0U) && (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT))
- {
+ } else if ((hi2c->EventCount == 0U) && (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT)) {
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
-
+
/* Generate Restart */
hi2c->Instance->CR1 |= I2C_CR1_START;
-
+
hi2c->EventCount++;
- }
- else
- {
- if(hi2c->XferCount == 0U)
- {
+ } else {
+ if (hi2c->XferCount == 0U) {
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
-
+
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
- }
- else if(hi2c->XferCount == 1U)
- {
- if(CurrentXferOptions == I2C_NO_OPTION_FRAME)
- {
+ } else if (hi2c->XferCount == 1U) {
+ if (CurrentXferOptions == I2C_NO_OPTION_FRAME) {
/* Disable Acknowledge */
- hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
+ hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
- if((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN)
- {
+ if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
- }
- else
- {
+ } else {
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
@@ -4286,70 +3803,54 @@ static HAL_StatusTypeDef I2C_Master_ADDR(I2C_HandleTypeDef *hi2c)
}
}
/* Prepare next transfer or stop current transfer */
- else if((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) \
- && (Prev_State != I2C_STATE_MASTER_BUSY_RX))
- {
- if(hi2c->XferOptions != I2C_NEXT_FRAME)
- {
+ else if ((CurrentXferOptions != I2C_FIRST_AND_LAST_FRAME) && (CurrentXferOptions != I2C_LAST_FRAME) && (Prev_State != I2C_STATE_MASTER_BUSY_RX)) {
+ if (hi2c->XferOptions != I2C_NEXT_FRAME) {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
- }
- else
- {
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
}
-
+
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
- }
- else
- {
+ } else {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
-
+
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
-
+
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
}
- }
- else if(hi2c->XferCount == 2U)
- {
- if(hi2c->XferOptions != I2C_NEXT_FRAME)
- {
+ } else if (hi2c->XferCount == 2U) {
+ if (hi2c->XferOptions != I2C_NEXT_FRAME) {
/* Enable Pos */
hi2c->Instance->CR1 |= I2C_CR1_POS;
-
+
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
-
+
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
- }
- else
- {
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
-
+
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
}
- if((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN)
- {
+ if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) {
/* Enable Last DMA bit */
hi2c->Instance->CR2 |= I2C_CR2_LAST;
}
- }
- else
- {
+ } else {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
- if((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN)
- {
+ if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) {
/* Enable Last DMA bit */
hi2c->Instance->CR2 |= I2C_CR2_LAST;
}
@@ -4357,13 +3858,11 @@ static HAL_StatusTypeDef I2C_Master_ADDR(I2C_HandleTypeDef *hi2c)
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
}
-
+
/* Reset Event counter */
hi2c->EventCount = 0U;
}
- }
- else
- {
+ } else {
/* Clear ADDR flag */
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
}
@@ -4372,31 +3871,28 @@ static HAL_StatusTypeDef I2C_Master_ADDR(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle TXE flag for Slave
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_SlaveTransmit_TXE(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Handle TXE flag for Slave
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_SlaveTransmit_TXE(I2C_HandleTypeDef *hi2c) {
/* Declaration of temporary variables to prevent undefined behavior of volatile usage */
uint32_t CurrentState = hi2c->State;
- if(hi2c->XferCount != 0U)
- {
+ if (hi2c->XferCount != 0U) {
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferCount--;
- if((hi2c->XferCount == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN))
- {
+ if ((hi2c->XferCount == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN)) {
/* Last Byte is received, disable Interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF);
-
+
/* Set state at HAL_I2C_STATE_LISTEN */
hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX;
- hi2c->State = HAL_I2C_STATE_LISTEN;
-
+ hi2c->State = HAL_I2C_STATE_LISTEN;
+
/* Call the Tx complete callback to inform upper layer of the end of receive process */
HAL_I2C_SlaveTxCpltCallback(hi2c);
}
@@ -4405,15 +3901,13 @@ static HAL_StatusTypeDef I2C_SlaveTransmit_TXE(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle BTF flag for Slave transmitter
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_SlaveTransmit_BTF(I2C_HandleTypeDef *hi2c)
-{
- if(hi2c->XferCount != 0U)
- {
+ * @brief Handle BTF flag for Slave transmitter
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_SlaveTransmit_BTF(I2C_HandleTypeDef *hi2c) {
+ if (hi2c->XferCount != 0U) {
/* Write data to DR */
hi2c->Instance->DR = (*hi2c->pBuffPtr++);
hi2c->XferCount--;
@@ -4422,30 +3916,27 @@ static HAL_StatusTypeDef I2C_SlaveTransmit_BTF(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle RXNE flag for Slave
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_SlaveReceive_RXNE(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Handle RXNE flag for Slave
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_SlaveReceive_RXNE(I2C_HandleTypeDef *hi2c) {
/* Declaration of temporary variables to prevent undefined behavior of volatile usage */
uint32_t CurrentState = hi2c->State;
- if(hi2c->XferCount != 0U)
- {
+ if (hi2c->XferCount != 0U) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferCount--;
- if((hi2c->XferCount == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN))
- {
+ if ((hi2c->XferCount == 0U) && (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN)) {
/* Last Byte is received, disable Interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_BUF);
/* Set state at HAL_I2C_STATE_LISTEN */
hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_RX;
- hi2c->State = HAL_I2C_STATE_LISTEN;
+ hi2c->State = HAL_I2C_STATE_LISTEN;
/* Call the Rx complete callback to inform upper layer of the end of receive process */
HAL_I2C_SlaveRxCpltCallback(hi2c);
@@ -4455,15 +3946,13 @@ static HAL_StatusTypeDef I2C_SlaveReceive_RXNE(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle BTF flag for Slave receiver
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_SlaveReceive_BTF(I2C_HandleTypeDef *hi2c)
-{
- if(hi2c->XferCount != 0U)
- {
+ * @brief Handle BTF flag for Slave receiver
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_SlaveReceive_BTF(I2C_HandleTypeDef *hi2c) {
+ if (hi2c->XferCount != 0U) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferCount--;
@@ -4472,28 +3961,23 @@ static HAL_StatusTypeDef I2C_SlaveReceive_BTF(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle ADD flag for Slave
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c)
-{
- uint8_t TransferDirection = I2C_DIRECTION_RECEIVE;
- uint16_t SlaveAddrCode = 0U;
+ * @brief Handle ADD flag for Slave
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c) {
+ uint8_t TransferDirection = I2C_DIRECTION_RECEIVE;
+ uint16_t SlaveAddrCode = 0U;
/* Transfer Direction requested by Master */
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TRA) == RESET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TRA) == RESET) {
TransferDirection = I2C_DIRECTION_TRANSMIT;
}
-
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_DUALF) == RESET)
- {
+
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_DUALF) == RESET) {
SlaveAddrCode = hi2c->Init.OwnAddress1;
- }
- else
- {
+ } else {
SlaveAddrCode = hi2c->Init.OwnAddress2;
}
@@ -4504,16 +3988,15 @@ static HAL_StatusTypeDef I2C_Slave_ADDR(I2C_HandleTypeDef *hi2c)
}
/**
- * @brief Handle STOPF flag for Slave
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c)
-{
+ * @brief Handle STOPF flag for Slave
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c) {
/* Declaration of temporary variable to prevent undefined behavior of volatile usage */
uint32_t CurrentState = hi2c->State;
-
+
/* Disable EVT, BUF and ERR interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
@@ -4524,32 +4007,25 @@ static HAL_StatusTypeDef I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c)
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
/* If a DMA is ongoing, Update handle size context */
- if((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN)
- {
- if((hi2c->State == HAL_I2C_STATE_BUSY_RX) || (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN))
- {
+ if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) {
+ if ((hi2c->State == HAL_I2C_STATE_BUSY_RX) || (hi2c->State == HAL_I2C_STATE_BUSY_RX_LISTEN)) {
hi2c->XferCount = __HAL_DMA_GET_COUNTER(hi2c->hdmarx);
- }
- else
- {
+ } else {
hi2c->XferCount = __HAL_DMA_GET_COUNTER(hi2c->hdmatx);
}
}
/* All data are not transferred, so set error code accordingly */
- if(hi2c->XferCount != 0U)
- {
+ if (hi2c->XferCount != 0U) {
/* Store Last receive data if any */
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == SET) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferCount--;
}
/* Store Last receive data if any */
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
hi2c->XferCount--;
@@ -4559,31 +4035,23 @@ static HAL_StatusTypeDef I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c)
hi2c->ErrorCode |= HAL_I2C_ERROR_AF;
}
- if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
- {
+ if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) {
/* Call the corresponding callback to inform upper layer of End of Transfer */
I2C_ITError(hi2c);
- }
- else
- {
- if((CurrentState == HAL_I2C_STATE_LISTEN ) || (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN) || \
- (CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN))
- {
- hi2c->XferOptions = I2C_NO_OPTION_FRAME;
+ } else {
+ if ((CurrentState == HAL_I2C_STATE_LISTEN) || (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN) || (CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN)) {
+ hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
/* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
HAL_I2C_ListenCpltCallback(hi2c);
- }
- else
- {
- if((hi2c->PreviousState == I2C_STATE_SLAVE_BUSY_RX) || (CurrentState == HAL_I2C_STATE_BUSY_RX))
- {
+ } else {
+ if ((hi2c->PreviousState == I2C_STATE_SLAVE_BUSY_RX) || (CurrentState == HAL_I2C_STATE_BUSY_RX)) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
HAL_I2C_SlaveRxCpltCallback(hi2c);
}
@@ -4593,19 +4061,16 @@ static HAL_StatusTypeDef I2C_Slave_STOPF(I2C_HandleTypeDef *hi2c)
}
/**
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_Slave_AF(I2C_HandleTypeDef *hi2c)
-{
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_Slave_AF(I2C_HandleTypeDef *hi2c) {
/* Declaration of temporary variables to prevent undefined behavior of volatile usage */
uint32_t CurrentState = hi2c->State;
uint32_t CurrentXferOptions = hi2c->XferOptions;
- if(((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) && \
- (CurrentState == HAL_I2C_STATE_LISTEN))
- {
+ if (((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_LAST_FRAME)) && (CurrentState == HAL_I2C_STATE_LISTEN)) {
hi2c->XferOptions = I2C_NO_OPTION_FRAME;
/* Disable EVT, BUF and ERR interrupt */
@@ -4618,19 +4083,17 @@ static HAL_StatusTypeDef I2C_Slave_AF(I2C_HandleTypeDef *hi2c)
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
-
+ hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
+
/* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
HAL_I2C_ListenCpltCallback(hi2c);
- }
- else if(CurrentState == HAL_I2C_STATE_BUSY_TX)
- {
- hi2c->XferOptions = I2C_NO_OPTION_FRAME;
+ } else if (CurrentState == HAL_I2C_STATE_BUSY_TX) {
+ hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->PreviousState = I2C_STATE_SLAVE_BUSY_TX;
- hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
-
+ hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
+
/* Disable EVT, BUF and ERR interrupt */
__HAL_I2C_DISABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_BUF | I2C_IT_ERR);
@@ -4641,61 +4104,51 @@ static HAL_StatusTypeDef I2C_Slave_AF(I2C_HandleTypeDef *hi2c)
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
HAL_I2C_SlaveTxCpltCallback(hi2c);
- }
- else
- {
+ } else {
/* Clear AF flag only */
/* State Listen, but XferOptions == FIRST or NEXT */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
}
-
+
return HAL_OK;
}
/**
- * @brief I2C interrupts error process
- * @param hi2c I2C handle.
- * @retval None
- */
-static void I2C_ITError(I2C_HandleTypeDef *hi2c)
-{
+ * @brief I2C interrupts error process
+ * @param hi2c I2C handle.
+ * @retval None
+ */
+static void I2C_ITError(I2C_HandleTypeDef *hi2c) {
/* Declaration of temporary variable to prevent undefined behavior of volatile usage */
uint32_t CurrentState = hi2c->State;
- if((CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN) || (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN))
- {
+ if ((CurrentState == HAL_I2C_STATE_BUSY_TX_LISTEN) || (CurrentState == HAL_I2C_STATE_BUSY_RX_LISTEN)) {
/* keep HAL_I2C_STATE_LISTEN */
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State = HAL_I2C_STATE_LISTEN;
- }
- else
- {
+ hi2c->State = HAL_I2C_STATE_LISTEN;
+ } else {
/* If state is an abort treatment on going, don't change state */
/* This change will be do later */
- if((hi2c->State != HAL_I2C_STATE_ABORT) && ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) != I2C_CR2_DMAEN))
- {
+ if ((hi2c->State != HAL_I2C_STATE_ABORT) && ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) != I2C_CR2_DMAEN)) {
hi2c->State = HAL_I2C_STATE_READY;
}
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
}
/* Disable Pos bit in I2C CR1 when error occurred in Master/Mem Receive IT Process */
hi2c->Instance->CR1 &= ~I2C_CR1_POS;
/* Abort DMA transfer */
- if((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN)
- {
+ if ((hi2c->Instance->CR2 & I2C_CR2_DMAEN) == I2C_CR2_DMAEN) {
hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN;
- if(hi2c->hdmatx->State != HAL_DMA_STATE_READY)
- {
- /* Set the DMA Abort callback :
+ if (hi2c->hdmatx->State != HAL_DMA_STATE_READY) {
+ /* Set the DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmatx->XferAbortCallback = I2C_DMAAbort;
- if(HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK)
- {
+ if (HAL_DMA_Abort_IT(hi2c->hdmatx) != HAL_OK) {
/* Disable I2C peripheral to prevent dummy data in buffer */
__HAL_I2C_DISABLE(hi2c);
@@ -4704,18 +4157,14 @@ static void I2C_ITError(I2C_HandleTypeDef *hi2c)
/* Call Directly XferAbortCallback function in case of error */
hi2c->hdmatx->XferAbortCallback(hi2c->hdmatx);
}
- }
- else
- {
- /* Set the DMA Abort callback :
+ } else {
+ /* Set the DMA Abort callback :
will lead to call HAL_I2C_ErrorCallback() at end of DMA abort procedure */
hi2c->hdmarx->XferAbortCallback = I2C_DMAAbort;
- if(HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK)
- {
+ if (HAL_DMA_Abort_IT(hi2c->hdmarx) != HAL_OK) {
/* Store Last receive data if any */
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
}
@@ -4729,15 +4178,12 @@ static void I2C_ITError(I2C_HandleTypeDef *hi2c)
hi2c->hdmarx->XferAbortCallback(hi2c->hdmarx);
}
}
- }
- else if(hi2c->State == HAL_I2C_STATE_ABORT)
- {
- hi2c->State = HAL_I2C_STATE_READY;
+ } else if (hi2c->State == HAL_I2C_STATE_ABORT) {
+ hi2c->State = HAL_I2C_STATE_READY;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Store Last receive data if any */
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
}
@@ -4747,12 +4193,9 @@ static void I2C_ITError(I2C_HandleTypeDef *hi2c)
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_I2C_AbortCpltCallback(hi2c);
- }
- else
- {
+ } else {
/* Store Last receive data if any */
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) {
/* Read data from DR */
(*hi2c->pBuffPtr++) = hi2c->Instance->DR;
}
@@ -4763,69 +4206,56 @@ static void I2C_ITError(I2C_HandleTypeDef *hi2c)
/* STOP Flag is not set after a NACK reception */
/* So may inform upper layer that listen phase is stopped */
/* during NACK error treatment */
- if((hi2c->State == HAL_I2C_STATE_LISTEN) && ((hi2c->ErrorCode & HAL_I2C_ERROR_AF) == HAL_I2C_ERROR_AF))
- {
- hi2c->XferOptions = I2C_NO_OPTION_FRAME;
+ if ((hi2c->State == HAL_I2C_STATE_LISTEN) && ((hi2c->ErrorCode & HAL_I2C_ERROR_AF) == HAL_I2C_ERROR_AF)) {
+ hi2c->XferOptions = I2C_NO_OPTION_FRAME;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
-
+ hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
+
/* Call the Listen Complete callback, to inform upper layer of the end of Listen usecase */
HAL_I2C_ListenCpltCallback(hi2c);
}
}
/**
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart)
-{
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart) {
/* Declaration of temporary variable to prevent undefined behavior of volatile usage */
uint32_t CurrentXferOptions = hi2c->XferOptions;
/* Generate Start condition if first transfer */
- if((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME))
- {
+ if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) {
/* Generate Start */
hi2c->Instance->CR1 |= I2C_CR1_START;
- }
- else if(hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX)
- {
+ } else if (hi2c->PreviousState == I2C_STATE_MASTER_BUSY_RX) {
/* Generate ReStart */
hi2c->Instance->CR1 |= I2C_CR1_START;
}
/* Wait until SB flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
- if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT)
- {
+ if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) {
/* Send slave address */
hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress);
- }
- else
- {
+ } else {
/* Send header of slave address */
hi2c->Instance->DR = I2C_10BIT_HEADER_WRITE(DevAddress);
/* Wait until ADD10 flag is set */
- if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -4835,14 +4265,10 @@ static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_
}
/* Wait until ADDR flag is set */
- if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -4851,17 +4277,16 @@ static HAL_StatusTypeDef I2C_MasterRequestWrite(I2C_HandleTypeDef *hi2c, uint16_
}
/**
- * @brief Master sends target device address for read request.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart)
-{
+ * @brief Master sends target device address for read request.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Timeout, uint32_t Tickstart) {
/* Declaration of temporary variable to prevent undefined behavior of volatile usage */
uint32_t CurrentXferOptions = hi2c->XferOptions;
@@ -4869,42 +4294,31 @@ static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t
hi2c->Instance->CR1 |= I2C_CR1_ACK;
/* Generate Start condition if first transfer */
- if((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME))
- {
+ if ((CurrentXferOptions == I2C_FIRST_AND_LAST_FRAME) || (CurrentXferOptions == I2C_FIRST_FRAME) || (CurrentXferOptions == I2C_NO_OPTION_FRAME)) {
/* Generate Start */
hi2c->Instance->CR1 |= I2C_CR1_START;
- }
- else if(hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX)
- {
+ } else if (hi2c->PreviousState == I2C_STATE_MASTER_BUSY_TX) {
/* Generate ReStart */
hi2c->Instance->CR1 |= I2C_CR1_START;
}
/* Wait until SB flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
- if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT)
- {
+ if (hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) {
/* Send slave address */
hi2c->Instance->DR = I2C_7BIT_ADD_READ(DevAddress);
- }
- else
- {
+ } else {
/* Send header of slave address */
hi2c->Instance->DR = I2C_10BIT_HEADER_WRITE(DevAddress);
/* Wait until ADD10 flag is set */
- if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADD10, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -4913,14 +4327,10 @@ static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t
hi2c->Instance->DR = I2C_10BIT_ADDRESS(DevAddress);
/* Wait until ADDR flag is set */
- if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -4932,8 +4342,7 @@ static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t
hi2c->Instance->CR1 |= I2C_CR1_START;
/* Wait until SB flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -4942,14 +4351,10 @@ static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t
}
/* Wait until ADDR flag is set */
- if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -4958,25 +4363,23 @@ static HAL_StatusTypeDef I2C_MasterRequestRead(I2C_HandleTypeDef *hi2c, uint16_t
}
/**
- * @brief Master sends target device address followed by internal memory address for write request.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param MemAddress Internal memory address
- * @param MemAddSize Size of internal memory address
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart)
-{
+ * @brief Master sends target device address followed by internal memory address for write request.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param MemAddress Internal memory address
+ * @param MemAddSize Size of internal memory address
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart) {
/* Generate Start */
hi2c->Instance->CR1 |= I2C_CR1_START;
/* Wait until SB flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -4984,14 +4387,10 @@ static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_
hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress);
/* Wait until ADDR flag is set */
- if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -5000,43 +4399,33 @@ static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
/* Wait until TXE flag is set */
- if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
/* If Memory address size is 8Bit */
- if(MemAddSize == I2C_MEMADD_SIZE_8BIT)
- {
+ if (MemAddSize == I2C_MEMADD_SIZE_8BIT) {
/* Send Memory Address */
hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress);
}
/* If Memory address size is 16Bit */
- else
- {
+ else {
/* Send MSB of Memory Address */
hi2c->Instance->DR = I2C_MEM_ADD_MSB(MemAddress);
/* Wait until TXE flag is set */
- if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -5049,19 +4438,18 @@ static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_
}
/**
- * @brief Master sends target device address followed by internal memory address for read request.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @param DevAddress Target device address: The device 7 bits address value
- * in datasheet must be shifted to the left before calling the interface
- * @param MemAddress Internal memory address
- * @param MemAddSize Size of internal memory address
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart)
-{
+ * @brief Master sends target device address followed by internal memory address for read request.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @param DevAddress Target device address: The device 7 bits address value
+ * in datasheet must be shifted to the left before calling the interface
+ * @param MemAddress Internal memory address
+ * @param MemAddSize Size of internal memory address
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout, uint32_t Tickstart) {
/* Enable Acknowledge */
hi2c->Instance->CR1 |= I2C_CR1_ACK;
@@ -5069,8 +4457,7 @@ static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t
hi2c->Instance->CR1 |= I2C_CR1_START;
/* Wait until SB flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -5078,14 +4465,10 @@ static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t
hi2c->Instance->DR = I2C_7BIT_ADD_WRITE(DevAddress);
/* Wait until ADDR flag is set */
- if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -5094,43 +4477,33 @@ static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t
__HAL_I2C_CLEAR_ADDRFLAG(hi2c);
/* Wait until TXE flag is set */
- if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
/* If Memory address size is 8Bit */
- if(MemAddSize == I2C_MEMADD_SIZE_8BIT)
- {
+ if (MemAddSize == I2C_MEMADD_SIZE_8BIT) {
/* Send Memory Address */
hi2c->Instance->DR = I2C_MEM_ADD_LSB(MemAddress);
}
/* If Memory address size is 16Bit */
- else
- {
+ else {
/* Send MSB of Memory Address */
hi2c->Instance->DR = I2C_MEM_ADD_MSB(MemAddress);
/* Wait until TXE flag is set */
- if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -5140,16 +4513,12 @@ static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t
}
/* Wait until TXE flag is set */
- if(I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnTXEFlagUntilTimeout(hi2c, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -5158,8 +4527,7 @@ static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t
hi2c->Instance->CR1 |= I2C_CR1_START;
/* Wait until SB flag is set */
- if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK)
- {
+ if (I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_SB, RESET, Timeout, Tickstart) != HAL_OK) {
return HAL_TIMEOUT;
}
@@ -5167,14 +4535,10 @@ static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t
hi2c->Instance->DR = I2C_7BIT_ADD_READ(DevAddress);
/* Wait until ADDR flag is set */
- if(I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK)
- {
- if(hi2c->ErrorCode == HAL_I2C_ERROR_AF)
- {
+ if (I2C_WaitOnMasterAddressFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, Timeout, Tickstart) != HAL_OK) {
+ if (hi2c->ErrorCode == HAL_I2C_ERROR_AF) {
return HAL_ERROR;
- }
- else
- {
+ } else {
return HAL_TIMEOUT;
}
}
@@ -5183,61 +4547,51 @@ static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t
}
/**
- * @brief DMA I2C process complete callback.
- * @param hdma DMA handle
- * @retval None
- */
-static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma)
-{
- I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
-
+ * @brief DMA I2C process complete callback.
+ * @param hdma DMA handle
+ * @retval None
+ */
+static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma) {
+ I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
+
/* Declaration of temporary variable to prevent undefined behavior of volatile usage */
uint32_t CurrentState = hi2c->State;
uint32_t CurrentMode = hi2c->Mode;
- if((CurrentState == HAL_I2C_STATE_BUSY_TX) || ((CurrentState == HAL_I2C_STATE_BUSY_RX) && (CurrentMode == HAL_I2C_MODE_SLAVE)))
- {
+ if ((CurrentState == HAL_I2C_STATE_BUSY_TX) || ((CurrentState == HAL_I2C_STATE_BUSY_RX) && (CurrentMode == HAL_I2C_MODE_SLAVE))) {
/* Disable DMA Request */
hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN;
-
+
hi2c->XferCount = 0U;
-
+
/* Enable EVT and ERR interrupt */
__HAL_I2C_ENABLE_IT(hi2c, I2C_IT_EVT | I2C_IT_ERR);
- }
- else
- {
+ } else {
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
-
+
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
-
+
/* Disable Last DMA */
hi2c->Instance->CR2 &= ~I2C_CR2_LAST;
-
+
/* Disable DMA Request */
hi2c->Instance->CR2 &= ~I2C_CR2_DMAEN;
-
+
hi2c->XferCount = 0U;
/* Check if Errors has been detected during transfer */
- if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE)
- {
+ if (hi2c->ErrorCode != HAL_I2C_ERROR_NONE) {
HAL_I2C_ErrorCallback(hi2c);
- }
- else
- {
+ } else {
hi2c->State = HAL_I2C_STATE_READY;
- if(hi2c->Mode == HAL_I2C_MODE_MEM)
- {
+ if (hi2c->Mode == HAL_I2C_MODE_MEM) {
hi2c->Mode = HAL_I2C_MODE_NONE;
HAL_I2C_MemRxCpltCallback(hi2c);
- }
- else
- {
+ } else {
hi2c->Mode = HAL_I2C_MODE_NONE;
HAL_I2C_MasterRxCpltCallback(hi2c);
@@ -5247,37 +4601,35 @@ static void I2C_DMAXferCplt(DMA_HandleTypeDef *hdma)
}
/**
- * @brief DMA I2C communication error callback.
- * @param hdma DMA handle
- * @retval None
- */
-static void I2C_DMAError(DMA_HandleTypeDef *hdma)
-{
- I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent;
-
+ * @brief DMA I2C communication error callback.
+ * @param hdma DMA handle
+ * @retval None
+ */
+static void I2C_DMAError(DMA_HandleTypeDef *hdma) {
+ I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
+
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
-
+
hi2c->XferCount = 0U;
-
+
hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
-
+ hi2c->Mode = HAL_I2C_MODE_NONE;
+
hi2c->ErrorCode |= HAL_I2C_ERROR_DMA;
-
- HAL_I2C_ErrorCallback(hi2c);
+
+ HAL_I2C_ErrorCallback(hi2c);
}
/**
- * @brief DMA I2C communication abort callback
- * (To be called at end of DMA Abort procedure).
- * @param hdma: DMA handle.
- * @retval None
- */
-static void I2C_DMAAbort(DMA_HandleTypeDef *hdma)
-{
- I2C_HandleTypeDef* hi2c = ( I2C_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
-
+ * @brief DMA I2C communication abort callback
+ * (To be called at end of DMA Abort procedure).
+ * @param hdma: DMA handle.
+ * @retval None
+ */
+static void I2C_DMAAbort(DMA_HandleTypeDef *hdma) {
+ I2C_HandleTypeDef *hi2c = (I2C_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
+
/* Disable Acknowledge */
hi2c->Instance->CR1 &= ~I2C_CR1_ACK;
@@ -5288,10 +4640,9 @@ static void I2C_DMAAbort(DMA_HandleTypeDef *hdma)
hi2c->hdmarx->XferAbortCallback = NULL;
/* Check if come from abort from user */
- if(hi2c->State == HAL_I2C_STATE_ABORT)
- {
- hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ if (hi2c->State == HAL_I2C_STATE_ABORT) {
+ hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
/* Disable I2C peripheral to prevent dummy data in buffer */
@@ -5299,11 +4650,9 @@ static void I2C_DMAAbort(DMA_HandleTypeDef *hdma)
/* Call the corresponding callback to inform upper layer of End of Transfer */
HAL_I2C_AbortCpltCallback(hi2c);
- }
- else
- {
+ } else {
hi2c->State = HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
/* Disable I2C peripheral to prevent dummy data in buffer */
__HAL_I2C_DISABLE(hi2c);
@@ -5314,64 +4663,57 @@ static void I2C_DMAAbort(DMA_HandleTypeDef *hdma)
}
/**
- * @brief This function handles I2C Communication Timeout.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @param Flag specifies the I2C flag to check.
- * @param Status The new Flag status (SET or RESET).
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart)
-{
+ * @brief This function handles I2C Communication Timeout.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @param Flag specifies the I2C flag to check.
+ * @param Status The new Flag status (SET or RESET).
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout, uint32_t Tickstart) {
/* Wait until flag is set */
- while((__HAL_I2C_GET_FLAG(hi2c, Flag) ? SET : RESET) == Status)
- {
+ while ((__HAL_I2C_GET_FLAG(hi2c, Flag) ? SET : RESET) == Status) {
/* Check for the Timeout */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U)||((HAL_GetTick() - Tickstart ) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
- hi2c->Mode = HAL_I2C_MODE_NONE;
+ hi2c->State = HAL_I2C_STATE_READY;
+ hi2c->Mode = HAL_I2C_MODE_NONE;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
-
+
return HAL_TIMEOUT;
}
}
}
-
+
return HAL_OK;
}
/**
- * @brief This function handles I2C Communication Timeout for Master addressing phase.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for I2C module
- * @param Flag specifies the I2C flag to check.
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout, uint32_t Tickstart)
-{
- while(__HAL_I2C_GET_FLAG(hi2c, Flag) == RESET)
- {
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET)
- {
+ * @brief This function handles I2C Communication Timeout for Master addressing phase.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for I2C module
+ * @param Flag specifies the I2C flag to check.
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, uint32_t Timeout, uint32_t Tickstart) {
+ while (__HAL_I2C_GET_FLAG(hi2c, Flag) == RESET) {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) {
/* Generate Stop */
hi2c->Instance->CR1 |= I2C_CR1_STOP;
/* Clear AF Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
- hi2c->ErrorCode = HAL_I2C_ERROR_AF;
+ hi2c->ErrorCode = HAL_I2C_ERROR_AF;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
@@ -5380,12 +4722,10 @@ static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeD
}
/* Check for the Timeout */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U)||((HAL_GetTick() - Tickstart ) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) {
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
@@ -5398,31 +4738,26 @@ static HAL_StatusTypeDef I2C_WaitOnMasterAddressFlagUntilTimeout(I2C_HandleTypeD
}
/**
- * @brief This function handles I2C Communication Timeout for specific usage of TXE flag.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_WaitOnTXEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart)
-{
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE) == RESET)
- {
+ * @brief This function handles I2C Communication Timeout for specific usage of TXE flag.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_WaitOnTXEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) {
+ while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXE) == RESET) {
/* Check if a NACK is detected */
- if(I2C_IsAcknowledgeFailed(hi2c) != HAL_OK)
- {
+ if (I2C_IsAcknowledgeFailed(hi2c) != HAL_OK) {
return HAL_ERROR;
}
-
+
/* Check for the Timeout */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U) || ((HAL_GetTick()-Tickstart) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) {
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
@@ -5431,35 +4766,30 @@ static HAL_StatusTypeDef I2C_WaitOnTXEFlagUntilTimeout(I2C_HandleTypeDef *hi2c,
}
}
}
- return HAL_OK;
+ return HAL_OK;
}
/**
- * @brief This function handles I2C Communication Timeout for specific usage of BTF flag.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_WaitOnBTFFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart)
-{
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == RESET)
- {
+ * @brief This function handles I2C Communication Timeout for specific usage of BTF flag.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_WaitOnBTFFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) {
+ while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BTF) == RESET) {
/* Check if a NACK is detected */
- if(I2C_IsAcknowledgeFailed(hi2c) != HAL_OK)
- {
+ if (I2C_IsAcknowledgeFailed(hi2c) != HAL_OK) {
return HAL_ERROR;
}
/* Check for the Timeout */
- if(Timeout != HAL_MAX_DELAY)
- {
- if((Timeout == 0U) || ((HAL_GetTick()-Tickstart) > Timeout))
- {
+ if (Timeout != HAL_MAX_DELAY) {
+ if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) {
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
@@ -5472,29 +4802,25 @@ static HAL_StatusTypeDef I2C_WaitOnBTFFlagUntilTimeout(I2C_HandleTypeDef *hi2c,
}
/**
- * @brief This function handles I2C Communication Timeout for specific usage of STOP flag.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart)
-{
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET)
- {
+ * @brief This function handles I2C Communication Timeout for specific usage of STOP flag.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) {
+ while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) {
/* Check if a NACK is detected */
- if(I2C_IsAcknowledgeFailed(hi2c) != HAL_OK)
- {
+ if (I2C_IsAcknowledgeFailed(hi2c) != HAL_OK) {
return HAL_ERROR;
}
/* Check for the Timeout */
- if((Timeout == 0U) || ((HAL_GetTick()-Tickstart) > Timeout))
- {
+ if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) {
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
@@ -5506,27 +4832,24 @@ static HAL_StatusTypeDef I2C_WaitOnSTOPFlagUntilTimeout(I2C_HandleTypeDef *hi2c,
}
/**
- * @brief This function handles I2C Communication Timeout for specific usage of RXNE flag.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @param Timeout Timeout duration
- * @param Tickstart Tick start value
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart)
-{
-
- while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET)
- {
+ * @brief This function handles I2C Communication Timeout for specific usage of RXNE flag.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @param Timeout Timeout duration
+ * @param Tickstart Tick start value
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout, uint32_t Tickstart) {
+
+ while (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == RESET) {
/* Check if a STOPF is detected */
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET)
- {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) {
/* Clear STOP Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF);
- hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
+ hi2c->ErrorCode = HAL_I2C_ERROR_NONE;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
@@ -5535,10 +4858,9 @@ static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c,
}
/* Check for the Timeout */
- if((Timeout == 0U) || ((HAL_GetTick()-Tickstart) > Timeout))
- {
+ if ((Timeout == 0U) || ((HAL_GetTick() - Tickstart) > Timeout)) {
hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
@@ -5550,21 +4872,19 @@ static HAL_StatusTypeDef I2C_WaitOnRXNEFlagUntilTimeout(I2C_HandleTypeDef *hi2c,
}
/**
- * @brief This function handles Acknowledge failed detection during an I2C Communication.
- * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
- * the configuration information for the specified I2C.
- * @retval HAL status
- */
-static HAL_StatusTypeDef I2C_IsAcknowledgeFailed(I2C_HandleTypeDef *hi2c)
-{
- if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET)
- {
+ * @brief This function handles Acknowledge failed detection during an I2C Communication.
+ * @param hi2c Pointer to a I2C_HandleTypeDef structure that contains
+ * the configuration information for the specified I2C.
+ * @retval HAL status
+ */
+static HAL_StatusTypeDef I2C_IsAcknowledgeFailed(I2C_HandleTypeDef *hi2c) {
+ if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) {
/* Clear NACKF Flag */
__HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF);
- hi2c->ErrorCode = HAL_I2C_ERROR_AF;
+ hi2c->ErrorCode = HAL_I2C_ERROR_AF;
hi2c->PreviousState = I2C_STATE_NONE;
- hi2c->State= HAL_I2C_STATE_READY;
+ hi2c->State = HAL_I2C_STATE_READY;
/* Process Unlocked */
__HAL_UNLOCK(hi2c);
@@ -5574,17 +4894,17 @@ static HAL_StatusTypeDef I2C_IsAcknowledgeFailed(I2C_HandleTypeDef *hi2c)
return HAL_OK;
}
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_I2C_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_iwdg.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_iwdg.c
index 79fef5d9..c9b891e4 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_iwdg.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_iwdg.c
@@ -103,27 +103,27 @@
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
#ifdef HAL_IWDG_MODULE_ENABLED
/** @defgroup IWDG IWDG
- * @brief IWDG HAL module driver.
- * @{
- */
+ * @brief IWDG HAL module driver.
+ * @{
+ */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup IWDG_Private_Defines IWDG Private Defines
- * @{
- */
+ * @{
+ */
/* Status register need 5 RC LSI divided by prescaler clock to be updated. With
higher prescaler (256), and according to HSI variation, we need to wait at
least 6 cycles so 48 ms. */
-#define HAL_IWDG_DEFAULT_TIMEOUT 48U
+#define HAL_IWDG_DEFAULT_TIMEOUT 48U
/**
- * @}
- */
+ * @}
+ */
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
@@ -131,8 +131,8 @@
/* Exported functions --------------------------------------------------------*/
/** @addtogroup IWDG_Exported_Functions
- * @{
- */
+ * @{
+ */
/** @addtogroup IWDG_Exported_Functions_Group1
* @brief Initialization and Start functions.
@@ -152,20 +152,18 @@
*/
/**
- * @brief Initialize the IWDG according to the specified parameters in the
- * IWDG_InitTypeDef and start watchdog. Before exiting function,
- * watchdog is refreshed in order to have correct time base.
- * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains
- * the configuration information for the specified IWDG module.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg)
-{
+ * @brief Initialize the IWDG according to the specified parameters in the
+ * IWDG_InitTypeDef and start watchdog. Before exiting function,
+ * watchdog is refreshed in order to have correct time base.
+ * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains
+ * the configuration information for the specified IWDG module.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg) {
uint32_t tickstart;
/* Check the IWDG handle allocation */
- if (hiwdg == NULL)
- {
+ if (hiwdg == NULL) {
return HAL_ERROR;
}
@@ -181,17 +179,15 @@ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg)
IWDG_ENABLE_WRITE_ACCESS(hiwdg);
/* Write to IWDG registers the Prescaler & Reload values to work with */
- hiwdg->Instance->PR = hiwdg->Init.Prescaler;
+ hiwdg->Instance->PR = hiwdg->Init.Prescaler;
hiwdg->Instance->RLR = hiwdg->Init.Reload;
/* Check pending flag, if previous update not done, return timeout */
tickstart = HAL_GetTick();
/* Wait for register to be updated */
- while (hiwdg->Instance->SR != RESET)
- {
- if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT)
- {
+ while (hiwdg->Instance->SR != RESET) {
+ if ((HAL_GetTick() - tickstart) > HAL_IWDG_DEFAULT_TIMEOUT) {
return HAL_TIMEOUT;
}
}
@@ -204,8 +200,8 @@ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg)
}
/**
- * @}
- */
+ * @}
+ */
/** @addtogroup IWDG_Exported_Functions_Group2
* @brief IO operation functions
@@ -222,13 +218,12 @@ HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg)
*/
/**
- * @brief Refresh the IWDG.
- * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains
- * the configuration information for the specified IWDG module.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg)
-{
+ * @brief Refresh the IWDG.
+ * @param hiwdg pointer to a IWDG_HandleTypeDef structure that contains
+ * the configuration information for the specified IWDG module.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg) {
/* Reload IWDG counter with value defined in the reload register */
__HAL_IWDG_RELOAD_COUNTER(hiwdg);
@@ -237,20 +232,20 @@ HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg)
}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_IWDG_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_pwr.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_pwr.c
index 44d66138..9444ed51 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_pwr.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_pwr.c
@@ -1,55 +1,55 @@
/**
- ******************************************************************************
- * @file stm32f1xx_hal_pwr.c
- * @author MCD Application Team
- * @brief PWR HAL module driver.
- *
- * This file provides firmware functions to manage the following
- * functionalities of the Power Controller (PWR) peripheral:
- * + Initialization/de-initialization functions
- * + Peripheral Control functions
- *
- ******************************************************************************
- * @attention
- *
- * <h2><center>&copy; COPYRIGHT(c) 2016 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.
- *
- ******************************************************************************
- */
+ ******************************************************************************
+ * @file stm32f1xx_hal_pwr.c
+ * @author MCD Application Team
+ * @brief PWR HAL module driver.
+ *
+ * This file provides firmware functions to manage the following
+ * functionalities of the Power Controller (PWR) peripheral:
+ * + Initialization/de-initialization functions
+ * + Peripheral Control functions
+ *
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2016 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.
+ *
+ ******************************************************************************
+ */
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup PWR PWR
- * @brief PWR HAL module driver
- * @{
- */
+ * @brief PWR HAL module driver
+ * @{
+ */
#ifdef HAL_PWR_MODULE_ENABLED
@@ -57,68 +57,67 @@
/* Private define ------------------------------------------------------------*/
/** @defgroup PWR_Private_Constants PWR Private Constants
- * @{
- */
-
+ * @{
+ */
+
/** @defgroup PWR_PVD_Mode_Mask PWR PVD Mode Mask
- * @{
- */
-#define PVD_MODE_IT 0x00010000U
-#define PVD_MODE_EVT 0x00020000U
-#define PVD_RISING_EDGE 0x00000001U
-#define PVD_FALLING_EDGE 0x00000002U
+ * @{
+ */
+#define PVD_MODE_IT 0x00010000U
+#define PVD_MODE_EVT 0x00020000U
+#define PVD_RISING_EDGE 0x00000001U
+#define PVD_FALLING_EDGE 0x00000002U
/**
- * @}
- */
-
+ * @}
+ */
/** @defgroup PWR_register_alias_address PWR Register alias address
- * @{
- */
+ * @{
+ */
/* ------------- PWR registers bit address in the alias region ---------------*/
-#define PWR_OFFSET (PWR_BASE - PERIPH_BASE)
-#define PWR_CR_OFFSET 0x00U
-#define PWR_CSR_OFFSET 0x04U
-#define PWR_CR_OFFSET_BB (PWR_OFFSET + PWR_CR_OFFSET)
-#define PWR_CSR_OFFSET_BB (PWR_OFFSET + PWR_CSR_OFFSET)
+#define PWR_OFFSET (PWR_BASE - PERIPH_BASE)
+#define PWR_CR_OFFSET 0x00U
+#define PWR_CSR_OFFSET 0x04U
+#define PWR_CR_OFFSET_BB (PWR_OFFSET + PWR_CR_OFFSET)
+#define PWR_CSR_OFFSET_BB (PWR_OFFSET + PWR_CSR_OFFSET)
/**
- * @}
- */
-
+ * @}
+ */
+
/** @defgroup PWR_CR_register_alias PWR CR Register alias address
- * @{
- */
+ * @{
+ */
/* --- CR Register ---*/
/* Alias word address of LPSDSR bit */
-#define LPSDSR_BIT_NUMBER PWR_CR_LPDS_Pos
-#define CR_LPSDSR_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32U) + (LPSDSR_BIT_NUMBER * 4U)))
+#define LPSDSR_BIT_NUMBER PWR_CR_LPDS_Pos
+#define CR_LPSDSR_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32U) + (LPSDSR_BIT_NUMBER * 4U)))
/* Alias word address of DBP bit */
-#define DBP_BIT_NUMBER PWR_CR_DBP_Pos
-#define CR_DBP_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32U) + (DBP_BIT_NUMBER * 4U)))
+#define DBP_BIT_NUMBER PWR_CR_DBP_Pos
+#define CR_DBP_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32U) + (DBP_BIT_NUMBER * 4U)))
/* Alias word address of PVDE bit */
-#define PVDE_BIT_NUMBER PWR_CR_PVDE_Pos
-#define CR_PVDE_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32U) + (PVDE_BIT_NUMBER * 4U)))
+#define PVDE_BIT_NUMBER PWR_CR_PVDE_Pos
+#define CR_PVDE_BB ((uint32_t)(PERIPH_BB_BASE + (PWR_CR_OFFSET_BB * 32U) + (PVDE_BIT_NUMBER * 4U)))
/**
- * @}
- */
+ * @}
+ */
/** @defgroup PWR_CSR_register_alias PWR CSR Register alias address
- * @{
- */
+ * @{
+ */
/* --- CSR Register ---*/
/* Alias word address of EWUP1 bit */
-#define CSR_EWUP_BB(VAL) ((uint32_t)(PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32U) + (POSITION_VAL(VAL) * 4U)))
+#define CSR_EWUP_BB(VAL) ((uint32_t)(PERIPH_BB_BASE + (PWR_CSR_OFFSET_BB * 32U) + (POSITION_VAL(VAL) * 4U)))
/**
- * @}
- */
-
+ * @}
+ */
+
/**
- * @}
- */
+ * @}
+ */
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
@@ -130,22 +129,20 @@ static void PWR_OverloadWfe(void);
/* Private functions ---------------------------------------------------------*/
__NOINLINE
-static void PWR_OverloadWfe(void)
-{
- __asm volatile( "wfe" );
- __asm volatile( "nop" );
+static void PWR_OverloadWfe(void) {
+ __asm volatile("wfe");
+ __asm volatile("nop");
}
/**
- * @}
- */
-
+ * @}
+ */
/** @defgroup PWR_Exported_Functions PWR Exported Functions
- * @{
- */
+ * @{
+ */
-/** @defgroup PWR_Exported_Functions_Group1 Initialization and de-initialization functions
+/** @defgroup PWR_Exported_Functions_Group1 Initialization and de-initialization functions
* @brief Initialization and de-initialization functions
*
@verbatim
@@ -166,53 +163,50 @@ static void PWR_OverloadWfe(void)
*/
/**
- * @brief Deinitializes the PWR peripheral registers to their default reset values.
- * @retval None
- */
-void HAL_PWR_DeInit(void)
-{
+ * @brief Deinitializes the PWR peripheral registers to their default reset values.
+ * @retval None
+ */
+void HAL_PWR_DeInit(void) {
__HAL_RCC_PWR_FORCE_RESET();
__HAL_RCC_PWR_RELEASE_RESET();
}
/**
- * @brief Enables access to the backup domain (RTC registers, RTC
- * backup data registers ).
- * @note If the HSE divided by 128 is used as the RTC clock, the
- * Backup Domain Access should be kept enabled.
- * @retval None
- */
-void HAL_PWR_EnableBkUpAccess(void)
-{
+ * @brief Enables access to the backup domain (RTC registers, RTC
+ * backup data registers ).
+ * @note If the HSE divided by 128 is used as the RTC clock, the
+ * Backup Domain Access should be kept enabled.
+ * @retval None
+ */
+void HAL_PWR_EnableBkUpAccess(void) {
/* Enable access to RTC and backup registers */
- *(__IO uint32_t *) CR_DBP_BB = (uint32_t)ENABLE;
+ *(__IO uint32_t *)CR_DBP_BB = (uint32_t)ENABLE;
}
/**
- * @brief Disables access to the backup domain (RTC registers, RTC
- * backup data registers).
- * @note If the HSE divided by 128 is used as the RTC clock, the
- * Backup Domain Access should be kept enabled.
- * @retval None
- */
-void HAL_PWR_DisableBkUpAccess(void)
-{
+ * @brief Disables access to the backup domain (RTC registers, RTC
+ * backup data registers).
+ * @note If the HSE divided by 128 is used as the RTC clock, the
+ * Backup Domain Access should be kept enabled.
+ * @retval None
+ */
+void HAL_PWR_DisableBkUpAccess(void) {
/* Disable access to RTC and backup registers */
- *(__IO uint32_t *) CR_DBP_BB = (uint32_t)DISABLE;
+ *(__IO uint32_t *)CR_DBP_BB = (uint32_t)DISABLE;
}
/**
- * @}
- */
+ * @}
+ */
-/** @defgroup PWR_Exported_Functions_Group2 Peripheral Control functions
+/** @defgroup PWR_Exported_Functions_Group2 Peripheral Control functions
* @brief Low Power modes configuration functions
*
@verbatim
===============================================================================
##### Peripheral Control functions #####
===============================================================================
-
+
*** PVD configuration ***
=========================
[..]
@@ -239,12 +233,12 @@ void HAL_PWR_DisableBkUpAccess(void)
=====================================
[..]
The device features 3 low-power modes:
- (+) Sleep mode: CPU clock off, all peripherals including Cortex-M3 core peripherals like
+ (+) Sleep mode: CPU clock off, all peripherals including Cortex-M3 core peripherals like
NVIC, SysTick, etc. are kept running
(+) Stop mode: All clocks are stopped
(+) Standby mode: 1.8V domain powered off
-
-
+
+
*** Sleep mode ***
==================
[..]
@@ -253,7 +247,7 @@ void HAL_PWR_DisableBkUpAccess(void)
functions with
(++) PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction
(++) PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction
-
+
(+) Exit:
(++) WFI entry mode, Any peripheral interrupt acknowledged by the nested vectored interrupt
controller (NVIC) can wake up the device from Sleep mode.
@@ -266,7 +260,7 @@ void HAL_PWR_DisableBkUpAccess(void)
[..]
The Stop mode is based on the Cortex-M3 deepsleep mode combined with peripheral
clock gating. The voltage regulator can be configured either in normal or low-power mode.
- In Stop mode, all clocks in the 1.8 V domain are stopped, the PLL, the HSI and the HSE RC
+ In Stop mode, all clocks in the 1.8 V domain are stopped, the PLL, the HSI and the HSE RC
oscillators are disabled. SRAM and register contents are preserved.
In Stop mode, all I/O pins keep the same state as in Run mode.
@@ -285,27 +279,27 @@ void HAL_PWR_DisableBkUpAccess(void)
====================
[..]
The Standby mode allows to achieve the lowest power consumption. It is based on the
- Cortex-M3 deepsleep mode, with the voltage regulator disabled. The 1.8 V domain is
- consequently powered off. The PLL, the HSI oscillator and the HSE oscillator are also
- switched off. SRAM and register contents are lost except for registers in the Backup domain
+ Cortex-M3 deepsleep mode, with the voltage regulator disabled. The 1.8 V domain is
+ consequently powered off. The PLL, the HSI oscillator and the HSE oscillator are also
+ switched off. SRAM and register contents are lost except for registers in the Backup domain
and Standby circuitry
-
+
(+) Entry:
(++) The Standby mode is entered using the HAL_PWR_EnterSTANDBYMode() function.
(+) Exit:
- (++) WKUP pin rising edge, RTC alarm event rising edge, external Reset in
+ (++) WKUP pin rising edge, RTC alarm event rising edge, external Reset in
NRSTpin, IWDG Reset
*** Auto-wakeup (AWU) from low-power mode ***
=============================================
[..]
-
- (+) The MCU can be woken up from low-power mode by an RTC Alarm event,
+
+ (+) The MCU can be woken up from low-power mode by an RTC Alarm event,
without depending on an external interrupt (Auto-wakeup mode).
-
+
(+) RTC auto-wakeup (AWU) from the Stop and Standby modes
- (++) To wake up from the Stop mode with an RTC alarm event, it is necessary to
+ (++) To wake up from the Stop mode with an RTC alarm event, it is necessary to
configure the RTC to generate the RTC alarm using the HAL_RTC_SetAlarm_IT() function.
*** PWR Workarounds linked to Silicon Limitation ***
@@ -314,124 +308,114 @@ void HAL_PWR_DisableBkUpAccess(void)
Below the list of all silicon limitations known on STM32F1xx prouct.
(#)Workarounds Implemented inside PWR HAL Driver
- (##)Debugging Stop mode with WFE entry - overloaded the WFE by an internal function
-
+ (##)Debugging Stop mode with WFE entry - overloaded the WFE by an internal function
+
@endverbatim
* @{
*/
/**
- * @brief Configures the voltage threshold detected by the Power Voltage Detector(PVD).
- * @param sConfigPVD: pointer to an PWR_PVDTypeDef structure that contains the configuration
- * information for the PVD.
- * @note Refer to the electrical characteristics of your device datasheet for
- * more details about the voltage threshold corresponding to each
- * detection level.
- * @retval None
- */
-void HAL_PWR_ConfigPVD(PWR_PVDTypeDef *sConfigPVD)
-{
+ * @brief Configures the voltage threshold detected by the Power Voltage Detector(PVD).
+ * @param sConfigPVD: pointer to an PWR_PVDTypeDef structure that contains the configuration
+ * information for the PVD.
+ * @note Refer to the electrical characteristics of your device datasheet for
+ * more details about the voltage threshold corresponding to each
+ * detection level.
+ * @retval None
+ */
+void HAL_PWR_ConfigPVD(PWR_PVDTypeDef *sConfigPVD) {
/* Check the parameters */
assert_param(IS_PWR_PVD_LEVEL(sConfigPVD->PVDLevel));
assert_param(IS_PWR_PVD_MODE(sConfigPVD->Mode));
/* Set PLS[7:5] bits according to PVDLevel value */
MODIFY_REG(PWR->CR, PWR_CR_PLS, sConfigPVD->PVDLevel);
-
+
/* Clear any previous config. Keep it clear if no event or IT mode is selected */
__HAL_PWR_PVD_EXTI_DISABLE_EVENT();
__HAL_PWR_PVD_EXTI_DISABLE_IT();
- __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE();
+ __HAL_PWR_PVD_EXTI_DISABLE_FALLING_EDGE();
__HAL_PWR_PVD_EXTI_DISABLE_RISING_EDGE();
/* Configure interrupt mode */
- if((sConfigPVD->Mode & PVD_MODE_IT) == PVD_MODE_IT)
- {
+ if ((sConfigPVD->Mode & PVD_MODE_IT) == PVD_MODE_IT) {
__HAL_PWR_PVD_EXTI_ENABLE_IT();
}
-
+
/* Configure event mode */
- if((sConfigPVD->Mode & PVD_MODE_EVT) == PVD_MODE_EVT)
- {
+ if ((sConfigPVD->Mode & PVD_MODE_EVT) == PVD_MODE_EVT) {
__HAL_PWR_PVD_EXTI_ENABLE_EVENT();
}
-
+
/* Configure the edge */
- if((sConfigPVD->Mode & PVD_RISING_EDGE) == PVD_RISING_EDGE)
- {
+ if ((sConfigPVD->Mode & PVD_RISING_EDGE) == PVD_RISING_EDGE) {
__HAL_PWR_PVD_EXTI_ENABLE_RISING_EDGE();
}
-
- if((sConfigPVD->Mode & PVD_FALLING_EDGE) == PVD_FALLING_EDGE)
- {
+
+ if ((sConfigPVD->Mode & PVD_FALLING_EDGE) == PVD_FALLING_EDGE) {
__HAL_PWR_PVD_EXTI_ENABLE_FALLING_EDGE();
}
}
/**
- * @brief Enables the Power Voltage Detector(PVD).
- * @retval None
- */
-void HAL_PWR_EnablePVD(void)
-{
+ * @brief Enables the Power Voltage Detector(PVD).
+ * @retval None
+ */
+void HAL_PWR_EnablePVD(void) {
/* Enable the power voltage detector */
- *(__IO uint32_t *) CR_PVDE_BB = (uint32_t)ENABLE;
+ *(__IO uint32_t *)CR_PVDE_BB = (uint32_t)ENABLE;
}
/**
- * @brief Disables the Power Voltage Detector(PVD).
- * @retval None
- */
-void HAL_PWR_DisablePVD(void)
-{
+ * @brief Disables the Power Voltage Detector(PVD).
+ * @retval None
+ */
+void HAL_PWR_DisablePVD(void) {
/* Disable the power voltage detector */
- *(__IO uint32_t *) CR_PVDE_BB = (uint32_t)DISABLE;
+ *(__IO uint32_t *)CR_PVDE_BB = (uint32_t)DISABLE;
}
/**
- * @brief Enables the WakeUp PINx functionality.
- * @param WakeUpPinx: Specifies the Power Wake-Up pin to enable.
- * This parameter can be one of the following values:
- * @arg PWR_WAKEUP_PIN1
- * @retval None
- */
-void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx)
-{
+ * @brief Enables the WakeUp PINx functionality.
+ * @param WakeUpPinx: Specifies the Power Wake-Up pin to enable.
+ * This parameter can be one of the following values:
+ * @arg PWR_WAKEUP_PIN1
+ * @retval None
+ */
+void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx) {
/* Check the parameter */
assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx));
/* Enable the EWUPx pin */
- *(__IO uint32_t *) CSR_EWUP_BB(WakeUpPinx) = (uint32_t)ENABLE;
+ *(__IO uint32_t *)CSR_EWUP_BB(WakeUpPinx) = (uint32_t)ENABLE;
}
/**
- * @brief Disables the WakeUp PINx functionality.
- * @param WakeUpPinx: Specifies the Power Wake-Up pin to disable.
- * This parameter can be one of the following values:
- * @arg PWR_WAKEUP_PIN1
- * @retval None
- */
-void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx)
-{
+ * @brief Disables the WakeUp PINx functionality.
+ * @param WakeUpPinx: Specifies the Power Wake-Up pin to disable.
+ * This parameter can be one of the following values:
+ * @arg PWR_WAKEUP_PIN1
+ * @retval None
+ */
+void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx) {
/* Check the parameter */
assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx));
/* Disable the EWUPx pin */
- *(__IO uint32_t *) CSR_EWUP_BB(WakeUpPinx) = (uint32_t)DISABLE;
+ *(__IO uint32_t *)CSR_EWUP_BB(WakeUpPinx) = (uint32_t)DISABLE;
}
/**
- * @brief Enters Sleep mode.
- * @note In Sleep mode, all I/O pins keep the same state as in Run mode.
- * @param Regulator: Regulator state as no effect in SLEEP mode - allows to support portability from legacy software
- * @param SLEEPEntry: Specifies if SLEEP mode is entered with WFI or WFE instruction.
- * When WFI entry is used, tick interrupt have to be disabled if not desired as
- * the interrupt wake up source.
- * This parameter can be one of the following values:
- * @arg PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction
- * @arg PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction
- * @retval None
- */
-void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry)
-{
+ * @brief Enters Sleep mode.
+ * @note In Sleep mode, all I/O pins keep the same state as in Run mode.
+ * @param Regulator: Regulator state as no effect in SLEEP mode - allows to support portability from legacy software
+ * @param SLEEPEntry: Specifies if SLEEP mode is entered with WFI or WFE instruction.
+ * When WFI entry is used, tick interrupt have to be disabled if not desired as
+ * the interrupt wake up source.
+ * This parameter can be one of the following values:
+ * @arg PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction
+ * @arg PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction
+ * @retval None
+ */
+void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) {
/* Check the parameters */
/* No check on Regulator because parameter not used in SLEEP mode */
/* Prevent unused argument(s) compilation warning */
@@ -443,13 +427,10 @@ void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry)
CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk));
/* Select SLEEP mode entry -------------------------------------------------*/
- if(SLEEPEntry == PWR_SLEEPENTRY_WFI)
- {
+ if (SLEEPEntry == PWR_SLEEPENTRY_WFI) {
/* Request Wait For Interrupt */
__WFI();
- }
- else
- {
+ } else {
/* Request Wait For Event */
__SEV();
__WFE();
@@ -458,32 +439,31 @@ void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry)
}
/**
- * @brief Enters Stop mode.
- * @note In Stop mode, all I/O pins keep the same state as in Run mode.
- * @note When exiting Stop mode by using an interrupt or a wakeup event,
- * HSI RC oscillator is selected as system clock.
- * @note When the voltage regulator operates in low power mode, an additional
- * startup delay is incurred when waking up from Stop mode.
- * By keeping the internal regulator ON during Stop mode, the consumption
- * is higher although the startup time is reduced.
- * @param Regulator: Specifies the regulator state in Stop mode.
- * This parameter can be one of the following values:
- * @arg PWR_MAINREGULATOR_ON: Stop mode with regulator ON
- * @arg PWR_LOWPOWERREGULATOR_ON: Stop mode with low power regulator ON
- * @param STOPEntry: Specifies if Stop mode in entered with WFI or WFE instruction.
- * This parameter can be one of the following values:
- * @arg PWR_STOPENTRY_WFI: Enter Stop mode with WFI instruction
- * @arg PWR_STOPENTRY_WFE: Enter Stop mode with WFE instruction
- * @retval None
- */
-void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry)
-{
+ * @brief Enters Stop mode.
+ * @note In Stop mode, all I/O pins keep the same state as in Run mode.
+ * @note When exiting Stop mode by using an interrupt or a wakeup event,
+ * HSI RC oscillator is selected as system clock.
+ * @note When the voltage regulator operates in low power mode, an additional
+ * startup delay is incurred when waking up from Stop mode.
+ * By keeping the internal regulator ON during Stop mode, the consumption
+ * is higher although the startup time is reduced.
+ * @param Regulator: Specifies the regulator state in Stop mode.
+ * This parameter can be one of the following values:
+ * @arg PWR_MAINREGULATOR_ON: Stop mode with regulator ON
+ * @arg PWR_LOWPOWERREGULATOR_ON: Stop mode with low power regulator ON
+ * @param STOPEntry: Specifies if Stop mode in entered with WFI or WFE instruction.
+ * This parameter can be one of the following values:
+ * @arg PWR_STOPENTRY_WFI: Enter Stop mode with WFI instruction
+ * @arg PWR_STOPENTRY_WFE: Enter Stop mode with WFE instruction
+ * @retval None
+ */
+void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry) {
/* Check the parameters */
assert_param(IS_PWR_REGULATOR(Regulator));
assert_param(IS_PWR_STOP_ENTRY(STOPEntry));
- /* Clear PDDS bit in PWR register to specify entering in STOP mode when CPU enter in Deepsleep */
- CLEAR_BIT(PWR->CR, PWR_CR_PDDS);
+ /* Clear PDDS bit in PWR register to specify entering in STOP mode when CPU enter in Deepsleep */
+ CLEAR_BIT(PWR->CR, PWR_CR_PDDS);
/* Select the voltage regulator mode by setting LPDS bit in PWR register according to Regulator parameter value */
MODIFY_REG(PWR->CR, PWR_CR_LPDS, Regulator);
@@ -492,13 +472,10 @@ void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry)
SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk));
/* Select Stop mode entry --------------------------------------------------*/
- if(STOPEntry == PWR_STOPENTRY_WFI)
- {
+ if (STOPEntry == PWR_STOPENTRY_WFI) {
/* Request Wait For Interrupt */
__WFI();
- }
- else
- {
+ } else {
/* Request Wait For Event */
__SEV();
PWR_OverloadWfe(); /* WFE redefine locally */
@@ -509,15 +486,14 @@ void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry)
}
/**
- * @brief Enters Standby mode.
- * @note In Standby mode, all I/O pins are high impedance except for:
- * - Reset pad (still available)
- * - TAMPER pin if configured for tamper or calibration out.
- * - WKUP pin (PA0) if enabled.
- * @retval None
- */
-void HAL_PWR_EnterSTANDBYMode(void)
-{
+ * @brief Enters Standby mode.
+ * @note In Standby mode, all I/O pins are high impedance except for:
+ * - Reset pad (still available)
+ * - TAMPER pin if configured for tamper or calibration out.
+ * - WKUP pin (PA0) if enabled.
+ * @retval None
+ */
+void HAL_PWR_EnterSTANDBYMode(void) {
/* Select Standby mode */
SET_BIT(PWR->CR, PWR_CR_PDDS);
@@ -525,79 +501,67 @@ void HAL_PWR_EnterSTANDBYMode(void)
SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk));
/* This option is used to ensure that store operations are completed */
-#if defined ( __CC_ARM)
+#if defined(__CC_ARM)
__force_stores();
#endif
/* Request Wait For Interrupt */
__WFI();
}
-
/**
- * @brief Indicates Sleep-On-Exit when returning from Handler mode to Thread mode.
- * @note Set SLEEPONEXIT bit of SCR register. When this bit is set, the processor
- * re-enters SLEEP mode when an interruption handling is over.
- * Setting this bit is useful when the processor is expected to run only on
- * interruptions handling.
- * @retval None
- */
-void HAL_PWR_EnableSleepOnExit(void)
-{
+ * @brief Indicates Sleep-On-Exit when returning from Handler mode to Thread mode.
+ * @note Set SLEEPONEXIT bit of SCR register. When this bit is set, the processor
+ * re-enters SLEEP mode when an interruption handling is over.
+ * Setting this bit is useful when the processor is expected to run only on
+ * interruptions handling.
+ * @retval None
+ */
+void HAL_PWR_EnableSleepOnExit(void) {
/* Set SLEEPONEXIT bit of Cortex System Control Register */
SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk));
}
-
/**
- * @brief Disables Sleep-On-Exit feature when returning from Handler mode to Thread mode.
- * @note Clears SLEEPONEXIT bit of SCR register. When this bit is set, the processor
- * re-enters SLEEP mode when an interruption handling is over.
- * @retval None
- */
-void HAL_PWR_DisableSleepOnExit(void)
-{
+ * @brief Disables Sleep-On-Exit feature when returning from Handler mode to Thread mode.
+ * @note Clears SLEEPONEXIT bit of SCR register. When this bit is set, the processor
+ * re-enters SLEEP mode when an interruption handling is over.
+ * @retval None
+ */
+void HAL_PWR_DisableSleepOnExit(void) {
/* Clear SLEEPONEXIT bit of Cortex System Control Register */
CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPONEXIT_Msk));
}
-
/**
- * @brief Enables CORTEX M3 SEVONPEND bit.
- * @note Sets SEVONPEND bit of SCR register. When this bit is set, this causes
- * WFE to wake up when an interrupt moves from inactive to pended.
- * @retval None
- */
-void HAL_PWR_EnableSEVOnPend(void)
-{
+ * @brief Enables CORTEX M3 SEVONPEND bit.
+ * @note Sets SEVONPEND bit of SCR register. When this bit is set, this causes
+ * WFE to wake up when an interrupt moves from inactive to pended.
+ * @retval None
+ */
+void HAL_PWR_EnableSEVOnPend(void) {
/* Set SEVONPEND bit of Cortex System Control Register */
SET_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SEVONPEND_Msk));
}
-
/**
- * @brief Disables CORTEX M3 SEVONPEND bit.
- * @note Clears SEVONPEND bit of SCR register. When this bit is set, this causes
- * WFE to wake up when an interrupt moves from inactive to pended.
- * @retval None
- */
-void HAL_PWR_DisableSEVOnPend(void)
-{
+ * @brief Disables CORTEX M3 SEVONPEND bit.
+ * @note Clears SEVONPEND bit of SCR register. When this bit is set, this causes
+ * WFE to wake up when an interrupt moves from inactive to pended.
+ * @retval None
+ */
+void HAL_PWR_DisableSEVOnPend(void) {
/* Clear SEVONPEND bit of Cortex System Control Register */
CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SEVONPEND_Msk));
}
-
-
/**
- * @brief This function handles the PWR PVD interrupt request.
- * @note This API should be called under the PVD_IRQHandler().
- * @retval None
- */
-void HAL_PWR_PVD_IRQHandler(void)
-{
+ * @brief This function handles the PWR PVD interrupt request.
+ * @note This API should be called under the PVD_IRQHandler().
+ * @retval None
+ */
+void HAL_PWR_PVD_IRQHandler(void) {
/* Check PWR exti flag */
- if(__HAL_PWR_PVD_EXTI_GET_FLAG() != RESET)
- {
+ if (__HAL_PWR_PVD_EXTI_GET_FLAG() != RESET) {
/* PWR PVD interrupt user callback */
HAL_PWR_PVDCallback();
@@ -607,31 +571,30 @@ void HAL_PWR_PVD_IRQHandler(void)
}
/**
- * @brief PWR PVD interrupt callback
- * @retval None
- */
-__weak void HAL_PWR_PVDCallback(void)
-{
+ * @brief PWR PVD interrupt callback
+ * @retval None
+ */
+__weak void HAL_PWR_PVDCallback(void) {
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_PWR_PVDCallback could be implemented in the user file
- */
+ */
}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_PWR_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c
index 240c5d11..02f2e074 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc.c
@@ -14,7 +14,7 @@
==============================================================================
[..]
After reset the device is running from Internal High Speed oscillator
- (HSI 8MHz) with Flash 0 wait state, Flash prefetch buffer is enabled,
+ (HSI 8MHz) with Flash 0 wait state, Flash prefetch buffer is enabled,
and all peripherals are off except internal SRAM, Flash and JTAG.
(+) There is no prescaler on High speed (AHB) and Low speed (APB) buses;
all peripherals mapped on these buses are running at HSI speed.
@@ -24,22 +24,22 @@
[..] Once the device started from reset, the user application has to:
(+) Configure the clock source to be used to drive the System clock
(if the application needs higher frequency/performance)
- (+) Configure the System clock frequency and Flash settings
+ (+) Configure the System clock frequency and Flash settings
(+) Configure the AHB and APB buses prescalers
(+) Enable the clock for the peripheral(s) to be used
(+) Configure the clock source(s) for peripherals whose clocks are not
- derived from the System clock (I2S, RTC, ADC, USB OTG FS)
+ derived from the System clock (I2S, RTC, ADC, USB OTG FS)
##### RCC Limitations #####
==============================================================================
[..]
- A delay between an RCC peripheral clock enable and the effective peripheral
- enabling should be taken into account in order to manage the peripheral read/write
+ A delay between an RCC peripheral clock enable and the effective peripheral
+ enabling should be taken into account in order to manage the peripheral read/write
from/to registers.
(+) This delay depends on the peripheral mapping.
(++) AHB & APB peripherals, 1 dummy read is necessary
- [..]
+ [..]
Workarounds:
(#) For AHB & APB peripherals, a dummy read to the peripheral register has been
inserted in each __HAL_RCC_PPP_CLK_ENABLE() macro.
@@ -72,20 +72,20 @@
* 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.
*
- ******************************************************************************
+ ******************************************************************************
*/
-
+
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup RCC RCC
-* @brief RCC HAL module driver
- * @{
- */
+ * @brief RCC HAL module driver
+ * @{
+ */
#ifdef HAL_RCC_MODULE_ENABLED
@@ -95,28 +95,28 @@
* @{
*/
/**
- * @}
- */
+ * @}
+ */
/* Private macro -------------------------------------------------------------*/
/** @defgroup RCC_Private_Macros RCC Private Macros
- * @{
- */
+ * @{
+ */
-#define MCO1_CLK_ENABLE() __HAL_RCC_GPIOA_CLK_ENABLE()
-#define MCO1_GPIO_PORT GPIOA
-#define MCO1_PIN GPIO_PIN_8
+#define MCO1_CLK_ENABLE() __HAL_RCC_GPIOA_CLK_ENABLE()
+#define MCO1_GPIO_PORT GPIOA
+#define MCO1_PIN GPIO_PIN_8
/**
- * @}
- */
+ * @}
+ */
/* Private variables ---------------------------------------------------------*/
/** @defgroup RCC_Private_Variables RCC Private Variables
- * @{
- */
+ * @{
+ */
/**
- * @}
- */
+ * @}
+ */
/* Private function prototypes -----------------------------------------------*/
static void RCC_Delay(uint32_t mdelay);
@@ -124,13 +124,13 @@ static void RCC_Delay(uint32_t mdelay);
/* Exported functions --------------------------------------------------------*/
/** @defgroup RCC_Exported_Functions RCC Exported Functions
- * @{
- */
+ * @{
+ */
-/** @defgroup RCC_Exported_Functions_Group1 Initialization and de-initialization functions
- * @brief Initialization and Configuration functions
+/** @defgroup RCC_Exported_Functions_Group1 Initialization and de-initialization functions
+ * @brief Initialization and Configuration functions
*
- @verbatim
+ @verbatim
===============================================================================
##### Initialization and de-initialization functions #####
===============================================================================
@@ -155,9 +155,9 @@ static void RCC_Delay(uint32_t mdelay);
(++) The second output is used to generate the clock for the USB OTG FS (48 MHz)
(#) CSS (Clock security system), once enable using the macro __HAL_RCC_CSS_ENABLE()
- and if a HSE clock failure occurs(HSE used directly or through PLL as System
+ and if a HSE clock failure occurs(HSE used directly or through PLL as System
clock source), the System clocks automatically switched to HSI and an interrupt
- is generated if enabled. The interrupt is linked to the Cortex-M3 NMI
+ is generated if enabled. The interrupt is linked to the Cortex-M3 NMI
(Non-Maskable Interrupt) exception vector.
(#) MCO1 (microcontroller clock output), used to output SYSCLK, HSI,
@@ -175,19 +175,19 @@ static void RCC_Delay(uint32_t mdelay);
-@- All the peripheral clocks are derived from the System clock (SYSCLK) except:
(+@) RTC: RTC clock can be derived either from the LSI, LSE or HSE clock
- divided by 128.
+ divided by 128.
(+@) USB OTG FS and RTC: USB OTG FS require a frequency equal to 48 MHz
to work correctly. This clock is derived of the main PLL through PLL Multiplier.
(+@) I2S interface on STM32F105x/STM32F107x can be derived from PLL3CLK
(+@) IWDG clock which is always the LSI clock.
(#) For STM32F10xxx, the maximum frequency of the SYSCLK and HCLK/PCLK2 is 72 MHz, PCLK1 36 MHz.
- For STM32F100xx, the maximum frequency of the SYSCLK and HCLK/PCLK1/PCLK2 is 24 MHz.
+ For STM32F100xx, the maximum frequency of the SYSCLK and HCLK/PCLK1/PCLK2 is 24 MHz.
Depending on the SYSCLK frequency, the flash latency should be adapted accordingly.
@endverbatim
* @{
*/
-
+
/*
Additional consideration on the SYSCLK based on Latency settings:
+-----------------------------------------------+
@@ -202,21 +202,20 @@ static void RCC_Delay(uint32_t mdelay);
*/
/**
- * @brief Resets the RCC clock configuration to the default reset state.
- * @note The default reset state of the clock configuration is given below:
- * - HSI ON and used as system clock source
- * - HSE, PLL, PLL2 and PLL3 are OFF
- * - AHB, APB1 and APB2 prescaler set to 1.
- * - CSS and MCO1 OFF
- * - All interrupts disabled
- * - All flags are cleared
- * @note This function does not modify the configuration of the
- * - Peripheral clocks
- * - LSI, LSE and RTC clocks
- * @retval HAL_StatusTypeDef
- */
-HAL_StatusTypeDef HAL_RCC_DeInit(void)
-{
+ * @brief Resets the RCC clock configuration to the default reset state.
+ * @note The default reset state of the clock configuration is given below:
+ * - HSI ON and used as system clock source
+ * - HSE, PLL, PLL2 and PLL3 are OFF
+ * - AHB, APB1 and APB2 prescaler set to 1.
+ * - CSS and MCO1 OFF
+ * - All interrupts disabled
+ * - All flags are cleared
+ * @note This function does not modify the configuration of the
+ * - Peripheral clocks
+ * - LSI, LSE and RTC clocks
+ * @retval HAL_StatusTypeDef
+ */
+HAL_StatusTypeDef HAL_RCC_DeInit(void) {
uint32_t tickstart;
/* Get Start Tick */
@@ -226,10 +225,8 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void)
SET_BIT(RCC->CR, RCC_CR_HSION);
/* Wait till HSI is ready */
- while (READ_BIT(RCC->CR, RCC_CR_HSIRDY) == RESET)
- {
- if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE)
- {
+ while (READ_BIT(RCC->CR, RCC_CR_HSIRDY) == RESET) {
+ if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -244,10 +241,8 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void)
CLEAR_REG(RCC->CFGR);
/* Wait till clock switch is ready */
- while (READ_BIT(RCC->CFGR, RCC_CFGR_SWS) != RESET)
- {
- if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE)
- {
+ while (READ_BIT(RCC->CFGR, RCC_CFGR_SWS) != RESET) {
+ if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -256,8 +251,7 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void)
SystemCoreClock = HSI_VALUE;
/* Adapt Systick interrupt period */
- if(HAL_InitTick(TICK_INT_PRIORITY) != HAL_OK)
- {
+ if (HAL_InitTick(TICK_INT_PRIORITY) != HAL_OK) {
return HAL_ERROR;
}
@@ -268,10 +262,8 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void)
CLEAR_BIT(RCC->CR, RCC_CR_PLLON);
/* Wait till PLL is disabled */
- while (READ_BIT(RCC->CR, RCC_CR_PLLRDY) != RESET)
- {
- if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE)
- {
+ while (READ_BIT(RCC->CR, RCC_CR_PLLRDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -286,10 +278,8 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void)
CLEAR_BIT(RCC->CR, RCC_CR_HSEON | RCC_CR_CSSON);
/* Wait till HSE is disabled */
- while (READ_BIT(RCC->CR, RCC_CR_HSERDY) != RESET)
- {
- if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE)
- {
+ while (READ_BIT(RCC->CR, RCC_CR_HSERDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > HSE_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -305,10 +295,8 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void)
CLEAR_BIT(RCC->CR, RCC_CR_PLL2ON);
/* Wait till PLL2 is disabled */
- while (READ_BIT(RCC->CR, RCC_CR_PLL2RDY) != RESET)
- {
- if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE)
- {
+ while (READ_BIT(RCC->CR, RCC_CR_PLL2RDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -322,10 +310,8 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void)
CLEAR_BIT(RCC->CR, RCC_CR_PLL3ON);
/* Wait till PLL3 is disabled */
- while (READ_BIT(RCC->CR, RCC_CR_PLL3RDY) != RESET)
- {
- if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE)
- {
+ while (READ_BIT(RCC->CR, RCC_CR_PLL3RDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -346,77 +332,65 @@ HAL_StatusTypeDef HAL_RCC_DeInit(void)
}
/**
- * @brief Initializes the RCC Oscillators according to the specified parameters in the
- * RCC_OscInitTypeDef.
- * @param RCC_OscInitStruct pointer to an RCC_OscInitTypeDef structure that
- * contains the configuration information for the RCC Oscillators.
- * @note The PLL is not disabled when used as system clock.
- * @note The PLL is not disabled when USB OTG FS clock is enabled (specific to devices with USB FS)
- * @note Transitions LSE Bypass to LSE On and LSE On to LSE Bypass are not
- * supported by this macro. User should request a transition to LSE Off
- * first and then LSE On or LSE Bypass.
- * @note Transition HSE Bypass to HSE On and HSE On to HSE Bypass are not
- * supported by this macro. User should request a transition to HSE Off
- * first and then HSE On or HSE Bypass.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
-{
- uint32_t tickstart = 0U;
-
+ * @brief Initializes the RCC Oscillators according to the specified parameters in the
+ * RCC_OscInitTypeDef.
+ * @param RCC_OscInitStruct pointer to an RCC_OscInitTypeDef structure that
+ * contains the configuration information for the RCC Oscillators.
+ * @note The PLL is not disabled when used as system clock.
+ * @note The PLL is not disabled when USB OTG FS clock is enabled (specific to devices with USB FS)
+ * @note Transitions LSE Bypass to LSE On and LSE On to LSE Bypass are not
+ * supported by this macro. User should request a transition to LSE Off
+ * first and then LSE On or LSE Bypass.
+ * @note Transition HSE Bypass to HSE On and HSE On to HSE Bypass are not
+ * supported by this macro. User should request a transition to HSE Off
+ * first and then HSE On or HSE Bypass.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) {
+ uint32_t tickstart = 0U;
+
/* Check the parameters */
assert_param(RCC_OscInitStruct != NULL);
assert_param(IS_RCC_OSCILLATORTYPE(RCC_OscInitStruct->OscillatorType));
-
+
/*------------------------------- HSE Configuration ------------------------*/
- /*----------------------------- HSI Configuration --------------------------*/
- if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI)
- {
+ /*----------------------------- HSI Configuration --------------------------*/
+ if (((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) {
/* Check the parameters */
assert_param(IS_RCC_HSI(RCC_OscInitStruct->HSIState));
assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue));
- /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */
- if((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI)
- || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2)))
- {
+ /* Check if HSI is used as system clock or as PLL source when PLL is selected as system clock */
+ if ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI)
+ || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI_DIV2))) {
/* When HSI is used as system clock it will not disabled */
- if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON))
- {
+ if ((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) {
return HAL_ERROR;
}
/* Otherwise, just the calibration is allowed */
- else
- {
+ else {
/* Adjusts the Internal High Speed oscillator (HSI) calibration value.*/
__HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->HSICalibrationValue);
}
- }
- else
- {
+ } else {
/* Check the HSI State */
- if(RCC_OscInitStruct->HSIState != RCC_HSI_OFF)
- {
- /* Enable the Internal High Speed oscillator (HSI). */
+ if (RCC_OscInitStruct->HSIState != RCC_HSI_OFF) {
+ /* Enable the Internal High Speed oscillator (HSI). */
__HAL_RCC_HSI_ENABLE();
/* Get Start Tick */
tickstart = HAL_GetTick();
/* Wait till HSI is ready */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET)
- {
- if((HAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) {
+ if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
/* Adjusts the Internal High Speed oscillator (HSI) calibration value.*/
__HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->HSICalibrationValue);
- }
- else
- {
+ } else {
/* Disable the Internal High Speed oscillator (HSI). */
__HAL_RCC_HSI_DISABLE();
@@ -424,62 +398,49 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
tickstart = HAL_GetTick();
/* Wait till HSI is disabled */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET)
- {
- if((HAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > HSI_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
}
}
}
- /*------------------------------ LSI Configuration -------------------------*/
-
- /*------------------------------ LSE Configuration -------------------------*/
+ /*------------------------------ LSI Configuration -------------------------*/
+ /*------------------------------ LSE Configuration -------------------------*/
#if defined(RCC_CR_PLL2ON)
/*-------------------------------- PLL2 Configuration -----------------------*/
/* Check the parameters */
assert_param(IS_RCC_PLL2(RCC_OscInitStruct->PLL2.PLL2State));
- if ((RCC_OscInitStruct->PLL2.PLL2State) != RCC_PLL2_NONE)
- {
- /* This bit can not be cleared if the PLL2 clock is used indirectly as system
+ if ((RCC_OscInitStruct->PLL2.PLL2State) != RCC_PLL2_NONE) {
+ /* This bit can not be cleared if the PLL2 clock is used indirectly as system
clock (i.e. it is used as PLL clock entry that is used as system clock). */
- if((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && \
- (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && \
- ((READ_BIT(RCC->CFGR2,RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2))
- {
+ if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK)
+ && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) {
return HAL_ERROR;
- }
- else
- {
- if((RCC_OscInitStruct->PLL2.PLL2State) == RCC_PLL2_ON)
- {
+ } else {
+ if ((RCC_OscInitStruct->PLL2.PLL2State) == RCC_PLL2_ON) {
/* Check the parameters */
assert_param(IS_RCC_PLL2_MUL(RCC_OscInitStruct->PLL2.PLL2MUL));
assert_param(IS_RCC_HSE_PREDIV2(RCC_OscInitStruct->PLL2.HSEPrediv2Value));
/* Prediv2 can be written only when the PLLI2S is disabled. */
/* Return an error only if new value is different from the programmed value */
- if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLL3ON) && \
- (__HAL_RCC_HSE_GET_PREDIV2() != RCC_OscInitStruct->PLL2.HSEPrediv2Value))
- {
+ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON) && (__HAL_RCC_HSE_GET_PREDIV2() != RCC_OscInitStruct->PLL2.HSEPrediv2Value)) {
return HAL_ERROR;
}
-
+
/* Disable the main PLL2. */
__HAL_RCC_PLL2_DISABLE();
-
+
/* Get Start Tick */
tickstart = HAL_GetTick();
-
+
/* Wait till PLL2 is disabled */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLL2_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -497,17 +458,13 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
tickstart = HAL_GetTick();
/* Wait till PLL2 is ready */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) == RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLL2_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) == RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
- }
- else
- {
- /* Set PREDIV1 source to HSE */
+ } else {
+ /* Set PREDIV1 source to HSE */
CLEAR_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC);
/* Disable the main PLL2. */
@@ -516,11 +473,9 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
/* Get Start Tick */
tickstart = HAL_GetTick();
- /* Wait till PLL2 is disabled */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLL2_TIMEOUT_VALUE)
- {
+ /* Wait till PLL2 is disabled */
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -532,13 +487,10 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
/*-------------------------------- PLL Configuration -----------------------*/
/* Check the parameters */
assert_param(IS_RCC_PLL(RCC_OscInitStruct->PLL.PLLState));
- if ((RCC_OscInitStruct->PLL.PLLState) != RCC_PLL_NONE)
- {
+ if ((RCC_OscInitStruct->PLL.PLLState) != RCC_PLL_NONE) {
/* Check if the PLL is used as system clock or not */
- if(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK)
- {
- if((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON)
- {
+ if (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK) {
+ if ((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON) {
/* Check the parameters */
assert_param(IS_RCC_PLLSOURCE(RCC_OscInitStruct->PLL.PLLSource));
assert_param(IS_RCC_PLL_MUL(RCC_OscInitStruct->PLL.PLLMUL));
@@ -550,18 +502,15 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
tickstart = HAL_GetTick();
/* Wait till PLL is disabled */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
/* Configure the HSE prediv factor --------------------------------*/
/* It can be written only when the PLL is disabled. Not used in PLL source is different than HSE */
- if(RCC_OscInitStruct->PLL.PLLSource == RCC_PLLSOURCE_HSE)
- {
+ if (RCC_OscInitStruct->PLL.PLLSource == RCC_PLLSOURCE_HSE) {
/* Check the parameter */
assert_param(IS_RCC_HSE_PREDIV(RCC_OscInitStruct->HSEPredivValue));
#if defined(RCC_CFGR2_PREDIV1SRC)
@@ -576,8 +525,7 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
}
/* Configure the main PLL clock source and multiplication factors. */
- __HAL_RCC_PLL_CONFIG(RCC_OscInitStruct->PLL.PLLSource,
- RCC_OscInitStruct->PLL.PLLMUL);
+ __HAL_RCC_PLL_CONFIG(RCC_OscInitStruct->PLL.PLLSource, RCC_OscInitStruct->PLL.PLLMUL);
/* Enable the main PLL. */
__HAL_RCC_PLL_ENABLE();
@@ -585,66 +533,57 @@ HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
tickstart = HAL_GetTick();
/* Wait till PLL is ready */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
- }
- else
- {
+ } else {
/* Disable the main PLL. */
__HAL_RCC_PLL_DISABLE();
/* Get Start Tick */
tickstart = HAL_GetTick();
- /* Wait till PLL is disabled */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE)
- {
+ /* Wait till PLL is disabled */
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
}
- }
- else
- {
+ } else {
return HAL_ERROR;
}
}
-
+
return HAL_OK;
}
/**
- * @brief Initializes the CPU, AHB and APB buses clocks according to the specified
- * parameters in the RCC_ClkInitStruct.
- * @param RCC_ClkInitStruct pointer to an RCC_OscInitTypeDef structure that
- * contains the configuration information for the RCC peripheral.
- * @param FLatency FLASH Latency
- * The value of this parameter depend on device used within the same series
- * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency
- * and updated by @ref HAL_RCC_GetHCLKFreq() function called within this function
- *
- * @note The HSI is used (enabled by hardware) as system clock source after
- * start-up from Reset, wake-up from STOP and STANDBY mode, or in case
- * of failure of the HSE used directly or indirectly as system clock
- * (if the Clock Security System CSS is enabled).
- *
- * @note A switch from one clock source to another occurs only if the target
- * clock source is ready (clock stable after start-up delay or PLL locked).
- * If a clock source which is not yet ready is selected, the switch will
- * occur when the clock source will be ready.
- * You can use @ref HAL_RCC_GetClockConfig() function to know which clock is
- * currently used as system clock source.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency)
-{
+ * @brief Initializes the CPU, AHB and APB buses clocks according to the specified
+ * parameters in the RCC_ClkInitStruct.
+ * @param RCC_ClkInitStruct pointer to an RCC_OscInitTypeDef structure that
+ * contains the configuration information for the RCC peripheral.
+ * @param FLatency FLASH Latency
+ * The value of this parameter depend on device used within the same series
+ * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency
+ * and updated by @ref HAL_RCC_GetHCLKFreq() function called within this function
+ *
+ * @note The HSI is used (enabled by hardware) as system clock source after
+ * start-up from Reset, wake-up from STOP and STANDBY mode, or in case
+ * of failure of the HSE used directly or indirectly as system clock
+ * (if the Clock Security System CSS is enabled).
+ *
+ * @note A switch from one clock source to another occurs only if the target
+ * clock source is ready (clock stable after start-up delay or PLL locked).
+ * If a clock source which is not yet ready is selected, the switch will
+ * occur when the clock source will be ready.
+ * You can use @ref HAL_RCC_GetClockConfig() function to know which clock is
+ * currently used as system clock source.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency) {
uint32_t tickstart = 0U;
/* Check the parameters */
@@ -652,38 +591,33 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui
assert_param(IS_RCC_CLOCKTYPE(RCC_ClkInitStruct->ClockType));
assert_param(IS_FLASH_LATENCY(FLatency));
- /* To correctly read data from FLASH memory, the number of wait states (LATENCY)
- must be correctly programmed according to the frequency of the CPU clock
+ /* To correctly read data from FLASH memory, the number of wait states (LATENCY)
+ must be correctly programmed according to the frequency of the CPU clock
(HCLK) of the device. */
#if defined(FLASH_ACR_LATENCY)
/* Increasing the number of wait states because of higher CPU frequency */
- if(FLatency > (FLASH->ACR & FLASH_ACR_LATENCY))
- {
+ if (FLatency > (FLASH->ACR & FLASH_ACR_LATENCY)) {
/* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */
__HAL_FLASH_SET_LATENCY(FLatency);
/* Check that the new number of wait states is taken into account to access the Flash
memory by reading the FLASH_ACR register */
- if((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency)
- {
+ if ((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency) {
return HAL_ERROR;
}
}
#endif /* FLASH_ACR_LATENCY */
/*-------------------------- HCLK Configuration --------------------------*/
- if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK)
- {
+ if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) {
/* Set the highest APBx dividers in order to ensure that we do not go through
a non-spec phase whatever we decrease or increase HCLK. */
- if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1)
- {
+ if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) {
MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_HCLK_DIV16);
}
- if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2)
- {
+ if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2) {
MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, (RCC_HCLK_DIV16 << 3));
}
@@ -692,35 +626,28 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui
MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_ClkInitStruct->AHBCLKDivider);
}
- /*------------------------- SYSCLK Configuration ---------------------------*/
- if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK)
- {
+ /*------------------------- SYSCLK Configuration ---------------------------*/
+ if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) {
assert_param(IS_RCC_SYSCLKSOURCE(RCC_ClkInitStruct->SYSCLKSource));
/* HSE is selected as System Clock Source */
- if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE)
- {
- /* Check the HSE ready flag */
- if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET)
- {
+ if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) {
+ /* Check the HSE ready flag */
+ if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) {
return HAL_ERROR;
}
}
/* PLL is selected as System Clock Source */
- else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK)
- {
- /* Check the PLL ready flag */
- if(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET)
- {
+ else if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) {
+ /* Check the PLL ready flag */
+ if (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) {
return HAL_ERROR;
}
}
/* HSI is selected as System Clock Source */
- else
- {
- /* Check the HSI ready flag */
- if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET)
- {
+ else {
+ /* Check the HSI ready flag */
+ if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) {
return HAL_ERROR;
}
}
@@ -729,89 +656,74 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui
/* Get Start Tick */
tickstart = HAL_GetTick();
- if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE)
- {
- while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSE)
- {
- if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE)
- {
+ if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) {
+ while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSE) {
+ if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
- }
- else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK)
- {
- while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK)
- {
- if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE)
- {
+ } else if (RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) {
+ while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK) {
+ if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
- }
- else
- {
- while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSI)
- {
- if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE)
- {
+ } else {
+ while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSI) {
+ if ((HAL_GetTick() - tickstart) > CLOCKSWITCH_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
- }
- }
+ }
+ }
#if defined(FLASH_ACR_LATENCY)
/* Decreasing the number of wait states because of lower CPU frequency */
- if(FLatency < (FLASH->ACR & FLASH_ACR_LATENCY))
- {
+ if (FLatency < (FLASH->ACR & FLASH_ACR_LATENCY)) {
/* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */
__HAL_FLASH_SET_LATENCY(FLatency);
/* Check that the new number of wait states is taken into account to access the Flash
memory by reading the FLASH_ACR register */
- if((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency)
- {
+ if ((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency) {
return HAL_ERROR;
}
- }
+ }
#endif /* FLASH_ACR_LATENCY */
- /*-------------------------- PCLK1 Configuration ---------------------------*/
- if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1)
- {
+ /*-------------------------- PCLK1 Configuration ---------------------------*/
+ if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) {
assert_param(IS_RCC_PCLK(RCC_ClkInitStruct->APB1CLKDivider));
MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_ClkInitStruct->APB1CLKDivider);
}
-
- /*-------------------------- PCLK2 Configuration ---------------------------*/
- if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2)
- {
+
+ /*-------------------------- PCLK2 Configuration ---------------------------*/
+ if (((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2) {
assert_param(IS_RCC_PCLK(RCC_ClkInitStruct->APB2CLKDivider));
MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, ((RCC_ClkInitStruct->APB2CLKDivider) << 3));
}
/* Update the SystemCoreClock global variable */
- SystemCoreClock = HAL_RCC_GetSysClockFreq() >> AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE)>> RCC_CFGR_HPRE_Pos];
+ SystemCoreClock = HAL_RCC_GetSysClockFreq() >> AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos];
/* Configure the source of time base considering new system clocks settings*/
- HAL_InitTick (TICK_INT_PRIORITY);
-
+ HAL_InitTick(TICK_INT_PRIORITY);
+
return HAL_OK;
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup RCC_Exported_Functions_Group2 Peripheral Control functions
* @brief RCC clocks control functions
*
- @verbatim
+ @verbatim
===============================================================================
##### Peripheral Control functions #####
- ===============================================================================
+ ===============================================================================
[..]
- This subsection provides a set of functions allowing to control the RCC Clocks
+ This subsection provides a set of functions allowing to control the RCC Clocks
frequencies.
@endverbatim
@@ -849,8 +761,7 @@ HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, ui
* @arg @ref RCC_MCODIV_1 no division applied to MCO clock
* @retval None
*/
-void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv)
-{
+void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv) {
GPIO_InitTypeDef gpio = {0U};
/* Check the parameters */
@@ -863,10 +774,10 @@ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_M
UNUSED(RCC_MCODiv);
/* Configure the MCO1 pin in alternate function mode */
- gpio.Mode = GPIO_MODE_AF_PP;
- gpio.Speed = GPIO_SPEED_FREQ_HIGH;
- gpio.Pull = GPIO_NOPULL;
- gpio.Pin = MCO1_PIN;
+ gpio.Mode = GPIO_MODE_AF_PP;
+ gpio.Speed = GPIO_SPEED_FREQ_HIGH;
+ gpio.Pull = GPIO_NOPULL;
+ gpio.Pin = MCO1_PIN;
/* MCO1 Clock Enable */
MCO1_CLK_ENABLE();
@@ -878,59 +789,52 @@ void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_M
}
/**
- * @brief Enables the Clock Security System.
- * @note If a failure is detected on the HSE oscillator clock, this oscillator
- * is automatically disabled and an interrupt is generated to inform the
- * software about the failure (Clock Security System Interrupt, CSSI),
- * allowing the MCU to perform rescue operations. The CSSI is linked to
- * the Cortex-M3 NMI (Non-Maskable Interrupt) exception vector.
- * @retval None
- */
-void HAL_RCC_EnableCSS(void)
-{
- *(__IO uint32_t *) RCC_CR_CSSON_BB = (uint32_t)ENABLE;
-}
+ * @brief Enables the Clock Security System.
+ * @note If a failure is detected on the HSE oscillator clock, this oscillator
+ * is automatically disabled and an interrupt is generated to inform the
+ * software about the failure (Clock Security System Interrupt, CSSI),
+ * allowing the MCU to perform rescue operations. The CSSI is linked to
+ * the Cortex-M3 NMI (Non-Maskable Interrupt) exception vector.
+ * @retval None
+ */
+void HAL_RCC_EnableCSS(void) { *(__IO uint32_t *)RCC_CR_CSSON_BB = (uint32_t)ENABLE; }
/**
- * @brief Disables the Clock Security System.
- * @retval None
- */
-void HAL_RCC_DisableCSS(void)
-{
- *(__IO uint32_t *) RCC_CR_CSSON_BB = (uint32_t)DISABLE;
-}
+ * @brief Disables the Clock Security System.
+ * @retval None
+ */
+void HAL_RCC_DisableCSS(void) { *(__IO uint32_t *)RCC_CR_CSSON_BB = (uint32_t)DISABLE; }
/**
- * @brief Returns the SYSCLK frequency
- * @note The system frequency computed by this function is not the real
- * frequency in the chip. It is calculated based on the predefined
- * constant and the selected clock source:
- * @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(*)
- * @note If SYSCLK source is HSE, function returns a value based on HSE_VALUE
- * divided by PREDIV factor(**)
- * @note If SYSCLK source is PLL, function returns a value based on HSE_VALUE
- * divided by PREDIV factor(**) or HSI_VALUE(*) multiplied by the PLL factor.
- * @note (*) HSI_VALUE is a constant defined in stm32f1xx_hal_conf.h file (default value
- * 8 MHz) but the real value may vary depending on the variations
- * in voltage and temperature.
- * @note (**) HSE_VALUE is a constant defined in stm32f1xx_hal_conf.h file (default value
- * 8 MHz), user has to ensure that HSE_VALUE is same as the real
- * frequency of the crystal used. Otherwise, this function may
- * have wrong result.
- *
- * @note The result of this function could be not correct when using fractional
- * value for HSE crystal.
- *
- * @note This function can be used by the user application to compute the
- * baud-rate for the communication peripherals or configure other parameters.
- *
- * @note Each time SYSCLK changes, this function must be called to update the
- * right SYSCLK value. Otherwise, any configuration based on this function will be incorrect.
- *
- * @retval SYSCLK frequency
- */
-uint32_t HAL_RCC_GetSysClockFreq(void)
-{
+ * @brief Returns the SYSCLK frequency
+ * @note The system frequency computed by this function is not the real
+ * frequency in the chip. It is calculated based on the predefined
+ * constant and the selected clock source:
+ * @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(*)
+ * @note If SYSCLK source is HSE, function returns a value based on HSE_VALUE
+ * divided by PREDIV factor(**)
+ * @note If SYSCLK source is PLL, function returns a value based on HSE_VALUE
+ * divided by PREDIV factor(**) or HSI_VALUE(*) multiplied by the PLL factor.
+ * @note (*) HSI_VALUE is a constant defined in stm32f1xx_hal_conf.h file (default value
+ * 8 MHz) but the real value may vary depending on the variations
+ * in voltage and temperature.
+ * @note (**) HSE_VALUE is a constant defined in stm32f1xx_hal_conf.h file (default value
+ * 8 MHz), user has to ensure that HSE_VALUE is same as the real
+ * frequency of the crystal used. Otherwise, this function may
+ * have wrong result.
+ *
+ * @note The result of this function could be not correct when using fractional
+ * value for HSE crystal.
+ *
+ * @note This function can be used by the user application to compute the
+ * baud-rate for the communication peripherals or configure other parameters.
+ *
+ * @note Each time SYSCLK changes, this function must be called to update the
+ * right SYSCLK value. Otherwise, any configuration based on this function will be incorrect.
+ *
+ * @retval SYSCLK frequency
+ */
+uint32_t HAL_RCC_GetSysClockFreq(void) {
#if defined(RCC_CFGR2_PREDIV1SRC)
const uint8_t aPLLMULFactorTable[14] = {0, 0, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 13};
const uint8_t aPredivFactorTable[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
@@ -952,302 +856,257 @@ uint32_t HAL_RCC_GetSysClockFreq(void)
tmpreg = RCC->CFGR;
/* Get SYSCLK source -------------------------------------------------------*/
- switch (tmpreg & RCC_CFGR_SWS)
+ switch (tmpreg & RCC_CFGR_SWS) {
+ case RCC_SYSCLKSOURCE_STATUS_HSE: /* HSE used as system clock */
{
- case RCC_SYSCLKSOURCE_STATUS_HSE: /* HSE used as system clock */
- {
- sysclockfreq = HSE_VALUE;
- break;
- }
- case RCC_SYSCLKSOURCE_STATUS_PLLCLK: /* PLL used as system clock */
- {
- pllmul = aPLLMULFactorTable[(uint32_t)(tmpreg & RCC_CFGR_PLLMULL) >> RCC_CFGR_PLLMULL_Pos];
- if ((tmpreg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2)
- {
+ sysclockfreq = HSE_VALUE;
+ break;
+ }
+ case RCC_SYSCLKSOURCE_STATUS_PLLCLK: /* PLL used as system clock */
+ {
+ pllmul = aPLLMULFactorTable[(uint32_t)(tmpreg & RCC_CFGR_PLLMULL) >> RCC_CFGR_PLLMULL_Pos];
+ if ((tmpreg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2) {
#if defined(RCC_CFGR2_PREDIV1)
- prediv = aPredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV1) >> RCC_CFGR2_PREDIV1_Pos];
+ prediv = aPredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV1) >> RCC_CFGR2_PREDIV1_Pos];
#else
- prediv = aPredivFactorTable[(uint32_t)(RCC->CFGR & RCC_CFGR_PLLXTPRE) >> RCC_CFGR_PLLXTPRE_Pos];
+ prediv = aPredivFactorTable[(uint32_t)(RCC->CFGR & RCC_CFGR_PLLXTPRE) >> RCC_CFGR_PLLXTPRE_Pos];
#endif /*RCC_CFGR2_PREDIV1*/
#if defined(RCC_CFGR2_PREDIV1SRC)
- if(HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC))
- {
- /* PLL2 selected as Prediv1 source */
- /* PLLCLK = PLL2CLK / PREDIV1 * PLLMUL with PLL2CLK = HSE/PREDIV2 * PLL2MUL */
- prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1;
- pll2mul = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> RCC_CFGR2_PLL2MUL_Pos) + 2;
- pllclk = (uint32_t)(((uint64_t)HSE_VALUE * (uint64_t)pll2mul * (uint64_t)pllmul) / ((uint64_t)prediv2 * (uint64_t)prediv));
- }
- else
- {
- /* HSE used as PLL clock source : PLLCLK = HSE/PREDIV1 * PLLMUL */
- pllclk = (uint32_t)((HSE_VALUE * pllmul) / prediv);
- }
-
- /* If PLLMUL was set to 13 means that it was to cover the case PLLMUL 6.5 (avoid using float) */
- /* In this case need to divide pllclk by 2 */
- if (pllmul == aPLLMULFactorTable[(uint32_t)(RCC_CFGR_PLLMULL6_5) >> RCC_CFGR_PLLMULL_Pos])
- {
- pllclk = pllclk / 2;
- }
-#else
+ if (HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) {
+ /* PLL2 selected as Prediv1 source */
+ /* PLLCLK = PLL2CLK / PREDIV1 * PLLMUL with PLL2CLK = HSE/PREDIV2 * PLL2MUL */
+ prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1;
+ pll2mul = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> RCC_CFGR2_PLL2MUL_Pos) + 2;
+ pllclk = (uint32_t)(((uint64_t)HSE_VALUE * (uint64_t)pll2mul * (uint64_t)pllmul) / ((uint64_t)prediv2 * (uint64_t)prediv));
+ } else {
/* HSE used as PLL clock source : PLLCLK = HSE/PREDIV1 * PLLMUL */
- pllclk = (uint32_t)((HSE_VALUE * pllmul) / prediv);
-#endif /*RCC_CFGR2_PREDIV1SRC*/
+ pllclk = (uint32_t)((HSE_VALUE * pllmul) / prediv);
}
- else
- {
- /* HSI used as PLL clock source : PLLCLK = HSI/2 * PLLMUL */
- pllclk = (uint32_t)((HSI_VALUE >> 1) * pllmul);
+
+ /* If PLLMUL was set to 13 means that it was to cover the case PLLMUL 6.5 (avoid using float) */
+ /* In this case need to divide pllclk by 2 */
+ if (pllmul == aPLLMULFactorTable[(uint32_t)(RCC_CFGR_PLLMULL6_5) >> RCC_CFGR_PLLMULL_Pos]) {
+ pllclk = pllclk / 2;
}
- sysclockfreq = pllclk;
- break;
- }
- case RCC_SYSCLKSOURCE_STATUS_HSI: /* HSI used as system clock source */
- default: /* HSI used as system clock */
- {
- sysclockfreq = HSI_VALUE;
- break;
+#else
+ /* HSE used as PLL clock source : PLLCLK = HSE/PREDIV1 * PLLMUL */
+ pllclk = (uint32_t)((HSE_VALUE * pllmul) / prediv);
+#endif /*RCC_CFGR2_PREDIV1SRC*/
+ } else {
+ /* HSI used as PLL clock source : PLLCLK = HSI/2 * PLLMUL */
+ pllclk = (uint32_t)((HSI_VALUE >> 1) * pllmul);
}
+ sysclockfreq = pllclk;
+ break;
+ }
+ case RCC_SYSCLKSOURCE_STATUS_HSI: /* HSI used as system clock source */
+ default: /* HSI used as system clock */
+ {
+ sysclockfreq = HSI_VALUE;
+ break;
+ }
}
return sysclockfreq;
}
/**
- * @brief Returns the HCLK frequency
- * @note Each time HCLK changes, this function must be called to update the
- * right HCLK value. Otherwise, any configuration based on this function will be incorrect.
- *
- * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency
- * and updated within this function
- * @retval HCLK frequency
- */
-uint32_t HAL_RCC_GetHCLKFreq(void)
-{
- return SystemCoreClock;
-}
+ * @brief Returns the HCLK frequency
+ * @note Each time HCLK changes, this function must be called to update the
+ * right HCLK value. Otherwise, any configuration based on this function will be incorrect.
+ *
+ * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency
+ * and updated within this function
+ * @retval HCLK frequency
+ */
+uint32_t HAL_RCC_GetHCLKFreq(void) { return SystemCoreClock; }
/**
- * @brief Returns the PCLK1 frequency
- * @note Each time PCLK1 changes, this function must be called to update the
- * right PCLK1 value. Otherwise, any configuration based on this function will be incorrect.
- * @retval PCLK1 frequency
- */
-uint32_t HAL_RCC_GetPCLK1Freq(void)
-{
+ * @brief Returns the PCLK1 frequency
+ * @note Each time PCLK1 changes, this function must be called to update the
+ * right PCLK1 value. Otherwise, any configuration based on this function will be incorrect.
+ * @retval PCLK1 frequency
+ */
+uint32_t HAL_RCC_GetPCLK1Freq(void) {
/* Get HCLK source and Compute PCLK1 frequency ---------------------------*/
return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE1) >> RCC_CFGR_PPRE1_Pos]);
-}
+}
/**
- * @brief Returns the PCLK2 frequency
- * @note Each time PCLK2 changes, this function must be called to update the
- * right PCLK2 value. Otherwise, any configuration based on this function will be incorrect.
- * @retval PCLK2 frequency
- */
-uint32_t HAL_RCC_GetPCLK2Freq(void)
-{
+ * @brief Returns the PCLK2 frequency
+ * @note Each time PCLK2 changes, this function must be called to update the
+ * right PCLK2 value. Otherwise, any configuration based on this function will be incorrect.
+ * @retval PCLK2 frequency
+ */
+uint32_t HAL_RCC_GetPCLK2Freq(void) {
/* Get HCLK source and Compute PCLK2 frequency ---------------------------*/
- return (HAL_RCC_GetHCLKFreq()>> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE2) >> RCC_CFGR_PPRE2_Pos]);
-}
+ return (HAL_RCC_GetHCLKFreq() >> APBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE2) >> RCC_CFGR_PPRE2_Pos]);
+}
/**
- * @brief Configures the RCC_OscInitStruct according to the internal
- * RCC configuration registers.
- * @param RCC_OscInitStruct pointer to an RCC_OscInitTypeDef structure that
- * will be configured.
- * @retval None
- */
-void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct)
-{
+ * @brief Configures the RCC_OscInitStruct according to the internal
+ * RCC configuration registers.
+ * @param RCC_OscInitStruct pointer to an RCC_OscInitTypeDef structure that
+ * will be configured.
+ * @retval None
+ */
+void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) {
/* Check the parameters */
assert_param(RCC_OscInitStruct != NULL);
/* Set all possible values for the Oscillator type parameter ---------------*/
- RCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI \
- | RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI;
+ RCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI;
#if defined(RCC_CFGR2_PREDIV1SRC)
/* Get the Prediv1 source --------------------------------------------------*/
- RCC_OscInitStruct->Prediv1Source = READ_BIT(RCC->CFGR2,RCC_CFGR2_PREDIV1SRC);
+ RCC_OscInitStruct->Prediv1Source = READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC);
#endif /* RCC_CFGR2_PREDIV1SRC */
/* Get the HSE configuration -----------------------------------------------*/
- if((RCC->CR &RCC_CR_HSEBYP) == RCC_CR_HSEBYP)
- {
+ if ((RCC->CR & RCC_CR_HSEBYP) == RCC_CR_HSEBYP) {
RCC_OscInitStruct->HSEState = RCC_HSE_BYPASS;
- }
- else if((RCC->CR &RCC_CR_HSEON) == RCC_CR_HSEON)
- {
+ } else if ((RCC->CR & RCC_CR_HSEON) == RCC_CR_HSEON) {
RCC_OscInitStruct->HSEState = RCC_HSE_ON;
- }
- else
- {
+ } else {
RCC_OscInitStruct->HSEState = RCC_HSE_OFF;
}
RCC_OscInitStruct->HSEPredivValue = __HAL_RCC_HSE_GET_PREDIV();
/* Get the HSI configuration -----------------------------------------------*/
- if((RCC->CR &RCC_CR_HSION) == RCC_CR_HSION)
- {
+ if ((RCC->CR & RCC_CR_HSION) == RCC_CR_HSION) {
RCC_OscInitStruct->HSIState = RCC_HSI_ON;
- }
- else
- {
+ } else {
RCC_OscInitStruct->HSIState = RCC_HSI_OFF;
}
RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->CR & RCC_CR_HSITRIM) >> RCC_CR_HSITRIM_Pos);
/* Get the LSE configuration -----------------------------------------------*/
- if((RCC->BDCR &RCC_BDCR_LSEBYP) == RCC_BDCR_LSEBYP)
- {
+ if ((RCC->BDCR & RCC_BDCR_LSEBYP) == RCC_BDCR_LSEBYP) {
RCC_OscInitStruct->LSEState = RCC_LSE_BYPASS;
- }
- else if((RCC->BDCR &RCC_BDCR_LSEON) == RCC_BDCR_LSEON)
- {
+ } else if ((RCC->BDCR & RCC_BDCR_LSEON) == RCC_BDCR_LSEON) {
RCC_OscInitStruct->LSEState = RCC_LSE_ON;
- }
- else
- {
+ } else {
RCC_OscInitStruct->LSEState = RCC_LSE_OFF;
}
-
+
/* Get the LSI configuration -----------------------------------------------*/
- if((RCC->CSR &RCC_CSR_LSION) == RCC_CSR_LSION)
- {
+ if ((RCC->CSR & RCC_CSR_LSION) == RCC_CSR_LSION) {
RCC_OscInitStruct->LSIState = RCC_LSI_ON;
- }
- else
- {
+ } else {
RCC_OscInitStruct->LSIState = RCC_LSI_OFF;
}
-
/* Get the PLL configuration -----------------------------------------------*/
- if((RCC->CR &RCC_CR_PLLON) == RCC_CR_PLLON)
- {
+ if ((RCC->CR & RCC_CR_PLLON) == RCC_CR_PLLON) {
RCC_OscInitStruct->PLL.PLLState = RCC_PLL_ON;
- }
- else
- {
+ } else {
RCC_OscInitStruct->PLL.PLLState = RCC_PLL_OFF;
}
RCC_OscInitStruct->PLL.PLLSource = (uint32_t)(RCC->CFGR & RCC_CFGR_PLLSRC);
- RCC_OscInitStruct->PLL.PLLMUL = (uint32_t)(RCC->CFGR & RCC_CFGR_PLLMULL);
+ RCC_OscInitStruct->PLL.PLLMUL = (uint32_t)(RCC->CFGR & RCC_CFGR_PLLMULL);
#if defined(RCC_CR_PLL2ON)
/* Get the PLL2 configuration -----------------------------------------------*/
- if((RCC->CR &RCC_CR_PLL2ON) == RCC_CR_PLL2ON)
- {
+ if ((RCC->CR & RCC_CR_PLL2ON) == RCC_CR_PLL2ON) {
RCC_OscInitStruct->PLL2.PLL2State = RCC_PLL2_ON;
- }
- else
- {
+ } else {
RCC_OscInitStruct->PLL2.PLL2State = RCC_PLL2_OFF;
}
RCC_OscInitStruct->PLL2.HSEPrediv2Value = __HAL_RCC_HSE_GET_PREDIV2();
- RCC_OscInitStruct->PLL2.PLL2MUL = (uint32_t)(RCC->CFGR2 & RCC_CFGR2_PLL2MUL);
+ RCC_OscInitStruct->PLL2.PLL2MUL = (uint32_t)(RCC->CFGR2 & RCC_CFGR2_PLL2MUL);
#endif /* RCC_CR_PLL2ON */
}
/**
- * @brief Get the RCC_ClkInitStruct according to the internal
- * RCC configuration registers.
- * @param RCC_ClkInitStruct pointer to an RCC_ClkInitTypeDef structure that
- * contains the current clock configuration.
- * @param pFLatency Pointer on the Flash Latency.
- * @retval None
- */
-void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency)
-{
+ * @brief Get the RCC_ClkInitStruct according to the internal
+ * RCC configuration registers.
+ * @param RCC_ClkInitStruct pointer to an RCC_ClkInitTypeDef structure that
+ * contains the current clock configuration.
+ * @param pFLatency Pointer on the Flash Latency.
+ * @retval None
+ */
+void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency) {
/* Check the parameters */
assert_param(RCC_ClkInitStruct != NULL);
assert_param(pFLatency != NULL);
/* Set all possible values for the Clock type parameter --------------------*/
RCC_ClkInitStruct->ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
-
- /* Get the SYSCLK configuration --------------------------------------------*/
+
+ /* Get the SYSCLK configuration --------------------------------------------*/
RCC_ClkInitStruct->SYSCLKSource = (uint32_t)(RCC->CFGR & RCC_CFGR_SW);
-
- /* Get the HCLK configuration ----------------------------------------------*/
- RCC_ClkInitStruct->AHBCLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_HPRE);
-
- /* Get the APB1 configuration ----------------------------------------------*/
- RCC_ClkInitStruct->APB1CLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_PPRE1);
-
- /* Get the APB2 configuration ----------------------------------------------*/
+
+ /* Get the HCLK configuration ----------------------------------------------*/
+ RCC_ClkInitStruct->AHBCLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_HPRE);
+
+ /* Get the APB1 configuration ----------------------------------------------*/
+ RCC_ClkInitStruct->APB1CLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_PPRE1);
+
+ /* Get the APB2 configuration ----------------------------------------------*/
RCC_ClkInitStruct->APB2CLKDivider = (uint32_t)((RCC->CFGR & RCC_CFGR_PPRE2) >> 3);
-
-#if defined(FLASH_ACR_LATENCY)
- /* Get the Flash Wait State (Latency) configuration ------------------------*/
- *pFLatency = (uint32_t)(FLASH->ACR & FLASH_ACR_LATENCY);
+
+#if defined(FLASH_ACR_LATENCY)
+ /* Get the Flash Wait State (Latency) configuration ------------------------*/
+ *pFLatency = (uint32_t)(FLASH->ACR & FLASH_ACR_LATENCY);
#else
/* For VALUE lines devices, only LATENCY_0 can be set*/
- *pFLatency = (uint32_t)FLASH_LATENCY_0;
+ *pFLatency = (uint32_t)FLASH_LATENCY_0;
#endif
}
/**
- * @brief This function handles the RCC CSS interrupt request.
- * @note This API should be called under the NMI_Handler().
- * @retval None
- */
-void HAL_RCC_NMI_IRQHandler(void)
-{
+ * @brief This function handles the RCC CSS interrupt request.
+ * @note This API should be called under the NMI_Handler().
+ * @retval None
+ */
+void HAL_RCC_NMI_IRQHandler(void) {
/* Check RCC CSSF flag */
- if(__HAL_RCC_GET_IT(RCC_IT_CSS))
- {
+ if (__HAL_RCC_GET_IT(RCC_IT_CSS)) {
/* RCC Clock Security System interrupt user callback */
HAL_RCC_CSSCallback();
-
+
/* Clear RCC CSS pending bit */
__HAL_RCC_CLEAR_IT(RCC_IT_CSS);
}
}
/**
- * @brief This function provides delay (in milliseconds) based on CPU cycles method.
- * @param mdelay: specifies the delay time length, in milliseconds.
- * @retval None
- */
-static void RCC_Delay(uint32_t mdelay)
-{
+ * @brief This function provides delay (in milliseconds) based on CPU cycles method.
+ * @param mdelay: specifies the delay time length, in milliseconds.
+ * @retval None
+ */
+static void RCC_Delay(uint32_t mdelay) {
__IO uint32_t Delay = mdelay * (SystemCoreClock / 8U / 1000U);
- do
- {
+ do {
__NOP();
- }
- while (Delay --);
+ } while (Delay--);
}
/**
- * @brief RCC Clock Security System interrupt callback
- * @retval none
- */
-__weak void HAL_RCC_CSSCallback(void)
-{
+ * @brief RCC Clock Security System interrupt callback
+ * @retval none
+ */
+__weak void HAL_RCC_CSSCallback(void) {
/* NOTE : This function Should not be modified, when the callback is needed,
the HAL_RCC_CSSCallback could be implemented in the user file
- */
+ */
}
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_RCC_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c
index 65db17b7..d700f0ca 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_rcc_ex.c
@@ -1,166 +1,159 @@
/**
- ******************************************************************************
- * @file stm32f1xx_hal_rcc_ex.c
- * @author MCD Application Team
- * @brief Extended RCC HAL module driver.
- * This file provides firmware functions to manage the following
- * functionalities RCC extension peripheral:
- * + Extended Peripheral Control functions
- *
- ******************************************************************************
- * @attention
- *
- * <h2><center>&copy; COPYRIGHT(c) 2016 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.
- *
- ******************************************************************************
- */
+ ******************************************************************************
+ * @file stm32f1xx_hal_rcc_ex.c
+ * @author MCD Application Team
+ * @brief Extended RCC HAL module driver.
+ * This file provides firmware functions to manage the following
+ * functionalities RCC extension peripheral:
+ * + Extended Peripheral Control functions
+ *
+ ******************************************************************************
+ * @attention
+ *
+ * <h2><center>&copy; COPYRIGHT(c) 2016 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.
+ *
+ ******************************************************************************
+ */
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
#ifdef HAL_RCC_MODULE_ENABLED
/** @defgroup RCCEx RCCEx
- * @brief RCC Extension HAL module driver.
- * @{
- */
+ * @brief RCC Extension HAL module driver.
+ * @{
+ */
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup RCCEx_Private_Constants RCCEx Private Constants
- * @{
- */
+ * @{
+ */
/**
- * @}
- */
+ * @}
+ */
/* Private macro -------------------------------------------------------------*/
/** @defgroup RCCEx_Private_Macros RCCEx Private Macros
- * @{
- */
+ * @{
+ */
/**
- * @}
- */
+ * @}
+ */
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup RCCEx_Exported_Functions RCCEx Exported Functions
- * @{
- */
+ * @{
+ */
-/** @defgroup RCCEx_Exported_Functions_Group1 Peripheral Control functions
- * @brief Extended Peripheral Control functions
+/** @defgroup RCCEx_Exported_Functions_Group1 Peripheral Control functions
+ * @brief Extended Peripheral Control functions
*
-@verbatim
+@verbatim
===============================================================================
##### Extended Peripheral Control functions #####
- ===============================================================================
+ ===============================================================================
[..]
- This subsection provides a set of functions allowing to control the RCC Clocks
+ This subsection provides a set of functions allowing to control the RCC Clocks
frequencies.
- [..]
+ [..]
(@) Important note: Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to
- select the RTC clock source; in this case the Backup domain will be reset in
- order to modify the RTC Clock source, as consequence RTC registers (including
+ select the RTC clock source; in this case the Backup domain will be reset in
+ order to modify the RTC Clock source, as consequence RTC registers (including
the backup registers) are set to their reset values.
-
+
@endverbatim
* @{
*/
/**
- * @brief Initializes the RCC extended peripherals clocks according to the specified parameters in the
- * RCC_PeriphCLKInitTypeDef.
- * @param PeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that
- * contains the configuration information for the Extended Peripherals clocks(RTC clock).
- *
- * @note Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select
- * the RTC clock source; in this case the Backup domain will be reset in
- * order to modify the RTC Clock source, as consequence RTC registers (including
- * the backup registers) are set to their reset values.
- *
- * @note In case of STM32F105xC or STM32F107xC devices, PLLI2S will be enabled if requested on
- * one of 2 I2S interfaces. When PLLI2S is enabled, you need to call HAL_RCCEx_DisablePLLI2S to
- * manually disable it.
- *
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit)
-{
+ * @brief Initializes the RCC extended peripherals clocks according to the specified parameters in the
+ * RCC_PeriphCLKInitTypeDef.
+ * @param PeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that
+ * contains the configuration information for the Extended Peripherals clocks(RTC clock).
+ *
+ * @note Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select
+ * the RTC clock source; in this case the Backup domain will be reset in
+ * order to modify the RTC Clock source, as consequence RTC registers (including
+ * the backup registers) are set to their reset values.
+ *
+ * @note In case of STM32F105xC or STM32F107xC devices, PLLI2S will be enabled if requested on
+ * one of 2 I2S interfaces. When PLLI2S is enabled, you need to call HAL_RCCEx_DisablePLLI2S to
+ * manually disable it.
+ *
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) {
uint32_t tickstart = 0U, temp_reg = 0U;
#if defined(STM32F105xC) || defined(STM32F107xC)
- uint32_t pllactive = 0U;
+ uint32_t pllactive = 0U;
#endif /* STM32F105xC || STM32F107xC */
/* Check the parameters */
assert_param(IS_RCC_PERIPHCLOCK(PeriphClkInit->PeriphClockSelection));
-
- /*------------------------------- RTC/LCD Configuration ------------------------*/
- if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC))
- {
+
+ /*------------------------------- RTC/LCD Configuration ------------------------*/
+ if ((((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == RCC_PERIPHCLK_RTC)) {
/* check for RTC Parameters used to output RTCCLK */
assert_param(IS_RCC_RTCCLKSOURCE(PeriphClkInit->RTCClockSelection));
- FlagStatus pwrclkchanged = RESET;
+ FlagStatus pwrclkchanged = RESET;
- /* As soon as function is called to change RTC clock source, activation of the
+ /* As soon as function is called to change RTC clock source, activation of the
power domain is done. */
/* Requires to enable write access to Backup Domain of necessary */
- if(__HAL_RCC_PWR_IS_CLK_DISABLED())
- {
- __HAL_RCC_PWR_CLK_ENABLE();
+ if (__HAL_RCC_PWR_IS_CLK_DISABLED()) {
+ __HAL_RCC_PWR_CLK_ENABLE();
pwrclkchanged = SET;
}
-
- if(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP))
- {
+
+ if (HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) {
/* Enable write access to Backup domain */
SET_BIT(PWR->CR, PWR_CR_DBP);
-
+
/* Wait for Backup domain Write protection disable */
tickstart = HAL_GetTick();
-
- while(HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP))
- {
- if((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE)
- {
+
+ while (HAL_IS_BIT_CLR(PWR->CR, PWR_CR_DBP)) {
+ if ((HAL_GetTick() - tickstart) > RCC_DBP_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
}
-
- /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */
+
+ /* Reset the Backup domain only if the RTC Clock source selection is modified from reset value */
temp_reg = (RCC->BDCR & RCC_BDCR_RTCSEL);
- if((temp_reg != 0x00000000U) && (temp_reg != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL)))
- {
+ if ((temp_reg != 0x00000000U) && (temp_reg != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL))) {
/* Store the content of BDCR register before the reset of Backup Domain */
temp_reg = (RCC->BDCR & ~(RCC_BDCR_RTCSEL));
/* RTC Clock selection can be changed only if the Backup Domain is reset */
@@ -170,44 +163,38 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk
RCC->BDCR = temp_reg;
/* Wait for LSERDY if LSE was enabled */
- if (HAL_IS_BIT_SET(temp_reg, RCC_BDCR_LSEON))
- {
+ if (HAL_IS_BIT_SET(temp_reg, RCC_BDCR_LSEON)) {
/* Get Start Tick */
tickstart = HAL_GetTick();
-
- /* Wait till LSE is ready */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET)
- {
- if((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE)
- {
+
+ /* Wait till LSE is ready */
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) {
+ if ((HAL_GetTick() - tickstart) > RCC_LSE_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
- }
- }
+ }
+ }
}
}
- __HAL_RCC_RTC_CONFIG(PeriphClkInit->RTCClockSelection);
+ __HAL_RCC_RTC_CONFIG(PeriphClkInit->RTCClockSelection);
/* Require to disable power clock if necessary */
- if(pwrclkchanged == SET)
- {
+ if (pwrclkchanged == SET) {
__HAL_RCC_PWR_CLK_DISABLE();
}
}
- /*------------------------------ ADC clock Configuration ------------------*/
- if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_ADC) == RCC_PERIPHCLK_ADC)
- {
+ /*------------------------------ ADC clock Configuration ------------------*/
+ if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_ADC) == RCC_PERIPHCLK_ADC) {
/* Check the parameters */
assert_param(IS_RCC_ADCPLLCLK_DIV(PeriphClkInit->AdcClockSelection));
-
+
/* Configure the ADC clock source */
__HAL_RCC_ADC_CONFIG(PeriphClkInit->AdcClockSelection);
}
#if defined(STM32F105xC) || defined(STM32F107xC)
- /*------------------------------ I2S2 Configuration ------------------------*/
- if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S2) == RCC_PERIPHCLK_I2S2)
- {
+ /*------------------------------ I2S2 Configuration ------------------------*/
+ if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S2) == RCC_PERIPHCLK_I2S2) {
/* Check the parameters */
assert_param(IS_RCC_I2S2CLKSOURCE(PeriphClkInit->I2s2ClockSelection));
@@ -215,39 +202,33 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk
__HAL_RCC_I2S2_CONFIG(PeriphClkInit->I2s2ClockSelection);
}
- /*------------------------------ I2S3 Configuration ------------------------*/
- if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S3) == RCC_PERIPHCLK_I2S3)
- {
+ /*------------------------------ I2S3 Configuration ------------------------*/
+ if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2S3) == RCC_PERIPHCLK_I2S3) {
/* Check the parameters */
assert_param(IS_RCC_I2S3CLKSOURCE(PeriphClkInit->I2s3ClockSelection));
-
+
/* Configure the I2S3 clock source */
__HAL_RCC_I2S3_CONFIG(PeriphClkInit->I2s3ClockSelection);
}
- /*------------------------------ PLL I2S Configuration ----------------------*/
+ /*------------------------------ PLL I2S Configuration ----------------------*/
/* Check that PLLI2S need to be enabled */
- if (HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_I2S2SRC) || HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_I2S3SRC))
- {
+ if (HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_I2S2SRC) || HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_I2S3SRC)) {
/* Update flag to indicate that PLL I2S should be active */
pllactive = 1;
}
/* Check if PLL I2S need to be enabled */
- if (pllactive == 1)
- {
+ if (pllactive == 1) {
/* Enable PLL I2S only if not active */
- if (HAL_IS_BIT_CLR(RCC->CR, RCC_CR_PLL3ON))
- {
+ if (HAL_IS_BIT_CLR(RCC->CR, RCC_CR_PLL3ON)) {
/* Check the parameters */
assert_param(IS_RCC_PLLI2S_MUL(PeriphClkInit->PLLI2S.PLLI2SMUL));
assert_param(IS_RCC_HSE_PREDIV2(PeriphClkInit->PLLI2S.HSEPrediv2Value));
/* Prediv2 can be written only when the PLL2 is disabled. */
/* Return an error only if new value is different from the programmed value */
- if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLL2ON) && \
- (__HAL_RCC_HSE_GET_PREDIV2() != PeriphClkInit->PLLI2S.HSEPrediv2Value))
- {
+ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL2ON) && (__HAL_RCC_HSE_GET_PREDIV2() != PeriphClkInit->PLLI2S.HSEPrediv2Value)) {
return HAL_ERROR;
}
@@ -256,42 +237,34 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk
/* Configure the main PLLI2S multiplication factors. */
__HAL_RCC_PLLI2S_CONFIG(PeriphClkInit->PLLI2S.PLLI2SMUL);
-
+
/* Enable the main PLLI2S. */
__HAL_RCC_PLLI2S_ENABLE();
-
+
/* Get Start Tick*/
tickstart = HAL_GetTick();
-
+
/* Wait till PLLI2S is ready */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) {
+ if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
- }
- else
- {
+ } else {
/* Return an error only if user wants to change the PLLI2SMUL whereas PLLI2S is active */
- if (READ_BIT(RCC->CFGR2, RCC_CFGR2_PLL3MUL) != PeriphClkInit->PLLI2S.PLLI2SMUL)
- {
- return HAL_ERROR;
+ if (READ_BIT(RCC->CFGR2, RCC_CFGR2_PLL3MUL) != PeriphClkInit->PLLI2S.PLLI2SMUL) {
+ return HAL_ERROR;
}
}
}
#endif /* STM32F105xC || STM32F107xC */
-#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\
- || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\
- || defined(STM32F105xC) || defined(STM32F107xC)
- /*------------------------------ USB clock Configuration ------------------*/
- if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USB) == RCC_PERIPHCLK_USB)
- {
+#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
+ /*------------------------------ USB clock Configuration ------------------*/
+ if (((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USB) == RCC_PERIPHCLK_USB) {
/* Check the parameters */
assert_param(IS_RCC_USBPLLCLK_DIV(PeriphClkInit->UsbClockSelection));
-
+
/* Configure the USB clock source */
__HAL_RCC_USB_CONFIG(PeriphClkInit->UsbClockSelection);
}
@@ -301,16 +274,15 @@ HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClk
}
/**
- * @brief Get the PeriphClkInit according to the internal
- * RCC configuration registers.
- * @param PeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that
- * returns the configuration information for the Extended Peripherals clocks(RTC, I2S, ADC clocks).
- * @retval None
- */
-void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit)
-{
+ * @brief Get the PeriphClkInit according to the internal
+ * RCC configuration registers.
+ * @param PeriphClkInit pointer to an RCC_PeriphCLKInitTypeDef structure that
+ * returns the configuration information for the Extended Peripherals clocks(RTC, I2S, ADC clocks).
+ * @retval None
+ */
+void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) {
uint32_t srcclk = 0U;
-
+
/* Set all possible values for the extended clock type parameter------------*/
PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_RTC;
@@ -345,9 +317,7 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit)
#endif /* STM32F103xE || STM32F103xG */
-#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\
- || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\
- || defined(STM32F105xC) || defined(STM32F107xC)
+#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
/* Get the USB clock configuration -----------------------------------------*/
PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_USB;
PeriphClkInit->UsbClockSelection = __HAL_RCC_GET_USB_SOURCE();
@@ -400,8 +370,7 @@ void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit)
@endif
* @retval Frequency in Hz (0: means that no available frequency for the peripheral)
*/
-uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk)
-{
+uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk) {
#if defined(STM32F105xC) || defined(STM32F107xC)
const uint8_t aPLLMULFactorTable[14] = {0, 0, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 13};
const uint8_t aPredivFactorTable[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
@@ -409,10 +378,9 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk)
uint32_t prediv1 = 0U, pllclk = 0U, pllmul = 0U;
uint32_t pll2mul = 0U, pll3mul = 0U, prediv2 = 0U;
#endif /* STM32F105xC || STM32F107xC */
-#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || \
- defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)
+#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)
const uint8_t aPLLMULFactorTable[16] = {2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 16};
- const uint8_t aPredivFactorTable[2] = {1, 2};
+ const uint8_t aPredivFactorTable[2] = {1, 2};
uint32_t prediv1 = 0U, pllclk = 0U, pllmul = 0U;
#endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG */
@@ -420,198 +388,160 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk)
/* Check the parameters */
assert_param(IS_RCC_PERIPHCLOCK(PeriphClk));
-
- switch (PeriphClk)
- {
-#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6)\
- || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG)\
- || defined(STM32F105xC) || defined(STM32F107xC)
- case RCC_PERIPHCLK_USB:
- {
- /* Get RCC configuration ------------------------------------------------------*/
- temp_reg = RCC->CFGR;
-
- /* Check if PLL is enabled */
- if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLLON))
- {
- pllmul = aPLLMULFactorTable[(uint32_t)(temp_reg & RCC_CFGR_PLLMULL) >> RCC_CFGR_PLLMULL_Pos];
- if ((temp_reg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2)
- {
-#if defined(STM32F105xC) || defined(STM32F107xC) || defined(STM32F100xB)\
- || defined(STM32F100xE)
- prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV1) >> RCC_CFGR2_PREDIV1_Pos];
+
+ switch (PeriphClk) {
+#if defined(STM32F102x6) || defined(STM32F102xB) || defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
+ case RCC_PERIPHCLK_USB: {
+ /* Get RCC configuration ------------------------------------------------------*/
+ temp_reg = RCC->CFGR;
+
+ /* Check if PLL is enabled */
+ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLLON)) {
+ pllmul = aPLLMULFactorTable[(uint32_t)(temp_reg & RCC_CFGR_PLLMULL) >> RCC_CFGR_PLLMULL_Pos];
+ if ((temp_reg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2) {
+#if defined(STM32F105xC) || defined(STM32F107xC) || defined(STM32F100xB) || defined(STM32F100xE)
+ prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV1) >> RCC_CFGR2_PREDIV1_Pos];
#else
- prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR & RCC_CFGR_PLLXTPRE) >> RCC_CFGR_PLLXTPRE_Pos];
+ prediv1 = aPredivFactorTable[(uint32_t)(RCC->CFGR & RCC_CFGR_PLLXTPRE) >> RCC_CFGR_PLLXTPRE_Pos];
#endif /* STM32F105xC || STM32F107xC || STM32F100xB || STM32F100xE */
#if defined(STM32F105xC) || defined(STM32F107xC)
- if(HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC))
- {
- /* PLL2 selected as Prediv1 source */
- /* PLLCLK = PLL2CLK / PREDIV1 * PLLMUL with PLL2CLK = HSE/PREDIV2 * PLL2MUL */
- prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1;
- pll2mul = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> RCC_CFGR2_PLL2MUL_Pos) + 2;
- pllclk = (uint32_t)((((HSE_VALUE / prediv2) * pll2mul) / prediv1) * pllmul);
- }
- else
- {
- /* HSE used as PLL clock source : PLLCLK = HSE/PREDIV1 * PLLMUL */
- pllclk = (uint32_t)((HSE_VALUE / prediv1) * pllmul);
- }
-
- /* If PLLMUL was set to 13 means that it was to cover the case PLLMUL 6.5 (avoid using float) */
- /* In this case need to divide pllclk by 2 */
- if (pllmul == aPLLMULFactorTable[(uint32_t)(RCC_CFGR_PLLMULL6_5) >> RCC_CFGR_PLLMULL_Pos])
- {
- pllclk = pllclk / 2;
- }
-#else
- if ((temp_reg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2)
- {
- /* HSE used as PLL clock source : PLLCLK = HSE/PREDIV1 * PLLMUL */
- pllclk = (uint32_t)((HSE_VALUE / prediv1) * pllmul);
- }
-#endif /* STM32F105xC || STM32F107xC */
- }
- else
- {
- /* HSI used as PLL clock source : PLLCLK = HSI/2 * PLLMUL */
- pllclk = (uint32_t)((HSI_VALUE >> 1) * pllmul);
+ if (HAL_IS_BIT_SET(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) {
+ /* PLL2 selected as Prediv1 source */
+ /* PLLCLK = PLL2CLK / PREDIV1 * PLLMUL with PLL2CLK = HSE/PREDIV2 * PLL2MUL */
+ prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1;
+ pll2mul = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> RCC_CFGR2_PLL2MUL_Pos) + 2;
+ pllclk = (uint32_t)((((HSE_VALUE / prediv2) * pll2mul) / prediv1) * pllmul);
+ } else {
+ /* HSE used as PLL clock source : PLLCLK = HSE/PREDIV1 * PLLMUL */
+ pllclk = (uint32_t)((HSE_VALUE / prediv1) * pllmul);
}
- /* Calcul of the USB frequency*/
-#if defined(STM32F105xC) || defined(STM32F107xC)
- /* USBCLK = PLLVCO = (2 x PLLCLK) / USB prescaler */
- if (__HAL_RCC_GET_USB_SOURCE() == RCC_USBCLKSOURCE_PLL_DIV2)
- {
- /* Prescaler of 2 selected for USB */
- frequency = pllclk;
- }
- else
- {
- /* Prescaler of 3 selected for USB */
- frequency = (2 * pllclk) / 3;
+ /* If PLLMUL was set to 13 means that it was to cover the case PLLMUL 6.5 (avoid using float) */
+ /* In this case need to divide pllclk by 2 */
+ if (pllmul == aPLLMULFactorTable[(uint32_t)(RCC_CFGR_PLLMULL6_5) >> RCC_CFGR_PLLMULL_Pos]) {
+ pllclk = pllclk / 2;
}
#else
- /* USBCLK = PLLCLK / USB prescaler */
- if (__HAL_RCC_GET_USB_SOURCE() == RCC_USBCLKSOURCE_PLL)
- {
- /* No prescaler selected for USB */
- frequency = pllclk;
- }
- else
- {
- /* Prescaler of 1.5 selected for USB */
- frequency = (pllclk * 2) / 3;
+ if ((temp_reg & RCC_CFGR_PLLSRC) != RCC_PLLSOURCE_HSI_DIV2) {
+ /* HSE used as PLL clock source : PLLCLK = HSE/PREDIV1 * PLLMUL */
+ pllclk = (uint32_t)((HSE_VALUE / prediv1) * pllmul);
}
-#endif
+#endif /* STM32F105xC || STM32F107xC */
+ } else {
+ /* HSI used as PLL clock source : PLLCLK = HSI/2 * PLLMUL */
+ pllclk = (uint32_t)((HSI_VALUE >> 1) * pllmul);
+ }
+
+ /* Calcul of the USB frequency*/
+#if defined(STM32F105xC) || defined(STM32F107xC)
+ /* USBCLK = PLLVCO = (2 x PLLCLK) / USB prescaler */
+ if (__HAL_RCC_GET_USB_SOURCE() == RCC_USBCLKSOURCE_PLL_DIV2) {
+ /* Prescaler of 2 selected for USB */
+ frequency = pllclk;
+ } else {
+ /* Prescaler of 3 selected for USB */
+ frequency = (2 * pllclk) / 3;
+ }
+#else
+ /* USBCLK = PLLCLK / USB prescaler */
+ if (__HAL_RCC_GET_USB_SOURCE() == RCC_USBCLKSOURCE_PLL) {
+ /* No prescaler selected for USB */
+ frequency = pllclk;
+ } else {
+ /* Prescaler of 1.5 selected for USB */
+ frequency = (pllclk * 2) / 3;
}
- break;
+#endif
}
+ break;
+ }
#endif /* STM32F102x6 || STM32F102xB || STM32F103x6 || STM32F103xB || STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */
#if defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
- case RCC_PERIPHCLK_I2S2:
- {
+ case RCC_PERIPHCLK_I2S2: {
#if defined(STM32F103xE) || defined(STM32F103xG)
+ /* SYSCLK used as source clock for I2S2 */
+ frequency = HAL_RCC_GetSysClockFreq();
+#else
+ if (__HAL_RCC_GET_I2S2_SOURCE() == RCC_I2S2CLKSOURCE_SYSCLK) {
/* SYSCLK used as source clock for I2S2 */
frequency = HAL_RCC_GetSysClockFreq();
-#else
- if (__HAL_RCC_GET_I2S2_SOURCE() == RCC_I2S2CLKSOURCE_SYSCLK)
- {
- /* SYSCLK used as source clock for I2S2 */
- frequency = HAL_RCC_GetSysClockFreq();
+ } else {
+ /* Check if PLLI2S is enabled */
+ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) {
+ /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */
+ prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1;
+ pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2;
+ frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul));
}
- else
- {
- /* Check if PLLI2S is enabled */
- if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON))
- {
- /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */
- prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1;
- pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2;
- frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul));
- }
- }
-#endif /* STM32F103xE || STM32F103xG */
- break;
}
- case RCC_PERIPHCLK_I2S3:
- {
+#endif /* STM32F103xE || STM32F103xG */
+ break;
+ }
+ case RCC_PERIPHCLK_I2S3: {
#if defined(STM32F103xE) || defined(STM32F103xG)
+ /* SYSCLK used as source clock for I2S3 */
+ frequency = HAL_RCC_GetSysClockFreq();
+#else
+ if (__HAL_RCC_GET_I2S3_SOURCE() == RCC_I2S3CLKSOURCE_SYSCLK) {
/* SYSCLK used as source clock for I2S3 */
frequency = HAL_RCC_GetSysClockFreq();
-#else
- if (__HAL_RCC_GET_I2S3_SOURCE() == RCC_I2S3CLKSOURCE_SYSCLK)
- {
- /* SYSCLK used as source clock for I2S3 */
- frequency = HAL_RCC_GetSysClockFreq();
- }
- else
- {
- /* Check if PLLI2S is enabled */
- if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON))
- {
- /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */
- prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1;
- pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2;
- frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul));
- }
+ } else {
+ /* Check if PLLI2S is enabled */
+ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON)) {
+ /* PLLI2SVCO = 2 * PLLI2SCLK = 2 * (HSE/PREDIV2 * PLL3MUL) */
+ prediv2 = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> RCC_CFGR2_PREDIV2_Pos) + 1;
+ pll3mul = ((RCC->CFGR2 & RCC_CFGR2_PLL3MUL) >> RCC_CFGR2_PLL3MUL_Pos) + 2;
+ frequency = (uint32_t)(2 * ((HSE_VALUE / prediv2) * pll3mul));
}
-#endif /* STM32F103xE || STM32F103xG */
- break;
}
+#endif /* STM32F103xE || STM32F103xG */
+ break;
+ }
#endif /* STM32F103xE || STM32F103xG || STM32F105xC || STM32F107xC */
- case RCC_PERIPHCLK_RTC:
- {
- /* Get RCC BDCR configuration ------------------------------------------------------*/
- temp_reg = RCC->BDCR;
-
- /* Check if LSE is ready if RTC clock selection is LSE */
- if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_LSE) && (HAL_IS_BIT_SET(temp_reg, RCC_BDCR_LSERDY)))
- {
- frequency = LSE_VALUE;
- }
- /* Check if LSI is ready if RTC clock selection is LSI */
- else if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_LSI) && (HAL_IS_BIT_SET(RCC->CSR, RCC_CSR_LSIRDY)))
- {
- frequency = LSI_VALUE;
- }
- else if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_HSE_DIV128) && (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSERDY)))
- {
- frequency = HSE_VALUE / 128U;
- }
- /* Clock not enabled for RTC*/
- else
- {
- frequency = 0U;
- }
- break;
+ case RCC_PERIPHCLK_RTC: {
+ /* Get RCC BDCR configuration ------------------------------------------------------*/
+ temp_reg = RCC->BDCR;
+
+ /* Check if LSE is ready if RTC clock selection is LSE */
+ if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_LSE) && (HAL_IS_BIT_SET(temp_reg, RCC_BDCR_LSERDY))) {
+ frequency = LSE_VALUE;
}
- case RCC_PERIPHCLK_ADC:
- {
- frequency = HAL_RCC_GetPCLK2Freq() / (((__HAL_RCC_GET_ADC_SOURCE() >> RCC_CFGR_ADCPRE_Pos) + 1) * 2);
- break;
+ /* Check if LSI is ready if RTC clock selection is LSI */
+ else if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_LSI) && (HAL_IS_BIT_SET(RCC->CSR, RCC_CSR_LSIRDY))) {
+ frequency = LSI_VALUE;
+ } else if (((temp_reg & RCC_BDCR_RTCSEL) == RCC_RTCCLKSOURCE_HSE_DIV128) && (HAL_IS_BIT_SET(RCC->CR, RCC_CR_HSERDY))) {
+ frequency = HSE_VALUE / 128U;
}
- default:
- {
- break;
+ /* Clock not enabled for RTC*/
+ else {
+ frequency = 0U;
}
+ break;
}
- return(frequency);
+ case RCC_PERIPHCLK_ADC: {
+ frequency = HAL_RCC_GetPCLK2Freq() / (((__HAL_RCC_GET_ADC_SOURCE() >> RCC_CFGR_ADCPRE_Pos) + 1) * 2);
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ return (frequency);
}
/**
- * @}
- */
+ * @}
+ */
#if defined(STM32F105xC) || defined(STM32F107xC)
/** @defgroup RCCEx_Exported_Functions_Group2 PLLI2S Management function
* @brief PLLI2S Management functions
*
-@verbatim
+@verbatim
===============================================================================
##### Extended PLLI2S Management functions #####
- ===============================================================================
+ ===============================================================================
[..]
This subsection provides a set of functions allowing to control the PLLI2S
activation or deactivation
@@ -620,28 +550,24 @@ uint32_t HAL_RCCEx_GetPeriphCLKFreq(uint32_t PeriphClk)
*/
/**
- * @brief Enable PLLI2S
- * @param PLLI2SInit pointer to an RCC_PLLI2SInitTypeDef structure that
- * contains the configuration information for the PLLI2S
- * @note The PLLI2S configuration not modified if used by I2S2 or I2S3 Interface.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_RCCEx_EnablePLLI2S(RCC_PLLI2SInitTypeDef *PLLI2SInit)
-{
+ * @brief Enable PLLI2S
+ * @param PLLI2SInit pointer to an RCC_PLLI2SInitTypeDef structure that
+ * contains the configuration information for the PLLI2S
+ * @note The PLLI2S configuration not modified if used by I2S2 or I2S3 Interface.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCCEx_EnablePLLI2S(RCC_PLLI2SInitTypeDef *PLLI2SInit) {
uint32_t tickstart = 0U;
/* Check that PLL I2S has not been already enabled by I2S2 or I2S3*/
- if (HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S2SRC) && HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S3SRC))
- {
+ if (HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S2SRC) && HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S3SRC)) {
/* Check the parameters */
assert_param(IS_RCC_PLLI2S_MUL(PLLI2SInit->PLLI2SMUL));
assert_param(IS_RCC_HSE_PREDIV2(PLLI2SInit->HSEPrediv2Value));
/* Prediv2 can be written only when the PLL2 is disabled. */
/* Return an error only if new value is different from the programmed value */
- if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLL2ON) && \
- (__HAL_RCC_HSE_GET_PREDIV2() != PLLI2SInit->HSEPrediv2Value))
- {
+ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL2ON) && (__HAL_RCC_HSE_GET_PREDIV2() != PLLI2SInit->HSEPrediv2Value)) {
return HAL_ERROR;
}
@@ -650,40 +576,33 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLLI2S(RCC_PLLI2SInitTypeDef *PLLI2SInit)
/* Get Start Tick*/
tickstart = HAL_GetTick();
-
- /* Wait till PLLI2S is ready */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE)
- {
+
+ /* Wait till PLLI2S is ready */
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
/* Configure the HSE prediv2 factor --------------------------------*/
__HAL_RCC_HSE_PREDIV2_CONFIG(PLLI2SInit->HSEPrediv2Value);
-
/* Configure the main PLLI2S multiplication factors. */
__HAL_RCC_PLLI2S_CONFIG(PLLI2SInit->PLLI2SMUL);
-
+
/* Enable the main PLLI2S. */
__HAL_RCC_PLLI2S_ENABLE();
-
+
/* Get Start Tick*/
tickstart = HAL_GetTick();
-
+
/* Wait till PLLI2S is ready */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) == RESET) {
+ if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
- }
- else
- {
+ } else {
/* PLLI2S cannot be modified as already used by I2S2 or I2S3 */
return HAL_ERROR;
}
@@ -692,52 +611,46 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLLI2S(RCC_PLLI2SInitTypeDef *PLLI2SInit)
}
/**
- * @brief Disable PLLI2S
- * @note PLLI2S is not disabled if used by I2S2 or I2S3 Interface.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_RCCEx_DisablePLLI2S(void)
-{
+ * @brief Disable PLLI2S
+ * @note PLLI2S is not disabled if used by I2S2 or I2S3 Interface.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCCEx_DisablePLLI2S(void) {
uint32_t tickstart = 0U;
/* Disable PLL I2S as not requested by I2S2 or I2S3*/
- if (HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S2SRC) && HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S3SRC))
- {
+ if (HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S2SRC) && HAL_IS_BIT_CLR(RCC->CFGR2, RCC_CFGR2_I2S3SRC)) {
/* Disable the main PLLI2S. */
__HAL_RCC_PLLI2S_DISABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
-
- /* Wait till PLLI2S is ready */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLLI2S_TIMEOUT_VALUE)
- {
+
+ /* Wait till PLLI2S is ready */
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLLI2SRDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLLI2S_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
- }
- else
- {
+ } else {
/* PLLI2S is currently used by I2S2 or I2S3. Cannot be disabled.*/
return HAL_ERROR;
}
-
+
return HAL_OK;
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup RCCEx_Exported_Functions_Group3 PLL2 Management function
* @brief PLL2 Management functions
*
-@verbatim
+@verbatim
===============================================================================
##### Extended PLL2 Management functions #####
- ===============================================================================
+ ===============================================================================
[..]
This subsection provides a set of functions allowing to control the PLL2
activation or deactivation
@@ -746,70 +659,59 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLLI2S(void)
*/
/**
- * @brief Enable PLL2
- * @param PLL2Init pointer to an RCC_PLL2InitTypeDef structure that
- * contains the configuration information for the PLL2
- * @note The PLL2 configuration not modified if used indirectly as system clock.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init)
-{
+ * @brief Enable PLL2
+ * @param PLL2Init pointer to an RCC_PLL2InitTypeDef structure that
+ * contains the configuration information for the PLL2
+ * @note The PLL2 configuration not modified if used indirectly as system clock.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init) {
uint32_t tickstart = 0U;
- /* This bit can not be cleared if the PLL2 clock is used indirectly as system
+ /* This bit can not be cleared if the PLL2 clock is used indirectly as system
clock (i.e. it is used as PLL clock entry that is used as system clock). */
- if((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && \
- (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && \
- ((READ_BIT(RCC->CFGR2,RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2))
- {
+ if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK)
+ && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
/* Check the parameters */
assert_param(IS_RCC_PLL2_MUL(PLL2Init->PLL2MUL));
assert_param(IS_RCC_HSE_PREDIV2(PLL2Init->HSEPrediv2Value));
/* Prediv2 can be written only when the PLLI2S is disabled. */
/* Return an error only if new value is different from the programmed value */
- if (HAL_IS_BIT_SET(RCC->CR,RCC_CR_PLL3ON) && \
- (__HAL_RCC_HSE_GET_PREDIV2() != PLL2Init->HSEPrediv2Value))
- {
+ if (HAL_IS_BIT_SET(RCC->CR, RCC_CR_PLL3ON) && (__HAL_RCC_HSE_GET_PREDIV2() != PLL2Init->HSEPrediv2Value)) {
return HAL_ERROR;
}
/* Disable the main PLL2. */
__HAL_RCC_PLL2_DISABLE();
-
+
/* Get Start Tick*/
tickstart = HAL_GetTick();
-
+
/* Wait till PLL2 is disabled */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLL2_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
-
+
/* Configure the HSE prediv2 factor --------------------------------*/
__HAL_RCC_HSE_PREDIV2_CONFIG(PLL2Init->HSEPrediv2Value);
/* Configure the main PLL2 multiplication factors. */
__HAL_RCC_PLL2_CONFIG(PLL2Init->PLL2MUL);
-
+
/* Enable the main PLL2. */
__HAL_RCC_PLL2_ENABLE();
-
+
/* Get Start Tick*/
tickstart = HAL_GetTick();
-
+
/* Wait till PLL2 is ready */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) == RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLL2_TIMEOUT_VALUE)
- {
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) == RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -819,35 +721,28 @@ HAL_StatusTypeDef HAL_RCCEx_EnablePLL2(RCC_PLL2InitTypeDef *PLL2Init)
}
/**
- * @brief Disable PLL2
- * @note PLL2 is not disabled if used indirectly as system clock.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void)
-{
+ * @brief Disable PLL2
+ * @note PLL2 is not disabled if used indirectly as system clock.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void) {
uint32_t tickstart = 0U;
- /* This bit can not be cleared if the PLL2 clock is used indirectly as system
+ /* This bit can not be cleared if the PLL2 clock is used indirectly as system
clock (i.e. it is used as PLL clock entry that is used as system clock). */
- if((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && \
- (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && \
- ((READ_BIT(RCC->CFGR2,RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2))
- {
+ if ((__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE) && (__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK)
+ && ((READ_BIT(RCC->CFGR2, RCC_CFGR2_PREDIV1SRC)) == RCC_CFGR2_PREDIV1SRC_PLL2)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
/* Disable the main PLL2. */
__HAL_RCC_PLL2_DISABLE();
/* Get Start Tick*/
tickstart = HAL_GetTick();
-
- /* Wait till PLL2 is disabled */
- while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != RESET)
- {
- if((HAL_GetTick() - tickstart ) > PLL2_TIMEOUT_VALUE)
- {
+
+ /* Wait till PLL2 is disabled */
+ while (__HAL_RCC_GET_FLAG(RCC_FLAG_PLL2RDY) != RESET) {
+ if ((HAL_GetTick() - tickstart) > PLL2_TIMEOUT_VALUE) {
return HAL_TIMEOUT;
}
}
@@ -857,23 +752,22 @@ HAL_StatusTypeDef HAL_RCCEx_DisablePLL2(void)
}
/**
- * @}
- */
+ * @}
+ */
#endif /* STM32F105xC || STM32F107xC */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_RCC_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
-
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c
index 89c7f948..9ab04fe8 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim.c
@@ -3,7 +3,7 @@
* @file stm32f1xx_hal_tim.c
* @author MCD Application Team
* @brief TIM HAL module driver
- * This file provides firmware functions to manage the following
+ * This file provides firmware functions to manage the following
* functionalities of the Timer (TIM) peripheral:
* + Time Base Initialization
* + Time Base Start
@@ -17,11 +17,11 @@
* + Time Input Capture Initialization
* + Time Input Capture Channel Configuration
* + Time Input Capture Start
- * + Time Input Capture Start Interruption
+ * + Time Input Capture Start Interruption
* + Time Input Capture Start DMA
* + Time One Pulse Initialization
* + Time One Pulse Channel Configuration
- * + Time One Pulse Start
+ * + Time One Pulse Start
* + Time Encoder Interface Initialization
* + Time Encoder Interface Start
* + Time Encoder Interface Start Interruption
@@ -35,18 +35,18 @@
==============================================================================
[..] The Timer features include:
(#) 16-bit up, down, up/down auto-reload counter.
- (#) 16-bit programmable prescaler allowing dividing (also on the fly) the
+ (#) 16-bit programmable prescaler allowing dividing (also on the fly) the
counter clock frequency either by any factor between 1 and 65536.
(#) Up to 4 independent channels for:
(++) Input Capture
(++) Output Compare
(++) PWM generation (Edge and Center-aligned Mode)
- (++) One-pulse mode output
+ (++) One-pulse mode output
##### How to use this driver #####
==============================================================================
[..]
- (#) Initialize the TIM low level resources by implementing the following functions
+ (#) Initialize the TIM low level resources by implementing the following functions
depending from feature used :
(++) Time Base : HAL_TIM_Base_MspInit()
(++) Input Capture : HAL_TIM_IC_MspInit()
@@ -62,21 +62,21 @@
__HAL_RCC_GPIOx_CLK_ENABLE();
(+++) Configure these TIM pins in Alternate function mode using HAL_GPIO_Init();
- (#) The external Clock can be configured, if needed (the default clock is the
+ (#) The external Clock can be configured, if needed (the default clock is the
internal clock from the APBx), using the following function:
- HAL_TIM_ConfigClockSource, the clock configuration should be done before
+ HAL_TIM_ConfigClockSource, the clock configuration should be done before
any start function.
- (#) Configure the TIM in the desired functioning mode using one of the
+ (#) Configure the TIM in the desired functioning mode using one of the
Initialization function of this driver:
(++) HAL_TIM_Base_Init: to use the Timer to generate a simple time base
- (++) HAL_TIM_OC_Init and HAL_TIM_OC_ConfigChannel: to use the Timer to generate an
+ (++) HAL_TIM_OC_Init and HAL_TIM_OC_ConfigChannel: to use the Timer to generate an
Output Compare signal.
- (++) HAL_TIM_PWM_Init and HAL_TIM_PWM_ConfigChannel: to use the Timer to generate a
+ (++) HAL_TIM_PWM_Init and HAL_TIM_PWM_ConfigChannel: to use the Timer to generate a
PWM signal.
- (++) HAL_TIM_IC_Init and HAL_TIM_IC_ConfigChannel: to use the Timer to measure an
+ (++) HAL_TIM_IC_Init and HAL_TIM_IC_ConfigChannel: to use the Timer to measure an
external signal.
- (++) HAL_TIM_OnePulse_Init and HAL_TIM_OnePulse_ConfigChannel: to use the Timer
+ (++) HAL_TIM_OnePulse_Init and HAL_TIM_OnePulse_ConfigChannel: to use the Timer
in One Pulse Mode.
(++) HAL_TIM_Encoder_Init: to use the Timer Encoder Interface.
@@ -127,13 +127,13 @@
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup TIM TIM
- * @brief TIM HAL module driver
- * @{
- */
+ * @brief TIM HAL module driver
+ * @{
+ */
#ifdef HAL_TIM_MODULE_ENABLED
@@ -143,41 +143,36 @@
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/** @defgroup TIM_Private_Functions TIM Private Functions
- * @{
- */
+ * @{
+ */
static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config);
static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter);
-static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
- uint32_t TIM_ICFilter);
+static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter);
static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter);
-static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
- uint32_t TIM_ICFilter);
-static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
- uint32_t TIM_ICFilter);
-static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler,
- uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter);
-static void TIM_ITRx_SetConfig(TIM_TypeDef* TIMx, uint16_t InputTriggerSource);
+static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter);
+static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter);
+static void TIM_ETR_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ExtTRGPrescaler, uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter);
+static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint16_t InputTriggerSource);
static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma);
static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma);
-static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim,
- TIM_SlaveConfigTypeDef * sSlaveConfig);
+static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef *sSlaveConfig);
/**
- * @}
- */
+ * @}
+ */
/* Exported functions ---------------------------------------------------------*/
/** @defgroup TIM_Exported_Functions TIM Exported Functions
- * @{
- */
+ * @{
+ */
-/** @defgroup TIM_Exported_Functions_Group1 Time Base functions
- * @brief Time Base functions
+/** @defgroup TIM_Exported_Functions_Group1 Time Base functions
+ * @brief Time Base functions
*
-@verbatim
+@verbatim
==============================================================================
##### Time Base functions #####
==============================================================================
@@ -196,20 +191,18 @@ static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim,
* @{
*/
/**
- * @brief Initializes the TIM Time base Unit according to the specified
- * parameters in the TIM_HandleTypeDef and create the associated handle.
- * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
- * requires a timer reset to avoid unexpected direction
- * due to DIR bit readonly in center aligned mode.
- * Ex: call @ref HAL_TIM_Base_DeInit() before HAL_TIM_Base_Init()
- * @param htim : TIM Base handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM Time base Unit according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
+ * requires a timer reset to avoid unexpected direction
+ * due to DIR bit readonly in center aligned mode.
+ * Ex: call @ref HAL_TIM_Base_DeInit() before HAL_TIM_Base_Init()
+ * @param htim : TIM Base handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim) {
/* Check the TIM handle allocation */
- if(htim == NULL)
- {
+ if (htim == NULL) {
return HAL_ERROR;
}
@@ -219,34 +212,32 @@ HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim)
assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload));
- if(htim->State == HAL_TIM_STATE_RESET)
- {
+ if (htim->State == HAL_TIM_STATE_RESET) {
/* Allocate lock resource and initialize it */
htim->Lock = HAL_UNLOCKED;
-
+
/* Init the low level hardware : GPIO, CLOCK, NVIC */
HAL_TIM_Base_MspInit(htim);
}
/* Set the TIM state */
- htim->State= HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Set the Time Base configuration */
TIM_Base_SetConfig(htim->Instance, &htim->Init);
/* Initialize the TIM state*/
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
return HAL_OK;
}
/**
- * @brief DeInitializes the TIM Base peripheral
- * @param htim : TIM Base handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes the TIM Base peripheral
+ * @param htim : TIM Base handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
@@ -268,12 +259,11 @@ HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Initializes the TIM Base MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM Base MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -282,12 +272,11 @@ __weak void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief DeInitializes TIM Base MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes TIM Base MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -295,67 +284,63 @@ __weak void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim)
*/
}
-
/**
- * @brief Starts the TIM Base generation.
- * @param htim : TIM handle
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim)
-{
+ * @brief Starts the TIM Base generation.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
/* Set the TIM state */
- htim->State= HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Enable the Peripheral */
__HAL_TIM_ENABLE(htim);
/* Change the TIM state*/
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
- * @brief Stops the TIM Base generation.
- * @param htim : TIM handle
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim)
-{
+ * @brief Stops the TIM Base generation.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
/* Set the TIM state */
- htim->State= HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Disable the Peripheral */
__HAL_TIM_DISABLE(htim);
/* Change the TIM state*/
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
- * @brief Starts the TIM Base generation in interrupt mode.
- * @param htim : TIM handle
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim)
-{
+ * @brief Starts the TIM Base generation in interrupt mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
- /* Enable the TIM Update interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE);
+ /* Enable the TIM Update interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE);
- /* Enable the Peripheral */
+ /* Enable the Peripheral */
__HAL_TIM_ENABLE(htim);
/* Return function status */
@@ -363,12 +348,11 @@ HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim)
}
/**
- * @brief Stops the TIM Base generation in interrupt mode.
- * @param htim : TIM handle
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim)
-{
+ * @brief Stops the TIM Base generation in interrupt mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
/* Disable the TIM Update interrupt */
@@ -382,29 +366,22 @@ HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim)
}
/**
- * @brief Starts the TIM Base generation in DMA mode.
- * @param htim : TIM handle
- * @param pData : The source Buffer address.
- * @param Length : The length of data to be transferred from memory to peripheral.
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length)
-{
+ * @brief Starts the TIM Base generation in DMA mode.
+ * @param htim : TIM handle
+ * @param pData : The source Buffer address.
+ * @param Length : The length of data to be transferred from memory to peripheral.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length) {
/* Check the parameters */
assert_param(IS_TIM_DMA_INSTANCE(htim->Instance));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if((pData == 0U) && (Length > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if ((pData == 0U) && (Length > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
@@ -412,7 +389,7 @@ HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pDat
htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt;
/* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ;
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError;
/* Enable the DMA channel */
HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)pData, (uint32_t)&htim->Instance->ARR, Length);
@@ -428,12 +405,11 @@ HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pDat
}
/**
- * @brief Stops the TIM Base generation in DMA mode.
- * @param htim : TIM handle
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim)
-{
+ * @brief Stops the TIM Base generation in DMA mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_DMA_INSTANCE(htim->Instance));
@@ -451,13 +427,13 @@ HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim)
}
/**
- * @}
- */
+ * @}
+ */
-/** @defgroup TIM_Exported_Functions_Group2 Time Output Compare functions
- * @brief Time Output Compare functions
+/** @defgroup TIM_Exported_Functions_Group2 Time Output Compare functions
+ * @brief Time Output Compare functions
*
-@verbatim
+@verbatim
==============================================================================
##### Time Output Compare functions #####
==============================================================================
@@ -476,20 +452,18 @@ HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim)
* @{
*/
/**
- * @brief Initializes the TIM Output Compare according to the specified
- * parameters in the TIM_HandleTypeDef and create the associated handle.
- * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
- * requires a timer reset to avoid unexpected direction
- * due to DIR bit readonly in center aligned mode.
- * Ex: call @ref HAL_TIM_OC_DeInit() before HAL_TIM_OC_Init()
- * @param htim : TIM Output Compare handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef* htim)
-{
+ * @brief Initializes the TIM Output Compare according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
+ * requires a timer reset to avoid unexpected direction
+ * due to DIR bit readonly in center aligned mode.
+ * Ex: call @ref HAL_TIM_OC_DeInit() before HAL_TIM_OC_Init()
+ * @param htim : TIM Output Compare handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef *htim) {
/* Check the TIM handle allocation */
- if(htim == NULL)
- {
+ if (htim == NULL) {
return HAL_ERROR;
}
@@ -499,38 +473,36 @@ HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef* htim)
assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload));
- if(htim->State == HAL_TIM_STATE_RESET)
- {
+ if (htim->State == HAL_TIM_STATE_RESET) {
/* Allocate lock resource and initialize it */
htim->Lock = HAL_UNLOCKED;
-
+
/* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
HAL_TIM_OC_MspInit(htim);
}
/* Set the TIM state */
- htim->State= HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Init the base time for the Output Compare */
- TIM_Base_SetConfig(htim->Instance, &htim->Init);
+ TIM_Base_SetConfig(htim->Instance, &htim->Init);
/* Initialize the TIM state*/
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
return HAL_OK;
}
/**
- * @brief DeInitializes the TIM peripheral
- * @param htim : TIM Output Compare handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes the TIM peripheral
+ * @param htim : TIM Output Compare handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
- htim->State = HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Disable the TIM Peripheral Clock */
__HAL_TIM_DISABLE(htim);
@@ -548,12 +520,11 @@ HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Initializes the TIM Output Compare MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM Output Compare MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -562,12 +533,11 @@ __weak void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief DeInitializes TIM Output Compare MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes TIM Output Compare MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -576,26 +546,24 @@ __weak void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Starts the TIM Output Compare signal generation.
- * @param htim : TIM Output Compare handle
- * @param Channel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the TIM Output Compare signal generation.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
/* Enable the Output compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Enable the main output */
__HAL_TIM_MOE_ENABLE(htim);
}
@@ -608,26 +576,24 @@ HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Stops the TIM Output Compare signal generation.
- * @param htim : TIM handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Output Compare signal generation.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
/* Disable the Output compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Disable the Main Ouput */
__HAL_TIM_MOE_DISABLE(htim);
}
@@ -640,60 +606,49 @@ HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Starts the TIM Output Compare signal generation in interrupt mode.
- * @param htim : TIM OC handle
- * @param Channel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the TIM Output Compare signal generation in interrupt mode.
+ * @param htim : TIM OC handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Enable the TIM Capture/Compare 1 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Enable the TIM Capture/Compare 2 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Enable the TIM Capture/Compare 3 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Enable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Enable the TIM Capture/Compare 4 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
- }
- break;
+ case TIM_CHANNEL_4: {
+ /* Enable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
+ } break;
- default:
+ default:
break;
}
/* Enable the Output compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Enable the main output */
__HAL_TIM_MOE_ENABLE(htim);
}
@@ -706,60 +661,49 @@ HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Stops the TIM Output Compare signal generation in interrupt mode.
- * @param htim : TIM Output Compare handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Output Compare signal generation in interrupt mode.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Capture/Compare 1 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Capture/Compare 2 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Capture/Compare 3 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Disable the TIM Capture/Compare 4 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
- }
- break;
+ case TIM_CHANNEL_4: {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
+ } break;
- default:
+ default:
break;
}
/* Disable the Output compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Disable the Main Ouput */
__HAL_TIM_MOE_DISABLE(htim);
}
@@ -772,113 +716,96 @@ HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Starts the TIM Output Compare signal generation in DMA mode.
- * @param htim : TIM Output Compare handle
- * @param Channel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @param pData : The source Buffer address.
- * @param Length : The length of data to be transferred from memory to TIM peripheral
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
-{
+ * @brief Starts the TIM Output Compare signal generation in DMA mode.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @param pData : The source Buffer address.
+ * @param Length : The length of data to be transferred from memory to TIM peripheral
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if(((uint32_t)pData == 0U) && (Length > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if (((uint32_t)pData == 0U) && (Length > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
- /* Enable the TIM Capture/Compare 1 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ /* Enable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_2: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
- /* Enable the TIM Capture/Compare 2 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ /* Enable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_3: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length);
- /* Enable the TIM Capture/Compare 3 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ /* Enable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_4: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length);
- /* Enable the TIM Capture/Compare 4 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
- }
- break;
+ /* Enable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
+ } break;
- default:
+ default:
break;
}
/* Enable the Output compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Enable the main output */
__HAL_TIM_MOE_ENABLE(htim);
}
@@ -891,60 +818,49 @@ HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel
}
/**
- * @brief Stops the TIM Output Compare signal generation in DMA mode.
- * @param htim : TIM Output Compare handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Output Compare signal generation in DMA mode.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Capture/Compare 1 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Capture/Compare 2 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Capture/Compare 3 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Disable the TIM Capture/Compare 4 interrupt */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
- }
- break;
+ case TIM_CHANNEL_4: {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
+ } break;
- default:
+ default:
break;
}
/* Disable the Output compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Disable the Main Ouput */
__HAL_TIM_MOE_DISABLE(htim);
}
@@ -960,13 +876,13 @@ HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @}
- */
+ * @}
+ */
-/** @defgroup TIM_Exported_Functions_Group3 Time PWM functions
- * @brief Time PWM functions
+/** @defgroup TIM_Exported_Functions_Group3 Time PWM functions
+ * @brief Time PWM functions
*
-@verbatim
+@verbatim
==============================================================================
##### Time PWM functions #####
==============================================================================
@@ -985,20 +901,18 @@ HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
* @{
*/
/**
- * @brief Initializes the TIM PWM Time Base according to the specified
- * parameters in the TIM_HandleTypeDef and create the associated handle.
- * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
- * requires a timer reset to avoid unexpected direction
- * due to DIR bit readonly in center aligned mode.
- * Ex: call @ref HAL_TIM_PWM_DeInit() before HAL_TIM_PWM_Init()
- * @param htim : TIM handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM PWM Time Base according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
+ * requires a timer reset to avoid unexpected direction
+ * due to DIR bit readonly in center aligned mode.
+ * Ex: call @ref HAL_TIM_PWM_DeInit() before HAL_TIM_PWM_Init()
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim) {
/* Check the TIM handle allocation */
- if(htim == NULL)
- {
+ if (htim == NULL) {
return HAL_ERROR;
}
@@ -1008,34 +922,32 @@ HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim)
assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload));
- if(htim->State == HAL_TIM_STATE_RESET)
- {
+ if (htim->State == HAL_TIM_STATE_RESET) {
/* Allocate lock resource and initialize it */
htim->Lock = HAL_UNLOCKED;
-
+
/* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
HAL_TIM_PWM_MspInit(htim);
}
/* Set the TIM state */
- htim->State= HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Init the base time for the PWM */
TIM_Base_SetConfig(htim->Instance, &htim->Init);
/* Initialize the TIM state*/
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
return HAL_OK;
}
/**
- * @brief DeInitializes the TIM peripheral
- * @param htim : TIM handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes the TIM peripheral
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
@@ -1057,12 +969,11 @@ HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Initializes the TIM PWM MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM PWM MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -1071,12 +982,11 @@ __weak void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief DeInitializes TIM PWM MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes TIM PWM MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -1085,26 +995,24 @@ __weak void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Starts the PWM signal generation.
- * @param htim : TIM handle
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the PWM signal generation.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
/* Enable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Enable the main output */
__HAL_TIM_MOE_ENABLE(htim);
}
@@ -1117,26 +1025,24 @@ HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Stops the PWM signal generation.
- * @param htim : TIM handle
- * @param Channel : TIM Channels to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the PWM signal generation.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
/* Disable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Disable the Main Ouput */
__HAL_TIM_MOE_DISABLE(htim);
}
@@ -1152,60 +1058,49 @@ HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Starts the PWM signal generation in interrupt mode.
- * @param htim : TIM handle
- * @param Channel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the PWM signal generation in interrupt mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Enable the TIM Capture/Compare 1 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Enable the TIM Capture/Compare 2 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Enable the TIM Capture/Compare 3 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Enable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Enable the TIM Capture/Compare 4 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
- }
- break;
+ case TIM_CHANNEL_4: {
+ /* Enable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
+ } break;
- default:
+ default:
break;
}
/* Enable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Enable the main output */
__HAL_TIM_MOE_ENABLE(htim);
}
@@ -1218,60 +1113,49 @@ HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel
}
/**
- * @brief Stops the PWM signal generation in interrupt mode.
- * @param htim : TIM handle
- * @param Channel : TIM Channels to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT (TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the PWM signal generation in interrupt mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Capture/Compare 1 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Capture/Compare 2 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Capture/Compare 3 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Disable the TIM Capture/Compare 4 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
- }
- break;
+ case TIM_CHANNEL_4: {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
+ } break;
- default:
+ default:
break;
}
/* Disable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Disable the Main Ouput */
__HAL_TIM_MOE_DISABLE(htim);
}
@@ -1284,113 +1168,96 @@ HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT (TIM_HandleTypeDef *htim, uint32_t Channel
}
/**
- * @brief Starts the TIM PWM signal generation in DMA mode.
- * @param htim : TIM handle
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @param pData : The source Buffer address.
- * @param Length : The length of data to be transferred from memory to TIM peripheral
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
-{
+ * @brief Starts the TIM PWM signal generation in DMA mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @param pData : The source Buffer address.
+ * @param Length : The length of data to be transferred from memory to TIM peripheral
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if(((uint32_t)pData == 0U) && (Length > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if (((uint32_t)pData == 0U) && (Length > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
- /* Enable the TIM Capture/Compare 1 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ /* Enable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_2: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
- /* Enable the TIM Capture/Compare 2 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ /* Enable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_3: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length);
- /* Enable the TIM Output Capture/Compare 3 request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ /* Enable the TIM Output Capture/Compare 3 request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_4: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length);
- /* Enable the TIM Capture/Compare 4 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
- }
- break;
+ /* Enable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
+ } break;
- default:
+ default:
break;
}
/* Enable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Enable the main output */
__HAL_TIM_MOE_ENABLE(htim);
}
@@ -1403,60 +1270,49 @@ HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channe
}
/**
- * @brief Stops the TIM PWM signal generation in DMA mode.
- * @param htim : TIM handle
- * @param Channel : TIM Channels to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM PWM signal generation in DMA mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Capture/Compare 1 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Capture/Compare 2 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Capture/Compare 3 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Disable the TIM Capture/Compare 4 interrupt */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
- }
- break;
+ case TIM_CHANNEL_4: {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
+ } break;
- default:
+ default:
break;
}
/* Disable the Capture compare channel */
TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Disable the Main Ouput */
__HAL_TIM_MOE_DISABLE(htim);
}
@@ -1472,13 +1328,13 @@ HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel
}
/**
- * @}
- */
+ * @}
+ */
-/** @defgroup TIM_Exported_Functions_Group4 Time Input Capture functions
- * @brief Time Input Capture functions
+/** @defgroup TIM_Exported_Functions_Group4 Time Input Capture functions
+ * @brief Time Input Capture functions
*
-@verbatim
+@verbatim
==============================================================================
##### Time Input Capture functions #####
==============================================================================
@@ -1497,20 +1353,18 @@ HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel
* @{
*/
/**
- * @brief Initializes the TIM Input Capture Time base according to the specified
- * parameters in the TIM_HandleTypeDef and create the associated handle.
- * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
- * requires a timer reset to avoid unexpected direction
- * due to DIR bit readonly in center aligned mode.
- * Ex: call @ref HAL_TIM_IC_DeInit() before HAL_TIM_IC_Init()
- * @param htim : TIM Input Capture handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM Input Capture Time base according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
+ * requires a timer reset to avoid unexpected direction
+ * due to DIR bit readonly in center aligned mode.
+ * Ex: call @ref HAL_TIM_IC_DeInit() before HAL_TIM_IC_Init()
+ * @param htim : TIM Input Capture handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim) {
/* Check the TIM handle allocation */
- if(htim == NULL)
- {
+ if (htim == NULL) {
return HAL_ERROR;
}
@@ -1520,34 +1374,32 @@ HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim)
assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision));
assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload));
- if(htim->State == HAL_TIM_STATE_RESET)
- {
+ if (htim->State == HAL_TIM_STATE_RESET) {
/* Allocate lock resource and initialize it */
htim->Lock = HAL_UNLOCKED;
-
+
/* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
HAL_TIM_IC_MspInit(htim);
}
/* Set the TIM state */
- htim->State= HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Init the base time for the input capture */
TIM_Base_SetConfig(htim->Instance, &htim->Init);
/* Initialize the TIM state*/
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
return HAL_OK;
}
/**
- * @brief DeInitializes the TIM peripheral
- * @param htim : TIM Input Capture handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes the TIM peripheral
+ * @param htim : TIM Input Capture handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
@@ -1569,12 +1421,11 @@ HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Initializes the TIM Input Capture MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM Input Capture MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -1583,12 +1434,11 @@ __weak void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief DeInitializes TIM Input Capture MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes TIM Input Capture MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -1597,18 +1447,17 @@ __weak void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Starts the TIM Input Capture measurement.
- * @param htim : TIM Input Capture handle
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_IC_Start (TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the TIM Input Capture measurement.
+ * @param htim : TIM Input Capture handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
@@ -1623,18 +1472,17 @@ HAL_StatusTypeDef HAL_TIM_IC_Start (TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Stops the TIM Input Capture measurement.
- * @param htim : TIM handle
- * @param Channel : TIM Channels to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Input Capture measurement.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
@@ -1649,52 +1497,42 @@ HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Starts the TIM Input Capture measurement in interrupt mode.
- * @param htim : TIM Input Capture handle
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_IC_Start_IT (TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the TIM Input Capture measurement in interrupt mode.
+ * @param htim : TIM Input Capture handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Enable the TIM Capture/Compare 1 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Enable the TIM Capture/Compare 2 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Enable the TIM Capture/Compare 3 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Enable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Enable the TIM Capture/Compare 4 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
- }
- break;
+ case TIM_CHANNEL_4: {
+ /* Enable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4);
+ } break;
- default:
+ default:
break;
}
/* Enable the Input Capture channel */
@@ -1708,52 +1546,42 @@ HAL_StatusTypeDef HAL_TIM_IC_Start_IT (TIM_HandleTypeDef *htim, uint32_t Channel
}
/**
- * @brief Stops the TIM Input Capture measurement in interrupt mode.
- * @param htim : TIM handle
- * @param Channel : TIM Channels to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Input Capture measurement in interrupt mode.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Capture/Compare 1 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Capture/Compare 2 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Capture/Compare 3 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Disable the TIM Capture/Compare 4 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
- }
- break;
+ case TIM_CHANNEL_4: {
+ /* Disable the TIM Capture/Compare 4 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4);
+ } break;
- default:
+ default:
break;
}
@@ -1768,107 +1596,91 @@ HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Starts the TIM Input Capture measurement in DMA mode.
- * @param htim : TIM Input Capture handle
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @param pData : The destination Buffer address.
- * @param Length : The length of data to be transferred from TIM peripheral to memory.
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
-{
+ * @brief Starts the TIM Input Capture measurement in DMA mode.
+ * @param htim : TIM Input Capture handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @param pData : The destination Buffer address.
+ * @param Length : The length of data to be transferred from TIM peripheral to memory.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if((pData == 0U) && (Length > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if ((pData == 0U) && (Length > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length);
- /* Enable the TIM Capture/Compare 1 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ /* Enable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt;
+ case TIM_CHANNEL_2: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData, Length);
- /* Enable the TIM Capture/Compare 2 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ /* Enable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt;
+ case TIM_CHANNEL_3: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->CCR3, (uint32_t)pData, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->CCR3, (uint32_t)pData, Length);
- /* Enable the TIM Capture/Compare 3 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ /* Enable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt;
+ case TIM_CHANNEL_4: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->CCR4, (uint32_t)pData, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->CCR4, (uint32_t)pData, Length);
- /* Enable the TIM Capture/Compare 4 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
- }
- break;
+ /* Enable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4);
+ } break;
- default:
+ default:
break;
}
@@ -1883,53 +1695,43 @@ HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel
}
/**
- * @brief Stops the TIM Input Capture measurement in DMA mode.
- * @param htim : TIM Input Capture handle
- * @param Channel : TIM Channels to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Input Capture measurement in DMA mode.
+ * @param htim : TIM Input Capture handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel));
assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Capture/Compare 1 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Capture/Compare 2 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Capture/Compare 3 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- case TIM_CHANNEL_4:
- {
- /* Disable the TIM Capture/Compare 4 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
- }
- break;
+ case TIM_CHANNEL_4: {
+ /* Disable the TIM Capture/Compare 4 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4);
+ } break;
- default:
+ default:
break;
}
@@ -1946,13 +1748,13 @@ HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
return HAL_OK;
}
/**
- * @}
- */
+ * @}
+ */
-/** @defgroup TIM_Exported_Functions_Group5 Time One Pulse functions
- * @brief Time One Pulse functions
+/** @defgroup TIM_Exported_Functions_Group5 Time One Pulse functions
+ * @brief Time One Pulse functions
*
-@verbatim
+@verbatim
==============================================================================
##### Time One Pulse functions #####
==============================================================================
@@ -1971,24 +1773,22 @@ HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
* @{
*/
/**
- * @brief Initializes the TIM One Pulse Time Base according to the specified
- * parameters in the TIM_HandleTypeDef and create the associated handle.
- * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
- * requires a timer reset to avoid unexpected direction
- * due to DIR bit readonly in center aligned mode.
- * Ex: call @ref HAL_TIM_OnePulse_DeInit() before HAL_TIM_OnePulse_Init()
- * @param htim : TIM OnePulse handle
- * @param OnePulseMode : Select the One pulse mode.
- * This parameter can be one of the following values:
- * @arg TIM_OPMODE_SINGLE: Only one pulse will be generated.
- * @arg TIM_OPMODE_REPETITIVE: Repetitive pulses wil be generated.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode)
-{
+ * @brief Initializes the TIM One Pulse Time Base according to the specified
+ * parameters in the TIM_HandleTypeDef and create the associated handle.
+ * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
+ * requires a timer reset to avoid unexpected direction
+ * due to DIR bit readonly in center aligned mode.
+ * Ex: call @ref HAL_TIM_OnePulse_DeInit() before HAL_TIM_OnePulse_Init()
+ * @param htim : TIM OnePulse handle
+ * @param OnePulseMode : Select the One pulse mode.
+ * This parameter can be one of the following values:
+ * @arg TIM_OPMODE_SINGLE: Only one pulse will be generated.
+ * @arg TIM_OPMODE_REPETITIVE: Repetitive pulses wil be generated.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode) {
/* Check the TIM handle allocation */
- if(htim == NULL)
- {
+ if (htim == NULL) {
return HAL_ERROR;
}
@@ -1999,17 +1799,16 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePul
assert_param(IS_TIM_AUTORELOAD_PRELOAD(htim->Init.AutoReloadPreload));
assert_param(IS_TIM_OPM_MODE(OnePulseMode));
- if(htim->State == HAL_TIM_STATE_RESET)
- {
+ if (htim->State == HAL_TIM_STATE_RESET) {
/* Allocate lock resource and initialize it */
htim->Lock = HAL_UNLOCKED;
-
+
/* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
HAL_TIM_OnePulse_MspInit(htim);
}
/* Set the TIM state */
- htim->State= HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Configure the Time base in the One Pulse Mode */
TIM_Base_SetConfig(htim->Instance, &htim->Init);
@@ -2021,18 +1820,17 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePul
htim->Instance->CR1 |= OnePulseMode;
/* Initialize the TIM state*/
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
return HAL_OK;
}
/**
- * @brief DeInitializes the TIM One Pulse
- * @param htim : TIM One Pulse handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes the TIM One Pulse
+ * @param htim : TIM One Pulse handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
@@ -2054,12 +1852,11 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Initializes the TIM One Pulse MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM One Pulse MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -2068,12 +1865,11 @@ __weak void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief DeInitializes TIM One Pulse MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes TIM One Pulse MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -2082,33 +1878,31 @@ __weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Starts the TIM One Pulse signal generation.
- * @param htim : TIM One Pulse handle
- * @param OutputChannel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
-{
+ * @brief Starts the TIM One Pulse signal generation.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) {
/* Prevent unused argument(s) compilation warning */
UNUSED(OutputChannel);
- /* Enable the Capture compare and the Input Capture channels
+ /* Enable the Capture compare and the Input Capture channels
(in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
- if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
- in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together
+ if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
+ in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together
- No need to enable the counter, it's enabled automatically by hardware
+ No need to enable the counter, it's enabled automatically by hardware
(the counter starts in response to a stimulus and generate a pulse */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Enable the main output */
__HAL_TIM_MOE_ENABLE(htim);
}
@@ -2118,30 +1912,28 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t Outpu
}
/**
- * @brief Stops the TIM One Pulse signal generation.
- * @param htim : TIM One Pulse handle
- * @param OutputChannel : TIM Channels to be disable
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
-{
+ * @brief Stops the TIM One Pulse signal generation.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channels to be disable
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) {
/* Prevent unused argument(s) compilation warning */
UNUSED(OutputChannel);
/* Disable the Capture compare and the Input Capture channels
(in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
- if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
+ if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Disable the Main Ouput */
__HAL_TIM_MOE_DISABLE(htim);
}
@@ -2154,26 +1946,25 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t Output
}
/**
- * @brief Starts the TIM One Pulse signal generation in interrupt mode.
- * @param htim : TIM One Pulse handle
- * @param OutputChannel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
-{
+ * @brief Starts the TIM One Pulse signal generation in interrupt mode.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) {
/* Prevent unused argument(s) compilation warning */
UNUSED(OutputChannel);
- /* Enable the Capture compare and the Input Capture channels
+ /* Enable the Capture compare and the Input Capture channels
(in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
- if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
- in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together
+ if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
+ in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together
- No need to enable the counter, it's enabled automatically by hardware
+ No need to enable the counter, it's enabled automatically by hardware
(the counter starts in response to a stimulus and generate a pulse */
/* Enable the TIM Capture/Compare 1 interrupt */
@@ -2185,8 +1976,7 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t Ou
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Enable the main output */
__HAL_TIM_MOE_ENABLE(htim);
}
@@ -2196,16 +1986,15 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t Ou
}
/**
- * @brief Stops the TIM One Pulse signal generation in interrupt mode.
- * @param htim : TIM One Pulse handle
- * @param OutputChannel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
-{
+ * @brief Stops the TIM One Pulse signal generation in interrupt mode.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) {
/* Prevent unused argument(s) compilation warning */
UNUSED(OutputChannel);
@@ -2215,35 +2004,34 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Out
/* Disable the TIM Capture/Compare 2 interrupt */
__HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
- /* Disable the Capture compare and the Input Capture channels
+ /* Disable the Capture compare and the Input Capture channels
(in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2)
if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and
- if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
+ if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output
in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
- if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET)
- {
+ if (IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) {
/* Disable the Main Ouput */
__HAL_TIM_MOE_DISABLE(htim);
}
/* Disable the Peripheral */
- __HAL_TIM_DISABLE(htim);
+ __HAL_TIM_DISABLE(htim);
/* Return function status */
return HAL_OK;
}
/**
- * @}
- */
+ * @}
+ */
-/** @defgroup TIM_Exported_Functions_Group6 Time Encoder functions
- * @brief Time Encoder functions
+/** @defgroup TIM_Exported_Functions_Group6 Time Encoder functions
+ * @brief Time Encoder functions
*
-@verbatim
+@verbatim
==============================================================================
##### Time Encoder functions #####
==============================================================================
@@ -2262,24 +2050,22 @@ HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Out
* @{
*/
/**
- * @brief Initializes the TIM Encoder Interface and create the associated handle.
- * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
- * requires a timer reset to avoid unexpected direction
- * due to DIR bit readonly in center aligned mode.
- * Ex: call @ref HAL_TIM_Encoder_DeInit() before HAL_TIM_Encoder_Init()
- * @param htim : TIM Encoder Interface handle
- * @param sConfig : TIM Encoder Interface configuration structure
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig)
-{
- uint32_t tmpsmcr = 0U;
+ * @brief Initializes the TIM Encoder Interface and create the associated handle.
+ * @note Switching from Center Aligned counter mode to Edge counter mode (or reverse)
+ * requires a timer reset to avoid unexpected direction
+ * due to DIR bit readonly in center aligned mode.
+ * Ex: call @ref HAL_TIM_Encoder_DeInit() before HAL_TIM_Encoder_Init()
+ * @param htim : TIM Encoder Interface handle
+ * @param sConfig : TIM Encoder Interface configuration structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef *sConfig) {
+ uint32_t tmpsmcr = 0U;
uint32_t tmpccmr1 = 0U;
- uint32_t tmpccer = 0U;
+ uint32_t tmpccer = 0U;
/* Check the TIM handle allocation */
- if(htim == NULL)
- {
+ if (htim == NULL) {
return HAL_ERROR;
}
@@ -2298,17 +2084,16 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_Ini
assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter));
assert_param(IS_TIM_IC_FILTER(sConfig->IC2Filter));
- if(htim->State == HAL_TIM_STATE_RESET)
- {
+ if (htim->State == HAL_TIM_STATE_RESET) {
/* Allocate lock resource and initialize it */
htim->Lock = HAL_UNLOCKED;
-
+
/* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
HAL_TIM_Encoder_MspInit(htim);
}
/* Set the TIM state */
- htim->State= HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Reset the SMS bits */
htim->Instance->SMCR &= ~TIM_SMCR_SMS;
@@ -2353,19 +2138,17 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_Ini
htim->Instance->CCER = tmpccer;
/* Initialize the TIM state*/
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
return HAL_OK;
}
-
/**
- * @brief DeInitializes the TIM Encoder interface
- * @param htim : TIM Encoder handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes the TIM Encoder interface
+ * @param htim : TIM Encoder handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
@@ -2387,12 +2170,11 @@ HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Initializes the TIM Encoder Interface MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM Encoder Interface MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -2401,12 +2183,11 @@ __weak void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief DeInitializes TIM Encoder Interface MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes TIM Encoder Interface MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -2415,39 +2196,34 @@ __weak void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Starts the TIM Encoder Interface.
- * @param htim : TIM Encoder Interface handle
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the TIM Encoder Interface.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
/* Enable the encoder interface channels */
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
- break;
+ break;
}
- case TIM_CHANNEL_2:
- {
+ case TIM_CHANNEL_2: {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
- break;
+ break;
+ }
+ default: {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+ break;
}
- default :
- {
- TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
- TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
- break;
- }
}
/* Enable the Peripheral */
__HAL_TIM_ENABLE(htim);
@@ -2457,40 +2233,35 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channe
}
/**
- * @brief Stops the TIM Encoder Interface.
- * @param htim : TIM Encoder Interface handle
- * @param Channel : TIM Channels to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Encoder Interface.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- /* Disable the Input Capture channels 1 and 2
- (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
- break;
+ /* Disable the Input Capture channels 1 and 2
+ (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
+ break;
}
- case TIM_CHANNEL_2:
- {
+ case TIM_CHANNEL_2: {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
- break;
+ break;
}
- default :
- {
+ default: {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
- break;
- }
+ break;
+ }
}
/* Disable the Peripheral */
@@ -2501,44 +2272,39 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel
}
/**
- * @brief Starts the TIM Encoder Interface in interrupt mode.
- * @param htim : TIM Encoder Interface handle
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the TIM Encoder Interface in interrupt mode.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
/* Enable the encoder interface channels */
/* Enable the capture compare Interrupts 1 and/or 2 */
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
- break;
+ break;
}
- case TIM_CHANNEL_2:
- {
+ case TIM_CHANNEL_2: {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
__HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
- break;
+ break;
+ }
+ default: {
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ break;
}
- default :
- {
- TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
- TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
- break;
- }
}
/* Enable the Peripheral */
@@ -2549,38 +2315,32 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Cha
}
/**
- * @brief Stops the TIM Encoder Interface in interrupt mode.
- * @param htim : TIM Encoder Interface handle
- * @param Channel : TIM Channels to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Encoder Interface in interrupt mode.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
/* Disable the Input Capture channels 1 and 2
(in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
- if(Channel == TIM_CHANNEL_1)
- {
+ if (Channel == TIM_CHANNEL_1) {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
/* Disable the capture compare Interrupts 1 */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
- }
- else if(Channel == TIM_CHANNEL_2)
- {
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ } else if (Channel == TIM_CHANNEL_2) {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
/* Disable the capture compare Interrupts 2 */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
- }
- else
- {
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ } else {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
@@ -2600,119 +2360,105 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Chan
}
/**
- * @brief Starts the TIM Encoder Interface in DMA mode.
- * @param htim : TIM Encoder Interface handle
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
- * @param pData1 : The destination Buffer address for IC1.
- * @param pData2 : The destination Buffer address for IC2.
- * @param Length : The length of data to be transferred from TIM peripheral to memory.
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length)
-{
+ * @brief Starts the TIM Encoder Interface in DMA mode.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
+ * @param pData1 : The destination Buffer address for IC1.
+ * @param pData2 : The destination Buffer address for IC2.
+ * @param Length : The length of data to be transferred from TIM peripheral to memory.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length) {
/* Check the parameters */
assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if((((pData1 == 0U) || (pData2 == 0U) )) && (Length > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if ((((pData1 == 0U) || (pData2 == 0U))) && (Length > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t )pData1, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length);
- /* Enable the TIM Input Capture DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ /* Enable the TIM Input Capture DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
- /* Enable the Peripheral */
- __HAL_TIM_ENABLE(htim);
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
- /* Enable the Capture compare channel */
- TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
- }
- break;
+ /* Enable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt;
+ case TIM_CHANNEL_2: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length);
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length);
- /* Enable the TIM Input Capture DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ /* Enable the TIM Input Capture DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
- /* Enable the Peripheral */
- __HAL_TIM_ENABLE(htim);
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
- /* Enable the Capture compare channel */
- TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
- }
- break;
+ /* Enable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+ } break;
- case TIM_CHANNEL_ALL:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt;
+ case TIM_CHANNEL_ALL: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length);
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt;
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length);
- /* Enable the Peripheral */
- __HAL_TIM_ENABLE(htim);
+ /* Enable the Peripheral */
+ __HAL_TIM_ENABLE(htim);
- /* Enable the Capture compare channel */
- TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
- TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
+ /* Enable the Capture compare channel */
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE);
+ TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE);
- /* Enable the TIM Input Capture DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
- /* Enable the TIM Input Capture DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ /* Enable the TIM Input Capture DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ /* Enable the TIM Input Capture DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- default:
+ default:
break;
}
/* Return function status */
@@ -2720,38 +2466,32 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Ch
}
/**
- * @brief Stops the TIM Encoder Interface in DMA mode.
- * @param htim : TIM Encoder Interface handle
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
- * @retval HAL status
-*/
-HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Encoder Interface in DMA mode.
+ * @param htim : TIM Encoder Interface handle
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_ALL: TIM Channel 1 and TIM Channel 2 are selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance));
/* Disable the Input Capture channels 1 and 2
(in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */
- if(Channel == TIM_CHANNEL_1)
- {
+ if (Channel == TIM_CHANNEL_1) {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
/* Disable the capture compare DMA Request 1 */
__HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
- }
- else if(Channel == TIM_CHANNEL_2)
- {
+ } else if (Channel == TIM_CHANNEL_2) {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
/* Disable the capture compare DMA Request 2 */
__HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
- }
- else
- {
+ } else {
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE);
@@ -2771,12 +2511,12 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Cha
}
/**
- * @}
- */
-/** @defgroup TIM_Exported_Functions_Group7 TIM IRQ handler management
- * @brief IRQ handler management
+ * @}
+ */
+/** @defgroup TIM_Exported_Functions_Group7 TIM IRQ handler management
+ * @brief IRQ handler management
*
-@verbatim
+@verbatim
==============================================================================
##### IRQ handler management #####
==============================================================================
@@ -2787,29 +2527,24 @@ HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Cha
* @{
*/
/**
- * @brief This function handles TIM interrupts requests.
- * @param htim : TIM handle
- * @retval None
- */
-void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
-{
+ * @brief This function handles TIM interrupts requests.
+ * @param htim : TIM handle
+ * @retval None
+ */
+void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) {
/* Capture compare 1 event */
- if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET)
- {
- if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC1) !=RESET)
- {
+ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET) {
+ if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC1) != RESET) {
{
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
/* Input capture event */
- if((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00U)
- {
+ if ((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00U) {
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
- else
- {
+ else {
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
@@ -2818,20 +2553,16 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
}
}
/* Capture compare 2 event */
- if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET)
- {
- if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC2) !=RESET)
- {
+ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET) {
+ if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC2) != RESET) {
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
/* Input capture event */
- if((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U)
- {
+ if ((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00U) {
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
- else
- {
+ else {
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
@@ -2839,20 +2570,16 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
}
}
/* Capture compare 3 event */
- if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET)
- {
- if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC3) !=RESET)
- {
+ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET) {
+ if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC3) != RESET) {
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
/* Input capture event */
- if((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U)
- {
+ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00U) {
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
- else
- {
+ else {
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
@@ -2860,20 +2587,16 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
}
}
/* Capture compare 4 event */
- if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET)
- {
- if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC4) !=RESET)
- {
+ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET) {
+ if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_CC4) != RESET) {
__HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4);
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
/* Input capture event */
- if((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U)
- {
+ if ((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00U) {
HAL_TIM_IC_CaptureCallback(htim);
}
/* Output compare event */
- else
- {
+ else {
HAL_TIM_OC_DelayElapsedCallback(htim);
HAL_TIM_PWM_PulseFinishedCallback(htim);
}
@@ -2881,37 +2604,29 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
}
}
/* TIM Update event */
- if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET)
- {
- if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) !=RESET)
- {
+ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET) {
+ if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_UPDATE) != RESET) {
__HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE);
HAL_TIM_PeriodElapsedCallback(htim);
}
}
/* TIM Break input event */
- if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET)
- {
- if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) !=RESET)
- {
+ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET) {
+ if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_BREAK) != RESET) {
__HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK);
HAL_TIMEx_BreakCallback(htim);
}
}
/* TIM Trigger detection event */
- if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET)
- {
- if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TRIGGER) !=RESET)
- {
+ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET) {
+ if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_TRIGGER) != RESET) {
__HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER);
HAL_TIM_TriggerCallback(htim);
}
}
/* TIM commutation event */
- if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET)
- {
- if(__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_COM) !=RESET)
- {
+ if (__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET) {
+ if (__HAL_TIM_GET_IT_SOURCE(htim, TIM_IT_COM) != RESET) {
__HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM);
HAL_TIMEx_CommutationCallback(htim);
}
@@ -2919,13 +2634,13 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup TIM_Exported_Functions_Group8 Peripheral Control functions
- * @brief Peripheral Control functions
+ * @brief Peripheral Control functions
*
-@verbatim
+@verbatim
==============================================================================
##### Peripheral Control functions #####
==============================================================================
@@ -2942,20 +2657,19 @@ void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim)
*/
/**
- * @brief Initializes the TIM Output Compare Channels according to the specified
- * parameters in the TIM_OC_InitTypeDef.
- * @param htim : TIM Output Compare handle
- * @param sConfig : TIM Output Compare configuration structure
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel)
-{
+ * @brief Initializes the TIM Output Compare Channels according to the specified
+ * parameters in the TIM_OC_InitTypeDef.
+ * @param htim : TIM Output Compare handle
+ * @param sConfig : TIM Output Compare configuration structure
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef *sConfig, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CHANNELS(Channel));
assert_param(IS_TIM_OC_MODE(sConfig->OCMode));
@@ -2966,41 +2680,32 @@ HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitT
htim->State = HAL_TIM_STATE_BUSY;
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
- /* Configure the TIM Channel 1 in Output Compare */
- TIM_OC1_SetConfig(htim->Instance, sConfig);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ /* Configure the TIM Channel 1 in Output Compare */
+ TIM_OC1_SetConfig(htim->Instance, sConfig);
+ } break;
- case TIM_CHANNEL_2:
- {
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- /* Configure the TIM Channel 2 in Output Compare */
- TIM_OC2_SetConfig(htim->Instance, sConfig);
- }
- break;
+ case TIM_CHANNEL_2: {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ /* Configure the TIM Channel 2 in Output Compare */
+ TIM_OC2_SetConfig(htim->Instance, sConfig);
+ } break;
- case TIM_CHANNEL_3:
- {
- assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
- /* Configure the TIM Channel 3 in Output Compare */
- TIM_OC3_SetConfig(htim->Instance, sConfig);
- }
- break;
+ case TIM_CHANNEL_3: {
+ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
+ /* Configure the TIM Channel 3 in Output Compare */
+ TIM_OC3_SetConfig(htim->Instance, sConfig);
+ } break;
- case TIM_CHANNEL_4:
- {
- assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
- /* Configure the TIM Channel 4 in Output Compare */
- TIM_OC4_SetConfig(htim->Instance, sConfig);
- }
- break;
+ case TIM_CHANNEL_4: {
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+ /* Configure the TIM Channel 4 in Output Compare */
+ TIM_OC4_SetConfig(htim->Instance, sConfig);
+ } break;
- default:
+ default:
break;
}
htim->State = HAL_TIM_STATE_READY;
@@ -3011,20 +2716,19 @@ HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitT
}
/**
- * @brief Initializes the TIM Input Capture Channels according to the specified
- * parameters in the TIM_IC_InitTypeDef.
- * @param htim : TIM IC handle
- * @param sConfig : TIM Input Capture configuration structure
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel)
-{
+ * @brief Initializes the TIM Input Capture Channels according to the specified
+ * parameters in the TIM_IC_InitTypeDef.
+ * @param htim : TIM IC handle
+ * @param sConfig : TIM Input Capture configuration structure
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef *sConfig, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
assert_param(IS_TIM_IC_POLARITY(sConfig->ICPolarity));
@@ -3036,61 +2740,42 @@ HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitT
htim->State = HAL_TIM_STATE_BUSY;
- if (Channel == TIM_CHANNEL_1)
- {
+ if (Channel == TIM_CHANNEL_1) {
/* TI1 Configuration */
- TIM_TI1_SetConfig(htim->Instance,
- sConfig->ICPolarity,
- sConfig->ICSelection,
- sConfig->ICFilter);
+ TIM_TI1_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter);
/* Reset the IC1PSC Bits */
htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC;
/* Set the IC1PSC value */
htim->Instance->CCMR1 |= sConfig->ICPrescaler;
- }
- else if (Channel == TIM_CHANNEL_2)
- {
+ } else if (Channel == TIM_CHANNEL_2) {
/* TI2 Configuration */
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- TIM_TI2_SetConfig(htim->Instance,
- sConfig->ICPolarity,
- sConfig->ICSelection,
- sConfig->ICFilter);
+ TIM_TI2_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter);
/* Reset the IC2PSC Bits */
htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC;
/* Set the IC2PSC value */
htim->Instance->CCMR1 |= (sConfig->ICPrescaler << 8U);
- }
- else if (Channel == TIM_CHANNEL_3)
- {
+ } else if (Channel == TIM_CHANNEL_3) {
/* TI3 Configuration */
assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
- TIM_TI3_SetConfig(htim->Instance,
- sConfig->ICPolarity,
- sConfig->ICSelection,
- sConfig->ICFilter);
+ TIM_TI3_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter);
/* Reset the IC3PSC Bits */
htim->Instance->CCMR2 &= ~TIM_CCMR2_IC3PSC;
/* Set the IC3PSC value */
htim->Instance->CCMR2 |= sConfig->ICPrescaler;
- }
- else
- {
+ } else {
/* TI4 Configuration */
assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
- TIM_TI4_SetConfig(htim->Instance,
- sConfig->ICPolarity,
- sConfig->ICSelection,
- sConfig->ICFilter);
+ TIM_TI4_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter);
/* Reset the IC4PSC Bits */
htim->Instance->CCMR2 &= ~TIM_CCMR2_IC4PSC;
@@ -3107,20 +2792,19 @@ HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitT
}
/**
- * @brief Initializes the TIM PWM channels according to the specified
- * parameters in the TIM_OC_InitTypeDef.
- * @param htim : TIM handle
- * @param sConfig : TIM PWM configuration structure
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @arg TIM_CHANNEL_4: TIM Channel 4 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel)
-{
+ * @brief Initializes the TIM PWM channels according to the specified
+ * parameters in the TIM_OC_InitTypeDef.
+ * @param htim : TIM handle
+ * @param sConfig : TIM PWM configuration structure
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4: TIM Channel 4 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef *sConfig, uint32_t Channel) {
__HAL_LOCK(htim);
/* Check the parameters */
@@ -3131,69 +2815,60 @@ HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_Init
htim->State = HAL_TIM_STATE_BUSY;
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
- /* Configure the Channel 1 in PWM mode */
- TIM_OC1_SetConfig(htim->Instance, sConfig);
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ /* Configure the Channel 1 in PWM mode */
+ TIM_OC1_SetConfig(htim->Instance, sConfig);
- /* Set the Preload enable bit for channel1 */
- htim->Instance->CCMR1 |= TIM_CCMR1_OC1PE;
+ /* Set the Preload enable bit for channel1 */
+ htim->Instance->CCMR1 |= TIM_CCMR1_OC1PE;
- /* Configure the Output Fast mode */
- htim->Instance->CCMR1 &= ~TIM_CCMR1_OC1FE;
- htim->Instance->CCMR1 |= sConfig->OCFastMode;
- }
- break;
+ /* Configure the Output Fast mode */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC1FE;
+ htim->Instance->CCMR1 |= sConfig->OCFastMode;
+ } break;
- case TIM_CHANNEL_2:
- {
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- /* Configure the Channel 2 in PWM mode */
- TIM_OC2_SetConfig(htim->Instance, sConfig);
+ case TIM_CHANNEL_2: {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ /* Configure the Channel 2 in PWM mode */
+ TIM_OC2_SetConfig(htim->Instance, sConfig);
- /* Set the Preload enable bit for channel2 */
- htim->Instance->CCMR1 |= TIM_CCMR1_OC2PE;
+ /* Set the Preload enable bit for channel2 */
+ htim->Instance->CCMR1 |= TIM_CCMR1_OC2PE;
- /* Configure the Output Fast mode */
- htim->Instance->CCMR1 &= ~TIM_CCMR1_OC2FE;
- htim->Instance->CCMR1 |= sConfig->OCFastMode << 8;
- }
- break;
+ /* Configure the Output Fast mode */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC2FE;
+ htim->Instance->CCMR1 |= sConfig->OCFastMode << 8;
+ } break;
- case TIM_CHANNEL_3:
- {
- assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
- /* Configure the Channel 3 in PWM mode */
- TIM_OC3_SetConfig(htim->Instance, sConfig);
+ case TIM_CHANNEL_3: {
+ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
+ /* Configure the Channel 3 in PWM mode */
+ TIM_OC3_SetConfig(htim->Instance, sConfig);
- /* Set the Preload enable bit for channel3 */
- htim->Instance->CCMR2 |= TIM_CCMR2_OC3PE;
+ /* Set the Preload enable bit for channel3 */
+ htim->Instance->CCMR2 |= TIM_CCMR2_OC3PE;
- /* Configure the Output Fast mode */
- htim->Instance->CCMR2 &= ~TIM_CCMR2_OC3FE;
- htim->Instance->CCMR2 |= sConfig->OCFastMode;
- }
- break;
+ /* Configure the Output Fast mode */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC3FE;
+ htim->Instance->CCMR2 |= sConfig->OCFastMode;
+ } break;
- case TIM_CHANNEL_4:
- {
- assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
- /* Configure the Channel 4 in PWM mode */
- TIM_OC4_SetConfig(htim->Instance, sConfig);
+ case TIM_CHANNEL_4: {
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+ /* Configure the Channel 4 in PWM mode */
+ TIM_OC4_SetConfig(htim->Instance, sConfig);
- /* Set the Preload enable bit for channel4 */
- htim->Instance->CCMR2 |= TIM_CCMR2_OC4PE;
+ /* Set the Preload enable bit for channel4 */
+ htim->Instance->CCMR2 |= TIM_CCMR2_OC4PE;
- /* Configure the Output Fast mode */
- htim->Instance->CCMR2 &= ~TIM_CCMR2_OC4FE;
- htim->Instance->CCMR2 |= sConfig->OCFastMode << 8;
- }
- break;
+ /* Configure the Output Fast mode */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC4FE;
+ htim->Instance->CCMR2 |= sConfig->OCFastMode << 8;
+ } break;
- default:
+ default:
break;
}
@@ -3205,331 +2880,276 @@ HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_Init
}
/**
- * @brief Initializes the TIM One Pulse Channels according to the specified
- * parameters in the TIM_OnePulse_InitTypeDef.
- * @param htim : TIM One Pulse handle
- * @param sConfig : TIM One Pulse configuration structure
- * @param OutputChannel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @param InputChannel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel)
-{
+ * @brief Initializes the TIM One Pulse Channels according to the specified
+ * parameters in the TIM_OnePulse_InitTypeDef.
+ * @param htim : TIM One Pulse handle
+ * @param sConfig : TIM One Pulse configuration structure
+ * @param OutputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @param InputChannel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef *sConfig, uint32_t OutputChannel, uint32_t InputChannel) {
TIM_OC_InitTypeDef temp1;
/* Check the parameters */
assert_param(IS_TIM_OPM_CHANNELS(OutputChannel));
assert_param(IS_TIM_OPM_CHANNELS(InputChannel));
- if(OutputChannel != InputChannel)
- {
- __HAL_LOCK(htim);
+ if (OutputChannel != InputChannel) {
+ __HAL_LOCK(htim);
- htim->State = HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
- /* Extract the Ouput compare configuration from sConfig structure */
- temp1.OCMode = sConfig->OCMode;
- temp1.Pulse = sConfig->Pulse;
- temp1.OCPolarity = sConfig->OCPolarity;
- temp1.OCNPolarity = sConfig->OCNPolarity;
- temp1.OCIdleState = sConfig->OCIdleState;
- temp1.OCNIdleState = sConfig->OCNIdleState;
+ /* Extract the Ouput compare configuration from sConfig structure */
+ temp1.OCMode = sConfig->OCMode;
+ temp1.Pulse = sConfig->Pulse;
+ temp1.OCPolarity = sConfig->OCPolarity;
+ temp1.OCNPolarity = sConfig->OCNPolarity;
+ temp1.OCIdleState = sConfig->OCIdleState;
+ temp1.OCNIdleState = sConfig->OCNIdleState;
- switch (OutputChannel)
- {
- case TIM_CHANNEL_1:
- {
- assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ switch (OutputChannel) {
+ case TIM_CHANNEL_1: {
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
TIM_OC1_SetConfig(htim->Instance, &temp1);
- }
- break;
- case TIM_CHANNEL_2:
- {
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ } break;
+ case TIM_CHANNEL_2: {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
TIM_OC2_SetConfig(htim->Instance, &temp1);
- }
- break;
+ } break;
default:
- break;
- }
- switch (InputChannel)
- {
- case TIM_CHANNEL_1:
- {
+ break;
+ }
+ switch (InputChannel) {
+ case TIM_CHANNEL_1: {
assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
- TIM_TI1_SetConfig(htim->Instance, sConfig->ICPolarity,
- sConfig->ICSelection, sConfig->ICFilter);
+ TIM_TI1_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter);
/* Reset the IC1PSC Bits */
- htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC;
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC;
/* Select the Trigger source */
- htim->Instance->SMCR &= ~TIM_SMCR_TS;
+ htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= TIM_TS_TI1FP1;
/* Select the Slave Mode */
- htim->Instance->SMCR &= ~TIM_SMCR_SMS;
+ htim->Instance->SMCR &= ~TIM_SMCR_SMS;
htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER;
- }
- break;
- case TIM_CHANNEL_2:
- {
+ } break;
+ case TIM_CHANNEL_2: {
assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- TIM_TI2_SetConfig(htim->Instance, sConfig->ICPolarity,
- sConfig->ICSelection, sConfig->ICFilter);
+ TIM_TI2_SetConfig(htim->Instance, sConfig->ICPolarity, sConfig->ICSelection, sConfig->ICFilter);
/* Reset the IC2PSC Bits */
- htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC;
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC;
/* Select the Trigger source */
- htim->Instance->SMCR &= ~TIM_SMCR_TS;
+ htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= TIM_TS_TI2FP2;
/* Select the Slave Mode */
- htim->Instance->SMCR &= ~TIM_SMCR_SMS;
+ htim->Instance->SMCR &= ~TIM_SMCR_SMS;
htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER;
- }
- break;
+ } break;
default:
- break;
- }
+ break;
+ }
- htim->State = HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
- __HAL_UNLOCK(htim);
+ __HAL_UNLOCK(htim);
- return HAL_OK;
-}
- else
- {
+ return HAL_OK;
+ } else {
return HAL_ERROR;
}
}
/**
- * @brief Configure the DMA Burst to transfer Data from the memory to the TIM peripheral
- * @param htim : TIM handle
- * @param BurstBaseAddress : TIM Base address from where the DMA will start the Data write
- * This parameter can be one of the following values:
- * @arg TIM_DMABASE_CR1
- * @arg TIM_DMABASE_CR2
- * @arg TIM_DMABASE_SMCR
- * @arg TIM_DMABASE_DIER
- * @arg TIM_DMABASE_SR
- * @arg TIM_DMABASE_EGR
- * @arg TIM_DMABASE_CCMR1
- * @arg TIM_DMABASE_CCMR2
- * @arg TIM_DMABASE_CCER
- * @arg TIM_DMABASE_CNT
- * @arg TIM_DMABASE_PSC
- * @arg TIM_DMABASE_ARR
- * @arg TIM_DMABASE_RCR
- * @arg TIM_DMABASE_CCR1
- * @arg TIM_DMABASE_CCR2
- * @arg TIM_DMABASE_CCR3
- * @arg TIM_DMABASE_CCR4
- * @arg TIM_DMABASE_BDTR
- * @arg TIM_DMABASE_DCR
- * @param BurstRequestSrc : TIM DMA Request sources
- * This parameter can be one of the following values:
- * @arg TIM_DMA_UPDATE: TIM update Interrupt source
- * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source
- * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source
- * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source
- * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source
- * @arg TIM_DMA_COM: TIM Commutation DMA source
- * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source
- * @param BurstBuffer : The Buffer address.
- * @param BurstLength : DMA Burst length. This parameter can be one value
- * between: TIM_DMABURSTLENGTH_1TRANSFER and TIM_DMABURSTLENGTH_18TRANSFERS.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc,
- uint32_t* BurstBuffer, uint32_t BurstLength)
-{
+ * @brief Configure the DMA Burst to transfer Data from the memory to the TIM peripheral
+ * @param htim : TIM handle
+ * @param BurstBaseAddress : TIM Base address from where the DMA will start the Data write
+ * This parameter can be one of the following values:
+ * @arg TIM_DMABASE_CR1
+ * @arg TIM_DMABASE_CR2
+ * @arg TIM_DMABASE_SMCR
+ * @arg TIM_DMABASE_DIER
+ * @arg TIM_DMABASE_SR
+ * @arg TIM_DMABASE_EGR
+ * @arg TIM_DMABASE_CCMR1
+ * @arg TIM_DMABASE_CCMR2
+ * @arg TIM_DMABASE_CCER
+ * @arg TIM_DMABASE_CNT
+ * @arg TIM_DMABASE_PSC
+ * @arg TIM_DMABASE_ARR
+ * @arg TIM_DMABASE_RCR
+ * @arg TIM_DMABASE_CCR1
+ * @arg TIM_DMABASE_CCR2
+ * @arg TIM_DMABASE_CCR3
+ * @arg TIM_DMABASE_CCR4
+ * @arg TIM_DMABASE_BDTR
+ * @arg TIM_DMABASE_DCR
+ * @param BurstRequestSrc : TIM DMA Request sources
+ * This parameter can be one of the following values:
+ * @arg TIM_DMA_UPDATE: TIM update Interrupt source
+ * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source
+ * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source
+ * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source
+ * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source
+ * @arg TIM_DMA_COM: TIM Commutation DMA source
+ * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source
+ * @param BurstBuffer : The Buffer address.
+ * @param BurstLength : DMA Burst length. This parameter can be one value
+ * between: TIM_DMABURSTLENGTH_1TRANSFER and TIM_DMABURSTLENGTH_18TRANSFERS.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength) {
/* Check the parameters */
assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance));
assert_param(IS_TIM_DMA_BASE(BurstBaseAddress));
assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
assert_param(IS_TIM_DMA_LENGTH(BurstLength));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if((BurstBuffer == 0U) && (BurstLength > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if ((BurstBuffer == 0U) && (BurstLength > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
- switch(BurstRequestSrc)
- {
- case TIM_DMA_UPDATE:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_CC1:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_CC2:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_CC3:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_CC4:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_COM:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_TRIGGER:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
- }
- break;
- default:
+ switch (BurstRequestSrc) {
+ case TIM_DMA_UPDATE: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_CC1: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_CC2: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_CC3: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_CC4: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMADelayPulseCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_COM: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_TRIGGER: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8U) + 1U);
+ } break;
+ default:
break;
}
- /* configure the DMA Burst Mode */
- htim->Instance->DCR = BurstBaseAddress | BurstLength;
+ /* configure the DMA Burst Mode */
+ htim->Instance->DCR = BurstBaseAddress | BurstLength;
- /* Enable the TIM DMA Request */
- __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc);
+ /* Enable the TIM DMA Request */
+ __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc);
- htim->State = HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
/* Return function status */
return HAL_OK;
}
/**
- * @brief Stops the TIM DMA Burst mode
- * @param htim : TIM handle
- * @param BurstRequestSrc : TIM DMA Request sources to disable
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc)
-{
+ * @brief Stops the TIM DMA Burst mode
+ * @param htim : TIM handle
+ * @param BurstRequestSrc : TIM DMA Request sources to disable
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc) {
/* Check the parameters */
assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
/* Abort the DMA transfer (at least disable the DMA channel) */
- switch(BurstRequestSrc)
- {
- case TIM_DMA_UPDATE:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_UPDATE]);
- }
- break;
- case TIM_DMA_CC1:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC1]);
- }
- break;
- case TIM_DMA_CC2:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC2]);
- }
- break;
- case TIM_DMA_CC3:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC3]);
- }
- break;
- case TIM_DMA_CC4:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC4]);
- }
- break;
- case TIM_DMA_COM:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_COMMUTATION]);
- }
- break;
- case TIM_DMA_TRIGGER:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_TRIGGER]);
- }
- break;
- default:
+ switch (BurstRequestSrc) {
+ case TIM_DMA_UPDATE: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_UPDATE]);
+ } break;
+ case TIM_DMA_CC1: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC1]);
+ } break;
+ case TIM_DMA_CC2: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC2]);
+ } break;
+ case TIM_DMA_CC3: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC3]);
+ } break;
+ case TIM_DMA_CC4: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC4]);
+ } break;
+ case TIM_DMA_COM: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_COMMUTATION]);
+ } break;
+ case TIM_DMA_TRIGGER: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_TRIGGER]);
+ } break;
+ default:
break;
}
@@ -3541,154 +3161,131 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t B
}
/**
- * @brief Configure the DMA Burst to transfer Data from the TIM peripheral to the memory
- * @param htim : TIM handle
- * @param BurstBaseAddress : TIM Base address from where the DMA will starts the Data read
- * This parameter can be one of the following values:
- * @arg TIM_DMABASE_CR1
- * @arg TIM_DMABASE_CR2
- * @arg TIM_DMABASE_SMCR
- * @arg TIM_DMABASE_DIER
- * @arg TIM_DMABASE_SR
- * @arg TIM_DMABASE_EGR
- * @arg TIM_DMABASE_CCMR1
- * @arg TIM_DMABASE_CCMR2
- * @arg TIM_DMABASE_CCER
- * @arg TIM_DMABASE_CNT
- * @arg TIM_DMABASE_PSC
- * @arg TIM_DMABASE_ARR
- * @arg TIM_DMABASE_RCR
- * @arg TIM_DMABASE_CCR1
- * @arg TIM_DMABASE_CCR2
- * @arg TIM_DMABASE_CCR3
- * @arg TIM_DMABASE_CCR4
- * @arg TIM_DMABASE_BDTR
- * @arg TIM_DMABASE_DCR
- * @param BurstRequestSrc : TIM DMA Request sources
- * This parameter can be one of the following values:
- * @arg TIM_DMA_UPDATE: TIM update Interrupt source
- * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source
- * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source
- * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source
- * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source
- * @arg TIM_DMA_COM: TIM Commutation DMA source
- * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source
- * @param BurstBuffer : The Buffer address.
- * @param BurstLength : DMA Burst length. This parameter can be one value
- * between: TIM_DMABURSTLENGTH_1TRANSFER and TIM_DMABURSTLENGTH_18TRANSFERS.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc,
- uint32_t *BurstBuffer, uint32_t BurstLength)
-{
+ * @brief Configure the DMA Burst to transfer Data from the TIM peripheral to the memory
+ * @param htim : TIM handle
+ * @param BurstBaseAddress : TIM Base address from where the DMA will starts the Data read
+ * This parameter can be one of the following values:
+ * @arg TIM_DMABASE_CR1
+ * @arg TIM_DMABASE_CR2
+ * @arg TIM_DMABASE_SMCR
+ * @arg TIM_DMABASE_DIER
+ * @arg TIM_DMABASE_SR
+ * @arg TIM_DMABASE_EGR
+ * @arg TIM_DMABASE_CCMR1
+ * @arg TIM_DMABASE_CCMR2
+ * @arg TIM_DMABASE_CCER
+ * @arg TIM_DMABASE_CNT
+ * @arg TIM_DMABASE_PSC
+ * @arg TIM_DMABASE_ARR
+ * @arg TIM_DMABASE_RCR
+ * @arg TIM_DMABASE_CCR1
+ * @arg TIM_DMABASE_CCR2
+ * @arg TIM_DMABASE_CCR3
+ * @arg TIM_DMABASE_CCR4
+ * @arg TIM_DMABASE_BDTR
+ * @arg TIM_DMABASE_DCR
+ * @param BurstRequestSrc : TIM DMA Request sources
+ * This parameter can be one of the following values:
+ * @arg TIM_DMA_UPDATE: TIM update Interrupt source
+ * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source
+ * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source
+ * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source
+ * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source
+ * @arg TIM_DMA_COM: TIM Commutation DMA source
+ * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source
+ * @param BurstBuffer : The Buffer address.
+ * @param BurstLength : DMA Burst length. This parameter can be one value
+ * between: TIM_DMABURSTLENGTH_1TRANSFER and TIM_DMABURSTLENGTH_18TRANSFERS.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, uint32_t *BurstBuffer, uint32_t BurstLength) {
/* Check the parameters */
assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance));
assert_param(IS_TIM_DMA_BASE(BurstBaseAddress));
assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
assert_param(IS_TIM_DMA_LENGTH(BurstLength));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if((BurstBuffer == 0U) && (BurstLength > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if ((BurstBuffer == 0U) && (BurstLength > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
- switch(BurstRequestSrc)
- {
- case TIM_DMA_UPDATE:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_CC1:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_CC2:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_CC3:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_CC4:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_COM:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
- }
- break;
- case TIM_DMA_TRIGGER:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt;
-
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError ;
-
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
- }
- break;
- default:
+ switch (BurstRequestSrc) {
+ case TIM_DMA_UPDATE: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_CC1: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_CC2: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_CC3: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_CC4: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = TIM_DMACaptureCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_COM: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = TIMEx_DMACommutationCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
+ } break;
+ case TIM_DMA_TRIGGER: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt;
+
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = TIM_DMAError;
+
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8U) + 1U);
+ } break;
+ default:
break;
}
@@ -3705,55 +3302,39 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t B
}
/**
- * @brief Stop the DMA burst reading
- * @param htim : TIM handle
- * @param BurstRequestSrc : TIM DMA Request sources to disable.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc)
-{
+ * @brief Stop the DMA burst reading
+ * @param htim : TIM handle
+ * @param BurstRequestSrc : TIM DMA Request sources to disable.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc) {
/* Check the parameters */
assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc));
/* Abort the DMA transfer (at least disable the DMA channel) */
- switch(BurstRequestSrc)
- {
- case TIM_DMA_UPDATE:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_UPDATE]);
- }
- break;
- case TIM_DMA_CC1:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC1]);
- }
- break;
- case TIM_DMA_CC2:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC2]);
- }
- break;
- case TIM_DMA_CC3:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC3]);
- }
- break;
- case TIM_DMA_CC4:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC4]);
- }
- break;
- case TIM_DMA_COM:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_COMMUTATION]);
- }
- break;
- case TIM_DMA_TRIGGER:
- {
- HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_TRIGGER]);
- }
- break;
- default:
+ switch (BurstRequestSrc) {
+ case TIM_DMA_UPDATE: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_UPDATE]);
+ } break;
+ case TIM_DMA_CC1: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC1]);
+ } break;
+ case TIM_DMA_CC2: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC2]);
+ } break;
+ case TIM_DMA_CC3: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC3]);
+ } break;
+ case TIM_DMA_CC4: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC4]);
+ } break;
+ case TIM_DMA_COM: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_COMMUTATION]);
+ } break;
+ case TIM_DMA_TRIGGER: {
+ HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_TRIGGER]);
+ } break;
+ default:
break;
}
@@ -3765,25 +3346,24 @@ HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t Bu
}
/**
- * @brief Generate a software event
- * @param htim : TIM handle
- * @param EventSource : specifies the event source.
- * This parameter can be one of the following values:
- * @arg TIM_EVENTSOURCE_UPDATE: Timer update Event source
- * @arg TIM_EVENTSOURCE_CC1: Timer Capture Compare 1 Event source
- * @arg TIM_EVENTSOURCE_CC2: Timer Capture Compare 2 Event source
- * @arg TIM_EVENTSOURCE_CC3: Timer Capture Compare 3 Event source
- * @arg TIM_EVENTSOURCE_CC4: Timer Capture Compare 4 Event source
- * @arg TIM_EVENTSOURCE_COM: Timer COM event source
- * @arg TIM_EVENTSOURCE_TRIGGER: Timer Trigger Event source
- * @arg TIM_EVENTSOURCE_BREAK: Timer Break event source
- * @note TIM6 and TIM7 can only generate an update event.
- * @note TIM_EVENTSOURCE_COM and TIM_EVENTSOURCE_BREAK are used only with TIM1, TIM15, TIM16 and TIM17.
- * @retval HAL status
- */
-
-HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource)
-{
+ * @brief Generate a software event
+ * @param htim : TIM handle
+ * @param EventSource : specifies the event source.
+ * This parameter can be one of the following values:
+ * @arg TIM_EVENTSOURCE_UPDATE: Timer update Event source
+ * @arg TIM_EVENTSOURCE_CC1: Timer Capture Compare 1 Event source
+ * @arg TIM_EVENTSOURCE_CC2: Timer Capture Compare 2 Event source
+ * @arg TIM_EVENTSOURCE_CC3: Timer Capture Compare 3 Event source
+ * @arg TIM_EVENTSOURCE_CC4: Timer Capture Compare 4 Event source
+ * @arg TIM_EVENTSOURCE_COM: Timer COM event source
+ * @arg TIM_EVENTSOURCE_TRIGGER: Timer Trigger Event source
+ * @arg TIM_EVENTSOURCE_BREAK: Timer Break event source
+ * @note TIM6 and TIM7 can only generate an update event.
+ * @note TIM_EVENTSOURCE_COM and TIM_EVENTSOURCE_BREAK are used only with TIM1, TIM15, TIM16 and TIM17.
+ * @retval HAL status
+ */
+
+HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
assert_param(IS_TIM_EVENT_SOURCE(EventSource));
@@ -3807,20 +3387,19 @@ HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventS
}
/**
- * @brief Configures the OCRef clear feature
- * @param htim : TIM handle
- * @param sClearInputConfig : pointer to a TIM_ClearInputConfigTypeDef structure that
- * contains the OCREF clear feature and parameters for the TIM peripheral.
- * @param Channel : specifies the TIM Channel
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1
- * @arg TIM_CHANNEL_2: TIM Channel 2
- * @arg TIM_CHANNEL_3: TIM Channel 3
- * @arg TIM_CHANNEL_4: TIM Channel 4
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel)
-{
+ * @brief Configures the OCRef clear feature
+ * @param htim : TIM handle
+ * @param sClearInputConfig : pointer to a TIM_ClearInputConfigTypeDef structure that
+ * contains the OCREF clear feature and parameters for the TIM peripheral.
+ * @param Channel : specifies the TIM Channel
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1
+ * @arg TIM_CHANNEL_2: TIM Channel 2
+ * @arg TIM_CHANNEL_3: TIM Channel 3
+ * @arg TIM_CHANNEL_4: TIM Channel 4
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef *sClearInputConfig, uint32_t Channel) {
uint32_t tmpsmcr = 0U;
/* Check the parameters */
@@ -3835,94 +3414,65 @@ HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInp
htim->State = HAL_TIM_STATE_BUSY;
- switch (sClearInputConfig->ClearInputSource)
- {
- case TIM_CLEARINPUTSOURCE_NONE:
- {
+ switch (sClearInputConfig->ClearInputSource) {
+ case TIM_CLEARINPUTSOURCE_NONE: {
- /* Clear the ETR Bits */
- tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP);
+ /* Clear the ETR Bits */
+ tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP);
- /* Set TIMx_SMCR */
- htim->Instance->SMCR = tmpsmcr;
- }
- break;
+ /* Set TIMx_SMCR */
+ htim->Instance->SMCR = tmpsmcr;
+ } break;
- case TIM_CLEARINPUTSOURCE_ETR:
- {
- TIM_ETR_SetConfig(htim->Instance,
- sClearInputConfig->ClearInputPrescaler,
- sClearInputConfig->ClearInputPolarity,
- sClearInputConfig->ClearInputFilter);
+ case TIM_CLEARINPUTSOURCE_ETR: {
+ TIM_ETR_SetConfig(htim->Instance, sClearInputConfig->ClearInputPrescaler, sClearInputConfig->ClearInputPolarity, sClearInputConfig->ClearInputFilter);
- }
- break;
- default:
+ } break;
+ default:
break;
}
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- if(sClearInputConfig->ClearInputState != RESET)
- {
- /* Enable the Ocref clear feature for Channel 1 */
- htim->Instance->CCMR1 |= TIM_CCMR1_OC1CE;
- }
- else
- {
- /* Disable the Ocref clear feature for Channel 1 */
- htim->Instance->CCMR1 &= ~TIM_CCMR1_OC1CE;
- }
- }
- break;
- case TIM_CHANNEL_2:
- {
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- if(sClearInputConfig->ClearInputState != RESET)
- {
- /* Enable the Ocref clear feature for Channel 2 */
- htim->Instance->CCMR1 |= TIM_CCMR1_OC2CE;
- }
- else
- {
- /* Disable the Ocref clear feature for Channel 2 */
- htim->Instance->CCMR1 &= ~TIM_CCMR1_OC2CE;
- }
- }
- break;
- case TIM_CHANNEL_3:
- {
- assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
- if(sClearInputConfig->ClearInputState != RESET)
- {
- /* Enable the Ocref clear feature for Channel 3 */
- htim->Instance->CCMR2 |= TIM_CCMR2_OC3CE;
- }
- else
- {
- /* Disable the Ocref clear feature for Channel 3 */
- htim->Instance->CCMR2 &= ~TIM_CCMR2_OC3CE;
- }
- }
- break;
- case TIM_CHANNEL_4:
- {
- assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
- if(sClearInputConfig->ClearInputState != RESET)
- {
- /* Enable the Ocref clear feature for Channel 4 */
- htim->Instance->CCMR2 |= TIM_CCMR2_OC4CE;
- }
- else
- {
- /* Disable the Ocref clear feature for Channel 4 */
- htim->Instance->CCMR2 &= ~TIM_CCMR2_OC4CE;
- }
- }
- break;
- default:
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ if (sClearInputConfig->ClearInputState != RESET) {
+ /* Enable the Ocref clear feature for Channel 1 */
+ htim->Instance->CCMR1 |= TIM_CCMR1_OC1CE;
+ } else {
+ /* Disable the Ocref clear feature for Channel 1 */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC1CE;
+ }
+ } break;
+ case TIM_CHANNEL_2: {
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ if (sClearInputConfig->ClearInputState != RESET) {
+ /* Enable the Ocref clear feature for Channel 2 */
+ htim->Instance->CCMR1 |= TIM_CCMR1_OC2CE;
+ } else {
+ /* Disable the Ocref clear feature for Channel 2 */
+ htim->Instance->CCMR1 &= ~TIM_CCMR1_OC2CE;
+ }
+ } break;
+ case TIM_CHANNEL_3: {
+ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
+ if (sClearInputConfig->ClearInputState != RESET) {
+ /* Enable the Ocref clear feature for Channel 3 */
+ htim->Instance->CCMR2 |= TIM_CCMR2_OC3CE;
+ } else {
+ /* Disable the Ocref clear feature for Channel 3 */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC3CE;
+ }
+ } break;
+ case TIM_CHANNEL_4: {
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+ if (sClearInputConfig->ClearInputState != RESET) {
+ /* Enable the Ocref clear feature for Channel 4 */
+ htim->Instance->CCMR2 |= TIM_CCMR2_OC4CE;
+ } else {
+ /* Disable the Ocref clear feature for Channel 4 */
+ htim->Instance->CCMR2 &= ~TIM_CCMR2_OC4CE;
+ }
+ } break;
+ default:
break;
}
@@ -3934,14 +3484,13 @@ HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInp
}
/**
- * @brief Configures the clock source to be used
- * @param htim : TIM handle
- * @param sClockSourceConfig : pointer to a TIM_ClockConfigTypeDef structure that
- * contains the clock source information for the TIM peripheral.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig)
-{
+ * @brief Configures the clock source to be used
+ * @param htim : TIM handle
+ * @param sClockSourceConfig : pointer to a TIM_ClockConfigTypeDef structure that
+ * contains the clock source information for the TIM peripheral.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef *sClockSourceConfig) {
uint32_t tmpsmcr = 0U;
/* Process Locked */
@@ -3958,139 +3507,136 @@ HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockCo
tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP);
htim->Instance->SMCR = tmpsmcr;
- switch (sClockSourceConfig->ClockSource)
- {
- case TIM_CLOCKSOURCE_INTERNAL:
- {
- assert_param(IS_TIM_INSTANCE(htim->Instance));
- /* Disable slave mode to clock the prescaler directly with the internal clock */
- htim->Instance->SMCR &= ~TIM_SMCR_SMS;
- }
- break;
-
-// case TIM_CLOCKSOURCE_ETRMODE1:
-// {
-// /* Check whether or not the timer instance supports external trigger input mode 1 (ETRF)*/
-// assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance));
-//
-// /* Check ETR input conditioning related parameters */
-// assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler));
-// assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
-// assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
-//
-// /* Configure the ETR Clock source */
-// TIM_ETR_SetConfig(htim->Instance,
-// sClockSourceConfig->ClockPrescaler,
-// sClockSourceConfig->ClockPolarity,
-// sClockSourceConfig->ClockFilter);
-// /* Get the TIMx SMCR register value */
-// tmpsmcr = htim->Instance->SMCR;
-// /* Reset the SMS and TS Bits */
-// tmpsmcr &= ~(TIM_SMCR_SMS | TIM_SMCR_TS);
-// /* Select the External clock mode1 and the ETRF trigger */
-// tmpsmcr |= (TIM_SLAVEMODE_EXTERNAL1 | TIM_CLOCKSOURCE_ETRMODE1);
-// /* Write to TIMx SMCR */
-// htim->Instance->SMCR = tmpsmcr;
-// }
-// break;
-//
-// case TIM_CLOCKSOURCE_ETRMODE2:
-// {
-// /* Check whether or not the timer instance supports external trigger input mode 2 (ETRF)*/
-// assert_param(IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(htim->Instance));
-//
-// /* Check ETR input conditioning related parameters */
-// assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler));
-// assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
-// assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
-//
-// /* Configure the ETR Clock source */
-// TIM_ETR_SetConfig(htim->Instance,
-// sClockSourceConfig->ClockPrescaler,
-// sClockSourceConfig->ClockPolarity,
-// sClockSourceConfig->ClockFilter);
-// /* Enable the External clock mode2 */
-// htim->Instance->SMCR |= TIM_SMCR_ECE;
-// }
-// break;
-//
-// case TIM_CLOCKSOURCE_TI1:
-// {
-// /* Check whether or not the timer instance supports external clock mode 1 */
-// assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance));
-//
-// /* Check TI1 input conditioning related parameters */
-// assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
-// assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
-//
-// TIM_TI1_ConfigInputStage(htim->Instance,
-// sClockSourceConfig->ClockPolarity,
-// sClockSourceConfig->ClockFilter);
-// TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1);
-// }
-// break;
-// case TIM_CLOCKSOURCE_TI2:
-// {
-// /* Check whether or not the timer instance supports external clock mode 1 (ETRF)*/
-// assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance));
-//
-// /* Check TI2 input conditioning related parameters */
-// assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
-// assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
-//
-// TIM_TI2_ConfigInputStage(htim->Instance,
-// sClockSourceConfig->ClockPolarity,
-// sClockSourceConfig->ClockFilter);
-// TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI2);
-// }
-// break;
-// case TIM_CLOCKSOURCE_TI1ED:
-// {
-// /* Check whether or not the timer instance supports external clock mode 1 */
-// assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance));
-//
-// /* Check TI1 input conditioning related parameters */
-// assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
-// assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
-//
-// TIM_TI1_ConfigInputStage(htim->Instance,
-// sClockSourceConfig->ClockPolarity,
-// sClockSourceConfig->ClockFilter);
-// TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1ED);
-// }
-// break;
-// case TIM_CLOCKSOURCE_ITR0:
-// {
-// /* Check whether or not the timer instance supports external clock mode 1 */
-// assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance));
-//
-// TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR0);
-// }
-// break;
-// case TIM_CLOCKSOURCE_ITR1:
-// {
-// /* Check whether or not the timer instance supports external clock mode 1 */
-// assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance));
-//
-// TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR1);
-// }
-// break;
-// case TIM_CLOCKSOURCE_ITR2:
-// {
-// /* Check whether or not the timer instance supports external clock mode 1 */
-// assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance));
-//
-// TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR2);
-// }
-// break;
-// case TIM_CLOCKSOURCE_ITR3:
-// {
-// /* Check whether or not the timer instance supports external clock mode 1 */
-// assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance));
-//
-// TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR3);
-// }
-// break;
+ switch (sClockSourceConfig->ClockSource) {
+ case TIM_CLOCKSOURCE_INTERNAL: {
+ assert_param(IS_TIM_INSTANCE(htim->Instance));
+ /* Disable slave mode to clock the prescaler directly with the internal clock */
+ htim->Instance->SMCR &= ~TIM_SMCR_SMS;
+ } break;
+
+ // case TIM_CLOCKSOURCE_ETRMODE1:
+ // {
+ // /* Check whether or not the timer instance supports external trigger input mode 1 (ETRF)*/
+ // assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance));
+ //
+ // /* Check ETR input conditioning related parameters */
+ // assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler));
+ // assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
+ // assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
+ //
+ // /* Configure the ETR Clock source */
+ // TIM_ETR_SetConfig(htim->Instance,
+ // sClockSourceConfig->ClockPrescaler,
+ // sClockSourceConfig->ClockPolarity,
+ // sClockSourceConfig->ClockFilter);
+ // /* Get the TIMx SMCR register value */
+ // tmpsmcr = htim->Instance->SMCR;
+ // /* Reset the SMS and TS Bits */
+ // tmpsmcr &= ~(TIM_SMCR_SMS | TIM_SMCR_TS);
+ // /* Select the External clock mode1 and the ETRF trigger */
+ // tmpsmcr |= (TIM_SLAVEMODE_EXTERNAL1 | TIM_CLOCKSOURCE_ETRMODE1);
+ // /* Write to TIMx SMCR */
+ // htim->Instance->SMCR = tmpsmcr;
+ // }
+ // break;
+ //
+ // case TIM_CLOCKSOURCE_ETRMODE2:
+ // {
+ // /* Check whether or not the timer instance supports external trigger input mode 2 (ETRF)*/
+ // assert_param(IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(htim->Instance));
+ //
+ // /* Check ETR input conditioning related parameters */
+ // assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler));
+ // assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
+ // assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
+ //
+ // /* Configure the ETR Clock source */
+ // TIM_ETR_SetConfig(htim->Instance,
+ // sClockSourceConfig->ClockPrescaler,
+ // sClockSourceConfig->ClockPolarity,
+ // sClockSourceConfig->ClockFilter);
+ // /* Enable the External clock mode2 */
+ // htim->Instance->SMCR |= TIM_SMCR_ECE;
+ // }
+ // break;
+ //
+ // case TIM_CLOCKSOURCE_TI1:
+ // {
+ // /* Check whether or not the timer instance supports external clock mode 1 */
+ // assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance));
+ //
+ // /* Check TI1 input conditioning related parameters */
+ // assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
+ // assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
+ //
+ // TIM_TI1_ConfigInputStage(htim->Instance,
+ // sClockSourceConfig->ClockPolarity,
+ // sClockSourceConfig->ClockFilter);
+ // TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1);
+ // }
+ // break;
+ // case TIM_CLOCKSOURCE_TI2:
+ // {
+ // /* Check whether or not the timer instance supports external clock mode 1 (ETRF)*/
+ // assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance));
+ //
+ // /* Check TI2 input conditioning related parameters */
+ // assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
+ // assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
+ //
+ // TIM_TI2_ConfigInputStage(htim->Instance,
+ // sClockSourceConfig->ClockPolarity,
+ // sClockSourceConfig->ClockFilter);
+ // TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI2);
+ // }
+ // break;
+ // case TIM_CLOCKSOURCE_TI1ED:
+ // {
+ // /* Check whether or not the timer instance supports external clock mode 1 */
+ // assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance));
+ //
+ // /* Check TI1 input conditioning related parameters */
+ // assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity));
+ // assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter));
+ //
+ // TIM_TI1_ConfigInputStage(htim->Instance,
+ // sClockSourceConfig->ClockPolarity,
+ // sClockSourceConfig->ClockFilter);
+ // TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1ED);
+ // }
+ // break;
+ // case TIM_CLOCKSOURCE_ITR0:
+ // {
+ // /* Check whether or not the timer instance supports external clock mode 1 */
+ // assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance));
+ //
+ // TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR0);
+ // }
+ // break;
+ // case TIM_CLOCKSOURCE_ITR1:
+ // {
+ // /* Check whether or not the timer instance supports external clock mode 1 */
+ // assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance));
+ //
+ // TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR1);
+ // }
+ // break;
+ // case TIM_CLOCKSOURCE_ITR2:
+ // {
+ // /* Check whether or not the timer instance supports external clock mode 1 */
+ // assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance));
+ //
+ // TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR2);
+ // }
+ // break;
+ // case TIM_CLOCKSOURCE_ITR3:
+ // {
+ // /* Check whether or not the timer instance supports external clock mode 1 */
+ // assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance));
+ //
+ // TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR3);
+ // }
+ // break;
default:
break;
@@ -4103,19 +3649,18 @@ HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockCo
}
/**
- * @brief Selects the signal connected to the TI1 input: direct from CH1_input
- * or a XOR combination between CH1_input, CH2_input & CH3_input
- * @param htim : TIM handle.
- * @param TI1_Selection : Indicate whether or not channel 1 is connected to the
- * output of a XOR gate.
- * This parameter can be one of the following values:
- * @arg TIM_TI1SELECTION_CH1: The TIMx_CH1 pin is connected to TI1 input
- * @arg TIM_TI1SELECTION_XORCOMBINATION: The TIMx_CH1, CH2 and CH3
- * pins are connected to the TI1 input (XOR combination)
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection)
-{
+ * @brief Selects the signal connected to the TI1 input: direct from CH1_input
+ * or a XOR combination between CH1_input, CH2_input & CH3_input
+ * @param htim : TIM handle.
+ * @param TI1_Selection : Indicate whether or not channel 1 is connected to the
+ * output of a XOR gate.
+ * This parameter can be one of the following values:
+ * @arg TIM_TI1SELECTION_CH1: The TIMx_CH1 pin is connected to TI1 input
+ * @arg TIM_TI1SELECTION_XORCOMBINATION: The TIMx_CH1, CH2 and CH3
+ * pins are connected to the TI1 input (XOR combination)
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection) {
uint32_t tmpcr2 = 0U;
/* Check the parameters */
@@ -4138,16 +3683,15 @@ HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_S
}
/**
- * @brief Configures the TIM in Slave mode
- * @param htim : TIM handle.
- * @param sSlaveConfig : pointer to a TIM_SlaveConfigTypeDef structure that
- * contains the selected trigger (internal trigger input, filtered
- * timer input or external trigger input) and the ) and the Slave
- * mode (Disable, Reset, Gated, Trigger, External clock mode 1).
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig)
-{
+ * @brief Configures the TIM in Slave mode
+ * @param htim : TIM handle.
+ * @param sSlaveConfig : pointer to a TIM_SlaveConfigTypeDef structure that
+ * contains the selected trigger (internal trigger input, filtered
+ * timer input or external trigger input) and the ) and the Slave
+ * mode (Disable, Reset, Gated, Trigger, External clock mode 1).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef *sSlaveConfig) {
/* Check the parameters */
assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance));
assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode));
@@ -4170,21 +3714,19 @@ HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TI
__HAL_UNLOCK(htim);
return HAL_OK;
- }
+}
/**
- * @brief Configures the TIM in Slave mode in interrupt mode
- * @param htim: TIM handle.
- * @param sSlaveConfig: pointer to a TIM_SlaveConfigTypeDef structure that
- * contains the selected trigger (internal trigger input, filtered
- * timer input or external trigger input) and the ) and the Slave
- * mode (Disable, Reset, Gated, Trigger, External clock mode 1).
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization_IT(TIM_HandleTypeDef *htim,
- TIM_SlaveConfigTypeDef * sSlaveConfig)
- {
- /* Check the parameters */
+ * @brief Configures the TIM in Slave mode in interrupt mode
+ * @param htim: TIM handle.
+ * @param sSlaveConfig: pointer to a TIM_SlaveConfigTypeDef structure that
+ * contains the selected trigger (internal trigger input, filtered
+ * timer input or external trigger input) and the ) and the Slave
+ * mode (Disable, Reset, Gated, Trigger, External clock mode 1).
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization_IT(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef *sSlaveConfig) {
+ /* Check the parameters */
assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance));
assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode));
assert_param(IS_TIM_TRIGGER_SELECTION(sSlaveConfig->InputTrigger));
@@ -4209,66 +3751,60 @@ HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization_IT(TIM_HandleTypeDef *htim,
}
/**
- * @brief Read the captured value from Capture Compare unit
- * @param htim : TIM handle.
- * @param Channel : TIM Channels to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1 : TIM Channel 1 selected
- * @arg TIM_CHANNEL_2 : TIM Channel 2 selected
- * @arg TIM_CHANNEL_3 : TIM Channel 3 selected
- * @arg TIM_CHANNEL_4 : TIM Channel 4 selected
- * @retval Captured value
- */
-uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Read the captured value from Capture Compare unit
+ * @param htim : TIM handle.
+ * @param Channel : TIM Channels to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1 : TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2 : TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3 : TIM Channel 3 selected
+ * @arg TIM_CHANNEL_4 : TIM Channel 4 selected
+ * @retval Captured value
+ */
+uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel) {
uint32_t tmpreg = 0U;
__HAL_LOCK(htim);
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Check the parameters */
- assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
- /* Return the capture 1 value */
- tmpreg = htim->Instance->CCR1;
+ /* Return the capture 1 value */
+ tmpreg = htim->Instance->CCR1;
- break;
- }
- case TIM_CHANNEL_2:
- {
- /* Check the parameters */
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ break;
+ }
+ case TIM_CHANNEL_2: {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- /* Return the capture 2 value */
- tmpreg = htim->Instance->CCR2;
+ /* Return the capture 2 value */
+ tmpreg = htim->Instance->CCR2;
- break;
- }
+ break;
+ }
- case TIM_CHANNEL_3:
- {
- /* Check the parameters */
- assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
+ case TIM_CHANNEL_3: {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC3_INSTANCE(htim->Instance));
- /* Return the capture 3 value */
- tmpreg = htim->Instance->CCR3;
+ /* Return the capture 3 value */
+ tmpreg = htim->Instance->CCR3;
- break;
- }
+ break;
+ }
- case TIM_CHANNEL_4:
- {
- /* Check the parameters */
- assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
+ case TIM_CHANNEL_4: {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC4_INSTANCE(htim->Instance));
- /* Return the capture 4 value */
- tmpreg = htim->Instance->CCR4;
+ /* Return the capture 4 value */
+ tmpreg = htim->Instance->CCR4;
- break;
- }
+ break;
+ }
default:
break;
@@ -4279,13 +3815,13 @@ uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup TIM_Exported_Functions_Group9 TIM Callbacks functions
- * @brief TIM Callbacks functions
+ * @brief TIM Callbacks functions
*
-@verbatim
+@verbatim
==============================================================================
##### TIM Callbacks functions #####
==============================================================================
@@ -4302,26 +3838,23 @@ uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel)
*/
/**
- * @brief Period elapsed callback in non blocking mode
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
-{
+ * @brief Period elapsed callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
the __HAL_TIM_PeriodElapsedCallback could be implemented in the user file
*/
-
}
/**
- * @brief Output Compare callback in non blocking mode
- * @param htim : TIM OC handle
- * @retval None
- */
-__weak void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim)
-{
+ * @brief Output Compare callback in non blocking mode
+ * @param htim : TIM OC handle
+ * @retval None
+ */
+__weak void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -4329,12 +3862,11 @@ __weak void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim)
*/
}
/**
- * @brief Input Capture callback in non blocking mode
- * @param htim : TIM IC handle
- * @retval None
- */
-__weak void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
-{
+ * @brief Input Capture callback in non blocking mode
+ * @param htim : TIM IC handle
+ * @retval None
+ */
+__weak void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -4343,12 +3875,11 @@ __weak void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
}
/**
- * @brief PWM Pulse finished callback in non blocking mode
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
-{
+ * @brief PWM Pulse finished callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -4357,12 +3888,11 @@ __weak void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
}
/**
- * @brief Hall Trigger detection callback in non blocking mode
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim)
-{
+ * @brief Hall Trigger detection callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -4371,12 +3901,11 @@ __weak void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim)
}
/**
- * @brief Timer error callback in non blocking mode
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim)
-{
+ * @brief Timer error callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -4385,18 +3914,18 @@ __weak void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim)
}
/**
- * @}
- */
+ * @}
+ */
-/** @defgroup TIM_Exported_Functions_Group10 Peripheral State functions
- * @brief Peripheral State functions
+/** @defgroup TIM_Exported_Functions_Group10 Peripheral State functions
+ * @brief Peripheral State functions
*
-@verbatim
+@verbatim
==============================================================================
##### Peripheral State functions #####
==============================================================================
[..]
- This subsection permit to get in run-time the status of the peripheral
+ This subsection permit to get in run-time the status of the peripheral
and the data flow.
@endverbatim
@@ -4404,116 +3933,89 @@ __weak void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim)
*/
/**
- * @brief Return the TIM Base state
- * @param htim : TIM Base handle
- * @retval HAL state
- */
-HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim)
-{
- return htim->State;
-}
+ * @brief Return the TIM Base state
+ * @param htim : TIM Base handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim) { return htim->State; }
/**
- * @brief Return the TIM OC state
- * @param htim : TIM Ouput Compare handle
- * @retval HAL state
- */
-HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim)
-{
- return htim->State;
-}
+ * @brief Return the TIM OC state
+ * @param htim : TIM Ouput Compare handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim) { return htim->State; }
/**
- * @brief Return the TIM PWM state
- * @param htim : TIM handle
- * @retval HAL state
- */
-HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim)
-{
- return htim->State;
-}
+ * @brief Return the TIM PWM state
+ * @param htim : TIM handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim) { return htim->State; }
/**
- * @brief Return the TIM Input Capture state
- * @param htim : TIM IC handle
- * @retval HAL state
- */
-HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim)
-{
- return htim->State;
-}
+ * @brief Return the TIM Input Capture state
+ * @param htim : TIM IC handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim) { return htim->State; }
/**
- * @brief Return the TIM One Pulse Mode state
- * @param htim : TIM OPM handle
- * @retval HAL state
- */
-HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim)
-{
- return htim->State;
-}
+ * @brief Return the TIM One Pulse Mode state
+ * @param htim : TIM OPM handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim) { return htim->State; }
/**
- * @brief Return the TIM Encoder Mode state
- * @param htim : TIM Encoder handle
- * @retval HAL state
- */
-HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim)
-{
- return htim->State;
-}
+ * @brief Return the TIM Encoder Mode state
+ * @param htim : TIM Encoder handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim) { return htim->State; }
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/** @addtogroup TIM_Private_Functions
- * @{
- */
+ * @{
+ */
/**
- * @brief TIM DMA error callback
- * @param hdma : pointer to DMA handle.
- * @retval None
- */
-void TIM_DMAError(DMA_HandleTypeDef *hdma)
-{
- TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ * @brief TIM DMA error callback
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+void TIM_DMAError(DMA_HandleTypeDef *hdma) {
+ TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
HAL_TIM_ErrorCallback(htim);
}
/**
- * @brief TIM DMA Delay Pulse complete callback.
- * @param hdma : pointer to DMA handle.
- * @retval None
- */
-void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma)
-{
- TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ * @brief TIM DMA Delay Pulse complete callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma) {
+ TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
- if (hdma == htim->hdma[TIM_DMA_ID_CC1])
- {
+ if (hdma == htim->hdma[TIM_DMA_ID_CC1]) {
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
- }
- else if (hdma == htim->hdma[TIM_DMA_ID_CC2])
- {
+ } else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) {
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
- }
- else if (hdma == htim->hdma[TIM_DMA_ID_CC3])
- {
+ } else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) {
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
- }
- else if (hdma == htim->hdma[TIM_DMA_ID_CC4])
- {
+ } else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) {
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
}
@@ -4522,30 +4024,22 @@ void TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma)
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED;
}
/**
- * @brief TIM DMA Capture complete callback.
- * @param hdma : pointer to DMA handle.
- * @retval None
- */
-void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma)
-{
- TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ * @brief TIM DMA Capture complete callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma) {
+ TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
- if (hdma == htim->hdma[TIM_DMA_ID_CC1])
- {
+ if (hdma == htim->hdma[TIM_DMA_ID_CC1]) {
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1;
- }
- else if (hdma == htim->hdma[TIM_DMA_ID_CC2])
- {
+ } else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) {
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2;
- }
- else if (hdma == htim->hdma[TIM_DMA_ID_CC3])
- {
+ } else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) {
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3;
- }
- else if (hdma == htim->hdma[TIM_DMA_ID_CC4])
- {
+ } else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) {
htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4;
}
@@ -4555,54 +4049,49 @@ void TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma)
}
/**
- * @brief TIM DMA Period Elapse complete callback.
- * @param hdma : pointer to DMA handle.
- * @retval None
- */
-static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma)
-{
- TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ * @brief TIM DMA Period Elapse complete callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma) {
+ TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
HAL_TIM_PeriodElapsedCallback(htim);
}
/**
- * @brief TIM DMA Trigger callback.
- * @param hdma : pointer to DMA handle.
- * @retval None
- */
-static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma)
-{
- TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ * @brief TIM DMA Trigger callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma) {
+ TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
HAL_TIM_TriggerCallback(htim);
}
/**
- * @brief Time Base configuration
- * @param TIMx : TIM periheral
- * @param Structure : TIM Base configuration structure
- * @retval None
- */
-void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure)
-{
+ * @brief Time Base configuration
+ * @param TIMx : TIM periheral
+ * @param Structure : TIM Base configuration structure
+ * @retval None
+ */
+void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure) {
uint32_t tmpcr1 = 0U;
- tmpcr1 = TIMx->CR1;
+ tmpcr1 = TIMx->CR1;
/* Set TIM Time Base Unit parameters ---------------------------------------*/
- if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx))
- {
+ if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) {
/* Select the Counter Mode */
tmpcr1 &= ~(TIM_CR1_DIR | TIM_CR1_CMS);
tmpcr1 |= Structure->CounterMode;
}
- if(IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx))
- {
+ if (IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) {
/* Set the clock division */
tmpcr1 &= ~TIM_CR1_CKD;
tmpcr1 |= (uint32_t)Structure->ClockDivision;
@@ -4615,41 +4104,39 @@ void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure)
TIMx->CR1 = tmpcr1;
/* Set the Autoreload value */
- TIMx->ARR = (uint32_t)Structure->Period ;
+ TIMx->ARR = (uint32_t)Structure->Period;
/* Set the Prescaler value */
TIMx->PSC = (uint32_t)Structure->Prescaler;
- if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx))
- {
+ if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) {
/* Set the Repetition Counter value */
TIMx->RCR = Structure->RepetitionCounter;
}
- /* Generate an update event to reload the Prescaler
+ /* Generate an update event to reload the Prescaler
and the repetition counter(only for TIM1 and TIM8) value immediatly */
TIMx->EGR = TIM_EGR_UG;
}
/**
- * @brief Time Ouput Compare 1 configuration
- * @param TIMx to select the TIM peripheral
- * @param OC_Config : The ouput configuration structure
- * @retval None
- */
-static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
-{
+ * @brief Time Ouput Compare 1 configuration
+ * @param TIMx to select the TIM peripheral
+ * @param OC_Config : The ouput configuration structure
+ * @retval None
+ */
+static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) {
uint32_t tmpccmrx = 0U;
- uint32_t tmpccer = 0U;
- uint32_t tmpcr2 = 0U;
+ uint32_t tmpccer = 0U;
+ uint32_t tmpcr2 = 0U;
- /* Disable the Channel 1: Reset the CC1E Bit */
+ /* Disable the Channel 1: Reset the CC1E Bit */
TIMx->CCER &= ~TIM_CCER_CC1E;
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
- tmpcr2 = TIMx->CR2;
+ tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR1 register value */
tmpccmrx = TIMx->CCMR1;
@@ -4665,8 +4152,7 @@ static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
/* Set the Output Compare Polarity */
tmpccer |= OC_Config->OCPolarity;
- if(IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_1))
- {
+ if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_1)) {
/* Check parameters */
assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity));
@@ -4678,8 +4164,7 @@ static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
tmpccer &= ~TIM_CCER_CC1NE;
}
- if(IS_TIM_BREAK_INSTANCE(TIMx))
- {
+ if (IS_TIM_BREAK_INSTANCE(TIMx)) {
/* Check parameters */
assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState));
assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState));
@@ -4706,16 +4191,15 @@ static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
}
/**
- * @brief Time Ouput Compare 2 configuration
- * @param TIMx to select the TIM peripheral
- * @param OC_Config : The ouput configuration structure
- * @retval None
- */
-void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
-{
+ * @brief Time Ouput Compare 2 configuration
+ * @param TIMx to select the TIM peripheral
+ * @param OC_Config : The ouput configuration structure
+ * @retval None
+ */
+void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) {
uint32_t tmpccmrx = 0U;
- uint32_t tmpccer = 0U;
- uint32_t tmpcr2 = 0U;
+ uint32_t tmpccer = 0U;
+ uint32_t tmpcr2 = 0U;
/* Disable the Channel 2: Reset the CC2E Bit */
TIMx->CCER &= ~TIM_CCER_CC2E;
@@ -4723,7 +4207,7 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
- tmpcr2 = TIMx->CR2;
+ tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR1 register value */
tmpccmrx = TIMx->CCMR1;
@@ -4740,8 +4224,7 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
/* Set the Output Compare Polarity */
tmpccer |= (OC_Config->OCPolarity << 4U);
- if(IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_2))
- {
+ if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_2)) {
assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity));
/* Reset the Output N Polarity level */
@@ -4750,11 +4233,9 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
tmpccer |= (OC_Config->OCNPolarity << 4U);
/* Reset the Output N State */
tmpccer &= ~TIM_CCER_CC2NE;
-
}
- if(IS_TIM_BREAK_INSTANCE(TIMx))
- {
+ if (IS_TIM_BREAK_INSTANCE(TIMx)) {
/* Check parameters */
assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState));
assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState));
@@ -4782,16 +4263,15 @@ void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
}
/**
- * @brief Time Ouput Compare 3 configuration
- * @param TIMx to select the TIM peripheral
- * @param OC_Config : The ouput configuration structure
- * @retval None
- */
-static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
-{
+ * @brief Time Ouput Compare 3 configuration
+ * @param TIMx to select the TIM peripheral
+ * @param OC_Config : The ouput configuration structure
+ * @retval None
+ */
+static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) {
uint32_t tmpccmrx = 0U;
- uint32_t tmpccer = 0U;
- uint32_t tmpcr2 = 0U;
+ uint32_t tmpccer = 0U;
+ uint32_t tmpcr2 = 0U;
/* Disable the Channel 3: Reset the CC2E Bit */
TIMx->CCER &= ~TIM_CCER_CC3E;
@@ -4799,7 +4279,7 @@ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
- tmpcr2 = TIMx->CR2;
+ tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR2 register value */
tmpccmrx = TIMx->CCMR2;
@@ -4815,8 +4295,7 @@ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
/* Set the Output Compare Polarity */
tmpccer |= (OC_Config->OCPolarity << 8U);
- if(IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_3))
- {
+ if (IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_3)) {
assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity));
/* Reset the Output N Polarity level */
@@ -4827,8 +4306,7 @@ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
tmpccer &= ~TIM_CCER_CC3NE;
}
- if(IS_TIM_BREAK_INSTANCE(TIMx))
- {
+ if (IS_TIM_BREAK_INSTANCE(TIMx)) {
/* Check parameters */
assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState));
assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState));
@@ -4856,16 +4334,15 @@ static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
}
/**
- * @brief Time Ouput Compare 4 configuration
- * @param TIMx to select the TIM peripheral
- * @param OC_Config : The ouput configuration structure
- * @retval None
- */
-static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
-{
+ * @brief Time Ouput Compare 4 configuration
+ * @param TIMx to select the TIM peripheral
+ * @param OC_Config : The ouput configuration structure
+ * @retval None
+ */
+static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) {
uint32_t tmpccmrx = 0U;
- uint32_t tmpccer = 0U;
- uint32_t tmpcr2 = 0U;
+ uint32_t tmpccer = 0U;
+ uint32_t tmpcr2 = 0U;
/* Disable the Channel 4: Reset the CC4E Bit */
TIMx->CCER &= ~TIM_CCER_CC4E;
@@ -4873,7 +4350,7 @@ static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
/* Get the TIMx CCER register value */
tmpccer = TIMx->CCER;
/* Get the TIMx CR2 register value */
- tmpcr2 = TIMx->CR2;
+ tmpcr2 = TIMx->CR2;
/* Get the TIMx CCMR2 register value */
tmpccmrx = TIMx->CCMR2;
@@ -4890,11 +4367,10 @@ static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
/* Set the Output Compare Polarity */
tmpccer |= (OC_Config->OCPolarity << 12U);
- if(IS_TIM_BREAK_INSTANCE(TIMx))
- {
+ if (IS_TIM_BREAK_INSTANCE(TIMx)) {
assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState));
- /* Reset the Output Compare IDLE State */
+ /* Reset the Output Compare IDLE State */
tmpcr2 &= ~TIM_CR2_OIS4;
/* Set the Output Idle state */
tmpcr2 |= (OC_Config->OCIdleState << 6);
@@ -4913,20 +4389,17 @@ static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config)
TIMx->CCER = tmpccer;
}
-
/**
- * @brief Time Slave configuration
- * @param htim: pointer to a TIM_HandleTypeDef structure that contains
- * the configuration information for TIM module.
- * @param sSlaveConfig: The slave configuration structure
- * @retval None
- */
-static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim,
- TIM_SlaveConfigTypeDef * sSlaveConfig)
-{
- uint32_t tmpsmcr = 0U;
+ * @brief Time Slave configuration
+ * @param htim: pointer to a TIM_HandleTypeDef structure that contains
+ * the configuration information for TIM module.
+ * @param sSlaveConfig: The slave configuration structure
+ * @retval None
+ */
+static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef *sSlaveConfig) {
+ uint32_t tmpsmcr = 0U;
uint32_t tmpccmr1 = 0U;
- uint32_t tmpccer = 0U;
+ uint32_t tmpccer = 0U;
/* Get the TIMx SMCR register value */
tmpsmcr = htim->Instance->SMCR;
@@ -4945,100 +4418,76 @@ static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim,
htim->Instance->SMCR = tmpsmcr;
/* Configure the trigger prescaler, filter, and polarity */
- switch (sSlaveConfig->InputTrigger)
- {
- case TIM_TS_ETRF:
- {
- /* Check the parameters */
- assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance));
- assert_param(IS_TIM_TRIGGERPRESCALER(sSlaveConfig->TriggerPrescaler));
- assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity));
- assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
- /* Configure the ETR Trigger source */
- TIM_ETR_SetConfig(htim->Instance,
- sSlaveConfig->TriggerPrescaler,
- sSlaveConfig->TriggerPolarity,
- sSlaveConfig->TriggerFilter);
- }
- break;
-
- case TIM_TS_TI1F_ED:
- {
- /* Check the parameters */
- assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
- assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
-
- /* Disable the Channel 1: Reset the CC1E Bit */
- tmpccer = htim->Instance->CCER;
- htim->Instance->CCER &= ~TIM_CCER_CC1E;
- tmpccmr1 = htim->Instance->CCMR1;
-
- /* Set the filter */
- tmpccmr1 &= ~TIM_CCMR1_IC1F;
- tmpccmr1 |= ((sSlaveConfig->TriggerFilter) << 4U);
-
- /* Write to TIMx CCMR1 and CCER registers */
- htim->Instance->CCMR1 = tmpccmr1;
- htim->Instance->CCER = tmpccer;
-
- }
- break;
-
- case TIM_TS_TI1FP1:
- {
- /* Check the parameters */
- assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
- assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity));
- assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
-
- /* Configure TI1 Filter and Polarity */
- TIM_TI1_ConfigInputStage(htim->Instance,
- sSlaveConfig->TriggerPolarity,
- sSlaveConfig->TriggerFilter);
- }
- break;
+ switch (sSlaveConfig->InputTrigger) {
+ case TIM_TS_ETRF: {
+ /* Check the parameters */
+ assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TRIGGERPRESCALER(sSlaveConfig->TriggerPrescaler));
+ assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity));
+ assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
+ /* Configure the ETR Trigger source */
+ TIM_ETR_SetConfig(htim->Instance, sSlaveConfig->TriggerPrescaler, sSlaveConfig->TriggerPolarity, sSlaveConfig->TriggerFilter);
+ } break;
+
+ case TIM_TS_TI1F_ED: {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
+
+ /* Disable the Channel 1: Reset the CC1E Bit */
+ tmpccer = htim->Instance->CCER;
+ htim->Instance->CCER &= ~TIM_CCER_CC1E;
+ tmpccmr1 = htim->Instance->CCMR1;
+
+ /* Set the filter */
+ tmpccmr1 &= ~TIM_CCMR1_IC1F;
+ tmpccmr1 |= ((sSlaveConfig->TriggerFilter) << 4U);
+
+ /* Write to TIMx CCMR1 and CCER registers */
+ htim->Instance->CCMR1 = tmpccmr1;
+ htim->Instance->CCER = tmpccer;
+
+ } break;
+
+ case TIM_TS_TI1FP1: {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC1_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity));
+ assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
+
+ /* Configure TI1 Filter and Polarity */
+ TIM_TI1_ConfigInputStage(htim->Instance, sSlaveConfig->TriggerPolarity, sSlaveConfig->TriggerFilter);
+ } break;
+
+ case TIM_TS_TI2FP2: {
+ /* Check the parameters */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity));
+ assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
- case TIM_TS_TI2FP2:
- {
- /* Check the parameters */
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity));
- assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter));
+ /* Configure TI2 Filter and Polarity */
+ TIM_TI2_ConfigInputStage(htim->Instance, sSlaveConfig->TriggerPolarity, sSlaveConfig->TriggerFilter);
+ } break;
- /* Configure TI2 Filter and Polarity */
- TIM_TI2_ConfigInputStage(htim->Instance,
- sSlaveConfig->TriggerPolarity,
- sSlaveConfig->TriggerFilter);
- }
- break;
-
- case TIM_TS_ITR0:
- {
- /* Check the parameter */
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- }
- break;
+ case TIM_TS_ITR0: {
+ /* Check the parameter */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ } break;
- case TIM_TS_ITR1:
- {
- /* Check the parameter */
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- }
- break;
+ case TIM_TS_ITR1: {
+ /* Check the parameter */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ } break;
- case TIM_TS_ITR2:
- {
- /* Check the parameter */
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- }
- break;
+ case TIM_TS_ITR2: {
+ /* Check the parameter */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ } break;
- case TIM_TS_ITR3:
- {
- /* Check the parameter */
- assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
- }
- break;
+ case TIM_TS_ITR3: {
+ /* Check the parameter */
+ assert_param(IS_TIM_CC2_INSTANCE(htim->Instance));
+ } break;
default:
break;
@@ -5046,44 +4495,39 @@ static void TIM_SlaveTimer_SetConfig(TIM_HandleTypeDef *htim,
}
/**
- * @brief Configure the TI1 as Input.
- * @param TIMx to select the TIM peripheral.
- * @param TIM_ICPolarity : The Input Polarity.
- * This parameter can be one of the following values:
- * @arg TIM_ICPOLARITY_RISING
- * @arg TIM_ICPOLARITY_FALLING
- * @arg TIM_ICPOLARITY_BOTHEDGE
- * @param TIM_ICSelection : specifies the input to be used.
- * This parameter can be one of the following values:
- * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 1 is selected to be connected to IC1.
- * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 1 is selected to be connected to IC2.
- * @arg TIM_ICSELECTION_TRC: TIM Input 1 is selected to be connected to TRC.
- * @param TIM_ICFilter : Specifies the Input Capture Filter.
- * This parameter must be a value between 0x00 and 0x0F.
- * @retval None
- * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI2FP1
- * (on channel2 path) is used as the input signal. Therefore CCMR1 must be
- * protected against un-initialized filter and polarity values.
- */
-void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
- uint32_t TIM_ICFilter)
-{
+ * @brief Configure the TI1 as Input.
+ * @param TIMx to select the TIM peripheral.
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPOLARITY_RISING
+ * @arg TIM_ICPOLARITY_FALLING
+ * @arg TIM_ICPOLARITY_BOTHEDGE
+ * @param TIM_ICSelection : specifies the input to be used.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 1 is selected to be connected to IC1.
+ * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 1 is selected to be connected to IC2.
+ * @arg TIM_ICSELECTION_TRC: TIM Input 1 is selected to be connected to TRC.
+ * @param TIM_ICFilter : Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI2FP1
+ * (on channel2 path) is used as the input signal. Therefore CCMR1 must be
+ * protected against un-initialized filter and polarity values.
+ */
+void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) {
uint32_t tmpccmr1 = 0U;
- uint32_t tmpccer = 0U;
+ uint32_t tmpccer = 0U;
/* Disable the Channel 1: Reset the CC1E Bit */
TIMx->CCER &= ~TIM_CCER_CC1E;
tmpccmr1 = TIMx->CCMR1;
- tmpccer = TIMx->CCER;
+ tmpccer = TIMx->CCER;
/* Select the Input */
- if(IS_TIM_CC2_INSTANCE(TIMx) != RESET)
- {
+ if (IS_TIM_CC2_INSTANCE(TIMx) != RESET) {
tmpccmr1 &= ~TIM_CCMR1_CC1S;
tmpccmr1 |= TIM_ICSelection;
- }
- else
- {
+ } else {
tmpccmr1 |= TIM_CCMR1_CC1S_0;
}
@@ -5097,25 +4541,24 @@ void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_
/* Write to TIMx CCMR1 and CCER registers */
TIMx->CCMR1 = tmpccmr1;
- TIMx->CCER = tmpccer;
+ TIMx->CCER = tmpccer;
}
/**
- * @brief Configure the Polarity and Filter for TI1.
- * @param TIMx to select the TIM peripheral.
- * @param TIM_ICPolarity : The Input Polarity.
- * This parameter can be one of the following values:
- * @arg TIM_ICPOLARITY_RISING
- * @arg TIM_ICPOLARITY_FALLING
- * @arg TIM_ICPOLARITY_BOTHEDGE
- * @param TIM_ICFilter : Specifies the Input Capture Filter.
- * This parameter must be a value between 0x00 and 0x0F.
- * @retval None
- */
-static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter)
-{
+ * @brief Configure the Polarity and Filter for TI1.
+ * @param TIMx to select the TIM peripheral.
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPOLARITY_RISING
+ * @arg TIM_ICPOLARITY_FALLING
+ * @arg TIM_ICPOLARITY_BOTHEDGE
+ * @param TIM_ICFilter : Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ */
+static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) {
uint32_t tmpccmr1 = 0U;
- uint32_t tmpccer = 0U;
+ uint32_t tmpccer = 0U;
/* Disable the Channel 1: Reset the CC1E Bit */
tmpccer = TIMx->CCER;
@@ -5132,39 +4575,37 @@ static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity,
/* Write to TIMx CCMR1 and CCER registers */
TIMx->CCMR1 = tmpccmr1;
- TIMx->CCER = tmpccer;
+ TIMx->CCER = tmpccer;
}
/**
- * @brief Configure the TI2 as Input.
- * @param TIMx to select the TIM peripheral
- * @param TIM_ICPolarity : The Input Polarity.
- * This parameter can be one of the following values:
- * @arg TIM_ICPOLARITY_RISING
- * @arg TIM_ICPOLARITY_FALLING
- * @arg TIM_ICPOLARITY_BOTHEDGE
- * @param TIM_ICSelection : specifies the input to be used.
- * This parameter can be one of the following values:
- * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 2 is selected to be connected to IC2.
- * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 2 is selected to be connected to IC1.
- * @arg TIM_ICSELECTION_TRC: TIM Input 2 is selected to be connected to TRC.
- * @param TIM_ICFilter : Specifies the Input Capture Filter.
- * This parameter must be a value between 0x00 and 0x0F.
- * @retval None
- * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI1FP2
- * (on channel1 path) is used as the input signal. Therefore CCMR1 must be
- * protected against un-initialized filter and polarity values.
- */
-static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
- uint32_t TIM_ICFilter)
-{
+ * @brief Configure the TI2 as Input.
+ * @param TIMx to select the TIM peripheral
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPOLARITY_RISING
+ * @arg TIM_ICPOLARITY_FALLING
+ * @arg TIM_ICPOLARITY_BOTHEDGE
+ * @param TIM_ICSelection : specifies the input to be used.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 2 is selected to be connected to IC2.
+ * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 2 is selected to be connected to IC1.
+ * @arg TIM_ICSELECTION_TRC: TIM Input 2 is selected to be connected to TRC.
+ * @param TIM_ICFilter : Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI1FP2
+ * (on channel1 path) is used as the input signal. Therefore CCMR1 must be
+ * protected against un-initialized filter and polarity values.
+ */
+static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) {
uint32_t tmpccmr1 = 0U;
- uint32_t tmpccer = 0U;
+ uint32_t tmpccer = 0U;
/* Disable the Channel 2: Reset the CC2E Bit */
TIMx->CCER &= ~TIM_CCER_CC2E;
tmpccmr1 = TIMx->CCMR1;
- tmpccer = TIMx->CCER;
+ tmpccer = TIMx->CCER;
/* Select the Input */
tmpccmr1 &= ~TIM_CCMR1_CC2S;
@@ -5179,31 +4620,30 @@ static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32
tmpccer |= ((TIM_ICPolarity << 4U) & (TIM_CCER_CC2P | TIM_CCER_CC2NP));
/* Write to TIMx CCMR1 and CCER registers */
- TIMx->CCMR1 = tmpccmr1 ;
- TIMx->CCER = tmpccer;
+ TIMx->CCMR1 = tmpccmr1;
+ TIMx->CCER = tmpccer;
}
/**
- * @brief Configure the Polarity and Filter for TI2.
- * @param TIMx to select the TIM peripheral.
- * @param TIM_ICPolarity : The Input Polarity.
- * This parameter can be one of the following values:
- * @arg TIM_ICPOLARITY_RISING
- * @arg TIM_ICPOLARITY_FALLING
- * @arg TIM_ICPOLARITY_BOTHEDGE
- * @param TIM_ICFilter : Specifies the Input Capture Filter.
- * This parameter must be a value between 0x00 and 0x0F.
- * @retval None
- */
-static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter)
-{
+ * @brief Configure the Polarity and Filter for TI2.
+ * @param TIMx to select the TIM peripheral.
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPOLARITY_RISING
+ * @arg TIM_ICPOLARITY_FALLING
+ * @arg TIM_ICPOLARITY_BOTHEDGE
+ * @param TIM_ICFilter : Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ */
+static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) {
uint32_t tmpccmr1 = 0U;
- uint32_t tmpccer = 0U;
+ uint32_t tmpccer = 0U;
/* Disable the Channel 2: Reset the CC2E Bit */
TIMx->CCER &= ~TIM_CCER_CC2E;
tmpccmr1 = TIMx->CCMR1;
- tmpccer = TIMx->CCER;
+ tmpccer = TIMx->CCER;
/* Set the filter */
tmpccmr1 &= ~TIM_CCMR1_IC2F;
@@ -5214,39 +4654,37 @@ static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity,
tmpccer |= (TIM_ICPolarity << 4U);
/* Write to TIMx CCMR1 and CCER registers */
- TIMx->CCMR1 = tmpccmr1 ;
- TIMx->CCER = tmpccer;
+ TIMx->CCMR1 = tmpccmr1;
+ TIMx->CCER = tmpccer;
}
/**
- * @brief Configure the TI3 as Input.
- * @param TIMx to select the TIM peripheral
- * @param TIM_ICPolarity : The Input Polarity.
- * This parameter can be one of the following values:
- * @arg TIM_ICPOLARITY_RISING
- * @arg TIM_ICPOLARITY_FALLING
- * @param TIM_ICSelection : specifies the input to be used.
- * This parameter can be one of the following values:
- * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 3 is selected to be connected to IC3.
- * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 3 is selected to be connected to IC4.
- * @arg TIM_ICSELECTION_TRC: TIM Input 3 is selected to be connected to TRC.
- * @param TIM_ICFilter : Specifies the Input Capture Filter.
- * This parameter must be a value between 0x00 and 0x0F.
- * @retval None
- * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI3FP4
- * (on channel1 path) is used as the input signal. Therefore CCMR2 must be
- * protected against un-initialized filter and polarity values.
- */
-static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
- uint32_t TIM_ICFilter)
-{
+ * @brief Configure the TI3 as Input.
+ * @param TIMx to select the TIM peripheral
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPOLARITY_RISING
+ * @arg TIM_ICPOLARITY_FALLING
+ * @param TIM_ICSelection : specifies the input to be used.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 3 is selected to be connected to IC3.
+ * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 3 is selected to be connected to IC4.
+ * @arg TIM_ICSELECTION_TRC: TIM Input 3 is selected to be connected to TRC.
+ * @param TIM_ICFilter : Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @retval None
+ * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI3FP4
+ * (on channel1 path) is used as the input signal. Therefore CCMR2 must be
+ * protected against un-initialized filter and polarity values.
+ */
+static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) {
uint32_t tmpccmr2 = 0U;
- uint32_t tmpccer = 0U;
+ uint32_t tmpccer = 0U;
/* Disable the Channel 3: Reset the CC3E Bit */
TIMx->CCER &= ~TIM_CCER_CC3E;
tmpccmr2 = TIMx->CCMR2;
- tmpccer = TIMx->CCER;
+ tmpccer = TIMx->CCER;
/* Select the Input */
tmpccmr2 &= ~TIM_CCMR2_CC3S;
@@ -5262,38 +4700,36 @@ static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32
/* Write to TIMx CCMR2 and CCER registers */
TIMx->CCMR2 = tmpccmr2;
- TIMx->CCER = tmpccer;
+ TIMx->CCER = tmpccer;
}
/**
- * @brief Configure the TI4 as Input.
- * @param TIMx to select the TIM peripheral
- * @param TIM_ICPolarity : The Input Polarity.
- * This parameter can be one of the following values:
- * @arg TIM_ICPOLARITY_RISING
- * @arg TIM_ICPOLARITY_FALLING
- * @param TIM_ICSelection : specifies the input to be used.
- * This parameter can be one of the following values:
- * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 4 is selected to be connected to IC4.
- * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 4 is selected to be connected to IC3.
- * @arg TIM_ICSELECTION_TRC: TIM Input 4 is selected to be connected to TRC.
- * @param TIM_ICFilter : Specifies the Input Capture Filter.
- * This parameter must be a value between 0x00 and 0x0F.
- * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI4FP3
- * (on channel1 path) is used as the input signal. Therefore CCMR2 must be
- * protected against un-initialized filter and polarity values.
- * @retval None
- */
-static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection,
- uint32_t TIM_ICFilter)
-{
+ * @brief Configure the TI4 as Input.
+ * @param TIMx to select the TIM peripheral
+ * @param TIM_ICPolarity : The Input Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICPOLARITY_RISING
+ * @arg TIM_ICPOLARITY_FALLING
+ * @param TIM_ICSelection : specifies the input to be used.
+ * This parameter can be one of the following values:
+ * @arg TIM_ICSELECTION_DIRECTTI: TIM Input 4 is selected to be connected to IC4.
+ * @arg TIM_ICSELECTION_INDIRECTTI: TIM Input 4 is selected to be connected to IC3.
+ * @arg TIM_ICSELECTION_TRC: TIM Input 4 is selected to be connected to TRC.
+ * @param TIM_ICFilter : Specifies the Input Capture Filter.
+ * This parameter must be a value between 0x00 and 0x0F.
+ * @note TIM_ICFilter and TIM_ICPolarity are not used in INDIRECT mode as TI4FP3
+ * (on channel1 path) is used as the input signal. Therefore CCMR2 must be
+ * protected against un-initialized filter and polarity values.
+ * @retval None
+ */
+static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter) {
uint32_t tmpccmr2 = 0U;
- uint32_t tmpccer = 0U;
+ uint32_t tmpccer = 0U;
/* Disable the Channel 4: Reset the CC4E Bit */
TIMx->CCER &= ~TIM_CCER_CC4E;
tmpccmr2 = TIMx->CCMR2;
- tmpccer = TIMx->CCER;
+ tmpccer = TIMx->CCER;
/* Select the Input */
tmpccmr2 &= ~TIM_CCMR2_CC4S;
@@ -5309,57 +4745,54 @@ static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32
/* Write to TIMx CCMR2 and CCER registers */
TIMx->CCMR2 = tmpccmr2;
- TIMx->CCER = tmpccer ;
+ TIMx->CCER = tmpccer;
}
/**
- * @brief Selects the Input Trigger source
- * @param TIMx to select the TIM peripheral
- * @param InputTriggerSource : The Input Trigger source.
- * This parameter can be one of the following values:
- * @arg TIM_TS_ITR0 : Internal Trigger 0
- * @arg TIM_TS_ITR1 : Internal Trigger 1
- * @arg TIM_TS_ITR2 : Internal Trigger 2
- * @arg TIM_TS_ITR3 : Internal Trigger 3
- * @arg TIM_TS_TI1F_ED : TI1 Edge Detector
- * @arg TIM_TS_TI1FP1 : Filtered Timer Input 1
- * @arg TIM_TS_TI2FP2 : Filtered Timer Input 2
- * @arg TIM_TS_ETRF : External Trigger input
- * @retval None
- */
-static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint16_t InputTriggerSource)
-{
+ * @brief Selects the Input Trigger source
+ * @param TIMx to select the TIM peripheral
+ * @param InputTriggerSource : The Input Trigger source.
+ * This parameter can be one of the following values:
+ * @arg TIM_TS_ITR0 : Internal Trigger 0
+ * @arg TIM_TS_ITR1 : Internal Trigger 1
+ * @arg TIM_TS_ITR2 : Internal Trigger 2
+ * @arg TIM_TS_ITR3 : Internal Trigger 3
+ * @arg TIM_TS_TI1F_ED : TI1 Edge Detector
+ * @arg TIM_TS_TI1FP1 : Filtered Timer Input 1
+ * @arg TIM_TS_TI2FP2 : Filtered Timer Input 2
+ * @arg TIM_TS_ETRF : External Trigger input
+ * @retval None
+ */
+static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint16_t InputTriggerSource) {
uint32_t tmpsmcr = 0U;
- /* Get the TIMx SMCR register value */
- tmpsmcr = TIMx->SMCR;
- /* Reset the TS Bits */
- tmpsmcr &= ~TIM_SMCR_TS;
- /* Set the Input Trigger source and the slave mode*/
- tmpsmcr |= InputTriggerSource | TIM_SLAVEMODE_EXTERNAL1;
- /* Write to TIMx SMCR */
- TIMx->SMCR = tmpsmcr;
+ /* Get the TIMx SMCR register value */
+ tmpsmcr = TIMx->SMCR;
+ /* Reset the TS Bits */
+ tmpsmcr &= ~TIM_SMCR_TS;
+ /* Set the Input Trigger source and the slave mode*/
+ tmpsmcr |= InputTriggerSource | TIM_SLAVEMODE_EXTERNAL1;
+ /* Write to TIMx SMCR */
+ TIMx->SMCR = tmpsmcr;
}
/**
- * @brief Configures the TIMx External Trigger (ETR).
- * @param TIMx to select the TIM peripheral
- * @param TIM_ExtTRGPrescaler : The external Trigger Prescaler.
- * This parameter can be one of the following values:
- * @arg TIM_ETRPRESCALER_DIV1: ETRP Prescaler OFF.
- * @arg TIM_ETRPRESCALER_DIV2: ETRP frequency divided by 2.
- * @arg TIM_ETRPRESCALER_DIV4: ETRP frequency divided by 4.
- * @arg TIM_ETRPRESCALER_DIV8: ETRP frequency divided by 8.
- * @param TIM_ExtTRGPolarity : The external Trigger Polarity.
- * This parameter can be one of the following values:
- * @arg TIM_ETRPOLARITY_INVERTED: active low or falling edge active.
- * @arg TIM_ETRPOLARITY_NONINVERTED: active high or rising edge active.
- * @param ExtTRGFilter : External Trigger Filter.
- * This parameter must be a value between 0x00 and 0x0F
- * @retval None
- */
-static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler,
- uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter)
-{
+ * @brief Configures the TIMx External Trigger (ETR).
+ * @param TIMx to select the TIM peripheral
+ * @param TIM_ExtTRGPrescaler : The external Trigger Prescaler.
+ * This parameter can be one of the following values:
+ * @arg TIM_ETRPRESCALER_DIV1: ETRP Prescaler OFF.
+ * @arg TIM_ETRPRESCALER_DIV2: ETRP frequency divided by 2.
+ * @arg TIM_ETRPRESCALER_DIV4: ETRP frequency divided by 4.
+ * @arg TIM_ETRPRESCALER_DIV8: ETRP frequency divided by 8.
+ * @param TIM_ExtTRGPolarity : The external Trigger Polarity.
+ * This parameter can be one of the following values:
+ * @arg TIM_ETRPOLARITY_INVERTED: active low or falling edge active.
+ * @arg TIM_ETRPOLARITY_NONINVERTED: active high or rising edge active.
+ * @param ExtTRGFilter : External Trigger Filter.
+ * This parameter must be a value between 0x00 and 0x0F
+ * @retval None
+ */
+static void TIM_ETR_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ExtTRGPrescaler, uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter) {
uint32_t tmpsmcr = 0U;
tmpsmcr = TIMx->SMCR;
@@ -5375,20 +4808,19 @@ static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler,
}
/**
- * @brief Enables or disables the TIM Capture Compare Channel x.
- * @param TIMx to select the TIM peripheral
- * @param Channel : specifies the TIM Channel
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1
- * @arg TIM_CHANNEL_2: TIM Channel 2
- * @arg TIM_CHANNEL_3: TIM Channel 3
- * @arg TIM_CHANNEL_4: TIM Channel 4
- * @param ChannelState : specifies the TIM Channel CCxE bit new state.
- * This parameter can be: TIM_CCx_ENABLE or TIM_CCx_Disable.
- * @retval None
- */
-void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState)
-{
+ * @brief Enables or disables the TIM Capture Compare Channel x.
+ * @param TIMx to select the TIM peripheral
+ * @param Channel : specifies the TIM Channel
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1
+ * @arg TIM_CHANNEL_2: TIM Channel 2
+ * @arg TIM_CHANNEL_3: TIM Channel 3
+ * @arg TIM_CHANNEL_4: TIM Channel 4
+ * @param ChannelState : specifies the TIM Channel CCxE bit new state.
+ * This parameter can be: TIM_CCx_ENABLE or TIM_CCx_Disable.
+ * @retval None
+ */
+void TIM_CCxChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelState) {
uint32_t tmp = 0U;
/* Check the parameters */
@@ -5401,19 +4833,19 @@ void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelStat
TIMx->CCER &= ~tmp;
/* Set or reset the CCxE Bit */
- TIMx->CCER |= (uint32_t)(ChannelState << Channel);
+ TIMx->CCER |= (uint32_t)(ChannelState << Channel);
}
/**
- * @}
- */
+ * @}
+ */
#endif /* HAL_TIM_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c
index 8bf99260..e1530203 100644
--- a/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c
+++ b/source/Core/BSP/Miniware/Vendor/STM32F1xx_HAL_Driver/Src/stm32f1xx_hal_tim_ex.c
@@ -98,13 +98,13 @@
#include "stm32f1xx_hal.h"
/** @addtogroup STM32F1xx_HAL_Driver
- * @{
- */
+ * @{
+ */
/** @defgroup TIMEx TIMEx
- * @brief TIM Extended HAL module driver
- * @{
- */
+ * @brief TIM Extended HAL module driver
+ * @{
+ */
#ifdef HAL_TIM_MODULE_ENABLED
@@ -114,16 +114,14 @@
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
-#if defined (STM32F100xB) || defined (STM32F100xE) || \
- defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F103xE) || defined (STM32F103xG) || \
- defined (STM32F105xC) || defined (STM32F107xC)
+#if defined(STM32F100xB) || defined(STM32F100xE) || defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
/** @defgroup TIMEx_Private_Functions TIMEx Private Functions
- * @{
- */
-static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelNState);
+ * @{
+ */
+static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelNState);
/**
- * @}
- */
+ * @}
+ */
#endif /* defined(STM32F100xB) || defined(STM32F100xE) || */
/* defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || */
/* defined(STM32F105xC) || defined(STM32F107xC) */
@@ -131,9 +129,8 @@ static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t Cha
/* Exported functions ---------------------------------------------------------*/
/** @defgroup TIMEx_Exported_Functions TIMEx Exported Functions
- * @{
- */
-
+ * @{
+ */
/** @defgroup TIMEx_Exported_Functions_Group1 Timer Hall Sensor functions
* @brief Timer Hall Sensor functions
@@ -157,18 +154,16 @@ static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t Cha
* @{
*/
/**
- * @brief Initializes the TIM Hall Sensor Interface and create the associated handle.
- * @param htim : TIM Encoder Interface handle
- * @param sConfig : TIM Hall Sensor configuration structure
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSensor_InitTypeDef* sConfig)
-{
+ * @brief Initializes the TIM Hall Sensor Interface and create the associated handle.
+ * @param htim : TIM Encoder Interface handle
+ * @param sConfig : TIM Hall Sensor configuration structure
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSensor_InitTypeDef *sConfig) {
TIM_OC_InitTypeDef OC_Config;
/* Check the TIM handle allocation */
- if(htim == NULL)
- {
+ if (htim == NULL) {
return HAL_ERROR;
}
@@ -180,17 +175,16 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSen
assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler));
assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter));
- if(htim->State == HAL_TIM_STATE_RESET)
- {
+ if (htim->State == HAL_TIM_STATE_RESET) {
/* Allocate lock resource and initialize it */
htim->Lock = HAL_UNLOCKED;
-
+
/* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */
HAL_TIMEx_HallSensor_MspInit(htim);
}
/* Set the TIM state */
- htim->State= HAL_TIM_STATE_BUSY;
+ htim->State = HAL_TIM_STATE_BUSY;
/* Configure the Time base in the Encoder Mode */
TIM_Base_SetConfig(htim->Instance, &htim->Init);
@@ -215,13 +209,13 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSen
htim->Instance->SMCR |= TIM_SLAVEMODE_RESET;
/* Program channel 2 in PWM 2 mode with the desired Commutation_Delay*/
- OC_Config.OCFastMode = TIM_OCFAST_DISABLE;
- OC_Config.OCIdleState = TIM_OCIDLESTATE_RESET;
- OC_Config.OCMode = TIM_OCMODE_PWM2;
+ OC_Config.OCFastMode = TIM_OCFAST_DISABLE;
+ OC_Config.OCIdleState = TIM_OCIDLESTATE_RESET;
+ OC_Config.OCMode = TIM_OCMODE_PWM2;
OC_Config.OCNIdleState = TIM_OCNIDLESTATE_RESET;
- OC_Config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
- OC_Config.OCPolarity = TIM_OCPOLARITY_HIGH;
- OC_Config.Pulse = sConfig->Commutation_Delay;
+ OC_Config.OCNPolarity = TIM_OCNPOLARITY_HIGH;
+ OC_Config.OCPolarity = TIM_OCPOLARITY_HIGH;
+ OC_Config.Pulse = sConfig->Commutation_Delay;
TIM_OC2_SetConfig(htim->Instance, &OC_Config);
@@ -231,18 +225,17 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSen
htim->Instance->CR2 |= TIM_TRGO_OC2REF;
/* Initialize the TIM state*/
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
return HAL_OK;
}
/**
- * @brief DeInitializes the TIM Hall Sensor interface
- * @param htim : TIM Hall Sensor handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes the TIM Hall Sensor interface
+ * @param htim : TIM Hall Sensor handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_INSTANCE(htim->Instance));
@@ -264,12 +257,11 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Initializes the TIM Hall Sensor MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim)
-{
+ * @brief Initializes the TIM Hall Sensor MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -278,12 +270,11 @@ __weak void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief DeInitializes TIM Hall Sensor MSP.
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim)
-{
+ * @brief DeInitializes TIM Hall Sensor MSP.
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -292,12 +283,11 @@ __weak void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim)
}
/**
- * @brief Starts the TIM Hall Sensor Interface.
- * @param htim : TIM Hall Sensor handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim)
-{
+ * @brief Starts the TIM Hall Sensor Interface.
+ * @param htim : TIM Hall Sensor handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
@@ -313,12 +303,11 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim)
}
/**
- * @brief Stops the TIM Hall sensor Interface.
- * @param htim : TIM Hall Sensor handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim)
-{
+ * @brief Stops the TIM Hall sensor Interface.
+ * @param htim : TIM Hall Sensor handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
@@ -334,12 +323,11 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim)
}
/**
- * @brief Starts the TIM Hall Sensor Interface in interrupt mode.
- * @param htim : TIM Hall Sensor handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim)
-{
+ * @brief Starts the TIM Hall Sensor Interface in interrupt mode.
+ * @param htim : TIM Hall Sensor handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
@@ -358,12 +346,11 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim)
}
/**
- * @brief Stops the TIM Hall Sensor Interface in interrupt mode.
- * @param htim : TIM handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim)
-{
+ * @brief Stops the TIM Hall Sensor Interface in interrupt mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
@@ -382,29 +369,22 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim)
}
/**
- * @brief Starts the TIM Hall Sensor Interface in DMA mode.
- * @param htim : TIM Hall Sensor handle
- * @param pData : The destination Buffer address.
- * @param Length : The length of data to be transferred from TIM peripheral to memory.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length)
-{
+ * @brief Starts the TIM Hall Sensor Interface in DMA mode.
+ * @param htim : TIM Hall Sensor handle
+ * @param pData : The destination Buffer address.
+ * @param Length : The length of data to be transferred from TIM peripheral to memory.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length) {
/* Check the parameters */
assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if(((uint32_t)pData == 0U) && (Length > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if (((uint32_t)pData == 0U) && (Length > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
@@ -415,7 +395,7 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32
/* Set the DMA Input Capture 1 Callback */
htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMACaptureCplt;
/* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
/* Enable the DMA channel for Capture 1*/
HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length);
@@ -431,12 +411,11 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32
}
/**
- * @brief Stops the TIM Hall Sensor Interface in DMA mode.
- * @param htim : TIM handle
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim)
-{
+ * @brief Stops the TIM Hall Sensor Interface in DMA mode.
+ * @param htim : TIM handle
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim) {
/* Check the parameters */
assert_param(IS_TIM_XOR_INSTANCE(htim->Instance));
@@ -444,7 +423,6 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim)
(in the Hall Sensor Interface the 3 possible channels that are used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */
TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE);
-
/* Disable the capture compare Interrupts 1 event */
__HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
@@ -456,12 +434,10 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim)
}
/**
- * @}
- */
+ * @}
+ */
-#if defined (STM32F100xB) || defined (STM32F100xE) || \
- defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F103xE) || defined (STM32F103xG) || \
- defined (STM32F105xC) || defined (STM32F107xC)
+#if defined(STM32F100xB) || defined(STM32F100xE) || defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
/** @defgroup TIMEx_Exported_Functions_Group2 Timer Complementary Output Compare functions
* @brief Timer Complementary Output Compare functions
@@ -484,18 +460,17 @@ HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim)
*/
/**
- * @brief Starts the TIM Output Compare signal generation on the complementary
- * output.
- * @param htim : TIM Output Compare handle
- * @param Channel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the TIM Output Compare signal generation on the complementary
+ * output.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
@@ -513,18 +488,17 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Stops the TIM Output Compare signal generation on the complementary
- * output.
- * @param htim : TIM handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Output Compare signal generation on the complementary
+ * output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
@@ -542,45 +516,37 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Starts the TIM Output Compare signal generation in interrupt mode
- * on the complementary output.
- * @param htim : TIM OC handle
- * @param Channel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the TIM Output Compare signal generation in interrupt mode
+ * on the complementary output.
+ * @param htim : TIM OC handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Enable the TIM Output Compare interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Enable the TIM Output Compare interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Enable the TIM Output Compare interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Enable the TIM Output Compare interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Enable the TIM Output Compare interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Enable the TIM Output Compare interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ } break;
- default:
+ default:
break;
}
@@ -601,47 +567,39 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Chann
}
/**
- * @brief Stops the TIM Output Compare signal generation in interrupt mode
- * on the complementary output.
- * @param htim : TIM Output Compare handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Output Compare signal generation in interrupt mode
+ * on the complementary output.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
uint32_t tmpccer = 0U;
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Output Compare interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Output Compare interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Output Compare interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Output Compare interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Output Compare interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Output Compare interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ } break;
- default:
+ default:
break;
}
@@ -650,8 +608,7 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channe
/* Disable the TIM Break interrupt (only if no more channel is active) */
tmpccer = htim->Instance->CCER;
- if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == RESET)
- {
+ if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == RESET) {
__HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK);
}
@@ -666,89 +623,75 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channe
}
/**
- * @brief Starts the TIM Output Compare signal generation in DMA mode
- * on the complementary output.
- * @param htim : TIM Output Compare handle
- * @param Channel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @param pData : The source Buffer address.
- * @param Length : The length of data to be transferred from memory to TIM peripheral
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
-{
+ * @brief Starts the TIM Output Compare signal generation in DMA mode
+ * on the complementary output.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @param pData : The source Buffer address.
+ * @param Length : The length of data to be transferred from memory to TIM peripheral
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if(((uint32_t)pData == 0U) && (Length > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if (((uint32_t)pData == 0U) && (Length > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
- /* Enable the TIM Output Compare DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ /* Enable the TIM Output Compare DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_2: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
- /* Enable the TIM Output Compare DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ /* Enable the TIM Output Compare DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_3: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length);
- /* Enable the TIM Output Compare DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ /* Enable the TIM Output Compare DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- default:
+ default:
break;
}
@@ -766,45 +709,37 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Chan
}
/**
- * @brief Stops the TIM Output Compare signal generation in DMA mode
- * on the complementary output.
- * @param htim : TIM Output Compare handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM Output Compare signal generation in DMA mode
+ * on the complementary output.
+ * @param htim : TIM Output Compare handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Output Compare DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Output Compare DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Output Compare DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Output Compare DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Output Compare DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Output Compare DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- default:
+ default:
break;
}
@@ -825,8 +760,8 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Chann
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup TIMEx_Exported_Functions_Group3 Timer Complementary PWM functions
* @brief Timer Complementary PWM functions
@@ -859,17 +794,16 @@ HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Chann
*/
/**
- * @brief Starts the PWM signal generation on the complementary output.
- * @param htim : TIM handle
- * @param Channel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the PWM signal generation on the complementary output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
@@ -887,17 +821,16 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel
}
/**
- * @brief Stops the PWM signal generation on the complementary output.
- * @param htim : TIM handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the PWM signal generation on the complementary output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
@@ -915,45 +848,37 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel)
}
/**
- * @brief Starts the PWM signal generation in interrupt mode on the
- * complementary output.
- * @param htim : TIM handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Starts the PWM signal generation in interrupt mode on the
+ * complementary output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Enable the TIM Capture/Compare 1 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Enable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Enable the TIM Capture/Compare 2 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Enable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Enable the TIM Capture/Compare 3 interrupt */
- __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Enable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3);
+ } break;
- default:
+ default:
break;
}
@@ -974,47 +899,39 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Chan
}
/**
- * @brief Stops the PWM signal generation in interrupt mode on the
- * complementary output.
- * @param htim : TIM handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the PWM signal generation in interrupt mode on the
+ * complementary output.
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) {
uint32_t tmpccer = 0U;
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Capture/Compare 1 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Capture/Compare 1 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Capture/Compare 2 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Capture/Compare 2 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Capture/Compare 3 interrupt */
- __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Capture/Compare 3 interrupt */
+ __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3);
+ } break;
- default:
+ default:
break;
}
@@ -1023,8 +940,7 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Chann
/* Disable the TIM Break interrupt (only if no more channel is active) */
tmpccer = htim->Instance->CCER;
- if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == RESET)
- {
+ if ((tmpccer & (TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) == RESET) {
__HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK);
}
@@ -1039,89 +955,75 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Chann
}
/**
- * @brief Starts the TIM PWM signal generation in DMA mode on the
- * complementary output
- * @param htim : TIM handle
- * @param Channel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @param pData : The source Buffer address.
- * @param Length : The length of data to be transferred from memory to TIM peripheral
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length)
-{
+ * @brief Starts the TIM PWM signal generation in DMA mode on the
+ * complementary output
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @param pData : The source Buffer address.
+ * @param Length : The length of data to be transferred from memory to TIM peripheral
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
- if((htim->State == HAL_TIM_STATE_BUSY))
- {
- return HAL_BUSY;
- }
- else if((htim->State == HAL_TIM_STATE_READY))
- {
- if(((uint32_t)pData == 0U) && (Length > 0U))
- {
+ if ((htim->State == HAL_TIM_STATE_BUSY)) {
+ return HAL_BUSY;
+ } else if ((htim->State == HAL_TIM_STATE_READY)) {
+ if (((uint32_t)pData == 0U) && (Length > 0U)) {
return HAL_ERROR;
- }
- else
- {
+ } else {
htim->State = HAL_TIM_STATE_BUSY;
}
}
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length);
- /* Enable the TIM Capture/Compare 1 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ /* Enable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_2: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length);
- /* Enable the TIM Capture/Compare 2 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ /* Enable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Set the DMA Period elapsed callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
+ case TIM_CHANNEL_3: {
+ /* Set the DMA Period elapsed callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = TIM_DMADelayPulseCplt;
- /* Set the DMA error callback */
- htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError ;
+ /* Set the DMA error callback */
+ htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = TIM_DMAError;
- /* Enable the DMA channel */
- HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length);
+ /* Enable the DMA channel */
+ HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3, Length);
- /* Enable the TIM Capture/Compare 3 DMA request */
- __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ /* Enable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- default:
+ default:
break;
}
@@ -1139,45 +1041,37 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Cha
}
/**
- * @brief Stops the TIM PWM signal generation in DMA mode on the complementary
- * output
- * @param htim : TIM handle
- * @param Channel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @arg TIM_CHANNEL_3: TIM Channel 3 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel)
-{
+ * @brief Stops the TIM PWM signal generation in DMA mode on the complementary
+ * output
+ * @param htim : TIM handle
+ * @param Channel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @arg TIM_CHANNEL_3: TIM Channel 3 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel));
- switch (Channel)
- {
- case TIM_CHANNEL_1:
- {
- /* Disable the TIM Capture/Compare 1 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
- }
- break;
+ switch (Channel) {
+ case TIM_CHANNEL_1: {
+ /* Disable the TIM Capture/Compare 1 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1);
+ } break;
- case TIM_CHANNEL_2:
- {
- /* Disable the TIM Capture/Compare 2 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
- }
- break;
+ case TIM_CHANNEL_2: {
+ /* Disable the TIM Capture/Compare 2 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2);
+ } break;
- case TIM_CHANNEL_3:
- {
- /* Disable the TIM Capture/Compare 3 DMA request */
- __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
- }
- break;
+ case TIM_CHANNEL_3: {
+ /* Disable the TIM Capture/Compare 3 DMA request */
+ __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3);
+ } break;
- default:
+ default:
break;
}
@@ -1198,8 +1092,8 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Chan
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup TIMEx_Exported_Functions_Group4 Timer Complementary One Pulse functions
* @brief Timer Complementary One Pulse functions
@@ -1220,17 +1114,16 @@ HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Chan
*/
/**
- * @brief Starts the TIM One Pulse signal generation on the complemetary
- * output.
- * @param htim : TIM One Pulse handle
- * @param OutputChannel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
-{
+ * @brief Starts the TIM One Pulse signal generation on the complemetary
+ * output.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
@@ -1245,17 +1138,16 @@ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t Ou
}
/**
- * @brief Stops the TIM One Pulse signal generation on the complementary
- * output.
- * @param htim : TIM One Pulse handle
- * @param OutputChannel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
-{
+ * @brief Stops the TIM One Pulse signal generation on the complementary
+ * output.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
@@ -1274,17 +1166,16 @@ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t Out
}
/**
- * @brief Starts the TIM One Pulse signal generation in interrupt mode on the
- * complementary channel.
- * @param htim : TIM One Pulse handle
- * @param OutputChannel : TIM Channel to be enabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
-{
+ * @brief Starts the TIM One Pulse signal generation in interrupt mode on the
+ * complementary channel.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channel to be enabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
@@ -1305,17 +1196,16 @@ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t
}
/**
- * @brief Stops the TIM One Pulse signal generation in interrupt mode on the
- * complementary channel.
- * @param htim : TIM One Pulse handle
- * @param OutputChannel : TIM Channel to be disabled
- * This parameter can be one of the following values:
- * @arg TIM_CHANNEL_1: TIM Channel 1 selected
- * @arg TIM_CHANNEL_2: TIM Channel 2 selected
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel)
-{
+ * @brief Stops the TIM One Pulse signal generation in interrupt mode on the
+ * complementary channel.
+ * @param htim : TIM One Pulse handle
+ * @param OutputChannel : TIM Channel to be disabled
+ * This parameter can be one of the following values:
+ * @arg TIM_CHANNEL_1: TIM Channel 1 selected
+ * @arg TIM_CHANNEL_2: TIM Channel 2 selected
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) {
/* Check the parameters */
assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel));
@@ -1339,8 +1229,8 @@ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t
}
/**
- * @}
- */
+ * @}
+ */
#endif /* defined(STM32F100xB) || defined(STM32F100xE) || */
/* defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || */
@@ -1363,43 +1253,38 @@ HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t
* @{
*/
-#if defined (STM32F100xB) || defined (STM32F100xE) || \
- defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F103xE) || defined (STM32F103xG) || \
- defined (STM32F105xC) || defined (STM32F107xC)
+#if defined(STM32F100xB) || defined(STM32F100xE) || defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
/**
- * @brief Configure the TIM commutation event sequence.
- * @note: this function is mandatory to use the commutation event in order to
- * update the configuration at each commutation detection on the TRGI input of the Timer,
- * the typical use of this feature is with the use of another Timer(interface Timer)
- * configured in Hall sensor interface, this interface Timer will generate the
- * commutation at its TRGO output (connected to Timer used in this function) each time
- * the TI1 of the Interface Timer detect a commutation at its input TI1.
- * @param htim : TIM handle
- * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
- * This parameter can be one of the following values:
- * @arg TIM_TS_ITR0: Internal trigger 0 selected
- * @arg TIM_TS_ITR1: Internal trigger 1 selected
- * @arg TIM_TS_ITR2: Internal trigger 2 selected
- * @arg TIM_TS_ITR3: Internal trigger 3 selected
- * @arg TIM_TS_NONE: No trigger is needed
- * @param CommutationSource : the Commutation Event source
- * This parameter can be one of the following values:
- * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
- * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource)
-{
+ * @brief Configure the TIM commutation event sequence.
+ * @note: this function is mandatory to use the commutation event in order to
+ * update the configuration at each commutation detection on the TRGI input of the Timer,
+ * the typical use of this feature is with the use of another Timer(interface Timer)
+ * configured in Hall sensor interface, this interface Timer will generate the
+ * commutation at its TRGO output (connected to Timer used in this function) each time
+ * the TI1 of the Interface Timer detect a commutation at its input TI1.
+ * @param htim : TIM handle
+ * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
+ * This parameter can be one of the following values:
+ * @arg TIM_TS_ITR0: Internal trigger 0 selected
+ * @arg TIM_TS_ITR1: Internal trigger 1 selected
+ * @arg TIM_TS_ITR2: Internal trigger 2 selected
+ * @arg TIM_TS_ITR3: Internal trigger 3 selected
+ * @arg TIM_TS_NONE: No trigger is needed
+ * @param CommutationSource : the Commutation Event source
+ * This parameter can be one of the following values:
+ * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
+ * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource) {
/* Check the parameters */
assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance));
assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger));
__HAL_LOCK(htim);
- if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
- (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3))
- {
+ if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3)) {
/* Select the Input trigger */
htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= InputTrigger;
@@ -1417,38 +1302,35 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent(TIM_HandleTypeDef *htim, uint
}
/**
- * @brief Configure the TIM commutation event sequence with interrupt.
- * @note: this function is mandatory to use the commutation event in order to
- * update the configuration at each commutation detection on the TRGI input of the Timer,
- * the typical use of this feature is with the use of another Timer(interface Timer)
- * configured in Hall sensor interface, this interface Timer will generate the
- * commutation at its TRGO output (connected to Timer used in this function) each time
- * the TI1 of the Interface Timer detect a commutation at its input TI1.
- * @param htim : TIM handle
- * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
- * This parameter can be one of the following values:
- * @arg TIM_TS_ITR0: Internal trigger 0 selected
- * @arg TIM_TS_ITR1: Internal trigger 1 selected
- * @arg TIM_TS_ITR2: Internal trigger 2 selected
- * @arg TIM_TS_ITR3: Internal trigger 3 selected
- * @arg TIM_TS_NONE: No trigger is needed
- * @param CommutationSource : the Commutation Event source
- * This parameter can be one of the following values:
- * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
- * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource)
-{
+ * @brief Configure the TIM commutation event sequence with interrupt.
+ * @note: this function is mandatory to use the commutation event in order to
+ * update the configuration at each commutation detection on the TRGI input of the Timer,
+ * the typical use of this feature is with the use of another Timer(interface Timer)
+ * configured in Hall sensor interface, this interface Timer will generate the
+ * commutation at its TRGO output (connected to Timer used in this function) each time
+ * the TI1 of the Interface Timer detect a commutation at its input TI1.
+ * @param htim : TIM handle
+ * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
+ * This parameter can be one of the following values:
+ * @arg TIM_TS_ITR0: Internal trigger 0 selected
+ * @arg TIM_TS_ITR1: Internal trigger 1 selected
+ * @arg TIM_TS_ITR2: Internal trigger 2 selected
+ * @arg TIM_TS_ITR3: Internal trigger 3 selected
+ * @arg TIM_TS_NONE: No trigger is needed
+ * @param CommutationSource : the Commutation Event source
+ * This parameter can be one of the following values:
+ * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
+ * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource) {
/* Check the parameters */
assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance));
assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger));
__HAL_LOCK(htim);
- if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
- (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3))
- {
+ if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3)) {
/* Select the Input trigger */
htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= InputTrigger;
@@ -1469,39 +1351,36 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_IT(TIM_HandleTypeDef *htim, u
}
/**
- * @brief Configure the TIM commutation event sequence with DMA.
- * @note: this function is mandatory to use the commutation event in order to
- * update the configuration at each commutation detection on the TRGI input of the Timer,
- * the typical use of this feature is with the use of another Timer(interface Timer)
- * configured in Hall sensor interface, this interface Timer will generate the
- * commutation at its TRGO output (connected to Timer used in this function) each time
- * the TI1 of the Interface Timer detect a commutation at its input TI1.
- * @note: The user should configure the DMA in his own software, in This function only the COMDE bit is set
- * @param htim : TIM handle
- * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
- * This parameter can be one of the following values:
- * @arg TIM_TS_ITR0: Internal trigger 0 selected
- * @arg TIM_TS_ITR1: Internal trigger 1 selected
- * @arg TIM_TS_ITR2: Internal trigger 2 selected
- * @arg TIM_TS_ITR3: Internal trigger 3 selected
- * @arg TIM_TS_NONE: No trigger is needed
- * @param CommutationSource : the Commutation Event source
- * This parameter can be one of the following values:
- * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
- * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource)
-{
+ * @brief Configure the TIM commutation event sequence with DMA.
+ * @note: this function is mandatory to use the commutation event in order to
+ * update the configuration at each commutation detection on the TRGI input of the Timer,
+ * the typical use of this feature is with the use of another Timer(interface Timer)
+ * configured in Hall sensor interface, this interface Timer will generate the
+ * commutation at its TRGO output (connected to Timer used in this function) each time
+ * the TI1 of the Interface Timer detect a commutation at its input TI1.
+ * @note: The user should configure the DMA in his own software, in This function only the COMDE bit is set
+ * @param htim : TIM handle
+ * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor
+ * This parameter can be one of the following values:
+ * @arg TIM_TS_ITR0: Internal trigger 0 selected
+ * @arg TIM_TS_ITR1: Internal trigger 1 selected
+ * @arg TIM_TS_ITR2: Internal trigger 2 selected
+ * @arg TIM_TS_ITR3: Internal trigger 3 selected
+ * @arg TIM_TS_NONE: No trigger is needed
+ * @param CommutationSource : the Commutation Event source
+ * This parameter can be one of the following values:
+ * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer
+ * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource) {
/* Check the parameters */
assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance));
assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger));
__HAL_LOCK(htim);
- if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) ||
- (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3))
- {
+ if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3)) {
/* Select the Input trigger */
htim->Instance->SMCR &= ~TIM_SMCR_TS;
htim->Instance->SMCR |= InputTrigger;
@@ -1528,16 +1407,14 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef *htim,
}
/**
- * @brief Configures the Break feature, dead time, Lock level, OSSI/OSSR State
- * and the AOE(automatic output enable).
- * @param htim : TIM handle
- * @param sBreakDeadTimeConfig : pointer to a TIM_ConfigBreakDeadConfigTypeDef structure that
- * contains the BDTR Register configuration information for the TIM peripheral.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim,
- TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig)
-{
+ * @brief Configures the Break feature, dead time, Lock level, OSSI/OSSR State
+ * and the AOE(automatic output enable).
+ * @param htim : TIM handle
+ * @param sBreakDeadTimeConfig : pointer to a TIM_ConfigBreakDeadConfigTypeDef structure that
+ * contains the BDTR Register configuration information for the TIM peripheral.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig) {
uint32_t tmpbdtr = 0U;
/* Check the parameters */
@@ -1579,15 +1456,14 @@ HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim,
/* defined(STM32F105xC) || defined(STM32F107xC) */
/**
- * @brief Configures the TIM in master mode.
- * @param htim : TIM handle.
- * @param sMasterConfig : pointer to a TIM_MasterConfigTypeDef structure that
- * contains the selected trigger output (TRGO) and the Master/Slave
- * mode.
- * @retval HAL status
- */
-HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef * sMasterConfig)
-{
+ * @brief Configures the TIM in master mode.
+ * @param htim : TIM handle.
+ * @param sMasterConfig : pointer to a TIM_MasterConfigTypeDef structure that
+ * contains the selected trigger output (TRGO) and the Master/Slave
+ * mode.
+ * @retval HAL status
+ */
+HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef *sMasterConfig) {
/* Check the parameters */
assert_param(IS_TIM_MASTER_INSTANCE(htim->Instance));
assert_param(IS_TIM_TRGO_SOURCE(sMasterConfig->MasterOutputTrigger));
@@ -1600,7 +1476,7 @@ HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim,
/* Reset the MMS Bits */
htim->Instance->CR2 &= ~TIM_CR2_MMS;
/* Select the TRGO source */
- htim->Instance->CR2 |= sMasterConfig->MasterOutputTrigger;
+ htim->Instance->CR2 |= sMasterConfig->MasterOutputTrigger;
/* Reset the MSM Bit */
htim->Instance->SMCR &= ~TIM_SMCR_MSM;
@@ -1615,8 +1491,8 @@ HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim,
}
/**
- * @}
- */
+ * @}
+ */
/** @defgroup TIMEx_Exported_Functions_Group6 Extension Callbacks functions
* @brief Extension Callbacks functions
@@ -1635,12 +1511,11 @@ HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim,
*/
/**
- * @brief Hall commutation changed callback in non blocking mode
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIMEx_CommutationCallback(TIM_HandleTypeDef *htim)
-{
+ * @brief Hall commutation changed callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIMEx_CommutationCallback(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -1649,12 +1524,11 @@ __weak void HAL_TIMEx_CommutationCallback(TIM_HandleTypeDef *htim)
}
/**
- * @brief Hall Break detection callback in non blocking mode
- * @param htim : TIM handle
- * @retval None
- */
-__weak void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim)
-{
+ * @brief Hall Break detection callback in non blocking mode
+ * @param htim : TIM handle
+ * @retval None
+ */
+__weak void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim) {
/* Prevent unused argument(s) compilation warning */
UNUSED(htim);
/* NOTE : This function Should not be modified, when the callback is needed,
@@ -1663,26 +1537,23 @@ __weak void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim)
}
/**
- * @brief TIM DMA Commutation callback.
- * @param hdma : pointer to DMA handle.
- * @retval None
- */
-void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma)
-{
- TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent;
+ * @brief TIM DMA Commutation callback.
+ * @param hdma : pointer to DMA handle.
+ * @retval None
+ */
+void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma) {
+ TIM_HandleTypeDef *htim = (TIM_HandleTypeDef *)((DMA_HandleTypeDef *)hdma)->Parent;
- htim->State= HAL_TIM_STATE_READY;
+ htim->State = HAL_TIM_STATE_READY;
HAL_TIMEx_CommutationCallback(htim);
}
/**
- * @}
- */
+ * @}
+ */
-#if defined (STM32F100xB) || defined (STM32F100xE) || \
- defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F103xE) || defined (STM32F103xG) || \
- defined (STM32F105xC) || defined (STM32F107xC)
+#if defined(STM32F100xB) || defined(STM32F100xE) || defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
/** @defgroup TIMEx_Exported_Functions_Group7 Extension Peripheral State functions
* @brief Extension Peripheral State functions
@@ -1700,62 +1571,56 @@ void TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma)
*/
/**
- * @brief Return the TIM Hall Sensor interface state
- * @param htim : TIM Hall Sensor handle
- * @retval HAL state
- */
-HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef *htim)
-{
- return htim->State;
-}
+ * @brief Return the TIM Hall Sensor interface state
+ * @param htim : TIM Hall Sensor handle
+ * @retval HAL state
+ */
+HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef *htim) { return htim->State; }
/**
- * @}
- */
+ * @}
+ */
#endif /* defined(STM32F100xB) || defined(STM32F100xE) || */
/* defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || */
/* defined(STM32F105xC) || defined(STM32F107xC) */
/**
- * @}
- */
+ * @}
+ */
-#if defined (STM32F100xB) || defined (STM32F100xE) || \
- defined (STM32F103x6) || defined (STM32F103xB) || defined (STM32F103xE) || defined (STM32F103xG) || \
- defined (STM32F105xC) || defined (STM32F107xC)
+#if defined(STM32F100xB) || defined(STM32F100xE) || defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || defined(STM32F105xC) || defined(STM32F107xC)
/** @addtogroup TIMEx_Private_Functions
- * @{
- */
+ * @{
+ */
/**
- * @brief Enables or disables the TIM Capture Compare Channel xN.
- * @param TIMx to select the TIM peripheral
- * @param Channel : specifies the TIM Channel
- * This parameter can be one of the following values:
- * @arg TIM_Channel_1: TIM Channel 1
- * @arg TIM_Channel_2: TIM Channel 2
- * @arg TIM_Channel_3: TIM Channel 3
- * @param ChannelNState : specifies the TIM Channel CCxNE bit new state.
- * This parameter can be: TIM_CCxN_ENABLE or TIM_CCxN_Disable.
- * @retval None
- */
-static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelNState)
-{
+ * @brief Enables or disables the TIM Capture Compare Channel xN.
+ * @param TIMx to select the TIM peripheral
+ * @param Channel : specifies the TIM Channel
+ * This parameter can be one of the following values:
+ * @arg TIM_Channel_1: TIM Channel 1
+ * @arg TIM_Channel_2: TIM Channel 2
+ * @arg TIM_Channel_3: TIM Channel 3
+ * @param ChannelNState : specifies the TIM Channel CCxNE bit new state.
+ * This parameter can be: TIM_CCxN_ENABLE or TIM_CCxN_Disable.
+ * @retval None
+ */
+static void TIM_CCxNChannelCmd(TIM_TypeDef *TIMx, uint32_t Channel, uint32_t ChannelNState) {
uint32_t tmp = 0U;
tmp = TIM_CCER_CC1NE << Channel;
/* Reset the CCxNE Bit */
- TIMx->CCER &= ~tmp;
+ TIMx->CCER &= ~tmp;
/* Set or reset the CCxNE Bit */
- TIMx->CCER |= (uint32_t)(ChannelNState << Channel);
+ TIMx->CCER |= (uint32_t)(ChannelNState << Channel);
}
/**
- * @}
- */
+ * @}
+ */
#endif /* defined(STM32F100xB) || defined(STM32F100xE) || */
/* defined(STM32F103x6) || defined(STM32F103xB) || defined(STM32F103xE) || defined(STM32F103xG) || */
@@ -1763,11 +1628,11 @@ static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t Cha
#endif /* HAL_TIM_MODULE_ENABLED */
/**
- * @}
- */
+ * @}
+ */
/**
- * @}
- */
+ * @}
+ */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
diff --git a/source/Core/BSP/Miniware/flash.c b/source/Core/BSP/Miniware/flash.c
index ba429dd4..d764df93 100644
--- a/source/Core/BSP/Miniware/flash.c
+++ b/source/Core/BSP/Miniware/flash.c
@@ -5,42 +5,37 @@
* Author: Ralim
*/
-#include "BSP_Flash.h"
#include "BSP.h"
-#include "string.h"
+#include "BSP_Flash.h"
#include "stm32f1xx_hal.h"
+#include "string.h"
-static uint16_t settings_page[512] __attribute__ ((section (".settings_page")));
+static uint16_t settings_page[512] __attribute__((section(".settings_page")));
uint8_t flash_save_buffer(const uint8_t *buffer, const uint16_t length) {
- FLASH_EraseInitTypeDef pEraseInit;
- pEraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
- pEraseInit.Banks = FLASH_BANK_1;
- pEraseInit.NbPages = 1;
- pEraseInit.PageAddress = (uint32_t) settings_page;
- uint32_t failingAddress = 0;
- resetWatchdog();
- __HAL_FLASH_CLEAR_FLAG(
- FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR | FLASH_FLAG_BSY);
- HAL_FLASH_Unlock();
- HAL_Delay(1);
- resetWatchdog();
- HAL_FLASHEx_Erase(&pEraseInit, &failingAddress);
- //^ Erase the page of flash (1024 bytes on this stm32)
- // erased the chunk
- // now we program it
- uint16_t *data = (uint16_t*) buffer;
- HAL_FLASH_Unlock();
- for (uint8_t i = 0; i < (length / 2); i++) {
- resetWatchdog();
- HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,
- (uint32_t) &settings_page[i], data[i]);
- }
- HAL_FLASH_Lock();
- return 1;
+ FLASH_EraseInitTypeDef pEraseInit;
+ pEraseInit.TypeErase = FLASH_TYPEERASE_PAGES;
+ pEraseInit.Banks = FLASH_BANK_1;
+ pEraseInit.NbPages = 1;
+ pEraseInit.PageAddress = (uint32_t)settings_page;
+ uint32_t failingAddress = 0;
+ resetWatchdog();
+ __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR | FLASH_FLAG_BSY);
+ HAL_FLASH_Unlock();
+ HAL_Delay(1);
+ resetWatchdog();
+ HAL_FLASHEx_Erase(&pEraseInit, &failingAddress);
+ //^ Erase the page of flash (1024 bytes on this stm32)
+ // erased the chunk
+ // now we program it
+ uint16_t *data = (uint16_t *)buffer;
+ HAL_FLASH_Unlock();
+ for (uint8_t i = 0; i < (length / 2); i++) {
+ resetWatchdog();
+ HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, (uint32_t)&settings_page[i], data[i]);
+ }
+ HAL_FLASH_Lock();
+ return 1;
}
-void flash_read_buffer(uint8_t *buffer, const uint16_t length) {
-
- memcpy(buffer, settings_page, length);
-}
+void flash_read_buffer(uint8_t *buffer, const uint16_t length) { memcpy(buffer, settings_page, length); }
diff --git a/source/Core/BSP/Miniware/fusb302b.cpp b/source/Core/BSP/Miniware/fusb302b.cpp
index ac5cbe76..dbb218b9 100644
--- a/source/Core/BSP/Miniware/fusb302b.cpp
+++ b/source/Core/BSP/Miniware/fusb302b.cpp
@@ -17,10 +17,10 @@
#include "Model_Config.h"
#ifdef POW_PD
#include "BSP.h"
-#include "fusb302b.h"
#include "I2CBB.hpp"
-#include <pd.h>
+#include "fusb302b.h"
#include "int_n.h"
+#include <pd.h>
/*
* Read a single byte from the FUSB302B
*
@@ -30,11 +30,11 @@
* Returns the value read from addr.
*/
static uint8_t fusb_read_byte(uint8_t addr) {
- uint8_t data[1];
- if (!I2CBB::Mem_Read(FUSB302B_ADDR, addr, (uint8_t*) data, 1)) {
- return 0;
- }
- return data[0];
+ uint8_t data[1];
+ if (!I2CBB::Mem_Read(FUSB302B_ADDR, addr, (uint8_t *)data, 1)) {
+ return 0;
+ }
+ return data[0];
}
/*
@@ -45,9 +45,7 @@ static uint8_t fusb_read_byte(uint8_t addr) {
* size: The number of bytes to read
* buf: The buffer into which data will be read
*/
-static bool fusb_read_buf(uint8_t addr, uint8_t size, uint8_t *buf) {
- return I2CBB::Mem_Read(FUSB302B_ADDR, addr, buf, size);
-}
+static bool fusb_read_buf(uint8_t addr, uint8_t size, uint8_t *buf) { return I2CBB::Mem_Read(FUSB302B_ADDR, addr, buf, size); }
/*
* Write a single byte to the FUSB302B
@@ -56,9 +54,7 @@ static bool fusb_read_buf(uint8_t addr, uint8_t size, uint8_t *buf) {
* addr: The memory address to which we will write
* byte: The value to write
*/
-static bool fusb_write_byte(uint8_t addr, uint8_t byte) {
- return I2CBB::Mem_Write(FUSB302B_ADDR, addr, (uint8_t*) &byte, 1);
-}
+static bool fusb_write_byte(uint8_t addr, uint8_t byte) { return I2CBB::Mem_Write(FUSB302B_ADDR, addr, (uint8_t *)&byte, 1); }
/*
* Write multiple bytes to the FUSB302B
@@ -68,198 +64,183 @@ static bool fusb_write_byte(uint8_t addr, uint8_t byte) {
* size: The number of bytes to write
* buf: The buffer to write
*/
-static bool fusb_write_buf(uint8_t addr, uint8_t size, const uint8_t *buf) {
- return I2CBB::Mem_Write(FUSB302B_ADDR, addr, buf, size);
-}
+static bool fusb_write_buf(uint8_t addr, uint8_t size, const uint8_t *buf) { return I2CBB::Mem_Write(FUSB302B_ADDR, addr, buf, size); }
void fusb_send_message(const union pd_msg *msg) {
- if (!I2CBB::lock2()) {
- return;
- }
- /* Token sequences for the FUSB302B */
- static uint8_t sop_seq[5] = {
- FUSB_FIFO_TX_SOP1,
- FUSB_FIFO_TX_SOP1,
- FUSB_FIFO_TX_SOP1,
- FUSB_FIFO_TX_SOP2,
- FUSB_FIFO_TX_PACKSYM };
- static const uint8_t eop_seq[4] = {
- FUSB_FIFO_TX_JAM_CRC,
- FUSB_FIFO_TX_EOP,
- FUSB_FIFO_TX_TXOFF,
- FUSB_FIFO_TX_TXON };
-
- /* Take the I2C2 mutex now so there can't be a race condition on sop_seq */
- /* Get the length of the message: a two-octet header plus NUMOBJ four-octet
- * data objects */
- uint8_t msg_len = 2 + 4 * PD_NUMOBJ_GET(msg);
-
- /* Set the number of bytes to be transmitted in the packet */
- sop_seq[4] = FUSB_FIFO_TX_PACKSYM | msg_len;
-
- /* Write all three parts of the message to the TX FIFO */
- fusb_write_buf( FUSB_FIFOS, 5, sop_seq);
- fusb_write_buf( FUSB_FIFOS, msg_len, msg->bytes);
- fusb_write_buf( FUSB_FIFOS, 4, eop_seq);
-
- I2CBB::unlock2();
-
+ if (!I2CBB::lock2()) {
+ return;
+ }
+ /* Token sequences for the FUSB302B */
+ static uint8_t sop_seq[5] = {FUSB_FIFO_TX_SOP1, FUSB_FIFO_TX_SOP1, FUSB_FIFO_TX_SOP1, FUSB_FIFO_TX_SOP2, FUSB_FIFO_TX_PACKSYM};
+ static const uint8_t eop_seq[4] = {FUSB_FIFO_TX_JAM_CRC, FUSB_FIFO_TX_EOP, FUSB_FIFO_TX_TXOFF, FUSB_FIFO_TX_TXON};
+
+ /* Take the I2C2 mutex now so there can't be a race condition on sop_seq */
+ /* Get the length of the message: a two-octet header plus NUMOBJ four-octet
+ * data objects */
+ uint8_t msg_len = 2 + 4 * PD_NUMOBJ_GET(msg);
+
+ /* Set the number of bytes to be transmitted in the packet */
+ sop_seq[4] = FUSB_FIFO_TX_PACKSYM | msg_len;
+
+ /* Write all three parts of the message to the TX FIFO */
+ fusb_write_buf(FUSB_FIFOS, 5, sop_seq);
+ fusb_write_buf(FUSB_FIFOS, msg_len, msg->bytes);
+ fusb_write_buf(FUSB_FIFOS, 4, eop_seq);
+
+ I2CBB::unlock2();
}
uint8_t fusb_read_message(union pd_msg *msg) {
- if (!I2CBB::lock2()) {
- asm("bkpt");
- }
- static uint8_t garbage[4];
- uint8_t numobj;
-
- // Read the header. If its not a SOP we dont actually want it at all
- // But on some revisions of the fusb if you dont both pick them up and read them out of the fifo, it gets stuck
- fusb_read_byte( FUSB_FIFOS);
- /* Read the message header into msg */
- fusb_read_buf( FUSB_FIFOS, 2, msg->bytes);
- /* Get the number of data objects */
- numobj = PD_NUMOBJ_GET(msg);
- /* If there is at least one data object, read the data objects */
- if (numobj > 0) {
- fusb_read_buf( FUSB_FIFOS, numobj * 4, msg->bytes + 2);
- }
- /* Throw the CRC32 in the garbage, since the PHY already checked it. */
- fusb_read_buf( FUSB_FIFOS, 4, garbage);
-
- I2CBB::unlock2();
- return 0;
+ if (!I2CBB::lock2()) {
+ asm("bkpt");
+ }
+ static uint8_t garbage[4];
+ uint8_t numobj;
+
+ // Read the header. If its not a SOP we dont actually want it at all
+ // But on some revisions of the fusb if you dont both pick them up and read them out of the fifo, it gets stuck
+ fusb_read_byte(FUSB_FIFOS);
+ /* Read the message header into msg */
+ fusb_read_buf(FUSB_FIFOS, 2, msg->bytes);
+ /* Get the number of data objects */
+ numobj = PD_NUMOBJ_GET(msg);
+ /* If there is at least one data object, read the data objects */
+ if (numobj > 0) {
+ fusb_read_buf(FUSB_FIFOS, numobj * 4, msg->bytes + 2);
+ }
+ /* Throw the CRC32 in the garbage, since the PHY already checked it. */
+ fusb_read_buf(FUSB_FIFOS, 4, garbage);
+
+ I2CBB::unlock2();
+ return 0;
}
void fusb_send_hardrst() {
- if (!I2CBB::lock2()) {
- return;
- }
- /* Send a hard reset */
- fusb_write_byte( FUSB_CONTROL3, 0x07 | FUSB_CONTROL3_SEND_HARD_RESET);
+ if (!I2CBB::lock2()) {
+ return;
+ }
+ /* Send a hard reset */
+ fusb_write_byte(FUSB_CONTROL3, 0x07 | FUSB_CONTROL3_SEND_HARD_RESET);
- I2CBB::unlock2();
+ I2CBB::unlock2();
}
bool fusb_setup() {
- if (!I2CBB::lock2()) {
- return false;
- }
- /* Fully reset the FUSB302B */
-// fusb_write_byte( FUSB_RESET, FUSB_RESET_SW_RES);
-// osDelay(2);
- if (!fusb_read_id()) {
- return false;
- }
-
- /* Turn on all power */
- fusb_write_byte( FUSB_POWER, 0x0F);
-
- /* Set interrupt masks */
- //Setting to 0 so interrupts are allowed
- fusb_write_byte( FUSB_MASK1, 0x00);
- fusb_write_byte( FUSB_MASKA, 0x00);
- fusb_write_byte( FUSB_MASKB, 0x00);
- fusb_write_byte( FUSB_CONTROL0, 0b11 << 2);
-
- /* Enable automatic retransmission */
- fusb_write_byte( FUSB_CONTROL3, 0x07);
- //set defaults
- fusb_write_byte( FUSB_CONTROL2, 0x00);
- /* Flush the RX buffer */
- fusb_write_byte( FUSB_CONTROL1,
- FUSB_CONTROL1_RX_FLUSH);
-
- /* Measure CC1 */
- fusb_write_byte( FUSB_SWITCHES0, 0x07);
- osDelay(10);
- uint8_t cc1 = fusb_read_byte( FUSB_STATUS0) & FUSB_STATUS0_BC_LVL;
-
- /* Measure CC2 */
- fusb_write_byte( FUSB_SWITCHES0, 0x0B);
- osDelay(10);
- uint8_t cc2 = fusb_read_byte( FUSB_STATUS0) & FUSB_STATUS0_BC_LVL;
-
- /* Select the correct CC line for BMC signaling; also enable AUTO_CRC */
- if (cc1 > cc2) {
- fusb_write_byte( FUSB_SWITCHES1, 0x25);
- fusb_write_byte( FUSB_SWITCHES0, 0x07);
- } else {
- fusb_write_byte( FUSB_SWITCHES1, 0x26);
- fusb_write_byte( FUSB_SWITCHES0, 0x0B);
- }
- I2CBB::unlock2();
- fusb_reset();
- GPIO_InitTypeDef GPIO_InitStruct;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
- GPIO_InitStruct.Pin = GPIO_PIN_9;
- GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
- GPIO_InitStruct.Pull = GPIO_PULLUP;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
- HAL_NVIC_SetPriority(EXTI9_5_IRQn, 10, 0);
- HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
- return true;
+ if (!I2CBB::lock2()) {
+ return false;
+ }
+ /* Fully reset the FUSB302B */
+ // fusb_write_byte( FUSB_RESET, FUSB_RESET_SW_RES);
+ // osDelay(2);
+ if (!fusb_read_id()) {
+ return false;
+ }
+
+ /* Turn on all power */
+ fusb_write_byte(FUSB_POWER, 0x0F);
+
+ /* Set interrupt masks */
+ // Setting to 0 so interrupts are allowed
+ fusb_write_byte(FUSB_MASK1, 0x00);
+ fusb_write_byte(FUSB_MASKA, 0x00);
+ fusb_write_byte(FUSB_MASKB, 0x00);
+ fusb_write_byte(FUSB_CONTROL0, 0b11 << 2);
+
+ /* Enable automatic retransmission */
+ fusb_write_byte(FUSB_CONTROL3, 0x07);
+ // set defaults
+ fusb_write_byte(FUSB_CONTROL2, 0x00);
+ /* Flush the RX buffer */
+ fusb_write_byte(FUSB_CONTROL1, FUSB_CONTROL1_RX_FLUSH);
+
+ /* Measure CC1 */
+ fusb_write_byte(FUSB_SWITCHES0, 0x07);
+ osDelay(10);
+ uint8_t cc1 = fusb_read_byte(FUSB_STATUS0) & FUSB_STATUS0_BC_LVL;
+
+ /* Measure CC2 */
+ fusb_write_byte(FUSB_SWITCHES0, 0x0B);
+ osDelay(10);
+ uint8_t cc2 = fusb_read_byte(FUSB_STATUS0) & FUSB_STATUS0_BC_LVL;
+
+ /* Select the correct CC line for BMC signaling; also enable AUTO_CRC */
+ if (cc1 > cc2) {
+ fusb_write_byte(FUSB_SWITCHES1, 0x25);
+ fusb_write_byte(FUSB_SWITCHES0, 0x07);
+ } else {
+ fusb_write_byte(FUSB_SWITCHES1, 0x26);
+ fusb_write_byte(FUSB_SWITCHES0, 0x0B);
+ }
+ I2CBB::unlock2();
+ fusb_reset();
+ GPIO_InitTypeDef GPIO_InitStruct;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
+ GPIO_InitStruct.Pin = GPIO_PIN_9;
+ GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
+ GPIO_InitStruct.Pull = GPIO_PULLUP;
+ HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
+ HAL_NVIC_SetPriority(EXTI9_5_IRQn, 10, 0);
+ HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
+ return true;
}
void fusb_get_status(union fusb_status *status) {
- if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
- if (!I2CBB::lock2()) {
- return;
- }
- }
-
- /* Read the interrupt and status flags into status */
- fusb_read_buf( FUSB_STATUS0A, 7, status->bytes);
- if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
- I2CBB::unlock2();
- }
-
+ if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
+ if (!I2CBB::lock2()) {
+ return;
+ }
+ }
+
+ /* Read the interrupt and status flags into status */
+ fusb_read_buf(FUSB_STATUS0A, 7, status->bytes);
+ if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
+ I2CBB::unlock2();
+ }
}
enum fusb_typec_current fusb_get_typec_current() {
- if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
- if (!I2CBB::lock2()) {
- return fusb_tcc_none;
- }
- }
- /* Read the BC_LVL into a variable */
- enum fusb_typec_current bc_lvl = (enum fusb_typec_current) (fusb_read_byte(
- FUSB_STATUS0) & FUSB_STATUS0_BC_LVL);
- if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
- I2CBB::unlock2();
- }
- return bc_lvl;
+ if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
+ if (!I2CBB::lock2()) {
+ return fusb_tcc_none;
+ }
+ }
+ /* Read the BC_LVL into a variable */
+ enum fusb_typec_current bc_lvl = (enum fusb_typec_current)(fusb_read_byte(FUSB_STATUS0) & FUSB_STATUS0_BC_LVL);
+ if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
+ I2CBB::unlock2();
+ }
+ return bc_lvl;
}
void fusb_reset() {
- if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
- if (!I2CBB::lock2()) {
- return;
- }
- }
-
- /* Flush the TX buffer */
- fusb_write_byte( FUSB_CONTROL0, 0x44);
- /* Flush the RX buffer */
- fusb_write_byte( FUSB_CONTROL1, FUSB_CONTROL1_RX_FLUSH);
- if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
- I2CBB::unlock2();
- }
+ if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
+ if (!I2CBB::lock2()) {
+ return;
+ }
+ }
+
+ /* Flush the TX buffer */
+ fusb_write_byte(FUSB_CONTROL0, 0x44);
+ /* Flush the RX buffer */
+ fusb_write_byte(FUSB_CONTROL1, FUSB_CONTROL1_RX_FLUSH);
+ if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
+ I2CBB::unlock2();
+ }
}
bool fusb_read_id() {
- //Return true if read of the revision ID is sane
- uint8_t version = 0;
- fusb_read_buf(FUSB_DEVICE_ID, 1, &version);
- if (version == 0 || version == 0xFF)
- return false;
- return true;
+ // Return true if read of the revision ID is sane
+ uint8_t version = 0;
+ fusb_read_buf(FUSB_DEVICE_ID, 1, &version);
+ if (version == 0 || version == 0xFF)
+ return false;
+ return true;
}
uint8_t fusb302_detect() {
- //Probe the I2C bus for its address
- return I2CBB::probe(FUSB302B_ADDR);
+ // Probe the I2C bus for its address
+ return I2CBB::probe(FUSB302B_ADDR);
}
#endif
diff --git a/source/Core/BSP/Miniware/logo.cpp b/source/Core/BSP/Miniware/logo.cpp
index e1a0f925..c6e77b53 100644
--- a/source/Core/BSP/Miniware/logo.cpp
+++ b/source/Core/BSP/Miniware/logo.cpp
@@ -8,19 +8,18 @@
#include "BSP.h"
#include "OLED.hpp"
-static uint8_t logo_page[1024] __attribute__ ((section (".logo_page")));
+static uint8_t logo_page[1024] __attribute__((section(".logo_page")));
// Logo header signature.
#define LOGO_HEADER_VALUE 0xF00DAA55
uint8_t showBootLogoIfavailable() {
-// Do not show logo data if signature is not found.
- if (LOGO_HEADER_VALUE != *(reinterpret_cast<const uint32_t*>(logo_page))) {
- return 0;
- }
+ // Do not show logo data if signature is not found.
+ if (LOGO_HEADER_VALUE != *(reinterpret_cast<const uint32_t *>(logo_page))) {
+ return 0;
+ }
- OLED::drawAreaSwapped(0, 0, 96, 16, (uint8_t*) (logo_page + 4));
- OLED::refresh();
- return 1;
+ OLED::drawAreaSwapped(0, 0, 96, 16, (uint8_t *)(logo_page + 4));
+ OLED::refresh();
+ return 1;
}
-
diff --git a/source/Core/BSP/Miniware/port.c b/source/Core/BSP/Miniware/port.c
index 5b742f0f..7ee68597 100644
--- a/source/Core/BSP/Miniware/port.c
+++ b/source/Core/BSP/Miniware/port.c
@@ -43,63 +43,63 @@
#ifndef configSYSTICK_CLOCK_HZ
#define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ
/* Ensure the SysTick is clocked at the same frequency as the core. */
-#define portNVIC_SYSTICK_CLK_BIT ( 1UL << 2UL )
+#define portNVIC_SYSTICK_CLK_BIT (1UL << 2UL)
#else
- /* The way the SysTick is clocked is not modified in case it is not the same
- as the core. */
- #define portNVIC_SYSTICK_CLK_BIT ( 0 )
+/* The way the SysTick is clocked is not modified in case it is not the same
+as the core. */
+#define portNVIC_SYSTICK_CLK_BIT (0)
#endif
/* Constants required to manipulate the core. Registers first... */
-#define portNVIC_SYSTICK_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000e010 ) )
-#define portNVIC_SYSTICK_LOAD_REG ( * ( ( volatile uint32_t * ) 0xe000e014 ) )
-#define portNVIC_SYSTICK_CURRENT_VALUE_REG ( * ( ( volatile uint32_t * ) 0xe000e018 ) )
-#define portNVIC_SYSPRI2_REG ( * ( ( volatile uint32_t * ) 0xe000ed20 ) )
+#define portNVIC_SYSTICK_CTRL_REG (*((volatile uint32_t *)0xe000e010))
+#define portNVIC_SYSTICK_LOAD_REG (*((volatile uint32_t *)0xe000e014))
+#define portNVIC_SYSTICK_CURRENT_VALUE_REG (*((volatile uint32_t *)0xe000e018))
+#define portNVIC_SYSPRI2_REG (*((volatile uint32_t *)0xe000ed20))
/* ...then bits in the registers. */
-#define portNVIC_SYSTICK_INT_BIT ( 1UL << 1UL )
-#define portNVIC_SYSTICK_ENABLE_BIT ( 1UL << 0UL )
-#define portNVIC_SYSTICK_COUNT_FLAG_BIT ( 1UL << 16UL )
-#define portNVIC_PENDSVCLEAR_BIT ( 1UL << 27UL )
-#define portNVIC_PEND_SYSTICK_CLEAR_BIT ( 1UL << 25UL )
+#define portNVIC_SYSTICK_INT_BIT (1UL << 1UL)
+#define portNVIC_SYSTICK_ENABLE_BIT (1UL << 0UL)
+#define portNVIC_SYSTICK_COUNT_FLAG_BIT (1UL << 16UL)
+#define portNVIC_PENDSVCLEAR_BIT (1UL << 27UL)
+#define portNVIC_PEND_SYSTICK_CLEAR_BIT (1UL << 25UL)
-#define portNVIC_PENDSV_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )
-#define portNVIC_SYSTICK_PRI ( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )
+#define portNVIC_PENDSV_PRI (((uint32_t)configKERNEL_INTERRUPT_PRIORITY) << 16UL)
+#define portNVIC_SYSTICK_PRI (((uint32_t)configKERNEL_INTERRUPT_PRIORITY) << 24UL)
/* Constants required to check the validity of an interrupt priority. */
-#define portFIRST_USER_INTERRUPT_NUMBER ( 16 )
-#define portNVIC_IP_REGISTERS_OFFSET_16 ( 0xE000E3F0 )
-#define portAIRCR_REG ( * ( ( volatile uint32_t * ) 0xE000ED0C ) )
-#define portMAX_8_BIT_VALUE ( ( uint8_t ) 0xff )
-#define portTOP_BIT_OF_BYTE ( ( uint8_t ) 0x80 )
-#define portMAX_PRIGROUP_BITS ( ( uint8_t ) 7 )
-#define portPRIORITY_GROUP_MASK ( 0x07UL << 8UL )
-#define portPRIGROUP_SHIFT ( 8UL )
+#define portFIRST_USER_INTERRUPT_NUMBER (16)
+#define portNVIC_IP_REGISTERS_OFFSET_16 (0xE000E3F0)
+#define portAIRCR_REG (*((volatile uint32_t *)0xE000ED0C))
+#define portMAX_8_BIT_VALUE ((uint8_t)0xff)
+#define portTOP_BIT_OF_BYTE ((uint8_t)0x80)
+#define portMAX_PRIGROUP_BITS ((uint8_t)7)
+#define portPRIORITY_GROUP_MASK (0x07UL << 8UL)
+#define portPRIGROUP_SHIFT (8UL)
/* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
-#define portVECTACTIVE_MASK ( 0xFFUL )
+#define portVECTACTIVE_MASK (0xFFUL)
/* Constants required to set up the initial stack. */
-#define portINITIAL_XPSR ( 0x01000000UL )
+#define portINITIAL_XPSR (0x01000000UL)
/* The systick is a 24-bit counter. */
-#define portMAX_24_BIT_NUMBER ( 0xffffffUL )
+#define portMAX_24_BIT_NUMBER (0xffffffUL)
/* A fiddle factor to estimate the number of SysTick counts that would have
occurred while the SysTick counter is stopped during tickless idle
calculations. */
-#define portMISSED_COUNTS_FACTOR ( 45UL )
+#define portMISSED_COUNTS_FACTOR (45UL)
/* For strict compliance with the Cortex-M spec the task start address should
have bit-0 clear, as it is loaded into the PC on exit from an ISR. */
-#define portSTART_ADDRESS_MASK ( ( StackType_t ) 0xfffffffeUL )
+#define portSTART_ADDRESS_MASK ((StackType_t)0xfffffffeUL)
/* Let the user override the pre-loading of the initial LR with the address of
prvTaskExitError() in case it messes up unwinding of the stack in the
debugger. */
#ifdef configTASK_RETURN_ADDRESS
- #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
+#define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
#else
-#define portTASK_RETURN_ADDRESS prvTaskExitError
+#define portTASK_RETURN_ADDRESS prvTaskExitError
#endif
/*
@@ -112,14 +112,14 @@ void vPortSetupTimerInterrupt(void);
/*
* Exception handlers.
*/
-void xPortPendSVHandler(void) __attribute__ (( naked ));
+void xPortPendSVHandler(void) __attribute__((naked));
void xPortSysTickHandler(void);
-void vPortSVCHandler(void) __attribute__ (( naked ));
+void vPortSVCHandler(void) __attribute__((naked));
/*
* Start first task is a separate function so it can be tested in isolation.
*/
-static void prvPortStartFirstTask(void) __attribute__ (( naked ));
+static void prvPortStartFirstTask(void) __attribute__((naked));
/*
* Used to catch tasks that attempt to return from their implementing function.
@@ -135,24 +135,24 @@ static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
/*
* The number of SysTick increments that make up one tick period.
*/
-#if( configUSE_TICKLESS_IDLE == 1 )
- static uint32_t ulTimerCountsForOneTick = 0;
+#if (configUSE_TICKLESS_IDLE == 1)
+static uint32_t ulTimerCountsForOneTick = 0;
#endif /* configUSE_TICKLESS_IDLE */
/*
* The maximum number of tick periods that can be suppressed is limited by the
* 24 bit resolution of the SysTick timer.
*/
-#if( configUSE_TICKLESS_IDLE == 1 )
- static uint32_t xMaximumPossibleSuppressedTicks = 0;
+#if (configUSE_TICKLESS_IDLE == 1)
+static uint32_t xMaximumPossibleSuppressedTicks = 0;
#endif /* configUSE_TICKLESS_IDLE */
/*
* Compensate for the CPU cycles that pass while the SysTick is stopped (low
* power functionality only.
*/
-#if( configUSE_TICKLESS_IDLE == 1 )
- static uint32_t ulStoppedTimerCompensation = 0;
+#if (configUSE_TICKLESS_IDLE == 1)
+static uint32_t ulStoppedTimerCompensation = 0;
#endif /* configUSE_TICKLESS_IDLE */
/*
@@ -160,11 +160,10 @@ static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
* FreeRTOS API functions are not called from interrupts that have been assigned
* a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
*/
-#if( configASSERT_DEFINED == 1 )
-static uint8_t ucMaxSysCallPriority = 0;
-static uint32_t ulMaxPRIGROUPValue = 0;
-static const volatile uint8_t *const pcInterruptPriorityRegisters =
- (const volatile uint8_t* const ) portNVIC_IP_REGISTERS_OFFSET_16;
+#if (configASSERT_DEFINED == 1)
+static uint8_t ucMaxSysCallPriority = 0;
+static uint32_t ulMaxPRIGROUPValue = 0;
+static const volatile uint8_t *const pcInterruptPriorityRegisters = (const volatile uint8_t *const)portNVIC_IP_REGISTERS_OFFSET_16;
#endif /* configASSERT_DEFINED */
/*-----------------------------------------------------------*/
@@ -172,79 +171,74 @@ static const volatile uint8_t *const pcInterruptPriorityRegisters =
/*
* See header file for description.
*/
-StackType_t* pxPortInitialiseStack(StackType_t *pxTopOfStack,
- TaskFunction_t pxCode, void *pvParameters) {
- /* Simulate the stack frame as it would be created by a context switch
- interrupt. */
- pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
- *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
- pxTopOfStack--;
- *pxTopOfStack = ((StackType_t) pxCode) & portSTART_ADDRESS_MASK; /* PC */
- pxTopOfStack--;
- *pxTopOfStack = (StackType_t) portTASK_RETURN_ADDRESS; /* LR */
- pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
- *pxTopOfStack = (StackType_t) pvParameters; /* R0 */
- pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
-
- return pxTopOfStack;
+StackType_t *pxPortInitialiseStack(StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters) {
+ /* Simulate the stack frame as it would be created by a context switch
+ interrupt. */
+ pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
+ *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
+ pxTopOfStack--;
+ *pxTopOfStack = ((StackType_t)pxCode) & portSTART_ADDRESS_MASK; /* PC */
+ pxTopOfStack--;
+ *pxTopOfStack = (StackType_t)portTASK_RETURN_ADDRESS; /* LR */
+ pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
+ *pxTopOfStack = (StackType_t)pvParameters; /* R0 */
+ pxTopOfStack -= 8; /* R11, R10, R9, R8, R7, R6, R5 and R4. */
+
+ return pxTopOfStack;
}
/*-----------------------------------------------------------*/
static void prvTaskExitError(void) {
- volatile uint32_t ulDummy = 0UL;
-
- /* A function that implements a task must not exit or attempt to return to
- its caller as there is nothing to return to. If a task wants to exit it
- should instead call vTaskDelete( NULL ).
-
- Artificially force an assert() to be triggered if configASSERT() is
- defined, then stop here so application writers can catch the error. */
- configASSERT(uxCriticalNesting == ~0UL);
- portDISABLE_INTERRUPTS();
- while (ulDummy == 0) {
- /* This file calls prvTaskExitError() after the scheduler has been
- started to remove a compiler warning about the function being defined
- but never called. ulDummy is used purely to quieten other warnings
- about code appearing after this function is called - making ulDummy
- volatile makes the compiler think the function could return and
- therefore not output an 'unreachable code' warning for code that appears
- after it. */
- }
+ volatile uint32_t ulDummy = 0UL;
+
+ /* A function that implements a task must not exit or attempt to return to
+ its caller as there is nothing to return to. If a task wants to exit it
+ should instead call vTaskDelete( NULL ).
+
+ Artificially force an assert() to be triggered if configASSERT() is
+ defined, then stop here so application writers can catch the error. */
+ configASSERT(uxCriticalNesting == ~0UL);
+ portDISABLE_INTERRUPTS();
+ while (ulDummy == 0) {
+ /* This file calls prvTaskExitError() after the scheduler has been
+ started to remove a compiler warning about the function being defined
+ but never called. ulDummy is used purely to quieten other warnings
+ about code appearing after this function is called - making ulDummy
+ volatile makes the compiler think the function could return and
+ therefore not output an 'unreachable code' warning for code that appears
+ after it. */
+ }
}
/*-----------------------------------------------------------*/
void vPortSVCHandler(void) {
- __asm volatile (
- " ldr r3, pxCurrentTCBConst2 \n" /* Restore the context. */
- " ldr r1, [r3] \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */
- " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
- " ldmia r0!, {r4-r11} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
- " msr psp, r0 \n" /* Restore the task stack pointer. */
- " isb \n"
- " mov r0, #0 \n"
- " msr basepri, r0 \n"
- " orr r14, #0xd \n"
- " bx r14 \n"
- " \n"
- " .align 4 \n"
- "pxCurrentTCBConst2: .word pxCurrentTCB \n"
- );
+ __asm volatile(" ldr r3, pxCurrentTCBConst2 \n" /* Restore the context. */
+ " ldr r1, [r3] \n" /* Use pxCurrentTCBConst to get the pxCurrentTCB address. */
+ " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
+ " ldmia r0!, {r4-r11} \n" /* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
+ " msr psp, r0 \n" /* Restore the task stack pointer. */
+ " isb \n"
+ " mov r0, #0 \n"
+ " msr basepri, r0 \n"
+ " orr r14, #0xd \n"
+ " bx r14 \n"
+ " \n"
+ " .align 4 \n"
+ "pxCurrentTCBConst2: .word pxCurrentTCB \n");
}
/*-----------------------------------------------------------*/
static void prvPortStartFirstTask(void) {
- __asm volatile(
- " ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */
- " ldr r0, [r0] \n"
- " ldr r0, [r0] \n"
- " msr msp, r0 \n" /* Set the msp back to the start of the stack. */
- " cpsie i \n" /* Globally enable interrupts. */
- " cpsie f \n"
- " dsb \n"
- " isb \n"
- " svc 0 \n" /* System call to start first task. */
- " nop \n"
- );
+ __asm volatile(" ldr r0, =0xE000ED08 \n" /* Use the NVIC offset register to locate the stack. */
+ " ldr r0, [r0] \n"
+ " ldr r0, [r0] \n"
+ " msr msp, r0 \n" /* Set the msp back to the start of the stack. */
+ " cpsie i \n" /* Globally enable interrupts. */
+ " cpsie f \n"
+ " dsb \n"
+ " isb \n"
+ " svc 0 \n" /* System call to start first task. */
+ " nop \n");
}
/*-----------------------------------------------------------*/
@@ -252,350 +246,332 @@ static void prvPortStartFirstTask(void) {
* See header file for description.
*/
BaseType_t xPortStartScheduler(void) {
- /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.
- See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
- configASSERT(configMAX_SYSCALL_INTERRUPT_PRIORITY);
-
-#if( configASSERT_DEFINED == 1 )
- {
- volatile uint32_t ulOriginalPriority;
- volatile uint8_t *const pucFirstUserPriorityRegister =
- (volatile uint8_t* const ) ( portNVIC_IP_REGISTERS_OFFSET_16
- + portFIRST_USER_INTERRUPT_NUMBER);
- volatile uint8_t ucMaxPriorityValue;
-
- /* Determine the maximum priority from which ISR safe FreeRTOS API
- functions can be called. ISR safe functions are those that end in
- "FromISR". FreeRTOS maintains separate thread and ISR API functions to
- ensure interrupt entry is as fast and simple as possible.
-
- Save the interrupt priority value that is about to be clobbered. */
- ulOriginalPriority = *pucFirstUserPriorityRegister;
-
- /* Determine the number of priority bits available. First write to all
- possible bits. */
- *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
-
- /* Read the value back to see how many bits stuck. */
- ucMaxPriorityValue = *pucFirstUserPriorityRegister;
-
- /* Use the same mask on the maximum system call priority. */
- ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY
- & ucMaxPriorityValue;
-
- /* Calculate the maximum acceptable priority group value for the number
- of bits read back. */
- ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;
- while ((ucMaxPriorityValue & portTOP_BIT_OF_BYTE) == portTOP_BIT_OF_BYTE) {
- ulMaxPRIGROUPValue--;
- ucMaxPriorityValue <<= (uint8_t) 0x01;
- }
+ /* configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.
+ See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html */
+ configASSERT(configMAX_SYSCALL_INTERRUPT_PRIORITY);
+
+#if (configASSERT_DEFINED == 1)
+ {
+ volatile uint32_t ulOriginalPriority;
+ volatile uint8_t *const pucFirstUserPriorityRegister = (volatile uint8_t *const)(portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER);
+ volatile uint8_t ucMaxPriorityValue;
+
+ /* Determine the maximum priority from which ISR safe FreeRTOS API
+ functions can be called. ISR safe functions are those that end in
+ "FromISR". FreeRTOS maintains separate thread and ISR API functions to
+ ensure interrupt entry is as fast and simple as possible.
+
+ Save the interrupt priority value that is about to be clobbered. */
+ ulOriginalPriority = *pucFirstUserPriorityRegister;
+
+ /* Determine the number of priority bits available. First write to all
+ possible bits. */
+ *pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
+
+ /* Read the value back to see how many bits stuck. */
+ ucMaxPriorityValue = *pucFirstUserPriorityRegister;
+
+ /* Use the same mask on the maximum system call priority. */
+ ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
+
+ /* Calculate the maximum acceptable priority group value for the number
+ of bits read back. */
+ ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;
+ while ((ucMaxPriorityValue & portTOP_BIT_OF_BYTE) == portTOP_BIT_OF_BYTE) {
+ ulMaxPRIGROUPValue--;
+ ucMaxPriorityValue <<= (uint8_t)0x01;
+ }
#ifdef __NVIC_PRIO_BITS
- {
- /* Check the CMSIS configuration that defines the number of
- priority bits matches the number of priority bits actually queried
- from the hardware. */
- configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == __NVIC_PRIO_BITS );
- }
- #endif
+ {
+ /* Check the CMSIS configuration that defines the number of
+ priority bits matches the number of priority bits actually queried
+ from the hardware. */
+ configASSERT((portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue) == __NVIC_PRIO_BITS);
+ }
+#endif
#ifdef configPRIO_BITS
- {
- /* Check the FreeRTOS configuration that defines the number of
- priority bits matches the number of priority bits actually queried
- from the hardware. */
- configASSERT( ( portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue ) == configPRIO_BITS );
- }
- #endif
-
- /* Shift the priority group value back to its position within the AIRCR
- register. */
- ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
- ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
-
- /* Restore the clobbered interrupt priority register to its original
- value. */
- *pucFirstUserPriorityRegister = ulOriginalPriority;
- }
+ {
+ /* Check the FreeRTOS configuration that defines the number of
+ priority bits matches the number of priority bits actually queried
+ from the hardware. */
+ configASSERT((portMAX_PRIGROUP_BITS - ulMaxPRIGROUPValue) == configPRIO_BITS);
+ }
+#endif
+
+ /* Shift the priority group value back to its position within the AIRCR
+ register. */
+ ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
+ ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
+
+ /* Restore the clobbered interrupt priority register to its original
+ value. */
+ *pucFirstUserPriorityRegister = ulOriginalPriority;
+ }
#endif /* conifgASSERT_DEFINED */
- /* Make PendSV and SysTick the lowest priority interrupts. */
- portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;
- portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;
+ /* Make PendSV and SysTick the lowest priority interrupts. */
+ portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;
+ portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;
- /* Start the timer that generates the tick ISR. Interrupts are disabled
- here already. */
- vPortSetupTimerInterrupt();
+ /* Start the timer that generates the tick ISR. Interrupts are disabled
+ here already. */
+ vPortSetupTimerInterrupt();
- /* Initialise the critical nesting count ready for the first task. */
- uxCriticalNesting = 0;
+ /* Initialise the critical nesting count ready for the first task. */
+ uxCriticalNesting = 0;
- /* Start the first task. */
- prvPortStartFirstTask();
+ /* Start the first task. */
+ prvPortStartFirstTask();
- /* Should never get here as the tasks will now be executing! Call the task
- exit error function to prevent compiler warnings about a static function
- not being called in the case that the application writer overrides this
- functionality by defining configTASK_RETURN_ADDRESS. Call
- vTaskSwitchContext() so link time optimisation does not remove the
- symbol. */
- vTaskSwitchContext();
- prvTaskExitError();
+ /* Should never get here as the tasks will now be executing! Call the task
+ exit error function to prevent compiler warnings about a static function
+ not being called in the case that the application writer overrides this
+ functionality by defining configTASK_RETURN_ADDRESS. Call
+ vTaskSwitchContext() so link time optimisation does not remove the
+ symbol. */
+ vTaskSwitchContext();
+ prvTaskExitError();
- /* Should not get here! */
- return 0;
+ /* Should not get here! */
+ return 0;
}
/*-----------------------------------------------------------*/
void vPortEndScheduler(void) {
- /* Not implemented in ports where there is nothing to return to.
- Artificially force an assert. */
- configASSERT(uxCriticalNesting == 1000UL);
+ /* Not implemented in ports where there is nothing to return to.
+ Artificially force an assert. */
+ configASSERT(uxCriticalNesting == 1000UL);
}
/*-----------------------------------------------------------*/
void vPortEnterCritical(void) {
- portDISABLE_INTERRUPTS();
- uxCriticalNesting++;
-
- /* This is not the interrupt safe version of the enter critical function so
- assert() if it is being called from an interrupt context. Only API
- functions that end in "FromISR" can be used in an interrupt. Only assert if
- the critical nesting count is 1 to protect against recursive calls if the
- assert function also uses a critical section. */
- if (uxCriticalNesting == 1) {
- configASSERT(( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK) == 0);
- }
+ portDISABLE_INTERRUPTS();
+ uxCriticalNesting++;
+
+ /* This is not the interrupt safe version of the enter critical function so
+ assert() if it is being called from an interrupt context. Only API
+ functions that end in "FromISR" can be used in an interrupt. Only assert if
+ the critical nesting count is 1 to protect against recursive calls if the
+ assert function also uses a critical section. */
+ if (uxCriticalNesting == 1) {
+ configASSERT((portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK) == 0);
+ }
}
/*-----------------------------------------------------------*/
void vPortExitCritical(void) {
- configASSERT(uxCriticalNesting);
- uxCriticalNesting--;
- if (uxCriticalNesting == 0) {
- portENABLE_INTERRUPTS();
- }
+ configASSERT(uxCriticalNesting);
+ uxCriticalNesting--;
+ if (uxCriticalNesting == 0) {
+ portENABLE_INTERRUPTS();
+ }
}
/*-----------------------------------------------------------*/
void xPortPendSVHandler(void) {
- /* This is a naked function. */
-
- __asm volatile
- (
- " mrs r0, psp \n"
- " isb \n"
- " \n"
- " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */
- " ldr r2, [r3] \n"
- " \n"
- " stmdb r0!, {r4-r11} \n" /* Save the remaining registers. */
- " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */
- " \n"
- " stmdb sp!, {r3, r14} \n"
- " mov r0, %0 \n"
- " msr basepri, r0 \n"
- " bl vTaskSwitchContext \n"
- " mov r0, #0 \n"
- " msr basepri, r0 \n"
- " ldmia sp!, {r3, r14} \n"
- " \n" /* Restore the context, including the critical nesting count. */
- " ldr r1, [r3] \n"
- " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
- " ldmia r0!, {r4-r11} \n" /* Pop the registers. */
- " msr psp, r0 \n"
- " isb \n"
- " bx r14 \n"
- " \n"
- " .align 4 \n"
- "pxCurrentTCBConst: .word pxCurrentTCB \n"
- ::"i"(configMAX_SYSCALL_INTERRUPT_PRIORITY)
- );
+ /* This is a naked function. */
+
+ __asm volatile(" mrs r0, psp \n"
+ " isb \n"
+ " \n"
+ " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */
+ " ldr r2, [r3] \n"
+ " \n"
+ " stmdb r0!, {r4-r11} \n" /* Save the remaining registers. */
+ " str r0, [r2] \n" /* Save the new top of stack into the first member of the TCB. */
+ " \n"
+ " stmdb sp!, {r3, r14} \n"
+ " mov r0, %0 \n"
+ " msr basepri, r0 \n"
+ " bl vTaskSwitchContext \n"
+ " mov r0, #0 \n"
+ " msr basepri, r0 \n"
+ " ldmia sp!, {r3, r14} \n"
+ " \n" /* Restore the context, including the critical nesting count. */
+ " ldr r1, [r3] \n"
+ " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
+ " ldmia r0!, {r4-r11} \n" /* Pop the registers. */
+ " msr psp, r0 \n"
+ " isb \n"
+ " bx r14 \n"
+ " \n"
+ " .align 4 \n"
+ "pxCurrentTCBConst: .word pxCurrentTCB \n" ::"i"(configMAX_SYSCALL_INTERRUPT_PRIORITY));
}
/*-----------------------------------------------------------*/
void xPortSysTickHandler(void) {
- /* The SysTick runs at the lowest interrupt priority, so when this interrupt
- executes all interrupts must be unmasked. There is therefore no need to
- save and then restore the interrupt mask value as its value is already
- known. */
- portDISABLE_INTERRUPTS();
- {
- /* Increment the RTOS tick. */
- if (xTaskIncrementTick() != pdFALSE) {
- /* A context switch is required. Context switching is performed in
- the PendSV interrupt. Pend the PendSV interrupt. */
- portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
- }
- }
- portENABLE_INTERRUPTS();
+ /* The SysTick runs at the lowest interrupt priority, so when this interrupt
+ executes all interrupts must be unmasked. There is therefore no need to
+ save and then restore the interrupt mask value as its value is already
+ known. */
+ portDISABLE_INTERRUPTS();
+ {
+ /* Increment the RTOS tick. */
+ if (xTaskIncrementTick() != pdFALSE) {
+ /* A context switch is required. Context switching is performed in
+ the PendSV interrupt. Pend the PendSV interrupt. */
+ portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
+ }
+ }
+ portENABLE_INTERRUPTS();
}
/*-----------------------------------------------------------*/
-#if( configUSE_TICKLESS_IDLE == 1 )
-
- __attribute__((weak)) void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
- {
- uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
- TickType_t xModifiableIdleTime;
-
- /* Make sure the SysTick reload value does not overflow the counter. */
- if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
- {
- xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
- }
-
- /* Stop the SysTick momentarily. The time the SysTick is stopped for
- is accounted for as best it can be, but using the tickless mode will
- inevitably result in some tiny drift of the time maintained by the
- kernel with respect to calendar time. */
- portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
-
- /* Calculate the reload value required to wait xExpectedIdleTime
- tick periods. -1 is used because this code will execute part way
- through one of the tick periods. */
- ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
- if( ulReloadValue > ulStoppedTimerCompensation )
- {
- ulReloadValue -= ulStoppedTimerCompensation;
- }
-
- /* Enter a critical section but don't use the taskENTER_CRITICAL()
- method as that will mask interrupts that should exit sleep mode. */
- __asm volatile( "cpsid i" ::: "memory" );
- __asm volatile( "dsb" );
- __asm volatile( "isb" );
-
- /* If a context switch is pending or a task is waiting for the scheduler
- to be unsuspended then abandon the low power entry. */
- if( eTaskConfirmSleepModeStatus() == eAbortSleep )
- {
- /* Restart from whatever is left in the count register to complete
- this tick period. */
- portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
-
- /* Restart SysTick. */
- portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
-
- /* Reset the reload register to the value required for normal tick
- periods. */
- portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
-
- /* Re-enable interrupts - see comments above the cpsid instruction()
- above. */
- __asm volatile( "cpsie i" ::: "memory" );
- }
- else
- {
- /* Set the new reload value. */
- portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
-
- /* Clear the SysTick count flag and set the count value back to
- zero. */
- portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
-
- /* Restart SysTick. */
- portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
-
- /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
- set its parameter to 0 to indicate that its implementation contains
- its own wait for interrupt or wait for event instruction, and so wfi
- should not be executed again. However, the original expected idle
- time variable must remain unmodified, so a copy is taken. */
- xModifiableIdleTime = xExpectedIdleTime;
- configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
- if( xModifiableIdleTime > 0 )
- {
- __asm volatile( "dsb" ::: "memory" );
- __asm volatile( "wfi" );
- __asm volatile( "isb" );
- }
- configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
-
- /* Re-enable interrupts to allow the interrupt that brought the MCU
- out of sleep mode to execute immediately. see comments above
- __disable_interrupt() call above. */
- __asm volatile( "cpsie i" ::: "memory" );
- __asm volatile( "dsb" );
- __asm volatile( "isb" );
-
- /* Disable interrupts again because the clock is about to be stopped
- and interrupts that execute while the clock is stopped will increase
- any slippage between the time maintained by the RTOS and calendar
- time. */
- __asm volatile( "cpsid i" ::: "memory" );
- __asm volatile( "dsb" );
- __asm volatile( "isb" );
-
- /* Disable the SysTick clock without reading the
- portNVIC_SYSTICK_CTRL_REG register to ensure the
- portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
- the time the SysTick is stopped for is accounted for as best it can
- be, but using the tickless mode will inevitably result in some tiny
- drift of the time maintained by the kernel with respect to calendar
- time*/
- portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT );
-
- /* Determine if the SysTick clock has already counted to zero and
- been set back to the current reload value (the reload back being
- correct for the entire expected idle time) or if the SysTick is yet
- to count to zero (in which case an interrupt other than the SysTick
- must have brought the system out of sleep mode). */
- if( ( portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
- {
- uint32_t ulCalculatedLoadValue;
-
- /* The tick interrupt is already pending, and the SysTick count
- reloaded with ulReloadValue. Reset the
- portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
- period. */
- ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
-
- /* Don't allow a tiny value, or values that have somehow
- underflowed because the post sleep hook did something
- that took too long. */
- if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
- {
- ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
- }
-
- portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
-
- /* As the pending tick will be processed as soon as this
- function exits, the tick value maintained by the tick is stepped
- forward by one less than the time spent waiting. */
- ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
- }
- else
- {
- /* Something other than the tick interrupt ended the sleep.
- Work out how long the sleep lasted rounded to complete tick
- periods (not the ulReload value which accounted for part
- ticks). */
- ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
-
- /* How many complete tick periods passed while the processor
- was waiting? */
- ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
-
- /* The reload value is set to whatever fraction of a single tick
- period remains. */
- portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1UL ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
- }
-
- /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
- again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
- value. */
- portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
- portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
- vTaskStepTick( ulCompleteTickPeriods );
- portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
-
- /* Exit with interrupts enabled. */
- __asm volatile( "cpsie i" ::: "memory" );
- }
- }
+#if (configUSE_TICKLESS_IDLE == 1)
+
+__attribute__((weak)) void vPortSuppressTicksAndSleep(TickType_t xExpectedIdleTime) {
+ uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements;
+ TickType_t xModifiableIdleTime;
+
+ /* Make sure the SysTick reload value does not overflow the counter. */
+ if (xExpectedIdleTime > xMaximumPossibleSuppressedTicks) {
+ xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
+ }
+
+ /* Stop the SysTick momentarily. The time the SysTick is stopped for
+ is accounted for as best it can be, but using the tickless mode will
+ inevitably result in some tiny drift of the time maintained by the
+ kernel with respect to calendar time. */
+ portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
+
+ /* Calculate the reload value required to wait xExpectedIdleTime
+ tick periods. -1 is used because this code will execute part way
+ through one of the tick periods. */
+ ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + (ulTimerCountsForOneTick * (xExpectedIdleTime - 1UL));
+ if (ulReloadValue > ulStoppedTimerCompensation) {
+ ulReloadValue -= ulStoppedTimerCompensation;
+ }
+
+ /* Enter a critical section but don't use the taskENTER_CRITICAL()
+ method as that will mask interrupts that should exit sleep mode. */
+ __asm volatile("cpsid i" ::: "memory");
+ __asm volatile("dsb");
+ __asm volatile("isb");
+
+ /* If a context switch is pending or a task is waiting for the scheduler
+ to be unsuspended then abandon the low power entry. */
+ if (eTaskConfirmSleepModeStatus() == eAbortSleep) {
+ /* Restart from whatever is left in the count register to complete
+ this tick period. */
+ portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
+
+ /* Restart SysTick. */
+ portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
+
+ /* Reset the reload register to the value required for normal tick
+ periods. */
+ portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
+
+ /* Re-enable interrupts - see comments above the cpsid instruction()
+ above. */
+ __asm volatile("cpsie i" ::: "memory");
+ } else {
+ /* Set the new reload value. */
+ portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
+
+ /* Clear the SysTick count flag and set the count value back to
+ zero. */
+ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
+
+ /* Restart SysTick. */
+ portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
+
+ /* Sleep until something happens. configPRE_SLEEP_PROCESSING() can
+ set its parameter to 0 to indicate that its implementation contains
+ its own wait for interrupt or wait for event instruction, and so wfi
+ should not be executed again. However, the original expected idle
+ time variable must remain unmodified, so a copy is taken. */
+ xModifiableIdleTime = xExpectedIdleTime;
+ configPRE_SLEEP_PROCESSING(xModifiableIdleTime);
+ if (xModifiableIdleTime > 0) {
+ __asm volatile("dsb" ::: "memory");
+ __asm volatile("wfi");
+ __asm volatile("isb");
+ }
+ configPOST_SLEEP_PROCESSING(xExpectedIdleTime);
+
+ /* Re-enable interrupts to allow the interrupt that brought the MCU
+ out of sleep mode to execute immediately. see comments above
+ __disable_interrupt() call above. */
+ __asm volatile("cpsie i" ::: "memory");
+ __asm volatile("dsb");
+ __asm volatile("isb");
+
+ /* Disable interrupts again because the clock is about to be stopped
+ and interrupts that execute while the clock is stopped will increase
+ any slippage between the time maintained by the RTOS and calendar
+ time. */
+ __asm volatile("cpsid i" ::: "memory");
+ __asm volatile("dsb");
+ __asm volatile("isb");
+
+ /* Disable the SysTick clock without reading the
+ portNVIC_SYSTICK_CTRL_REG register to ensure the
+ portNVIC_SYSTICK_COUNT_FLAG_BIT is not cleared if it is set. Again,
+ the time the SysTick is stopped for is accounted for as best it can
+ be, but using the tickless mode will inevitably result in some tiny
+ drift of the time maintained by the kernel with respect to calendar
+ time*/
+ portNVIC_SYSTICK_CTRL_REG = (portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT);
+
+ /* Determine if the SysTick clock has already counted to zero and
+ been set back to the current reload value (the reload back being
+ correct for the entire expected idle time) or if the SysTick is yet
+ to count to zero (in which case an interrupt other than the SysTick
+ must have brought the system out of sleep mode). */
+ if ((portNVIC_SYSTICK_CTRL_REG & portNVIC_SYSTICK_COUNT_FLAG_BIT) != 0) {
+ uint32_t ulCalculatedLoadValue;
+
+ /* The tick interrupt is already pending, and the SysTick count
+ reloaded with ulReloadValue. Reset the
+ portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
+ period. */
+ ulCalculatedLoadValue = (ulTimerCountsForOneTick - 1UL) - (ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG);
+
+ /* Don't allow a tiny value, or values that have somehow
+ underflowed because the post sleep hook did something
+ that took too long. */
+ if ((ulCalculatedLoadValue < ulStoppedTimerCompensation) || (ulCalculatedLoadValue > ulTimerCountsForOneTick)) {
+ ulCalculatedLoadValue = (ulTimerCountsForOneTick - 1UL);
+ }
+
+ portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
+
+ /* As the pending tick will be processed as soon as this
+ function exits, the tick value maintained by the tick is stepped
+ forward by one less than the time spent waiting. */
+ ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
+ } else {
+ /* Something other than the tick interrupt ended the sleep.
+ Work out how long the sleep lasted rounded to complete tick
+ periods (not the ulReload value which accounted for part
+ ticks). */
+ ulCompletedSysTickDecrements = (xExpectedIdleTime * ulTimerCountsForOneTick) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
+
+ /* How many complete tick periods passed while the processor
+ was waiting? */
+ ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
+
+ /* The reload value is set to whatever fraction of a single tick
+ period remains. */
+ portNVIC_SYSTICK_LOAD_REG = ((ulCompleteTickPeriods + 1UL) * ulTimerCountsForOneTick) - ulCompletedSysTickDecrements;
+ }
+
+ /* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
+ again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
+ value. */
+ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
+ portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
+ vTaskStepTick(ulCompleteTickPeriods);
+ portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
+
+ /* Exit with interrupts enabled. */
+ __asm volatile("cpsie i" ::: "memory");
+ }
+}
#endif /* configUSE_TICKLESS_IDLE */
/*-----------------------------------------------------------*/
@@ -604,84 +580,80 @@ void xPortSysTickHandler(void) {
* Setup the systick timer to generate the tick interrupts at the required
* frequency.
*/
-__attribute__(( weak )) void vPortSetupTimerInterrupt(void) {
- /* Calculate the constants required to configure the tick interrupt. */
-#if( configUSE_TICKLESS_IDLE == 1 )
- {
- ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
- xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
- ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
- }
- #endif /* configUSE_TICKLESS_IDLE */
-
- /* Stop and clear the SysTick. */
- portNVIC_SYSTICK_CTRL_REG = 0UL;
- portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
-
- /* Configure SysTick to interrupt at the requested rate. */
- portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ)
- - 1UL;
- portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT
- | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT);
+__attribute__((weak)) void vPortSetupTimerInterrupt(void) {
+ /* Calculate the constants required to configure the tick interrupt. */
+#if (configUSE_TICKLESS_IDLE == 1)
+ {
+ ulTimerCountsForOneTick = (configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ);
+ xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
+ ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / (configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ);
+ }
+#endif /* configUSE_TICKLESS_IDLE */
+
+ /* Stop and clear the SysTick. */
+ portNVIC_SYSTICK_CTRL_REG = 0UL;
+ portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
+
+ /* Configure SysTick to interrupt at the requested rate. */
+ portNVIC_SYSTICK_LOAD_REG = (configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ) - 1UL;
+ portNVIC_SYSTICK_CTRL_REG = (portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT);
}
/*-----------------------------------------------------------*/
-#if( configASSERT_DEFINED == 1 )
+#if (configASSERT_DEFINED == 1)
void vPortValidateInterruptPriority(void) {
- uint32_t ulCurrentInterrupt;
- uint8_t ucCurrentPriority;
-
- /* Obtain the number of the currently executing interrupt. */
- __asm volatile( "mrs %0, ipsr" : "=r"( ulCurrentInterrupt ) :: "memory" );
-
- /* Is the interrupt number a user defined interrupt? */
- if (ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER) {
- /* Look up the interrupt's priority. */
- ucCurrentPriority = pcInterruptPriorityRegisters[ulCurrentInterrupt];
-
- /* The following assertion will fail if a service routine (ISR) for
- an interrupt that has been assigned a priority above
- configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
- function. ISR safe FreeRTOS API functions must *only* be called
- from interrupts that have been assigned a priority at or below
- configMAX_SYSCALL_INTERRUPT_PRIORITY.
-
- Numerically low interrupt priority numbers represent logically high
- interrupt priorities, therefore the priority of the interrupt must
- be set to a value equal to or numerically *higher* than
- configMAX_SYSCALL_INTERRUPT_PRIORITY.
-
- Interrupts that use the FreeRTOS API must not be left at their
- default priority of zero as that is the highest possible priority,
- which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
- and therefore also guaranteed to be invalid.
-
- FreeRTOS maintains separate thread and ISR API functions to ensure
- interrupt entry is as fast and simple as possible.
-
- The following links provide detailed information:
- http://www.freertos.org/RTOS-Cortex-M3-M4.html
- http://www.freertos.org/FAQHelp.html */
- configASSERT(ucCurrentPriority >= ucMaxSysCallPriority);
- }
-
- /* Priority grouping: The interrupt controller (NVIC) allows the bits
- that define each interrupt's priority to be split between bits that
- define the interrupt's pre-emption priority bits and bits that define
- the interrupt's sub-priority. For simplicity all bits must be defined
- to be pre-emption priority bits. The following assertion will fail if
- this is not the case (if some bits represent a sub-priority).
-
- If the application only uses CMSIS libraries for interrupt
- configuration then the correct setting can be achieved on all Cortex-M
- devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
- scheduler. Note however that some vendor specific peripheral libraries
- assume a non-zero priority group setting, in which cases using a value
- of zero will result in unpredictable behaviour. */
- configASSERT(
- ( portAIRCR_REG & portPRIORITY_GROUP_MASK) <= ulMaxPRIGROUPValue);
+ uint32_t ulCurrentInterrupt;
+ uint8_t ucCurrentPriority;
+
+ /* Obtain the number of the currently executing interrupt. */
+ __asm volatile("mrs %0, ipsr" : "=r"(ulCurrentInterrupt)::"memory");
+
+ /* Is the interrupt number a user defined interrupt? */
+ if (ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER) {
+ /* Look up the interrupt's priority. */
+ ucCurrentPriority = pcInterruptPriorityRegisters[ulCurrentInterrupt];
+
+ /* The following assertion will fail if a service routine (ISR) for
+ an interrupt that has been assigned a priority above
+ configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
+ function. ISR safe FreeRTOS API functions must *only* be called
+ from interrupts that have been assigned a priority at or below
+ configMAX_SYSCALL_INTERRUPT_PRIORITY.
+
+ Numerically low interrupt priority numbers represent logically high
+ interrupt priorities, therefore the priority of the interrupt must
+ be set to a value equal to or numerically *higher* than
+ configMAX_SYSCALL_INTERRUPT_PRIORITY.
+
+ Interrupts that use the FreeRTOS API must not be left at their
+ default priority of zero as that is the highest possible priority,
+ which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
+ and therefore also guaranteed to be invalid.
+
+ FreeRTOS maintains separate thread and ISR API functions to ensure
+ interrupt entry is as fast and simple as possible.
+
+ The following links provide detailed information:
+ http://www.freertos.org/RTOS-Cortex-M3-M4.html
+ http://www.freertos.org/FAQHelp.html */
+ configASSERT(ucCurrentPriority >= ucMaxSysCallPriority);
+ }
+
+ /* Priority grouping: The interrupt controller (NVIC) allows the bits
+ that define each interrupt's priority to be split between bits that
+ define the interrupt's pre-emption priority bits and bits that define
+ the interrupt's sub-priority. For simplicity all bits must be defined
+ to be pre-emption priority bits. The following assertion will fail if
+ this is not the case (if some bits represent a sub-priority).
+
+ If the application only uses CMSIS libraries for interrupt
+ configuration then the correct setting can be achieved on all Cortex-M
+ devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
+ scheduler. Note however that some vendor specific peripheral libraries
+ assume a non-zero priority group setting, in which cases using a value
+ of zero will result in unpredictable behaviour. */
+ configASSERT((portAIRCR_REG & portPRIORITY_GROUP_MASK) <= ulMaxPRIGROUPValue);
}
#endif /* configASSERT_DEFINED */
-
diff --git a/source/Core/BSP/Miniware/postRTOS.cpp b/source/Core/BSP/Miniware/postRTOS.cpp
index d0743771..34cd8e33 100644
--- a/source/Core/BSP/Miniware/postRTOS.cpp
+++ b/source/Core/BSP/Miniware/postRTOS.cpp
@@ -1,21 +1,21 @@
#include "BSP.h"
#include "FreeRTOS.h"
+#include "I2C_Wrapper.hpp"
#include "QC3.h"
#include "Settings.h"
#include "cmsis_os.h"
+#include "fusbpd.h"
#include "main.hpp"
#include "power.hpp"
#include "stdlib.h"
#include "task.h"
-#include "I2C_Wrapper.hpp"
-#include "fusbpd.h"
// Initialisation to be performed with scheduler active
void postRToSInit() {
#ifdef POW_PD
- if (usb_pd_detect() == true) {
- //Spawn all of the USB-C processors
- fusb302_start_processing();
- }
+ if (usb_pd_detect() == true) {
+ // Spawn all of the USB-C processors
+ fusb302_start_processing();
+ }
#endif
}
diff --git a/source/Core/BSP/Miniware/preRTOS.cpp b/source/Core/BSP/Miniware/preRTOS.cpp
index e1d38434..5d9852b4 100644
--- a/source/Core/BSP/Miniware/preRTOS.cpp
+++ b/source/Core/BSP/Miniware/preRTOS.cpp
@@ -5,22 +5,22 @@
* Author: Ralim
*/
-#include <I2C_Wrapper.hpp>
#include "BSP.h"
-#include "Setup.h"
-#include "Pins.h"
#include "I2CBB.hpp"
-#include "fusbpd.h"
#include "Model_Config.h"
+#include "Pins.h"
+#include "Setup.h"
+#include "fusbpd.h"
+#include <I2C_Wrapper.hpp>
void preRToSInit() {
- /* Reset of all peripherals, Initializes the Flash interface and the Systick.
- */
- HAL_Init();
- Setup_HAL(); // Setup all the HAL objects
- BSPInit();
+ /* Reset of all peripherals, Initializes the Flash interface and the Systick.
+ */
+ HAL_Init();
+ Setup_HAL(); // Setup all the HAL objects
+ BSPInit();
#ifdef I2C_SOFT
- I2CBB::init();
+ I2CBB::init();
#endif
- /* Init the IPC objects */
- FRToSI2C::FRToSInit();
+ /* Init the IPC objects */
+ FRToSI2C::FRToSInit();
}
diff --git a/source/Core/BSP/Miniware/stm32f1xx_hal_msp.c b/source/Core/BSP/Miniware/stm32f1xx_hal_msp.c
index 058fb241..5f6f7624 100644
--- a/source/Core/BSP/Miniware/stm32f1xx_hal_msp.c
+++ b/source/Core/BSP/Miniware/stm32f1xx_hal_msp.c
@@ -1,141 +1,132 @@
#include "Pins.h"
-#include "stm32f1xx_hal.h"
#include "Setup.h"
+#include "stm32f1xx_hal.h"
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void) {
- __HAL_RCC_AFIO_CLK_ENABLE()
- ;
-
- HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
-
- /* System interrupt init*/
- /* MemoryManagement_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(MemoryManagement_IRQn, 0, 0);
- /* BusFault_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(BusFault_IRQn, 0, 0);
- /* UsageFault_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(UsageFault_IRQn, 0, 0);
- /* SVCall_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(SVCall_IRQn, 0, 0);
- /* DebugMonitor_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(DebugMonitor_IRQn, 0, 0);
- /* PendSV_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(PendSV_IRQn, 15, 0);
- /* SysTick_IRQn interrupt configuration */
- HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0);
-
+ __HAL_RCC_AFIO_CLK_ENABLE();
+
+ HAL_NVIC_SetPriorityGrouping(NVIC_PRIORITYGROUP_4);
+
+ /* System interrupt init*/
+ /* MemoryManagement_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(MemoryManagement_IRQn, 0, 0);
+ /* BusFault_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(BusFault_IRQn, 0, 0);
+ /* UsageFault_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(UsageFault_IRQn, 0, 0);
+ /* SVCall_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(SVCall_IRQn, 0, 0);
+ /* DebugMonitor_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(DebugMonitor_IRQn, 0, 0);
+ /* PendSV_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(PendSV_IRQn, 15, 0);
+ /* SysTick_IRQn interrupt configuration */
+ HAL_NVIC_SetPriority(SysTick_IRQn, 15, 0);
}
void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) {
- GPIO_InitTypeDef GPIO_InitStruct;
- if (hadc->Instance == ADC1) {
- __HAL_RCC_ADC1_CLK_ENABLE()
- ;
-
- /* ADC1 DMA Init */
- /* ADC1 Init */
- hdma_adc1.Instance = DMA1_Channel1;
- hdma_adc1.Init.Direction = DMA_PERIPH_TO_MEMORY;
- hdma_adc1.Init.PeriphInc = DMA_PINC_DISABLE;
- hdma_adc1.Init.MemInc = DMA_MINC_ENABLE;
- hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
- hdma_adc1.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
- hdma_adc1.Init.Mode = DMA_CIRCULAR;
- hdma_adc1.Init.Priority = DMA_PRIORITY_MEDIUM;
- HAL_DMA_Init(&hdma_adc1);
-
- __HAL_LINKDMA(hadc, DMA_Handle, hdma_adc1);
-
- /* ADC1 interrupt Init */
- HAL_NVIC_SetPriority(ADC1_2_IRQn, 15, 0);
- HAL_NVIC_EnableIRQ(ADC1_2_IRQn);
- } else {
- __HAL_RCC_ADC2_CLK_ENABLE()
- ;
-
- /**ADC2 GPIO Configuration
- PB0 ------> ADC2_IN8
- PB1 ------> ADC2_IN9
- */
- GPIO_InitStruct.Pin = TIP_TEMP_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
- HAL_GPIO_Init(TIP_TEMP_GPIO_Port, &GPIO_InitStruct);
- GPIO_InitStruct.Pin = TMP36_INPUT_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
- HAL_GPIO_Init(TMP36_INPUT_GPIO_Port, &GPIO_InitStruct);
- GPIO_InitStruct.Pin = VIN_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
- HAL_GPIO_Init(VIN_GPIO_Port, &GPIO_InitStruct);
-
- /* ADC2 interrupt Init */
- HAL_NVIC_SetPriority(ADC1_2_IRQn, 15, 0);
- HAL_NVIC_EnableIRQ(ADC1_2_IRQn);
- }
-
+ GPIO_InitTypeDef GPIO_InitStruct;
+ if (hadc->Instance == ADC1) {
+ __HAL_RCC_ADC1_CLK_ENABLE();
+
+ /* ADC1 DMA Init */
+ /* ADC1 Init */
+ hdma_adc1.Instance = DMA1_Channel1;
+ hdma_adc1.Init.Direction = DMA_PERIPH_TO_MEMORY;
+ hdma_adc1.Init.PeriphInc = DMA_PINC_DISABLE;
+ hdma_adc1.Init.MemInc = DMA_MINC_ENABLE;
+ hdma_adc1.Init.PeriphDataAlignment = DMA_PDATAALIGN_WORD;
+ hdma_adc1.Init.MemDataAlignment = DMA_MDATAALIGN_WORD;
+ hdma_adc1.Init.Mode = DMA_CIRCULAR;
+ hdma_adc1.Init.Priority = DMA_PRIORITY_MEDIUM;
+ HAL_DMA_Init(&hdma_adc1);
+
+ __HAL_LINKDMA(hadc, DMA_Handle, hdma_adc1);
+
+ /* ADC1 interrupt Init */
+ HAL_NVIC_SetPriority(ADC1_2_IRQn, 15, 0);
+ HAL_NVIC_EnableIRQ(ADC1_2_IRQn);
+ } else {
+ __HAL_RCC_ADC2_CLK_ENABLE();
+
+ /**ADC2 GPIO Configuration
+ PB0 ------> ADC2_IN8
+ PB1 ------> ADC2_IN9
+ */
+ GPIO_InitStruct.Pin = TIP_TEMP_Pin;
+ GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
+ HAL_GPIO_Init(TIP_TEMP_GPIO_Port, &GPIO_InitStruct);
+ GPIO_InitStruct.Pin = TMP36_INPUT_Pin;
+ GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
+ HAL_GPIO_Init(TMP36_INPUT_GPIO_Port, &GPIO_InitStruct);
+ GPIO_InitStruct.Pin = VIN_Pin;
+ GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
+ HAL_GPIO_Init(VIN_GPIO_Port, &GPIO_InitStruct);
+
+ /* ADC2 interrupt Init */
+ HAL_NVIC_SetPriority(ADC1_2_IRQn, 15, 0);
+ HAL_NVIC_EnableIRQ(ADC1_2_IRQn);
+ }
}
void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) {
- GPIO_InitTypeDef GPIO_InitStruct;
- /**I2C1 GPIO Configuration
- PB6 ------> I2C1_SCL
- PB7 ------> I2C1_SDA
- */
- GPIO_InitStruct.Pin = SCL_Pin | SDA_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
- GPIO_InitStruct.Pull = GPIO_PULLUP;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
- HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
-
- /* Peripheral clock enable */
- __HAL_RCC_I2C1_CLK_ENABLE()
- ;
- /* I2C1 DMA Init */
- /* I2C1_RX Init */
- hdma_i2c1_rx.Instance = DMA1_Channel7;
- hdma_i2c1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
- hdma_i2c1_rx.Init.PeriphInc = DMA_PINC_DISABLE;
- hdma_i2c1_rx.Init.MemInc = DMA_MINC_ENABLE;
- hdma_i2c1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
- hdma_i2c1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
- hdma_i2c1_rx.Init.Mode = DMA_NORMAL;
- hdma_i2c1_rx.Init.Priority = DMA_PRIORITY_LOW;
- HAL_DMA_Init(&hdma_i2c1_rx);
-
- __HAL_LINKDMA(hi2c, hdmarx, hdma_i2c1_rx);
-
- /* I2C1_TX Init */
- hdma_i2c1_tx.Instance = DMA1_Channel6;
- hdma_i2c1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
- hdma_i2c1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
- hdma_i2c1_tx.Init.MemInc = DMA_MINC_ENABLE;
- hdma_i2c1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
- hdma_i2c1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
- hdma_i2c1_tx.Init.Mode = DMA_NORMAL;
- hdma_i2c1_tx.Init.Priority = DMA_PRIORITY_MEDIUM;
- HAL_DMA_Init(&hdma_i2c1_tx);
-
- __HAL_LINKDMA(hi2c, hdmatx, hdma_i2c1_tx);
-
- /* I2C1 interrupt Init */
- HAL_NVIC_SetPriority(I2C1_EV_IRQn, 15, 0);
- HAL_NVIC_EnableIRQ(I2C1_EV_IRQn);
- HAL_NVIC_SetPriority(I2C1_ER_IRQn, 15, 0);
- HAL_NVIC_EnableIRQ(I2C1_ER_IRQn);
-
+ GPIO_InitTypeDef GPIO_InitStruct;
+ /**I2C1 GPIO Configuration
+ PB6 ------> I2C1_SCL
+ PB7 ------> I2C1_SDA
+ */
+ GPIO_InitStruct.Pin = SCL_Pin | SDA_Pin;
+ GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
+ GPIO_InitStruct.Pull = GPIO_PULLUP;
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
+ HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
+
+ /* Peripheral clock enable */
+ __HAL_RCC_I2C1_CLK_ENABLE();
+ /* I2C1 DMA Init */
+ /* I2C1_RX Init */
+ hdma_i2c1_rx.Instance = DMA1_Channel7;
+ hdma_i2c1_rx.Init.Direction = DMA_PERIPH_TO_MEMORY;
+ hdma_i2c1_rx.Init.PeriphInc = DMA_PINC_DISABLE;
+ hdma_i2c1_rx.Init.MemInc = DMA_MINC_ENABLE;
+ hdma_i2c1_rx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
+ hdma_i2c1_rx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
+ hdma_i2c1_rx.Init.Mode = DMA_NORMAL;
+ hdma_i2c1_rx.Init.Priority = DMA_PRIORITY_LOW;
+ HAL_DMA_Init(&hdma_i2c1_rx);
+
+ __HAL_LINKDMA(hi2c, hdmarx, hdma_i2c1_rx);
+
+ /* I2C1_TX Init */
+ hdma_i2c1_tx.Instance = DMA1_Channel6;
+ hdma_i2c1_tx.Init.Direction = DMA_MEMORY_TO_PERIPH;
+ hdma_i2c1_tx.Init.PeriphInc = DMA_PINC_DISABLE;
+ hdma_i2c1_tx.Init.MemInc = DMA_MINC_ENABLE;
+ hdma_i2c1_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE;
+ hdma_i2c1_tx.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE;
+ hdma_i2c1_tx.Init.Mode = DMA_NORMAL;
+ hdma_i2c1_tx.Init.Priority = DMA_PRIORITY_MEDIUM;
+ HAL_DMA_Init(&hdma_i2c1_tx);
+
+ __HAL_LINKDMA(hi2c, hdmatx, hdma_i2c1_tx);
+
+ /* I2C1 interrupt Init */
+ HAL_NVIC_SetPriority(I2C1_EV_IRQn, 15, 0);
+ HAL_NVIC_EnableIRQ(I2C1_EV_IRQn);
+ HAL_NVIC_SetPriority(I2C1_ER_IRQn, 15, 0);
+ HAL_NVIC_EnableIRQ(I2C1_ER_IRQn);
}
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim_base) {
- if (htim_base->Instance == TIM3) {
- /* Peripheral clock enable */
- __HAL_RCC_TIM3_CLK_ENABLE()
- ;
- } else if (htim_base->Instance == TIM2) {
- /* Peripheral clock enable */
- __HAL_RCC_TIM2_CLK_ENABLE()
- ;
- }
+ if (htim_base->Instance == TIM3) {
+ /* Peripheral clock enable */
+ __HAL_RCC_TIM3_CLK_ENABLE();
+ } else if (htim_base->Instance == TIM2) {
+ /* Peripheral clock enable */
+ __HAL_RCC_TIM2_CLK_ENABLE();
+ }
}
diff --git a/source/Core/BSP/Miniware/stm32f1xx_hal_timebase_TIM.c b/source/Core/BSP/Miniware/stm32f1xx_hal_timebase_TIM.c
index 033a3f80..db48d90b 100644
--- a/source/Core/BSP/Miniware/stm32f1xx_hal_timebase_TIM.c
+++ b/source/Core/BSP/Miniware/stm32f1xx_hal_timebase_TIM.c
@@ -62,7 +62,7 @@
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
TIM_HandleTypeDef htim1;
-uint32_t uwIncrementState = 0;
+uint32_t uwIncrementState = 0;
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
@@ -76,49 +76,49 @@ uint32_t uwIncrementState = 0;
* @retval HAL status
*/
HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) {
- RCC_ClkInitTypeDef clkconfig;
- uint32_t uwTimclock = 0;
- uint32_t uwPrescalerValue = 0;
- uint32_t pFLatency;
-
- /*Configure the TIM1 IRQ priority */
- HAL_NVIC_SetPriority(TIM1_UP_IRQn, TickPriority, 0);
-
- /* Enable the TIM1 global Interrupt */
- HAL_NVIC_EnableIRQ(TIM1_UP_IRQn);
-
- /* Enable TIM1 clock */
- __HAL_RCC_TIM1_CLK_ENABLE();
-
- /* Get clock configuration */
- HAL_RCC_GetClockConfig(&clkconfig, &pFLatency);
-
- /* Compute TIM1 clock */
- uwTimclock = HAL_RCC_GetPCLK2Freq();
-
- /* Compute the prescaler value to have TIM1 counter clock equal to 1MHz */
- uwPrescalerValue = (uint32_t) ((uwTimclock / 1000000) - 1);
-
- /* Initialize TIM1 */
- htim1.Instance = TIM1;
-
- /* Initialize TIMx peripheral as follow:
- + Period = [(TIM1CLK/1000) - 1]. to have a (1/1000) s time base.
- + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock.
- + ClockDivision = 0
- + Counter direction = Up
- */
- htim1.Init.Period = (1000000 / 1000) - 1;
- htim1.Init.Prescaler = uwPrescalerValue;
- htim1.Init.ClockDivision = 0;
- htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
- if (HAL_TIM_Base_Init(&htim1) == HAL_OK) {
- /* Start the TIM time Base generation in interrupt mode */
- return HAL_TIM_Base_Start_IT(&htim1);
- }
-
- /* Return function status */
- return HAL_ERROR;
+ RCC_ClkInitTypeDef clkconfig;
+ uint32_t uwTimclock = 0;
+ uint32_t uwPrescalerValue = 0;
+ uint32_t pFLatency;
+
+ /*Configure the TIM1 IRQ priority */
+ HAL_NVIC_SetPriority(TIM1_UP_IRQn, TickPriority, 0);
+
+ /* Enable the TIM1 global Interrupt */
+ HAL_NVIC_EnableIRQ(TIM1_UP_IRQn);
+
+ /* Enable TIM1 clock */
+ __HAL_RCC_TIM1_CLK_ENABLE();
+
+ /* Get clock configuration */
+ HAL_RCC_GetClockConfig(&clkconfig, &pFLatency);
+
+ /* Compute TIM1 clock */
+ uwTimclock = HAL_RCC_GetPCLK2Freq();
+
+ /* Compute the prescaler value to have TIM1 counter clock equal to 1MHz */
+ uwPrescalerValue = (uint32_t)((uwTimclock / 1000000) - 1);
+
+ /* Initialize TIM1 */
+ htim1.Instance = TIM1;
+
+ /* Initialize TIMx peripheral as follow:
+ + Period = [(TIM1CLK/1000) - 1]. to have a (1/1000) s time base.
+ + Prescaler = (uwTimclock/1000000 - 1) to have a 1MHz counter clock.
+ + ClockDivision = 0
+ + Counter direction = Up
+ */
+ htim1.Init.Period = (1000000 / 1000) - 1;
+ htim1.Init.Prescaler = uwPrescalerValue;
+ htim1.Init.ClockDivision = 0;
+ htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
+ if (HAL_TIM_Base_Init(&htim1) == HAL_OK) {
+ /* Start the TIM time Base generation in interrupt mode */
+ return HAL_TIM_Base_Start_IT(&htim1);
+ }
+
+ /* Return function status */
+ return HAL_ERROR;
}
/**
@@ -128,8 +128,8 @@ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) {
* @retval None
*/
void HAL_SuspendTick(void) {
- /* Disable TIM1 update Interrupt */
- __HAL_TIM_DISABLE_IT(&htim1, TIM_IT_UPDATE);
+ /* Disable TIM1 update Interrupt */
+ __HAL_TIM_DISABLE_IT(&htim1, TIM_IT_UPDATE);
}
/**
@@ -139,8 +139,8 @@ void HAL_SuspendTick(void) {
* @retval None
*/
void HAL_ResumeTick(void) {
- /* Enable TIM1 Update interrupt */
- __HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE);
+ /* Enable TIM1 Update interrupt */
+ __HAL_TIM_ENABLE_IT(&htim1, TIM_IT_UPDATE);
}
/**
diff --git a/source/Core/BSP/Miniware/stm32f1xx_it.c b/source/Core/BSP/Miniware/stm32f1xx_it.c
index a38190b4..ce9fa3b4 100644
--- a/source/Core/BSP/Miniware/stm32f1xx_it.c
+++ b/source/Core/BSP/Miniware/stm32f1xx_it.c
@@ -1,42 +1,34 @@
// This is the stock standard STM interrupt file full of handlers
-#include "stm32f1xx_hal.h"
-#include "stm32f1xx.h"
#include "stm32f1xx_it.h"
-#include "cmsis_os.h"
#include "Setup.h"
+#include "cmsis_os.h"
+#include "stm32f1xx.h"
+#include "stm32f1xx_hal.h"
-extern TIM_HandleTypeDef htim1; //used for the systick
+extern TIM_HandleTypeDef htim1; // used for the systick
/******************************************************************************/
/* Cortex-M3 Processor Interruption and Exception Handlers */
/******************************************************************************/
-void NMI_Handler(void) {
-}
+void NMI_Handler(void) {}
-//We have the assembly for a breakpoint trigger here to halt the system when a debugger is connected
+// We have the assembly for a breakpoint trigger here to halt the system when a debugger is connected
// Hardfault handler, often a screwup in the code
-void HardFault_Handler(void) {
-}
+void HardFault_Handler(void) {}
// Memory management unit had an error
-void MemManage_Handler(void) {
-}
+void MemManage_Handler(void) {}
// Prefetcher or busfault occured
-void BusFault_Handler(void) {
-}
+void BusFault_Handler(void) {}
-void UsageFault_Handler(void) {
-}
+void UsageFault_Handler(void) {}
-void DebugMon_Handler(void) {
-}
+void DebugMon_Handler(void) {}
// Systick is used by FreeRTOS tick
-void SysTick_Handler(void) {
- osSystickHandler();
-}
+void SysTick_Handler(void) { osSystickHandler(); }
/******************************************************************************/
/* STM32F1xx Peripheral Interrupt Handlers */
@@ -46,42 +38,22 @@ void SysTick_Handler(void) {
/******************************************************************************/
// DMA used to move the ADC readings into system ram
-void DMA1_Channel1_IRQHandler(void) {
- HAL_DMA_IRQHandler(&hdma_adc1);
-}
-//ADC interrupt used for DMA
-void ADC1_2_IRQHandler(void) {
- HAL_ADC_IRQHandler(&hadc1);
-}
-
-//Timer 1 has overflowed, used for HAL ticks
-void TIM1_UP_IRQHandler(void) {
- HAL_TIM_IRQHandler(&htim1);
-}
-//Timer 3 is used for the PWM output to the tip
-void TIM3_IRQHandler(void) {
- HAL_TIM_IRQHandler(&htim3);
-}
-
-//Timer 2 is used for co-ordination of PWM & ADC
-void TIM2_IRQHandler(void) {
- HAL_TIM_IRQHandler(&htim2);
-}
-
-void I2C1_EV_IRQHandler(void) {
- HAL_I2C_EV_IRQHandler(&hi2c1);
-}
-void I2C1_ER_IRQHandler(void) {
- HAL_I2C_ER_IRQHandler(&hi2c1);
-}
-
-void DMA1_Channel6_IRQHandler(void) {
- HAL_DMA_IRQHandler(&hdma_i2c1_tx);
-}
-
-void DMA1_Channel7_IRQHandler(void) {
- HAL_DMA_IRQHandler(&hdma_i2c1_rx);
-}
-void EXTI9_5_IRQHandler(void) {
- HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_9);
-}
+void DMA1_Channel1_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_adc1); }
+// ADC interrupt used for DMA
+void ADC1_2_IRQHandler(void) { HAL_ADC_IRQHandler(&hadc1); }
+
+// Timer 1 has overflowed, used for HAL ticks
+void TIM1_UP_IRQHandler(void) { HAL_TIM_IRQHandler(&htim1); }
+// Timer 3 is used for the PWM output to the tip
+void TIM3_IRQHandler(void) { HAL_TIM_IRQHandler(&htim3); }
+
+// Timer 2 is used for co-ordination of PWM & ADC
+void TIM2_IRQHandler(void) { HAL_TIM_IRQHandler(&htim2); }
+
+void I2C1_EV_IRQHandler(void) { HAL_I2C_EV_IRQHandler(&hi2c1); }
+void I2C1_ER_IRQHandler(void) { HAL_I2C_ER_IRQHandler(&hi2c1); }
+
+void DMA1_Channel6_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_i2c1_tx); }
+
+void DMA1_Channel7_IRQHandler(void) { HAL_DMA_IRQHandler(&hdma_i2c1_rx); }
+void EXTI9_5_IRQHandler(void) { HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_9); }
diff --git a/source/Core/BSP/Miniware/system_stm32f1xx.c b/source/Core/BSP/Miniware/system_stm32f1xx.c
index 08dee014..19a323e4 100644
--- a/source/Core/BSP/Miniware/system_stm32f1xx.c
+++ b/source/Core/BSP/Miniware/system_stm32f1xx.c
@@ -2,10 +2,11 @@
// And as such, is BSD licneced from STM
#include "stm32f1xx.h"
-#if !defined (HSI_VALUE)
- #define HSI_VALUE 8000000U /*!< Default value of the Internal oscillator in Hz.
- This value can be provided and adapted by the user application. */
-#endif /* HSI_VALUE */
+#if !defined(HSI_VALUE)
+#define HSI_VALUE \
+ 8000000U /*!< Default value of the Internal oscillator in Hz. \
+ This value can be provided and adapted by the user application. */
+#endif /* HSI_VALUE */
/*!< Uncomment the following line if you need to use external SRAM */
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
@@ -13,23 +14,23 @@
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
#ifndef VECT_TAB_OFFSET
-#define VECT_TAB_OFFSET 0x00004000U /*!< Vector Table base offset field.
- This value must be a multiple of 0x200. */
-//We offset this by 0x4000 to because of the bootloader
+#define VECT_TAB_OFFSET \
+ 0x00004000U /*!< Vector Table base offset field. \
+ This value must be a multiple of 0x200. */
+// We offset this by 0x4000 to because of the bootloader
#endif
/*******************************************************************************
* Clock Definitions
*******************************************************************************/
-#if defined(STM32F100xB) ||defined(STM32F100xE)
- uint32_t SystemCoreClock = 24000000U; /*!< System Clock Frequency (Core Clock) */
-#else /*!< HSI Selected as System Clock source */
+#if defined(STM32F100xB) || defined(STM32F100xE)
+uint32_t SystemCoreClock = 24000000U; /*!< System Clock Frequency (Core Clock) */
+#else /*!< HSI Selected as System Clock source */
uint32_t SystemCoreClock = 64000000U; /*!< System Clock Frequency (Core Clock) */
#endif
-const uint8_t AHBPrescTable[16U] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7,
- 8, 9 };
-const uint8_t APBPrescTable[8U] = { 0, 0, 0, 0, 1, 2, 3, 4 };
+const uint8_t AHBPrescTable[16U] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
+const uint8_t APBPrescTable[8U] = {0, 0, 0, 0, 1, 2, 3, 4};
/**
* @brief Setup the microcontroller system
@@ -40,57 +41,57 @@ const uint8_t APBPrescTable[8U] = { 0, 0, 0, 0, 1, 2, 3, 4 };
* @retval None
*/
void SystemInit(void) {
- /* Reset the RCC clock configuration to the default reset state(for debug purpose) */
- /* Set HSION bit */
- RCC->CR |= 0x00000001U;
+ /* Reset the RCC clock configuration to the default reset state(for debug purpose) */
+ /* Set HSION bit */
+ RCC->CR |= 0x00000001U;
- /* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */
+ /* Reset SW, HPRE, PPRE1, PPRE2, ADCPRE and MCO bits */
#if !defined(STM32F105xC) && !defined(STM32F107xC)
- RCC->CFGR &= 0xF8FF0000U;
+ RCC->CFGR &= 0xF8FF0000U;
#else
- RCC->CFGR &= 0xF0FF0000U;
-#endif /* STM32F105xC */
+ RCC->CFGR &= 0xF0FF0000U;
+#endif /* STM32F105xC */
- /* Reset HSEON, CSSON and PLLON bits */
- RCC->CR &= 0xFEF6FFFFU;
+ /* Reset HSEON, CSSON and PLLON bits */
+ RCC->CR &= 0xFEF6FFFFU;
- /* Reset HSEBYP bit */
- RCC->CR &= 0xFFFBFFFFU;
+ /* Reset HSEBYP bit */
+ RCC->CR &= 0xFFFBFFFFU;
- /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */
- RCC->CFGR &= 0xFF80FFFFU;
+ /* Reset PLLSRC, PLLXTPRE, PLLMUL and USBPRE/OTGFSPRE bits */
+ RCC->CFGR &= 0xFF80FFFFU;
#if defined(STM32F105xC) || defined(STM32F107xC)
- /* Reset PLL2ON and PLL3ON bits */
- RCC->CR &= 0xEBFFFFFFU;
+ /* Reset PLL2ON and PLL3ON bits */
+ RCC->CR &= 0xEBFFFFFFU;
- /* Disable all interrupts and clear pending bits */
- RCC->CIR = 0x00FF0000U;
+ /* Disable all interrupts and clear pending bits */
+ RCC->CIR = 0x00FF0000U;
- /* Reset CFGR2 register */
- RCC->CFGR2 = 0x00000000U;
+ /* Reset CFGR2 register */
+ RCC->CFGR2 = 0x00000000U;
#elif defined(STM32F100xB) || defined(STM32F100xE)
- /* Disable all interrupts and clear pending bits */
- RCC->CIR = 0x009F0000U;
+ /* Disable all interrupts and clear pending bits */
+ RCC->CIR = 0x009F0000U;
- /* Reset CFGR2 register */
- RCC->CFGR2 = 0x00000000U;
+ /* Reset CFGR2 register */
+ RCC->CFGR2 = 0x00000000U;
#else
- /* Disable all interrupts and clear pending bits */
- RCC->CIR = 0x009F0000U;
+ /* Disable all interrupts and clear pending bits */
+ RCC->CIR = 0x009F0000U;
#endif /* STM32F105xC */
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
- #ifdef DATA_IN_ExtSRAM
- SystemInit_ExtMemCtl();
- #endif /* DATA_IN_ExtSRAM */
-#endif
+#ifdef DATA_IN_ExtSRAM
+ SystemInit_ExtMemCtl();
+#endif /* DATA_IN_ExtSRAM */
+#endif
#ifdef VECT_TAB_SRAM
SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */
#else
- SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */
-#endif
+ SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH. */
+#endif
}
/**
@@ -129,7 +130,7 @@ void SystemInit(void) {
* @retval None
*/
void SystemCoreClockUpdate(void) {
- uint32_t tmp = 0U, pllmull = 0U, pllsource = 0U;
+ uint32_t tmp = 0U, pllmull = 0U, pllsource = 0U;
#if defined(STM32F105xC) || defined(STM32F107xC)
uint32_t prediv1source = 0U, prediv1factor = 0U, prediv2factor = 0U, pll2mull = 0U;
@@ -139,116 +140,106 @@ void SystemCoreClockUpdate(void) {
uint32_t prediv1factor = 0U;
#endif /* STM32F100xB or STM32F100xE */
- /* Get SYSCLK source -------------------------------------------------------*/
- tmp = RCC->CFGR & RCC_CFGR_SWS;
-
- switch (tmp) {
- case 0x00U: /* HSI used as system clock */
- SystemCoreClock = HSI_VALUE;
- break;
- case 0x04U: /* HSE used as system clock */
- SystemCoreClock = HSE_VALUE;
- break;
- case 0x08U: /* PLL used as system clock */
-
- /* Get PLL clock source and multiplication factor ----------------------*/
- pllmull = RCC->CFGR & RCC_CFGR_PLLMULL;
- pllsource = RCC->CFGR & RCC_CFGR_PLLSRC;
-
-#if !defined(STM32F105xC) && !defined(STM32F107xC)
- pllmull = (pllmull >> 18U) + 2U;
-
- if (pllsource == 0x00U) {
- /* HSI oscillator clock divided by 2 selected as PLL clock entry */
- SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
- } else {
+ /* Get SYSCLK source -------------------------------------------------------*/
+ tmp = RCC->CFGR & RCC_CFGR_SWS;
+
+ switch (tmp) {
+ case 0x00U: /* HSI used as system clock */
+ SystemCoreClock = HSI_VALUE;
+ break;
+ case 0x04U: /* HSE used as system clock */
+ SystemCoreClock = HSE_VALUE;
+ break;
+ case 0x08U: /* PLL used as system clock */
+
+ /* Get PLL clock source and multiplication factor ----------------------*/
+ pllmull = RCC->CFGR & RCC_CFGR_PLLMULL;
+ pllsource = RCC->CFGR & RCC_CFGR_PLLSRC;
+
+#if !defined(STM32F105xC) && !defined(STM32F107xC)
+ pllmull = (pllmull >> 18U) + 2U;
+
+ if (pllsource == 0x00U) {
+ /* HSI oscillator clock divided by 2 selected as PLL clock entry */
+ SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
+ } else {
#if defined(STM32F100xB) || defined(STM32F100xE)
- prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
- /* HSE oscillator clock selected as PREDIV1 clock entry */
- SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
- #else
- /* HSE selected as PLL clock entry */
- if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t) RESET) {/* HSE oscillator clock divided by 2 */
- SystemCoreClock = (HSE_VALUE >> 1U) * pllmull;
- } else {
- SystemCoreClock = HSE_VALUE * pllmull;
- }
-#endif
- }
+ prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
+ /* HSE oscillator clock selected as PREDIV1 clock entry */
+ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
#else
- pllmull = pllmull >> 18U;
-
- if (pllmull != 0x0DU)
- {
- pllmull += 2U;
+ /* HSE selected as PLL clock entry */
+ if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET) { /* HSE oscillator clock divided by 2 */
+ SystemCoreClock = (HSE_VALUE >> 1U) * pllmull;
+ } else {
+ SystemCoreClock = HSE_VALUE * pllmull;
}
- else
- { /* PLL multiplication factor = PLL input clock * 6.5 */
- pllmull = 13U / 2U;
- }
-
- if (pllsource == 0x00U)
- {
- /* HSI oscillator clock divided by 2 selected as PLL clock entry */
- SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
- }
- else
- {/* PREDIV1 selected as PLL clock entry */
-
- /* Get PREDIV1 clock source and division factor */
- prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC;
- prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
-
- if (prediv1source == 0U)
- {
- /* HSE oscillator clock selected as PREDIV1 clock entry */
- SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
- }
- else
- {/* PLL2 clock selected as PREDIV1 clock entry */
-
- /* Get PREDIV2 division factor and PLL2 multiplication factor */
- prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4U) + 1U;
- pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8U) + 2U;
- SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull;
- }
+#endif
+ }
+#else
+ pllmull = pllmull >> 18U;
+
+ if (pllmull != 0x0DU) {
+ pllmull += 2U;
+ } else { /* PLL multiplication factor = PLL input clock * 6.5 */
+ pllmull = 13U / 2U;
+ }
+
+ if (pllsource == 0x00U) {
+ /* HSI oscillator clock divided by 2 selected as PLL clock entry */
+ SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
+ } else { /* PREDIV1 selected as PLL clock entry */
+
+ /* Get PREDIV1 clock source and division factor */
+ prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC;
+ prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
+
+ if (prediv1source == 0U) {
+ /* HSE oscillator clock selected as PREDIV1 clock entry */
+ SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
+ } else { /* PLL2 clock selected as PREDIV1 clock entry */
+
+ /* Get PREDIV2 division factor and PLL2 multiplication factor */
+ prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4U) + 1U;
+ pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8U) + 2U;
+ SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull;
}
-#endif /* STM32F105xC */
- break;
-
- default:
- SystemCoreClock = HSI_VALUE;
- break;
- }
-
- /* Compute HCLK clock frequency ----------------*/
- /* Get HCLK prescaler */
- tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)];
- /* HCLK clock frequency */
- SystemCoreClock >>= tmp;
+ }
+#endif /* STM32F105xC */
+ break;
+
+ default:
+ SystemCoreClock = HSI_VALUE;
+ break;
+ }
+
+ /* Compute HCLK clock frequency ----------------*/
+ /* Get HCLK prescaler */
+ tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)];
+ /* HCLK clock frequency */
+ SystemCoreClock >>= tmp;
}
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
/**
- * @brief Setup the external memory controller. Called in startup_stm32f1xx.s
- * before jump to __main
- * @param None
- * @retval None
- */
+ * @brief Setup the external memory controller. Called in startup_stm32f1xx.s
+ * before jump to __main
+ * @param None
+ * @retval None
+ */
#ifdef DATA_IN_ExtSRAM
/**
- * @brief Setup the external memory controller.
- * Called in startup_stm32f1xx_xx.s/.c before jump to main.
- * This function configures the external SRAM mounted on STM3210E-EVAL
- * board (STM32 High density devices). This SRAM will be used as program
- * data memory (including heap and stack).
- * @param None
- * @retval None
- */
-void SystemInit_ExtMemCtl(void)
-{
+ * @brief Setup the external memory controller.
+ * Called in startup_stm32f1xx_xx.s/.c before jump to main.
+ * This function configures the external SRAM mounted on STM3210E-EVAL
+ * board (STM32 High density devices). This SRAM will be used as program
+ * data memory (including heap and stack).
+ * @param None
+ * @retval None
+ */
+void SystemInit_ExtMemCtl(void) {
__IO uint32_t tmpreg;
- /*!< FSMC Bank1 NOR/SRAM3 is used for the STM3210E-EVAL, if another Bank is
+ /*!< FSMC Bank1 NOR/SRAM3 is used for the STM3210E-EVAL, if another Bank is
required, then adjust the Register Addresses */
/* Enable FSMC clock */
@@ -256,36 +247,36 @@ void SystemInit_ExtMemCtl(void)
/* Delay after an RCC peripheral clock enabling */
tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FSMCEN);
-
+
/* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */
RCC->APB2ENR = 0x000001E0U;
-
+
/* Delay after an RCC peripheral clock enabling */
tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPDEN);
(void)(tmpreg);
-
-/* --------------- SRAM Data lines, NOE and NWE configuration ---------------*/
-/*---------------- SRAM Address lines configuration -------------------------*/
-/*---------------- NOE and NWE configuration --------------------------------*/
-/*---------------- NE3 configuration ----------------------------------------*/
-/*---------------- NBL0, NBL1 configuration ---------------------------------*/
-
- GPIOD->CRL = 0x44BB44BBU;
+
+ /* --------------- SRAM Data lines, NOE and NWE configuration ---------------*/
+ /*---------------- SRAM Address lines configuration -------------------------*/
+ /*---------------- NOE and NWE configuration --------------------------------*/
+ /*---------------- NE3 configuration ----------------------------------------*/
+ /*---------------- NBL0, NBL1 configuration ---------------------------------*/
+
+ GPIOD->CRL = 0x44BB44BBU;
GPIOD->CRH = 0xBBBBBBBBU;
- GPIOE->CRL = 0xB44444BBU;
+ GPIOE->CRL = 0xB44444BBU;
GPIOE->CRH = 0xBBBBBBBBU;
- GPIOF->CRL = 0x44BBBBBBU;
+ GPIOF->CRL = 0x44BBBBBBU;
GPIOF->CRH = 0xBBBB4444U;
- GPIOG->CRL = 0x44BBBBBBU;
+ GPIOG->CRL = 0x44BBBBBBU;
GPIOG->CRH = 0x444B4B44U;
-
-/*---------------- FSMC Configuration ---------------------------------------*/
-/*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/
-
+
+ /*---------------- FSMC Configuration ---------------------------------------*/
+ /*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/
+
FSMC_Bank1->BTCR[4U] = 0x00001091U;
FSMC_Bank1->BTCR[5U] = 0x00110212U;
}
diff --git a/source/Core/Drivers/BMA223.cpp b/source/Core/Drivers/BMA223.cpp
index 4da4ae76..cffe109d 100644
--- a/source/Core/Drivers/BMA223.cpp
+++ b/source/Core/Drivers/BMA223.cpp
@@ -9,56 +9,55 @@
#include <array>
bool BMA223::detect() {
- if (FRToSI2C::probe(BMA223_ADDRESS)) {
- //Read chip id to ensure its not an address collision
- uint8_t id = 0;
- if (FRToSI2C::Mem_Read(BMA223_ADDRESS, BMA223_BGW_CHIPID, &id, 1)) {
- return id == 0b11111000;
- }
- }
-
- return false;
+ if (FRToSI2C::probe(BMA223_ADDRESS)) {
+ // Read chip id to ensure its not an address collision
+ uint8_t id = 0;
+ if (FRToSI2C::Mem_Read(BMA223_ADDRESS, BMA223_BGW_CHIPID, &id, 1)) {
+ return id == 0b11111000;
+ }
+ }
+
+ return false;
}
-static const FRToSI2C::I2C_REG i2c_registers[] = { //
- //
- { BMA223_PMU_RANGE, 0b00000011, 0 }, //2G range
- { BMA223_PMU_BW, 0b00001101, 0 }, //250Hz filter
- { BMA223_PMU_LPW, 0b00000000, 0 }, //Full power
- { BMA223_ACCD_HBW, 0b00000000, 0 }, //filtered data out
- { BMA223_INT_OUT_CTRL, 0b00001010, 0 }, //interrupt active low and OD to get it hi-z
- { BMA223_INT_RST_LATCH, 0b10000000, 0 }, //interrupt active low and OD to get it hi-z
- { BMA223_INT_EN_0, 0b01000000, 0 }, //Enable orientation
- { BMA223_INT_A, 0b00100111, 0 }, //Setup orientation detection
-
- //
- };
+static const FRToSI2C::I2C_REG i2c_registers[] = {
+ //
+ //
+ {BMA223_PMU_RANGE, 0b00000011, 0}, // 2G range
+ {BMA223_PMU_BW, 0b00001101, 0}, // 250Hz filter
+ {BMA223_PMU_LPW, 0b00000000, 0}, // Full power
+ {BMA223_ACCD_HBW, 0b00000000, 0}, // filtered data out
+ {BMA223_INT_OUT_CTRL, 0b00001010, 0}, // interrupt active low and OD to get it hi-z
+ {BMA223_INT_RST_LATCH, 0b10000000, 0}, // interrupt active low and OD to get it hi-z
+ {BMA223_INT_EN_0, 0b01000000, 0}, // Enable orientation
+ {BMA223_INT_A, 0b00100111, 0}, // Setup orientation detection
+
+ //
+};
bool BMA223::initalize() {
- //Setup acceleration readings
- //2G range
- //bandwidth = 250Hz
- //High pass filter on (Slow compensation)
- //Turn off IRQ output pins
- //Orientation recognition in symmetrical mode
- // Hysteresis is set to ~ 16 counts
- //Theta blocking is set to 0b10
-
- return FRToSI2C::writeRegistersBulk(BMA223_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0]));
-
+ // Setup acceleration readings
+ // 2G range
+ // bandwidth = 250Hz
+ // High pass filter on (Slow compensation)
+ // Turn off IRQ output pins
+ // Orientation recognition in symmetrical mode
+ // Hysteresis is set to ~ 16 counts
+ // Theta blocking is set to 0b10
+
+ return FRToSI2C::writeRegistersBulk(BMA223_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0]));
}
void BMA223::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) {
- //The BMA is odd in that its output data width is only 8 bits
- //And yet there are MSB and LSB registers _sigh_.
- uint8_t sensorData[6] = { 0, 0, 0, 0, 0, 0 };
-
- if (FRToSI2C::Mem_Read(BMA223_ADDRESS, BMA223_ACCD_X_LSB, sensorData, 6) == false) {
- x = y = z = 0;
- return;
- }
- //Shift 6 to make its range ~= the other accelerometers
- x = sensorData[1] << 6;
- y = sensorData[3] << 6;
- z = sensorData[5] << 6;
-
+ // The BMA is odd in that its output data width is only 8 bits
+ // And yet there are MSB and LSB registers _sigh_.
+ uint8_t sensorData[6] = {0, 0, 0, 0, 0, 0};
+
+ if (FRToSI2C::Mem_Read(BMA223_ADDRESS, BMA223_ACCD_X_LSB, sensorData, 6) == false) {
+ x = y = z = 0;
+ return;
+ }
+ // Shift 6 to make its range ~= the other accelerometers
+ x = sensorData[1] << 6;
+ y = sensorData[3] << 6;
+ z = sensorData[5] << 6;
}
diff --git a/source/Core/Drivers/Buttons.cpp b/source/Core/Drivers/Buttons.cpp
index e252ab8c..8cc83b88 100644
--- a/source/Core/Drivers/Buttons.cpp
+++ b/source/Core/Drivers/Buttons.cpp
@@ -4,112 +4,112 @@
* Created on: 29 May 2020
* Author: Ralim
*/
-#include <Buttons.hpp>
#include "FreeRTOS.h"
-#include "task.h"
#include "gui.hpp"
+#include "task.h"
+#include <Buttons.hpp>
uint32_t lastButtonTime = 0;
ButtonState getButtonState() {
- /*
- * Read in the buttons and then determine if a state change needs to occur
- */
+ /*
+ * Read in the buttons and then determine if a state change needs to occur
+ */
- /*
- * If the previous state was 00 Then we want to latch the new state if
- * different & update time
- * If the previous state was !00 Then we want to search if we trigger long
- * press (buttons still down), or if release we trigger press
- * (downtime>filter)
- */
- static uint8_t previousState = 0;
- static uint32_t previousStateChange = 0;
- const uint16_t timeout = 400;
- uint8_t currentState;
- currentState = (getButtonA()) << 0;
- currentState |= (getButtonB()) << 1;
+ /*
+ * If the previous state was 00 Then we want to latch the new state if
+ * different & update time
+ * If the previous state was !00 Then we want to search if we trigger long
+ * press (buttons still down), or if release we trigger press
+ * (downtime>filter)
+ */
+ static uint8_t previousState = 0;
+ static uint32_t previousStateChange = 0;
+ const uint16_t timeout = 400;
+ uint8_t currentState;
+ currentState = (getButtonA()) << 0;
+ currentState |= (getButtonB()) << 1;
- if (currentState)
- lastButtonTime = xTaskGetTickCount();
- if (currentState == previousState) {
- if (currentState == 0)
- return BUTTON_NONE;
- if ((xTaskGetTickCount() - previousStateChange) > timeout) {
- // User has been holding the button down
- // We want to send a button is held message
- if (currentState == 0x01)
- return BUTTON_F_LONG;
- else if (currentState == 0x02)
- return BUTTON_B_LONG;
- else
- return BUTTON_BOTH_LONG; // Both being held case
- } else
- return BUTTON_NONE;
- } else {
- // A change in button state has occurred
- ButtonState retVal = BUTTON_NONE;
- if (currentState) {
- // User has pressed a button down (nothing done on down)
- if (currentState != previousState) {
- // There has been a change in the button states
- // If there is a rising edge on one of the buttons from double press we
- // want to mask that out As users are having issues with not release
- // both at once
- if (previousState == 0x03)
- currentState = 0x03;
- }
- } else {
- // User has released buttons
- // If they previously had the buttons down we want to check if they were <
- // long hold and trigger a press
- if ((xTaskGetTickCount() - previousStateChange) < timeout) {
- // The user didn't hold the button for long
- // So we send button press
+ if (currentState)
+ lastButtonTime = xTaskGetTickCount();
+ if (currentState == previousState) {
+ if (currentState == 0)
+ return BUTTON_NONE;
+ if ((xTaskGetTickCount() - previousStateChange) > timeout) {
+ // User has been holding the button down
+ // We want to send a button is held message
+ if (currentState == 0x01)
+ return BUTTON_F_LONG;
+ else if (currentState == 0x02)
+ return BUTTON_B_LONG;
+ else
+ return BUTTON_BOTH_LONG; // Both being held case
+ } else
+ return BUTTON_NONE;
+ } else {
+ // A change in button state has occurred
+ ButtonState retVal = BUTTON_NONE;
+ if (currentState) {
+ // User has pressed a button down (nothing done on down)
+ if (currentState != previousState) {
+ // There has been a change in the button states
+ // If there is a rising edge on one of the buttons from double press we
+ // want to mask that out As users are having issues with not release
+ // both at once
+ if (previousState == 0x03)
+ currentState = 0x03;
+ }
+ } else {
+ // User has released buttons
+ // If they previously had the buttons down we want to check if they were <
+ // long hold and trigger a press
+ if ((xTaskGetTickCount() - previousStateChange) < timeout) {
+ // The user didn't hold the button for long
+ // So we send button press
- if (previousState == 0x01)
- retVal = BUTTON_F_SHORT;
- else if (previousState == 0x02)
- retVal = BUTTON_B_SHORT;
- else
- retVal = BUTTON_BOTH; // Both being held case
- }
- }
- previousState = currentState;
- previousStateChange = xTaskGetTickCount();
- return retVal;
- }
- return BUTTON_NONE;
+ if (previousState == 0x01)
+ retVal = BUTTON_F_SHORT;
+ else if (previousState == 0x02)
+ retVal = BUTTON_B_SHORT;
+ else
+ retVal = BUTTON_BOTH; // Both being held case
+ }
+ }
+ previousState = currentState;
+ previousStateChange = xTaskGetTickCount();
+ return retVal;
+ }
+ return BUTTON_NONE;
}
void waitForButtonPress() {
- // we are just lazy and sleep until user confirms button press
- // This also eats the button press event!
- ButtonState buttons = getButtonState();
- while (buttons) {
- buttons = getButtonState();
- GUIDelay();
- }
- while (!buttons) {
- buttons = getButtonState();
- GUIDelay();
- }
+ // we are just lazy and sleep until user confirms button press
+ // This also eats the button press event!
+ ButtonState buttons = getButtonState();
+ while (buttons) {
+ buttons = getButtonState();
+ GUIDelay();
+ }
+ while (!buttons) {
+ buttons = getButtonState();
+ GUIDelay();
+ }
}
void waitForButtonPressOrTimeout(uint32_t timeout) {
- timeout += xTaskGetTickCount();
- // calculate the exit point
+ timeout += xTaskGetTickCount();
+ // calculate the exit point
- ButtonState buttons = getButtonState();
- while (buttons) {
- buttons = getButtonState();
- GUIDelay();
- if (xTaskGetTickCount() > timeout)
- return;
- }
- while (!buttons) {
- buttons = getButtonState();
- GUIDelay();
- if (xTaskGetTickCount() > timeout)
- return;
- }
+ ButtonState buttons = getButtonState();
+ while (buttons) {
+ buttons = getButtonState();
+ GUIDelay();
+ if (xTaskGetTickCount() > timeout)
+ return;
+ }
+ while (!buttons) {
+ buttons = getButtonState();
+ GUIDelay();
+ if (xTaskGetTickCount() > timeout)
+ return;
+ }
}
diff --git a/source/Core/Drivers/FUSB302/fusbpd.cpp b/source/Core/Drivers/FUSB302/fusbpd.cpp
index f8624fbe..56539f28 100644
--- a/source/Core/Drivers/FUSB302/fusbpd.cpp
+++ b/source/Core/Drivers/FUSB302/fusbpd.cpp
@@ -6,23 +6,23 @@
*/
#include "Model_Config.h"
#ifdef POW_PD
-#include <fusbpd.h>
-#include <pd.h>
#include "BSP.h"
#include "I2CBB.hpp"
#include "fusb302b.h"
+#include "int_n.h"
#include "policy_engine.h"
#include "protocol_rx.h"
#include "protocol_tx.h"
-#include "int_n.h"
+#include <fusbpd.h>
+#include <pd.h>
void fusb302_start_processing() {
- /* Initialize the FUSB302B */
- if (fusb_setup()) {
- PolicyEngine::init();
- ProtocolTransmit::init();
- ProtocolReceive::init();
- InterruptHandler::init();
- }
+ /* Initialize the FUSB302B */
+ if (fusb_setup()) {
+ PolicyEngine::init();
+ ProtocolTransmit::init();
+ ProtocolReceive::init();
+ InterruptHandler::init();
+ }
}
#endif
diff --git a/source/Core/Drivers/FUSB302/int_n.cpp b/source/Core/Drivers/FUSB302/int_n.cpp
index 9250b4a0..892dbfe2 100644
--- a/source/Core/Drivers/FUSB302/int_n.cpp
+++ b/source/Core/Drivers/FUSB302/int_n.cpp
@@ -16,65 +16,63 @@
*/
#include "int_n.h"
-#include "fusbpd.h"
-#include <pd.h>
+#include "BSP.h"
#include "fusb302b.h"
-#include "protocol_rx.h"
-#include "protocol_tx.h"
+#include "fusbpd.h"
#include "policy_engine.h"
#include "protocol_rx.h"
#include "protocol_tx.h"
#include "task.h"
-#include "BSP.h"
+#include <pd.h>
-osThreadId InterruptHandler::TaskHandle = NULL;
-uint32_t InterruptHandler::TaskBuffer[InterruptHandler::TaskStackSize];
+osThreadId InterruptHandler::TaskHandle = NULL;
+uint32_t InterruptHandler::TaskBuffer[InterruptHandler::TaskStackSize];
osStaticThreadDef_t InterruptHandler::TaskControlBlock;
void InterruptHandler::init() {
- osThreadStaticDef(intTask, Thread, PDB_PRIO_PRL_INT_N, 0, TaskStackSize, TaskBuffer, &TaskControlBlock);
- TaskHandle = osThreadCreate(osThread(intTask), NULL);
+ osThreadStaticDef(intTask, Thread, PDB_PRIO_PRL_INT_N, 0, TaskStackSize, TaskBuffer, &TaskControlBlock);
+ TaskHandle = osThreadCreate(osThread(intTask), NULL);
}
void InterruptHandler::Thread(const void *arg) {
- (void) arg;
- union fusb_status status;
- while (true) {
- /* If the INT_N line is low */
- if (xTaskNotifyWait(0x00, 0x0F, NULL, PolicyEngine::setupCompleteOrTimedOut() ? 1000 : 10) == pdPASS) {
- //delay slightly so we catch the crc with better timing
- osDelay(1);
- }
- /* Read the FUSB302B status and interrupt registers */
- fusb_get_status(&status);
- /* If the I_TXSENT or I_RETRYFAIL flag is set, tell the Protocol TX
- * thread */
- if (status.interrupta & FUSB_INTERRUPTA_I_TXSENT) {
- ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_I_TXSENT);
- }
- if (status.interrupta & FUSB_INTERRUPTA_I_RETRYFAIL) {
- ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_I_RETRYFAIL);
- }
+ (void)arg;
+ union fusb_status status;
+ while (true) {
+ /* If the INT_N line is low */
+ if (xTaskNotifyWait(0x00, 0x0F, NULL, PolicyEngine::setupCompleteOrTimedOut() ? 1000 : 10) == pdPASS) {
+ // delay slightly so we catch the crc with better timing
+ osDelay(1);
+ }
+ /* Read the FUSB302B status and interrupt registers */
+ fusb_get_status(&status);
+ /* If the I_TXSENT or I_RETRYFAIL flag is set, tell the Protocol TX
+ * thread */
+ if (status.interrupta & FUSB_INTERRUPTA_I_TXSENT) {
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_I_TXSENT);
+ }
+ if (status.interrupta & FUSB_INTERRUPTA_I_RETRYFAIL) {
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_I_RETRYFAIL);
+ }
- /* If the I_GCRCSENT flag is set, tell the Protocol RX thread */
- //This means a message was recieved with a good CRC
- if (status.interruptb & FUSB_INTERRUPTB_I_GCRCSENT) {
- ProtocolReceive::notify(PDB_EVT_PRLRX_I_GCRCSENT);
- }
+ /* If the I_GCRCSENT flag is set, tell the Protocol RX thread */
+ // This means a message was recieved with a good CRC
+ if (status.interruptb & FUSB_INTERRUPTB_I_GCRCSENT) {
+ ProtocolReceive::notify(PDB_EVT_PRLRX_I_GCRCSENT);
+ }
- /* If the I_OCP_TEMP and OVRTEMP flags are set, tell the Policy
- * Engine thread */
- if ((status.interrupta & FUSB_INTERRUPTA_I_OCP_TEMP) && (status.status1 & FUSB_STATUS1_OVRTEMP)) {
- PolicyEngine::notify(PDB_EVT_PE_I_OVRTEMP);
- }
- }
+ /* If the I_OCP_TEMP and OVRTEMP flags are set, tell the Policy
+ * Engine thread */
+ if ((status.interrupta & FUSB_INTERRUPTA_I_OCP_TEMP) && (status.status1 & FUSB_STATUS1_OVRTEMP)) {
+ PolicyEngine::notify(PDB_EVT_PE_I_OVRTEMP);
+ }
+ }
}
void InterruptHandler::irqCallback() {
- if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
- if (TaskHandle != NULL) {
- BaseType_t taskWoke = pdFALSE;
- xTaskNotifyFromISR(TaskHandle, 0x01, eNotifyAction::eSetBits, &taskWoke);
- portYIELD_FROM_ISR(taskWoke);
- }
- }
+ if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
+ if (TaskHandle != NULL) {
+ BaseType_t taskWoke = pdFALSE;
+ xTaskNotifyFromISR(TaskHandle, 0x01, eNotifyAction::eSetBits, &taskWoke);
+ portYIELD_FROM_ISR(taskWoke);
+ }
+ }
}
diff --git a/source/Core/Drivers/FUSB302/policy_engine.cpp b/source/Core/Drivers/FUSB302/policy_engine.cpp
index fb726a8f..5ce5428e 100644
--- a/source/Core/Drivers/FUSB302/policy_engine.cpp
+++ b/source/Core/Drivers/FUSB302/policy_engine.cpp
@@ -16,677 +16,619 @@
*/
#include "policy_engine.h"
-#include <stdbool.h>
+#include "fusb302b.h"
#include "int_n.h"
-#include <pd.h>
#include "protocol_tx.h"
-#include "fusb302b.h"
-bool PolicyEngine::pdNegotiationComplete;
-int PolicyEngine::current_voltage_mv;
-int PolicyEngine::_requested_voltage;
-bool PolicyEngine::_unconstrained_power;
-union pd_msg PolicyEngine::currentMessage;
-uint16_t PolicyEngine::hdr_template;
-bool PolicyEngine::_explicit_contract;
-int8_t PolicyEngine::_hard_reset_counter;
-int8_t PolicyEngine::_old_tcc_match;
-uint8_t PolicyEngine::_pps_index;
-uint8_t PolicyEngine::_last_pps;
-osThreadId PolicyEngine::TaskHandle = NULL;
-uint32_t PolicyEngine::TaskBuffer[PolicyEngine::TaskStackSize];
-osStaticThreadDef_t PolicyEngine::TaskControlBlock;
-union pd_msg PolicyEngine::tempMessage;
-union pd_msg PolicyEngine::_last_dpm_request;
+#include <pd.h>
+#include <stdbool.h>
+bool PolicyEngine::pdNegotiationComplete;
+int PolicyEngine::current_voltage_mv;
+int PolicyEngine::_requested_voltage;
+bool PolicyEngine::_unconstrained_power;
+union pd_msg PolicyEngine::currentMessage;
+uint16_t PolicyEngine::hdr_template;
+bool PolicyEngine::_explicit_contract;
+int8_t PolicyEngine::_hard_reset_counter;
+int8_t PolicyEngine::_old_tcc_match;
+uint8_t PolicyEngine::_pps_index;
+uint8_t PolicyEngine::_last_pps;
+osThreadId PolicyEngine::TaskHandle = NULL;
+uint32_t PolicyEngine::TaskBuffer[PolicyEngine::TaskStackSize];
+osStaticThreadDef_t PolicyEngine::TaskControlBlock;
+union pd_msg PolicyEngine::tempMessage;
+union pd_msg PolicyEngine::_last_dpm_request;
PolicyEngine::policy_engine_state PolicyEngine::state = PESinkStartup;
-StaticQueue_t PolicyEngine::xStaticQueue;
-uint8_t PolicyEngine::ucQueueStorageArea[PDB_MSG_POOL_SIZE
- * sizeof(union pd_msg)];
-QueueHandle_t PolicyEngine::messagesWaiting = NULL;
-EventGroupHandle_t PolicyEngine::xEventGroupHandle = NULL;
-StaticEventGroup_t PolicyEngine::xCreatedEventGroup;
-void PolicyEngine::init() {
- messagesWaiting = xQueueCreateStatic(PDB_MSG_POOL_SIZE,
- sizeof(union pd_msg), ucQueueStorageArea, &xStaticQueue);
- //Create static thread at PDB_PRIO_PE priority
- osThreadStaticDef(PolEng, pe_task, PDB_PRIO_PE, 0, TaskStackSize,
- TaskBuffer, &TaskControlBlock);
- TaskHandle = osThreadCreate(osThread(PolEng), NULL);
- xEventGroupHandle = xEventGroupCreateStatic(&xCreatedEventGroup);
+StaticQueue_t PolicyEngine::xStaticQueue;
+uint8_t PolicyEngine::ucQueueStorageArea[PDB_MSG_POOL_SIZE * sizeof(union pd_msg)];
+QueueHandle_t PolicyEngine::messagesWaiting = NULL;
+EventGroupHandle_t PolicyEngine::xEventGroupHandle = NULL;
+StaticEventGroup_t PolicyEngine::xCreatedEventGroup;
+void PolicyEngine::init() {
+ messagesWaiting = xQueueCreateStatic(PDB_MSG_POOL_SIZE, sizeof(union pd_msg), ucQueueStorageArea, &xStaticQueue);
+ // Create static thread at PDB_PRIO_PE priority
+ osThreadStaticDef(PolEng, pe_task, PDB_PRIO_PE, 0, TaskStackSize, TaskBuffer, &TaskControlBlock);
+ TaskHandle = osThreadCreate(osThread(PolEng), NULL);
+ xEventGroupHandle = xEventGroupCreateStatic(&xCreatedEventGroup);
}
void PolicyEngine::notify(uint32_t notification) {
- if (xEventGroupHandle != NULL) {
- xEventGroupSetBits(xEventGroupHandle, notification);
- }
+ if (xEventGroupHandle != NULL) {
+ xEventGroupSetBits(xEventGroupHandle, notification);
+ }
}
void PolicyEngine::pe_task(const void *arg) {
- (void) arg;
-//Internal thread loop
- hdr_template = PD_DATAROLE_UFP | PD_POWERROLE_SINK;
- /* Initialize the old_tcc_match */
- _old_tcc_match = -1;
- /* Initialize the pps_index */
- _pps_index = 8;
- /* Initialize the last_pps */
- _last_pps = 8;
-
- for (;;) {
- //Loop based on state
- switch (state) {
-
- case PESinkStartup:
- state = pe_sink_startup();
- break;
- case PESinkDiscovery:
- state = pe_sink_discovery();
- break;
- case PESinkWaitCap:
- state = pe_sink_wait_cap();
- break;
- case PESinkEvalCap:
- state = pe_sink_eval_cap();
- break;
- case PESinkSelectCap:
- state = pe_sink_select_cap();
- break;
- case PESinkTransitionSink:
- state = pe_sink_transition_sink();
- break;
- case PESinkReady:
- state = pe_sink_ready();
- break;
- case PESinkGetSourceCap:
- state = pe_sink_get_source_cap();
- break;
- case PESinkGiveSinkCap:
- state = pe_sink_give_sink_cap();
- break;
- case PESinkHardReset:
- state = pe_sink_hard_reset();
- break;
- case PESinkTransitionDefault:
- state = pe_sink_transition_default();
- break;
- case PESinkSoftReset:
- state = pe_sink_soft_reset();
- break;
- case PESinkSendSoftReset:
- state = pe_sink_send_soft_reset();
- break;
- case PESinkSendNotSupported:
- state = pe_sink_send_not_supported();
- break;
- case PESinkChunkReceived:
- state = pe_sink_chunk_received();
- break;
- case PESinkSourceUnresponsive:
- state = pe_sink_source_unresponsive();
- break;
- case PESinkNotSupportedReceived:
- state = pe_sink_not_supported_received();
- break;
- default:
- state = PESinkStartup;
- break;
- }
- }
+ (void)arg;
+ // Internal thread loop
+ hdr_template = PD_DATAROLE_UFP | PD_POWERROLE_SINK;
+ /* Initialize the old_tcc_match */
+ _old_tcc_match = -1;
+ /* Initialize the pps_index */
+ _pps_index = 8;
+ /* Initialize the last_pps */
+ _last_pps = 8;
+
+ for (;;) {
+ // Loop based on state
+ switch (state) {
+
+ case PESinkStartup:
+ state = pe_sink_startup();
+ break;
+ case PESinkDiscovery:
+ state = pe_sink_discovery();
+ break;
+ case PESinkWaitCap:
+ state = pe_sink_wait_cap();
+ break;
+ case PESinkEvalCap:
+ state = pe_sink_eval_cap();
+ break;
+ case PESinkSelectCap:
+ state = pe_sink_select_cap();
+ break;
+ case PESinkTransitionSink:
+ state = pe_sink_transition_sink();
+ break;
+ case PESinkReady:
+ state = pe_sink_ready();
+ break;
+ case PESinkGetSourceCap:
+ state = pe_sink_get_source_cap();
+ break;
+ case PESinkGiveSinkCap:
+ state = pe_sink_give_sink_cap();
+ break;
+ case PESinkHardReset:
+ state = pe_sink_hard_reset();
+ break;
+ case PESinkTransitionDefault:
+ state = pe_sink_transition_default();
+ break;
+ case PESinkSoftReset:
+ state = pe_sink_soft_reset();
+ break;
+ case PESinkSendSoftReset:
+ state = pe_sink_send_soft_reset();
+ break;
+ case PESinkSendNotSupported:
+ state = pe_sink_send_not_supported();
+ break;
+ case PESinkChunkReceived:
+ state = pe_sink_chunk_received();
+ break;
+ case PESinkSourceUnresponsive:
+ state = pe_sink_source_unresponsive();
+ break;
+ case PESinkNotSupportedReceived:
+ state = pe_sink_not_supported_received();
+ break;
+ default:
+ state = PESinkStartup;
+ break;
+ }
+ }
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_startup() {
- /* We don't have an explicit contract currently */
- _explicit_contract = false;
+ /* We don't have an explicit contract currently */
+ _explicit_contract = false;
-//If desired could send an alert that PD is starting
+ // If desired could send an alert that PD is starting
- /* No need to reset the protocol layer here. There are two ways into this
- * state: startup and exiting hard reset. On startup, the protocol layer
- * is reset by the startup procedure. When exiting hard reset, the
- * protocol layer is reset by the hard reset state machine. Since it's
- * already done somewhere else, there's no need to do it again here. */
+ /* No need to reset the protocol layer here. There are two ways into this
+ * state: startup and exiting hard reset. On startup, the protocol layer
+ * is reset by the startup procedure. When exiting hard reset, the
+ * protocol layer is reset by the hard reset state machine. Since it's
+ * already done somewhere else, there's no need to do it again here. */
- return PESinkDiscovery;
+ return PESinkDiscovery;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_discovery() {
- /* Wait for VBUS. Since it's our only power source, we already know that
- * we have it, so just move on. */
+ /* Wait for VBUS. Since it's our only power source, we already know that
+ * we have it, so just move on. */
- return PESinkWaitCap;
+ return PESinkWaitCap;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_wait_cap() {
- /* Fetch a message from the protocol layer */
- eventmask_t evt = 0;
- if (readMessage()) {
- evt = PDB_EVT_PE_MSG_RX_PEND;
- } else {
- evt = waitForEvent(
- PDB_EVT_PE_MSG_RX | PDB_EVT_PE_I_OVRTEMP | PDB_EVT_PE_RESET,
- //Wait for cap timeout
- PD_T_TYPEC_SINK_WAIT_CAP);
- }
- /* If we timed out waiting for Source_Capabilities, send a hard reset */
- if (evt == 0) {
- return PESinkHardReset;
- }
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkWaitCap;
- }
- /* If we're too hot, we shouldn't negotiate power yet */
- if (evt & PDB_EVT_PE_I_OVRTEMP) {
- return PESinkWaitCap;
- }
-
- /* If we got a message */
- if (evt & (PDB_EVT_PE_MSG_RX | PDB_EVT_PE_MSG_RX_PEND)) {
- /* Get the message */
- while ((evt & PDB_EVT_PE_MSG_RX_PEND) || readMessage() == true) {
- /* If we got a Source_Capabilities message, read it. */
- if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SOURCE_CAPABILITIES
- && PD_NUMOBJ_GET(&tempMessage) > 0) {
- /* First, determine what PD revision we're using */
- if ((hdr_template & PD_HDR_SPECREV) == PD_SPECREV_1_0) {
- /* If the other end is using at least version 3.0, we'll
- * use version 3.0. */
- if ((tempMessage.hdr & PD_HDR_SPECREV) >= PD_SPECREV_3_0) {
- hdr_template |= PD_SPECREV_3_0;
- /* Otherwise, use 2.0. Don't worry about the 1.0 case
- * because we don't have hardware for PD 1.0 signaling. */
- } else {
- hdr_template |= PD_SPECREV_2_0;
- }
- }
- return PESinkEvalCap;
- /* If the message was a Soft_Reset, do the soft reset procedure */
- }
- evt = 0;
- }
- return PESinkWaitCap; //wait for more messages?
-
- }
-
- /* If we failed to get a message, send a hard reset */
- return PESinkHardReset;
+ /* Fetch a message from the protocol layer */
+ eventmask_t evt = 0;
+ if (readMessage()) {
+ evt = PDB_EVT_PE_MSG_RX_PEND;
+ } else {
+ evt = waitForEvent(PDB_EVT_PE_MSG_RX | PDB_EVT_PE_I_OVRTEMP | PDB_EVT_PE_RESET,
+ // Wait for cap timeout
+ PD_T_TYPEC_SINK_WAIT_CAP);
+ }
+ /* If we timed out waiting for Source_Capabilities, send a hard reset */
+ if (evt == 0) {
+ return PESinkHardReset;
+ }
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkWaitCap;
+ }
+ /* If we're too hot, we shouldn't negotiate power yet */
+ if (evt & PDB_EVT_PE_I_OVRTEMP) {
+ return PESinkWaitCap;
+ }
+
+ /* If we got a message */
+ if (evt & (PDB_EVT_PE_MSG_RX | PDB_EVT_PE_MSG_RX_PEND)) {
+ /* Get the message */
+ while ((evt & PDB_EVT_PE_MSG_RX_PEND) || readMessage() == true) {
+ /* If we got a Source_Capabilities message, read it. */
+ if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SOURCE_CAPABILITIES && PD_NUMOBJ_GET(&tempMessage) > 0) {
+ /* First, determine what PD revision we're using */
+ if ((hdr_template & PD_HDR_SPECREV) == PD_SPECREV_1_0) {
+ /* If the other end is using at least version 3.0, we'll
+ * use version 3.0. */
+ if ((tempMessage.hdr & PD_HDR_SPECREV) >= PD_SPECREV_3_0) {
+ hdr_template |= PD_SPECREV_3_0;
+ /* Otherwise, use 2.0. Don't worry about the 1.0 case
+ * because we don't have hardware for PD 1.0 signaling. */
+ } else {
+ hdr_template |= PD_SPECREV_2_0;
+ }
+ }
+ return PESinkEvalCap;
+ /* If the message was a Soft_Reset, do the soft reset procedure */
+ }
+ evt = 0;
+ }
+ return PESinkWaitCap; // wait for more messages?
+ }
+
+ /* If we failed to get a message, send a hard reset */
+ return PESinkHardReset;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_eval_cap() {
- /* If we have a Source_Capabilities message, remember the index of the
- * first PPS APDO so we can check if the request is for a PPS APDO in
- * PE_SNK_Select_Cap. */
- /* Start by assuming we won't find a PPS APDO (set the index greater
- * than the maximum possible) */
- _pps_index = 8;
- /* Search for the first PPS APDO */
- for (int8_t i = 0; i < PD_NUMOBJ_GET(&tempMessage); i++) {
- if ((tempMessage.obj[i] & PD_PDO_TYPE) == PD_PDO_TYPE_AUGMENTED
- && (tempMessage.obj[i] & PD_APDO_TYPE) == PD_APDO_TYPE_PPS) {
- _pps_index = i + 1;
- break;
- }
- }
- /* New capabilities also means we can't be making a request from the
- * same PPS APDO */
- _last_pps = 8;
-
- /* Ask the DPM what to request */
- if (pdbs_dpm_evaluate_capability(&tempMessage, &_last_dpm_request)) {
-
- return PESinkSelectCap;
- }
-
- return PESinkWaitCap;
+ /* If we have a Source_Capabilities message, remember the index of the
+ * first PPS APDO so we can check if the request is for a PPS APDO in
+ * PE_SNK_Select_Cap. */
+ /* Start by assuming we won't find a PPS APDO (set the index greater
+ * than the maximum possible) */
+ _pps_index = 8;
+ /* Search for the first PPS APDO */
+ for (int8_t i = 0; i < PD_NUMOBJ_GET(&tempMessage); i++) {
+ if ((tempMessage.obj[i] & PD_PDO_TYPE) == PD_PDO_TYPE_AUGMENTED && (tempMessage.obj[i] & PD_APDO_TYPE) == PD_APDO_TYPE_PPS) {
+ _pps_index = i + 1;
+ break;
+ }
+ }
+ /* New capabilities also means we can't be making a request from the
+ * same PPS APDO */
+ _last_pps = 8;
+
+ /* Ask the DPM what to request */
+ if (pdbs_dpm_evaluate_capability(&tempMessage, &_last_dpm_request)) {
+
+ return PESinkSelectCap;
+ }
+
+ return PESinkWaitCap;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_select_cap() {
- /* Transmit the request */
- waitForEvent(0xFFFF, 0); //clear pending
- ProtocolTransmit::pushMessage(&_last_dpm_request);
- //Send indication that there is a message pending
- ProtocolTransmit::notify(
- ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
- eventmask_t evt = waitForEvent(
- PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET || evt == 0) {
- return PESinkTransitionDefault;
- }
- /* If the message transmission failed, send a hard reset */
- if ((evt & PDB_EVT_PE_TX_ERR) == PDB_EVT_PE_TX_ERR) {
- return PESinkHardReset;
- }
-
- /* Wait for a response */
- evt = waitForEvent(PDB_EVT_PE_MSG_RX | PDB_EVT_PE_RESET,
- PD_T_SENDER_RESPONSE);
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
- /* If we didn't get a response before the timeout, send a hard reset */
- if (evt == 0) {
- return PESinkHardReset;
- }
-
- /* Get the response message */
- if (messageWaiting()) {
- readMessage();
- /* If the source accepted our request, wait for the new power */
- if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_ACCEPT
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkTransitionSink;
- /* If the message was a Soft_Reset, do the soft reset procedure */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SOFT_RESET
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
- return PESinkSoftReset;
- /* If the message was Wait or Reject */
- } else if ((PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_REJECT
- || PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_WAIT)
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
- /* If we don't have an explicit contract, wait for capabilities */
- if (!_explicit_contract) {
- return PESinkWaitCap;
- /* If we do have an explicit contract, go to the ready state */
- } else {
- return PESinkReady;
- }
- } else {
- return PESinkSendSoftReset;
- }
- }
- return PESinkHardReset;
+ /* Transmit the request */
+ waitForEvent(0xFFFF, 0); // clear pending
+ ProtocolTransmit::pushMessage(&_last_dpm_request);
+ // Send indication that there is a message pending
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
+ eventmask_t evt = waitForEvent(PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET || evt == 0) {
+ return PESinkTransitionDefault;
+ }
+ /* If the message transmission failed, send a hard reset */
+ if ((evt & PDB_EVT_PE_TX_ERR) == PDB_EVT_PE_TX_ERR) {
+ return PESinkHardReset;
+ }
+
+ /* Wait for a response */
+ evt = waitForEvent(PDB_EVT_PE_MSG_RX | PDB_EVT_PE_RESET, PD_T_SENDER_RESPONSE);
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
+ /* If we didn't get a response before the timeout, send a hard reset */
+ if (evt == 0) {
+ return PESinkHardReset;
+ }
+
+ /* Get the response message */
+ if (messageWaiting()) {
+ readMessage();
+ /* If the source accepted our request, wait for the new power */
+ if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_ACCEPT && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkTransitionSink;
+ /* If the message was a Soft_Reset, do the soft reset procedure */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SOFT_RESET && PD_NUMOBJ_GET(&tempMessage) == 0) {
+ return PESinkSoftReset;
+ /* If the message was Wait or Reject */
+ } else if ((PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_REJECT || PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_WAIT) && PD_NUMOBJ_GET(&tempMessage) == 0) {
+ /* If we don't have an explicit contract, wait for capabilities */
+ if (!_explicit_contract) {
+ return PESinkWaitCap;
+ /* If we do have an explicit contract, go to the ready state */
+ } else {
+ return PESinkReady;
+ }
+ } else {
+ return PESinkSendSoftReset;
+ }
+ }
+ return PESinkHardReset;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_transition_sink() {
- /* Wait for the PS_RDY message */
- eventmask_t evt = waitForEvent(PDB_EVT_PE_MSG_RX | PDB_EVT_PE_RESET,
- PD_T_PS_TRANSITION);
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
- /* If no message was received, send a hard reset */
- if (evt == 0) {
- return PESinkHardReset;
- }
-
- /* If we received a message, read it */
- if (messageWaiting()) {
- readMessage();
- /* If we got a PS_RDY, handle it */
- if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_PS_RDY
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
- /* We just finished negotiating an explicit contract */
- _explicit_contract = true;
-
- /* Set the output appropriately */
- pdbs_dpm_transition_requested();
-
- return PESinkReady;
- /* If there was a protocol error, send a hard reset */
- } else {
- /* Turn off the power output before this hard reset to make sure we
- * don't supply an incorrect voltage to the device we're powering.
- */
- pdbs_dpm_transition_default();
-
- return PESinkHardReset;
- }
- }
-
- return PESinkHardReset;
+ /* Wait for the PS_RDY message */
+ eventmask_t evt = waitForEvent(PDB_EVT_PE_MSG_RX | PDB_EVT_PE_RESET, PD_T_PS_TRANSITION);
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
+ /* If no message was received, send a hard reset */
+ if (evt == 0) {
+ return PESinkHardReset;
+ }
+
+ /* If we received a message, read it */
+ if (messageWaiting()) {
+ readMessage();
+ /* If we got a PS_RDY, handle it */
+ if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_PS_RDY && PD_NUMOBJ_GET(&tempMessage) == 0) {
+ /* We just finished negotiating an explicit contract */
+ _explicit_contract = true;
+
+ /* Set the output appropriately */
+ pdbs_dpm_transition_requested();
+
+ return PESinkReady;
+ /* If there was a protocol error, send a hard reset */
+ } else {
+ /* Turn off the power output before this hard reset to make sure we
+ * don't supply an incorrect voltage to the device we're powering.
+ */
+ pdbs_dpm_transition_default();
+
+ return PESinkHardReset;
+ }
+ }
+
+ return PESinkHardReset;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_ready() {
- eventmask_t evt;
-
- /* Wait for an event */
- evt = waitForEvent(
- PDB_EVT_PE_MSG_RX | PDB_EVT_PE_RESET | PDB_EVT_PE_I_OVRTEMP);
-
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
-
- /* If we overheated, send a hard reset */
- if (evt & PDB_EVT_PE_I_OVRTEMP) {
- return PESinkHardReset;
- }
-
- /* If we received a message */
- if (evt & PDB_EVT_PE_MSG_RX) {
- if (messageWaiting()) {
- readMessage();
- /* Ignore vendor-defined messages */
- if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_VENDOR_DEFINED
- && PD_NUMOBJ_GET(&tempMessage) > 0) {
-
- return PESinkReady;
- /* Ignore Ping messages */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_PING
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkReady;
- /* DR_Swap messages are not supported */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_DR_SWAP
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkSendNotSupported;
- /* Get_Source_Cap messages are not supported */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_GET_SOURCE_CAP
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkSendNotSupported;
- /* PR_Swap messages are not supported */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_PR_SWAP
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkSendNotSupported;
- /* VCONN_Swap messages are not supported */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_VCONN_SWAP
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkSendNotSupported;
- /* Request messages are not supported */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_REQUEST
- && PD_NUMOBJ_GET(&tempMessage) > 0) {
-
- return PESinkSendNotSupported;
- /* Sink_Capabilities messages are not supported */
- } else if (PD_MSGTYPE_GET(&tempMessage)
- == PD_MSGTYPE_SINK_CAPABILITIES
- && PD_NUMOBJ_GET(&tempMessage) > 0) {
-
- return PESinkSendNotSupported;
- /* Handle GotoMin messages */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_GOTOMIN
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
- /* GiveBack is not supported */
- return PESinkSendNotSupported;
-
- /* Evaluate new Source_Capabilities */
- } else if (PD_MSGTYPE_GET(&tempMessage)
- == PD_MSGTYPE_SOURCE_CAPABILITIES
- && PD_NUMOBJ_GET(&tempMessage) > 0) {
- /* Don't free the message: we need to keep the
- * Source_Capabilities message so we can evaluate it. */
- return PESinkEvalCap;
- /* Give sink capabilities when asked */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_GET_SINK_CAP
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkGiveSinkCap;
- /* If the message was a Soft_Reset, do the soft reset procedure */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SOFT_RESET
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkSoftReset;
- /* PD 3.0 messges */
- } else if ((hdr_template & PD_HDR_SPECREV) == PD_SPECREV_3_0) {
- /* If the message is a multi-chunk extended message, let it
- * time out. */
- if ((tempMessage.hdr & PD_HDR_EXT)
- && (PD_DATA_SIZE_GET(&tempMessage)
- > PD_MAX_EXT_MSG_LEGACY_LEN)) {
-
- return PESinkChunkReceived;
- /* Tell the DPM a message we sent got a response of
- * Not_Supported. */
- } else if (PD_MSGTYPE_GET(&tempMessage)
- == PD_MSGTYPE_NOT_SUPPORTED
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkNotSupportedReceived;
- /* If we got an unknown message, send a soft reset */
- } else {
-
- return PESinkSendSoftReset;
- }
- /* If we got an unknown message, send a soft reset ??? */
- } else {
-
- return PESinkSendSoftReset;
- }
- }
- }
-
- return PESinkReady;
+ eventmask_t evt;
+
+ /* Wait for an event */
+ evt = waitForEvent(PDB_EVT_PE_MSG_RX | PDB_EVT_PE_RESET | PDB_EVT_PE_I_OVRTEMP);
+
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
+
+ /* If we overheated, send a hard reset */
+ if (evt & PDB_EVT_PE_I_OVRTEMP) {
+ return PESinkHardReset;
+ }
+
+ /* If we received a message */
+ if (evt & PDB_EVT_PE_MSG_RX) {
+ if (messageWaiting()) {
+ readMessage();
+ /* Ignore vendor-defined messages */
+ if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_VENDOR_DEFINED && PD_NUMOBJ_GET(&tempMessage) > 0) {
+
+ return PESinkReady;
+ /* Ignore Ping messages */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_PING && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkReady;
+ /* DR_Swap messages are not supported */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_DR_SWAP && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkSendNotSupported;
+ /* Get_Source_Cap messages are not supported */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_GET_SOURCE_CAP && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkSendNotSupported;
+ /* PR_Swap messages are not supported */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_PR_SWAP && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkSendNotSupported;
+ /* VCONN_Swap messages are not supported */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_VCONN_SWAP && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkSendNotSupported;
+ /* Request messages are not supported */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_REQUEST && PD_NUMOBJ_GET(&tempMessage) > 0) {
+
+ return PESinkSendNotSupported;
+ /* Sink_Capabilities messages are not supported */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SINK_CAPABILITIES && PD_NUMOBJ_GET(&tempMessage) > 0) {
+
+ return PESinkSendNotSupported;
+ /* Handle GotoMin messages */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_GOTOMIN && PD_NUMOBJ_GET(&tempMessage) == 0) {
+ /* GiveBack is not supported */
+ return PESinkSendNotSupported;
+
+ /* Evaluate new Source_Capabilities */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SOURCE_CAPABILITIES && PD_NUMOBJ_GET(&tempMessage) > 0) {
+ /* Don't free the message: we need to keep the
+ * Source_Capabilities message so we can evaluate it. */
+ return PESinkEvalCap;
+ /* Give sink capabilities when asked */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_GET_SINK_CAP && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkGiveSinkCap;
+ /* If the message was a Soft_Reset, do the soft reset procedure */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SOFT_RESET && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkSoftReset;
+ /* PD 3.0 messges */
+ } else if ((hdr_template & PD_HDR_SPECREV) == PD_SPECREV_3_0) {
+ /* If the message is a multi-chunk extended message, let it
+ * time out. */
+ if ((tempMessage.hdr & PD_HDR_EXT) && (PD_DATA_SIZE_GET(&tempMessage) > PD_MAX_EXT_MSG_LEGACY_LEN)) {
+
+ return PESinkChunkReceived;
+ /* Tell the DPM a message we sent got a response of
+ * Not_Supported. */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_NOT_SUPPORTED && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkNotSupportedReceived;
+ /* If we got an unknown message, send a soft reset */
+ } else {
+
+ return PESinkSendSoftReset;
+ }
+ /* If we got an unknown message, send a soft reset ??? */
+ } else {
+
+ return PESinkSendSoftReset;
+ }
+ }
+ }
+
+ return PESinkReady;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_get_source_cap() {
- /* Get a message object */
- union pd_msg *get_source_cap = &tempMessage;
- /* Make a Get_Source_Cap message */
- get_source_cap->hdr = hdr_template | PD_MSGTYPE_GET_SOURCE_CAP
- | PD_NUMOBJ(0);
- /* Transmit the Get_Source_Cap */
- ProtocolTransmit::pushMessage(get_source_cap);
- ProtocolTransmit::notify(
- ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
- eventmask_t evt = waitForEvent(
- PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
- /* Free the sent message */
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
- /* If the message transmission failed, send a hard reset */
- if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
- return PESinkHardReset;
- }
-
- return PESinkReady;
+ /* Get a message object */
+ union pd_msg *get_source_cap = &tempMessage;
+ /* Make a Get_Source_Cap message */
+ get_source_cap->hdr = hdr_template | PD_MSGTYPE_GET_SOURCE_CAP | PD_NUMOBJ(0);
+ /* Transmit the Get_Source_Cap */
+ ProtocolTransmit::pushMessage(get_source_cap);
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
+ eventmask_t evt = waitForEvent(PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
+ /* Free the sent message */
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
+ /* If the message transmission failed, send a hard reset */
+ if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
+ return PESinkHardReset;
+ }
+
+ return PESinkReady;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_give_sink_cap() {
- /* Get a message object */
- union pd_msg *snk_cap = &tempMessage;
- /* Get our capabilities from the DPM */
- pdbs_dpm_get_sink_capability(snk_cap);
-
- /* Transmit our capabilities */
- ProtocolTransmit::pushMessage(snk_cap);
- ProtocolTransmit::notify(
- ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
- eventmask_t evt = waitForEvent(
- PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
-
- /* Free the Sink_Capabilities message */
-
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
- /* If the message transmission failed, send a hard reset */
- if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
- return PESinkHardReset;
- }
-
- return PESinkReady;
+ /* Get a message object */
+ union pd_msg *snk_cap = &tempMessage;
+ /* Get our capabilities from the DPM */
+ pdbs_dpm_get_sink_capability(snk_cap);
+
+ /* Transmit our capabilities */
+ ProtocolTransmit::pushMessage(snk_cap);
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
+ eventmask_t evt = waitForEvent(PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
+
+ /* Free the Sink_Capabilities message */
+
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
+ /* If the message transmission failed, send a hard reset */
+ if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
+ return PESinkHardReset;
+ }
+
+ return PESinkReady;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_hard_reset() {
- /* If we've already sent the maximum number of hard resets, assume the
- * source is unresponsive. */
- if (_hard_reset_counter > PD_N_HARD_RESET_COUNT) {
- return PESinkSourceUnresponsive;
- }
- //So, we could send a hardreset here; however that will cause a power cycle on the PSU end.. Which will then reset this MCU
- //So therefore we went get anywhere :)
- /* Increment HardResetCounter */
- _hard_reset_counter++;
-
- return PESinkTransitionDefault;
+ /* If we've already sent the maximum number of hard resets, assume the
+ * source is unresponsive. */
+ if (_hard_reset_counter > PD_N_HARD_RESET_COUNT) {
+ return PESinkSourceUnresponsive;
+ }
+ // So, we could send a hardreset here; however that will cause a power cycle on the PSU end.. Which will then reset this MCU
+ // So therefore we went get anywhere :)
+ /* Increment HardResetCounter */
+ _hard_reset_counter++;
+
+ return PESinkTransitionDefault;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_transition_default() {
- _explicit_contract = false;
+ _explicit_contract = false;
- /* Tell the DPM to transition to default power */
- pdbs_dpm_transition_default();
+ /* Tell the DPM to transition to default power */
+ pdbs_dpm_transition_default();
- /* There is no local hardware to reset. */
- /* Since we never change our data role from UFP, there is no reason to set
- * it here. */
+ /* There is no local hardware to reset. */
+ /* Since we never change our data role from UFP, there is no reason to set
+ * it here. */
- return PESinkStartup;
+ return PESinkStartup;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_soft_reset() {
- /* No need to explicitly reset the protocol layer here. It resets itself
- * when a Soft_Reset message is received. */
-
- /* Get a message object */
- union pd_msg accept;
- /* Make an Accept message */
- accept.hdr = hdr_template | PD_MSGTYPE_ACCEPT | PD_NUMOBJ(0);
- /* Transmit the Accept */
- ProtocolTransmit::pushMessage(&accept);
- ProtocolTransmit::notify(
- ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
- eventmask_t evt = waitForEvent(
- PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
- /* Free the sent message */
-
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
- /* If the message transmission failed, send a hard reset */
- if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
- return PESinkHardReset;
- }
-
- return PESinkWaitCap;
+ /* No need to explicitly reset the protocol layer here. It resets itself
+ * when a Soft_Reset message is received. */
+
+ /* Get a message object */
+ union pd_msg accept;
+ /* Make an Accept message */
+ accept.hdr = hdr_template | PD_MSGTYPE_ACCEPT | PD_NUMOBJ(0);
+ /* Transmit the Accept */
+ ProtocolTransmit::pushMessage(&accept);
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
+ eventmask_t evt = waitForEvent(PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
+ /* Free the sent message */
+
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
+ /* If the message transmission failed, send a hard reset */
+ if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
+ return PESinkHardReset;
+ }
+
+ return PESinkWaitCap;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_send_soft_reset() {
- /* No need to explicitly reset the protocol layer here. It resets itself
- * just before a Soft_Reset message is transmitted. */
-
- /* Get a message object */
- union pd_msg *softrst = &tempMessage;
- /* Make a Soft_Reset message */
- softrst->hdr = hdr_template | PD_MSGTYPE_SOFT_RESET | PD_NUMOBJ(0);
- /* Transmit the soft reset */
- ProtocolTransmit::pushMessage(softrst);
- ProtocolTransmit::notify(
- ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
- eventmask_t evt = waitForEvent(
- PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
- /* If the message transmission failed, send a hard reset */
- if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
- return PESinkHardReset;
- }
-
- /* Wait for a response */
- evt = waitForEvent(PDB_EVT_PE_MSG_RX | PDB_EVT_PE_RESET,
- PD_T_SENDER_RESPONSE);
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
- /* If we didn't get a response before the timeout, send a hard reset */
- if (evt == 0) {
- return PESinkHardReset;
- }
-
- /* Get the response message */
- if (messageWaiting()) {
- readMessage();
- /* If the source accepted our soft reset, wait for capabilities. */
- if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_ACCEPT
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkWaitCap;
- /* If the message was a Soft_Reset, do the soft reset procedure */
- } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SOFT_RESET
- && PD_NUMOBJ_GET(&tempMessage) == 0) {
-
- return PESinkSoftReset;
- /* Otherwise, send a hard reset */
- } else {
-
- return PESinkHardReset;
- }
- }
- return PESinkHardReset;
+ /* No need to explicitly reset the protocol layer here. It resets itself
+ * just before a Soft_Reset message is transmitted. */
+
+ /* Get a message object */
+ union pd_msg *softrst = &tempMessage;
+ /* Make a Soft_Reset message */
+ softrst->hdr = hdr_template | PD_MSGTYPE_SOFT_RESET | PD_NUMOBJ(0);
+ /* Transmit the soft reset */
+ ProtocolTransmit::pushMessage(softrst);
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
+ eventmask_t evt = waitForEvent(PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
+ /* If the message transmission failed, send a hard reset */
+ if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
+ return PESinkHardReset;
+ }
+
+ /* Wait for a response */
+ evt = waitForEvent(PDB_EVT_PE_MSG_RX | PDB_EVT_PE_RESET, PD_T_SENDER_RESPONSE);
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
+ /* If we didn't get a response before the timeout, send a hard reset */
+ if (evt == 0) {
+ return PESinkHardReset;
+ }
+
+ /* Get the response message */
+ if (messageWaiting()) {
+ readMessage();
+ /* If the source accepted our soft reset, wait for capabilities. */
+ if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_ACCEPT && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkWaitCap;
+ /* If the message was a Soft_Reset, do the soft reset procedure */
+ } else if (PD_MSGTYPE_GET(&tempMessage) == PD_MSGTYPE_SOFT_RESET && PD_NUMOBJ_GET(&tempMessage) == 0) {
+
+ return PESinkSoftReset;
+ /* Otherwise, send a hard reset */
+ } else {
+
+ return PESinkHardReset;
+ }
+ }
+ return PESinkHardReset;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_send_not_supported() {
- /* Get a message object */
- union pd_msg *not_supported = &tempMessage;
-
- if ((hdr_template & PD_HDR_SPECREV) == PD_SPECREV_2_0) {
- /* Make a Reject message */
- not_supported->hdr = hdr_template | PD_MSGTYPE_REJECT | PD_NUMOBJ(0);
- } else if ((hdr_template & PD_HDR_SPECREV) == PD_SPECREV_3_0) {
- /* Make a Not_Supported message */
- not_supported->hdr = hdr_template | PD_MSGTYPE_NOT_SUPPORTED
- | PD_NUMOBJ(0);
- }
-
- /* Transmit the message */
- ProtocolTransmit::pushMessage(not_supported);
- ProtocolTransmit::notify(
- ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
- eventmask_t evt = waitForEvent(
- PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
-
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
- /* If the message transmission failed, send a soft reset */
- if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
- return PESinkSendSoftReset;
- }
-
- return PESinkReady;
+ /* Get a message object */
+ union pd_msg *not_supported = &tempMessage;
+
+ if ((hdr_template & PD_HDR_SPECREV) == PD_SPECREV_2_0) {
+ /* Make a Reject message */
+ not_supported->hdr = hdr_template | PD_MSGTYPE_REJECT | PD_NUMOBJ(0);
+ } else if ((hdr_template & PD_HDR_SPECREV) == PD_SPECREV_3_0) {
+ /* Make a Not_Supported message */
+ not_supported->hdr = hdr_template | PD_MSGTYPE_NOT_SUPPORTED | PD_NUMOBJ(0);
+ }
+
+ /* Transmit the message */
+ ProtocolTransmit::pushMessage(not_supported);
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_MSG_TX);
+ eventmask_t evt = waitForEvent(PDB_EVT_PE_TX_DONE | PDB_EVT_PE_TX_ERR | PDB_EVT_PE_RESET);
+
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
+ /* If the message transmission failed, send a soft reset */
+ if ((evt & PDB_EVT_PE_TX_DONE) == 0) {
+ return PESinkSendSoftReset;
+ }
+
+ return PESinkReady;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_chunk_received() {
- /* Wait for tChunkingNotSupported */
- eventmask_t evt = waitForEvent(PDB_EVT_PE_RESET,
- PD_T_CHUNKING_NOT_SUPPORTED);
- /* If we got reset signaling, transition to default */
- if (evt & PDB_EVT_PE_RESET) {
- return PESinkTransitionDefault;
- }
+ /* Wait for tChunkingNotSupported */
+ eventmask_t evt = waitForEvent(PDB_EVT_PE_RESET, PD_T_CHUNKING_NOT_SUPPORTED);
+ /* If we got reset signaling, transition to default */
+ if (evt & PDB_EVT_PE_RESET) {
+ return PESinkTransitionDefault;
+ }
- return PESinkSendNotSupported;
+ return PESinkSendNotSupported;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_not_supported_received() {
- /* Inform the Device Policy Manager that we received a Not_Supported
- * message. */
+ /* Inform the Device Policy Manager that we received a Not_Supported
+ * message. */
- return PESinkReady;
+ return PESinkReady;
}
PolicyEngine::policy_engine_state PolicyEngine::pe_sink_source_unresponsive() {
-//Sit and chill, as PD is not working
- osDelay(PD_T_PD_DEBOUNCE);
+ // Sit and chill, as PD is not working
+ osDelay(PD_T_PD_DEBOUNCE);
- return PESinkSourceUnresponsive;
+ return PESinkSourceUnresponsive;
}
-uint32_t PolicyEngine::waitForEvent(uint32_t mask, TickType_t ticksToWait) {
- return xEventGroupWaitBits(xEventGroupHandle, mask, mask, pdFALSE,
- ticksToWait);
-
-}
-
-bool PolicyEngine::isPD3_0() {
- return (hdr_template & PD_HDR_SPECREV) == PD_SPECREV_3_0;
-}
+uint32_t PolicyEngine::waitForEvent(uint32_t mask, TickType_t ticksToWait) { return xEventGroupWaitBits(xEventGroupHandle, mask, mask, pdFALSE, ticksToWait); }
+bool PolicyEngine::isPD3_0() { return (hdr_template & PD_HDR_SPECREV) == PD_SPECREV_3_0; }
diff --git a/source/Core/Drivers/FUSB302/policy_engine_user.cpp b/source/Core/Drivers/FUSB302/policy_engine_user.cpp
index 4e65cf85..0241436b 100644
--- a/source/Core/Drivers/FUSB302/policy_engine_user.cpp
+++ b/source/Core/Drivers/FUSB302/policy_engine_user.cpp
@@ -4,9 +4,9 @@
* Created on: 14 Jun 2020
* Author: Ralim
*/
+#include "BSP_PD.h"
#include "pd.h"
#include "policy_engine.h"
-#include "BSP_PD.h"
/* The current draw when the output is disabled */
#define DPM_MIN_CURRENT PD_MA2PDI(50)
/*
@@ -16,212 +16,178 @@
* If there is no such PDO, returns -1 instead.
*/
static int8_t dpm_get_range_fixed_pdo_index(const union pd_msg *caps) {
- /* Get the number of PDOs */
- uint8_t numobj = PD_NUMOBJ_GET(caps);
-
- /* Get ready to iterate over the PDOs */
- int8_t i;
- int8_t step;
- i = numobj - 1;
- step = -1;
- uint16_t current = 100; // in centiamps
- uint16_t voltagemin = 8000;
- uint16_t voltagemax = 10000;
- /* Look at the PDOs to see if one falls in our voltage range. */
- while (0 <= i && i < numobj) {
- /* If we have a fixed PDO, its V is within our range, and its I is at
- * least our desired I */
- uint16_t v = PD_PDO_SRC_FIXED_VOLTAGE_GET(caps->obj[i]);
- if ((caps->obj[i] & PD_PDO_TYPE) == PD_PDO_TYPE_FIXED) {
- if ( PD_PDO_SRC_FIXED_CURRENT_GET(caps->obj[i]) >= current) {
- if (v >= PD_MV2PDV(voltagemin) && v <= PD_MV2PDV(voltagemax)) {
- return i;
- }
- }
- }
- i += step;
- }
- return -1;
+ /* Get the number of PDOs */
+ uint8_t numobj = PD_NUMOBJ_GET(caps);
+
+ /* Get ready to iterate over the PDOs */
+ int8_t i;
+ int8_t step;
+ i = numobj - 1;
+ step = -1;
+ uint16_t current = 100; // in centiamps
+ uint16_t voltagemin = 8000;
+ uint16_t voltagemax = 10000;
+ /* Look at the PDOs to see if one falls in our voltage range. */
+ while (0 <= i && i < numobj) {
+ /* If we have a fixed PDO, its V is within our range, and its I is at
+ * least our desired I */
+ uint16_t v = PD_PDO_SRC_FIXED_VOLTAGE_GET(caps->obj[i]);
+ if ((caps->obj[i] & PD_PDO_TYPE) == PD_PDO_TYPE_FIXED) {
+ if (PD_PDO_SRC_FIXED_CURRENT_GET(caps->obj[i]) >= current) {
+ if (v >= PD_MV2PDV(voltagemin) && v <= PD_MV2PDV(voltagemax)) {
+ return i;
+ }
+ }
+ }
+ i += step;
+ }
+ return -1;
}
-bool PolicyEngine::pdbs_dpm_evaluate_capability(
- const union pd_msg *capabilities, union pd_msg *request) {
-
- /* Get the number of PDOs */
- uint8_t numobj = PD_NUMOBJ_GET(capabilities);
-
- /* Get whether or not the power supply is constrained */
- _unconstrained_power =
- capabilities->obj[0] & PD_PDO_SRC_FIXED_UNCONSTRAINED;
-
- /* Make sure we have configuration */
- /* Look at the PDOs to see if one matches our desires */
-//Look against USB_PD_Desired_Levels to select in order of preference
- for (uint8_t desiredLevel = 0; desiredLevel < USB_PD_Desired_Levels_Len;
- desiredLevel++) {
- for (uint8_t i = 0; i < numobj; i++) {
- /* If we have a fixed PDO, its V equals our desired V, and its I is
- * at least our desired I */
- if ((capabilities->obj[i] & PD_PDO_TYPE) == PD_PDO_TYPE_FIXED) {
- //This is a fixed PDO entry
- int voltage = PD_PDV2MV(
- PD_PDO_SRC_FIXED_VOLTAGE_GET(capabilities->obj[i]));
- int current = PD_PDO_SRC_FIXED_CURRENT_GET(
- capabilities->obj[i]);
- uint16_t desiredVoltage = USB_PD_Desired_Levels[(desiredLevel
- * 2) + 0];
- uint16_t desiredminCurrent = USB_PD_Desired_Levels[(desiredLevel
- * 2) + 1];
- //As pd stores current in 10mA increments, divide by 10
- desiredminCurrent /= 10;
- if (voltage == desiredVoltage) {
- if (current >= desiredminCurrent) {
- /* We got what we wanted, so build a request for that */
- request->hdr = hdr_template | PD_MSGTYPE_REQUEST
- | PD_NUMOBJ(1);
-
- /* GiveBack disabled */
- request->obj[0] =
- PD_RDO_FV_MAX_CURRENT_SET(
- current) | PD_RDO_FV_CURRENT_SET(current)
- | PD_RDO_NO_USB_SUSPEND | PD_RDO_OBJPOS_SET(i + 1);
- //We support usb comms (ish)
- request->obj[0] |= PD_RDO_USB_COMMS;
-
- /* Update requested voltage */
- _requested_voltage = voltage;
-
- return true;
- }
- }
- }
-
- }
- }
-
- /* Nothing matched (or no configuration), so get 5 V at low current */
- request->hdr = hdr_template | PD_MSGTYPE_REQUEST | PD_NUMOBJ(1);
- request->obj[0] =
- PD_RDO_FV_MAX_CURRENT_SET(
- DPM_MIN_CURRENT) | PD_RDO_FV_CURRENT_SET(DPM_MIN_CURRENT) | PD_RDO_NO_USB_SUSPEND
- | PD_RDO_OBJPOS_SET(1);
- /* If the output is enabled and we got here, it must be a capability
- * mismatch. */
- if (pdNegotiationComplete) {
- request->obj[0] |= PD_RDO_CAP_MISMATCH;
- }
- request->obj[0] |= PD_RDO_USB_COMMS;
-
- /* Update requested voltage */
- _requested_voltage = 5000;
-
- return false;
+bool PolicyEngine::pdbs_dpm_evaluate_capability(const union pd_msg *capabilities, union pd_msg *request) {
+
+ /* Get the number of PDOs */
+ uint8_t numobj = PD_NUMOBJ_GET(capabilities);
+
+ /* Get whether or not the power supply is constrained */
+ _unconstrained_power = capabilities->obj[0] & PD_PDO_SRC_FIXED_UNCONSTRAINED;
+
+ /* Make sure we have configuration */
+ /* Look at the PDOs to see if one matches our desires */
+ // Look against USB_PD_Desired_Levels to select in order of preference
+ for (uint8_t desiredLevel = 0; desiredLevel < USB_PD_Desired_Levels_Len; desiredLevel++) {
+ for (uint8_t i = 0; i < numobj; i++) {
+ /* If we have a fixed PDO, its V equals our desired V, and its I is
+ * at least our desired I */
+ if ((capabilities->obj[i] & PD_PDO_TYPE) == PD_PDO_TYPE_FIXED) {
+ // This is a fixed PDO entry
+ int voltage = PD_PDV2MV(PD_PDO_SRC_FIXED_VOLTAGE_GET(capabilities->obj[i]));
+ int current = PD_PDO_SRC_FIXED_CURRENT_GET(capabilities->obj[i]);
+ uint16_t desiredVoltage = USB_PD_Desired_Levels[(desiredLevel * 2) + 0];
+ uint16_t desiredminCurrent = USB_PD_Desired_Levels[(desiredLevel * 2) + 1];
+ // As pd stores current in 10mA increments, divide by 10
+ desiredminCurrent /= 10;
+ if (voltage == desiredVoltage) {
+ if (current >= desiredminCurrent) {
+ /* We got what we wanted, so build a request for that */
+ request->hdr = hdr_template | PD_MSGTYPE_REQUEST | PD_NUMOBJ(1);
+
+ /* GiveBack disabled */
+ request->obj[0] = PD_RDO_FV_MAX_CURRENT_SET(current) | PD_RDO_FV_CURRENT_SET(current) | PD_RDO_NO_USB_SUSPEND | PD_RDO_OBJPOS_SET(i + 1);
+ // We support usb comms (ish)
+ request->obj[0] |= PD_RDO_USB_COMMS;
+
+ /* Update requested voltage */
+ _requested_voltage = voltage;
+
+ return true;
+ }
+ }
+ }
+ }
+ }
+
+ /* Nothing matched (or no configuration), so get 5 V at low current */
+ request->hdr = hdr_template | PD_MSGTYPE_REQUEST | PD_NUMOBJ(1);
+ request->obj[0] = PD_RDO_FV_MAX_CURRENT_SET(DPM_MIN_CURRENT) | PD_RDO_FV_CURRENT_SET(DPM_MIN_CURRENT) | PD_RDO_NO_USB_SUSPEND | PD_RDO_OBJPOS_SET(1);
+ /* If the output is enabled and we got here, it must be a capability
+ * mismatch. */
+ if (pdNegotiationComplete) {
+ request->obj[0] |= PD_RDO_CAP_MISMATCH;
+ }
+ request->obj[0] |= PD_RDO_USB_COMMS;
+
+ /* Update requested voltage */
+ _requested_voltage = 5000;
+
+ return false;
}
void PolicyEngine::pdbs_dpm_get_sink_capability(union pd_msg *cap) {
- /* Keep track of how many PDOs we've added */
- int numobj = 0;
-
- /* If we have no configuration or want something other than 5 V, add a PDO
- * for vSafe5V */
- /* Minimum current, 5 V, and higher capability. */
- cap->obj[numobj++] =
- PD_PDO_TYPE_FIXED
- | PD_PDO_SNK_FIXED_VOLTAGE_SET(
- PD_MV2PDV(5000)) | PD_PDO_SNK_FIXED_CURRENT_SET(DPM_MIN_CURRENT);
-
- /* Get the current we want */
- uint16_t current = USB_PD_Desired_Levels[1] / 10; // In centi-amps
- uint16_t voltage = USB_PD_Desired_Levels[0]; // in mv
- /* Add a PDO for the desired power. */
- cap->obj[numobj++] = PD_PDO_TYPE_FIXED
- | PD_PDO_SNK_FIXED_VOLTAGE_SET(
- PD_MV2PDV(voltage)) | PD_PDO_SNK_FIXED_CURRENT_SET(current);
-
- /* Get the PDO from the voltage range */
- int8_t i = dpm_get_range_fixed_pdo_index(cap);
-
- /* If it's vSafe5V, set our vSafe5V's current to what we want */
- if (i == 0) {
- cap->obj[0] &= ~PD_PDO_SNK_FIXED_CURRENT;
- cap->obj[0] |= PD_PDO_SNK_FIXED_CURRENT_SET(current);
- } else {
- /* If we want more than 5 V, set the Higher Capability flag */
- if (PD_MV2PDV(voltage) != PD_MV2PDV(5000)) {
- cap->obj[0] |= PD_PDO_SNK_FIXED_HIGHER_CAP;
- }
-
- /* If the range PDO is a different voltage than the preferred
- * voltage, add it to the array. */
- if (i
- > 0&& PD_PDO_SRC_FIXED_VOLTAGE_GET(cap->obj[i]) != PD_MV2PDV(voltage)) {
- cap->obj[numobj++] =
- PD_PDO_TYPE_FIXED
- | PD_PDO_SNK_FIXED_VOLTAGE_SET(
- PD_PDO_SRC_FIXED_VOLTAGE_GET(cap->obj[i])) | PD_PDO_SNK_FIXED_CURRENT_SET(
- PD_PDO_SRC_FIXED_CURRENT_GET(cap->obj[i]));
- }
-
- /* If we have three PDOs at this point, make sure the last two are
- * sorted by voltage. */
- if (numobj == 3
- && (cap->obj[1] & PD_PDO_SNK_FIXED_VOLTAGE)
- > (cap->obj[2] & PD_PDO_SNK_FIXED_VOLTAGE)) {
- cap->obj[1] ^= cap->obj[2];
- cap->obj[2] ^= cap->obj[1];
- cap->obj[1] ^= cap->obj[2];
- }
- }
-
- /* Set the unconstrained power flag. */
- if (_unconstrained_power) {
- cap->obj[0] |= PD_PDO_SNK_FIXED_UNCONSTRAINED;
- }
- /* Set the USB communications capable flag. */
- cap->obj[0] |= PD_PDO_SNK_FIXED_USB_COMMS;
-
- /* Set the Sink_Capabilities message header */
- cap->hdr = hdr_template | PD_MSGTYPE_SINK_CAPABILITIES | PD_NUMOBJ(numobj);
+ /* Keep track of how many PDOs we've added */
+ int numobj = 0;
+
+ /* If we have no configuration or want something other than 5 V, add a PDO
+ * for vSafe5V */
+ /* Minimum current, 5 V, and higher capability. */
+ cap->obj[numobj++] = PD_PDO_TYPE_FIXED | PD_PDO_SNK_FIXED_VOLTAGE_SET(PD_MV2PDV(5000)) | PD_PDO_SNK_FIXED_CURRENT_SET(DPM_MIN_CURRENT);
+
+ /* Get the current we want */
+ uint16_t current = USB_PD_Desired_Levels[1] / 10; // In centi-amps
+ uint16_t voltage = USB_PD_Desired_Levels[0]; // in mv
+ /* Add a PDO for the desired power. */
+ cap->obj[numobj++] = PD_PDO_TYPE_FIXED | PD_PDO_SNK_FIXED_VOLTAGE_SET(PD_MV2PDV(voltage)) | PD_PDO_SNK_FIXED_CURRENT_SET(current);
+
+ /* Get the PDO from the voltage range */
+ int8_t i = dpm_get_range_fixed_pdo_index(cap);
+
+ /* If it's vSafe5V, set our vSafe5V's current to what we want */
+ if (i == 0) {
+ cap->obj[0] &= ~PD_PDO_SNK_FIXED_CURRENT;
+ cap->obj[0] |= PD_PDO_SNK_FIXED_CURRENT_SET(current);
+ } else {
+ /* If we want more than 5 V, set the Higher Capability flag */
+ if (PD_MV2PDV(voltage) != PD_MV2PDV(5000)) {
+ cap->obj[0] |= PD_PDO_SNK_FIXED_HIGHER_CAP;
+ }
+
+ /* If the range PDO is a different voltage than the preferred
+ * voltage, add it to the array. */
+ if (i > 0 && PD_PDO_SRC_FIXED_VOLTAGE_GET(cap->obj[i]) != PD_MV2PDV(voltage)) {
+ cap->obj[numobj++] = PD_PDO_TYPE_FIXED | PD_PDO_SNK_FIXED_VOLTAGE_SET(PD_PDO_SRC_FIXED_VOLTAGE_GET(cap->obj[i])) | PD_PDO_SNK_FIXED_CURRENT_SET(PD_PDO_SRC_FIXED_CURRENT_GET(cap->obj[i]));
+ }
+
+ /* If we have three PDOs at this point, make sure the last two are
+ * sorted by voltage. */
+ if (numobj == 3 && (cap->obj[1] & PD_PDO_SNK_FIXED_VOLTAGE) > (cap->obj[2] & PD_PDO_SNK_FIXED_VOLTAGE)) {
+ cap->obj[1] ^= cap->obj[2];
+ cap->obj[2] ^= cap->obj[1];
+ cap->obj[1] ^= cap->obj[2];
+ }
+ }
+
+ /* Set the unconstrained power flag. */
+ if (_unconstrained_power) {
+ cap->obj[0] |= PD_PDO_SNK_FIXED_UNCONSTRAINED;
+ }
+ /* Set the USB communications capable flag. */
+ cap->obj[0] |= PD_PDO_SNK_FIXED_USB_COMMS;
+
+ /* Set the Sink_Capabilities message header */
+ cap->hdr = hdr_template | PD_MSGTYPE_SINK_CAPABILITIES | PD_NUMOBJ(numobj);
}
-bool PolicyEngine::pdbs_dpm_evaluate_typec_current(
- enum fusb_typec_current tcc) {
- (void) tcc;
- //This is for evaluating 5V static current advertised by resistors
- /* We don't control the voltage anymore; it will always be 5 V. */
- current_voltage_mv = _requested_voltage = 5000;
- //For the soldering iron we accept this as a fallback, but it sucks
- pdNegotiationComplete = false;
- return true;
+bool PolicyEngine::pdbs_dpm_evaluate_typec_current(enum fusb_typec_current tcc) {
+ (void)tcc;
+ // This is for evaluating 5V static current advertised by resistors
+ /* We don't control the voltage anymore; it will always be 5 V. */
+ current_voltage_mv = _requested_voltage = 5000;
+ // For the soldering iron we accept this as a fallback, but it sucks
+ pdNegotiationComplete = false;
+ return true;
}
void PolicyEngine::pdbs_dpm_transition_default() {
- /* Cast the dpm_data to the right type */
+ /* Cast the dpm_data to the right type */
- /* Pretend we requested 5 V */
- current_voltage_mv = 5000;
- /* Turn the output off */
- pdNegotiationComplete = false;
+ /* Pretend we requested 5 V */
+ current_voltage_mv = 5000;
+ /* Turn the output off */
+ pdNegotiationComplete = false;
}
void PolicyEngine::pdbs_dpm_transition_requested() {
- /* Cast the dpm_data to the right type */
- pdNegotiationComplete = true;
+ /* Cast the dpm_data to the right type */
+ pdNegotiationComplete = true;
}
-void PolicyEngine::handleMessage(union pd_msg *msg) {
- xQueueSend(messagesWaiting, msg, 100);
-}
+void PolicyEngine::handleMessage(union pd_msg *msg) { xQueueSend(messagesWaiting, msg, 100); }
-bool PolicyEngine::messageWaiting() {
- return uxQueueMessagesWaiting(messagesWaiting) > 0;
-}
+bool PolicyEngine::messageWaiting() { return uxQueueMessagesWaiting(messagesWaiting) > 0; }
-bool PolicyEngine::readMessage() {
- return xQueueReceive(messagesWaiting, &tempMessage, 0) == pdTRUE;
-}
+bool PolicyEngine::readMessage() { return xQueueReceive(messagesWaiting, &tempMessage, 0) == pdTRUE; }
void PolicyEngine::pdbs_dpm_transition_typec() {
-//This means PD failed, so we either have a dump 5V only type C or a QC charger
-//For now; treat this as failed neg
- pdNegotiationComplete = false;
+ // This means PD failed, so we either have a dump 5V only type C or a QC charger
+ // For now; treat this as failed neg
+ pdNegotiationComplete = false;
}
diff --git a/source/Core/Drivers/FUSB302/protocol_rx.cpp b/source/Core/Drivers/FUSB302/protocol_rx.cpp
index 4ab58925..2c87f325 100644
--- a/source/Core/Drivers/FUSB302/protocol_rx.cpp
+++ b/source/Core/Drivers/FUSB302/protocol_rx.cpp
@@ -17,173 +17,167 @@
#include "protocol_rx.h"
-#include <stdlib.h>
-#include "string.h"
-#include <pd.h>
+#include "fusb302b.h"
#include "policy_engine.h"
#include "protocol_tx.h"
-#include "fusb302b.h"
-osThreadId ProtocolReceive::TaskHandle = NULL;
-EventGroupHandle_t ProtocolReceive::xEventGroupHandle = NULL;
-StaticEventGroup_t ProtocolReceive::xCreatedEventGroup;
-uint32_t ProtocolReceive::TaskBuffer[ProtocolReceive::TaskStackSize];
+#include "string.h"
+#include <pd.h>
+#include <stdlib.h>
+osThreadId ProtocolReceive::TaskHandle = NULL;
+EventGroupHandle_t ProtocolReceive::xEventGroupHandle = NULL;
+StaticEventGroup_t ProtocolReceive::xCreatedEventGroup;
+uint32_t ProtocolReceive::TaskBuffer[ProtocolReceive::TaskStackSize];
osStaticThreadDef_t ProtocolReceive::TaskControlBlock;
-union pd_msg ProtocolReceive::tempMessage;
-uint8_t ProtocolReceive::_rx_messageid;
-uint8_t ProtocolReceive::_tx_messageidcounter;
+union pd_msg ProtocolReceive::tempMessage;
+uint8_t ProtocolReceive::_rx_messageid;
+uint8_t ProtocolReceive::_tx_messageidcounter;
/*
* PRL_Rx_Wait_for_PHY_Message state
*/
ProtocolReceive::protocol_rx_state ProtocolReceive::protocol_rx_wait_phy() {
- /* Wait for an event */
- _rx_messageid = 0;
- eventmask_t evt = waitForEvent(
- PDB_EVT_PRLRX_RESET | PDB_EVT_PRLRX_I_GCRCSENT | PDB_EVT_PRLRX_I_RXPEND);
-
- /* If we got a reset event, reset */
- if (evt & PDB_EVT_PRLRX_RESET) {
- waitForEvent(PDB_EVT_PRLRX_RESET, 0);
- return PRLRxWaitPHY;
- }
- /* If we got an I_GCRCSENT event, read the message and decide what to do */
- if (evt & PDB_EVT_PRLRX_I_GCRCSENT) {
- /* Get a buffer to read the message into. Guaranteed to not fail
- * because we have a big enough pool and are careful. */
- union pd_msg *_rx_message = &tempMessage;
- memset(&tempMessage, 0, sizeof(tempMessage));
- /* Read the message */
- fusb_read_message(_rx_message);
- /* If it's a Soft_Reset, go to the soft reset state */
- if (PD_MSGTYPE_GET(_rx_message) == PD_MSGTYPE_SOFT_RESET
- && PD_NUMOBJ_GET(_rx_message) == 0) {
- return PRLRxReset;
- } else {
- /* Otherwise, check the message ID */
- return PRLRxCheckMessageID;
- }
- } else if (evt & PDB_EVT_PRLRX_I_RXPEND) {
- //There is an RX message pending that is not a Good CRC
- union pd_msg *_rx_message = &tempMessage;
- /* Read the message */
- fusb_read_message(_rx_message);
- return PRLRxWaitPHY;
- }
-
- return PRLRxWaitPHY;
+ /* Wait for an event */
+ _rx_messageid = 0;
+ eventmask_t evt = waitForEvent(PDB_EVT_PRLRX_RESET | PDB_EVT_PRLRX_I_GCRCSENT | PDB_EVT_PRLRX_I_RXPEND);
+
+ /* If we got a reset event, reset */
+ if (evt & PDB_EVT_PRLRX_RESET) {
+ waitForEvent(PDB_EVT_PRLRX_RESET, 0);
+ return PRLRxWaitPHY;
+ }
+ /* If we got an I_GCRCSENT event, read the message and decide what to do */
+ if (evt & PDB_EVT_PRLRX_I_GCRCSENT) {
+ /* Get a buffer to read the message into. Guaranteed to not fail
+ * because we have a big enough pool and are careful. */
+ union pd_msg *_rx_message = &tempMessage;
+ memset(&tempMessage, 0, sizeof(tempMessage));
+ /* Read the message */
+ fusb_read_message(_rx_message);
+ /* If it's a Soft_Reset, go to the soft reset state */
+ if (PD_MSGTYPE_GET(_rx_message) == PD_MSGTYPE_SOFT_RESET && PD_NUMOBJ_GET(_rx_message) == 0) {
+ return PRLRxReset;
+ } else {
+ /* Otherwise, check the message ID */
+ return PRLRxCheckMessageID;
+ }
+ } else if (evt & PDB_EVT_PRLRX_I_RXPEND) {
+ // There is an RX message pending that is not a Good CRC
+ union pd_msg *_rx_message = &tempMessage;
+ /* Read the message */
+ fusb_read_message(_rx_message);
+ return PRLRxWaitPHY;
+ }
+
+ return PRLRxWaitPHY;
}
/*
* PRL_Rx_Layer_Reset_for_Receive state
*/
ProtocolReceive::protocol_rx_state ProtocolReceive::protocol_rx_reset() {
- /* Reset MessageIDCounter */
- _tx_messageidcounter = 0;
+ /* Reset MessageIDCounter */
+ _tx_messageidcounter = 0;
- /* Clear stored MessageID */
- _rx_messageid = -1;
+ /* Clear stored MessageID */
+ _rx_messageid = -1;
- /* TX transitions to its reset state */
- ProtocolTransmit::notify(
- ProtocolTransmit::Notifications::PDB_EVT_PRLTX_RESET);
- taskYIELD();
+ /* TX transitions to its reset state */
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_RESET);
+ taskYIELD();
- /* If we got a RESET signal, reset the machine */
- if (waitForEvent(PDB_EVT_PRLRX_RESET, 0) != 0) {
- return PRLRxWaitPHY;
- }
+ /* If we got a RESET signal, reset the machine */
+ if (waitForEvent(PDB_EVT_PRLRX_RESET, 0) != 0) {
+ return PRLRxWaitPHY;
+ }
- /* Go to the Check_MessageID state */
- return PRLRxCheckMessageID;
+ /* Go to the Check_MessageID state */
+ return PRLRxCheckMessageID;
}
volatile uint32_t rxCounter = 0;
/*
* PRL_Rx_Check_MessageID state
*/
ProtocolReceive::protocol_rx_state ProtocolReceive::protocol_rx_check_messageid() {
- /* If we got a RESET signal, reset the machine */
-// if (waitForEvent(PDB_EVT_PRLRX_RESET, 0) == PDB_EVT_PRLRX_RESET) {
-// return PRLRxWaitPHY;
-// }
- /* If the message has the stored ID, we've seen this message before. Free
- * it and don't pass it to the policy engine. */
-
- /* Otherwise, there's either no stored ID or this message has an ID we
- * haven't just seen. Transition to the Store_MessageID state. */
-// if (PD_MESSAGEID_GET(&tempMessage) == _rx_messageid) {
-// return PRLRxWaitPHY;
-// } else
- {
- rxCounter++;
- return PRLRxStoreMessageID;
- }
+ /* If we got a RESET signal, reset the machine */
+ // if (waitForEvent(PDB_EVT_PRLRX_RESET, 0) == PDB_EVT_PRLRX_RESET) {
+ // return PRLRxWaitPHY;
+ // }
+ /* If the message has the stored ID, we've seen this message before. Free
+ * it and don't pass it to the policy engine. */
+
+ /* Otherwise, there's either no stored ID or this message has an ID we
+ * haven't just seen. Transition to the Store_MessageID state. */
+ // if (PD_MESSAGEID_GET(&tempMessage) == _rx_messageid) {
+ // return PRLRxWaitPHY;
+ // } else
+ {
+ rxCounter++;
+ return PRLRxStoreMessageID;
+ }
}
/*
* PRL_Rx_Store_MessageID state
*/
ProtocolReceive::protocol_rx_state ProtocolReceive::protocol_rx_store_messageid() {
- /* Tell ProtocolTX to discard the message being transmitted */
+ /* Tell ProtocolTX to discard the message being transmitted */
- ProtocolTransmit::notify(
- ProtocolTransmit::Notifications::PDB_EVT_PRLTX_DISCARD);
+ ProtocolTransmit::notify(ProtocolTransmit::Notifications::PDB_EVT_PRLTX_DISCARD);
- /* Update the stored MessageID */
- _rx_messageid = PD_MESSAGEID_GET(&tempMessage);
+ /* Update the stored MessageID */
+ _rx_messageid = PD_MESSAGEID_GET(&tempMessage);
- /* Pass the message to the policy engine. */
+ /* Pass the message to the policy engine. */
- PolicyEngine::handleMessage(&tempMessage);
- PolicyEngine::notify(PDB_EVT_PE_MSG_RX);
- taskYIELD();
- /* Don't check if we got a RESET because we'd do nothing different. */
+ PolicyEngine::handleMessage(&tempMessage);
+ PolicyEngine::notify(PDB_EVT_PE_MSG_RX);
+ taskYIELD();
+ /* Don't check if we got a RESET because we'd do nothing different. */
- return PRLRxWaitPHY;
+ return PRLRxWaitPHY;
}
void ProtocolReceive::init() {
- osThreadStaticDef(protRX, thread, PDB_PRIO_PRL, 0, TaskStackSize,
- TaskBuffer, &TaskControlBlock);
- xEventGroupHandle = xEventGroupCreateStatic(&xCreatedEventGroup);
- TaskHandle = osThreadCreate(osThread(protRX), NULL);
+ osThreadStaticDef(protRX, thread, PDB_PRIO_PRL, 0, TaskStackSize, TaskBuffer, &TaskControlBlock);
+ xEventGroupHandle = xEventGroupCreateStatic(&xCreatedEventGroup);
+ TaskHandle = osThreadCreate(osThread(protRX), NULL);
}
void ProtocolReceive::thread(const void *args) {
- (void) args;
- ProtocolReceive::protocol_rx_state state = PRLRxWaitPHY;
-
- while (true) {
- switch (state) {
- case PRLRxWaitPHY:
- state = protocol_rx_wait_phy();
- break;
- case PRLRxReset:
- state = protocol_rx_reset();
- break;
- case PRLRxCheckMessageID:
- state = protocol_rx_check_messageid();
- break;
- case PRLRxStoreMessageID:
- state = protocol_rx_store_messageid();
- break;
- default:
- /* This is an error. It really shouldn't happen. We might
- * want to handle it anyway, though. */
- state = PRLRxWaitPHY;
- break;
- }
- }
+ (void)args;
+ ProtocolReceive::protocol_rx_state state = PRLRxWaitPHY;
+
+ while (true) {
+ switch (state) {
+ case PRLRxWaitPHY:
+ state = protocol_rx_wait_phy();
+ break;
+ case PRLRxReset:
+ state = protocol_rx_reset();
+ break;
+ case PRLRxCheckMessageID:
+ state = protocol_rx_check_messageid();
+ break;
+ case PRLRxStoreMessageID:
+ state = protocol_rx_store_messageid();
+ break;
+ default:
+ /* This is an error. It really shouldn't happen. We might
+ * want to handle it anyway, though. */
+ state = PRLRxWaitPHY;
+ break;
+ }
+ }
}
void ProtocolReceive::notify(uint32_t notification) {
- if (xEventGroupHandle != NULL) {
- xEventGroupSetBits(xEventGroupHandle, notification);
- }
+ if (xEventGroupHandle != NULL) {
+ xEventGroupSetBits(xEventGroupHandle, notification);
+ }
}
uint32_t ProtocolReceive::waitForEvent(uint32_t mask, TickType_t ticksToWait) {
- if (xEventGroupHandle != NULL) {
- return xEventGroupWaitBits(xEventGroupHandle, mask, mask,
- pdFALSE, ticksToWait);
- }
- return 0;
+ if (xEventGroupHandle != NULL) {
+ return xEventGroupWaitBits(xEventGroupHandle, mask, mask, pdFALSE, ticksToWait);
+ }
+ return 0;
}
diff --git a/source/Core/Drivers/FUSB302/protocol_tx.cpp b/source/Core/Drivers/FUSB302/protocol_tx.cpp
index 9f014550..fadc68af 100644
--- a/source/Core/Drivers/FUSB302/protocol_tx.cpp
+++ b/source/Core/Drivers/FUSB302/protocol_tx.cpp
@@ -16,283 +16,268 @@
*/
#include "protocol_tx.h"
-#include <pd.h>
-#include "policy_engine.h"
-#include "protocol_rx.h"
#include "fusb302b.h"
#include "fusbpd.h"
+#include "policy_engine.h"
+#include "protocol_rx.h"
+#include <pd.h>
-osThreadId ProtocolTransmit::TaskHandle = NULL;
-uint32_t ProtocolTransmit::TaskBuffer[ProtocolTransmit::TaskStackSize];
+osThreadId ProtocolTransmit::TaskHandle = NULL;
+uint32_t ProtocolTransmit::TaskBuffer[ProtocolTransmit::TaskStackSize];
osStaticThreadDef_t ProtocolTransmit::TaskControlBlock;
-StaticQueue_t ProtocolTransmit::xStaticQueue;
-bool ProtocolTransmit::messageSending = false;
-uint8_t ProtocolTransmit::ucQueueStorageArea[PDB_MSG_POOL_SIZE
- * sizeof(union pd_msg)];
-QueueHandle_t ProtocolTransmit::messagesWaiting = NULL;
-uint8_t ProtocolTransmit::_tx_messageidcounter;
-union pd_msg ProtocolTransmit::temp_msg;
-EventGroupHandle_t ProtocolTransmit::xEventGroupHandle = NULL;
-StaticEventGroup_t ProtocolTransmit::xCreatedEventGroup;
+StaticQueue_t ProtocolTransmit::xStaticQueue;
+bool ProtocolTransmit::messageSending = false;
+uint8_t ProtocolTransmit::ucQueueStorageArea[PDB_MSG_POOL_SIZE * sizeof(union pd_msg)];
+QueueHandle_t ProtocolTransmit::messagesWaiting = NULL;
+uint8_t ProtocolTransmit::_tx_messageidcounter;
+union pd_msg ProtocolTransmit::temp_msg;
+EventGroupHandle_t ProtocolTransmit::xEventGroupHandle = NULL;
+StaticEventGroup_t ProtocolTransmit::xCreatedEventGroup;
/*
* PRL_Tx_PHY_Layer_Reset state
*/
ProtocolTransmit::protocol_tx_state ProtocolTransmit::protocol_tx_phy_reset() {
- /* Reset the PHY */
- fusb_reset();
-
- /* If a message was pending when we got here, tell the policy engine that
- * we failed to send it */
- if (messagePending()) {
- /* Tell the policy engine that we failed */
- PolicyEngine::notify( PDB_EVT_PE_TX_ERR);
- /* Finish failing to send the message */
- while (messagePending()) {
- getMessage(); //Discard
- }
- }
-
- /* Wait for a message request */
- return PRLTxWaitMessage;
+ /* Reset the PHY */
+ fusb_reset();
+
+ /* If a message was pending when we got here, tell the policy engine that
+ * we failed to send it */
+ if (messagePending()) {
+ /* Tell the policy engine that we failed */
+ PolicyEngine::notify(PDB_EVT_PE_TX_ERR);
+ /* Finish failing to send the message */
+ while (messagePending()) {
+ getMessage(); // Discard
+ }
+ }
+
+ /* Wait for a message request */
+ return PRLTxWaitMessage;
}
/*
* PRL_Tx_Wait_for_Message_Request state
*/
ProtocolTransmit::protocol_tx_state ProtocolTransmit::protocol_tx_wait_message() {
- /* Wait for an event */
- ProtocolTransmit::Notifications evt = waitForEvent(
- (uint32_t) Notifications::PDB_EVT_PRLTX_RESET
- | (uint32_t) Notifications::PDB_EVT_PRLTX_DISCARD
- | (uint32_t) Notifications::PDB_EVT_PRLTX_MSG_TX);
-
- if ((uint32_t) evt & (uint32_t) Notifications::PDB_EVT_PRLTX_RESET) {
- return PRLTxPHYReset;
- }
-
- /* If the policy engine is trying to send a message */
- if ((uint32_t) evt & (uint32_t) Notifications::PDB_EVT_PRLTX_MSG_TX) {
- /* Get the message */
- getMessage();
-
- /* If it's a Soft_Reset, reset the TX layer first */
- if (PD_MSGTYPE_GET(&temp_msg) == PD_MSGTYPE_SOFT_RESET
- && PD_NUMOBJ_GET(&(temp_msg)) == 0) {
- return PRLTxReset;
- /* Otherwise, just send the message */
- } else {
- return PRLTxConstructMessage;
- }
- }
-
- /* Silence the compiler warning */
- return PRLTxWaitMessage;
+ /* Wait for an event */
+ ProtocolTransmit::Notifications evt = waitForEvent((uint32_t)Notifications::PDB_EVT_PRLTX_RESET | (uint32_t)Notifications::PDB_EVT_PRLTX_DISCARD | (uint32_t)Notifications::PDB_EVT_PRLTX_MSG_TX);
+
+ if ((uint32_t)evt & (uint32_t)Notifications::PDB_EVT_PRLTX_RESET) {
+ return PRLTxPHYReset;
+ }
+
+ /* If the policy engine is trying to send a message */
+ if ((uint32_t)evt & (uint32_t)Notifications::PDB_EVT_PRLTX_MSG_TX) {
+ /* Get the message */
+ getMessage();
+
+ /* If it's a Soft_Reset, reset the TX layer first */
+ if (PD_MSGTYPE_GET(&temp_msg) == PD_MSGTYPE_SOFT_RESET && PD_NUMOBJ_GET(&(temp_msg)) == 0) {
+ return PRLTxReset;
+ /* Otherwise, just send the message */
+ } else {
+ return PRLTxConstructMessage;
+ }
+ }
+
+ /* Silence the compiler warning */
+ return PRLTxWaitMessage;
}
ProtocolTransmit::protocol_tx_state ProtocolTransmit::protocol_tx_reset() {
- /* Clear MessageIDCounter */
- _tx_messageidcounter = 0;
+ /* Clear MessageIDCounter */
+ _tx_messageidcounter = 0;
- /* Tell the Protocol RX thread to reset */
- ProtocolReceive::notify( PDB_EVT_PRLRX_RESET);
- taskYIELD();
+ /* Tell the Protocol RX thread to reset */
+ ProtocolReceive::notify(PDB_EVT_PRLRX_RESET);
+ taskYIELD();
- return PRLTxConstructMessage;
+ return PRLTxConstructMessage;
}
/*
* PRL_Tx_Construct_Message state
*/
ProtocolTransmit::protocol_tx_state ProtocolTransmit::protocol_tx_construct_message() {
- /* Set the correct MessageID in the message */
- temp_msg.hdr &= ~PD_HDR_MESSAGEID;
- temp_msg.hdr |= (_tx_messageidcounter % 8) << PD_HDR_MESSAGEID_SHIFT;
-
- /* PD 3.0 collision avoidance */
-// if (PolicyEngine::isPD3_0()) {
-// /* If we're starting an AMS, wait for permission to transmit */
-// evt = waitForEvent((uint32_t) Notifications::PDB_EVT_PRLTX_START_AMS,
-// 0);
-// if ((uint32_t) evt
-// & (uint32_t) Notifications::PDB_EVT_PRLTX_START_AMS) {
-// while (fusb_get_typec_current() != fusb_sink_tx_ok) {
-// osDelay(1);
-// }
-// }
-// }
- messageSending = true;
- /* Send the message to the PHY */
- fusb_send_message(&temp_msg);
-
- return PRLTxWaitResponse;
+ /* Set the correct MessageID in the message */
+ temp_msg.hdr &= ~PD_HDR_MESSAGEID;
+ temp_msg.hdr |= (_tx_messageidcounter % 8) << PD_HDR_MESSAGEID_SHIFT;
+
+ /* PD 3.0 collision avoidance */
+ // if (PolicyEngine::isPD3_0()) {
+ // /* If we're starting an AMS, wait for permission to transmit */
+ // evt = waitForEvent((uint32_t) Notifications::PDB_EVT_PRLTX_START_AMS,
+ // 0);
+ // if ((uint32_t) evt
+ // & (uint32_t) Notifications::PDB_EVT_PRLTX_START_AMS) {
+ // while (fusb_get_typec_current() != fusb_sink_tx_ok) {
+ // osDelay(1);
+ // }
+ // }
+ // }
+ messageSending = true;
+ /* Send the message to the PHY */
+ fusb_send_message(&temp_msg);
+
+ return PRLTxWaitResponse;
}
/*
* PRL_Tx_Wait_for_PHY_Response state
*/
ProtocolTransmit::protocol_tx_state ProtocolTransmit::protocol_tx_wait_response() {
- /* Wait for an event. There is no need to run CRCReceiveTimer, since the
- * FUSB302B handles that as part of its retry mechanism. */
- ProtocolTransmit::Notifications evt = waitForEvent(
- (uint32_t) Notifications::PDB_EVT_PRLTX_RESET
- | (uint32_t) Notifications::PDB_EVT_PRLTX_DISCARD
- | (uint32_t) Notifications::PDB_EVT_PRLTX_I_TXSENT
- | (uint32_t) Notifications::PDB_EVT_PRLTX_I_RETRYFAIL);
-
- if ((uint32_t) evt & (uint32_t) Notifications::PDB_EVT_PRLTX_RESET) {
- return PRLTxPHYReset;
- }
- if ((uint32_t) evt & (uint32_t) Notifications::PDB_EVT_PRLTX_DISCARD) {
- return PRLTxDiscardMessage;
- }
-
- /* If the message was sent successfully */
- if ((uint32_t) evt & (uint32_t) Notifications::PDB_EVT_PRLTX_I_TXSENT) {
- return PRLTxMatchMessageID;
- }
- /* If the message failed to be sent */
- if ((uint32_t) evt & (uint32_t) Notifications::PDB_EVT_PRLTX_I_RETRYFAIL) {
- return PRLTxTransmissionError;
- }
-
- /* Silence the compiler warning */
- return PRLTxDiscardMessage;
+ /* Wait for an event. There is no need to run CRCReceiveTimer, since the
+ * FUSB302B handles that as part of its retry mechanism. */
+ ProtocolTransmit::Notifications evt = waitForEvent((uint32_t)Notifications::PDB_EVT_PRLTX_RESET | (uint32_t)Notifications::PDB_EVT_PRLTX_DISCARD | (uint32_t)Notifications::PDB_EVT_PRLTX_I_TXSENT
+ | (uint32_t)Notifications::PDB_EVT_PRLTX_I_RETRYFAIL);
+
+ if ((uint32_t)evt & (uint32_t)Notifications::PDB_EVT_PRLTX_RESET) {
+ return PRLTxPHYReset;
+ }
+ if ((uint32_t)evt & (uint32_t)Notifications::PDB_EVT_PRLTX_DISCARD) {
+ return PRLTxDiscardMessage;
+ }
+
+ /* If the message was sent successfully */
+ if ((uint32_t)evt & (uint32_t)Notifications::PDB_EVT_PRLTX_I_TXSENT) {
+ return PRLTxMatchMessageID;
+ }
+ /* If the message failed to be sent */
+ if ((uint32_t)evt & (uint32_t)Notifications::PDB_EVT_PRLTX_I_RETRYFAIL) {
+ return PRLTxTransmissionError;
+ }
+
+ /* Silence the compiler warning */
+ return PRLTxDiscardMessage;
}
/*
* PRL_Tx_Match_MessageID state
*/
ProtocolTransmit::protocol_tx_state ProtocolTransmit::protocol_tx_match_messageid() {
- union pd_msg goodcrc;
-
- /* Read the GoodCRC */
- fusb_read_message(&goodcrc);
-
- /* Check that the message is correct */
- if (PD_MSGTYPE_GET(&goodcrc) == PD_MSGTYPE_GOODCRC
- && PD_NUMOBJ_GET(&goodcrc) == 0
- && PD_MESSAGEID_GET(&goodcrc) == _tx_messageidcounter) {
- return PRLTxMessageSent;
- } else {
- return PRLTxTransmissionError;
- }
+ union pd_msg goodcrc;
+
+ /* Read the GoodCRC */
+ fusb_read_message(&goodcrc);
+
+ /* Check that the message is correct */
+ if (PD_MSGTYPE_GET(&goodcrc) == PD_MSGTYPE_GOODCRC && PD_NUMOBJ_GET(&goodcrc) == 0 && PD_MESSAGEID_GET(&goodcrc) == _tx_messageidcounter) {
+ return PRLTxMessageSent;
+ } else {
+ return PRLTxTransmissionError;
+ }
}
ProtocolTransmit::protocol_tx_state ProtocolTransmit::protocol_tx_transmission_error() {
- /* Increment MessageIDCounter */
- _tx_messageidcounter = (_tx_messageidcounter + 1) % 8;
+ /* Increment MessageIDCounter */
+ _tx_messageidcounter = (_tx_messageidcounter + 1) % 8;
- /* Tell the policy engine that we failed */
- PolicyEngine::notify( PDB_EVT_PE_TX_ERR);
+ /* Tell the policy engine that we failed */
+ PolicyEngine::notify(PDB_EVT_PE_TX_ERR);
- return PRLTxWaitMessage;
+ return PRLTxWaitMessage;
}
ProtocolTransmit::protocol_tx_state ProtocolTransmit::protocol_tx_message_sent() {
- messageSending = false;
- /* Increment MessageIDCounter */
- _tx_messageidcounter = (_tx_messageidcounter + 1) % 8;
+ messageSending = false;
+ /* Increment MessageIDCounter */
+ _tx_messageidcounter = (_tx_messageidcounter + 1) % 8;
- /* Tell the policy engine that we succeeded */
- PolicyEngine::notify( PDB_EVT_PE_TX_DONE);
+ /* Tell the policy engine that we succeeded */
+ PolicyEngine::notify(PDB_EVT_PE_TX_DONE);
- return PRLTxWaitMessage;
+ return PRLTxWaitMessage;
}
ProtocolTransmit::protocol_tx_state ProtocolTransmit::protocol_tx_discard_message() {
- /* If we were working on sending a message, increment MessageIDCounter */
- if (messageSending) {
- _tx_messageidcounter = (_tx_messageidcounter + 1) % 8;
-
- return PRLTxPHYReset;
- } else {
- return PRLTxWaitMessage;
- }
+ /* If we were working on sending a message, increment MessageIDCounter */
+ if (messageSending) {
+ _tx_messageidcounter = (_tx_messageidcounter + 1) % 8;
+
+ return PRLTxPHYReset;
+ } else {
+ return PRLTxWaitMessage;
+ }
}
void ProtocolTransmit::thread(const void *args) {
- (void) args;
- ProtocolTransmit::protocol_tx_state state = PRLTxPHYReset;
-
- //Init the incoming message queue
-
- while (true) {
- switch (state) {
- case PRLTxPHYReset:
- state = protocol_tx_phy_reset();
- break;
- case PRLTxWaitMessage:
- state = protocol_tx_wait_message();
- break;
- case PRLTxReset:
- state = protocol_tx_reset();
- break;
- case PRLTxConstructMessage:
- state = protocol_tx_construct_message();
- break;
- case PRLTxWaitResponse:
- state = protocol_tx_wait_response();
- break;
- case PRLTxMatchMessageID:
- state = protocol_tx_match_messageid();
- break;
- case PRLTxTransmissionError:
- state = protocol_tx_transmission_error();
- break;
- case PRLTxMessageSent:
- state = protocol_tx_message_sent();
- break;
- case PRLTxDiscardMessage:
- state = protocol_tx_discard_message();
- break;
- default:
- state = PRLTxPHYReset;
- break;
- }
- }
+ (void)args;
+ ProtocolTransmit::protocol_tx_state state = PRLTxPHYReset;
+
+ // Init the incoming message queue
+
+ while (true) {
+ switch (state) {
+ case PRLTxPHYReset:
+ state = protocol_tx_phy_reset();
+ break;
+ case PRLTxWaitMessage:
+ state = protocol_tx_wait_message();
+ break;
+ case PRLTxReset:
+ state = protocol_tx_reset();
+ break;
+ case PRLTxConstructMessage:
+ state = protocol_tx_construct_message();
+ break;
+ case PRLTxWaitResponse:
+ state = protocol_tx_wait_response();
+ break;
+ case PRLTxMatchMessageID:
+ state = protocol_tx_match_messageid();
+ break;
+ case PRLTxTransmissionError:
+ state = protocol_tx_transmission_error();
+ break;
+ case PRLTxMessageSent:
+ state = protocol_tx_message_sent();
+ break;
+ case PRLTxDiscardMessage:
+ state = protocol_tx_discard_message();
+ break;
+ default:
+ state = PRLTxPHYReset;
+ break;
+ }
+ }
}
void ProtocolTransmit::notify(ProtocolTransmit::Notifications notification) {
- if (xEventGroupHandle != NULL) {
- xEventGroupSetBits(xEventGroupHandle, (uint32_t) notification);
- }
+ if (xEventGroupHandle != NULL) {
+ xEventGroupSetBits(xEventGroupHandle, (uint32_t)notification);
+ }
}
void ProtocolTransmit::init() {
- messagesWaiting = xQueueCreateStatic(PDB_MSG_POOL_SIZE,
- sizeof(union pd_msg), ucQueueStorageArea, &xStaticQueue);
+ messagesWaiting = xQueueCreateStatic(PDB_MSG_POOL_SIZE, sizeof(union pd_msg), ucQueueStorageArea, &xStaticQueue);
- osThreadStaticDef(pd_txTask, thread, PDB_PRIO_PRL, 0, TaskStackSize,
- TaskBuffer, &TaskControlBlock);
- TaskHandle = osThreadCreate(osThread(pd_txTask), NULL);
- xEventGroupHandle = xEventGroupCreateStatic(&xCreatedEventGroup);
+ osThreadStaticDef(pd_txTask, thread, PDB_PRIO_PRL, 0, TaskStackSize, TaskBuffer, &TaskControlBlock);
+ TaskHandle = osThreadCreate(osThread(pd_txTask), NULL);
+ xEventGroupHandle = xEventGroupCreateStatic(&xCreatedEventGroup);
}
void ProtocolTransmit::pushMessage(union pd_msg *msg) {
- if (messagesWaiting) {
- xQueueSend(messagesWaiting, msg, 100);
- }
+ if (messagesWaiting) {
+ xQueueSend(messagesWaiting, msg, 100);
+ }
}
bool ProtocolTransmit::messagePending() {
- if (messagesWaiting) {
- return uxQueueMessagesWaiting(messagesWaiting) > 0;
- }
- return false;
+ if (messagesWaiting) {
+ return uxQueueMessagesWaiting(messagesWaiting) > 0;
+ }
+ return false;
}
void ProtocolTransmit::getMessage() {
- //Loads the pending message into the buffer
- if (messagesWaiting) {
- xQueueReceive(messagesWaiting, &temp_msg, 1);
- }
+ // Loads the pending message into the buffer
+ if (messagesWaiting) {
+ xQueueReceive(messagesWaiting, &temp_msg, 1);
+ }
}
-ProtocolTransmit::Notifications ProtocolTransmit::waitForEvent(uint32_t mask,
- TickType_t ticksToWait) {
- if (xEventGroupHandle) {
- return (Notifications) xEventGroupWaitBits(xEventGroupHandle, mask,
- mask,
- pdFALSE, ticksToWait);
- }
- return (Notifications)0;
+ProtocolTransmit::Notifications ProtocolTransmit::waitForEvent(uint32_t mask, TickType_t ticksToWait) {
+ if (xEventGroupHandle) {
+ return (Notifications)xEventGroupWaitBits(xEventGroupHandle, mask, mask, pdFALSE, ticksToWait);
+ }
+ return (Notifications)0;
}
diff --git a/source/Core/Drivers/I2CBB.cpp b/source/Core/Drivers/I2CBB.cpp
index 200fecfe..07474bfd 100644
--- a/source/Core/Drivers/I2CBB.cpp
+++ b/source/Core/Drivers/I2CBB.cpp
@@ -6,308 +6,299 @@
*/
#include "Model_Config.h"
#ifdef I2C_SOFT
-#include <I2CBB.hpp>
#include "FreeRTOS.h"
+#include <I2CBB.hpp>
SemaphoreHandle_t I2CBB::I2CSemaphore = NULL;
StaticSemaphore_t I2CBB::xSemaphoreBuffer;
SemaphoreHandle_t I2CBB::I2CSemaphore2 = NULL;
StaticSemaphore_t I2CBB::xSemaphoreBuffer2;
-void I2CBB::init() {
- //Set GPIO's to output open drain
- GPIO_InitTypeDef GPIO_InitStruct;
- __HAL_RCC_GPIOA_CLK_ENABLE();
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
- GPIO_InitStruct.Pin = SDA2_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
- GPIO_InitStruct.Pull = GPIO_PULLUP;
- HAL_GPIO_Init(SDA2_GPIO_Port, &GPIO_InitStruct);
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
- GPIO_InitStruct.Pin = SCL2_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
- GPIO_InitStruct.Pull = GPIO_PULLUP;
- HAL_GPIO_Init(SCL2_GPIO_Port, &GPIO_InitStruct);
- SOFT_SDA_HIGH();
- SOFT_SCL_HIGH();
- I2CSemaphore = xSemaphoreCreateMutexStatic(&xSemaphoreBuffer);
- I2CSemaphore2 = xSemaphoreCreateMutexStatic(&xSemaphoreBuffer2);
- unlock();
- unlock2();
-
+void I2CBB::init() {
+ // Set GPIO's to output open drain
+ GPIO_InitTypeDef GPIO_InitStruct;
+ __HAL_RCC_GPIOA_CLK_ENABLE();
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
+ GPIO_InitStruct.Pin = SDA2_Pin;
+ GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
+ GPIO_InitStruct.Pull = GPIO_PULLUP;
+ HAL_GPIO_Init(SDA2_GPIO_Port, &GPIO_InitStruct);
+ GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
+ GPIO_InitStruct.Pin = SCL2_Pin;
+ GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
+ GPIO_InitStruct.Pull = GPIO_PULLUP;
+ HAL_GPIO_Init(SCL2_GPIO_Port, &GPIO_InitStruct);
+ SOFT_SDA_HIGH();
+ SOFT_SCL_HIGH();
+ I2CSemaphore = xSemaphoreCreateMutexStatic(&xSemaphoreBuffer);
+ I2CSemaphore2 = xSemaphoreCreateMutexStatic(&xSemaphoreBuffer2);
+ unlock();
+ unlock2();
}
bool I2CBB::probe(uint8_t address) {
- if (!lock())
- return false;
- start();
- bool ack = send(address);
- stop();
- unlock();
- return ack;
+ if (!lock())
+ return false;
+ start();
+ bool ack = send(address);
+ stop();
+ unlock();
+ return ack;
}
-bool I2CBB::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData,
- uint16_t Size) {
- if (!lock())
- return false;
- start();
- bool ack = send(DevAddress);
- if (!ack) {
- stop();
- unlock();
- return false;
- }
- ack = send(MemAddress);
- if (!ack) {
- stop();
- unlock();
- return false;
- }
- SOFT_SCL_LOW();
- SOFT_I2C_DELAY();
-// stop();
- start();
- ack = send(DevAddress | 1);
- if (!ack) {
- stop();
- unlock();
- return false;
- }
- while (Size) {
- pData[0] = read(Size > 1);
- pData++;
- Size--;
- }
- stop();
- unlock();
- return true;
+bool I2CBB::Mem_Read(uint16_t DevAddress, uint16_t MemAddress, uint8_t *pData, uint16_t Size) {
+ if (!lock())
+ return false;
+ start();
+ bool ack = send(DevAddress);
+ if (!ack) {
+ stop();
+ unlock();
+ return false;
+ }
+ ack = send(MemAddress);
+ if (!ack) {
+ stop();
+ unlock();
+ return false;
+ }
+ SOFT_SCL_LOW();
+ SOFT_I2C_DELAY();
+ // stop();
+ start();
+ ack = send(DevAddress | 1);
+ if (!ack) {
+ stop();
+ unlock();
+ return false;
+ }
+ while (Size) {
+ pData[0] = read(Size > 1);
+ pData++;
+ Size--;
+ }
+ stop();
+ unlock();
+ return true;
}
-bool I2CBB::Mem_Write(uint16_t DevAddress, uint16_t MemAddress,
- const uint8_t *pData, uint16_t Size) {
- if (!lock())
- return false;
- start();
- bool ack = send(DevAddress);
- if (!ack) {
- stop();
- asm("bkpt");
- unlock();
- return false;
- }
- ack = send(MemAddress);
- if (!ack) {
- stop();
- asm("bkpt");
- unlock();
- return false;
- }
- while (Size) {
- resetWatchdog();
- ack = send(pData[0]);
- if (!ack) {
- stop();
- asm("bkpt");
- unlock();
- return false;
- }
- pData++;
- Size--;
- }
- stop();
- unlock();
- return true;
+bool I2CBB::Mem_Write(uint16_t DevAddress, uint16_t MemAddress, const uint8_t *pData, uint16_t Size) {
+ if (!lock())
+ return false;
+ start();
+ bool ack = send(DevAddress);
+ if (!ack) {
+ stop();
+ asm("bkpt");
+ unlock();
+ return false;
+ }
+ ack = send(MemAddress);
+ if (!ack) {
+ stop();
+ asm("bkpt");
+ unlock();
+ return false;
+ }
+ while (Size) {
+ resetWatchdog();
+ ack = send(pData[0]);
+ if (!ack) {
+ stop();
+ asm("bkpt");
+ unlock();
+ return false;
+ }
+ pData++;
+ Size--;
+ }
+ stop();
+ unlock();
+ return true;
}
void I2CBB::Transmit(uint16_t DevAddress, uint8_t *pData, uint16_t Size) {
- if (!lock())
- return;
- start();
- bool ack = send(DevAddress);
- if (!ack) {
- stop();
- unlock();
- return;
- }
- while (Size) {
- ack = send(pData[0]);
- if (!ack) {
- stop();
- unlock();
- return;
- }
- pData++;
- Size--;
- }
- stop();
- unlock();
-
+ if (!lock())
+ return;
+ start();
+ bool ack = send(DevAddress);
+ if (!ack) {
+ stop();
+ unlock();
+ return;
+ }
+ while (Size) {
+ ack = send(pData[0]);
+ if (!ack) {
+ stop();
+ unlock();
+ return;
+ }
+ pData++;
+ Size--;
+ }
+ stop();
+ unlock();
}
void I2CBB::Receive(uint16_t DevAddress, uint8_t *pData, uint16_t Size) {
- if (!lock())
- return;
- start();
- bool ack = send(DevAddress | 1);
- if (!ack) {
- stop();
- unlock();
- return;
- }
- while (Size) {
- pData[0] = read(Size > 1);
- pData++;
- Size--;
- }
- stop();
- unlock();
+ if (!lock())
+ return;
+ start();
+ bool ack = send(DevAddress | 1);
+ if (!ack) {
+ stop();
+ unlock();
+ return;
+ }
+ while (Size) {
+ pData[0] = read(Size > 1);
+ pData++;
+ Size--;
+ }
+ stop();
+ unlock();
}
-void I2CBB::TransmitReceive(uint16_t DevAddress, uint8_t *pData_tx,
- uint16_t Size_tx, uint8_t *pData_rx, uint16_t Size_rx) {
- if (Size_tx == 0 && Size_rx == 0)
- return;
- if (lock() == false)
- return;
- if (Size_tx) {
- start();
- bool ack = send(DevAddress);
- if (!ack) {
- stop();
- unlock();
- return;
- }
- while (Size_tx) {
- ack = send(pData_tx[0]);
- if (!ack) {
- stop();
- unlock();
- return;
- }
- pData_tx++;
- Size_tx--;
- }
- }
- if (Size_rx) {
- start();
- bool ack = send(DevAddress | 1);
- if (!ack) {
- stop();
- unlock();
- return;
- }
- while (Size_rx) {
- pData_rx[0] = read(Size_rx > 1);
- pData_rx++;
- Size_rx--;
- }
- }
- stop();
- unlock();
+void I2CBB::TransmitReceive(uint16_t DevAddress, uint8_t *pData_tx, uint16_t Size_tx, uint8_t *pData_rx, uint16_t Size_rx) {
+ if (Size_tx == 0 && Size_rx == 0)
+ return;
+ if (lock() == false)
+ return;
+ if (Size_tx) {
+ start();
+ bool ack = send(DevAddress);
+ if (!ack) {
+ stop();
+ unlock();
+ return;
+ }
+ while (Size_tx) {
+ ack = send(pData_tx[0]);
+ if (!ack) {
+ stop();
+ unlock();
+ return;
+ }
+ pData_tx++;
+ Size_tx--;
+ }
+ }
+ if (Size_rx) {
+ start();
+ bool ack = send(DevAddress | 1);
+ if (!ack) {
+ stop();
+ unlock();
+ return;
+ }
+ while (Size_rx) {
+ pData_rx[0] = read(Size_rx > 1);
+ pData_rx++;
+ Size_rx--;
+ }
+ }
+ stop();
+ unlock();
}
void I2CBB::start() {
- /* I2C Start condition, data line goes low when clock is high */
- SOFT_SCL_HIGH();
- SOFT_SDA_HIGH();
- SOFT_I2C_DELAY();
- SOFT_SDA_LOW();
- SOFT_I2C_DELAY();
- SOFT_SCL_LOW();
- SOFT_I2C_DELAY();
- SOFT_SDA_HIGH();
+ /* I2C Start condition, data line goes low when clock is high */
+ SOFT_SCL_HIGH();
+ SOFT_SDA_HIGH();
+ SOFT_I2C_DELAY();
+ SOFT_SDA_LOW();
+ SOFT_I2C_DELAY();
+ SOFT_SCL_LOW();
+ SOFT_I2C_DELAY();
+ SOFT_SDA_HIGH();
}
void I2CBB::stop() {
- /* I2C Stop condition, clock goes high when data is low */
- SOFT_SDA_LOW();
- SOFT_I2C_DELAY();
- SOFT_SCL_HIGH();
- SOFT_I2C_DELAY();
- SOFT_SDA_HIGH();
- SOFT_I2C_DELAY();
+ /* I2C Stop condition, clock goes high when data is low */
+ SOFT_SDA_LOW();
+ SOFT_I2C_DELAY();
+ SOFT_SCL_HIGH();
+ SOFT_I2C_DELAY();
+ SOFT_SDA_HIGH();
+ SOFT_I2C_DELAY();
}
bool I2CBB::send(uint8_t value) {
- for (uint8_t i = 0; i < 8; i++) {
- write_bit(value & 0x80); // write the most-significant bit
- value <<= 1;
- }
+ for (uint8_t i = 0; i < 8; i++) {
+ write_bit(value & 0x80); // write the most-significant bit
+ value <<= 1;
+ }
- SOFT_SDA_HIGH();
- bool ack = (read_bit() == 0);
- return ack;
+ SOFT_SDA_HIGH();
+ bool ack = (read_bit() == 0);
+ return ack;
}
uint8_t I2CBB::read(bool ack) {
- uint8_t B = 0;
+ uint8_t B = 0;
- uint8_t i;
- for (i = 0; i < 8; i++) {
- B <<= 1;
- B |= read_bit();
- }
+ uint8_t i;
+ for (i = 0; i < 8; i++) {
+ B <<= 1;
+ B |= read_bit();
+ }
- SOFT_SDA_HIGH();
- if (ack)
- write_bit(0);
- else
- write_bit(1);
- return B;
+ SOFT_SDA_HIGH();
+ if (ack)
+ write_bit(0);
+ else
+ write_bit(1);
+ return B;
}
uint8_t I2CBB::read_bit() {
- uint8_t b;
+ uint8_t b;
- SOFT_SDA_HIGH();
- SOFT_I2C_DELAY();
- SOFT_SCL_HIGH();
- SOFT_I2C_DELAY();
+ SOFT_SDA_HIGH();
+ SOFT_I2C_DELAY();
+ SOFT_SCL_HIGH();
+ SOFT_I2C_DELAY();
- if (SOFT_SDA_READ())
- b = 1;
- else
- b = 0;
+ if (SOFT_SDA_READ())
+ b = 1;
+ else
+ b = 0;
- SOFT_SCL_LOW();
- return b;
+ SOFT_SCL_LOW();
+ return b;
}
-void I2CBB::unlock() {
- xSemaphoreGive(I2CSemaphore);
-}
+void I2CBB::unlock() { xSemaphoreGive(I2CSemaphore); }
bool I2CBB::lock() {
- if (I2CSemaphore == NULL) {
- asm("bkpt");
- }
- bool a = xSemaphoreTake(I2CSemaphore, (TickType_t) 100) == pdTRUE;
- return a;
+ if (I2CSemaphore == NULL) {
+ asm("bkpt");
+ }
+ bool a = xSemaphoreTake(I2CSemaphore, (TickType_t)100) == pdTRUE;
+ return a;
}
void I2CBB::write_bit(uint8_t val) {
- if (val) {
- SOFT_SDA_HIGH();
- } else {
- SOFT_SDA_LOW();
- }
+ if (val) {
+ SOFT_SDA_HIGH();
+ } else {
+ SOFT_SDA_LOW();
+ }
- SOFT_I2C_DELAY();
- SOFT_SCL_HIGH();
- SOFT_I2C_DELAY();
- SOFT_SCL_LOW();
+ SOFT_I2C_DELAY();
+ SOFT_SCL_HIGH();
+ SOFT_I2C_DELAY();
+ SOFT_SCL_LOW();
}
-void I2CBB::unlock2() {
- xSemaphoreGive(I2CSemaphore2);
-}
+void I2CBB::unlock2() { xSemaphoreGive(I2CSemaphore2); }
bool I2CBB::lock2() {
- if (I2CSemaphore2 == NULL) {
- asm("bkpt");
- }
- bool a = xSemaphoreTake(I2CSemaphore2, (TickType_t) 500) == pdTRUE;
+ if (I2CSemaphore2 == NULL) {
+ asm("bkpt");
+ }
+ bool a = xSemaphoreTake(I2CSemaphore2, (TickType_t)500) == pdTRUE;
- return a;
+ return a;
}
#endif
diff --git a/source/Core/Drivers/LIS2DH12.cpp b/source/Core/Drivers/LIS2DH12.cpp
index 02aad5b6..6aea8ba2 100644
--- a/source/Core/Drivers/LIS2DH12.cpp
+++ b/source/Core/Drivers/LIS2DH12.cpp
@@ -10,34 +10,30 @@
#include "LIS2DH12.hpp"
#include "cmsis_os.h"
-static const FRToSI2C::I2C_REG i2c_registers[] = { { LIS_CTRL_REG1, 0x17, 0 }, // 25Hz
- { LIS_CTRL_REG2, 0b00001000, 0 }, // Highpass filter off
- { LIS_CTRL_REG3, 0b01100000, 0 }, // Setup interrupt pins
- { LIS_CTRL_REG4, 0b00001000, 0 }, // Block update mode off, HR on
- { LIS_CTRL_REG5, 0b00000010, 0 }, //
- { LIS_CTRL_REG6, 0b01100010, 0 },
- //Basically setup the unit to run, and enable 4D orientation detection
- { LIS_INT2_CFG, 0b01111110, 0 }, //setup for movement detection
- { LIS_INT2_THS, 0x28, 0 }, //
- { LIS_INT2_DURATION, 64, 0 }, //
- { LIS_INT1_CFG, 0b01111110, 0 }, //
- { LIS_INT1_THS, 0x28, 0 }, //
- { LIS_INT1_DURATION, 64, 0 } };
-
-bool LIS2DH12::initalize() {
- return FRToSI2C::writeRegistersBulk(LIS2DH_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0]));
-}
+static const FRToSI2C::I2C_REG i2c_registers[] = {{LIS_CTRL_REG1, 0x17, 0}, // 25Hz
+ {LIS_CTRL_REG2, 0b00001000, 0}, // Highpass filter off
+ {LIS_CTRL_REG3, 0b01100000, 0}, // Setup interrupt pins
+ {LIS_CTRL_REG4, 0b00001000, 0}, // Block update mode off, HR on
+ {LIS_CTRL_REG5, 0b00000010, 0}, //
+ {LIS_CTRL_REG6, 0b01100010, 0},
+ // Basically setup the unit to run, and enable 4D orientation detection
+ {LIS_INT2_CFG, 0b01111110, 0}, // setup for movement detection
+ {LIS_INT2_THS, 0x28, 0}, //
+ {LIS_INT2_DURATION, 64, 0}, //
+ {LIS_INT1_CFG, 0b01111110, 0}, //
+ {LIS_INT1_THS, 0x28, 0}, //
+ {LIS_INT1_DURATION, 64, 0}};
+
+bool LIS2DH12::initalize() { return FRToSI2C::writeRegistersBulk(LIS2DH_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); }
void LIS2DH12::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) {
- std::array<int16_t, 3> sensorData;
+ std::array<int16_t, 3> sensorData;
- FRToSI2C::Mem_Read(LIS2DH_I2C_ADDRESS, 0xA8, reinterpret_cast<uint8_t*>(sensorData.begin()), sensorData.size() * sizeof(int16_t));
+ FRToSI2C::Mem_Read(LIS2DH_I2C_ADDRESS, 0xA8, reinterpret_cast<uint8_t *>(sensorData.begin()), sensorData.size() * sizeof(int16_t));
- x = sensorData[0];
- y = sensorData[1];
- z = sensorData[2];
+ x = sensorData[0];
+ y = sensorData[1];
+ z = sensorData[2];
}
-bool LIS2DH12::detect() {
- return FRToSI2C::probe(LIS2DH_I2C_ADDRESS);
-}
+bool LIS2DH12::detect() { return FRToSI2C::probe(LIS2DH_I2C_ADDRESS); }
diff --git a/source/Core/Drivers/MMA8652FC.cpp b/source/Core/Drivers/MMA8652FC.cpp
index fa8b91fe..3d0fa0d7 100644
--- a/source/Core/Drivers/MMA8652FC.cpp
+++ b/source/Core/Drivers/MMA8652FC.cpp
@@ -10,54 +10,48 @@
#include "MMA8652FC.hpp"
#include "cmsis_os.h"
-
-static const FRToSI2C::I2C_REG i2c_registers[] = { { CTRL_REG2, 0, 0 }, //Normal mode
- { CTRL_REG2, 0x40, 2 }, // Reset all registers to POR values
- { FF_MT_CFG_REG, 0x78, 0 }, // Enable motion detection for X, Y, Z axis, latch disabled
- { PL_CFG_REG, 0x40, 0 }, //Enable the orientation detection
- { PL_COUNT_REG, 200, 0 }, //200 count debounce
- { PL_BF_ZCOMP_REG, 0b01000111, 0 }, //Set the threshold to 42 degrees
- { P_L_THS_REG, 0b10011100, 0 }, //Up the trip angles
- { CTRL_REG4, 0x01 | (1 << 4), 0 }, // Enable dataready interrupt & orientation interrupt
- { CTRL_REG5, 0x01, 0 }, // Route data ready interrupts to INT1 ->PB5 ->EXTI5, leaving orientation routed to INT2
- { CTRL_REG2, 0x12, 0 }, //Set maximum resolution oversampling
- { XYZ_DATA_CFG_REG, (1 << 4), 0 }, //select high pass filtered data
- { HP_FILTER_CUTOFF_REG, 0x03, 0 }, //select high pass filtered data
- { CTRL_REG1, 0x19, 0 } // ODR=12 Hz, Active mode
+static const FRToSI2C::I2C_REG i2c_registers[] = {
+ {CTRL_REG2, 0, 0}, // Normal mode
+ {CTRL_REG2, 0x40, 2}, // Reset all registers to POR values
+ {FF_MT_CFG_REG, 0x78, 0}, // Enable motion detection for X, Y, Z axis, latch disabled
+ {PL_CFG_REG, 0x40, 0}, // Enable the orientation detection
+ {PL_COUNT_REG, 200, 0}, // 200 count debounce
+ {PL_BF_ZCOMP_REG, 0b01000111, 0}, // Set the threshold to 42 degrees
+ {P_L_THS_REG, 0b10011100, 0}, // Up the trip angles
+ {CTRL_REG4, 0x01 | (1 << 4), 0}, // Enable dataready interrupt & orientation interrupt
+ {CTRL_REG5, 0x01, 0}, // Route data ready interrupts to INT1 ->PB5 ->EXTI5, leaving orientation routed to INT2
+ {CTRL_REG2, 0x12, 0}, // Set maximum resolution oversampling
+ {XYZ_DATA_CFG_REG, (1 << 4), 0}, // select high pass filtered data
+ {HP_FILTER_CUTOFF_REG, 0x03, 0}, // select high pass filtered data
+ {CTRL_REG1, 0x19, 0} // ODR=12 Hz, Active mode
};
-bool MMA8652FC::initalize() {
- return FRToSI2C::writeRegistersBulk(MMA8652FC_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0]));
-
-}
+bool MMA8652FC::initalize() { return FRToSI2C::writeRegistersBulk(MMA8652FC_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); }
Orientation MMA8652FC::getOrientation() {
- //First read the PL_STATUS register
- uint8_t plStatus = FRToSI2C::I2C_RegisterRead(MMA8652FC_I2C_ADDRESS,
- PL_STATUS_REG);
- if ((plStatus & 0b10000000) == 0b10000000) {
- plStatus >>= 1; //We don't need the up/down bit
- plStatus &= 0x03; //mask to the two lower bits
+ // First read the PL_STATUS register
+ uint8_t plStatus = FRToSI2C::I2C_RegisterRead(MMA8652FC_I2C_ADDRESS, PL_STATUS_REG);
+ if ((plStatus & 0b10000000) == 0b10000000) {
+ plStatus >>= 1; // We don't need the up/down bit
+ plStatus &= 0x03; // mask to the two lower bits
- //0 == left handed
- //1 == right handed
+ // 0 == left handed
+ // 1 == right handed
- return static_cast<Orientation>(plStatus);
- }
+ return static_cast<Orientation>(plStatus);
+ }
- return ORIENTATION_FLAT;
+ return ORIENTATION_FLAT;
}
void MMA8652FC::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) {
- std::array<int16_t, 3> sensorData;
+ std::array<int16_t, 3> sensorData;
- FRToSI2C::Mem_Read(MMA8652FC_I2C_ADDRESS, OUT_X_MSB_REG, reinterpret_cast<uint8_t*>(sensorData.begin()), sensorData.size() * sizeof(int16_t));
+ FRToSI2C::Mem_Read(MMA8652FC_I2C_ADDRESS, OUT_X_MSB_REG, reinterpret_cast<uint8_t *>(sensorData.begin()), sensorData.size() * sizeof(int16_t));
- x = static_cast<int16_t>(__builtin_bswap16(*reinterpret_cast<uint16_t*>(&sensorData[0])));
- y = static_cast<int16_t>(__builtin_bswap16(*reinterpret_cast<uint16_t*>(&sensorData[1])));
- z = static_cast<int16_t>(__builtin_bswap16(*reinterpret_cast<uint16_t*>(&sensorData[2])));
+ x = static_cast<int16_t>(__builtin_bswap16(*reinterpret_cast<uint16_t *>(&sensorData[0])));
+ y = static_cast<int16_t>(__builtin_bswap16(*reinterpret_cast<uint16_t *>(&sensorData[1])));
+ z = static_cast<int16_t>(__builtin_bswap16(*reinterpret_cast<uint16_t *>(&sensorData[2])));
}
-bool MMA8652FC::detect() {
- return FRToSI2C::probe(MMA8652FC_I2C_ADDRESS);
-}
+bool MMA8652FC::detect() { return FRToSI2C::probe(MMA8652FC_I2C_ADDRESS); }
diff --git a/source/Core/Drivers/MSA301.cpp b/source/Core/Drivers/MSA301.cpp
index ceaf4522..a3d64de8 100644
--- a/source/Core/Drivers/MSA301.cpp
+++ b/source/Core/Drivers/MSA301.cpp
@@ -5,46 +5,42 @@
* Author: Ralim
*/
-#include <MSA301.h>
#include "MSA301_defines.h"
+#include <MSA301.h>
#define MSA301_I2C_ADDRESS 0x4C
-bool MSA301::detect() {
- return FRToSI2C::probe(MSA301_I2C_ADDRESS);
-}
+bool MSA301::detect() { return FRToSI2C::probe(MSA301_I2C_ADDRESS); }
-static const FRToSI2C::I2C_REG i2c_registers[] = { //
- //
- { MSA301_REG_ODR, 0b00001000, 1 }, //X/Y/Z enabled @ 250Hz
- { MSA301_REG_POWERMODE, 0b0001001, 1 }, // Normal mode
- { MSA301_REG_RESRANGE, 0b00000001, 0 }, // 14bit resolution @ 4G range
- { MSA301_REG_ORIENT_HY, 0b01000000, 0 }, // 4*62.5mg hyst, no blocking, symmetrical
- { MSA301_REG_INTSET0, 1 << 6, 0 }, // Turn on orientation detection (by enabling its interrupt)
+static const FRToSI2C::I2C_REG i2c_registers[] = {
+ //
+ //
+ {MSA301_REG_ODR, 0b00001000, 1}, // X/Y/Z enabled @ 250Hz
+ {MSA301_REG_POWERMODE, 0b0001001, 1}, // Normal mode
+ {MSA301_REG_RESRANGE, 0b00000001, 0}, // 14bit resolution @ 4G range
+ {MSA301_REG_ORIENT_HY, 0b01000000, 0}, // 4*62.5mg hyst, no blocking, symmetrical
+ {MSA301_REG_INTSET0, 1 << 6, 0}, // Turn on orientation detection (by enabling its interrupt)
- };
+};
-bool MSA301::initalize() {
- return FRToSI2C::writeRegistersBulk(MSA301_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0]));
-}
+bool MSA301::initalize() { return FRToSI2C::writeRegistersBulk(MSA301_I2C_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0])); }
Orientation MSA301::getOrientation() {
- uint8_t temp = 0;
- FRToSI2C::Mem_Read(MSA301_I2C_ADDRESS, MSA301_REG_ORIENT_STATUS, &temp, 1);
- switch (temp) {
- case 112:
- return Orientation::ORIENTATION_LEFT_HAND;
- case 96:
- return Orientation::ORIENTATION_RIGHT_HAND;
- default:
- return Orientation::ORIENTATION_FLAT;
- }
+ uint8_t temp = 0;
+ FRToSI2C::Mem_Read(MSA301_I2C_ADDRESS, MSA301_REG_ORIENT_STATUS, &temp, 1);
+ switch (temp) {
+ case 112:
+ return Orientation::ORIENTATION_LEFT_HAND;
+ case 96:
+ return Orientation::ORIENTATION_RIGHT_HAND;
+ default:
+ return Orientation::ORIENTATION_FLAT;
+ }
}
void MSA301::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) {
- uint8_t temp[6];
- //Bulk read all 6 regs
- FRToSI2C::Mem_Read(MSA301_I2C_ADDRESS, MSA301_REG_OUT_X_L, temp, 6);
- x = int16_t(((int16_t) temp[1]) << 8 | temp[0]) >> 2;
- y = int16_t(((int16_t) temp[3]) << 8 | temp[2]) >> 2;
- z = int16_t(((int16_t) temp[5]) << 8 | temp[4]) >> 2;
-
+ uint8_t temp[6];
+ // Bulk read all 6 regs
+ FRToSI2C::Mem_Read(MSA301_I2C_ADDRESS, MSA301_REG_OUT_X_L, temp, 6);
+ x = int16_t(((int16_t)temp[1]) << 8 | temp[0]) >> 2;
+ y = int16_t(((int16_t)temp[3]) << 8 | temp[2]) >> 2;
+ z = int16_t(((int16_t)temp[5]) << 8 | temp[4]) >> 2;
}
diff --git a/source/Core/Drivers/OLED.cpp b/source/Core/Drivers/OLED.cpp
index 776aa7b5..f939d724 100644
--- a/source/Core/Drivers/OLED.cpp
+++ b/source/Core/Drivers/OLED.cpp
@@ -5,63 +5,63 @@
* Author: Ben V. Brown
*/
-#include <string.h>
-#include <OLED.hpp>
-#include <stdlib.h>
+#include "../../configuration.h"
#include "Translation.h"
#include "cmsis_os.h"
-#include "../../configuration.h"
+#include <OLED.hpp>
+#include <stdlib.h>
+#include <string.h>
-const uint8_t *OLED::currentFont; // Pointer to the current font used for
+const uint8_t *OLED::currentFont; // Pointer to the current font used for
// rendering to the buffer
-uint8_t *OLED::firstStripPtr; // Pointers to the strips to allow for buffer
+uint8_t *OLED::firstStripPtr; // Pointers to the strips to allow for buffer
// having extra content
-uint8_t *OLED::secondStripPtr; // Pointers to the strips
-bool OLED::inLeftHandedMode; // Whether the screen is in left or not (used for
+uint8_t *OLED::secondStripPtr; // Pointers to the strips
+bool OLED::inLeftHandedMode; // Whether the screen is in left or not (used for
// offsets in GRAM)
OLED::DisplayState OLED::displayState;
-uint8_t OLED::fontWidth, OLED::fontHeight;
-int16_t OLED::cursor_x, OLED::cursor_y;
-bool OLED::initDone = false;
-uint8_t OLED::displayOffset;
-uint8_t OLED::screenBuffer[16 + (OLED_WIDTH * 2) + 10]; // The data buffer
-uint8_t OLED::secondFrameBuffer[OLED_WIDTH * 2];
+uint8_t OLED::fontWidth, OLED::fontHeight;
+int16_t OLED::cursor_x, OLED::cursor_y;
+bool OLED::initDone = false;
+uint8_t OLED::displayOffset;
+uint8_t OLED::screenBuffer[16 + (OLED_WIDTH * 2) + 10]; // The data buffer
+uint8_t OLED::secondFrameBuffer[OLED_WIDTH * 2];
/*Setup params for the OLED screen*/
/*http://www.displayfuture.com/Display/datasheet/controller/SSD1307.pdf*/
/*All commands are prefixed with 0x80*/
/*Data packets are prefixed with 0x40*/
FRToSI2C::I2C_REG OLED_Setup_Array[] = {
-/**/
-{ 0x80, 0xAE, 0 }, /*Display off*/
-{ 0x80, 0xD5, 0 }, /*Set display clock divide ratio / osc freq*/
-{ 0x80, 0x52, 0 }, /*Divide ratios*/
-{ 0x80, 0xA8, 0 }, /*Set Multiplex Ratio*/
-{ 0x80, 0x0F, 0 }, /*16 == max brightness,39==dimmest*/
-{ 0x80, 0xC0, 0 }, /*Set COM Scan direction*/
-{ 0x80, 0xD3, 0 }, /*Set vertical Display offset*/
-{ 0x80, 0x00, 0 }, /*0 Offset*/
-{ 0x80, 0x40, 0 }, /*Set Display start line to 0*/
-{ 0x80, 0xA0, 0 }, /*Set Segment remap to normal*/
-{ 0x80, 0x8D, 0 }, /*Charge Pump*/
-{ 0x80, 0x14, 0 }, /*Charge Pump settings*/
-{ 0x80, 0xDA, 0 }, /*Set VCOM Pins hardware config*/
-{ 0x80, 0x02, 0 }, /*Combination 2*/
-{ 0x80, 0x81, 0 }, /*Contrast*/
-{ 0x80, 0x33, 0 }, /*^51*/
-{ 0x80, 0xD9, 0 }, /*Set pre-charge period*/
-{ 0x80, 0xF1, 0 }, /*Pre charge period*/
-{ 0x80, 0xDB, 0 }, /*Adjust VCOMH regulator ouput*/
-{ 0x80, 0x30, 0 }, /*VCOM level*/
-{ 0x80, 0xA4, 0 }, /*Enable the display GDDR*/
-{ 0x80, 0XA6, 0 }, /*Normal display*/
-{ 0x80, 0x20, 0 }, /*Memory Mode*/
-{ 0x80, 0x00, 0 }, /*Wrap memory*/
-{ 0x80, 0xAF, 0 }, /*Display on*/
+ /**/
+ {0x80, 0xAE, 0}, /*Display off*/
+ {0x80, 0xD5, 0}, /*Set display clock divide ratio / osc freq*/
+ {0x80, 0x52, 0}, /*Divide ratios*/
+ {0x80, 0xA8, 0}, /*Set Multiplex Ratio*/
+ {0x80, 0x0F, 0}, /*16 == max brightness,39==dimmest*/
+ {0x80, 0xC0, 0}, /*Set COM Scan direction*/
+ {0x80, 0xD3, 0}, /*Set vertical Display offset*/
+ {0x80, 0x00, 0}, /*0 Offset*/
+ {0x80, 0x40, 0}, /*Set Display start line to 0*/
+ {0x80, 0xA0, 0}, /*Set Segment remap to normal*/
+ {0x80, 0x8D, 0}, /*Charge Pump*/
+ {0x80, 0x14, 0}, /*Charge Pump settings*/
+ {0x80, 0xDA, 0}, /*Set VCOM Pins hardware config*/
+ {0x80, 0x02, 0}, /*Combination 2*/
+ {0x80, 0x81, 0}, /*Contrast*/
+ {0x80, 0x33, 0}, /*^51*/
+ {0x80, 0xD9, 0}, /*Set pre-charge period*/
+ {0x80, 0xF1, 0}, /*Pre charge period*/
+ {0x80, 0xDB, 0}, /*Adjust VCOMH regulator ouput*/
+ {0x80, 0x30, 0}, /*VCOM level*/
+ {0x80, 0xA4, 0}, /*Enable the display GDDR*/
+ {0x80, 0XA6, 0}, /*Normal display*/
+ {0x80, 0x20, 0}, /*Memory Mode*/
+ {0x80, 0x00, 0}, /*Wrap memory*/
+ {0x80, 0xAF, 0}, /*Display on*/
};
// Setup based on the SSD1307 and modified for the SSD1306
-const uint8_t REFRESH_COMMANDS[17] = { 0x80, 0xAF, 0x80, 0x21, 0x80, 0x20, 0x80, 0x7F, 0x80, 0xC0, 0x80, 0x22, 0x80, 0x00, 0x80, 0x01, 0x40 };
+const uint8_t REFRESH_COMMANDS[17] = {0x80, 0xAF, 0x80, 0x21, 0x80, 0x20, 0x80, 0x7F, 0x80, 0xC0, 0x80, 0x22, 0x80, 0x00, 0x80, 0x01, 0x40};
/*
* Animation timing function that follows a bezier curve.
@@ -69,9 +69,7 @@ const uint8_t REFRESH_COMMANDS[17] = { 0x80, 0xAF, 0x80, 0x21, 0x80, 0x20, 0x80,
* Returns a new percentage value with ease in and ease out.
* Original floating point formula: t * t * (3.0f - 2.0f * t);
*/
-static uint8_t easeInOutTiming(uint8_t t) {
- return t * t * (300 - 2 * t) / 10000;
-}
+static uint8_t easeInOutTiming(uint8_t t) { return t * t * (300 - 2 * t) / 10000; }
/*
* Returns the value between a and b, using a percentage value t.
@@ -79,41 +77,39 @@ static uint8_t easeInOutTiming(uint8_t t) {
* @param b The value associated with 100%
* @param t The percentage [0..<100]
*/
-static uint8_t lerp(uint8_t a, uint8_t b, uint8_t t) {
- return a + t * (b - a) / 100;
-}
+static uint8_t lerp(uint8_t a, uint8_t b, uint8_t t) { return a + t * (b - a) / 100; }
void OLED::initialize() {
- cursor_x = cursor_y = 0;
- currentFont = USER_FONT_12;
- fontWidth = 12;
- inLeftHandedMode = false;
- firstStripPtr = &screenBuffer[FRAMEBUFFER_START];
- secondStripPtr = &screenBuffer[FRAMEBUFFER_START + OLED_WIDTH];
- fontHeight = 16;
- displayOffset = 0;
- memcpy(&screenBuffer[0], &REFRESH_COMMANDS[0], sizeof(REFRESH_COMMANDS));
-
- // Set the display to be ON once the settings block is sent and send the
- // initialisation data to the OLED.
-
- for (int tries = 0; tries < 10; tries++) {
- if (FRToSI2C::writeRegistersBulk(DEVICEADDR_OLED, OLED_Setup_Array, sizeof(OLED_Setup_Array) / sizeof(OLED_Setup_Array[0]))) {
- return;
- }
- }
- setDisplayState(DisplayState::ON);
- initDone = true;
+ cursor_x = cursor_y = 0;
+ currentFont = USER_FONT_12;
+ fontWidth = 12;
+ inLeftHandedMode = false;
+ firstStripPtr = &screenBuffer[FRAMEBUFFER_START];
+ secondStripPtr = &screenBuffer[FRAMEBUFFER_START + OLED_WIDTH];
+ fontHeight = 16;
+ displayOffset = 0;
+ memcpy(&screenBuffer[0], &REFRESH_COMMANDS[0], sizeof(REFRESH_COMMANDS));
+
+ // Set the display to be ON once the settings block is sent and send the
+ // initialisation data to the OLED.
+
+ for (int tries = 0; tries < 10; tries++) {
+ if (FRToSI2C::writeRegistersBulk(DEVICEADDR_OLED, OLED_Setup_Array, sizeof(OLED_Setup_Array) / sizeof(OLED_Setup_Array[0]))) {
+ return;
+ }
+ }
+ setDisplayState(DisplayState::ON);
+ initDone = true;
}
void OLED::setFramebuffer(uint8_t *buffer) {
- if (buffer == NULL) {
- firstStripPtr = &screenBuffer[FRAMEBUFFER_START];
- secondStripPtr = &screenBuffer[FRAMEBUFFER_START + OLED_WIDTH];
- return;
- }
-
- firstStripPtr = &buffer[0];
- secondStripPtr = &buffer[OLED_WIDTH];
+ if (buffer == NULL) {
+ firstStripPtr = &screenBuffer[FRAMEBUFFER_START];
+ secondStripPtr = &screenBuffer[FRAMEBUFFER_START + OLED_WIDTH];
+ return;
+ }
+
+ firstStripPtr = &buffer[0];
+ secondStripPtr = &buffer[OLED_WIDTH];
}
/*
@@ -122,18 +118,18 @@ void OLED::setFramebuffer(uint8_t *buffer) {
* Precursor is the command char that is used to select the table.
*/
void OLED::drawChar(char c) {
- if (c == '\x01' && cursor_y == 0) { // 0x01 is used as new line char
- cursor_x = 0;
- cursor_y = 8;
- return;
- } else if (c == 0) {
- return;
- }
- uint16_t index = c - 2; //First index is \x02
- uint8_t *charPointer;
- charPointer = ((uint8_t*) currentFont) + ((fontWidth * (fontHeight / 8)) * index);
- drawArea(cursor_x, cursor_y, fontWidth, fontHeight, charPointer);
- cursor_x += fontWidth;
+ if (c == '\x01' && cursor_y == 0) { // 0x01 is used as new line char
+ cursor_x = 0;
+ cursor_y = 8;
+ return;
+ } else if (c == 0) {
+ return;
+ }
+ uint16_t index = c - 2; // First index is \x02
+ uint8_t *charPointer;
+ charPointer = ((uint8_t *)currentFont) + ((fontWidth * (fontHeight / 8)) * index);
+ drawArea(cursor_x, cursor_y, fontWidth, fontHeight, charPointer);
+ cursor_x += fontWidth;
}
/*
@@ -141,18 +137,18 @@ void OLED::drawChar(char c) {
* of the indicator in pixels (0..<16).
*/
void OLED::drawScrollIndicator(uint8_t y, uint8_t height) {
- union u_type {
- uint16_t whole;
- uint8_t strips[2];
- } column;
-
- column.whole = (1 << height) - 1;
- column.whole <<= y;
-
- // Draw a one pixel wide bar to the left with a single pixel as
- // the scroll indicator.
- fillArea(OLED_WIDTH - 1, 0, 1, 8, column.strips[0]);
- fillArea(OLED_WIDTH - 1, 8, 1, 8, column.strips[1]);
+ union u_type {
+ uint16_t whole;
+ uint8_t strips[2];
+ } column;
+
+ column.whole = (1 << height) - 1;
+ column.whole <<= y;
+
+ // Draw a one pixel wide bar to the left with a single pixel as
+ // the scroll indicator.
+ fillArea(OLED_WIDTH - 1, 0, 1, 8, column.strips[0]);
+ fillArea(OLED_WIDTH - 1, 8, 1, 8, column.strips[1]);
}
/**
@@ -163,327 +159,323 @@ void OLED::drawScrollIndicator(uint8_t y, uint8_t height) {
* Otherwise a rewinding navigation animation is shown to the second framebuffer contents.
*/
void OLED::transitionSecondaryFramebuffer(bool forwardNavigation) {
- uint8_t *firstBackStripPtr = &secondFrameBuffer[0];
- uint8_t *secondBackStripPtr = &secondFrameBuffer[OLED_WIDTH];
-
- uint32_t totalDuration = 50; // 500ms
- uint32_t duration = 0;
- uint32_t start = xTaskGetTickCount();
- uint8_t offset = 0;
-
- while (duration <= totalDuration) {
- duration = xTaskGetTickCount() - start;
- uint8_t progress = duration * TICKS_SECOND / totalDuration;
- progress = easeInOutTiming(progress);
- progress = lerp(0, OLED_WIDTH, progress);
- if (progress > OLED_WIDTH) {
- progress = OLED_WIDTH;
- }
-
-// When forward, current contents move to the left out.
-// Otherwise the contents move to the right out.
- uint8_t oldStart = forwardNavigation ? 0 : progress;
- uint8_t oldPrevious = forwardNavigation ? progress - offset : offset;
-
-// Content from the second framebuffer moves in from the right (forward)
-// or from the left (not forward).
- uint8_t newStart = forwardNavigation ? OLED_WIDTH - progress : 0;
- uint8_t newEnd = forwardNavigation ? 0 : OLED_WIDTH - progress;
-
- offset = progress;
-
- memmove(&firstStripPtr[oldStart], &firstStripPtr[oldPrevious],
- OLED_WIDTH - progress);
- memmove(&secondStripPtr[oldStart], &secondStripPtr[oldPrevious],
- OLED_WIDTH - progress);
-
- memmove(&firstStripPtr[newStart], &firstBackStripPtr[newEnd], progress);
- memmove(&secondStripPtr[newStart], &secondBackStripPtr[newEnd], progress);
-
- refresh();
- osDelay(40);
- }
+ uint8_t *firstBackStripPtr = &secondFrameBuffer[0];
+ uint8_t *secondBackStripPtr = &secondFrameBuffer[OLED_WIDTH];
+
+ uint32_t totalDuration = 50; // 500ms
+ uint32_t duration = 0;
+ uint32_t start = xTaskGetTickCount();
+ uint8_t offset = 0;
+
+ while (duration <= totalDuration) {
+ duration = xTaskGetTickCount() - start;
+ uint8_t progress = duration * TICKS_SECOND / totalDuration;
+ progress = easeInOutTiming(progress);
+ progress = lerp(0, OLED_WIDTH, progress);
+ if (progress > OLED_WIDTH) {
+ progress = OLED_WIDTH;
+ }
+
+ // When forward, current contents move to the left out.
+ // Otherwise the contents move to the right out.
+ uint8_t oldStart = forwardNavigation ? 0 : progress;
+ uint8_t oldPrevious = forwardNavigation ? progress - offset : offset;
+
+ // Content from the second framebuffer moves in from the right (forward)
+ // or from the left (not forward).
+ uint8_t newStart = forwardNavigation ? OLED_WIDTH - progress : 0;
+ uint8_t newEnd = forwardNavigation ? 0 : OLED_WIDTH - progress;
+
+ offset = progress;
+
+ memmove(&firstStripPtr[oldStart], &firstStripPtr[oldPrevious], OLED_WIDTH - progress);
+ memmove(&secondStripPtr[oldStart], &secondStripPtr[oldPrevious], OLED_WIDTH - progress);
+
+ memmove(&firstStripPtr[newStart], &firstBackStripPtr[newEnd], progress);
+ memmove(&secondStripPtr[newStart], &secondBackStripPtr[newEnd], progress);
+
+ refresh();
+ osDelay(40);
+ }
}
void OLED::useSecondaryFramebuffer(bool useSecondary) {
- if (useSecondary) {
- setFramebuffer(secondFrameBuffer);
- } else {
- setFramebuffer(NULL);
- }
+ if (useSecondary) {
+ setFramebuffer(secondFrameBuffer);
+ } else {
+ setFramebuffer(NULL);
+ }
}
void OLED::setRotation(bool leftHanded) {
#ifdef OLED_FLIP
- leftHanded = !leftHanded;
+ leftHanded = !leftHanded;
#endif
- if (inLeftHandedMode == leftHanded) {
- return;
- }
-
- // send command struct again with changes
- if (leftHanded) {
- OLED_Setup_Array[5].val = 0xC8; // c1?
- OLED_Setup_Array[9].val = 0xA1;
- } else {
- OLED_Setup_Array[5].val = 0xC0;
- OLED_Setup_Array[9].val = 0xA0;
- }
- FRToSI2C::writeRegistersBulk(DEVICEADDR_OLED, OLED_Setup_Array, sizeof(OLED_Setup_Array) / sizeof(OLED_Setup_Array[0]));
-
- inLeftHandedMode = leftHanded;
-
- screenBuffer[5] = inLeftHandedMode ? 0 : 32; // display is shifted by 32 in left handed
- // mode as driver ram is 128 wide
- screenBuffer[7] = inLeftHandedMode ? 95 : 0x7F; // End address of the ram segment we are writing to (96 wide)
- screenBuffer[9] = inLeftHandedMode ? 0xC8 : 0xC0;
+ if (inLeftHandedMode == leftHanded) {
+ return;
+ }
+
+ // send command struct again with changes
+ if (leftHanded) {
+ OLED_Setup_Array[5].val = 0xC8; // c1?
+ OLED_Setup_Array[9].val = 0xA1;
+ } else {
+ OLED_Setup_Array[5].val = 0xC0;
+ OLED_Setup_Array[9].val = 0xA0;
+ }
+ FRToSI2C::writeRegistersBulk(DEVICEADDR_OLED, OLED_Setup_Array, sizeof(OLED_Setup_Array) / sizeof(OLED_Setup_Array[0]));
+
+ inLeftHandedMode = leftHanded;
+
+ screenBuffer[5] = inLeftHandedMode ? 0 : 32; // display is shifted by 32 in left handed
+ // mode as driver ram is 128 wide
+ screenBuffer[7] = inLeftHandedMode ? 95 : 0x7F; // End address of the ram segment we are writing to (96 wide)
+ screenBuffer[9] = inLeftHandedMode ? 0xC8 : 0xC0;
}
// print a string to the current cursor location
void OLED::print(const char *str) {
- while (str[0]) {
- drawChar(str[0]);
- str++;
- }
+ while (str[0]) {
+ drawChar(str[0]);
+ str++;
+ }
}
void OLED::setFont(uint8_t fontNumber) {
- if (fontNumber == 1) {
-// small font
- currentFont = USER_FONT_6x8;
- fontHeight = 8;
- fontWidth = 6;
- } else if (fontNumber == 2) {
- currentFont = ExtraFontChars;
- fontHeight = 16;
- fontWidth = 12;
- } else {
- currentFont = USER_FONT_12;
- fontHeight = 16;
- fontWidth = 12;
- }
+ if (fontNumber == 1) {
+ // small font
+ currentFont = USER_FONT_6x8;
+ fontHeight = 8;
+ fontWidth = 6;
+ } else if (fontNumber == 2) {
+ currentFont = ExtraFontChars;
+ fontHeight = 16;
+ fontWidth = 12;
+ } else {
+ currentFont = USER_FONT_12;
+ fontHeight = 16;
+ fontWidth = 12;
+ }
}
uint8_t OLED::getFont() {
- if (currentFont == USER_FONT_6x8)
- return 1;
- else if (currentFont == ExtraFontChars)
- return 2;
- else
- return 0;
+ if (currentFont == USER_FONT_6x8)
+ return 1;
+ else if (currentFont == ExtraFontChars)
+ return 2;
+ else
+ return 0;
}
inline void stripLeaderZeros(char *buffer, uint8_t places) {
- //Removing the leading zero's by swapping them to SymbolSpace
- // Stop 1 short so that we dont blank entire number if its zero
- for (int i = 0; i < (places - 1); i++) {
- if (buffer[i] == 2) {
- buffer[i] = SymbolSpace[0];
- } else {
- return;
- }
- }
+ // Removing the leading zero's by swapping them to SymbolSpace
+ // Stop 1 short so that we dont blank entire number if its zero
+ for (int i = 0; i < (places - 1); i++) {
+ if (buffer[i] == 2) {
+ buffer[i] = SymbolSpace[0];
+ } else {
+ return;
+ }
+ }
}
// maximum places is 5
void OLED::printNumber(uint16_t number, uint8_t places, bool noLeaderZeros) {
- char buffer[7] = { 0 };
-
- if (places >= 5) {
- buffer[5] = 2 + number % 10;
- number /= 10;
- }
- if (places > 4) {
- buffer[4] = 2 + number % 10;
- number /= 10;
- }
-
- if (places > 3) {
- buffer[3] = 2 + number % 10;
- number /= 10;
- }
-
- if (places > 2) {
- buffer[2] = 2 + number % 10;
- number /= 10;
- }
-
- if (places > 1) {
- buffer[1] = 2 + number % 10;
- number /= 10;
- }
-
- buffer[0] = 2 + number % 10;
- if (noLeaderZeros)
- stripLeaderZeros(buffer, places);
- print(buffer);
+ char buffer[7] = {0};
+
+ if (places >= 5) {
+ buffer[5] = 2 + number % 10;
+ number /= 10;
+ }
+ if (places > 4) {
+ buffer[4] = 2 + number % 10;
+ number /= 10;
+ }
+
+ if (places > 3) {
+ buffer[3] = 2 + number % 10;
+ number /= 10;
+ }
+
+ if (places > 2) {
+ buffer[2] = 2 + number % 10;
+ number /= 10;
+ }
+
+ if (places > 1) {
+ buffer[1] = 2 + number % 10;
+ number /= 10;
+ }
+
+ buffer[0] = 2 + number % 10;
+ if (noLeaderZeros)
+ stripLeaderZeros(buffer, places);
+ print(buffer);
}
void OLED::debugNumber(int32_t val) {
- if (abs(val) > 99999) {
- OLED::print(SymbolSpace); // out of bounds
- return;
- }
- if (val >= 0) {
- OLED::print(SymbolSpace);
- OLED::printNumber(val, 5);
- } else {
- OLED::print(SymbolMinus);
- OLED::printNumber(-val, 5);
- }
+ if (abs(val) > 99999) {
+ OLED::print(SymbolSpace); // out of bounds
+ return;
+ }
+ if (val >= 0) {
+ OLED::print(SymbolSpace);
+ OLED::printNumber(val, 5);
+ } else {
+ OLED::print(SymbolMinus);
+ OLED::printNumber(-val, 5);
+ }
}
void OLED::drawSymbol(uint8_t symbolID) {
- // draw a symbol to the current cursor location
- setFont(2);
- drawChar(symbolID + 2);
- setFont(0);
+ // draw a symbol to the current cursor location
+ setFont(2);
+ drawChar(symbolID + 2);
+ setFont(0);
}
// Draw an area, but y must be aligned on 0/8 offset
void OLED::drawArea(int16_t x, int8_t y, uint8_t wide, uint8_t height, const uint8_t *ptr) {
- // Splat this from x->x+wide in two strides
- if (x <= -wide)
- return; // cutoffleft
- if (x > 96)
- return; // cutoff right
-
- uint8_t visibleStart = 0;
- uint8_t visibleEnd = wide;
-
- // trimming to draw partials
- if (x < 0) {
- visibleStart -= x; // subtract negative value == add absolute value
- }
- if (x + wide > 96) {
- visibleEnd = 96 - x;
- }
-
- if (y == 0) {
-// Splat first line of data
- for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) {
- firstStripPtr[xx + x] = ptr[xx];
- }
- }
- if (y == 8 || height == 16) {
-// Splat the second line
- for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) {
- secondStripPtr[x + xx] = ptr[xx + (height == 16 ? wide : 0)];
- }
- }
+ // Splat this from x->x+wide in two strides
+ if (x <= -wide)
+ return; // cutoffleft
+ if (x > 96)
+ return; // cutoff right
+
+ uint8_t visibleStart = 0;
+ uint8_t visibleEnd = wide;
+
+ // trimming to draw partials
+ if (x < 0) {
+ visibleStart -= x; // subtract negative value == add absolute value
+ }
+ if (x + wide > 96) {
+ visibleEnd = 96 - x;
+ }
+
+ if (y == 0) {
+ // Splat first line of data
+ for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) {
+ firstStripPtr[xx + x] = ptr[xx];
+ }
+ }
+ if (y == 8 || height == 16) {
+ // Splat the second line
+ for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) {
+ secondStripPtr[x + xx] = ptr[xx + (height == 16 ? wide : 0)];
+ }
+ }
}
// Draw an area, but y must be aligned on 0/8 offset
// For data which has octets swapped in a 16-bit word.
void OLED::drawAreaSwapped(int16_t x, int8_t y, uint8_t wide, uint8_t height, const uint8_t *ptr) {
- // Splat this from x->x+wide in two strides
- if (x <= -wide)
- return; // cutoffleft
- if (x > 96)
- return; // cutoff right
-
- uint8_t visibleStart = 0;
- uint8_t visibleEnd = wide;
-
- // trimming to draw partials
- if (x < 0) {
- visibleStart -= x; // subtract negative value == add absolute value
- }
- if (x + wide > 96) {
- visibleEnd = 96 - x;
- }
-
- if (y == 0) {
- // Splat first line of data
- for (uint8_t xx = visibleStart; xx < visibleEnd; xx += 2) {
- firstStripPtr[xx + x] = ptr[xx + 1];
- firstStripPtr[xx + x + 1] = ptr[xx];
- }
- }
- if (y == 8 || height == 16) {
- // Splat the second line
- for (uint8_t xx = visibleStart; xx < visibleEnd; xx += 2) {
- secondStripPtr[x + xx] = ptr[xx + 1 + (height == 16 ? wide : 0)];
- secondStripPtr[x + xx + 1] = ptr[xx + (height == 16 ? wide : 0)];
- }
- }
+ // Splat this from x->x+wide in two strides
+ if (x <= -wide)
+ return; // cutoffleft
+ if (x > 96)
+ return; // cutoff right
+
+ uint8_t visibleStart = 0;
+ uint8_t visibleEnd = wide;
+
+ // trimming to draw partials
+ if (x < 0) {
+ visibleStart -= x; // subtract negative value == add absolute value
+ }
+ if (x + wide > 96) {
+ visibleEnd = 96 - x;
+ }
+
+ if (y == 0) {
+ // Splat first line of data
+ for (uint8_t xx = visibleStart; xx < visibleEnd; xx += 2) {
+ firstStripPtr[xx + x] = ptr[xx + 1];
+ firstStripPtr[xx + x + 1] = ptr[xx];
+ }
+ }
+ if (y == 8 || height == 16) {
+ // Splat the second line
+ for (uint8_t xx = visibleStart; xx < visibleEnd; xx += 2) {
+ secondStripPtr[x + xx] = ptr[xx + 1 + (height == 16 ? wide : 0)];
+ secondStripPtr[x + xx + 1] = ptr[xx + (height == 16 ? wide : 0)];
+ }
+ }
}
void OLED::fillArea(int16_t x, int8_t y, uint8_t wide, uint8_t height, const uint8_t value) {
- // Splat this from x->x+wide in two strides
- if (x <= -wide)
- return; // cutoffleft
- if (x > 96)
- return; // cutoff right
-
- uint8_t visibleStart = 0;
- uint8_t visibleEnd = wide;
-
- // trimming to draw partials
- if (x < 0) {
- visibleStart -= x; // subtract negative value == add absolute value
- }
- if (x + wide > 96) {
- visibleEnd = 96 - x;
- }
-
- if (y == 0) {
-// Splat first line of data
- for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) {
- firstStripPtr[xx + x] = value;
- }
- }
- if (y == 8 || height == 16) {
-// Splat the second line
- for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) {
- secondStripPtr[x + xx] = value;
- }
- }
+ // Splat this from x->x+wide in two strides
+ if (x <= -wide)
+ return; // cutoffleft
+ if (x > 96)
+ return; // cutoff right
+
+ uint8_t visibleStart = 0;
+ uint8_t visibleEnd = wide;
+
+ // trimming to draw partials
+ if (x < 0) {
+ visibleStart -= x; // subtract negative value == add absolute value
+ }
+ if (x + wide > 96) {
+ visibleEnd = 96 - x;
+ }
+
+ if (y == 0) {
+ // Splat first line of data
+ for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) {
+ firstStripPtr[xx + x] = value;
+ }
+ }
+ if (y == 8 || height == 16) {
+ // Splat the second line
+ for (uint8_t xx = visibleStart; xx < visibleEnd; xx++) {
+ secondStripPtr[x + xx] = value;
+ }
+ }
}
void OLED::drawFilledRect(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1, bool clear) {
- // Draw this in 3 sections
- // This is basically a N wide version of vertical line
-
- // Step 1 : Draw in the top few pixels that are not /8 aligned
- // LSB is at the top of the screen
- uint8_t mask = 0xFF;
- if (y0) {
- mask = mask << (y0 % 8);
- for (uint8_t col = x0; col < x1; col++)
- if (clear)
- firstStripPtr[(y0 / 8) * 96 + col] &= ~mask;
- else
- firstStripPtr[(y0 / 8) * 96 + col] |= mask;
- }
- // Next loop down the line the total number of solids
- if (y0 / 8 != y1 / 8)
- for (uint8_t col = x0; col < x1; col++)
- for (uint8_t r = (y0 / 8); r < (y1 / 8); r++) {
- // This gives us the row index r
- if (clear)
- firstStripPtr[(r * 96) + col] = 0;
- else
- firstStripPtr[(r * 96) + col] = 0xFF;
- }
-
- // Finally draw the tail
- mask = ~(mask << (y1 % 8));
- for (uint8_t col = x0; col < x1; col++)
- if (clear)
- firstStripPtr[(y1 / 8) * 96 + col] &= ~mask;
- else
- firstStripPtr[(y1 / 8) * 96 + col] |= mask;
+ // Draw this in 3 sections
+ // This is basically a N wide version of vertical line
+
+ // Step 1 : Draw in the top few pixels that are not /8 aligned
+ // LSB is at the top of the screen
+ uint8_t mask = 0xFF;
+ if (y0) {
+ mask = mask << (y0 % 8);
+ for (uint8_t col = x0; col < x1; col++)
+ if (clear)
+ firstStripPtr[(y0 / 8) * 96 + col] &= ~mask;
+ else
+ firstStripPtr[(y0 / 8) * 96 + col] |= mask;
+ }
+ // Next loop down the line the total number of solids
+ if (y0 / 8 != y1 / 8)
+ for (uint8_t col = x0; col < x1; col++)
+ for (uint8_t r = (y0 / 8); r < (y1 / 8); r++) {
+ // This gives us the row index r
+ if (clear)
+ firstStripPtr[(r * 96) + col] = 0;
+ else
+ firstStripPtr[(r * 96) + col] = 0xFF;
+ }
+
+ // Finally draw the tail
+ mask = ~(mask << (y1 % 8));
+ for (uint8_t col = x0; col < x1; col++)
+ if (clear)
+ firstStripPtr[(y1 / 8) * 96 + col] &= ~mask;
+ else
+ firstStripPtr[(y1 / 8) * 96 + col] |= mask;
}
void OLED::drawHeatSymbol(uint8_t state) {
- // Draw symbol 14
- // Then draw over it, the bottom 5 pixels always stay. 8 pixels above that are
- // the levels masks the symbol nicely
- state /= 31; // 0-> 8 range
- // Then we want to draw down (16-(5+state)
- uint8_t cursor_x_temp = cursor_x;
- drawSymbol(14);
- drawFilledRect(cursor_x_temp, 0, cursor_x_temp + 12, 2 + (8 - state), true);
+ // Draw symbol 14
+ // Then draw over it, the bottom 5 pixels always stay. 8 pixels above that are
+ // the levels masks the symbol nicely
+ state /= 31; // 0-> 8 range
+ // Then we want to draw down (16-(5+state)
+ uint8_t cursor_x_temp = cursor_x;
+ drawSymbol(14);
+ drawFilledRect(cursor_x_temp, 0, cursor_x_temp + 12, 2 + (8 - state), true);
}
-bool OLED::isInitDone() {
- return initDone;
-}
+bool OLED::isInitDone() { return initDone; }
diff --git a/source/Core/Drivers/SC7A20.cpp b/source/Core/Drivers/SC7A20.cpp
index 7bebb29d..b6b7ee4f 100644
--- a/source/Core/Drivers/SC7A20.cpp
+++ b/source/Core/Drivers/SC7A20.cpp
@@ -10,60 +10,59 @@
#include <array>
bool SC7A20::detect() {
- if (FRToSI2C::probe(SC7A20_ADDRESS)) {
- //Read chip id to ensure its not an address collision
- uint8_t id = 0;
- if (FRToSI2C::Mem_Read(SC7A20_ADDRESS, SC7A20_WHO_AMI_I, &id, 1)) {
- return id == 0b00010001;
- }
- }
+ if (FRToSI2C::probe(SC7A20_ADDRESS)) {
+ // Read chip id to ensure its not an address collision
+ uint8_t id = 0;
+ if (FRToSI2C::Mem_Read(SC7A20_ADDRESS, SC7A20_WHO_AMI_I, &id, 1)) {
+ return id == 0b00010001;
+ }
+ }
- return false;
+ return false;
}
-static const FRToSI2C::I2C_REG i2c_registers[] = { //
- //
- { SC7A20_CTRL_REG1, 0b01100111, 0 }, //200Hz, XYZ enabled
- { SC7A20_CTRL_REG2, 0b00000000, 0 }, //Setup filter to 0x00 ??
- { SC7A20_CTRL_REG3, 0b00000000, 0 }, //int1 off
- { SC7A20_CTRL_REG4, 0b01001000, 0 }, //Block mode off,little-endian,2G,High-pres,self test off
- { SC7A20_CTRL_REG5, 0b00000100, 0 }, //fifo off, D4D on int1
- { SC7A20_CTRL_REG6, 0x00, 0 }, //INT2 off
- //Basically setup the unit to run, and enable 4D orientation detection
- { SC7A20_INT2_CFG, 0b01111110, 0 }, //setup for movement detection
- { SC7A20_INT2_THS, 0x28, 0 }, //
- { SC7A20_INT2_DURATION, 64, 0 }, //
- { SC7A20_INT1_CFG, 0b01111110, 0 }, //
- { SC7A20_INT1_THS, 0x28, 0 }, //
- { SC7A20_INT1_DURATION, 64, 0 }
+static const FRToSI2C::I2C_REG i2c_registers[] = {
+ //
+ //
+ {SC7A20_CTRL_REG1, 0b01100111, 0}, // 200Hz, XYZ enabled
+ {SC7A20_CTRL_REG2, 0b00000000, 0}, // Setup filter to 0x00 ??
+ {SC7A20_CTRL_REG3, 0b00000000, 0}, // int1 off
+ {SC7A20_CTRL_REG4, 0b01001000, 0}, // Block mode off,little-endian,2G,High-pres,self test off
+ {SC7A20_CTRL_REG5, 0b00000100, 0}, // fifo off, D4D on int1
+ {SC7A20_CTRL_REG6, 0x00, 0}, // INT2 off
+ // Basically setup the unit to run, and enable 4D orientation detection
+ {SC7A20_INT2_CFG, 0b01111110, 0}, // setup for movement detection
+ {SC7A20_INT2_THS, 0x28, 0}, //
+ {SC7A20_INT2_DURATION, 64, 0}, //
+ {SC7A20_INT1_CFG, 0b01111110, 0}, //
+ {SC7A20_INT1_THS, 0x28, 0}, //
+ {SC7A20_INT1_DURATION, 64, 0}
- //
- };
+ //
+};
bool SC7A20::initalize() {
- //Setup acceleration readings
- //2G range
- //bandwidth = 250Hz
- //High pass filter on (Slow compensation)
- //Turn off IRQ output pins
- //Orientation recognition in symmetrical mode
- // Hysteresis is set to ~ 16 counts
- //Theta blocking is set to 0b10
-
- return FRToSI2C::writeRegistersBulk(SC7A20_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0]));
+ // Setup acceleration readings
+ // 2G range
+ // bandwidth = 250Hz
+ // High pass filter on (Slow compensation)
+ // Turn off IRQ output pins
+ // Orientation recognition in symmetrical mode
+ // Hysteresis is set to ~ 16 counts
+ // Theta blocking is set to 0b10
+ return FRToSI2C::writeRegistersBulk(SC7A20_ADDRESS, i2c_registers, sizeof(i2c_registers) / sizeof(i2c_registers[0]));
}
void SC7A20::getAxisReadings(int16_t &x, int16_t &y, int16_t &z) {
- //We can tell the accelerometer to output in LE mode which makes this simple
- uint16_t sensorData[3] = { 0, 0, 0 };
-
- if (FRToSI2C::Mem_Read(SC7A20_ADDRESS, SC7A20_OUT_X_L, (uint8_t*) sensorData, 6) == false) {
- x = y = z = 0;
- return;
- }
- //Shift 6 to make its range ~= the other accelerometers
- x = sensorData[0];
- y = sensorData[1];
- z = sensorData[2];
+ // We can tell the accelerometer to output in LE mode which makes this simple
+ uint16_t sensorData[3] = {0, 0, 0};
+ if (FRToSI2C::Mem_Read(SC7A20_ADDRESS, SC7A20_OUT_X_L, (uint8_t *)sensorData, 6) == false) {
+ x = y = z = 0;
+ return;
+ }
+ // Shift 6 to make its range ~= the other accelerometers
+ x = sensorData[0];
+ y = sensorData[1];
+ z = sensorData[2];
}
diff --git a/source/Core/Drivers/Si7210.cpp b/source/Core/Drivers/Si7210.cpp
index b3eae4ae..642e481c 100644
--- a/source/Core/Drivers/Si7210.cpp
+++ b/source/Core/Drivers/Si7210.cpp
@@ -10,175 +10,168 @@
* This class is licensed as MIT to match this code base
*/
-#include <Si7210.h>
-#include "Si7210_defines.h"
#include "I2C_Wrapper.hpp"
-bool Si7210::detect() {
- return FRToSI2C::wakePart(SI7210_ADDRESS);
-
-}
+#include "Si7210_defines.h"
+#include <Si7210.h>
+bool Si7210::detect() { return FRToSI2C::wakePart(SI7210_ADDRESS); }
bool Si7210::init() {
- //Turn on auto increment and sanity check ID
- //Load OTP cal
-
- uint8_t temp;
- if (FRToSI2C::Mem_Read(SI7210_ADDRESS, SI7210_REG_ID, &temp, 1)) {
- // We don't really care what model it is etc, just probing to check its probably this iC
- if (temp != 0x00 && temp != 0xFF) {
- temp = 0x00;
-
- /* Set device and internal driver settings */
- if (!write_reg( SI7210_CTRL1, (uint8_t) ~SW_LOW4FIELD_MASK, 0)) {
- return false;
- }
-
- /* Disable periodic auto-wakeup by device, and tamper detect. */
- if ((!write_reg(SI7210_CTRL3, (uint8_t) ~SL_TIMEENA_MASK, 0)))
- return false;
-
- /* Disable tamper detection by setting sw_tamper to 63 */
- if (!write_reg(SI7210_CTRL3, SL_FAST_MASK | SL_TIMEENA_MASK, 63 << 2))
- return false;
-
- if (!set_high_range())
- return false;
-
- /* Stop the control loop by setting stop bit */
- if (!write_reg( SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) /* WARNING: Removed USE_STORE MASK */
- return false;
-
- /* Use a burst size of 128/4096 samples in FIR and IIR modes */
- if (!write_reg(SI7210_CTRL4, 0, DF_BURSTSIZE_128 | DF_BW_4096))
- return false;
-
- /* Select field strength measurement */
- if (!write_reg( SI7210_DSPSIGSEL, 0, DSP_SIGSEL_FIELD_MASK))
- return false;
-
- return true; //start_periodic_measurement();
-
- }
- }
- return false;
+ // Turn on auto increment and sanity check ID
+ // Load OTP cal
+
+ uint8_t temp;
+ if (FRToSI2C::Mem_Read(SI7210_ADDRESS, SI7210_REG_ID, &temp, 1)) {
+ // We don't really care what model it is etc, just probing to check its probably this iC
+ if (temp != 0x00 && temp != 0xFF) {
+ temp = 0x00;
+
+ /* Set device and internal driver settings */
+ if (!write_reg(SI7210_CTRL1, (uint8_t)~SW_LOW4FIELD_MASK, 0)) {
+ return false;
+ }
+
+ /* Disable periodic auto-wakeup by device, and tamper detect. */
+ if ((!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, 0)))
+ return false;
+
+ /* Disable tamper detection by setting sw_tamper to 63 */
+ if (!write_reg(SI7210_CTRL3, SL_FAST_MASK | SL_TIMEENA_MASK, 63 << 2))
+ return false;
+
+ if (!set_high_range())
+ return false;
+
+ /* Stop the control loop by setting stop bit */
+ if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK)) /* WARNING: Removed USE_STORE MASK */
+ return false;
+
+ /* Use a burst size of 128/4096 samples in FIR and IIR modes */
+ if (!write_reg(SI7210_CTRL4, 0, DF_BURSTSIZE_128 | DF_BW_4096))
+ return false;
+
+ /* Select field strength measurement */
+ if (!write_reg(SI7210_DSPSIGSEL, 0, DSP_SIGSEL_FIELD_MASK))
+ return false;
+
+ return true; // start_periodic_measurement();
+ }
+ }
+ return false;
}
int16_t Si7210::read() {
- //Read the two regs
- int16_t temp = 0;
- if (!get_field_strength(&temp)) {
- temp = 0;
- }
- return temp;
+ // Read the two regs
+ int16_t temp = 0;
+ if (!get_field_strength(&temp)) {
+ temp = 0;
+ }
+ return temp;
}
bool Si7210::write_reg(const uint8_t reg, const uint8_t mask, const uint8_t val) {
- uint8_t temp = 0;
- if (mask) {
- if (!read_reg(reg, &temp)) {
- return false;
- }
- temp &= mask;
- }
- temp |= val;
- return FRToSI2C::Mem_Write(SI7210_ADDRESS, reg, &temp, 1);
+ uint8_t temp = 0;
+ if (mask) {
+ if (!read_reg(reg, &temp)) {
+ return false;
+ }
+ temp &= mask;
+ }
+ temp |= val;
+ return FRToSI2C::Mem_Write(SI7210_ADDRESS, reg, &temp, 1);
}
-bool Si7210::read_reg(const uint8_t reg, uint8_t* val) {
- return FRToSI2C::Mem_Read(SI7210_ADDRESS, reg, val, 1);
-}
+bool Si7210::read_reg(const uint8_t reg, uint8_t *val) { return FRToSI2C::Mem_Read(SI7210_ADDRESS, reg, val, 1); }
bool Si7210::start_periodic_measurement() {
- /* Enable periodic wakeup */
- if (!write_reg(SI7210_CTRL3, (uint8_t) ~SL_TIMEENA_MASK, SL_TIMEENA_MASK))
- return false;
-
- /* Start measurement */
- /* Change to ~STOP_MASK with STOP_MASK */
- return write_reg( SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, 0);
+ /* Enable periodic wakeup */
+ if (!write_reg(SI7210_CTRL3, (uint8_t)~SL_TIMEENA_MASK, SL_TIMEENA_MASK))
+ return false;
+ /* Start measurement */
+ /* Change to ~STOP_MASK with STOP_MASK */
+ return write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, 0);
}
-bool Si7210::get_field_strength(int16_t* field) {
- *field = 0;
- uint8_t val = 0;
- FRToSI2C::wakePart(SI7210_ADDRESS);
+bool Si7210::get_field_strength(int16_t *field) {
+ *field = 0;
+ uint8_t val = 0;
+ FRToSI2C::wakePart(SI7210_ADDRESS);
- if (!write_reg( SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK))
- return false;
+ if (!write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, STOP_MASK))
+ return false;
- /* Read most-significant byte */
- if (!read_reg( SI7210_DSPSIGM, &val))
- return false;
- *field = (val & DSP_SIGM_DATA_MASK) << 8;
+ /* Read most-significant byte */
+ if (!read_reg(SI7210_DSPSIGM, &val))
+ return false;
+ *field = (val & DSP_SIGM_DATA_MASK) << 8;
- /* Read least-significant byte of data */
- if (!read_reg( SI7210_DSPSIGL, &val))
- return false;
+ /* Read least-significant byte of data */
+ if (!read_reg(SI7210_DSPSIGL, &val))
+ return false;
- *field += val;
- *field -= 16384U;
- //field is now a +- measurement
- //In units of 0.0125 mT
- // Aka 12.5uT
- //Clear flags
- read_reg( SI7210_CTRL1, &val);
- read_reg( SI7210_CTRL2, &val);
-//Start next one
+ *field += val;
+ *field -= 16384U;
+ // field is now a +- measurement
+ // In units of 0.0125 mT
+ // Aka 12.5uT
+ // Clear flags
+ read_reg(SI7210_CTRL1, &val);
+ read_reg(SI7210_CTRL2, &val);
+ // Start next one
- /* Use a burst size of 128/4096 samples in FIR and IIR modes */
- write_reg( SI7210_CTRL4, 0, DF_BURSTSIZE_128 | DF_BW_4096);
+ /* Use a burst size of 128/4096 samples in FIR and IIR modes */
+ write_reg(SI7210_CTRL4, 0, DF_BURSTSIZE_128 | DF_BW_4096);
- /* Selet field strength measurement */
- write_reg( SI7210_DSPSIGSEL, 0, DSP_SIGSEL_FIELD_MASK);
+ /* Selet field strength measurement */
+ write_reg(SI7210_DSPSIGSEL, 0, DSP_SIGSEL_FIELD_MASK);
- /* Start measurement */
- write_reg( SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, ONEBURST_MASK);
+ /* Start measurement */
+ write_reg(SI7210_POWER_CTRL, MEAS_MASK | USESTORE_MASK, ONEBURST_MASK);
- return true;
+ return true;
}
bool Si7210::set_high_range() {
- //To set the unit into 200mT range, no magnet temperature calibration
- // We want to copy OTP 0x27->0x2C into a0->a5
- uint8_t base_addr = 0x27; // You can change this to pick the temp calibration
- bool worked = true;
- uint8_t val = 0;
-
- /* Load A0 register */
- worked &= write_reg( SI7210_OTP_ADDR, 0, base_addr);
- worked &= write_reg( SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
- worked &= read_reg( SI7210_OTP_DATA, &val);
- worked &= write_reg( SI7210_A0, 0, val);
-
- /* Load A1 register */
- worked &= write_reg( SI7210_OTP_ADDR, 0, base_addr + 1);
- worked &= write_reg( SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
- worked &= read_reg( SI7210_OTP_DATA, &val);
- worked &= write_reg( SI7210_A1, 0, val);
-
- /* Load A2 register */
- worked &= write_reg( SI7210_OTP_ADDR, 0, base_addr + 2);
- worked &= write_reg( SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
- worked &= read_reg( SI7210_OTP_DATA, &val);
- worked &= write_reg( SI7210_A2, 0, val);
-
- /* Load A3 register */
- worked &= write_reg( SI7210_OTP_ADDR, 0, base_addr + 3);
- worked &= write_reg( SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
- worked &= read_reg( SI7210_OTP_DATA, &val);
- worked &= write_reg( SI7210_A3, 0, val);
-
- /* Load A4 register */
- worked &= write_reg( SI7210_OTP_ADDR, 0, base_addr + 4);
- worked &= write_reg( SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
- worked &= read_reg( SI7210_OTP_DATA, &val);
- worked &= write_reg( SI7210_A4, 0, val);
-
- /* Load A5 register */
- worked &= write_reg( SI7210_OTP_ADDR, 0, base_addr + 5);
- worked &= write_reg( SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
- worked &= read_reg( SI7210_OTP_DATA, &val);
- worked &= write_reg( SI7210_A5, 0, val);
- return worked;
+ // To set the unit into 200mT range, no magnet temperature calibration
+ // We want to copy OTP 0x27->0x2C into a0->a5
+ uint8_t base_addr = 0x27; // You can change this to pick the temp calibration
+ bool worked = true;
+ uint8_t val = 0;
+
+ /* Load A0 register */
+ worked &= write_reg(SI7210_OTP_ADDR, 0, base_addr);
+ worked &= write_reg(SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
+ worked &= read_reg(SI7210_OTP_DATA, &val);
+ worked &= write_reg(SI7210_A0, 0, val);
+
+ /* Load A1 register */
+ worked &= write_reg(SI7210_OTP_ADDR, 0, base_addr + 1);
+ worked &= write_reg(SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
+ worked &= read_reg(SI7210_OTP_DATA, &val);
+ worked &= write_reg(SI7210_A1, 0, val);
+
+ /* Load A2 register */
+ worked &= write_reg(SI7210_OTP_ADDR, 0, base_addr + 2);
+ worked &= write_reg(SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
+ worked &= read_reg(SI7210_OTP_DATA, &val);
+ worked &= write_reg(SI7210_A2, 0, val);
+
+ /* Load A3 register */
+ worked &= write_reg(SI7210_OTP_ADDR, 0, base_addr + 3);
+ worked &= write_reg(SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
+ worked &= read_reg(SI7210_OTP_DATA, &val);
+ worked &= write_reg(SI7210_A3, 0, val);
+
+ /* Load A4 register */
+ worked &= write_reg(SI7210_OTP_ADDR, 0, base_addr + 4);
+ worked &= write_reg(SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
+ worked &= read_reg(SI7210_OTP_DATA, &val);
+ worked &= write_reg(SI7210_A4, 0, val);
+
+ /* Load A5 register */
+ worked &= write_reg(SI7210_OTP_ADDR, 0, base_addr + 5);
+ worked &= write_reg(SI7210_OTP_CTRL, 0, OTP_READ_EN_MASK);
+ worked &= read_reg(SI7210_OTP_DATA, &val);
+ worked &= write_reg(SI7210_A5, 0, val);
+ return worked;
}
diff --git a/source/Core/Drivers/TipThermoModel.cpp b/source/Core/Drivers/TipThermoModel.cpp
index 34d038c6..f6911f9e 100644
--- a/source/Core/Drivers/TipThermoModel.cpp
+++ b/source/Core/Drivers/TipThermoModel.cpp
@@ -6,11 +6,11 @@
*/
#include "TipThermoModel.h"
-#include "Settings.h"
-#include "BSP.h"
-#include "power.hpp"
#include "../../configuration.h"
+#include "BSP.h"
+#include "Settings.h"
#include "main.hpp"
+#include "power.hpp"
/*
* The hardware is laid out as a non-inverting op-amp
* There is a pullup of 39k(TS100) from the +ve input to 3.9V (1M pulup on TS100)
@@ -29,217 +29,211 @@
*/
uint32_t TipThermoModel::convertTipRawADCTouV(uint16_t rawADC) {
- // This takes the raw ADC samples, converts these to uV
- // Then divides this down by the gain to convert to the uV on the input to the op-amp (A+B terminals)
- // Then remove the calibration value that is stored as a tip offset
- uint32_t vddRailmVX10 = 33000; //The vreg is +-2%, but we have no higher accuracy available
- // 4096 * 8 readings for full scale
- // Convert the input ADC reading back into mV times 10 format.
- uint32_t rawInputmVX10 = (rawADC * vddRailmVX10) / (4096 * 8);
-
- uint32_t valueuV = rawInputmVX10 * 100; // shift into uV
- //Now to divide this down by the gain
- valueuV /= OP_AMP_GAIN_STAGE;
-
- if (systemSettings.CalibrationOffset) {
- //Remove uV tipOffset
- if (valueuV >= systemSettings.CalibrationOffset)
- valueuV -= systemSettings.CalibrationOffset;
- else
- valueuV = 0;
- }
-
- return valueuV;
+ // This takes the raw ADC samples, converts these to uV
+ // Then divides this down by the gain to convert to the uV on the input to the op-amp (A+B terminals)
+ // Then remove the calibration value that is stored as a tip offset
+ uint32_t vddRailmVX10 = 33000; // The vreg is +-2%, but we have no higher accuracy available
+ // 4096 * 8 readings for full scale
+ // Convert the input ADC reading back into mV times 10 format.
+ uint32_t rawInputmVX10 = (rawADC * vddRailmVX10) / (4096 * 8);
+
+ uint32_t valueuV = rawInputmVX10 * 100; // shift into uV
+ // Now to divide this down by the gain
+ valueuV /= OP_AMP_GAIN_STAGE;
+
+ if (systemSettings.CalibrationOffset) {
+ // Remove uV tipOffset
+ if (valueuV >= systemSettings.CalibrationOffset)
+ valueuV -= systemSettings.CalibrationOffset;
+ else
+ valueuV = 0;
+ }
+
+ return valueuV;
}
-uint32_t TipThermoModel::convertTipRawADCToDegC(uint16_t rawADC) {
- return convertuVToDegC(convertTipRawADCTouV(rawADC));
-}
+uint32_t TipThermoModel::convertTipRawADCToDegC(uint16_t rawADC) { return convertuVToDegC(convertTipRawADCTouV(rawADC)); }
#ifdef ENABLED_FAHRENHEIT_SUPPORT
-uint32_t TipThermoModel::convertTipRawADCToDegF(uint16_t rawADC) {
- return convertuVToDegF(convertTipRawADCTouV(rawADC));
-}
+uint32_t TipThermoModel::convertTipRawADCToDegF(uint16_t rawADC) { return convertuVToDegF(convertTipRawADCTouV(rawADC)); }
#endif
-//Table that is designed to be walked to find the best sample for the lookup
+// Table that is designed to be walked to find the best sample for the lookup
-//Extrapolate between two points
+// Extrapolate between two points
// [x1, y1] = point 1
// [x2, y2] = point 2
// x = input value
// output is x's interpolated y value
-int32_t LinearInterpolate(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x) {
- return y1 + (((((x - x1) * 1000) / (x2 - x1)) * (y2 - y1))) / 1000;
-}
+int32_t LinearInterpolate(int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t x) { return y1 + (((((x - x1) * 1000) / (x2 - x1)) * (y2 - y1))) / 1000; }
#ifdef TEMP_uV_LOOKUP_HAKKO
-const uint16_t uVtoDegC[] = { //
- //
- 0, 0, //
- 266, 10, //
- 522, 20, //
- 770, 30, //
- 1010, 40, //
- 1244, 50, //
- 1473, 60, //
- 1697, 70, //
- 1917, 80, //
- 2135, 90, //
- 2351, 100, //
- 2566, 110, //
- 2780, 120, //
- 2994, 130, //
- 3209, 140, //
- 3426, 150, //
- 3644, 160, //
- 3865, 170, //
- 4088, 180, //
- 4314, 190, //
- 4544, 200, //
- 4777, 210, //
- 5014, 220, //
- 5255, 230, //
- 5500, 240, //
- 5750, 250, //
- 6003, 260, //
- 6261, 270, //
- 6523, 280, //
- 6789, 290, //
- 7059, 300, //
- 7332, 310, //
- 7609, 320, //
- 7889, 330, //
- 8171, 340, //
- 8456, 350, //
- 8742, 360, //
- 9030, 370, //
- 9319, 380, //
- 9607, 390, //
- 9896, 400, //
- 10183, 410, //
- 10468, 420, //
- 10750, 430, //
- 11029, 440, //
- 11304, 450, //
- 11573, 460, //
- 11835, 470, //
- 12091, 480, //
- 12337, 490, //
- 12575, 500, //
-
- };
+const uint16_t uVtoDegC[] = {
+ //
+ //
+ 0, 0, //
+ 266, 10, //
+ 522, 20, //
+ 770, 30, //
+ 1010, 40, //
+ 1244, 50, //
+ 1473, 60, //
+ 1697, 70, //
+ 1917, 80, //
+ 2135, 90, //
+ 2351, 100, //
+ 2566, 110, //
+ 2780, 120, //
+ 2994, 130, //
+ 3209, 140, //
+ 3426, 150, //
+ 3644, 160, //
+ 3865, 170, //
+ 4088, 180, //
+ 4314, 190, //
+ 4544, 200, //
+ 4777, 210, //
+ 5014, 220, //
+ 5255, 230, //
+ 5500, 240, //
+ 5750, 250, //
+ 6003, 260, //
+ 6261, 270, //
+ 6523, 280, //
+ 6789, 290, //
+ 7059, 300, //
+ 7332, 310, //
+ 7609, 320, //
+ 7889, 330, //
+ 8171, 340, //
+ 8456, 350, //
+ 8742, 360, //
+ 9030, 370, //
+ 9319, 380, //
+ 9607, 390, //
+ 9896, 400, //
+ 10183, 410, //
+ 10468, 420, //
+ 10750, 430, //
+ 11029, 440, //
+ 11304, 450, //
+ 11573, 460, //
+ 11835, 470, //
+ 12091, 480, //
+ 12337, 490, //
+ 12575, 500, //
+
+};
#endif
#ifdef TEMP_uV_LOOKUP_TS80
-const uint16_t uVtoDegC[] = { //
- //
- 530 , 0, //
- 1282 , 10, //
- 2034 , 20, //
- 2786 , 30, //
- 3538 , 40, //
- 4290 , 50, //
- 5043 , 60, //
- 5795 , 70, //
- 6547 , 80, //
- 7299 , 90, //
- 8051 , 100, //
- 8803 , 110, //
- 9555 , 120, //
- 10308 , 130, //
- 11060 , 140, //
- 11812 , 150, //
- 12564 , 160, //
- 13316 , 170, //
- 14068 , 180, //
- 14820 , 190, //
- 15573 , 200, //
- 16325 , 210, //
- 17077 , 220, //
- 17829 , 230, //
- 18581 , 240, //
- 19333 , 250, //
- 20085 , 260, //
- 20838 , 270, //
- 21590 , 280, //
- 22342 , 290, //
- 23094 , 300, //
- 23846 , 310, //
- 24598 , 320, //
- 25350 , 330, //
- 26103 , 340, //
- 26855 , 350, //
- 27607 , 360, //
- 28359 , 370, //
- 29111 , 380, //
- 29863 , 390, //
- 30615 , 400, //
- 31368 , 410, //
- 32120 , 420, //
- 32872 , 430, //
- 33624 , 440, //
- 34376 , 450, //
- 35128 , 460, //
- 35880 , 470, //
- 36632 , 480, //
- 37385 , 490, //
- 38137 , 500, //
- };
+const uint16_t uVtoDegC[] = {
+ //
+ //
+ 530, 0, //
+ 1282, 10, //
+ 2034, 20, //
+ 2786, 30, //
+ 3538, 40, //
+ 4290, 50, //
+ 5043, 60, //
+ 5795, 70, //
+ 6547, 80, //
+ 7299, 90, //
+ 8051, 100, //
+ 8803, 110, //
+ 9555, 120, //
+ 10308, 130, //
+ 11060, 140, //
+ 11812, 150, //
+ 12564, 160, //
+ 13316, 170, //
+ 14068, 180, //
+ 14820, 190, //
+ 15573, 200, //
+ 16325, 210, //
+ 17077, 220, //
+ 17829, 230, //
+ 18581, 240, //
+ 19333, 250, //
+ 20085, 260, //
+ 20838, 270, //
+ 21590, 280, //
+ 22342, 290, //
+ 23094, 300, //
+ 23846, 310, //
+ 24598, 320, //
+ 25350, 330, //
+ 26103, 340, //
+ 26855, 350, //
+ 27607, 360, //
+ 28359, 370, //
+ 29111, 380, //
+ 29863, 390, //
+ 30615, 400, //
+ 31368, 410, //
+ 32120, 420, //
+ 32872, 430, //
+ 33624, 440, //
+ 34376, 450, //
+ 35128, 460, //
+ 35880, 470, //
+ 36632, 480, //
+ 37385, 490, //
+ 38137, 500, //
+};
#endif
uint32_t TipThermoModel::convertuVToDegC(uint32_t tipuVDelta) {
- if (tipuVDelta) {
- int noItems = sizeof(uVtoDegC) / (2 * sizeof(uint16_t));
- for (int i = 1; i < (noItems - 1); i++) {
- //If current tip temp is less than current lookup, then this current lookup is the higher point to interpolate
- if (tipuVDelta < uVtoDegC[i * 2]) {
- return LinearInterpolate(uVtoDegC[(i - 1) * 2], uVtoDegC[((i - 1) * 2) + 1], uVtoDegC[i * 2], uVtoDegC[(i * 2) + 1], tipuVDelta);
- }
- }
- return LinearInterpolate(uVtoDegC[(noItems - 2) * 2], uVtoDegC[((noItems - 2) * 2) + 1], uVtoDegC[(noItems - 1) * 2], uVtoDegC[((noItems - 1) * 2) + 1], tipuVDelta);
- }
- return 0;
+ if (tipuVDelta) {
+ int noItems = sizeof(uVtoDegC) / (2 * sizeof(uint16_t));
+ for (int i = 1; i < (noItems - 1); i++) {
+ // If current tip temp is less than current lookup, then this current lookup is the higher point to interpolate
+ if (tipuVDelta < uVtoDegC[i * 2]) {
+ return LinearInterpolate(uVtoDegC[(i - 1) * 2], uVtoDegC[((i - 1) * 2) + 1], uVtoDegC[i * 2], uVtoDegC[(i * 2) + 1], tipuVDelta);
+ }
+ }
+ return LinearInterpolate(uVtoDegC[(noItems - 2) * 2], uVtoDegC[((noItems - 2) * 2) + 1], uVtoDegC[(noItems - 1) * 2], uVtoDegC[((noItems - 1) * 2) + 1], tipuVDelta);
+ }
+ return 0;
}
#ifdef ENABLED_FAHRENHEIT_SUPPORT
-uint32_t TipThermoModel::convertuVToDegF(uint32_t tipuVDelta) {
- return convertCtoF(convertuVToDegC(tipuVDelta));
-}
+uint32_t TipThermoModel::convertuVToDegF(uint32_t tipuVDelta) { return convertCtoF(convertuVToDegC(tipuVDelta)); }
uint32_t TipThermoModel::convertCtoF(uint32_t degC) {
- //(Y °C × 9/5) + 32 =Y°F
- return (32 + ((degC * 9) / 5));
+ //(Y °C × 9/5) + 32 =Y°F
+ return (32 + ((degC * 9) / 5));
}
uint32_t TipThermoModel::convertFtoC(uint32_t degF) {
- //(Y°F − 32) × 5/9 = Y°C
- if (degF < 32) {
- return 0;
- }
- return ((degF - 32) * 5) / 9;
+ //(Y°F − 32) × 5/9 = Y°C
+ if (degF < 32) {
+ return 0;
+ }
+ return ((degF - 32) * 5) / 9;
}
#endif
uint32_t TipThermoModel::getTipInC(bool sampleNow) {
- int32_t currentTipTempInC = TipThermoModel::convertTipRawADCToDegC(getTipRawTemp(sampleNow));
- currentTipTempInC += getHandleTemperature() / 10; //Add handle offset
- // Power usage indicates that our tip temp is lower than our thermocouple temp.
- // I found a number that doesn't unbalance the existing PID, causing overshoot.
- // This could be tuned in concert with PID parameters...
- currentTipTempInC -= x10WattHistory.average() / 25;
- if (currentTipTempInC < 0)
- return 0;
- return currentTipTempInC;
+ int32_t currentTipTempInC = TipThermoModel::convertTipRawADCToDegC(getTipRawTemp(sampleNow));
+ currentTipTempInC += getHandleTemperature() / 10; // Add handle offset
+ // Power usage indicates that our tip temp is lower than our thermocouple temp.
+ // I found a number that doesn't unbalance the existing PID, causing overshoot.
+ // This could be tuned in concert with PID parameters...
+ currentTipTempInC -= x10WattHistory.average() / 25;
+ if (currentTipTempInC < 0)
+ return 0;
+ return currentTipTempInC;
}
#ifdef ENABLED_FAHRENHEIT_SUPPORT
uint32_t TipThermoModel::getTipInF(bool sampleNow) {
- uint32_t currentTipTempInF = getTipInC(sampleNow);
- currentTipTempInF = convertCtoF(currentTipTempInF);
- return currentTipTempInF;
+ uint32_t currentTipTempInF = getTipInC(sampleNow);
+ currentTipTempInF = convertCtoF(currentTipTempInF);
+ return currentTipTempInF;
}
#endif
uint32_t TipThermoModel::getTipMaxInC() {
- uint32_t maximumTipTemp = TipThermoModel::convertTipRawADCToDegC(0x7FFF - (21 * 5)); //back off approx 5 deg c from ADC max
- maximumTipTemp += getHandleTemperature() / 10; //Add handle offset
- return maximumTipTemp - 1;
+ uint32_t maximumTipTemp = TipThermoModel::convertTipRawADCToDegC(0x7FFF - (21 * 5)); // back off approx 5 deg c from ADC max
+ maximumTipTemp += getHandleTemperature() / 10; // Add handle offset
+ return maximumTipTemp - 1;
}
diff --git a/source/Core/Src/FreeRTOSHooks.c b/source/Core/Src/FreeRTOSHooks.c
index d801f9d9..d795f04b 100644
--- a/source/Core/Src/FreeRTOSHooks.c
+++ b/source/Core/Src/FreeRTOSHooks.c
@@ -7,28 +7,23 @@
#include "FreeRTOSHooks.h"
#include "BSP.h"
-void vApplicationIdleHook(void) {
- resetWatchdog();
-}
+void vApplicationIdleHook(void) { resetWatchdog(); }
/* USER CODE BEGIN GET_IDLE_TASK_MEMORY */
static StaticTask_t xIdleTaskTCBBuffer;
-static StackType_t xIdleStack[configMINIMAL_STACK_SIZE];
+static StackType_t xIdleStack[configMINIMAL_STACK_SIZE];
-void vApplicationGetIdleTaskMemory(StaticTask_t **ppxIdleTaskTCBBuffer,
- StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize) {
- *ppxIdleTaskTCBBuffer = &xIdleTaskTCBBuffer;
- *ppxIdleTaskStackBuffer = &xIdleStack[0];
- *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;
- /* place for user code */
+void vApplicationGetIdleTaskMemory(StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize) {
+ *ppxIdleTaskTCBBuffer = &xIdleTaskTCBBuffer;
+ *ppxIdleTaskStackBuffer = &xIdleStack[0];
+ *pulIdleTaskStackSize = configMINIMAL_STACK_SIZE;
+ /* place for user code */
}
+void vApplicationStackOverflowHook(TaskHandle_t *pxTask, signed portCHAR *pcTaskName) {
+ (void)pxTask;
+ (void)pcTaskName;
-void vApplicationStackOverflowHook(TaskHandle_t *pxTask,
- signed portCHAR *pcTaskName) {
- (void) pxTask;
- (void) pcTaskName;
-
-// We dont have a good way to handle a stack overflow at this point in time
- reboot();
+ // We dont have a good way to handle a stack overflow at this point in time
+ reboot();
}
diff --git a/source/Core/Src/QC3.cpp b/source/Core/Src/QC3.cpp
index efcee1d8..132ac11c 100644
--- a/source/Core/Src/QC3.cpp
+++ b/source/Core/Src/QC3.cpp
@@ -12,172 +12,169 @@
#include "cmsis_os.h"
#include "stdint.h"
enum QCState {
- NOT_STARTED = 0, // Have not checked
- QC_3 = 1,
- QC_2 = 2,
- NO_QC = 3,
+ NOT_STARTED = 0, // Have not checked
+ QC_3 = 1,
+ QC_2 = 2,
+ NO_QC = 3,
};
void QC_Seek9V() {
- QC_DNegZero_Six();
- QC_DPlusThree_Three();
+ QC_DNegZero_Six();
+ QC_DPlusThree_Three();
}
void QC_Seek12V() {
- QC_DNegZero_Six();
- QC_DPlusZero_Six();
+ QC_DNegZero_Six();
+ QC_DPlusZero_Six();
}
void QC_Seek20V() {
- QC_DNegThree_Three();
- QC_DPlusThree_Three();
+ QC_DNegThree_Three();
+ QC_DPlusThree_Three();
}
void QC_SeekContMode() {
- QC_DNegThree_Three();
- QC_DPlusZero_Six();
+ QC_DNegThree_Three();
+ QC_DPlusZero_Six();
}
void QC_SeekContPlus() {
- QC_SeekContMode();
- osDelay(30);
- QC_Seek20V();
- osDelay(10);
- QC_SeekContMode();
+ QC_SeekContMode();
+ osDelay(30);
+ QC_Seek20V();
+ osDelay(10);
+ QC_SeekContMode();
}
void QC_SeekContNeg() {
- QC_SeekContMode();
- osDelay(30);
- QC_Seek12V();
- osDelay(10);
- QC_SeekContMode();
+ QC_SeekContMode();
+ osDelay(30);
+ QC_Seek12V();
+ osDelay(10);
+ QC_SeekContMode();
}
-QCState QCMode = QCState::NOT_STARTED;
+QCState QCMode = QCState::NOT_STARTED;
uint8_t QCTries = 0;
-void seekQC(int16_t Vx10, uint16_t divisor) {
- if (QCMode == QCState::NOT_STARTED)
- startQC(divisor);
+void seekQC(int16_t Vx10, uint16_t divisor) {
+ if (QCMode == QCState::NOT_STARTED)
+ startQC(divisor);
- if (Vx10 < 45)
- return;
- if (xTaskGetTickCount() < TICKS_SECOND)
- return;
+ if (Vx10 < 45)
+ return;
+ if (xTaskGetTickCount() < TICKS_SECOND)
+ return;
#ifdef POW_QC_20V
- if (Vx10 > 200)
- Vx10 = 200; // Cap max value at 20V
+ if (Vx10 > 200)
+ Vx10 = 200; // Cap max value at 20V
#else
- if (Vx10 > 130)
- Vx10 = 130; // Cap max value at 13V
+ if (Vx10 > 130)
+ Vx10 = 130; // Cap max value at 13V
#endif
- // Seek the QC to the Voltage given if this adapter supports continuous mode
- // try and step towards the wanted value
+ // Seek the QC to the Voltage given if this adapter supports continuous mode
+ // try and step towards the wanted value
- // 1. Measure current voltage
- int16_t vStart = getInputVoltageX10(divisor, 1);
- int difference = Vx10 - vStart;
+ // 1. Measure current voltage
+ int16_t vStart = getInputVoltageX10(divisor, 1);
+ int difference = Vx10 - vStart;
- // 2. calculate ideal steps (0.2V changes)
+ // 2. calculate ideal steps (0.2V changes)
- int steps = difference / 2;
- if (QCMode == QCState::QC_3) {
- if (steps > -2 && steps < 2)
- return; // dont bother with small steps
- while (steps < 0) {
- QC_SeekContNeg();
- osDelay(30);
- steps++;
- }
- while (steps > 0) {
- QC_SeekContPlus();
- osDelay(30);
- steps--;
- }
- osDelay(100);
- }
+ int steps = difference / 2;
+ if (QCMode == QCState::QC_3) {
+ if (steps > -2 && steps < 2)
+ return; // dont bother with small steps
+ while (steps < 0) {
+ QC_SeekContNeg();
+ osDelay(30);
+ steps++;
+ }
+ while (steps > 0) {
+ QC_SeekContPlus();
+ osDelay(30);
+ steps--;
+ }
+ osDelay(100);
+ }
#ifdef ENABLE_QC2
- // Re-measure
- /* Disabled due to nothing to test and code space of around 1k*/
- steps = vStart - getInputVoltageX10(divisor, 1);
- if (steps < 0)
- steps = -steps;
- if (steps > 4) {
- // No continuous mode, so QC2
- QCMode = QCState::QC_2;
- // Goto nearest
- if (Vx10 > 190) {
- // request 20V
- QC_Seek20V();
- } else if (Vx10 > 110) {
- // request 12V
- QC_Seek12V();
- } else {
- // request 9V
- QC_Seek9V();
- }
- }
+ // Re-measure
+ /* Disabled due to nothing to test and code space of around 1k*/
+ steps = vStart - getInputVoltageX10(divisor, 1);
+ if (steps < 0)
+ steps = -steps;
+ if (steps > 4) {
+ // No continuous mode, so QC2
+ QCMode = QCState::QC_2;
+ // Goto nearest
+ if (Vx10 > 190) {
+ // request 20V
+ QC_Seek20V();
+ } else if (Vx10 > 110) {
+ // request 12V
+ QC_Seek12V();
+ } else {
+ // request 9V
+ QC_Seek9V();
+ }
+ }
#endif
}
// Must be called after FreeRToS Starts
void startQC(uint16_t divisor) {
- // Pre check that the input could be >5V already, and if so, dont both
- // negotiating as someone is feeding in hv
- if (getInputVoltageX10(divisor, 1) > 80) {
- QCTries = 11;
- QCMode = QCState::NO_QC;
- return;
- }
- if (QCTries > 10) {
- QCMode = QCState::NO_QC;
- return;
- }
- QCMode = QCState::NOT_STARTED;
- QC_Init_GPIO();
+ // Pre check that the input could be >5V already, and if so, dont both
+ // negotiating as someone is feeding in hv
+ if (getInputVoltageX10(divisor, 1) > 80) {
+ QCTries = 11;
+ QCMode = QCState::NO_QC;
+ return;
+ }
+ if (QCTries > 10) {
+ QCMode = QCState::NO_QC;
+ return;
+ }
+ QCMode = QCState::NOT_STARTED;
+ QC_Init_GPIO();
- // Tries to negotiate QC for 9V
- // This is a multiple step process.
- // 1. Set around 0.6V on D+ for 1.25 Seconds or so
- // 2. After this It should un-short D+->D- and instead add a 20k pulldown on
- // D-
- QC_DPlusZero_Six();
+ // Tries to negotiate QC for 9V
+ // This is a multiple step process.
+ // 1. Set around 0.6V on D+ for 1.25 Seconds or so
+ // 2. After this It should un-short D+->D- and instead add a 20k pulldown on
+ // D-
+ QC_DPlusZero_Six();
- // Delay 1.25 seconds
- uint8_t enteredQC = 0;
- for (uint16_t i = 0; i < 200 && enteredQC == 0; i++) {
- osDelay(10); // 10mS pause
- if (i > 130) {
- if (QC_DM_PulledDown()) {
- enteredQC = 1;
- }
- if (i == 140) {
- // For some marginal QC chargers, we try adding a pulldown
- QC_DM_PullDown();
- }
- }
- }
- QC_DM_No_PullDown();
- if (enteredQC) {
- // We have a QC capable charger
- QC_Seek9V();
- QC_Post_Probe_En();
- QC_Seek9V();
- // Wait for frontend ADC to stabilise
- QCMode = QCState::QC_2;
- for (uint8_t i = 0; i < 10; i++) {
- if (getInputVoltageX10(divisor, 1) > 80) {
- // yay we have at least QC2.0 or QC3.0
- QCMode = QCState::QC_3; // We have at least QC2, pray for 3
- return;
- }
- osDelay(100); // 100mS
- }
- QCMode = QCState::NOT_STARTED;
- QCTries++;
-
- } else {
- // no QC
- QCTries++;
- QCMode = QCState::NO_QC;
- }
+ // Delay 1.25 seconds
+ uint8_t enteredQC = 0;
+ for (uint16_t i = 0; i < 200 && enteredQC == 0; i++) {
+ osDelay(10); // 10mS pause
+ if (i > 130) {
+ if (QC_DM_PulledDown()) {
+ enteredQC = 1;
+ }
+ if (i == 140) {
+ // For some marginal QC chargers, we try adding a pulldown
+ QC_DM_PullDown();
+ }
+ }
+ }
+ QC_DM_No_PullDown();
+ if (enteredQC) {
+ // We have a QC capable charger
+ QC_Seek9V();
+ QC_Post_Probe_En();
+ QC_Seek9V();
+ // Wait for frontend ADC to stabilise
+ QCMode = QCState::QC_2;
+ for (uint8_t i = 0; i < 10; i++) {
+ if (getInputVoltageX10(divisor, 1) > 80) {
+ // yay we have at least QC2.0 or QC3.0
+ QCMode = QCState::QC_3; // We have at least QC2, pray for 3
+ return;
+ }
+ osDelay(100); // 100mS
+ }
+ QCMode = QCState::NOT_STARTED;
+ QCTries++;
+ } else {
+ // no QC
+ QCTries++;
+ QCMode = QCState::NO_QC;
+ }
}
-bool hasQCNegotiated() {
- return QCMode == QCState::QC_3 || QCMode == QCState::QC_2;
-}
+bool hasQCNegotiated() { return QCMode == QCState::QC_3 || QCMode == QCState::QC_2; }
diff --git a/source/Core/Src/Settings.cpp b/source/Core/Src/Settings.cpp
index 9748d230..ad6de09a 100644
--- a/source/Core/Src/Settings.cpp
+++ b/source/Core/Src/Settings.cpp
@@ -9,30 +9,30 @@
*/
#include "Settings.h"
-#include "Setup.h"
#include "../../configuration.h"
#include "BSP.h"
+#include "Setup.h"
#include "string.h"
volatile systemSettingsType systemSettings;
void saveSettings() {
- // First we erase the flash
- flash_save_buffer((uint8_t*) &systemSettings, sizeof(systemSettingsType));
+ // First we erase the flash
+ flash_save_buffer((uint8_t *)&systemSettings, sizeof(systemSettingsType));
}
bool restoreSettings() {
- // We read the flash
- flash_read_buffer((uint8_t*) &systemSettings, sizeof(systemSettingsType));
+ // We read the flash
+ flash_read_buffer((uint8_t *)&systemSettings, sizeof(systemSettingsType));
- // if the version is correct were done
- // if not we reset and save
- if (systemSettings.version != SETTINGSVERSION) {
- // probably not setup
- resetSettings();
- return true;
- }
- return false;
+ // if the version is correct were done
+ // if not we reset and save
+ if (systemSettings.version != SETTINGSVERSION) {
+ // probably not setup
+ resetSettings();
+ return true;
+ }
+ return false;
}
// Lookup function for cutoff setting -> X10 voltage
/*
@@ -43,59 +43,59 @@ bool restoreSettings() {
* 4=6S
*/
uint8_t lookupVoltageLevel() {
- if (systemSettings.minDCVoltageCells == 0)
- return 90; // 9V since iron does not function effectively below this
- else
- return (systemSettings.minDCVoltageCells * 33) + (33 * 2);
+ if (systemSettings.minDCVoltageCells == 0)
+ return 90; // 9V since iron does not function effectively below this
+ else
+ return (systemSettings.minDCVoltageCells * 33) + (33 * 2);
}
void resetSettings() {
- memset((void*) &systemSettings, 0, sizeof(systemSettingsType));
- systemSettings.SleepTemp = SLEEP_TEMP; // Temperature the iron sleeps at - default 150.0 C
- systemSettings.SleepTime = SLEEP_TIME; // How many seconds/minutes we wait until going
- // to sleep - default 1 min
- systemSettings.SolderingTemp = SOLDERING_TEMP; // Default soldering temp is 320.0 C
- systemSettings.minDCVoltageCells = CUT_OUT_SETTING; // default to no cut-off voltage
- systemSettings.QCIdealVoltage = 0; // Default to 9V for QC3.0 Voltage
- systemSettings.version = SETTINGSVERSION; // Store the version number to allow for easier upgrades
- systemSettings.detailedSoldering = DETAILED_SOLDERING; // Detailed soldering screen
- systemSettings.detailedIDLE = DETAILED_IDLE; // Detailed idle screen (off for first time users)
- systemSettings.OrientationMode = ORIENTATION_MODE; // Default to automatic
- systemSettings.sensitivity = SENSITIVITY; // Default high sensitivity
- systemSettings.voltageDiv = VOLTAGE_DIV; // Default divider from schematic
- systemSettings.ShutdownTime = SHUTDOWN_TIME; // How many minutes until the unit turns itself off
- systemSettings.BoostTemp = BOOST_TEMP; // default to 400C
- systemSettings.autoStartMode = AUTO_START_MODE; // Auto start off for safety
- systemSettings.lockingMode = LOCKING_MODE; // Disable locking for safety
- systemSettings.coolingTempBlink = COOLING_TEMP_BLINK; // Blink the temperature on the cooling screen when its > 50C
+ memset((void *)&systemSettings, 0, sizeof(systemSettingsType));
+ systemSettings.SleepTemp = SLEEP_TEMP; // Temperature the iron sleeps at - default 150.0 C
+ systemSettings.SleepTime = SLEEP_TIME; // How many seconds/minutes we wait until going
+ // to sleep - default 1 min
+ systemSettings.SolderingTemp = SOLDERING_TEMP; // Default soldering temp is 320.0 C
+ systemSettings.minDCVoltageCells = CUT_OUT_SETTING; // default to no cut-off voltage
+ systemSettings.QCIdealVoltage = 0; // Default to 9V for QC3.0 Voltage
+ systemSettings.version = SETTINGSVERSION; // Store the version number to allow for easier upgrades
+ systemSettings.detailedSoldering = DETAILED_SOLDERING; // Detailed soldering screen
+ systemSettings.detailedIDLE = DETAILED_IDLE; // Detailed idle screen (off for first time users)
+ systemSettings.OrientationMode = ORIENTATION_MODE; // Default to automatic
+ systemSettings.sensitivity = SENSITIVITY; // Default high sensitivity
+ systemSettings.voltageDiv = VOLTAGE_DIV; // Default divider from schematic
+ systemSettings.ShutdownTime = SHUTDOWN_TIME; // How many minutes until the unit turns itself off
+ systemSettings.BoostTemp = BOOST_TEMP; // default to 400C
+ systemSettings.autoStartMode = AUTO_START_MODE; // Auto start off for safety
+ systemSettings.lockingMode = LOCKING_MODE; // Disable locking for safety
+ systemSettings.coolingTempBlink = COOLING_TEMP_BLINK; // Blink the temperature on the cooling screen when its > 50C
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- systemSettings.temperatureInF = TEMPERATURE_INF; // default to 0
+ systemSettings.temperatureInF = TEMPERATURE_INF; // default to 0
#endif
- systemSettings.descriptionScrollSpeed = DESCRIPTION_SCROLL_SPEED; // default to slow
- systemSettings.CalibrationOffset = CALIBRATION_OFFSET; // the adc offset in uV
- systemSettings.powerLimit = POWER_LIMIT; // 30 watts default limit
- systemSettings.ReverseButtonTempChangeEnabled = REVERSE_BUTTON_TEMP_CHANGE; //
- systemSettings.TempChangeShortStep = TEMP_CHANGE_SHORT_STEP; //
- systemSettings.TempChangeLongStep = TEMP_CHANGE_LONG_STEP; //
- systemSettings.KeepAwakePulse = POWER_PULSE_DEFAULT;
- systemSettings.hallEffectSensitivity = 1;
- systemSettings.accelMissingWarningCounter = 0;
- systemSettings.pdMissingWarningCounter = 0;
+ systemSettings.descriptionScrollSpeed = DESCRIPTION_SCROLL_SPEED; // default to slow
+ systemSettings.CalibrationOffset = CALIBRATION_OFFSET; // the adc offset in uV
+ systemSettings.powerLimit = POWER_LIMIT; // 30 watts default limit
+ systemSettings.ReverseButtonTempChangeEnabled = REVERSE_BUTTON_TEMP_CHANGE; //
+ systemSettings.TempChangeShortStep = TEMP_CHANGE_SHORT_STEP; //
+ systemSettings.TempChangeLongStep = TEMP_CHANGE_LONG_STEP; //
+ systemSettings.KeepAwakePulse = POWER_PULSE_DEFAULT;
+ systemSettings.hallEffectSensitivity = 1;
+ systemSettings.accelMissingWarningCounter = 0;
+ systemSettings.pdMissingWarningCounter = 0;
- saveSettings(); // Save defaults
+ saveSettings(); // Save defaults
}
uint16_t lookupHallEffectThreshold() {
- // Return the threshold above which the hall effect sensor is "activated"
- switch (systemSettings.hallEffectSensitivity) {
- case 0:
- return 0;
- case 1: //Low
- return 1000;
- case 2: //Medium
- return 500;
- case 3: //High
- return 100;
- default:
- return 0; //Off
- }
+ // Return the threshold above which the hall effect sensor is "activated"
+ switch (systemSettings.hallEffectSensitivity) {
+ case 0:
+ return 0;
+ case 1: // Low
+ return 1000;
+ case 2: // Medium
+ return 500;
+ case 3: // High
+ return 100;
+ default:
+ return 0; // Off
+ }
}
diff --git a/source/Core/Src/freertos.c b/source/Core/Src/freertos.c
index dd171c8e..74c6fde2 100644
--- a/source/Core/Src/freertos.c
+++ b/source/Core/Src/freertos.c
@@ -1,50 +1,50 @@
/**
- ******************************************************************************
- * File Name : freertos.c
- * Description : Code for freertos applications
- ******************************************************************************
- * This notice applies to any and all portions of this file
- * that are not between comment pairs USER CODE BEGIN and
- * USER CODE END. Other portions of this file, whether
- * inserted by the user or by software development tools
- * are owned by their respective copyright owners.
- *
- * Copyright (c) 2017 STMicroelectronics International N.V.
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted, provided that the following conditions are met:
- *
- * 1. Redistribution 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 other
- * contributors to this software may be used to endorse or promote products
- * derived from this software without specific written permission.
- * 4. This software, including modifications and/or derivative works of this
- * software, must execute solely and exclusively on microcontroller or
- * microprocessor devices manufactured by or for STMicroelectronics.
- * 5. Redistribution and use of this software other than as permitted under
- * this license is void and will automatically terminate your rights under
- * this license.
- *
- * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
- * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
- * SHALL STMICROELECTRONICS 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.
- *
- ******************************************************************************
- */
+ ******************************************************************************
+ * File Name : freertos.c
+ * Description : Code for freertos applications
+ ******************************************************************************
+ * This notice applies to any and all portions of this file
+ * that are not between comment pairs USER CODE BEGIN and
+ * USER CODE END. Other portions of this file, whether
+ * inserted by the user or by software development tools
+ * are owned by their respective copyright owners.
+ *
+ * Copyright (c) 2017 STMicroelectronics International N.V.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted, provided that the following conditions are met:
+ *
+ * 1. Redistribution 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 other
+ * contributors to this software may be used to endorse or promote products
+ * derived from this software without specific written permission.
+ * 4. This software, including modifications and/or derivative works of this
+ * software, must execute solely and exclusively on microcontroller or
+ * microprocessor devices manufactured by or for STMicroelectronics.
+ * 5. Redistribution and use of this software other than as permitted under
+ * this license is void and will automatically terminate your rights under
+ * this license.
+ *
+ * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
+ * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
+ * SHALL STMICROELECTRONICS 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.
+ *
+ ******************************************************************************
+ */
/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
diff --git a/source/Core/Src/gui.cpp b/source/Core/Src/gui.cpp
index 86674071..46fbf7cc 100644
--- a/source/Core/Src/gui.cpp
+++ b/source/Core/Src/gui.cpp
@@ -6,14 +6,14 @@
*/
#include "gui.hpp"
+#include "../../configuration.h"
+#include "Buttons.hpp"
+#include "TipThermoModel.h"
#include "Translation.h"
#include "cmsis_os.h"
#include "main.hpp"
-#include "TipThermoModel.h"
#include "string.h"
#include "unit.h"
-#include "../../configuration.h"
-#include "Buttons.hpp"
void gui_Menu(const menuitem *menu);
@@ -59,8 +59,8 @@ static bool settings_setResetSettings(void);
static void settings_displayResetSettings(void);
static bool settings_setCalibrate(void);
static void settings_displayCalibrate(void);
-//static bool settings_setTipGain(void);
-//static void settings_displayTipGain(void);
+// static bool settings_setTipGain(void);
+// static void settings_displayTipGain(void);
static bool settings_setCalibrateVIN(void);
static void settings_displayCalibrateVIN(void);
static void settings_displayReverseButtonTempChangeEnabled(void);
@@ -109,7 +109,7 @@ static bool settings_enterAdvancedMenu(void);
* Temperature Unit
* Display orientation
* Cooldown blink
- * Reverse Temp change buttons + -
+ * Reverse Temp change buttons + -
*
* Advanced
* Enable Power Limit
@@ -122,7 +122,7 @@ static bool settings_enterAdvancedMenu(void);
* Reset Settings
*
*/
-const menuitem rootSettingsMenu[] {
+const menuitem rootSettingsMenu[]{
/*
* Power Source
* Soldering Menu
@@ -132,32 +132,32 @@ const menuitem rootSettingsMenu[] {
* Exit
*/
#ifdef POW_DC
- { (const char *) SettingsDescriptions[0], settings_setInputVRange, settings_displayInputVRange }, /*Voltage input*/
+ {(const char *)SettingsDescriptions[0], settings_setInputVRange, settings_displayInputVRange}, /*Voltage input*/
#endif
#ifdef POW_QC
- { (const char *) SettingsDescriptions[19], settings_setQCInputV, settings_displayQCInputV }, /*Voltage input*/
+ {(const char *)SettingsDescriptions[19], settings_setQCInputV, settings_displayQCInputV}, /*Voltage input*/
#endif
- { (const char *) NULL, settings_enterSolderingMenu, settings_displaySolderingMenu }, /*Soldering*/
- { (const char *) NULL, settings_enterPowerMenu, settings_displayPowerMenu }, /*Sleep Options Menu*/
- { (const char *) NULL, settings_enterUIMenu, settings_displayUIMenu }, /*UI Menu*/
- { (const char *) NULL, settings_enterAdvancedMenu, settings_displayAdvancedMenu }, /*Advanced Menu*/
- { NULL, NULL, NULL } // end of menu marker. DO NOT REMOVE
+ {(const char *)NULL, settings_enterSolderingMenu, settings_displaySolderingMenu}, /*Soldering*/
+ {(const char *)NULL, settings_enterPowerMenu, settings_displayPowerMenu}, /*Sleep Options Menu*/
+ {(const char *)NULL, settings_enterUIMenu, settings_displayUIMenu}, /*UI Menu*/
+ {(const char *)NULL, settings_enterAdvancedMenu, settings_displayAdvancedMenu}, /*Advanced Menu*/
+ {NULL, NULL, NULL} // end of menu marker. DO NOT REMOVE
};
const menuitem solderingMenu[] = {
-/*
- * Boost Mode Enabled
- * Boost Mode Temp
- * Auto Start
- * Temp change short step
- * Temp change long step
- */
-{ (const char *) SettingsDescriptions[8], settings_setBoostTemp, settings_displayBoostTemp }, /*Boost Temp*/
-{ (const char *) SettingsDescriptions[9], settings_setAutomaticStartMode, settings_displayAutomaticStartMode }, /*Auto start*/
-{ (const char *) SettingsDescriptions[22], settings_setTempChangeShortStep, settings_displayTempChangeShortStep }, /*Temp change short step*/
-{ (const char *) SettingsDescriptions[23], settings_setTempChangeLongStep, settings_displayTempChangeLongStep }, /*Temp change long step*/
-{ (const char *) SettingsDescriptions[27], settings_setLockingMode, settings_displayLockingMode }, /*Locking Mode*/
-{ NULL, NULL, NULL } // end of menu marker. DO NOT REMOVE
+ /*
+ * Boost Mode Enabled
+ * Boost Mode Temp
+ * Auto Start
+ * Temp change short step
+ * Temp change long step
+ */
+ {(const char *)SettingsDescriptions[8], settings_setBoostTemp, settings_displayBoostTemp}, /*Boost Temp*/
+ {(const char *)SettingsDescriptions[9], settings_setAutomaticStartMode, settings_displayAutomaticStartMode}, /*Auto start*/
+ {(const char *)SettingsDescriptions[22], settings_setTempChangeShortStep, settings_displayTempChangeShortStep}, /*Temp change short step*/
+ {(const char *)SettingsDescriptions[23], settings_setTempChangeLongStep, settings_displayTempChangeLongStep}, /*Temp change long step*/
+ {(const char *)SettingsDescriptions[27], settings_setLockingMode, settings_displayLockingMode}, /*Locking Mode*/
+ {NULL, NULL, NULL} // end of menu marker. DO NOT REMOVE
};
const menuitem UIMenu[] = {
/*
@@ -166,62 +166,61 @@ const menuitem UIMenu[] = {
* Temperature Unit
* Display orientation
* Cooldown blink
- * Reverse Temp change buttons + -
+ * Reverse Temp change buttons + -
*/
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- { (const char *)SettingsDescriptions[5], settings_setTempF,
- settings_displayTempF}, /* Temperature units*/
+ {(const char *)SettingsDescriptions[5], settings_setTempF, settings_displayTempF}, /* Temperature units*/
#endif
- { (const char *) SettingsDescriptions[7], settings_setDisplayRotation, settings_displayDisplayRotation }, /*Display Rotation*/
- { (const char *) SettingsDescriptions[10], settings_setCoolingBlinkEnabled, settings_displayCoolingBlinkEnabled }, /*Cooling blink warning*/
- { (const char *) SettingsDescriptions[15], settings_setScrollSpeed, settings_displayScrollSpeed }, /*Scroll Speed for descriptions*/
- { (const char *) SettingsDescriptions[21], settings_setReverseButtonTempChangeEnabled, settings_displayReverseButtonTempChangeEnabled }, /* Reverse Temp change buttons + - */
- { NULL, NULL, NULL } // end of menu marker. DO NOT REMOVE
+ {(const char *)SettingsDescriptions[7], settings_setDisplayRotation, settings_displayDisplayRotation}, /*Display Rotation*/
+ {(const char *)SettingsDescriptions[10], settings_setCoolingBlinkEnabled, settings_displayCoolingBlinkEnabled}, /*Cooling blink warning*/
+ {(const char *)SettingsDescriptions[15], settings_setScrollSpeed, settings_displayScrollSpeed}, /*Scroll Speed for descriptions*/
+ {(const char *)SettingsDescriptions[21], settings_setReverseButtonTempChangeEnabled, settings_displayReverseButtonTempChangeEnabled}, /* Reverse Temp change buttons + - */
+ {NULL, NULL, NULL} // end of menu marker. DO NOT REMOVE
};
const menuitem PowerMenu[] = {
-/*
- * Sleep Temp
- * Sleep Time
- * Shutdown Time
- * Motion Sensitivity
- */
-{ (const char *) SettingsDescriptions[1], settings_setSleepTemp, settings_displaySleepTemp }, /*Sleep Temp*/
-{ (const char *) SettingsDescriptions[2], settings_setSleepTime, settings_displaySleepTime }, /*Sleep Time*/
-{ (const char *) SettingsDescriptions[3], settings_setShutdownTime, settings_displayShutdownTime }, /*Shutdown Time*/
-{ (const char *) SettingsDescriptions[4], settings_setSensitivity, settings_displaySensitivity }, /* Motion Sensitivity*/
+ /*
+ * Sleep Temp
+ * Sleep Time
+ * Shutdown Time
+ * Motion Sensitivity
+ */
+ {(const char *)SettingsDescriptions[1], settings_setSleepTemp, settings_displaySleepTemp}, /*Sleep Temp*/
+ {(const char *)SettingsDescriptions[2], settings_setSleepTime, settings_displaySleepTime}, /*Sleep Time*/
+ {(const char *)SettingsDescriptions[3], settings_setShutdownTime, settings_displayShutdownTime}, /*Shutdown Time*/
+ {(const char *)SettingsDescriptions[4], settings_setSensitivity, settings_displaySensitivity}, /* Motion Sensitivity*/
#ifdef HALL_SENSOR
- { (const char *) SettingsDescriptions[26], settings_setHallEffect, settings_displayHallEffect }, /* HallEffect Sensitivity*/
+ {(const char *)SettingsDescriptions[26], settings_setHallEffect, settings_displayHallEffect}, /* HallEffect Sensitivity*/
#endif
- { NULL, NULL, NULL } // end of menu marker. DO NOT REMOVE
+ {NULL, NULL, NULL} // end of menu marker. DO NOT REMOVE
};
const menuitem advancedMenu[] = {
-/*
- * Power limit
- * Detailed IDLE
- * Detailed Soldering
- * Calibrate Temperature
- * Calibrate Input V
- * Reset Settings
- * Power Pulse
- */
-{ (const char *) SettingsDescriptions[20], settings_setPowerLimit, settings_displayPowerLimit }, /*Power limit*/
-{ (const char *) SettingsDescriptions[6], settings_setAdvancedIDLEScreens, settings_displayAdvancedIDLEScreens }, /* Advanced idle screen*/
-{ (const char *) SettingsDescriptions[14], settings_setAdvancedSolderingScreens, settings_displayAdvancedSolderingScreens }, /* Advanced soldering screen*/
-{ (const char *) SettingsDescriptions[12], settings_setResetSettings, settings_displayResetSettings }, /*Resets settings*/
-{ (const char *) SettingsDescriptions[11], settings_setCalibrate, settings_displayCalibrate }, /*Calibrate tip*/
-{ (const char *) SettingsDescriptions[13], settings_setCalibrateVIN, settings_displayCalibrateVIN }, /*Voltage input cal*/
-{ (const char *) SettingsDescriptions[24], settings_setPowerPulse, settings_displayPowerPulse }, /*Power Pulse adjustment */
-//{ (const char *) SettingsDescriptions[25], settings_setTipGain, settings_displayTipGain }, /*TipGain*/
-{ NULL, NULL, NULL } // end of menu marker. DO NOT REMOVE
+ /*
+ * Power limit
+ * Detailed IDLE
+ * Detailed Soldering
+ * Calibrate Temperature
+ * Calibrate Input V
+ * Reset Settings
+ * Power Pulse
+ */
+ {(const char *)SettingsDescriptions[20], settings_setPowerLimit, settings_displayPowerLimit}, /*Power limit*/
+ {(const char *)SettingsDescriptions[6], settings_setAdvancedIDLEScreens, settings_displayAdvancedIDLEScreens}, /* Advanced idle screen*/
+ {(const char *)SettingsDescriptions[14], settings_setAdvancedSolderingScreens, settings_displayAdvancedSolderingScreens}, /* Advanced soldering screen*/
+ {(const char *)SettingsDescriptions[12], settings_setResetSettings, settings_displayResetSettings}, /*Resets settings*/
+ {(const char *)SettingsDescriptions[11], settings_setCalibrate, settings_displayCalibrate}, /*Calibrate tip*/
+ {(const char *)SettingsDescriptions[13], settings_setCalibrateVIN, settings_displayCalibrateVIN}, /*Voltage input cal*/
+ {(const char *)SettingsDescriptions[24], settings_setPowerPulse, settings_displayPowerPulse}, /*Power Pulse adjustment */
+ //{ (const char *) SettingsDescriptions[25], settings_setTipGain, settings_displayTipGain }, /*TipGain*/
+ {NULL, NULL, NULL} // end of menu marker. DO NOT REMOVE
};
static void printShortDescriptionDoubleLine(uint32_t shortDescIndex) {
- OLED::setFont(1);
- OLED::setCharCursor(0, 0);
- OLED::print(SettingsShortNames[shortDescIndex][0]);
- OLED::setCharCursor(0, 1);
- OLED::print(SettingsShortNames[shortDescIndex][1]);
+ OLED::setFont(1);
+ OLED::setCharCursor(0, 0);
+ OLED::print(SettingsShortNames[shortDescIndex][0]);
+ OLED::setCharCursor(0, 1);
+ OLED::print(SettingsShortNames[shortDescIndex][1]);
}
/**
@@ -232,553 +231,532 @@ static void printShortDescriptionDoubleLine(uint32_t shortDescIndex) {
* description.
*/
static void printShortDescription(uint32_t shortDescIndex, uint16_t cursorCharPosition) {
- // print short description (default single line, explicit double line)
- printShortDescriptionDoubleLine(shortDescIndex);
-
- // prepare cursor for value
- OLED::setFont(0);
- OLED::setCharCursor(cursorCharPosition, 0);
- // make room for scroll indicator
- OLED::setCursor(OLED::getCursorX() - 2, 0);
+ // print short description (default single line, explicit double line)
+ printShortDescriptionDoubleLine(shortDescIndex);
+
+ // prepare cursor for value
+ OLED::setFont(0);
+ OLED::setCharCursor(cursorCharPosition, 0);
+ // make room for scroll indicator
+ OLED::setCursor(OLED::getCursorX() - 2, 0);
}
static int userConfirmation(const char *message) {
- uint16_t messageWidth = FONT_12_WIDTH * (strlen(message) + 7);
- uint32_t messageStart = xTaskGetTickCount();
-
- OLED::setFont(0);
- OLED::setCursor(0, 0);
- int16_t lastOffset = -1;
- bool lcdRefresh = true;
-
- for (;;) {
- int16_t messageOffset = ((xTaskGetTickCount() - messageStart) / (systemSettings.descriptionScrollSpeed == 1 ? 10 : 20));
- messageOffset %= messageWidth; // Roll around at the end
-
- if (lastOffset != messageOffset) {
- OLED::clearScreen();
-
- //^ Rolling offset based on time
- OLED::setCursor((OLED_WIDTH - messageOffset), 0);
- OLED::print(message);
- lastOffset = messageOffset;
- lcdRefresh = true;
- }
-
- ButtonState buttons = getButtonState();
- switch (buttons) {
- case BUTTON_F_SHORT:
- // User confirmed
- return 1;
-
- case BUTTON_NONE:
- break;
- default:
- case BUTTON_BOTH:
- case BUTTON_B_SHORT:
- case BUTTON_F_LONG:
- case BUTTON_B_LONG:
- return 0;
- }
-
- if (lcdRefresh) {
- OLED::refresh();
- osDelay(40);
- lcdRefresh = false;
- }
- }
- return 0;
+ uint16_t messageWidth = FONT_12_WIDTH * (strlen(message) + 7);
+ uint32_t messageStart = xTaskGetTickCount();
+
+ OLED::setFont(0);
+ OLED::setCursor(0, 0);
+ int16_t lastOffset = -1;
+ bool lcdRefresh = true;
+
+ for (;;) {
+ int16_t messageOffset = ((xTaskGetTickCount() - messageStart) / (systemSettings.descriptionScrollSpeed == 1 ? 10 : 20));
+ messageOffset %= messageWidth; // Roll around at the end
+
+ if (lastOffset != messageOffset) {
+ OLED::clearScreen();
+
+ //^ Rolling offset based on time
+ OLED::setCursor((OLED_WIDTH - messageOffset), 0);
+ OLED::print(message);
+ lastOffset = messageOffset;
+ lcdRefresh = true;
+ }
+
+ ButtonState buttons = getButtonState();
+ switch (buttons) {
+ case BUTTON_F_SHORT:
+ // User confirmed
+ return 1;
+
+ case BUTTON_NONE:
+ break;
+ default:
+ case BUTTON_BOTH:
+ case BUTTON_B_SHORT:
+ case BUTTON_F_LONG:
+ case BUTTON_B_LONG:
+ return 0;
+ }
+
+ if (lcdRefresh) {
+ OLED::refresh();
+ osDelay(40);
+ lcdRefresh = false;
+ }
+ }
+ return 0;
}
#ifdef POW_DC
static bool settings_setInputVRange(void) {
- systemSettings.minDCVoltageCells = (systemSettings.minDCVoltageCells + 1) % 5;
- return systemSettings.minDCVoltageCells == 4;
+ systemSettings.minDCVoltageCells = (systemSettings.minDCVoltageCells + 1) % 5;
+ return systemSettings.minDCVoltageCells == 4;
}
static void settings_displayInputVRange(void) {
- printShortDescription(0, 6);
-
- if (systemSettings.minDCVoltageCells) {
- OLED::printNumber(2 + systemSettings.minDCVoltageCells, 1);
- OLED::print(SymbolCellCount);
- } else {
- OLED::print(SymbolDC);
- }
+ printShortDescription(0, 6);
+
+ if (systemSettings.minDCVoltageCells) {
+ OLED::printNumber(2 + systemSettings.minDCVoltageCells, 1);
+ OLED::print(SymbolCellCount);
+ } else {
+ OLED::print(SymbolDC);
+ }
}
#endif
#ifdef POW_QC
static bool settings_setQCInputV(void) {
#ifdef POW_QC_20V
- systemSettings.QCIdealVoltage = (systemSettings.QCIdealVoltage + 1) % 3;
- return systemSettings.QCIdealVoltage == 2;
+ systemSettings.QCIdealVoltage = (systemSettings.QCIdealVoltage + 1) % 3;
+ return systemSettings.QCIdealVoltage == 2;
#else
- systemSettings.QCIdealVoltage = (systemSettings.QCIdealVoltage + 1) % 2;
- return systemSettings.QCIdealVoltage == 1;
+ systemSettings.QCIdealVoltage = (systemSettings.QCIdealVoltage + 1) % 2;
+ return systemSettings.QCIdealVoltage == 1;
#endif
}
static void settings_displayQCInputV(void) {
- printShortDescription(19, 5);
- //0 = 9V, 1=12V, 2=20V (Fixed Voltages)
- // These are only used in QC modes
- switch (systemSettings.QCIdealVoltage) {
- case 0:
- OLED::printNumber(9, 2);
- OLED::print(SymbolVolts);
- break;
- case 1:
- OLED::printNumber(12, 2);
- OLED::print(SymbolVolts);
- break;
- case 2:
- OLED::printNumber(20, 2);
- OLED::print(SymbolVolts);
- break;
- default:
- break;
- }
+ printShortDescription(19, 5);
+ // 0 = 9V, 1=12V, 2=20V (Fixed Voltages)
+ // These are only used in QC modes
+ switch (systemSettings.QCIdealVoltage) {
+ case 0:
+ OLED::printNumber(9, 2);
+ OLED::print(SymbolVolts);
+ break;
+ case 1:
+ OLED::printNumber(12, 2);
+ OLED::print(SymbolVolts);
+ break;
+ case 2:
+ OLED::printNumber(20, 2);
+ OLED::print(SymbolVolts);
+ break;
+ default:
+ break;
+ }
}
#endif
static bool settings_setSleepTemp(void) {
- // If in C, 10 deg, if in F 20 deg
+ // If in C, 10 deg, if in F 20 deg
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- {
- systemSettings.SleepTemp += 20;
- if (systemSettings.SleepTemp > 580)
- systemSettings.SleepTemp = 60;
- return systemSettings.SleepTemp == 580;
- }
- else
+ if (systemSettings.temperatureInF) {
+ systemSettings.SleepTemp += 20;
+ if (systemSettings.SleepTemp > 580)
+ systemSettings.SleepTemp = 60;
+ return systemSettings.SleepTemp == 580;
+ } else
#endif
- {
- systemSettings.SleepTemp += 10;
- if (systemSettings.SleepTemp > 300)
- systemSettings.SleepTemp = 10;
- return systemSettings.SleepTemp == 300;
- }
+ {
+ systemSettings.SleepTemp += 10;
+ if (systemSettings.SleepTemp > 300)
+ systemSettings.SleepTemp = 10;
+ return systemSettings.SleepTemp == 300;
+ }
}
static void settings_displaySleepTemp(void) {
- printShortDescription(1, 5);
- OLED::printNumber(systemSettings.SleepTemp, 3);
+ printShortDescription(1, 5);
+ OLED::printNumber(systemSettings.SleepTemp, 3);
}
static bool settings_setSleepTime(void) {
- systemSettings.SleepTime++; // Go up 1 minute at a time
- if (systemSettings.SleepTime >= 16) {
- systemSettings.SleepTime = 0; // can't set time over 10 mins
- }
- // Remember that ^ is the time of no movement
- if (DetectedAccelerometerVersion == NO_DETECTED_ACCELEROMETER)
- systemSettings.SleepTime = 0; // Disable sleep on no accel
- return systemSettings.SleepTime == 15;
+ systemSettings.SleepTime++; // Go up 1 minute at a time
+ if (systemSettings.SleepTime >= 16) {
+ systemSettings.SleepTime = 0; // can't set time over 10 mins
+ }
+ // Remember that ^ is the time of no movement
+ if (DetectedAccelerometerVersion == NO_DETECTED_ACCELEROMETER)
+ systemSettings.SleepTime = 0; // Disable sleep on no accel
+ return systemSettings.SleepTime == 15;
}
static void settings_displaySleepTime(void) {
- printShortDescription(2, 5);
- if (systemSettings.SleepTime == 0) {
- OLED::print(OffString);
- } else if (systemSettings.SleepTime < 6) {
- OLED::printNumber(systemSettings.SleepTime * 10, 2);
- OLED::print(SymbolSeconds);
- } else {
- OLED::printNumber(systemSettings.SleepTime - 5, 2);
- OLED::print(SymbolMinutes);
- }
+ printShortDescription(2, 5);
+ if (systemSettings.SleepTime == 0) {
+ OLED::print(OffString);
+ } else if (systemSettings.SleepTime < 6) {
+ OLED::printNumber(systemSettings.SleepTime * 10, 2);
+ OLED::print(SymbolSeconds);
+ } else {
+ OLED::printNumber(systemSettings.SleepTime - 5, 2);
+ OLED::print(SymbolMinutes);
+ }
}
static bool settings_setShutdownTime(void) {
- systemSettings.ShutdownTime++;
- if (systemSettings.ShutdownTime > 60) {
- systemSettings.ShutdownTime = 0; // wrap to off
- }
- if (DetectedAccelerometerVersion == NO_DETECTED_ACCELEROMETER)
- systemSettings.ShutdownTime = 0; // Disable shutdown on no accel
- return systemSettings.ShutdownTime == 60;
+ systemSettings.ShutdownTime++;
+ if (systemSettings.ShutdownTime > 60) {
+ systemSettings.ShutdownTime = 0; // wrap to off
+ }
+ if (DetectedAccelerometerVersion == NO_DETECTED_ACCELEROMETER)
+ systemSettings.ShutdownTime = 0; // Disable shutdown on no accel
+ return systemSettings.ShutdownTime == 60;
}
static void settings_displayShutdownTime(void) {
- printShortDescription(3, 5);
- if (systemSettings.ShutdownTime == 0) {
- OLED::print(OffString);
- } else {
- OLED::printNumber(systemSettings.ShutdownTime, 2);
- OLED::print(SymbolMinutes);
- }
+ printShortDescription(3, 5);
+ if (systemSettings.ShutdownTime == 0) {
+ OLED::print(OffString);
+ } else {
+ OLED::printNumber(systemSettings.ShutdownTime, 2);
+ OLED::print(SymbolMinutes);
+ }
}
#ifdef ENABLED_FAHRENHEIT_SUPPORT
-static bool settings_setTempF(void)
-{
- systemSettings.temperatureInF = !systemSettings.temperatureInF;
- if (systemSettings.temperatureInF)
- {
- // Change sleep, boost and soldering temps to the F equiv
- // C to F == F= ( (C*9) +160)/5
- systemSettings.BoostTemp = ((systemSettings.BoostTemp * 9) + 160) / 5;
- systemSettings.SolderingTemp =
- ((systemSettings.SolderingTemp * 9) + 160) / 5;
- systemSettings.SleepTemp = ((systemSettings.SleepTemp * 9) + 160) / 5;
- }
- else
- {
- // Change sleep, boost and soldering temps to the C equiv
- // F->C == C = ((F-32)*5)/9
- systemSettings.BoostTemp = ((systemSettings.BoostTemp - 32) * 5) / 9;
- systemSettings.SolderingTemp = ((systemSettings.SolderingTemp - 32) * 5) / 9;
- systemSettings.SleepTemp = ((systemSettings.SleepTemp - 32) * 5) / 9;
- }
- // Rescale both to be multiples of 10
- systemSettings.BoostTemp = systemSettings.BoostTemp / 10;
- systemSettings.BoostTemp *= 10;
- systemSettings.SolderingTemp = systemSettings.SolderingTemp / 10;
- systemSettings.SolderingTemp *= 10;
- systemSettings.SleepTemp = systemSettings.SleepTemp / 10;
- systemSettings.SleepTemp *= 10;
- return false;
+static bool settings_setTempF(void) {
+ systemSettings.temperatureInF = !systemSettings.temperatureInF;
+ if (systemSettings.temperatureInF) {
+ // Change sleep, boost and soldering temps to the F equiv
+ // C to F == F= ( (C*9) +160)/5
+ systemSettings.BoostTemp = ((systemSettings.BoostTemp * 9) + 160) / 5;
+ systemSettings.SolderingTemp = ((systemSettings.SolderingTemp * 9) + 160) / 5;
+ systemSettings.SleepTemp = ((systemSettings.SleepTemp * 9) + 160) / 5;
+ } else {
+ // Change sleep, boost and soldering temps to the C equiv
+ // F->C == C = ((F-32)*5)/9
+ systemSettings.BoostTemp = ((systemSettings.BoostTemp - 32) * 5) / 9;
+ systemSettings.SolderingTemp = ((systemSettings.SolderingTemp - 32) * 5) / 9;
+ systemSettings.SleepTemp = ((systemSettings.SleepTemp - 32) * 5) / 9;
+ }
+ // Rescale both to be multiples of 10
+ systemSettings.BoostTemp = systemSettings.BoostTemp / 10;
+ systemSettings.BoostTemp *= 10;
+ systemSettings.SolderingTemp = systemSettings.SolderingTemp / 10;
+ systemSettings.SolderingTemp *= 10;
+ systemSettings.SleepTemp = systemSettings.SleepTemp / 10;
+ systemSettings.SleepTemp *= 10;
+ return false;
}
-static void settings_displayTempF(void)
-{
- printShortDescription(5, 7);
+static void settings_displayTempF(void) {
+ printShortDescription(5, 7);
- OLED::print((systemSettings.temperatureInF) ? SymbolDegF : SymbolDegC);
+ OLED::print((systemSettings.temperatureInF) ? SymbolDegF : SymbolDegC);
}
#endif
static bool settings_setSensitivity(void) {
- systemSettings.sensitivity++;
- systemSettings.sensitivity = systemSettings.sensitivity % 10;
- return systemSettings.sensitivity == 9;
+ systemSettings.sensitivity++;
+ systemSettings.sensitivity = systemSettings.sensitivity % 10;
+ return systemSettings.sensitivity == 9;
}
static void settings_displaySensitivity(void) {
- printShortDescription(4, 7);
- OLED::printNumber(systemSettings.sensitivity, 1, false);
+ printShortDescription(4, 7);
+ OLED::printNumber(systemSettings.sensitivity, 1, false);
}
static bool settings_setAdvancedSolderingScreens(void) {
- systemSettings.detailedSoldering = !systemSettings.detailedSoldering;
- return false;
+ systemSettings.detailedSoldering = !systemSettings.detailedSoldering;
+ return false;
}
static void settings_displayAdvancedSolderingScreens(void) {
- printShortDescription(14, 7);
+ printShortDescription(14, 7);
- OLED::drawCheckbox(systemSettings.detailedSoldering);
+ OLED::drawCheckbox(systemSettings.detailedSoldering);
}
static bool settings_setAdvancedIDLEScreens(void) {
- systemSettings.detailedIDLE = !systemSettings.detailedIDLE;
- return false;
+ systemSettings.detailedIDLE = !systemSettings.detailedIDLE;
+ return false;
}
static void settings_displayAdvancedIDLEScreens(void) {
- printShortDescription(6, 7);
+ printShortDescription(6, 7);
- OLED::drawCheckbox(systemSettings.detailedIDLE);
+ OLED::drawCheckbox(systemSettings.detailedIDLE);
}
static bool settings_setPowerLimit(void) {
- systemSettings.powerLimit += POWER_LIMIT_STEPS;
- if (systemSettings.powerLimit > MAX_POWER_LIMIT)
- systemSettings.powerLimit = 0;
- return systemSettings.powerLimit + POWER_LIMIT_STEPS > MAX_POWER_LIMIT;
+ systemSettings.powerLimit += POWER_LIMIT_STEPS;
+ if (systemSettings.powerLimit > MAX_POWER_LIMIT)
+ systemSettings.powerLimit = 0;
+ return systemSettings.powerLimit + POWER_LIMIT_STEPS > MAX_POWER_LIMIT;
}
static void settings_displayPowerLimit(void) {
- printShortDescription(20, 5);
- if (systemSettings.powerLimit == 0) {
- OLED::print(OffString);
- } else {
- OLED::printNumber(systemSettings.powerLimit, 2);
- OLED::print(SymbolWatts);
- }
+ printShortDescription(20, 5);
+ if (systemSettings.powerLimit == 0) {
+ OLED::print(OffString);
+ } else {
+ OLED::printNumber(systemSettings.powerLimit, 2);
+ OLED::print(SymbolWatts);
+ }
}
static bool settings_setScrollSpeed(void) {
- if (systemSettings.descriptionScrollSpeed == 0)
- systemSettings.descriptionScrollSpeed = 1;
- else
- systemSettings.descriptionScrollSpeed = 0;
- return false;
+ if (systemSettings.descriptionScrollSpeed == 0)
+ systemSettings.descriptionScrollSpeed = 1;
+ else
+ systemSettings.descriptionScrollSpeed = 0;
+ return false;
}
static void settings_displayScrollSpeed(void) {
- printShortDescription(15, 7);
- OLED::print((systemSettings.descriptionScrollSpeed) ? SettingFastChar : SettingSlowChar);
+ printShortDescription(15, 7);
+ OLED::print((systemSettings.descriptionScrollSpeed) ? SettingFastChar : SettingSlowChar);
}
static bool settings_setDisplayRotation(void) {
- systemSettings.OrientationMode++;
- systemSettings.OrientationMode = systemSettings.OrientationMode % 3;
- switch (systemSettings.OrientationMode) {
- case 0:
- OLED::setRotation(false);
- break;
- case 1:
- OLED::setRotation(true);
- break;
- case 2:
- // do nothing on auto
- break;
- default:
- break;
- }
- return systemSettings.OrientationMode == 2;
+ systemSettings.OrientationMode++;
+ systemSettings.OrientationMode = systemSettings.OrientationMode % 3;
+ switch (systemSettings.OrientationMode) {
+ case 0:
+ OLED::setRotation(false);
+ break;
+ case 1:
+ OLED::setRotation(true);
+ break;
+ case 2:
+ // do nothing on auto
+ break;
+ default:
+ break;
+ }
+ return systemSettings.OrientationMode == 2;
}
static void settings_displayDisplayRotation(void) {
- printShortDescription(7, 7);
-
- switch (systemSettings.OrientationMode) {
- case 0:
- OLED::print(SettingRightChar);
- break;
- case 1:
- OLED::print(SettingLeftChar);
- break;
- case 2:
- OLED::print(SettingAutoChar);
- break;
- default:
- OLED::print(SettingRightChar);
- break;
- }
+ printShortDescription(7, 7);
+
+ switch (systemSettings.OrientationMode) {
+ case 0:
+ OLED::print(SettingRightChar);
+ break;
+ case 1:
+ OLED::print(SettingLeftChar);
+ break;
+ case 2:
+ OLED::print(SettingAutoChar);
+ break;
+ default:
+ OLED::print(SettingRightChar);
+ break;
+ }
}
static bool settings_setBoostTemp(void) {
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- {
- if (systemSettings.BoostTemp == 0)
- {
- systemSettings.BoostTemp = 480; // loop back at 480
- }
- else
- {
- systemSettings.BoostTemp += 20; // Go up 20F at a time
- }
-
- if (systemSettings.BoostTemp > 850)
- {
- systemSettings.BoostTemp = 0; // jump to off
- }
- return systemSettings.BoostTemp == 840;
- }
- else
+ if (systemSettings.temperatureInF) {
+ if (systemSettings.BoostTemp == 0) {
+ systemSettings.BoostTemp = 480; // loop back at 480
+ } else {
+ systemSettings.BoostTemp += 20; // Go up 20F at a time
+ }
+
+ if (systemSettings.BoostTemp > 850) {
+ systemSettings.BoostTemp = 0; // jump to off
+ }
+ return systemSettings.BoostTemp == 840;
+ } else
#endif
- {
- if (systemSettings.BoostTemp == 0) {
- systemSettings.BoostTemp = 250; // loop back at 250
- } else {
- systemSettings.BoostTemp += 10; // Go up 10C at a time
- }
- if (systemSettings.BoostTemp > 450) {
- systemSettings.BoostTemp = 0; //Go to off state
- }
- return systemSettings.BoostTemp == 450;
- }
+ {
+ if (systemSettings.BoostTemp == 0) {
+ systemSettings.BoostTemp = 250; // loop back at 250
+ } else {
+ systemSettings.BoostTemp += 10; // Go up 10C at a time
+ }
+ if (systemSettings.BoostTemp > 450) {
+ systemSettings.BoostTemp = 0; // Go to off state
+ }
+ return systemSettings.BoostTemp == 450;
+ }
}
static void settings_displayBoostTemp(void) {
- printShortDescription(8, 5);
- if (systemSettings.BoostTemp) {
- OLED::printNumber(systemSettings.BoostTemp, 3);
- } else {
- OLED::print(OffString);
- }
+ printShortDescription(8, 5);
+ if (systemSettings.BoostTemp) {
+ OLED::printNumber(systemSettings.BoostTemp, 3);
+ } else {
+ OLED::print(OffString);
+ }
}
static bool settings_setAutomaticStartMode(void) {
- systemSettings.autoStartMode++;
- systemSettings.autoStartMode %= 4;
- return systemSettings.autoStartMode == 3;
+ systemSettings.autoStartMode++;
+ systemSettings.autoStartMode %= 4;
+ return systemSettings.autoStartMode == 3;
}
static void settings_displayAutomaticStartMode(void) {
- printShortDescription(9, 7);
-
- switch (systemSettings.autoStartMode) {
- case 0:
- OLED::print(SettingStartNoneChar);
- break;
- case 1:
- OLED::print(SettingStartSolderingChar);
- break;
- case 2:
- OLED::print(SettingStartSleepChar);
- break;
- case 3:
- OLED::print(SettingStartSleepOffChar);
- break;
- default:
- OLED::print(SettingStartNoneChar);
- break;
- }
+ printShortDescription(9, 7);
+
+ switch (systemSettings.autoStartMode) {
+ case 0:
+ OLED::print(SettingStartNoneChar);
+ break;
+ case 1:
+ OLED::print(SettingStartSolderingChar);
+ break;
+ case 2:
+ OLED::print(SettingStartSleepChar);
+ break;
+ case 3:
+ OLED::print(SettingStartSleepOffChar);
+ break;
+ default:
+ OLED::print(SettingStartNoneChar);
+ break;
+ }
}
static bool settings_setLockingMode(void) {
- systemSettings.lockingMode++;
- systemSettings.lockingMode %= 3;
- return systemSettings.lockingMode == 2;
+ systemSettings.lockingMode++;
+ systemSettings.lockingMode %= 3;
+ return systemSettings.lockingMode == 2;
}
static void settings_displayLockingMode(void) {
- printShortDescription(27, 7);
-
- switch (systemSettings.lockingMode) {
- case 0:
- OLED::print (SettingLockDisableChar);
- break;
- case 1:
- OLED::print (SettingLockBoostChar);
- break;
- case 2:
- OLED::print (SettingLockFullChar);
- break;
- default:
- OLED::print(SettingLockDisableChar);
- break;
- }
+ printShortDescription(27, 7);
+
+ switch (systemSettings.lockingMode) {
+ case 0:
+ OLED::print(SettingLockDisableChar);
+ break;
+ case 1:
+ OLED::print(SettingLockBoostChar);
+ break;
+ case 2:
+ OLED::print(SettingLockFullChar);
+ break;
+ default:
+ OLED::print(SettingLockDisableChar);
+ break;
+ }
}
static bool settings_setCoolingBlinkEnabled(void) {
- systemSettings.coolingTempBlink = !systemSettings.coolingTempBlink;
- return false;
+ systemSettings.coolingTempBlink = !systemSettings.coolingTempBlink;
+ return false;
}
static void settings_displayCoolingBlinkEnabled(void) {
- printShortDescription(10, 7);
+ printShortDescription(10, 7);
- OLED::drawCheckbox(systemSettings.coolingTempBlink);
+ OLED::drawCheckbox(systemSettings.coolingTempBlink);
}
static bool settings_setResetSettings(void) {
- if (userConfirmation(SettingsResetWarning)) {
- resetSettings();
+ if (userConfirmation(SettingsResetWarning)) {
+ resetSettings();
- OLED::setFont(0);
- OLED::setCursor(0, 0);
- OLED::print(ResetOKMessage);
- OLED::refresh();
+ OLED::setFont(0);
+ OLED::setCursor(0, 0);
+ OLED::print(ResetOKMessage);
+ OLED::refresh();
- waitForButtonPressOrTimeout(2000); // 2 second timeout
- }
- return false;
+ waitForButtonPressOrTimeout(2000); // 2 second timeout
+ }
+ return false;
}
-static void settings_displayResetSettings(void) {
- printShortDescription(12, 7);
-}
+static void settings_displayResetSettings(void) { printShortDescription(12, 7); }
static void setTipOffset() {
- systemSettings.CalibrationOffset = 0;
-
- // If the thermo-couple at the end of the tip, and the handle are at
- // equilibrium, then the output should be zero, as there is no temperature
- // differential.
- while (systemSettings.CalibrationOffset == 0) {
- uint32_t offset = 0;
- for (uint8_t i = 0; i < 16; i++) {
- offset += getTipRawTemp(1);
- // cycle through the filter a fair bit to ensure we're stable.
- OLED::clearScreen();
- OLED::setCursor(0, 0);
- OLED::print(SymbolDot);
- for (uint8_t x = 0; x < (i / 4); x++)
- OLED::print(SymbolDot);
- OLED::refresh();
- osDelay(100);
- }
- systemSettings.CalibrationOffset = TipThermoModel::convertTipRawADCTouV(offset / 16);
- }
- OLED::clearScreen();
- OLED::setCursor(0, 0);
- OLED::drawCheckbox(true);
- OLED::printNumber(systemSettings.CalibrationOffset, 4);
- OLED::refresh();
- osDelay(1200);
+ systemSettings.CalibrationOffset = 0;
+
+ // If the thermo-couple at the end of the tip, and the handle are at
+ // equilibrium, then the output should be zero, as there is no temperature
+ // differential.
+ while (systemSettings.CalibrationOffset == 0) {
+ uint32_t offset = 0;
+ for (uint8_t i = 0; i < 16; i++) {
+ offset += getTipRawTemp(1);
+ // cycle through the filter a fair bit to ensure we're stable.
+ OLED::clearScreen();
+ OLED::setCursor(0, 0);
+ OLED::print(SymbolDot);
+ for (uint8_t x = 0; x < (i / 4); x++)
+ OLED::print(SymbolDot);
+ OLED::refresh();
+ osDelay(100);
+ }
+ systemSettings.CalibrationOffset = TipThermoModel::convertTipRawADCTouV(offset / 16);
+ }
+ OLED::clearScreen();
+ OLED::setCursor(0, 0);
+ OLED::drawCheckbox(true);
+ OLED::printNumber(systemSettings.CalibrationOffset, 4);
+ OLED::refresh();
+ osDelay(1200);
}
-//Provide the user the option to tune their own tip if custom is selected
-//If not only do single point tuning as per usual
+// Provide the user the option to tune their own tip if custom is selected
+// If not only do single point tuning as per usual
static bool settings_setCalibrate(void) {
- if (userConfirmation(SettingsCalibrationWarning)) {
- // User confirmed
- // So we now perform the actual calculation
- setTipOffset();
- }
- return false;
+ if (userConfirmation(SettingsCalibrationWarning)) {
+ // User confirmed
+ // So we now perform the actual calculation
+ setTipOffset();
+ }
+ return false;
}
-static void settings_displayCalibrate(void) {
- printShortDescription(11, 5);
-}
+static void settings_displayCalibrate(void) { printShortDescription(11, 5); }
static bool settings_setCalibrateVIN(void) {
- // Jump to the voltage calibration subscreen
- OLED::setFont(0);
- OLED::clearScreen();
-
- for (;;) {
- OLED::setCursor(0, 0);
- OLED::printNumber(getInputVoltageX10(systemSettings.voltageDiv, 0) / 10, 2);
- OLED::print(SymbolDot);
- OLED::printNumber(getInputVoltageX10(systemSettings.voltageDiv, 0) % 10, 1, false);
- OLED::print(SymbolVolts);
-
- ButtonState buttons = getButtonState();
- switch (buttons) {
- case BUTTON_F_SHORT:
- systemSettings.voltageDiv++;
- break;
-
- case BUTTON_B_SHORT:
- systemSettings.voltageDiv--;
- break;
-
- case BUTTON_BOTH:
- case BUTTON_F_LONG:
- case BUTTON_B_LONG:
- saveSettings();
- OLED::setCursor(0, 0);
- OLED::printNumber(systemSettings.voltageDiv, 3);
- OLED::refresh();
- waitForButtonPressOrTimeout(1000);
- return false;
- case BUTTON_NONE:
- default:
- break;
- }
-
- OLED::refresh();
- osDelay(40);
-
- // Cap to sensible values
+ // Jump to the voltage calibration subscreen
+ OLED::setFont(0);
+ OLED::clearScreen();
+
+ for (;;) {
+ OLED::setCursor(0, 0);
+ OLED::printNumber(getInputVoltageX10(systemSettings.voltageDiv, 0) / 10, 2);
+ OLED::print(SymbolDot);
+ OLED::printNumber(getInputVoltageX10(systemSettings.voltageDiv, 0) % 10, 1, false);
+ OLED::print(SymbolVolts);
+
+ ButtonState buttons = getButtonState();
+ switch (buttons) {
+ case BUTTON_F_SHORT:
+ systemSettings.voltageDiv++;
+ break;
+
+ case BUTTON_B_SHORT:
+ systemSettings.voltageDiv--;
+ break;
+
+ case BUTTON_BOTH:
+ case BUTTON_F_LONG:
+ case BUTTON_B_LONG:
+ saveSettings();
+ OLED::setCursor(0, 0);
+ OLED::printNumber(systemSettings.voltageDiv, 3);
+ OLED::refresh();
+ waitForButtonPressOrTimeout(1000);
+ return false;
+ case BUTTON_NONE:
+ default:
+ break;
+ }
+
+ OLED::refresh();
+ osDelay(40);
+
+ // Cap to sensible values
#if defined(MODEL_TS80) + defined(MODEL_TS80P) > 0
- if (systemSettings.voltageDiv < 500)
- {
- systemSettings.voltageDiv = 500;
- }
- else if (systemSettings.voltageDiv > 900)
- {
- systemSettings.voltageDiv = 900;
- }
+ if (systemSettings.voltageDiv < 500) {
+ systemSettings.voltageDiv = 500;
+ } else if (systemSettings.voltageDiv > 900) {
+ systemSettings.voltageDiv = 900;
+ }
#else
- if (systemSettings.voltageDiv < 360) {
- systemSettings.voltageDiv = 360;
- } else if (systemSettings.voltageDiv > 520) {
- systemSettings.voltageDiv = 520;
- }
+ if (systemSettings.voltageDiv < 360) {
+ systemSettings.voltageDiv = 360;
+ } else if (systemSettings.voltageDiv > 520) {
+ systemSettings.voltageDiv = 520;
+ }
#endif
- }
- return false;
+ }
+ return false;
}
//
-//static bool settings_setTipGain(void) {
+// static bool settings_setTipGain(void) {
// OLED::setFont(0);
// OLED::clearScreen();
//
@@ -821,295 +799,280 @@ static bool settings_setCalibrateVIN(void) {
// return false;
//}
//
-//static void settings_displayTipGain(void) {
+// static void settings_displayTipGain(void) {
// printShortDescription(25, 5);
//}
static bool settings_setReverseButtonTempChangeEnabled(void) {
- systemSettings.ReverseButtonTempChangeEnabled = !systemSettings.ReverseButtonTempChangeEnabled;
- return false;
+ systemSettings.ReverseButtonTempChangeEnabled = !systemSettings.ReverseButtonTempChangeEnabled;
+ return false;
}
static void settings_displayReverseButtonTempChangeEnabled(void) {
- printShortDescription(21, 7);
- OLED::drawCheckbox(systemSettings.ReverseButtonTempChangeEnabled);
+ printShortDescription(21, 7);
+ OLED::drawCheckbox(systemSettings.ReverseButtonTempChangeEnabled);
}
static bool settings_setTempChangeShortStep(void) {
- systemSettings.TempChangeShortStep += TEMP_CHANGE_SHORT_STEP;
- if (systemSettings.TempChangeShortStep > TEMP_CHANGE_SHORT_STEP_MAX) {
- systemSettings.TempChangeShortStep = TEMP_CHANGE_SHORT_STEP; // loop back at TEMP_CHANGE_SHORT_STEP_MAX
- }
- return systemSettings.TempChangeShortStep == TEMP_CHANGE_SHORT_STEP_MAX;
+ systemSettings.TempChangeShortStep += TEMP_CHANGE_SHORT_STEP;
+ if (systemSettings.TempChangeShortStep > TEMP_CHANGE_SHORT_STEP_MAX) {
+ systemSettings.TempChangeShortStep = TEMP_CHANGE_SHORT_STEP; // loop back at TEMP_CHANGE_SHORT_STEP_MAX
+ }
+ return systemSettings.TempChangeShortStep == TEMP_CHANGE_SHORT_STEP_MAX;
}
static void settings_displayTempChangeShortStep(void) {
- printShortDescription(22, 6);
- OLED::printNumber(systemSettings.TempChangeShortStep, 2);
+ printShortDescription(22, 6);
+ OLED::printNumber(systemSettings.TempChangeShortStep, 2);
}
static bool settings_setTempChangeLongStep(void) {
- systemSettings.TempChangeLongStep += TEMP_CHANGE_LONG_STEP;
- if (systemSettings.TempChangeLongStep > TEMP_CHANGE_LONG_STEP_MAX) {
- systemSettings.TempChangeLongStep = TEMP_CHANGE_LONG_STEP; // loop back at TEMP_CHANGE_LONG_STEP_MAX
- }
- return systemSettings.TempChangeLongStep == TEMP_CHANGE_LONG_STEP_MAX;
+ systemSettings.TempChangeLongStep += TEMP_CHANGE_LONG_STEP;
+ if (systemSettings.TempChangeLongStep > TEMP_CHANGE_LONG_STEP_MAX) {
+ systemSettings.TempChangeLongStep = TEMP_CHANGE_LONG_STEP; // loop back at TEMP_CHANGE_LONG_STEP_MAX
+ }
+ return systemSettings.TempChangeLongStep == TEMP_CHANGE_LONG_STEP_MAX;
}
static void settings_displayTempChangeLongStep(void) {
- printShortDescription(23, 6);
- OLED::printNumber(systemSettings.TempChangeLongStep, 2);
+ printShortDescription(23, 6);
+ OLED::printNumber(systemSettings.TempChangeLongStep, 2);
}
static bool settings_setPowerPulse(void) {
- systemSettings.KeepAwakePulse += POWER_PULSE_INCREMENT;
- systemSettings.KeepAwakePulse %= POWER_PULSE_MAX;
+ systemSettings.KeepAwakePulse += POWER_PULSE_INCREMENT;
+ systemSettings.KeepAwakePulse %= POWER_PULSE_MAX;
- return systemSettings.KeepAwakePulse == POWER_PULSE_MAX - 1;
+ return systemSettings.KeepAwakePulse == POWER_PULSE_MAX - 1;
}
static void settings_displayPowerPulse(void) {
- printShortDescription(24, 5);
- if (systemSettings.KeepAwakePulse) {
- OLED::printNumber(systemSettings.KeepAwakePulse / 10, 1);
- OLED::print(SymbolDot);
- OLED::printNumber(systemSettings.KeepAwakePulse % 10, 1);
- } else {
- OLED::print(OffString);
- }
+ printShortDescription(24, 5);
+ if (systemSettings.KeepAwakePulse) {
+ OLED::printNumber(systemSettings.KeepAwakePulse / 10, 1);
+ OLED::print(SymbolDot);
+ OLED::printNumber(systemSettings.KeepAwakePulse % 10, 1);
+ } else {
+ OLED::print(OffString);
+ }
}
#ifdef HALL_SENSOR
static void settings_displayHallEffect(void) {
- printShortDescription(26, 7);
- switch (systemSettings.hallEffectSensitivity) {
- case 1:
- OLED::print(SettingSensitivityLow);
- break;
- case 2:
- OLED::print(SettingSensitivityMedium);
- break;
- case 3:
- OLED::print(SettingSensitivityHigh);
- break;
- case 0:
- default:
- OLED::print(SettingSensitivityOff);
- break;
- }
+ printShortDescription(26, 7);
+ switch (systemSettings.hallEffectSensitivity) {
+ case 1:
+ OLED::print(SettingSensitivityLow);
+ break;
+ case 2:
+ OLED::print(SettingSensitivityMedium);
+ break;
+ case 3:
+ OLED::print(SettingSensitivityHigh);
+ break;
+ case 0:
+ default:
+ OLED::print(SettingSensitivityOff);
+ break;
+ }
}
static bool settings_setHallEffect(void) {
- //To keep life simpler for now, we have a few preset sensitivity levels
- // Off, Low, Medium, High
- systemSettings.hallEffectSensitivity++;
- systemSettings.hallEffectSensitivity %= 4;
- return systemSettings.hallEffectSensitivity == 3;
+ // To keep life simpler for now, we have a few preset sensitivity levels
+ // Off, Low, Medium, High
+ systemSettings.hallEffectSensitivity++;
+ systemSettings.hallEffectSensitivity %= 4;
+ return systemSettings.hallEffectSensitivity == 3;
}
#endif
static void displayMenu(size_t index) {
- // Call into the menu
- OLED::setFont(1);
- OLED::setCursor(0, 0);
- // Draw title
- OLED::print(SettingsMenuEntries[index]);
- // Draw symbol
- // 16 pixel wide image
- // 2 pixel wide scrolling indicator
- OLED::drawArea(96 - 16 - 2, 0, 16, 16, (&SettingsMenuIcons[(16 * 2) * index]));
+ // Call into the menu
+ OLED::setFont(1);
+ OLED::setCursor(0, 0);
+ // Draw title
+ OLED::print(SettingsMenuEntries[index]);
+ // Draw symbol
+ // 16 pixel wide image
+ // 2 pixel wide scrolling indicator
+ OLED::drawArea(96 - 16 - 2, 0, 16, 16, (&SettingsMenuIcons[(16 * 2) * index]));
}
-static void settings_displayCalibrateVIN(void) {
- printShortDescription(13, 5);
-}
-static void settings_displaySolderingMenu(void) {
- displayMenu(0);
-}
+static void settings_displayCalibrateVIN(void) { printShortDescription(13, 5); }
+static void settings_displaySolderingMenu(void) { displayMenu(0); }
static bool settings_enterSolderingMenu(void) {
- gui_Menu(solderingMenu);
- return false;
-}
-static void settings_displayPowerMenu(void) {
- displayMenu(1);
+ gui_Menu(solderingMenu);
+ return false;
}
+static void settings_displayPowerMenu(void) { displayMenu(1); }
static bool settings_enterPowerMenu(void) {
- gui_Menu(PowerMenu);
- return false;
-}
-static void settings_displayUIMenu(void) {
- displayMenu(2);
+ gui_Menu(PowerMenu);
+ return false;
}
+static void settings_displayUIMenu(void) { displayMenu(2); }
static bool settings_enterUIMenu(void) {
- gui_Menu(UIMenu);
- return false;
-}
-static void settings_displayAdvancedMenu(void) {
- displayMenu(3);
+ gui_Menu(UIMenu);
+ return false;
}
+static void settings_displayAdvancedMenu(void) { displayMenu(3); }
static bool settings_enterAdvancedMenu(void) {
- gui_Menu(advancedMenu);
- return false;
+ gui_Menu(advancedMenu);
+ return false;
}
void gui_Menu(const menuitem *menu) {
- // Draw the settings menu and provide iteration support etc
- uint8_t currentScreen = 0;
- uint32_t autoRepeatTimer = 0;
- uint8_t autoRepeatAcceleration = 0;
- bool earlyExit = false;
- uint32_t descriptionStart = 0;
- int16_t lastOffset = -1;
- bool lcdRefresh = true;
- ButtonState lastButtonState = BUTTON_NONE;
- static bool enterGUIMenu = true;
- enterGUIMenu = true;
- uint8_t scrollContentSize = 0;
- bool scrollBlink = false;
- bool lastValue = false;
-
- for (uint8_t i = 0; menu[i].draw != NULL; i++) {
- scrollContentSize += 1;
- }
-
- // Animated menu opening.
- if (menu[currentScreen].draw != NULL) {
- // This menu is drawn in a secondary framebuffer.
- // Then we play a transition from the current primary
- // framebuffer to the new buffer.
- // The extra buffer is discarded at the end of the transition.
- OLED::useSecondaryFramebuffer(true);
- OLED::setFont(0);
- OLED::setCursor(0, 0);
- OLED::clearScreen();
- menu[currentScreen].draw();
- OLED::useSecondaryFramebuffer(false);
- OLED::transitionSecondaryFramebuffer(true);
- }
-
- while ((menu[currentScreen].draw != NULL) && earlyExit == false) {
- OLED::setFont(0);
- OLED::setCursor(0, 0);
- // If the user has hesitated for >=3 seconds, show the long text
- // Otherwise "draw" the option
- if ((xTaskGetTickCount() - lastButtonTime < 3000) || menu[currentScreen].description == NULL) {
- OLED::clearScreen();
- menu[currentScreen].draw();
- uint8_t indicatorHeight = OLED_HEIGHT / scrollContentSize;
- uint8_t position = OLED_HEIGHT * currentScreen / scrollContentSize;
- if (lastValue)
- scrollBlink = !scrollBlink;
- if (!lastValue || !scrollBlink)
- OLED::drawScrollIndicator(position, indicatorHeight);
- lastOffset = -1;
- lcdRefresh = true;
- } else {
- // Draw description
- if (descriptionStart == 0)
- descriptionStart = xTaskGetTickCount();
- // lower the value - higher the speed
- int16_t descriptionWidth =
- FONT_12_WIDTH * (strlen(menu[currentScreen].description) + 7);
- int16_t descriptionOffset = ((xTaskGetTickCount() - descriptionStart) / (systemSettings.descriptionScrollSpeed == 1 ? 10 : 20));
- descriptionOffset %= descriptionWidth; // Roll around at the end
- if (lastOffset != descriptionOffset) {
- OLED::clearScreen();
- OLED::setCursor((OLED_WIDTH - descriptionOffset), 0);
- OLED::print(menu[currentScreen].description);
- lastOffset = descriptionOffset;
- lcdRefresh = true;
- }
- }
-
- ButtonState buttons = getButtonState();
-
- if (buttons != lastButtonState) {
- autoRepeatAcceleration = 0;
- lastButtonState = buttons;
- }
-
- switch (buttons) {
- case BUTTON_BOTH:
- earlyExit = true; // will make us exit next loop
- descriptionStart = 0;
- break;
- case BUTTON_F_SHORT:
- // increment
- if (descriptionStart == 0) {
- if (menu[currentScreen].incrementHandler != NULL) {
- enterGUIMenu = false;
- lastValue = menu[currentScreen].incrementHandler();
-
- if (enterGUIMenu) {
- OLED::useSecondaryFramebuffer(true);
- OLED::setFont(0);
- OLED::setCursor(0, 0);
- OLED::clearScreen();
- menu[currentScreen].draw();
- OLED::useSecondaryFramebuffer(false);
- OLED::transitionSecondaryFramebuffer(false);
- }
- enterGUIMenu = true;
- } else {
- earlyExit = true;
- }
- } else
- descriptionStart = 0;
- break;
- case BUTTON_B_SHORT:
- if (descriptionStart == 0) {
- currentScreen++;
- lastValue = false;
- } else
- descriptionStart = 0;
- break;
- case BUTTON_F_LONG:
- if ((int) (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration) >
- PRESS_ACCEL_INTERVAL_MAX) {
- if ((lastValue = menu[currentScreen].incrementHandler()))
- autoRepeatTimer = 1000;
- else
- autoRepeatTimer = 0;
-
- autoRepeatTimer += xTaskGetTickCount();
-
- descriptionStart = 0;
-
- autoRepeatAcceleration += PRESS_ACCEL_STEP;
- }
- break;
- case BUTTON_B_LONG:
- if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration >
- PRESS_ACCEL_INTERVAL_MAX) {
- currentScreen++;
- autoRepeatTimer = xTaskGetTickCount();
- descriptionStart = 0;
-
- autoRepeatAcceleration += PRESS_ACCEL_STEP;
- }
- break;
- case BUTTON_NONE:
- default:
- break;
- }
-
- if ((PRESS_ACCEL_INTERVAL_MAX - autoRepeatAcceleration) <
- PRESS_ACCEL_INTERVAL_MIN) {
- autoRepeatAcceleration =
- PRESS_ACCEL_INTERVAL_MAX - PRESS_ACCEL_INTERVAL_MIN;
- }
-
- if (lcdRefresh) {
- OLED::refresh(); // update the LCD
- osDelay(40);
- lcdRefresh = false;
- }
- if ((xTaskGetTickCount() - lastButtonTime) > (1000 * 30)) {
- // If user has not pressed any buttons in 30 seconds, exit back a menu layer
- // This will trickle the user back to the main screen eventually
- earlyExit = true;
- descriptionStart = 0;
- }
- }
+ // Draw the settings menu and provide iteration support etc
+ uint8_t currentScreen = 0;
+ uint32_t autoRepeatTimer = 0;
+ uint8_t autoRepeatAcceleration = 0;
+ bool earlyExit = false;
+ uint32_t descriptionStart = 0;
+ int16_t lastOffset = -1;
+ bool lcdRefresh = true;
+ ButtonState lastButtonState = BUTTON_NONE;
+ static bool enterGUIMenu = true;
+ enterGUIMenu = true;
+ uint8_t scrollContentSize = 0;
+ bool scrollBlink = false;
+ bool lastValue = false;
+
+ for (uint8_t i = 0; menu[i].draw != NULL; i++) {
+ scrollContentSize += 1;
+ }
+
+ // Animated menu opening.
+ if (menu[currentScreen].draw != NULL) {
+ // This menu is drawn in a secondary framebuffer.
+ // Then we play a transition from the current primary
+ // framebuffer to the new buffer.
+ // The extra buffer is discarded at the end of the transition.
+ OLED::useSecondaryFramebuffer(true);
+ OLED::setFont(0);
+ OLED::setCursor(0, 0);
+ OLED::clearScreen();
+ menu[currentScreen].draw();
+ OLED::useSecondaryFramebuffer(false);
+ OLED::transitionSecondaryFramebuffer(true);
+ }
+
+ while ((menu[currentScreen].draw != NULL) && earlyExit == false) {
+ OLED::setFont(0);
+ OLED::setCursor(0, 0);
+ // If the user has hesitated for >=3 seconds, show the long text
+ // Otherwise "draw" the option
+ if ((xTaskGetTickCount() - lastButtonTime < 3000) || menu[currentScreen].description == NULL) {
+ OLED::clearScreen();
+ menu[currentScreen].draw();
+ uint8_t indicatorHeight = OLED_HEIGHT / scrollContentSize;
+ uint8_t position = OLED_HEIGHT * currentScreen / scrollContentSize;
+ if (lastValue)
+ scrollBlink = !scrollBlink;
+ if (!lastValue || !scrollBlink)
+ OLED::drawScrollIndicator(position, indicatorHeight);
+ lastOffset = -1;
+ lcdRefresh = true;
+ } else {
+ // Draw description
+ if (descriptionStart == 0)
+ descriptionStart = xTaskGetTickCount();
+ // lower the value - higher the speed
+ int16_t descriptionWidth = FONT_12_WIDTH * (strlen(menu[currentScreen].description) + 7);
+ int16_t descriptionOffset = ((xTaskGetTickCount() - descriptionStart) / (systemSettings.descriptionScrollSpeed == 1 ? 10 : 20));
+ descriptionOffset %= descriptionWidth; // Roll around at the end
+ if (lastOffset != descriptionOffset) {
+ OLED::clearScreen();
+ OLED::setCursor((OLED_WIDTH - descriptionOffset), 0);
+ OLED::print(menu[currentScreen].description);
+ lastOffset = descriptionOffset;
+ lcdRefresh = true;
+ }
+ }
+
+ ButtonState buttons = getButtonState();
+
+ if (buttons != lastButtonState) {
+ autoRepeatAcceleration = 0;
+ lastButtonState = buttons;
+ }
+
+ switch (buttons) {
+ case BUTTON_BOTH:
+ earlyExit = true; // will make us exit next loop
+ descriptionStart = 0;
+ break;
+ case BUTTON_F_SHORT:
+ // increment
+ if (descriptionStart == 0) {
+ if (menu[currentScreen].incrementHandler != NULL) {
+ enterGUIMenu = false;
+ lastValue = menu[currentScreen].incrementHandler();
+
+ if (enterGUIMenu) {
+ OLED::useSecondaryFramebuffer(true);
+ OLED::setFont(0);
+ OLED::setCursor(0, 0);
+ OLED::clearScreen();
+ menu[currentScreen].draw();
+ OLED::useSecondaryFramebuffer(false);
+ OLED::transitionSecondaryFramebuffer(false);
+ }
+ enterGUIMenu = true;
+ } else {
+ earlyExit = true;
+ }
+ } else
+ descriptionStart = 0;
+ break;
+ case BUTTON_B_SHORT:
+ if (descriptionStart == 0) {
+ currentScreen++;
+ lastValue = false;
+ } else
+ descriptionStart = 0;
+ break;
+ case BUTTON_F_LONG:
+ if ((int)(xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration) > PRESS_ACCEL_INTERVAL_MAX) {
+ if ((lastValue = menu[currentScreen].incrementHandler()))
+ autoRepeatTimer = 1000;
+ else
+ autoRepeatTimer = 0;
+
+ autoRepeatTimer += xTaskGetTickCount();
+
+ descriptionStart = 0;
+
+ autoRepeatAcceleration += PRESS_ACCEL_STEP;
+ }
+ break;
+ case BUTTON_B_LONG:
+ if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration > PRESS_ACCEL_INTERVAL_MAX) {
+ currentScreen++;
+ autoRepeatTimer = xTaskGetTickCount();
+ descriptionStart = 0;
+
+ autoRepeatAcceleration += PRESS_ACCEL_STEP;
+ }
+ break;
+ case BUTTON_NONE:
+ default:
+ break;
+ }
+
+ if ((PRESS_ACCEL_INTERVAL_MAX - autoRepeatAcceleration) < PRESS_ACCEL_INTERVAL_MIN) {
+ autoRepeatAcceleration = PRESS_ACCEL_INTERVAL_MAX - PRESS_ACCEL_INTERVAL_MIN;
+ }
+
+ if (lcdRefresh) {
+ OLED::refresh(); // update the LCD
+ osDelay(40);
+ lcdRefresh = false;
+ }
+ if ((xTaskGetTickCount() - lastButtonTime) > (1000 * 30)) {
+ // If user has not pressed any buttons in 30 seconds, exit back a menu layer
+ // This will trickle the user back to the main screen eventually
+ earlyExit = true;
+ descriptionStart = 0;
+ }
+ }
}
void enterSettingsMenu() {
- gui_Menu(rootSettingsMenu); // Call the root menu
- saveSettings();
+ gui_Menu(rootSettingsMenu); // Call the root menu
+ saveSettings();
}
diff --git a/source/Core/Src/main.cpp b/source/Core/Src/main.cpp
index 14d27bb5..4a29f8fa 100644
--- a/source/Core/Src/main.cpp
+++ b/source/Core/Src/main.cpp
@@ -5,67 +5,66 @@
*/
#include "BSP.h"
-#include <main.hpp>
#include "LIS2DH12.hpp"
-#include <MMA8652FC.hpp>
-#include <power.hpp>
#include "Settings.h"
#include "cmsis_os.h"
+#include <MMA8652FC.hpp>
+#include <main.hpp>
+#include <power.hpp>
uint8_t DetectedAccelerometerVersion = 0;
-bool settingsWereReset = false;
+bool settingsWereReset = false;
// FreeRTOS variables
-osThreadId GUITaskHandle;
+osThreadId GUITaskHandle;
static const size_t GUITaskStackSize = 1024 / 4;
-uint32_t GUITaskBuffer[GUITaskStackSize];
+uint32_t GUITaskBuffer[GUITaskStackSize];
osStaticThreadDef_t GUITaskControlBlock;
-osThreadId PIDTaskHandle;
+osThreadId PIDTaskHandle;
static const size_t PIDTaskStackSize = 512 / 4;
-uint32_t PIDTaskBuffer[PIDTaskStackSize];
+uint32_t PIDTaskBuffer[PIDTaskStackSize];
osStaticThreadDef_t PIDTaskControlBlock;
-osThreadId MOVTaskHandle;
+osThreadId MOVTaskHandle;
static const size_t MOVTaskStackSize = 1024 / 4;
-uint32_t MOVTaskBuffer[MOVTaskStackSize];
+uint32_t MOVTaskBuffer[MOVTaskStackSize];
osStaticThreadDef_t MOVTaskControlBlock;
-osThreadId POWTaskHandle;
+osThreadId POWTaskHandle;
static const size_t POWTaskStackSize = 512 / 4;
-uint32_t POWTaskBuffer[POWTaskStackSize];
+uint32_t POWTaskBuffer[POWTaskStackSize];
osStaticThreadDef_t POWTaskControlBlock;
// End FreeRTOS
// Main sets up the hardware then hands over to the FreeRTOS kernel
int main(void) {
- preRToSInit();
- setTipX10Watts(0); // force tip off
- resetWatchdog();
- OLED::setFont(0); // default to bigger font
- // Testing for which accelerometer is mounted
- settingsWereReset = restoreSettings(); // load the settings from flash
- resetWatchdog();
- /* Create the thread(s) */
- /* definition and creation of POWTask - Power management for QC */
- osThreadStaticDef(POWTask, startPOWTask, osPriorityAboveNormal, 0, POWTaskStackSize, POWTaskBuffer, &POWTaskControlBlock);
- POWTaskHandle = osThreadCreate(osThread(POWTask), NULL);
+ preRToSInit();
+ setTipX10Watts(0); // force tip off
+ resetWatchdog();
+ OLED::setFont(0); // default to bigger font
+ // Testing for which accelerometer is mounted
+ settingsWereReset = restoreSettings(); // load the settings from flash
+ resetWatchdog();
+ /* Create the thread(s) */
+ /* definition and creation of POWTask - Power management for QC */
+ osThreadStaticDef(POWTask, startPOWTask, osPriorityAboveNormal, 0, POWTaskStackSize, POWTaskBuffer, &POWTaskControlBlock);
+ POWTaskHandle = osThreadCreate(osThread(POWTask), NULL);
- /* definition and creation of GUITask - The OLED control & update*/
- osThreadStaticDef(GUITask, startGUITask, osPriorityBelowNormal, 0, GUITaskStackSize, GUITaskBuffer, &GUITaskControlBlock);
- GUITaskHandle = osThreadCreate(osThread(GUITask), NULL);
+ /* definition and creation of GUITask - The OLED control & update*/
+ osThreadStaticDef(GUITask, startGUITask, osPriorityBelowNormal, 0, GUITaskStackSize, GUITaskBuffer, &GUITaskControlBlock);
+ GUITaskHandle = osThreadCreate(osThread(GUITask), NULL);
- /* definition and creation of PIDTask - Heating control*/
- osThreadStaticDef(PIDTask, startPIDTask, osPriorityRealtime, 0, PIDTaskStackSize, PIDTaskBuffer, &PIDTaskControlBlock);
- PIDTaskHandle = osThreadCreate(osThread(PIDTask), NULL);
+ /* definition and creation of PIDTask - Heating control*/
+ osThreadStaticDef(PIDTask, startPIDTask, osPriorityRealtime, 0, PIDTaskStackSize, PIDTaskBuffer, &PIDTaskControlBlock);
+ PIDTaskHandle = osThreadCreate(osThread(PIDTask), NULL);
- /* definition and creation of MOVTask - Accelerometer management */
- osThreadStaticDef(MOVTask, startMOVTask, osPriorityNormal, 0, MOVTaskStackSize, MOVTaskBuffer, &MOVTaskControlBlock);
- MOVTaskHandle = osThreadCreate(osThread(MOVTask), NULL);
- resetWatchdog();
+ /* definition and creation of MOVTask - Accelerometer management */
+ osThreadStaticDef(MOVTask, startMOVTask, osPriorityNormal, 0, MOVTaskStackSize, MOVTaskBuffer, &MOVTaskControlBlock);
+ MOVTaskHandle = osThreadCreate(osThread(MOVTask), NULL);
+ resetWatchdog();
- /* Start scheduler */
- osKernelStart();
- /* We should never get here as control is now taken by the scheduler */
- for (;;) {
- }
+ /* Start scheduler */
+ osKernelStart();
+ /* We should never get here as control is now taken by the scheduler */
+ for (;;) {}
}
diff --git a/source/Core/Src/power.cpp b/source/Core/Src/power.cpp
index 5620f50c..d0533497 100644
--- a/source/Core/Src/power.cpp
+++ b/source/Core/Src/power.cpp
@@ -5,71 +5,71 @@
* Authors: Ben V. Brown, David Hilton <- Mostly David
*/
-#include <power.hpp>
-#include <Settings.h>
#include <BSP.h>
+#include <Settings.h>
+#include <power.hpp>
static int32_t PWMToX10Watts(uint8_t pwm, uint8_t sample);
-expMovingAverage<uint32_t, wattHistoryFilter> x10WattHistory = { 0 };
+expMovingAverage<uint32_t, wattHistoryFilter> x10WattHistory = {0};
int32_t tempToX10Watts(int32_t rawTemp) {
- // mass is in milliJ/*C, rawC is raw per degree C
- // returns milliWatts needed to raise/lower a mass by rawTemp
- // degrees in one cycle.
- int32_t milliJoules = tipMass * rawTemp;
- return milliJoules;
+ // mass is in milliJ/*C, rawC is raw per degree C
+ // returns milliWatts needed to raise/lower a mass by rawTemp
+ // degrees in one cycle.
+ int32_t milliJoules = tipMass * rawTemp;
+ return milliJoules;
}
void setTipX10Watts(int32_t mw) {
- int32_t output = X10WattsToPWM(mw, 1);
- setTipPWM(output);
- uint32_t actualMilliWatts = PWMToX10Watts(output, 0);
+ int32_t output = X10WattsToPWM(mw, 1);
+ setTipPWM(output);
+ uint32_t actualMilliWatts = PWMToX10Watts(output, 0);
- x10WattHistory.update(actualMilliWatts);
+ x10WattHistory.update(actualMilliWatts);
}
static uint32_t availableW10(uint8_t sample) {
- //P = V^2 / R, v*v = v^2 * 100
- // R = R*10
- // P therefore is in V^2*100/R*10 = W*10.
- uint32_t v = getInputVoltageX10(systemSettings.voltageDiv, sample); // 100 = 10v
- uint32_t availableWattsX10 = (v * v) / tipResistance;
- //However, 100% duty cycle is not possible as there is a dead time while the ADC takes a reading
- //Therefore need to scale available milliwats by this
+ // P = V^2 / R, v*v = v^2 * 100
+ // R = R*10
+ // P therefore is in V^2*100/R*10 = W*10.
+ uint32_t v = getInputVoltageX10(systemSettings.voltageDiv, sample); // 100 = 10v
+ uint32_t availableWattsX10 = (v * v) / tipResistance;
+ // However, 100% duty cycle is not possible as there is a dead time while the ADC takes a reading
+ // Therefore need to scale available milliwats by this
- // avMw=(AvMw*powerPWM)/totalPWM.
- availableWattsX10 = availableWattsX10 * powerPWM;
- availableWattsX10 /= totalPWM;
+ // avMw=(AvMw*powerPWM)/totalPWM.
+ availableWattsX10 = availableWattsX10 * powerPWM;
+ availableWattsX10 /= totalPWM;
- //availableMilliWattsX10 is now an accurate representation
- return availableWattsX10;
+ // availableMilliWattsX10 is now an accurate representation
+ return availableWattsX10;
}
uint8_t X10WattsToPWM(int32_t milliWatts, uint8_t sample) {
- // Scale input milliWatts to the pwm range available
- if (milliWatts < 1) {
- //keep the battery voltage updating the filter
- getInputVoltageX10(systemSettings.voltageDiv, sample);
- return 0;
- }
+ // Scale input milliWatts to the pwm range available
+ if (milliWatts < 1) {
+ // keep the battery voltage updating the filter
+ getInputVoltageX10(systemSettings.voltageDiv, sample);
+ return 0;
+ }
- //Calculate desired milliwatts as a percentage of availableW10
- uint32_t pwm;
- do {
- pwm = (powerPWM * milliWatts) / availableW10(sample);
- if (pwm > powerPWM) {
- // constrain to max PWM counter, shouldn't be possible,
- // but small cost for safety to avoid wraps
- pwm = powerPWM;
- }
- } while (tryBetterPWM(pwm));
+ // Calculate desired milliwatts as a percentage of availableW10
+ uint32_t pwm;
+ do {
+ pwm = (powerPWM * milliWatts) / availableW10(sample);
+ if (pwm > powerPWM) {
+ // constrain to max PWM counter, shouldn't be possible,
+ // but small cost for safety to avoid wraps
+ pwm = powerPWM;
+ }
+ } while (tryBetterPWM(pwm));
- return pwm;
+ return pwm;
}
static int32_t PWMToX10Watts(uint8_t pwm, uint8_t sample) {
- uint32_t maxMW = availableW10(sample); //Get the milliwatts for the max pwm period
- //Then convert pwm into percentage of powerPWM to get the percentage of the max mw
- return (((uint32_t) pwm) * maxMW) / powerPWM;
+ uint32_t maxMW = availableW10(sample); // Get the milliwatts for the max pwm period
+ // Then convert pwm into percentage of powerPWM to get the percentage of the max mw
+ return (((uint32_t)pwm) * maxMW) / powerPWM;
}
diff --git a/source/Core/Src/syscalls.c b/source/Core/Src/syscalls.c
index 94e38850..b1cefd18 100644
--- a/source/Core/Src/syscalls.c
+++ b/source/Core/Src/syscalls.c
@@ -1,19 +1,14 @@
/* Includes */
-#include <sys/stat.h>
-#include <stdlib.h>
#include <errno.h>
-#include <stdio.h>
#include <signal.h>
-#include <time.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
#include <sys/time.h>
#include <sys/times.h>
-
+#include <time.h>
/* Functions */
-void initialise_monitor_handles() {
-}
-
-int _getpid(void) {
- return 1;
-}
+void initialise_monitor_handles() {}
+int _getpid(void) { return 1; }
diff --git a/source/Core/Threads/GUIThread.cpp b/source/Core/Threads/GUIThread.cpp
index a5fc94e2..c59513d5 100644
--- a/source/Core/Threads/GUIThread.cpp
+++ b/source/Core/Threads/GUIThread.cpp
@@ -27,752 +27,747 @@ extern "C" {
#include "policy_engine.h"
#endif
// File local variables
-extern uint32_t currentTempTargetDegC;
+extern uint32_t currentTempTargetDegC;
extern TickType_t lastMovementTime;
extern osThreadId GUITaskHandle;
extern osThreadId MOVTaskHandle;
extern osThreadId PIDTaskHandle;
-static bool shouldBeSleeping(bool inAutoStart = false);
-static bool shouldShutdown();
-void showWarnings();
+static bool shouldBeSleeping(bool inAutoStart = false);
+static bool shouldShutdown();
+void showWarnings();
#define MOVEMENT_INACTIVITY_TIME (60 * configTICK_RATE_HZ)
-#define BUTTON_INACTIVITY_TIME (60 * configTICK_RATE_HZ)
+#define BUTTON_INACTIVITY_TIME (60 * configTICK_RATE_HZ)
static TickType_t lastHallEffectSleepStart = 0;
-static uint16_t min(uint16_t a, uint16_t b) {
- if (a > b)
- return b;
- else
- return a;
+static uint16_t min(uint16_t a, uint16_t b) {
+ if (a > b)
+ return b;
+ else
+ return a;
}
void warnUser(const char *warning, const int font, const int timeout) {
- OLED::setFont(font);
- OLED::clearScreen();
- OLED::setCursor(0, 0);
- OLED::print(warning);
- OLED::refresh();
- waitForButtonPressOrTimeout(timeout);
+ OLED::setFont(font);
+ OLED::clearScreen();
+ OLED::setCursor(0, 0);
+ OLED::print(warning);
+ OLED::refresh();
+ waitForButtonPressOrTimeout(timeout);
}
void printVoltage() {
- uint32_t volt = getInputVoltageX10(systemSettings.voltageDiv, 0);
- OLED::printNumber(volt / 10, 2);
- OLED::print(SymbolDot);
- OLED::printNumber(volt % 10, 1);
+ uint32_t volt = getInputVoltageX10(systemSettings.voltageDiv, 0);
+ OLED::printNumber(volt / 10, 2);
+ OLED::print(SymbolDot);
+ OLED::printNumber(volt % 10, 1);
}
void GUIDelay() {
- // Called in all UI looping tasks,
- // This limits the re-draw rate to the LCD and also lets the DMA run
- // As the gui task can very easily fill this bus with transactions, which will
- // prevent the movement detection from running
- osDelay(50);
+ // Called in all UI looping tasks,
+ // This limits the re-draw rate to the LCD and also lets the DMA run
+ // As the gui task can very easily fill this bus with transactions, which will
+ // prevent the movement detection from running
+ osDelay(50);
}
void gui_drawTipTemp(bool symbol) {
- // Draw tip temp handling unit conversion & tolerance near setpoint
- uint32_t Temp = 0;
+ // Draw tip temp handling unit conversion & tolerance near setpoint
+ uint32_t Temp = 0;
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF) {
- Temp = TipThermoModel::getTipInF();
- } else
+ if (systemSettings.temperatureInF) {
+ Temp = TipThermoModel::getTipInF();
+ } else
#endif
- {
- Temp = TipThermoModel::getTipInC();
- }
-
- OLED::printNumber(Temp, 3); // Draw the tip temp out
- if (symbol) {
- if (OLED::getFont() == 0) {
- // Big font, can draw nice symbols
+ {
+ Temp = TipThermoModel::getTipInC();
+ }
+
+ OLED::printNumber(Temp, 3); // Draw the tip temp out
+ if (symbol) {
+ if (OLED::getFont() == 0) {
+ // Big font, can draw nice symbols
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- OLED::drawSymbol(0);
- else
+ if (systemSettings.temperatureInF)
+ OLED::drawSymbol(0);
+ else
#endif
- OLED::drawSymbol(1);
- } else {
- // Otherwise fall back to chars
+ OLED::drawSymbol(1);
+ } else {
+ // Otherwise fall back to chars
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- OLED::print(SymbolDegF);
- else
+ if (systemSettings.temperatureInF)
+ OLED::print(SymbolDegF);
+ else
#endif
- OLED::print(SymbolDegC);
- }
- }
+ OLED::print(SymbolDegC);
+ }
+ }
}
#ifdef POW_DC
// returns true if undervoltage has occured
static bool checkVoltageForExit() {
- if (!getIsPoweredByDCIN()) {
- return false;
- }
- uint16_t v = getInputVoltageX10(systemSettings.voltageDiv, 0);
-
- // Dont check for first 2 seconds while the ADC stabilizes and the DMA fills
- // the buffer
- if (xTaskGetTickCount() > (TICKS_SECOND * 2)) {
- if ((v < lookupVoltageLevel())) {
- currentTempTargetDegC = 0;
- OLED::clearScreen();
- OLED::setCursor(0, 0);
- if (systemSettings.detailedSoldering) {
- OLED::setFont(1);
- OLED::print(UndervoltageString);
- OLED::setCursor(0, 8);
- OLED::print(InputVoltageString);
- printVoltage();
- OLED::print(SymbolVolts);
- } else {
- OLED::setFont(0);
- OLED::print(UVLOWarningString);
- }
-
- OLED::refresh();
- GUIDelay();
- waitForButtonPress();
- return true;
- }
- }
- return false;
+ if (!getIsPoweredByDCIN()) {
+ return false;
+ }
+ uint16_t v = getInputVoltageX10(systemSettings.voltageDiv, 0);
+
+ // Dont check for first 2 seconds while the ADC stabilizes and the DMA fills
+ // the buffer
+ if (xTaskGetTickCount() > (TICKS_SECOND * 2)) {
+ if ((v < lookupVoltageLevel())) {
+ currentTempTargetDegC = 0;
+ OLED::clearScreen();
+ OLED::setCursor(0, 0);
+ if (systemSettings.detailedSoldering) {
+ OLED::setFont(1);
+ OLED::print(UndervoltageString);
+ OLED::setCursor(0, 8);
+ OLED::print(InputVoltageString);
+ printVoltage();
+ OLED::print(SymbolVolts);
+ } else {
+ OLED::setFont(0);
+ OLED::print(UVLOWarningString);
+ }
+
+ OLED::refresh();
+ GUIDelay();
+ waitForButtonPress();
+ return true;
+ }
+ }
+ return false;
}
#endif
static void gui_drawBatteryIcon() {
#if defined(POW_PD) || defined(POW_QC)
- if (!getIsPoweredByDCIN()) {
- // On TS80 we replace this symbol with the voltage we are operating on
- // If <9V then show single digit, if not show dual small ones vertically stacked
- uint8_t V = getInputVoltageX10(systemSettings.voltageDiv, 0);
- if (V % 10 >= 5)
- V = V / 10 + 1; // round up
- else
- V = V / 10;
- if (V >= 10) {
- int16_t xPos = OLED::getCursorX();
- OLED::setFont(1);
- OLED::printNumber(V / 10, 1);
- OLED::setCursor(xPos, 8);
- OLED::printNumber(V % 10, 1);
- OLED::setFont(0);
- OLED::setCursor(xPos + 12, 0); // need to reset this as if we drew a wide char
- } else {
- OLED::printNumber(V, 1);
- }
- return;
- }
+ if (!getIsPoweredByDCIN()) {
+ // On TS80 we replace this symbol with the voltage we are operating on
+ // If <9V then show single digit, if not show dual small ones vertically stacked
+ uint8_t V = getInputVoltageX10(systemSettings.voltageDiv, 0);
+ if (V % 10 >= 5)
+ V = V / 10 + 1; // round up
+ else
+ V = V / 10;
+ if (V >= 10) {
+ int16_t xPos = OLED::getCursorX();
+ OLED::setFont(1);
+ OLED::printNumber(V / 10, 1);
+ OLED::setCursor(xPos, 8);
+ OLED::printNumber(V % 10, 1);
+ OLED::setFont(0);
+ OLED::setCursor(xPos + 12, 0); // need to reset this as if we drew a wide char
+ } else {
+ OLED::printNumber(V, 1);
+ }
+ return;
+ }
#endif
#ifdef POW_DC
- if (systemSettings.minDCVoltageCells) {
- // User is on a lithium battery
- // we need to calculate which of the 10 levels they are on
- uint8_t cellCount = systemSettings.minDCVoltageCells + 2;
- uint32_t cellV = getInputVoltageX10(systemSettings.voltageDiv, 0) / cellCount;
- // Should give us approx cell voltage X10
- // Range is 42 -> 33 = 9 steps therefore we will use battery 0-9
- if (cellV < 33)
- cellV = 33;
- cellV -= 33; // Should leave us a number of 0-9
- if (cellV > 9)
- cellV = 9;
- OLED::drawBattery(cellV + 1);
- } else {
- OLED::drawSymbol(15); // Draw the DC Logo
- }
+ if (systemSettings.minDCVoltageCells) {
+ // User is on a lithium battery
+ // we need to calculate which of the 10 levels they are on
+ uint8_t cellCount = systemSettings.minDCVoltageCells + 2;
+ uint32_t cellV = getInputVoltageX10(systemSettings.voltageDiv, 0) / cellCount;
+ // Should give us approx cell voltage X10
+ // Range is 42 -> 33 = 9 steps therefore we will use battery 0-9
+ if (cellV < 33)
+ cellV = 33;
+ cellV -= 33; // Should leave us a number of 0-9
+ if (cellV > 9)
+ cellV = 9;
+ OLED::drawBattery(cellV + 1);
+ } else {
+ OLED::drawSymbol(15); // Draw the DC Logo
+ }
#endif
}
static void gui_solderingTempAdjust() {
- uint32_t lastChange = xTaskGetTickCount();
- currentTempTargetDegC = 0;
- uint32_t autoRepeatTimer = 0;
- uint8_t autoRepeatAcceleration = 0;
- for (;;) {
- OLED::setCursor(0, 0);
- OLED::clearScreen();
- OLED::setFont(0);
- ButtonState buttons = getButtonState();
- if (buttons)
- lastChange = xTaskGetTickCount();
- switch (buttons) {
- case BUTTON_NONE:
- // stay
- break;
- case BUTTON_BOTH:
- // exit
- return;
- break;
- case BUTTON_B_LONG:
- if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration >
- PRESS_ACCEL_INTERVAL_MAX) {
- if (systemSettings.ReverseButtonTempChangeEnabled) {
- systemSettings.SolderingTemp += systemSettings.TempChangeLongStep;
- } else
- systemSettings.SolderingTemp -= systemSettings.TempChangeLongStep;
-
- autoRepeatTimer = xTaskGetTickCount();
- autoRepeatAcceleration += PRESS_ACCEL_STEP;
- }
- break;
- case BUTTON_B_SHORT:
- if (systemSettings.ReverseButtonTempChangeEnabled) {
- systemSettings.SolderingTemp += systemSettings.TempChangeShortStep;
- } else
- systemSettings.SolderingTemp -= systemSettings.TempChangeShortStep;
- break;
- case BUTTON_F_LONG:
- if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration >
- PRESS_ACCEL_INTERVAL_MAX) {
- if (systemSettings.ReverseButtonTempChangeEnabled) {
- systemSettings.SolderingTemp -= systemSettings.TempChangeLongStep;
- } else
- systemSettings.SolderingTemp += systemSettings.TempChangeLongStep;
- autoRepeatTimer = xTaskGetTickCount();
- autoRepeatAcceleration += PRESS_ACCEL_STEP;
- }
- break;
- case BUTTON_F_SHORT:
- if (systemSettings.ReverseButtonTempChangeEnabled) {
- systemSettings.SolderingTemp -= systemSettings.TempChangeShortStep; // add 10
- } else
- systemSettings.SolderingTemp += systemSettings.TempChangeShortStep; // add 10
- break;
- default:
- break;
- }
- if ((PRESS_ACCEL_INTERVAL_MAX - autoRepeatAcceleration) <
- PRESS_ACCEL_INTERVAL_MIN) {
- autoRepeatAcceleration =
- PRESS_ACCEL_INTERVAL_MAX - PRESS_ACCEL_INTERVAL_MIN;
- }
- // constrain between 10-450 C
+ uint32_t lastChange = xTaskGetTickCount();
+ currentTempTargetDegC = 0;
+ uint32_t autoRepeatTimer = 0;
+ uint8_t autoRepeatAcceleration = 0;
+ for (;;) {
+ OLED::setCursor(0, 0);
+ OLED::clearScreen();
+ OLED::setFont(0);
+ ButtonState buttons = getButtonState();
+ if (buttons)
+ lastChange = xTaskGetTickCount();
+ switch (buttons) {
+ case BUTTON_NONE:
+ // stay
+ break;
+ case BUTTON_BOTH:
+ // exit
+ return;
+ break;
+ case BUTTON_B_LONG:
+ if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration > PRESS_ACCEL_INTERVAL_MAX) {
+ if (systemSettings.ReverseButtonTempChangeEnabled) {
+ systemSettings.SolderingTemp += systemSettings.TempChangeLongStep;
+ } else
+ systemSettings.SolderingTemp -= systemSettings.TempChangeLongStep;
+
+ autoRepeatTimer = xTaskGetTickCount();
+ autoRepeatAcceleration += PRESS_ACCEL_STEP;
+ }
+ break;
+ case BUTTON_B_SHORT:
+ if (systemSettings.ReverseButtonTempChangeEnabled) {
+ systemSettings.SolderingTemp += systemSettings.TempChangeShortStep;
+ } else
+ systemSettings.SolderingTemp -= systemSettings.TempChangeShortStep;
+ break;
+ case BUTTON_F_LONG:
+ if (xTaskGetTickCount() - autoRepeatTimer + autoRepeatAcceleration > PRESS_ACCEL_INTERVAL_MAX) {
+ if (systemSettings.ReverseButtonTempChangeEnabled) {
+ systemSettings.SolderingTemp -= systemSettings.TempChangeLongStep;
+ } else
+ systemSettings.SolderingTemp += systemSettings.TempChangeLongStep;
+ autoRepeatTimer = xTaskGetTickCount();
+ autoRepeatAcceleration += PRESS_ACCEL_STEP;
+ }
+ break;
+ case BUTTON_F_SHORT:
+ if (systemSettings.ReverseButtonTempChangeEnabled) {
+ systemSettings.SolderingTemp -= systemSettings.TempChangeShortStep; // add 10
+ } else
+ systemSettings.SolderingTemp += systemSettings.TempChangeShortStep; // add 10
+ break;
+ default:
+ break;
+ }
+ if ((PRESS_ACCEL_INTERVAL_MAX - autoRepeatAcceleration) < PRESS_ACCEL_INTERVAL_MIN) {
+ autoRepeatAcceleration = PRESS_ACCEL_INTERVAL_MAX - PRESS_ACCEL_INTERVAL_MIN;
+ }
+ // constrain between 10-450 C
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF) {
- if (systemSettings.SolderingTemp > 850)
- systemSettings.SolderingTemp = 850;
- if (systemSettings.SolderingTemp < 60)
- systemSettings.SolderingTemp = 60;
- } else
+ if (systemSettings.temperatureInF) {
+ if (systemSettings.SolderingTemp > 850)
+ systemSettings.SolderingTemp = 850;
+ if (systemSettings.SolderingTemp < 60)
+ systemSettings.SolderingTemp = 60;
+ } else
#endif
- {
- if (systemSettings.SolderingTemp > 450)
- systemSettings.SolderingTemp = 450;
- if (systemSettings.SolderingTemp < 10)
- systemSettings.SolderingTemp = 10;
- }
+ {
+ if (systemSettings.SolderingTemp > 450)
+ systemSettings.SolderingTemp = 450;
+ if (systemSettings.SolderingTemp < 10)
+ systemSettings.SolderingTemp = 10;
+ }
- if (xTaskGetTickCount() - lastChange > 2000)
- return; // exit if user just doesn't press anything for a bit
+ if (xTaskGetTickCount() - lastChange > 2000)
+ return; // exit if user just doesn't press anything for a bit
#ifdef OLED_FLIP
- if (!OLED::getRotation()) {
+ if (!OLED::getRotation()) {
#else
- if (OLED::getRotation()) {
+ if (OLED::getRotation()) {
#endif
- OLED::print(systemSettings.ReverseButtonTempChangeEnabled ? SymbolPlus : SymbolMinus);
- } else {
- OLED::print(systemSettings.ReverseButtonTempChangeEnabled ? SymbolMinus : SymbolPlus);
- }
+ OLED::print(systemSettings.ReverseButtonTempChangeEnabled ? SymbolPlus : SymbolMinus);
+ } else {
+ OLED::print(systemSettings.ReverseButtonTempChangeEnabled ? SymbolMinus : SymbolPlus);
+ }
- OLED::print(SymbolSpace);
- OLED::printNumber(systemSettings.SolderingTemp, 3);
+ OLED::print(SymbolSpace);
+ OLED::printNumber(systemSettings.SolderingTemp, 3);
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- OLED::drawSymbol(0);
- else
+ if (systemSettings.temperatureInF)
+ OLED::drawSymbol(0);
+ else
#endif
- {
- OLED::drawSymbol(1);
- }
- OLED::print(SymbolSpace);
+ {
+ OLED::drawSymbol(1);
+ }
+ OLED::print(SymbolSpace);
#ifdef OLED_FLIP
- if (!OLED::getRotation()) {
+ if (!OLED::getRotation()) {
#else
- if (OLED::getRotation()) {
+ if (OLED::getRotation()) {
#endif
- OLED::print(systemSettings.ReverseButtonTempChangeEnabled ? SymbolMinus : SymbolPlus);
- } else {
- OLED::print(systemSettings.ReverseButtonTempChangeEnabled ? SymbolPlus : SymbolMinus);
- }
- OLED::refresh();
- GUIDelay();
- }
+ OLED::print(systemSettings.ReverseButtonTempChangeEnabled ? SymbolMinus : SymbolPlus);
+ } else {
+ OLED::print(systemSettings.ReverseButtonTempChangeEnabled ? SymbolPlus : SymbolMinus);
+ }
+ OLED::refresh();
+ GUIDelay();
+ }
}
static bool shouldShutdown() {
- if (systemSettings.ShutdownTime) { // only allow shutdown exit if time > 0
- if (lastMovementTime) {
- if (((TickType_t) (xTaskGetTickCount() - lastMovementTime)) > (TickType_t) (systemSettings.ShutdownTime * TICKS_MIN)) {
- return true;
- }
- }
- if (lastHallEffectSleepStart) {
- if (((TickType_t) (xTaskGetTickCount() - lastHallEffectSleepStart)) > (TickType_t) (systemSettings.ShutdownTime * TICKS_MIN)) {
- return true;
- }
- }
- }
- return false;
+ if (systemSettings.ShutdownTime) { // only allow shutdown exit if time > 0
+ if (lastMovementTime) {
+ if (((TickType_t)(xTaskGetTickCount() - lastMovementTime)) > (TickType_t)(systemSettings.ShutdownTime * TICKS_MIN)) {
+ return true;
+ }
+ }
+ if (lastHallEffectSleepStart) {
+ if (((TickType_t)(xTaskGetTickCount() - lastHallEffectSleepStart)) > (TickType_t)(systemSettings.ShutdownTime * TICKS_MIN)) {
+ return true;
+ }
+ }
+ }
+ return false;
}
static int gui_SolderingSleepingMode(bool stayOff, bool autoStarted) {
- // Drop to sleep temperature and display until movement or button press
+ // Drop to sleep temperature and display until movement or button press
- for (;;) {
- // user moved or pressed a button, go back to soldering
- //If in the first two seconds we disable this to let accelerometer warm up
+ for (;;) {
+ // user moved or pressed a button, go back to soldering
+ // If in the first two seconds we disable this to let accelerometer warm up
#ifdef POW_DC
- if (checkVoltageForExit())
- return 1; // return non-zero on error
+ if (checkVoltageForExit())
+ return 1; // return non-zero on error
#endif
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF) {
- currentTempTargetDegC = stayOff ? 0 : TipThermoModel::convertFtoC(min(systemSettings.SleepTemp, systemSettings.SolderingTemp));
- } else
+ if (systemSettings.temperatureInF) {
+ currentTempTargetDegC = stayOff ? 0 : TipThermoModel::convertFtoC(min(systemSettings.SleepTemp, systemSettings.SolderingTemp));
+ } else
#endif
- {
- currentTempTargetDegC = stayOff ? 0 : min(systemSettings.SleepTemp, systemSettings.SolderingTemp);
- }
- // draw the lcd
- uint16_t tipTemp;
+ {
+ currentTempTargetDegC = stayOff ? 0 : min(systemSettings.SleepTemp, systemSettings.SolderingTemp);
+ }
+ // draw the lcd
+ uint16_t tipTemp;
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- tipTemp = TipThermoModel::getTipInF();
- else
+ if (systemSettings.temperatureInF)
+ tipTemp = TipThermoModel::getTipInF();
+ else
#endif
- {
- tipTemp = TipThermoModel::getTipInC();
- }
-
- OLED::clearScreen();
- OLED::setCursor(0, 0);
- if (systemSettings.detailedSoldering) {
- OLED::setFont(1);
- OLED::print(SleepingAdvancedString);
- OLED::setCursor(0, 8);
- OLED::print(SleepingTipAdvancedString);
- OLED::printNumber(tipTemp, 3);
+ {
+ tipTemp = TipThermoModel::getTipInC();
+ }
+
+ OLED::clearScreen();
+ OLED::setCursor(0, 0);
+ if (systemSettings.detailedSoldering) {
+ OLED::setFont(1);
+ OLED::print(SleepingAdvancedString);
+ OLED::setCursor(0, 8);
+ OLED::print(SleepingTipAdvancedString);
+ OLED::printNumber(tipTemp, 3);
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- OLED::print(SymbolDegF);
- else
+ if (systemSettings.temperatureInF)
+ OLED::print(SymbolDegF);
+ else
#endif
- {
- OLED::print(SymbolDegC);
- }
-
- OLED::print(SymbolSpace);
- printVoltage();
- OLED::print(SymbolVolts);
- } else {
- OLED::setFont(0);
- OLED::print(SleepingSimpleString);
- OLED::printNumber(tipTemp, 3);
+ {
+ OLED::print(SymbolDegC);
+ }
+
+ OLED::print(SymbolSpace);
+ printVoltage();
+ OLED::print(SymbolVolts);
+ } else {
+ OLED::setFont(0);
+ OLED::print(SleepingSimpleString);
+ OLED::printNumber(tipTemp, 3);
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- OLED::drawSymbol(0);
- else
+ if (systemSettings.temperatureInF)
+ OLED::drawSymbol(0);
+ else
#endif
- {
- OLED::drawSymbol(1);
- }
- }
-
- OLED::refresh();
- GUIDelay();
- if (!shouldBeSleeping(autoStarted)) {
- return 0;
- }
- if (shouldShutdown()) {
- // shutdown
- currentTempTargetDegC = 0;
- return 1; // we want to exit soldering mode
- }
- }
- return 0;
+ {
+ OLED::drawSymbol(1);
+ }
+ }
+
+ OLED::refresh();
+ GUIDelay();
+ if (!shouldBeSleeping(autoStarted)) {
+ return 0;
+ }
+ if (shouldShutdown()) {
+ // shutdown
+ currentTempTargetDegC = 0;
+ return 1; // we want to exit soldering mode
+ }
+ }
+ return 0;
}
static void display_countdown(int sleepThres) {
- /*
- * Print seconds or minutes (if > 99 seconds) until sleep
- * mode is triggered.
- */
- int lastEventTime = lastButtonTime < lastMovementTime ? lastMovementTime : lastButtonTime;
- TickType_t downCount = sleepThres - xTaskGetTickCount() + lastEventTime;
- if (downCount > (99 * TICKS_SECOND)) {
- OLED::printNumber(downCount / 60000 + 1, 2);
- OLED::print(SymbolMinutes);
- } else {
- OLED::printNumber(downCount / 1000 + 1, 2);
- OLED::print(SymbolSeconds);
- }
+ /*
+ * Print seconds or minutes (if > 99 seconds) until sleep
+ * mode is triggered.
+ */
+ int lastEventTime = lastButtonTime < lastMovementTime ? lastMovementTime : lastButtonTime;
+ TickType_t downCount = sleepThres - xTaskGetTickCount() + lastEventTime;
+ if (downCount > (99 * TICKS_SECOND)) {
+ OLED::printNumber(downCount / 60000 + 1, 2);
+ OLED::print(SymbolMinutes);
+ } else {
+ OLED::printNumber(downCount / 1000 + 1, 2);
+ OLED::print(SymbolSeconds);
+ }
}
static uint32_t getSleepTimeout() {
- if (systemSettings.sensitivity && systemSettings.SleepTime) {
-
- uint32_t sleepThres = 0;
- if (systemSettings.SleepTime < 6)
- sleepThres = systemSettings.SleepTime * 10 * 1000;
- else
- sleepThres = (systemSettings.SleepTime - 5) * 60 * 1000;
- return sleepThres;
- }
- return 0;
+ if (systemSettings.sensitivity && systemSettings.SleepTime) {
+
+ uint32_t sleepThres = 0;
+ if (systemSettings.SleepTime < 6)
+ sleepThres = systemSettings.SleepTime * 10 * 1000;
+ else
+ sleepThres = (systemSettings.SleepTime - 5) * 60 * 1000;
+ return sleepThres;
+ }
+ return 0;
}
static bool shouldBeSleeping(bool inAutoStart) {
-// Return true if the iron should be in sleep mode
- if (systemSettings.sensitivity && systemSettings.SleepTime) {
- if (inAutoStart) {
- //In auto start we are asleep until movement
- if (lastMovementTime == 0 && lastButtonTime == 0) {
- return true;
- }
- }
- if (lastMovementTime > 0 || lastButtonTime > 0) {
- if ((xTaskGetTickCount() - lastMovementTime) > getSleepTimeout() && (xTaskGetTickCount() - lastButtonTime) > getSleepTimeout()) {
- return true;
- }
- }
- }
+ // Return true if the iron should be in sleep mode
+ if (systemSettings.sensitivity && systemSettings.SleepTime) {
+ if (inAutoStart) {
+ // In auto start we are asleep until movement
+ if (lastMovementTime == 0 && lastButtonTime == 0) {
+ return true;
+ }
+ }
+ if (lastMovementTime > 0 || lastButtonTime > 0) {
+ if ((xTaskGetTickCount() - lastMovementTime) > getSleepTimeout() && (xTaskGetTickCount() - lastButtonTime) > getSleepTimeout()) {
+ return true;
+ }
+ }
+ }
#ifdef HALL_SENSOR
- // If the hall effect sensor is enabled in the build, check if its over
- // threshold, and if so then we force sleep
- if (lookupHallEffectThreshold()) {
- int16_t hallEffectStrength = getRawHallEffect();
- if (hallEffectStrength < 0)
- hallEffectStrength = -hallEffectStrength;
- // Have absolute value of measure of magnetic field strength
- if (hallEffectStrength > lookupHallEffectThreshold()) {
- if (lastHallEffectSleepStart == 0) {
- lastHallEffectSleepStart = xTaskGetTickCount();
- }
- if ((xTaskGetTickCount() - lastHallEffectSleepStart) > TICKS_SECOND) {
- return true;
- }
- } else {
- lastHallEffectSleepStart = 0;
- }
- }
+ // If the hall effect sensor is enabled in the build, check if its over
+ // threshold, and if so then we force sleep
+ if (lookupHallEffectThreshold()) {
+ int16_t hallEffectStrength = getRawHallEffect();
+ if (hallEffectStrength < 0)
+ hallEffectStrength = -hallEffectStrength;
+ // Have absolute value of measure of magnetic field strength
+ if (hallEffectStrength > lookupHallEffectThreshold()) {
+ if (lastHallEffectSleepStart == 0) {
+ lastHallEffectSleepStart = xTaskGetTickCount();
+ }
+ if ((xTaskGetTickCount() - lastHallEffectSleepStart) > TICKS_SECOND) {
+ return true;
+ }
+ } else {
+ lastHallEffectSleepStart = 0;
+ }
+ }
#endif
- return false;
+ return false;
}
static void gui_solderingMode(uint8_t jumpToSleep) {
- /*
- * * Soldering (gui_solderingMode)
- * -> Main loop where we draw temp, and animations
- * --> User presses buttons and they goto the temperature adjust screen
- * ---> Display the current setpoint temperature
- * ---> Use buttons to change forward and back on temperature
- * ---> Both buttons or timeout for exiting
- * --> Long hold front button to enter boost mode
- * ---> Just temporarily sets the system into the alternate temperature for
- * PID control
- * --> Long hold back button to exit
- * --> Double button to exit
- * --> Long hold double button to toggle key lock
- */
- bool boostModeOn = false;
- bool buttonsLocked = false;
-
- if (jumpToSleep) {
- if (gui_SolderingSleepingMode(jumpToSleep == 2, true) == 1) {
- lastButtonTime = xTaskGetTickCount();
- return; // If the function returns non-0 then exit
- }
- }
- for (;;) {
- ButtonState buttons = getButtonState();
- if (buttonsLocked && (systemSettings.lockingMode != 0)) { // If buttons locked
- switch (buttons) {
- case BUTTON_NONE:
- boostModeOn = false;
- break;
- case BUTTON_BOTH_LONG:
- // Unlock buttons
- buttonsLocked = false;
- warnUser(UnlockingKeysString, 0, TICKS_SECOND);
- break;
- case BUTTON_F_LONG:
- // if boost mode is enabled turn it on
- if (systemSettings.BoostTemp && (systemSettings.lockingMode == 1)) {
- boostModeOn = true;
- }
- break;
- // fall through
- case BUTTON_BOTH:
- case BUTTON_B_LONG:
- case BUTTON_F_SHORT:
- case BUTTON_B_SHORT:
- // Do nothing and display a lock warming
- warnUser(WarningKeysLockedString, 0, TICKS_SECOND / 2);
- break;
- default:
- break;
- }
- } else { // Button not locked
- switch (buttons) {
- case BUTTON_NONE:
- // stay
- boostModeOn = false;
- break;
- case BUTTON_BOTH:
- // exit
- return;
- break;
- case BUTTON_B_LONG:
- return; // exit on back long hold
- break;
- case BUTTON_F_LONG:
- // if boost mode is enabled turn it on
- if (systemSettings.BoostTemp)
- boostModeOn = true;
- break;
- case BUTTON_F_SHORT:
- case BUTTON_B_SHORT: {
- uint16_t oldTemp = systemSettings.SolderingTemp;
- gui_solderingTempAdjust(); // goto adjust temp mode
- if (oldTemp != systemSettings.SolderingTemp) {
- saveSettings(); // only save on change
- }
- }
- break;
- case BUTTON_BOTH_LONG:
- if (systemSettings.lockingMode != 0) {
- // Lock buttons
- buttonsLocked = true;
- warnUser(LockingKeysString, 0, TICKS_SECOND);
- }
- break;
- default:
- break;
- }
- }
- // else we update the screen information
- OLED::setCursor(0, 0);
- OLED::clearScreen();
- OLED::setFont(0);
- // Draw in the screen details
- if (systemSettings.detailedSoldering) {
- OLED::setFont(1);
- OLED::print(SolderingAdvancedPowerPrompt); // Power:
- OLED::printNumber(x10WattHistory.average() / 10, 2);
- OLED::print(SymbolDot);
- OLED::printNumber(x10WattHistory.average() % 10, 1);
- OLED::print(SymbolWatts);
-
- if (systemSettings.sensitivity && systemSettings.SleepTime) {
- OLED::print(SymbolSpace);
- display_countdown(getSleepTimeout());
- }
-
- OLED::setCursor(0, 8);
- OLED::print(SleepingTipAdvancedString);
- gui_drawTipTemp(true);
- OLED::print(SymbolSpace);
- printVoltage();
- OLED::print(SymbolVolts);
- } else {
- // We switch the layout direction depending on the orientation of the oled
- if (OLED::getRotation()) {
- // battery
- gui_drawBatteryIcon();
- OLED::print(SymbolSpace); // Space out gap between battery <-> temp
- gui_drawTipTemp(true); // Draw current tip temp
-
- // We draw boost arrow if boosting, or else gap temp <-> heat
- // indicator
- if (boostModeOn)
- OLED::drawSymbol(2);
- else
- OLED::print(SymbolSpace);
-
- // Draw heating/cooling symbols
- OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average()));
- } else {
- // Draw heating/cooling symbols
- OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average()));
- // We draw boost arrow if boosting, or else gap temp <-> heat
- // indicator
- if (boostModeOn)
- OLED::drawSymbol(2);
- else
- OLED::print(SymbolSpace);
- gui_drawTipTemp(true); // Draw current tip temp
-
- OLED::print(SymbolSpace); // Space out gap between battery <-> temp
-
- gui_drawBatteryIcon();
- }
- }
- OLED::refresh();
-
- // Update the setpoints for the temperature
- if (boostModeOn) {
+ /*
+ * * Soldering (gui_solderingMode)
+ * -> Main loop where we draw temp, and animations
+ * --> User presses buttons and they goto the temperature adjust screen
+ * ---> Display the current setpoint temperature
+ * ---> Use buttons to change forward and back on temperature
+ * ---> Both buttons or timeout for exiting
+ * --> Long hold front button to enter boost mode
+ * ---> Just temporarily sets the system into the alternate temperature for
+ * PID control
+ * --> Long hold back button to exit
+ * --> Double button to exit
+ * --> Long hold double button to toggle key lock
+ */
+ bool boostModeOn = false;
+ bool buttonsLocked = false;
+
+ if (jumpToSleep) {
+ if (gui_SolderingSleepingMode(jumpToSleep == 2, true) == 1) {
+ lastButtonTime = xTaskGetTickCount();
+ return; // If the function returns non-0 then exit
+ }
+ }
+ for (;;) {
+ ButtonState buttons = getButtonState();
+ if (buttonsLocked && (systemSettings.lockingMode != 0)) { // If buttons locked
+ switch (buttons) {
+ case BUTTON_NONE:
+ boostModeOn = false;
+ break;
+ case BUTTON_BOTH_LONG:
+ // Unlock buttons
+ buttonsLocked = false;
+ warnUser(UnlockingKeysString, 0, TICKS_SECOND);
+ break;
+ case BUTTON_F_LONG:
+ // if boost mode is enabled turn it on
+ if (systemSettings.BoostTemp && (systemSettings.lockingMode == 1)) {
+ boostModeOn = true;
+ }
+ break;
+ // fall through
+ case BUTTON_BOTH:
+ case BUTTON_B_LONG:
+ case BUTTON_F_SHORT:
+ case BUTTON_B_SHORT:
+ // Do nothing and display a lock warming
+ warnUser(WarningKeysLockedString, 0, TICKS_SECOND / 2);
+ break;
+ default:
+ break;
+ }
+ } else { // Button not locked
+ switch (buttons) {
+ case BUTTON_NONE:
+ // stay
+ boostModeOn = false;
+ break;
+ case BUTTON_BOTH:
+ // exit
+ return;
+ break;
+ case BUTTON_B_LONG:
+ return; // exit on back long hold
+ break;
+ case BUTTON_F_LONG:
+ // if boost mode is enabled turn it on
+ if (systemSettings.BoostTemp)
+ boostModeOn = true;
+ break;
+ case BUTTON_F_SHORT:
+ case BUTTON_B_SHORT: {
+ uint16_t oldTemp = systemSettings.SolderingTemp;
+ gui_solderingTempAdjust(); // goto adjust temp mode
+ if (oldTemp != systemSettings.SolderingTemp) {
+ saveSettings(); // only save on change
+ }
+ } break;
+ case BUTTON_BOTH_LONG:
+ if (systemSettings.lockingMode != 0) {
+ // Lock buttons
+ buttonsLocked = true;
+ warnUser(LockingKeysString, 0, TICKS_SECOND);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ // else we update the screen information
+ OLED::setCursor(0, 0);
+ OLED::clearScreen();
+ OLED::setFont(0);
+ // Draw in the screen details
+ if (systemSettings.detailedSoldering) {
+ OLED::setFont(1);
+ OLED::print(SolderingAdvancedPowerPrompt); // Power:
+ OLED::printNumber(x10WattHistory.average() / 10, 2);
+ OLED::print(SymbolDot);
+ OLED::printNumber(x10WattHistory.average() % 10, 1);
+ OLED::print(SymbolWatts);
+
+ if (systemSettings.sensitivity && systemSettings.SleepTime) {
+ OLED::print(SymbolSpace);
+ display_countdown(getSleepTimeout());
+ }
+
+ OLED::setCursor(0, 8);
+ OLED::print(SleepingTipAdvancedString);
+ gui_drawTipTemp(true);
+ OLED::print(SymbolSpace);
+ printVoltage();
+ OLED::print(SymbolVolts);
+ } else {
+ // We switch the layout direction depending on the orientation of the oled
+ if (OLED::getRotation()) {
+ // battery
+ gui_drawBatteryIcon();
+ OLED::print(SymbolSpace); // Space out gap between battery <-> temp
+ gui_drawTipTemp(true); // Draw current tip temp
+
+ // We draw boost arrow if boosting, or else gap temp <-> heat
+ // indicator
+ if (boostModeOn)
+ OLED::drawSymbol(2);
+ else
+ OLED::print(SymbolSpace);
+
+ // Draw heating/cooling symbols
+ OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average()));
+ } else {
+ // Draw heating/cooling symbols
+ OLED::drawHeatSymbol(X10WattsToPWM(x10WattHistory.average()));
+ // We draw boost arrow if boosting, or else gap temp <-> heat
+ // indicator
+ if (boostModeOn)
+ OLED::drawSymbol(2);
+ else
+ OLED::print(SymbolSpace);
+ gui_drawTipTemp(true); // Draw current tip temp
+
+ OLED::print(SymbolSpace); // Space out gap between battery <-> temp
+
+ gui_drawBatteryIcon();
+ }
+ }
+ OLED::refresh();
+
+ // Update the setpoints for the temperature
+ if (boostModeOn) {
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- currentTempTargetDegC = TipThermoModel::convertFtoC(systemSettings.BoostTemp);
- else
+ if (systemSettings.temperatureInF)
+ currentTempTargetDegC = TipThermoModel::convertFtoC(systemSettings.BoostTemp);
+ else
#endif
- {
- currentTempTargetDegC = (systemSettings.BoostTemp);
- }
- } else {
+ {
+ currentTempTargetDegC = (systemSettings.BoostTemp);
+ }
+ } else {
#ifdef ENABLED_FAHRENHEIT_SUPPORT
- if (systemSettings.temperatureInF)
- currentTempTargetDegC = TipThermoModel::convertFtoC(systemSettings.SolderingTemp);
- else
+ if (systemSettings.temperatureInF)
+ currentTempTargetDegC = TipThermoModel::convertFtoC(systemSettings.SolderingTemp);
+ else
#endif
- {
- currentTempTargetDegC = (systemSettings.SolderingTemp);
- }
- }
+ {
+ currentTempTargetDegC = (systemSettings.SolderingTemp);
+ }
+ }
#ifdef POW_DC
- // Undervoltage test
- if (checkVoltageForExit()) {
- lastButtonTime = xTaskGetTickCount();
- return;
- }
+ // Undervoltage test
+ if (checkVoltageForExit()) {
+ lastButtonTime = xTaskGetTickCount();
+ return;
+ }
#endif
- if (shouldBeSleeping()) {
- if (gui_SolderingSleepingMode(false, false)) {
- return; // If the function returns non-0 then exit
- }
- }
- // slow down ui update rate
- GUIDelay();
- }
+ if (shouldBeSleeping()) {
+ if (gui_SolderingSleepingMode(false, false)) {
+ return; // If the function returns non-0 then exit
+ }
+ }
+ // slow down ui update rate
+ GUIDelay();
+ }
}
void showDebugMenu(void) {
- uint8_t screen = 0;
- ButtonState b;
- OLED::setFont(1); // small font
- for (;;) {
- OLED::clearScreen(); // Ensure the buffer starts clean
- OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left)
- OLED::print(SymbolVersionNumber); // Print version number
- OLED::setCursor(0, 8); // second line
- OLED::print(DebugMenu[screen]);
- switch (screen) {
- case 0: // Just prints date
- break;
- case 1:
- // High water mark for GUI
- OLED::printNumber(uxTaskGetStackHighWaterMark(GUITaskHandle), 5);
- break;
- case 2:
- // High water mark for the Movement task
- OLED::printNumber(uxTaskGetStackHighWaterMark(MOVTaskHandle), 5);
- break;
- case 3:
- // High water mark for the PID task
- OLED::printNumber(uxTaskGetStackHighWaterMark(PIDTaskHandle), 5);
- break;
- case 4:
- // system up time stamp
- OLED::printNumber(xTaskGetTickCount() / 100, 5);
- break;
- case 5:
- // Movement time stamp
- OLED::printNumber(lastMovementTime / 100, 5);
- break;
- case 6:
- // Raw Tip
- {
- uint32_t temp = systemSettings.CalibrationOffset;
- systemSettings.CalibrationOffset = 0;
- OLED::printNumber(TipThermoModel::convertTipRawADCTouV(getTipRawTemp(0)), 6);
- systemSettings.CalibrationOffset = temp;
- }
- break;
- case 7:
- // Temp in C
- OLED::printNumber(TipThermoModel::getTipInC(), 5);
- break;
- case 8:
- // Handle Temp
- OLED::printNumber(getHandleTemperature(), 3);
- break;
- case 9:
- // Voltage input
- printVoltage();
- break;
- case 10:
- // Print PCB ID number
- OLED::printNumber(DetectedAccelerometerVersion, 2);
- break;
- case 11:
- // Power negotiation status
- if (getIsPoweredByDCIN()) {
- OLED::printNumber(0, 1);
- } else {
- //We are not powered via DC, so want to display the appropriate state for PD or QC
- bool poweredbyPD = false;
+ uint8_t screen = 0;
+ ButtonState b;
+ OLED::setFont(1); // small font
+ for (;;) {
+ OLED::clearScreen(); // Ensure the buffer starts clean
+ OLED::setCursor(0, 0); // Position the cursor at the 0,0 (top left)
+ OLED::print(SymbolVersionNumber); // Print version number
+ OLED::setCursor(0, 8); // second line
+ OLED::print(DebugMenu[screen]);
+ switch (screen) {
+ case 0: // Just prints date
+ break;
+ case 1:
+ // High water mark for GUI
+ OLED::printNumber(uxTaskGetStackHighWaterMark(GUITaskHandle), 5);
+ break;
+ case 2:
+ // High water mark for the Movement task
+ OLED::printNumber(uxTaskGetStackHighWaterMark(MOVTaskHandle), 5);
+ break;
+ case 3:
+ // High water mark for the PID task
+ OLED::printNumber(uxTaskGetStackHighWaterMark(PIDTaskHandle), 5);
+ break;
+ case 4:
+ // system up time stamp
+ OLED::printNumber(xTaskGetTickCount() / 100, 5);
+ break;
+ case 5:
+ // Movement time stamp
+ OLED::printNumber(lastMovementTime / 100, 5);
+ break;
+ case 6:
+ // Raw Tip
+ {
+ uint32_t temp = systemSettings.CalibrationOffset;
+ systemSettings.CalibrationOffset = 0;
+ OLED::printNumber(TipThermoModel::convertTipRawADCTouV(getTipRawTemp(0)), 6);
+ systemSettings.CalibrationOffset = temp;
+ }
+ break;
+ case 7:
+ // Temp in C
+ OLED::printNumber(TipThermoModel::getTipInC(), 5);
+ break;
+ case 8:
+ // Handle Temp
+ OLED::printNumber(getHandleTemperature(), 3);
+ break;
+ case 9:
+ // Voltage input
+ printVoltage();
+ break;
+ case 10:
+ // Print PCB ID number
+ OLED::printNumber(DetectedAccelerometerVersion, 2);
+ break;
+ case 11:
+ // Power negotiation status
+ if (getIsPoweredByDCIN()) {
+ OLED::printNumber(0, 1);
+ } else {
+ // We are not powered via DC, so want to display the appropriate state for PD or QC
+ bool poweredbyPD = false;
#ifdef POW_PD
- if (usb_pd_detect()) {
- //We are PD capable
- if (PolicyEngine::pdHasNegotiated()) {
- //We are powered via PD
- poweredbyPD = true;
- }
- }
+ if (usb_pd_detect()) {
+ // We are PD capable
+ if (PolicyEngine::pdHasNegotiated()) {
+ // We are powered via PD
+ poweredbyPD = true;
+ }
+ }
#endif
- if (poweredbyPD) {
- OLED::printNumber(2, 1);
- } else {
-
- OLED::printNumber(1, 1);
- }
- }
- break;
- case 12:
- //Max deg C limit
- OLED::printNumber(TipThermoModel::getTipMaxInC(), 3);
- break;
- default:
- break;
- }
-
- OLED::refresh();
- b = getButtonState();
- if (b == BUTTON_B_SHORT)
- return;
- else if (b == BUTTON_F_SHORT) {
- screen++;
- screen = screen % 13;
- }
- GUIDelay();
- }
+ if (poweredbyPD) {
+ OLED::printNumber(2, 1);
+ } else {
+
+ OLED::printNumber(1, 1);
+ }
+ }
+ break;
+ case 12:
+ // Max deg C limit
+ OLED::printNumber(TipThermoModel::getTipMaxInC(), 3);
+ break;
+ default:
+ break;
+ }
+
+ OLED::refresh();
+ b = getButtonState();
+ if (b == BUTTON_B_SHORT)
+ return;
+ else if (b == BUTTON_F_SHORT) {
+ screen++;
+ screen = screen % 13;
+ }
+ GUIDelay();
+ }
}
void showWarnings() {
- // Display alert if settings were reset
- if (settingsWereReset) {
- warnUser(SettingsResetMessage, 1, 10 * TICKS_SECOND);
- }
+ // Display alert if settings were reset
+ if (settingsWereReset) {
+ warnUser(SettingsResetMessage, 1, 10 * TICKS_SECOND);
+ }
#ifndef NO_WARN_MISSING
- //We also want to alert if accel or pd is not detected / not responding
- // In this case though, we dont want to nag the user _too_ much
- // So only show first 2 times
- while (DetectedAccelerometerVersion == ACCELEROMETERS_SCANNING) {
- osDelay(1);
- }
- // Display alert if accelerometer is not detected
- if (DetectedAccelerometerVersion == NO_DETECTED_ACCELEROMETER) {
- if (systemSettings.accelMissingWarningCounter < 2) {
- systemSettings.accelMissingWarningCounter++;
- saveSettings();
- warnUser(NoAccelerometerMessage, 1, 10 * TICKS_SECOND);
- }
- }
+ // We also want to alert if accel or pd is not detected / not responding
+ // In this case though, we dont want to nag the user _too_ much
+ // So only show first 2 times
+ while (DetectedAccelerometerVersion == ACCELEROMETERS_SCANNING) {
+ osDelay(1);
+ }
+ // Display alert if accelerometer is not detected
+ if (DetectedAccelerometerVersion == NO_DETECTED_ACCELEROMETER) {
+ if (systemSettings.accelMissingWarningCounter < 2) {
+ systemSettings.accelMissingWarningCounter++;
+ saveSettings();
+ warnUser(NoAccelerometerMessage, 1, 10 * TICKS_SECOND);
+ }
+ }
#ifdef POW_PD
-//We expect pd to be present
- if (!usb_pd_detect()) {
- if (systemSettings.pdMissingWarningCounter < 2) {
- systemSettings.pdMissingWarningCounter++;
- saveSettings();
- warnUser(NoPowerDeliveryMessage, 1, 10 * TICKS_SECOND);
- }
- }
+ // We expect pd to be present
+ if (!usb_pd_detect()) {
+ if (systemSettings.pdMissingWarningCounter < 2) {
+ systemSettings.pdMissingWarningCounter++;
+ saveSettings();
+ warnUser(NoPowerDeliveryMessage, 1, 10 * TICKS_SECOND);
+ }
+ }
#endif
#endif
}
@@ -780,185 +775,184 @@ void showWarnings() {
uint8_t idleScreenBGF[sizeof(idleScreenBG)];
/* StartGUITask function */
void startGUITask(void const *argument __unused) {
- OLED::initialize(); // start up the LCD
-
- uint8_t tempWarningState = 0;
- bool buttonLockout = false;
- bool tempOnDisplay = false;
- bool tipDisconnectedDisplay = false;
- {
- // Generate the flipped screen into ram for later use
- // flipped is generated by flipping each row
- for (int row = 0; row < 2; row++) {
- for (int x = 0; x < 84; x++) {
- idleScreenBGF[(row * 84) + x] = idleScreenBG[(row * 84) + (83 - x)];
- }
- }
- }
- getTipRawTemp(1); // reset filter
- OLED::setRotation(systemSettings.OrientationMode & 1);
- uint32_t ticks = xTaskGetTickCount();
- ticks += 4000; // 4 seconds from now
- while (xTaskGetTickCount() < ticks) {
- if (showBootLogoIfavailable() == false)
- ticks = xTaskGetTickCount();
- ButtonState buttons = getButtonState();
- if (buttons)
- ticks = xTaskGetTickCount(); // make timeout now so we will exit
- OLED::refresh();
- GUIDelay();
- }
-
- showWarnings();
-
- if (systemSettings.autoStartMode) {
- // jump directly to the autostart mode
- gui_solderingMode(systemSettings.autoStartMode - 1);
- buttonLockout = true;
- }
-
- for (;;) {
- ButtonState buttons = getButtonState();
- if (buttons != BUTTON_NONE) {
- OLED::setDisplayState(OLED::DisplayState::ON);
- OLED::setFont(0);
- }
- if (tempWarningState == 2)
- buttons = BUTTON_F_SHORT;
- if (buttons != BUTTON_NONE && buttonLockout)
- buttons = BUTTON_NONE;
- else
- buttonLockout = false;
-
- switch (buttons) {
- case BUTTON_NONE:
- // Do nothing
- break;
- case BUTTON_BOTH:
- // Not used yet
- // In multi-language this might be used to reset language on a long hold
- // or some such
- break;
-
- case BUTTON_B_LONG:
- // Show the version information
- showDebugMenu();
- break;
- case BUTTON_F_LONG:
- gui_solderingTempAdjust();
- saveSettings();
- break;
- case BUTTON_F_SHORT:
- gui_solderingMode(0); // enter soldering mode
- buttonLockout = true;
- break;
- case BUTTON_B_SHORT:
- enterSettingsMenu(); // enter the settings menu
- buttonLockout = true;
- break;
- default:
- break;
- }
-
- currentTempTargetDegC = 0; // ensure tip is off
- getInputVoltageX10(systemSettings.voltageDiv, 0);
- uint32_t tipTemp = TipThermoModel::getTipInC();
-
- // Preemptively turn the display on. Turn it off if and only if
- // the tip temperature is below 50 degrees C *and* motion sleep
- // detection is enabled *and* there has been no activity (movement or
- // button presses) in a while.
- // This is zero cost really as state is only changed on display updates
- OLED::setDisplayState(OLED::DisplayState::ON);
-
- if ((tipTemp < 50) && systemSettings.sensitivity && (((xTaskGetTickCount() - lastMovementTime) >
- MOVEMENT_INACTIVITY_TIME) && ((xTaskGetTickCount() - lastButtonTime) > BUTTON_INACTIVITY_TIME))) {
- OLED::setDisplayState(OLED::DisplayState::OFF);
- }
- uint16_t tipDisconnectedThres = TipThermoModel::getTipMaxInC() - 5;
- // Clear the lcd buffer
- OLED::clearScreen();
- OLED::setCursor(0, 0);
- if (systemSettings.detailedIDLE) {
- OLED::setFont(1);
- if (tipTemp > tipDisconnectedThres) {
- OLED::print(TipDisconnectedString);
- } else {
- OLED::print(IdleTipString);
- gui_drawTipTemp(false);
- OLED::print(IdleSetString);
- OLED::printNumber(systemSettings.SolderingTemp, 3);
- }
- OLED::setCursor(0, 8);
-
- OLED::print(InputVoltageString);
- printVoltage();
-
- } else {
- OLED::setFont(0);
+ OLED::initialize(); // start up the LCD
+
+ uint8_t tempWarningState = 0;
+ bool buttonLockout = false;
+ bool tempOnDisplay = false;
+ bool tipDisconnectedDisplay = false;
+ {
+ // Generate the flipped screen into ram for later use
+ // flipped is generated by flipping each row
+ for (int row = 0; row < 2; row++) {
+ for (int x = 0; x < 84; x++) {
+ idleScreenBGF[(row * 84) + x] = idleScreenBG[(row * 84) + (83 - x)];
+ }
+ }
+ }
+ getTipRawTemp(1); // reset filter
+ OLED::setRotation(systemSettings.OrientationMode & 1);
+ uint32_t ticks = xTaskGetTickCount();
+ ticks += 4000; // 4 seconds from now
+ while (xTaskGetTickCount() < ticks) {
+ if (showBootLogoIfavailable() == false)
+ ticks = xTaskGetTickCount();
+ ButtonState buttons = getButtonState();
+ if (buttons)
+ ticks = xTaskGetTickCount(); // make timeout now so we will exit
+ OLED::refresh();
+ GUIDelay();
+ }
+
+ showWarnings();
+
+ if (systemSettings.autoStartMode) {
+ // jump directly to the autostart mode
+ gui_solderingMode(systemSettings.autoStartMode - 1);
+ buttonLockout = true;
+ }
+
+ for (;;) {
+ ButtonState buttons = getButtonState();
+ if (buttons != BUTTON_NONE) {
+ OLED::setDisplayState(OLED::DisplayState::ON);
+ OLED::setFont(0);
+ }
+ if (tempWarningState == 2)
+ buttons = BUTTON_F_SHORT;
+ if (buttons != BUTTON_NONE && buttonLockout)
+ buttons = BUTTON_NONE;
+ else
+ buttonLockout = false;
+
+ switch (buttons) {
+ case BUTTON_NONE:
+ // Do nothing
+ break;
+ case BUTTON_BOTH:
+ // Not used yet
+ // In multi-language this might be used to reset language on a long hold
+ // or some such
+ break;
+
+ case BUTTON_B_LONG:
+ // Show the version information
+ showDebugMenu();
+ break;
+ case BUTTON_F_LONG:
+ gui_solderingTempAdjust();
+ saveSettings();
+ break;
+ case BUTTON_F_SHORT:
+ gui_solderingMode(0); // enter soldering mode
+ buttonLockout = true;
+ break;
+ case BUTTON_B_SHORT:
+ enterSettingsMenu(); // enter the settings menu
+ buttonLockout = true;
+ break;
+ default:
+ break;
+ }
+
+ currentTempTargetDegC = 0; // ensure tip is off
+ getInputVoltageX10(systemSettings.voltageDiv, 0);
+ uint32_t tipTemp = TipThermoModel::getTipInC();
+
+ // Preemptively turn the display on. Turn it off if and only if
+ // the tip temperature is below 50 degrees C *and* motion sleep
+ // detection is enabled *and* there has been no activity (movement or
+ // button presses) in a while.
+ // This is zero cost really as state is only changed on display updates
+ OLED::setDisplayState(OLED::DisplayState::ON);
+
+ if ((tipTemp < 50) && systemSettings.sensitivity && (((xTaskGetTickCount() - lastMovementTime) > MOVEMENT_INACTIVITY_TIME) && ((xTaskGetTickCount() - lastButtonTime) > BUTTON_INACTIVITY_TIME))) {
+ OLED::setDisplayState(OLED::DisplayState::OFF);
+ }
+ uint16_t tipDisconnectedThres = TipThermoModel::getTipMaxInC() - 5;
+ // Clear the lcd buffer
+ OLED::clearScreen();
+ OLED::setCursor(0, 0);
+ if (systemSettings.detailedIDLE) {
+ OLED::setFont(1);
+ if (tipTemp > tipDisconnectedThres) {
+ OLED::print(TipDisconnectedString);
+ } else {
+ OLED::print(IdleTipString);
+ gui_drawTipTemp(false);
+ OLED::print(IdleSetString);
+ OLED::printNumber(systemSettings.SolderingTemp, 3);
+ }
+ OLED::setCursor(0, 8);
+
+ OLED::print(InputVoltageString);
+ printVoltage();
+
+ } else {
+ OLED::setFont(0);
#ifdef OLED_FLIP
- if (!OLED::getRotation()) {
+ if (!OLED::getRotation()) {
#else
- if (OLED::getRotation()) {
+ if (OLED::getRotation()) {
#endif
- OLED::drawArea(12, 0, 84, 16, idleScreenBG);
- OLED::setCursor(0, 0);
- gui_drawBatteryIcon();
- } else {
- OLED::drawArea(0, 0, 84, 16, idleScreenBGF); // Needs to be flipped so button ends up
- // on right side of screen
- OLED::setCursor(84, 0);
- gui_drawBatteryIcon();
- }
- tipDisconnectedDisplay = false;
- if (tipTemp > 55)
- tempOnDisplay = true;
- else if (tipTemp < 45)
- tempOnDisplay = false;
- if (tipTemp > tipDisconnectedThres) {
- tempOnDisplay = false;
- tipDisconnectedDisplay = true;
- }
- if (tempOnDisplay || tipDisconnectedDisplay) {
- // draw temp over the start soldering button
- // Location changes on screen rotation
+ OLED::drawArea(12, 0, 84, 16, idleScreenBG);
+ OLED::setCursor(0, 0);
+ gui_drawBatteryIcon();
+ } else {
+ OLED::drawArea(0, 0, 84, 16, idleScreenBGF); // Needs to be flipped so button ends up
+ // on right side of screen
+ OLED::setCursor(84, 0);
+ gui_drawBatteryIcon();
+ }
+ tipDisconnectedDisplay = false;
+ if (tipTemp > 55)
+ tempOnDisplay = true;
+ else if (tipTemp < 45)
+ tempOnDisplay = false;
+ if (tipTemp > tipDisconnectedThres) {
+ tempOnDisplay = false;
+ tipDisconnectedDisplay = true;
+ }
+ if (tempOnDisplay || tipDisconnectedDisplay) {
+ // draw temp over the start soldering button
+ // Location changes on screen rotation
#ifdef OLED_FLIP
- if (!OLED::getRotation()) {
+ if (!OLED::getRotation()) {
#else
- if (OLED::getRotation()) {
+ if (OLED::getRotation()) {
#endif
- // in right handed mode we want to draw over the first part
- OLED::fillArea(55, 0, 41, 16, 0); // clear the area for the temp
- OLED::setCursor(56, 0);
-
- } else {
- OLED::fillArea(0, 0, 41, 16, 0); // clear the area
- OLED::setCursor(0, 0);
- }
- //If we have a tip connected draw the temp, if not we leave it blank
- if (!tipDisconnectedDisplay) {
- // draw in the temp
- if (!(systemSettings.coolingTempBlink && (xTaskGetTickCount() % 26 < 16)))
- gui_drawTipTemp(false); // draw in the temp
- } else {
- //Draw in missing tip symbol
+ // in right handed mode we want to draw over the first part
+ OLED::fillArea(55, 0, 41, 16, 0); // clear the area for the temp
+ OLED::setCursor(56, 0);
+
+ } else {
+ OLED::fillArea(0, 0, 41, 16, 0); // clear the area
+ OLED::setCursor(0, 0);
+ }
+ // If we have a tip connected draw the temp, if not we leave it blank
+ if (!tipDisconnectedDisplay) {
+ // draw in the temp
+ if (!(systemSettings.coolingTempBlink && (xTaskGetTickCount() % 26 < 16)))
+ gui_drawTipTemp(false); // draw in the temp
+ } else {
+ // Draw in missing tip symbol
#ifdef OLED_FLIP
- if (!OLED::getRotation()) {
+ if (!OLED::getRotation()) {
#else
- if (OLED::getRotation()) {
+ if (OLED::getRotation()) {
#endif
- // in right handed mode we want to draw over the first part
- OLED::drawArea(55, 0, 41, 16, disconnectedTipIcon);
-
- } else {
- OLED::drawArea(0, 0, 41, 16, disconnectedTipIcon);
- }
- }
- }
- }
-
- OLED::refresh();
- GUIDelay();
- }
+ // in right handed mode we want to draw over the first part
+ OLED::drawArea(55, 0, 41, 16, disconnectedTipIcon);
+
+ } else {
+ OLED::drawArea(0, 0, 41, 16, disconnectedTipIcon);
+ }
+ }
+ }
+ }
+
+ OLED::refresh();
+ GUIDelay();
+ }
}
diff --git a/source/Core/Threads/MOVThread.cpp b/source/Core/Threads/MOVThread.cpp
index d9d5d160..17fdca54 100644
--- a/source/Core/Threads/MOVThread.cpp
+++ b/source/Core/Threads/MOVThread.cpp
@@ -6,7 +6,6 @@
*/
#include "BMA223.hpp"
-#include "SC7A20.hpp"
#include "BSP.h"
#include "FreeRTOS.h"
#include "I2C_Wrapper.hpp"
@@ -14,6 +13,7 @@
#include "MMA8652FC.hpp"
#include "MSA301.h"
#include "QC3.h"
+#include "SC7A20.hpp"
#include "Settings.h"
#include "TipThermoModel.h"
#include "cmsis_os.h"
@@ -23,60 +23,60 @@
#include "stdlib.h"
#include "task.h"
#define MOVFilter 8
-uint8_t accelInit = 0;
+uint8_t accelInit = 0;
TickType_t lastMovementTime = 0;
-void detectAccelerometerVersion() {
- DetectedAccelerometerVersion = 99;
+void detectAccelerometerVersion() {
+ DetectedAccelerometerVersion = 99;
#ifdef ACCEL_MMA
if (MMA8652FC::detect()) {
if (MMA8652FC::initalize()) {
- DetectedAccelerometerVersion = 1;
+ DetectedAccelerometerVersion = 1;
}
} else
#endif
#ifdef ACCEL_LIS
- if (LIS2DH12::detect()) {
- // Setup the ST Accelerometer
- if (LIS2DH12::initalize()) {
- DetectedAccelerometerVersion = 2;
- }
- } else
+ if (LIS2DH12::detect()) {
+ // Setup the ST Accelerometer
+ if (LIS2DH12::initalize()) {
+ DetectedAccelerometerVersion = 2;
+ }
+ } else
#endif
#ifdef ACCEL_BMA
if (BMA223::detect()) {
// Setup the ST Accelerometer
if (BMA223::initalize()) {
- DetectedAccelerometerVersion = 3;
+ DetectedAccelerometerVersion = 3;
}
} else
#endif
#ifdef ACCEL_MSA
- if (MSA301::detect()) {
- // Setup the MSA301 Accelerometer
- if (MSA301::initalize()) {
- DetectedAccelerometerVersion = 4;
- }
- } else
+ if (MSA301::detect()) {
+ // Setup the MSA301 Accelerometer
+ if (MSA301::initalize()) {
+ DetectedAccelerometerVersion = 4;
+ }
+ } else
#endif
#ifdef ACCEL_SC7
- if (SC7A20::detect()) {
- // Setup the SC7A20 Accelerometer
- if (SC7A20::initalize()) {
- DetectedAccelerometerVersion = 5;
- }
- } else
+ if (SC7A20::detect()) {
+ // Setup the SC7A20 Accelerometer
+ if (SC7A20::initalize()) {
+ DetectedAccelerometerVersion = 5;
+ }
+ } else
#endif
- {
- // disable imu sensitivity
- systemSettings.sensitivity = 0;
- }
+ {
+ // disable imu sensitivity
+ systemSettings.sensitivity = 0;
+ }
}
inline void readAccelerometer(int16_t &tx, int16_t &ty, int16_t &tz, Orientation &rotation) {
#ifdef ACCEL_LIS
- if (DetectedAccelerometerVersion == 2) {
- LIS2DH12::getAxisReadings(tx, ty, tz);
- rotation = LIS2DH12::getOrientation();
- } else
+ if (DetectedAccelerometerVersion == 2) {
+ LIS2DH12::getAxisReadings(tx, ty, tz);
+ rotation = LIS2DH12::getOrientation();
+ } else
#endif
#ifdef ACCEL_MMA
if (DetectedAccelerometerVersion == 1) {
@@ -91,81 +91,81 @@ inline void readAccelerometer(int16_t &tx, int16_t &ty, int16_t &tz, Orientation
} else
#endif
#ifdef ACCEL_MSA
- if (DetectedAccelerometerVersion == 4) {
- MSA301::getAxisReadings(tx, ty, tz);
- rotation = MSA301::getOrientation();
- } else
+ if (DetectedAccelerometerVersion == 4) {
+ MSA301::getAxisReadings(tx, ty, tz);
+ rotation = MSA301::getOrientation();
+ } else
#endif
#ifdef ACCEL_SC7
- if (DetectedAccelerometerVersion == 5) {
- SC7A20::getAxisReadings(tx, ty, tz);
- rotation = SC7A20::getOrientation();
- } else
+ if (DetectedAccelerometerVersion == 5) {
+ SC7A20::getAxisReadings(tx, ty, tz);
+ rotation = SC7A20::getOrientation();
+ } else
#endif
- {
- // do nothing :(
- }
+ {
+ // do nothing :(
+ }
}
void startMOVTask(void const *argument __unused) {
- detectAccelerometerVersion();
- osDelay(TICKS_100MS / 2); // wait ~50ms for setup of accel to finalise
- lastMovementTime = 0;
- // Mask 2 seconds if we are in autostart so that if user is plugging in and
- // then putting in stand it doesnt wake instantly
- if (systemSettings.autoStartMode)
- osDelay(2 * TICKS_SECOND);
+ detectAccelerometerVersion();
+ osDelay(TICKS_100MS / 2); // wait ~50ms for setup of accel to finalise
+ lastMovementTime = 0;
+ // Mask 2 seconds if we are in autostart so that if user is plugging in and
+ // then putting in stand it doesnt wake instantly
+ if (systemSettings.autoStartMode)
+ osDelay(2 * TICKS_SECOND);
- int16_t datax[MOVFilter] = { 0 };
- int16_t datay[MOVFilter] = { 0 };
- int16_t dataz[MOVFilter] = { 0 };
- uint8_t currentPointer = 0;
- int16_t tx = 0, ty = 0, tz = 0;
- int32_t avgx, avgy, avgz;
- if (systemSettings.sensitivity > 9)
- systemSettings.sensitivity = 9;
- Orientation rotation = ORIENTATION_FLAT;
- for (;;) {
- int32_t threshold = 1500 + (9 * 200);
- threshold -= systemSettings.sensitivity * 200; // 200 is the step size
- readAccelerometer(tx, ty, tz, rotation);
- if (systemSettings.OrientationMode == 2) {
- if (rotation != ORIENTATION_FLAT) {
- OLED::setRotation(rotation == ORIENTATION_LEFT_HAND); // link the data through
- }
- }
- datax[currentPointer] = (int32_t) tx;
- datay[currentPointer] = (int32_t) ty;
- dataz[currentPointer] = (int32_t) tz;
- if (!accelInit) {
- for (uint8_t i = currentPointer + 1; i < MOVFilter; i++) {
- datax[i] = (int32_t) tx;
- datay[i] = (int32_t) ty;
- dataz[i] = (int32_t) tz;
- }
- accelInit = 1;
- }
- currentPointer = (currentPointer + 1) % MOVFilter;
- avgx = avgy = avgz = 0;
- // calculate averages
- for (uint8_t i = 0; i < MOVFilter; i++) {
- avgx += datax[i];
- avgy += datay[i];
- avgz += dataz[i];
- }
- avgx /= MOVFilter;
- avgy /= MOVFilter;
- avgz /= MOVFilter;
+ int16_t datax[MOVFilter] = {0};
+ int16_t datay[MOVFilter] = {0};
+ int16_t dataz[MOVFilter] = {0};
+ uint8_t currentPointer = 0;
+ int16_t tx = 0, ty = 0, tz = 0;
+ int32_t avgx, avgy, avgz;
+ if (systemSettings.sensitivity > 9)
+ systemSettings.sensitivity = 9;
+ Orientation rotation = ORIENTATION_FLAT;
+ for (;;) {
+ int32_t threshold = 1500 + (9 * 200);
+ threshold -= systemSettings.sensitivity * 200; // 200 is the step size
+ readAccelerometer(tx, ty, tz, rotation);
+ if (systemSettings.OrientationMode == 2) {
+ if (rotation != ORIENTATION_FLAT) {
+ OLED::setRotation(rotation == ORIENTATION_LEFT_HAND); // link the data through
+ }
+ }
+ datax[currentPointer] = (int32_t)tx;
+ datay[currentPointer] = (int32_t)ty;
+ dataz[currentPointer] = (int32_t)tz;
+ if (!accelInit) {
+ for (uint8_t i = currentPointer + 1; i < MOVFilter; i++) {
+ datax[i] = (int32_t)tx;
+ datay[i] = (int32_t)ty;
+ dataz[i] = (int32_t)tz;
+ }
+ accelInit = 1;
+ }
+ currentPointer = (currentPointer + 1) % MOVFilter;
+ avgx = avgy = avgz = 0;
+ // calculate averages
+ for (uint8_t i = 0; i < MOVFilter; i++) {
+ avgx += datax[i];
+ avgy += datay[i];
+ avgz += dataz[i];
+ }
+ avgx /= MOVFilter;
+ avgy /= MOVFilter;
+ avgz /= MOVFilter;
- // Sum the deltas
- int32_t error = (abs(avgx - tx) + abs(avgy - ty) + abs(avgz - tz));
- // So now we have averages, we want to look if these are different by more
- // than the threshold
+ // Sum the deltas
+ int32_t error = (abs(avgx - tx) + abs(avgy - ty) + abs(avgz - tz));
+ // So now we have averages, we want to look if these are different by more
+ // than the threshold
- // If movement has occurred then we update the tick timer
- if (error > threshold) {
- lastMovementTime = xTaskGetTickCount();
- }
+ // If movement has occurred then we update the tick timer
+ if (error > threshold) {
+ lastMovementTime = xTaskGetTickCount();
+ }
- osDelay(TICKS_100MS); // Slow down update rate
- }
+ osDelay(TICKS_100MS); // Slow down update rate
+ }
}
diff --git a/source/Core/Threads/PIDThread.cpp b/source/Core/Threads/PIDThread.cpp
index 72f7606f..170522f9 100644
--- a/source/Core/Threads/PIDThread.cpp
+++ b/source/Core/Threads/PIDThread.cpp
@@ -5,124 +5,119 @@
* Author: Ralim
*/
-#include "main.hpp"
#include "BSP.h"
-#include "power.hpp"
-#include "history.hpp"
+#include "FreeRTOS.h"
+#include "Settings.h"
#include "TipThermoModel.h"
#include "cmsis_os.h"
-#include "FreeRTOS.h"
+#include "history.hpp"
+#include "main.hpp"
+#include "power.hpp"
#include "task.h"
-#include "Settings.h"
-static TickType_t powerPulseRate = 10000;
-static TickType_t powerPulseDuration = 250;
-TaskHandle_t pidTaskNotification = NULL;
-uint32_t currentTempTargetDegC = 0; // Current temperature target in C
+static TickType_t powerPulseRate = 10000;
+static TickType_t powerPulseDuration = 250;
+TaskHandle_t pidTaskNotification = NULL;
+uint32_t currentTempTargetDegC = 0; // Current temperature target in C
/* StartPIDTask function */
void startPIDTask(void const *argument __unused) {
- /*
- * We take the current tip temperature & evaluate the next step for the tip
- * control PWM.
- */
- setTipX10Watts(0); // disable the output driver if the output is set to be off
- TickType_t lastPowerPulseStart = 0;
- TickType_t lastPowerPulseEnd = 0;
-
- history<int32_t, PID_TIM_HZ> tempError = { { 0 }, 0, 0 };
- currentTempTargetDegC = 0; // Force start with no output (off). If in sleep / soldering this will
- // be over-ridden rapidly
- pidTaskNotification = xTaskGetCurrentTaskHandle();
- uint32_t PIDTempTarget = 0;
- for (;;) {
+ /*
+ * We take the current tip temperature & evaluate the next step for the tip
+ * control PWM.
+ */
+ setTipX10Watts(0); // disable the output driver if the output is set to be off
+ TickType_t lastPowerPulseStart = 0;
+ TickType_t lastPowerPulseEnd = 0;
- if (ulTaskNotifyTake(pdTRUE, 2000)) {
- // This is a call to block this thread until the ADC does its samples
- int32_t x10WattsOut = 0;
- // Do the reading here to keep the temp calculations churning along
- uint32_t currentTipTempInC = TipThermoModel::getTipInC(true);
- PIDTempTarget = currentTempTargetDegC;
- if (PIDTempTarget) {
- // Cap the max set point to 450C
- if (PIDTempTarget > (450)) {
- //Maximum allowed output
- PIDTempTarget = (450);
- }
- //Safety check that not aiming higher than current tip can measure
- if (PIDTempTarget > TipThermoModel::getTipMaxInC()) {
- PIDTempTarget = TipThermoModel::getTipMaxInC();
- }
- // Convert the current tip to degree's C
+ history<int32_t, PID_TIM_HZ> tempError = {{0}, 0, 0};
+ currentTempTargetDegC = 0; // Force start with no output (off). If in sleep / soldering this will
+ // be over-ridden rapidly
+ pidTaskNotification = xTaskGetCurrentTaskHandle();
+ uint32_t PIDTempTarget = 0;
+ for (;;) {
- // As we get close to our target, temp noise causes the system
- // to be unstable. Use a rolling average to dampen it.
- // We overshoot by roughly 1 degree C.
- // This helps stabilize the display.
- int32_t tError = PIDTempTarget - currentTipTempInC + 1;
- tError = tError > INT16_MAX ? INT16_MAX : tError;
- tError = tError < INT16_MIN ? INT16_MIN : tError;
- tempError.update(tError);
+ if (ulTaskNotifyTake(pdTRUE, 2000)) {
+ // This is a call to block this thread until the ADC does its samples
+ int32_t x10WattsOut = 0;
+ // Do the reading here to keep the temp calculations churning along
+ uint32_t currentTipTempInC = TipThermoModel::getTipInC(true);
+ PIDTempTarget = currentTempTargetDegC;
+ if (PIDTempTarget) {
+ // Cap the max set point to 450C
+ if (PIDTempTarget > (450)) {
+ // Maximum allowed output
+ PIDTempTarget = (450);
+ }
+ // Safety check that not aiming higher than current tip can measure
+ if (PIDTempTarget > TipThermoModel::getTipMaxInC()) {
+ PIDTempTarget = TipThermoModel::getTipMaxInC();
+ }
+ // Convert the current tip to degree's C
- // Now for the PID!
+ // As we get close to our target, temp noise causes the system
+ // to be unstable. Use a rolling average to dampen it.
+ // We overshoot by roughly 1 degree C.
+ // This helps stabilize the display.
+ int32_t tError = PIDTempTarget - currentTipTempInC + 1;
+ tError = tError > INT16_MAX ? INT16_MAX : tError;
+ tError = tError < INT16_MIN ? INT16_MIN : tError;
+ tempError.update(tError);
- // P term - total power needed to hit target temp next cycle.
- // thermal mass = 1690 milliJ/*C for my tip.
- // = Watts*Seconds to raise Temp from room temp to +100*C, divided by 100*C.
- // we divide milliWattsNeeded by 20 to let the I term dominate near the set point.
- // This is necessary because of the temp noise and thermal lag in the system.
- // Once we have feed-forward temp estimation we should be able to better tune this.
+ // Now for the PID!
- int32_t x10WattsNeeded = tempToX10Watts(tError);
-// tempError.average());
- // note that milliWattsNeeded is sometimes negative, this counters overshoot
- // from I term's inertia.
- x10WattsOut += x10WattsNeeded;
+ // P term - total power needed to hit target temp next cycle.
+ // thermal mass = 1690 milliJ/*C for my tip.
+ // = Watts*Seconds to raise Temp from room temp to +100*C, divided by 100*C.
+ // we divide milliWattsNeeded by 20 to let the I term dominate near the set point.
+ // This is necessary because of the temp noise and thermal lag in the system.
+ // Once we have feed-forward temp estimation we should be able to better tune this.
- // I term - energy needed to compensate for heat loss.
- // We track energy put into the system over some window.
- // Assuming the temp is stable, energy in = energy transfered.
- // (If it isn't, P will dominate).
- x10WattsOut += x10WattHistory.average();
+ int32_t x10WattsNeeded = tempToX10Watts(tError);
+ // tempError.average());
+ // note that milliWattsNeeded is sometimes negative, this counters overshoot
+ // from I term's inertia.
+ x10WattsOut += x10WattsNeeded;
- // D term - use sudden temp change to counter fast cooling/heating.
- // In practice, this provides an early boost if temp is dropping
- // and counters extra power if the iron is no longer losing temp.
- // basically: temp - lastTemp
- // Unfortunately, our temp signal is too noisy to really help.
+ // I term - energy needed to compensate for heat loss.
+ // We track energy put into the system over some window.
+ // Assuming the temp is stable, energy in = energy transfered.
+ // (If it isn't, P will dominate).
+ x10WattsOut += x10WattHistory.average();
- }
- //If the user turns on the option of using an occasional pulse to keep the power bank on
- if (systemSettings.KeepAwakePulse) {
+ // D term - use sudden temp change to counter fast cooling/heating.
+ // In practice, this provides an early boost if temp is dropping
+ // and counters extra power if the iron is no longer losing temp.
+ // basically: temp - lastTemp
+ // Unfortunately, our temp signal is too noisy to really help.
+ }
+ // If the user turns on the option of using an occasional pulse to keep the power bank on
+ if (systemSettings.KeepAwakePulse) {
- if (xTaskGetTickCount() - lastPowerPulseStart
- > powerPulseRate) {
- lastPowerPulseStart = xTaskGetTickCount();
- lastPowerPulseEnd = lastPowerPulseStart
- + powerPulseDuration;
- }
+ if (xTaskGetTickCount() - lastPowerPulseStart > powerPulseRate) {
+ lastPowerPulseStart = xTaskGetTickCount();
+ lastPowerPulseEnd = lastPowerPulseStart + powerPulseDuration;
+ }
- //If current PID is less than the pulse level, check if we want to constrain to the pulse as the floor
- if (x10WattsOut < systemSettings.KeepAwakePulse
- && xTaskGetTickCount() < lastPowerPulseEnd) {
- x10WattsOut = systemSettings.KeepAwakePulse;
- }
- }
+ // If current PID is less than the pulse level, check if we want to constrain to the pulse as the floor
+ if (x10WattsOut < systemSettings.KeepAwakePulse && xTaskGetTickCount() < lastPowerPulseEnd) {
+ x10WattsOut = systemSettings.KeepAwakePulse;
+ }
+ }
- //Secondary safety check to forcefully disable header when within ADC noise of top of ADC
- if (getTipRawTemp(0) > (0x7FFF - 150)) {
- x10WattsOut = 0;
- }
- if (systemSettings.powerLimit
- && x10WattsOut > (systemSettings.powerLimit * 10)) {
- setTipX10Watts(systemSettings.powerLimit * 10);
- } else {
- setTipX10Watts(x10WattsOut);
- }
+ // Secondary safety check to forcefully disable header when within ADC noise of top of ADC
+ if (getTipRawTemp(0) > (0x7FFF - 150)) {
+ x10WattsOut = 0;
+ }
+ if (systemSettings.powerLimit && x10WattsOut > (systemSettings.powerLimit * 10)) {
+ setTipX10Watts(systemSettings.powerLimit * 10);
+ } else {
+ setTipX10Watts(x10WattsOut);
+ }
- resetWatchdog();
- } else {
- //ADC interrupt timeout
- setTipPWM(0);
- }
- }
+ resetWatchdog();
+ } else {
+ // ADC interrupt timeout
+ setTipPWM(0);
+ }
+ }
}
diff --git a/source/Core/Threads/POWThread.cpp b/source/Core/Threads/POWThread.cpp
index d48b54e9..2f5661e4 100644
--- a/source/Core/Threads/POWThread.cpp
+++ b/source/Core/Threads/POWThread.cpp
@@ -17,9 +17,9 @@
// Small worker thread to handle power (mostly QC) related steps
void startPOWTask(void const *argument __unused) {
- postRToSInit();
- for (;;) {
- osDelay(TICKS_100MS); // Slow down update rate
- power_check();
- }
+ postRToSInit();
+ for (;;) {
+ osDelay(TICKS_100MS); // Slow down update rate
+ power_check();
+ }
}
diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS/cmsis_os.c b/source/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS/cmsis_os.c
index 552f583c..6dde9712 100644
--- a/source/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS/cmsis_os.c
+++ b/source/Middlewares/Third_Party/FreeRTOS/Source/CMSIS_RTOS/cmsis_os.c
@@ -21,9 +21,9 @@
* Version 1.02
* Control functions for short timeouts in microsecond resolution:
* Added: osKernelSysTick, osKernelSysTickFrequency, osKernelSysTickMicroSec
- * Removed: osSignalGet
- *
- *
+ * Removed: osSignalGet
+ *
+ *
*----------------------------------------------------------------------------
*
* Portions Copyright � 2016 STMicroelectronics International N.V. All rights reserved.
@@ -54,58 +54,58 @@
*---------------------------------------------------------------------------*/
/**
- ******************************************************************************
- * @file cmsis_os.c
- * @author MCD Application Team
- * @date 03-March-2017
- * @brief CMSIS-RTOS API implementation for FreeRTOS V9.0.0
- ******************************************************************************
- * @attention
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted, provided that the following conditions are met:
- *
- * 1. Redistribution 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 other
- * contributors to this software may be used to endorse or promote products
- * derived from this software without specific written permission.
- * 4. This software, including modifications and/or derivative works of this
- * software, must execute solely and exclusively on microcontroller or
- * microprocessor devices manufactured by or for STMicroelectronics.
- * 5. Redistribution and use of this software other than as permitted under
- * this license is void and will automatically terminate your rights under
- * this license.
- *
- * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
- * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
- * SHALL STMICROELECTRONICS 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.
- *
- ******************************************************************************
- */
+ ******************************************************************************
+ * @file cmsis_os.c
+ * @author MCD Application Team
+ * @date 03-March-2017
+ * @brief CMSIS-RTOS API implementation for FreeRTOS V9.0.0
+ ******************************************************************************
+ * @attention
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted, provided that the following conditions are met:
+ *
+ * 1. Redistribution 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 other
+ * contributors to this software may be used to endorse or promote products
+ * derived from this software without specific written permission.
+ * 4. This software, including modifications and/or derivative works of this
+ * software, must execute solely and exclusively on microcontroller or
+ * microprocessor devices manufactured by or for STMicroelectronics.
+ * 5. Redistribution and use of this software other than as permitted under
+ * this license is void and will automatically terminate your rights under
+ * this license.
+ *
+ * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
+ * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT
+ * SHALL STMICROELECTRONICS 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.
+ *
+ ******************************************************************************
+ */
-#include <string.h>
#include "cmsis_os.h"
+#include <string.h>
/*
* ARM Compiler 4/5
*/
#if defined(__CC_ARM)
-#define __ASM __asm
-#define __INLINE __inline
+#define __ASM __asm
+#define __INLINE __inline
#define __STATIC_INLINE static __inline
#include "cmsis_armcc.h"
@@ -114,8 +114,8 @@
*/
#elif defined(__GNUC__)
-#define __ASM __asm /*!< asm keyword for GNU Compiler */
-#define __INLINE inline /*!< inline keyword for GNU Compiler */
+#define __ASM __asm /*!< asm keyword for GNU Compiler */
+#define __INLINE inline /*!< inline keyword for GNU Compiler */
#define __STATIC_INLINE static inline
uint32_t __get_IPSR(void);
// #include "cmsis_gcc.h"
@@ -141,12 +141,10 @@ uint32_t __get_IPSR(void);
extern void xPortSysTickHandler(void);
/* Convert from CMSIS type osPriority to FreeRTOS priority number */
-static unsigned portBASE_TYPE makeFreeRtosPriority(osPriority priority)
-{
+static unsigned portBASE_TYPE makeFreeRtosPriority(osPriority priority) {
unsigned portBASE_TYPE fpriority = tskIDLE_PRIORITY;
- if (priority != osPriorityError)
- {
+ if (priority != osPriorityError) {
fpriority += (priority - osPriorityIdle);
}
@@ -155,12 +153,10 @@ static unsigned portBASE_TYPE makeFreeRtosPriority(osPriority priority)
#if (INCLUDE_uxTaskPriorityGet == 1)
/* Convert from FreeRTOS priority number to CMSIS type osPriority */
-static osPriority makeCmsisPriority(unsigned portBASE_TYPE fpriority)
-{
+static osPriority makeCmsisPriority(unsigned portBASE_TYPE fpriority) {
osPriority priority = osPriorityError;
- if ((fpriority - tskIDLE_PRIORITY) <= (osPriorityRealtime - osPriorityIdle))
- {
+ if ((fpriority - tskIDLE_PRIORITY) <= (osPriorityRealtime - osPriorityIdle)) {
priority = (osPriority)((int)osPriorityIdle + (int)(fpriority - tskIDLE_PRIORITY));
}
@@ -169,43 +165,38 @@ static osPriority makeCmsisPriority(unsigned portBASE_TYPE fpriority)
#endif
/* Determine whether we are in thread mode or handler mode. */
-static int inHandlerMode(void)
-{
- return __get_IPSR() != 0;
-}
+static int inHandlerMode(void) { return __get_IPSR() != 0; }
/*********************** Kernel Control Functions *****************************/
/**
-* @brief Initialize the RTOS Kernel for creating objects.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS.
-*/
+ * @brief Initialize the RTOS Kernel for creating objects.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS.
+ */
osStatus osKernelInitialize(void);
/**
-* @brief Start the RTOS Kernel with executing the specified thread.
-* @param thread_def thread definition referenced with \ref osThread.
-* @param argument pointer that is passed to the thread function as start argument.
-* @retval status code that indicates the execution status of the function
-* @note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osKernelStart(void)
-{
+ * @brief Start the RTOS Kernel with executing the specified thread.
+ * @param thread_def thread definition referenced with \ref osThread.
+ * @param argument pointer that is passed to the thread function as start argument.
+ * @retval status code that indicates the execution status of the function
+ * @note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osKernelStart(void) {
vTaskStartScheduler();
return osOK;
}
/**
-* @brief Check if the RTOS kernel is already started
-* @param None
-* @retval (0) RTOS is not started
-* (1) RTOS is started
-* (-1) if this feature is disabled in FreeRTOSConfig.h
-* @note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS.
-*/
-int32_t osKernelRunning(void)
-{
+ * @brief Check if the RTOS kernel is already started
+ * @param None
+ * @retval (0) RTOS is not started
+ * (1) RTOS is started
+ * (-1) if this feature is disabled in FreeRTOSConfig.h
+ * @note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS.
+ */
+int32_t osKernelRunning(void) {
#if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1))
if (xTaskGetSchedulerState() == taskSCHEDULER_NOT_STARTED)
return 0;
@@ -218,61 +209,45 @@ int32_t osKernelRunning(void)
#if (defined(osFeature_SysTick) && (osFeature_SysTick != 0)) // System Timer available
/**
-* @brief Get the value of the Kernel SysTick timer
-* @param None
-* @retval None
-* @note MUST REMAIN UNCHANGED: \b osKernelSysTick shall be consistent in every CMSIS-RTOS.
-*/
-uint32_t osKernelSysTick(void)
-{
- if (inHandlerMode())
- {
+ * @brief Get the value of the Kernel SysTick timer
+ * @param None
+ * @retval None
+ * @note MUST REMAIN UNCHANGED: \b osKernelSysTick shall be consistent in every CMSIS-RTOS.
+ */
+uint32_t osKernelSysTick(void) {
+ if (inHandlerMode()) {
return xTaskGetTickCountFromISR();
- }
- else
- {
+ } else {
return xTaskGetTickCount();
}
}
#endif // System Timer available
/*********************** Thread Management *****************************/
/**
-* @brief Create a thread and add it to Active Threads and set it to state READY.
-* @param thread_def thread definition referenced with \ref osThread.
-* @param argument pointer that is passed to the thread function as start argument.
-* @retval thread ID for reference by other functions or NULL in case of error.
-* @note MUST REMAIN UNCHANGED: \b osThreadCreate shall be consistent in every CMSIS-RTOS.
-*/
-osThreadId osThreadCreate(const osThreadDef_t *thread_def, void *argument)
-{
+ * @brief Create a thread and add it to Active Threads and set it to state READY.
+ * @param thread_def thread definition referenced with \ref osThread.
+ * @param argument pointer that is passed to the thread function as start argument.
+ * @retval thread ID for reference by other functions or NULL in case of error.
+ * @note MUST REMAIN UNCHANGED: \b osThreadCreate shall be consistent in every CMSIS-RTOS.
+ */
+osThreadId osThreadCreate(const osThreadDef_t *thread_def, void *argument) {
TaskHandle_t handle;
#if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1)
- if ((thread_def->buffer != NULL) && (thread_def->controlblock != NULL))
- {
- handle = xTaskCreateStatic((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name,
- thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority),
+ if ((thread_def->buffer != NULL) && (thread_def->controlblock != NULL)) {
+ handle = xTaskCreateStatic((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority),
thread_def->buffer, thread_def->controlblock);
- }
- else
- {
- if (xTaskCreate((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name,
- thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority),
- &handle) != pdPASS)
- {
+ } else {
+ if (xTaskCreate((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), &handle) != pdPASS) {
return NULL;
}
}
#elif (configSUPPORT_STATIC_ALLOCATION == 1)
- handle = xTaskCreateStatic((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name,
- thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority),
- thread_def->buffer, thread_def->controlblock);
+ handle = xTaskCreateStatic((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), thread_def->buffer,
+ thread_def->controlblock);
#else
- if (xTaskCreate((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name,
- thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority),
- &handle) != pdPASS)
- {
+ if (xTaskCreate((TaskFunction_t)thread_def->pthread, (const portCHAR *)thread_def->name, thread_def->stacksize, argument, makeFreeRtosPriority(thread_def->tpriority), &handle) != pdPASS) {
return NULL;
}
#endif
@@ -281,12 +256,11 @@ osThreadId osThreadCreate(const osThreadDef_t *thread_def, void *argument)
}
/**
-* @brief Return the thread ID of the current running thread.
-* @retval thread ID for reference by other functions or NULL in case of error.
-* @note MUST REMAIN UNCHANGED: \b osThreadGetId shall be consistent in every CMSIS-RTOS.
-*/
-osThreadId osThreadGetId(void)
-{
+ * @brief Return the thread ID of the current running thread.
+ * @retval thread ID for reference by other functions or NULL in case of error.
+ * @note MUST REMAIN UNCHANGED: \b osThreadGetId shall be consistent in every CMSIS-RTOS.
+ */
+osThreadId osThreadGetId(void) {
#if ((INCLUDE_xTaskGetCurrentTaskHandle == 1) || (configUSE_MUTEXES == 1))
return xTaskGetCurrentTaskHandle();
#else
@@ -295,13 +269,12 @@ osThreadId osThreadGetId(void)
}
/**
-* @brief Terminate execution of a thread and remove it from Active Threads.
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osThreadTerminate shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osThreadTerminate(osThreadId thread_id)
-{
+ * @brief Terminate execution of a thread and remove it from Active Threads.
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osThreadTerminate shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osThreadTerminate(osThreadId thread_id) {
#if (INCLUDE_vTaskDelete == 1)
vTaskDelete(thread_id);
return osOK;
@@ -311,26 +284,24 @@ osStatus osThreadTerminate(osThreadId thread_id)
}
/**
-* @brief Pass control to next thread that is in state \b READY.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osThreadYield shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osThreadYield(void)
-{
+ * @brief Pass control to next thread that is in state \b READY.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osThreadYield shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osThreadYield(void) {
taskYIELD();
return osOK;
}
/**
-* @brief Change priority of an active thread.
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
-* @param priority new priority value for the thread function.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osThreadSetPriority shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osThreadSetPriority(osThreadId thread_id, osPriority priority)
-{
+ * @brief Change priority of an active thread.
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
+ * @param priority new priority value for the thread function.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osThreadSetPriority shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osThreadSetPriority(osThreadId thread_id, osPriority priority) {
#if (INCLUDE_vTaskPrioritySet == 1)
vTaskPrioritySet(thread_id, makeFreeRtosPriority(priority));
return osOK;
@@ -340,20 +311,16 @@ osStatus osThreadSetPriority(osThreadId thread_id, osPriority priority)
}
/**
-* @brief Get current priority of an active thread.
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
-* @retval current priority value of the thread function.
-* @note MUST REMAIN UNCHANGED: \b osThreadGetPriority shall be consistent in every CMSIS-RTOS.
-*/
-osPriority osThreadGetPriority(osThreadId thread_id)
-{
+ * @brief Get current priority of an active thread.
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
+ * @retval current priority value of the thread function.
+ * @note MUST REMAIN UNCHANGED: \b osThreadGetPriority shall be consistent in every CMSIS-RTOS.
+ */
+osPriority osThreadGetPriority(osThreadId thread_id) {
#if (INCLUDE_uxTaskPriorityGet == 1)
- if (inHandlerMode())
- {
+ if (inHandlerMode()) {
return makeCmsisPriority(uxTaskPriorityGetFromISR(thread_id));
- }
- else
- {
+ } else {
return makeCmsisPriority(uxTaskPriorityGet(thread_id));
}
#else
@@ -363,12 +330,11 @@ osPriority osThreadGetPriority(osThreadId thread_id)
/*********************** Generic Wait Functions *******************************/
/**
-* @brief Wait for Timeout (Time Delay)
-* @param millisec time delay value
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osDelay(uint32_t millisec)
-{
+ * @brief Wait for Timeout (Time Delay)
+ * @param millisec time delay value
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osDelay(uint32_t millisec) {
#if INCLUDE_vTaskDelay
TickType_t ticks = millisec / portTICK_PERIOD_MS;
@@ -384,59 +350,45 @@ osStatus osDelay(uint32_t millisec)
#if (defined(osFeature_Wait) && (osFeature_Wait != 0)) /* Generic Wait available */
/**
-* @brief Wait for Signal, Message, Mail, or Timeout
-* @param millisec timeout value or 0 in case of no time-out
-* @retval event that contains signal, message, or mail information or error code.
-* @note MUST REMAIN UNCHANGED: \b osWait shall be consistent in every CMSIS-RTOS.
-*/
+ * @brief Wait for Signal, Message, Mail, or Timeout
+ * @param millisec timeout value or 0 in case of no time-out
+ * @retval event that contains signal, message, or mail information or error code.
+ * @note MUST REMAIN UNCHANGED: \b osWait shall be consistent in every CMSIS-RTOS.
+ */
osEvent osWait(uint32_t millisec);
#endif /* Generic Wait available */
/*********************** Timer Management Functions ***************************/
/**
-* @brief Create a timer.
-* @param timer_def timer object referenced with \ref osTimer.
-* @param type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior.
-* @param argument argument to the timer call back function.
-* @retval timer ID for reference by other functions or NULL in case of error.
-* @note MUST REMAIN UNCHANGED: \b osTimerCreate shall be consistent in every CMSIS-RTOS.
-*/
-osTimerId osTimerCreate(const osTimerDef_t *timer_def, os_timer_type type, void *argument)
-{
+ * @brief Create a timer.
+ * @param timer_def timer object referenced with \ref osTimer.
+ * @param type osTimerOnce for one-shot or osTimerPeriodic for periodic behavior.
+ * @param argument argument to the timer call back function.
+ * @retval timer ID for reference by other functions or NULL in case of error.
+ * @note MUST REMAIN UNCHANGED: \b osTimerCreate shall be consistent in every CMSIS-RTOS.
+ */
+osTimerId osTimerCreate(const osTimerDef_t *timer_def, os_timer_type type, void *argument) {
#if (configUSE_TIMERS == 1)
#if ((configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1))
- if (timer_def->controlblock != NULL)
- {
+ if (timer_def->controlblock != NULL) {
return xTimerCreateStatic((const char *)"",
1, // period should be filled when starting the Timer using osTimerStart
- (type == osTimerPeriodic) ? pdTRUE : pdFALSE,
- (void *)argument,
- (TaskFunction_t)timer_def->ptimer,
- (StaticTimer_t *)timer_def->controlblock);
- }
- else
- {
+ (type == osTimerPeriodic) ? pdTRUE : pdFALSE, (void *)argument, (TaskFunction_t)timer_def->ptimer, (StaticTimer_t *)timer_def->controlblock);
+ } else {
return xTimerCreate((const char *)"",
1, // period should be filled when starting the Timer using osTimerStart
- (type == osTimerPeriodic) ? pdTRUE : pdFALSE,
- (void *)argument,
- (TaskFunction_t)timer_def->ptimer);
+ (type == osTimerPeriodic) ? pdTRUE : pdFALSE, (void *)argument, (TaskFunction_t)timer_def->ptimer);
}
#elif (configSUPPORT_STATIC_ALLOCATION == 1)
return xTimerCreateStatic((const char *)"",
1, // period should be filled when starting the Timer using osTimerStart
- (type == osTimerPeriodic) ? pdTRUE : pdFALSE,
- (void *)argument,
- (TaskFunction_t)timer_def->ptimer,
- (StaticTimer_t *)timer_def->controlblock);
+ (type == osTimerPeriodic) ? pdTRUE : pdFALSE, (void *)argument, (TaskFunction_t)timer_def->ptimer, (StaticTimer_t *)timer_def->controlblock);
#else
return xTimerCreate((const char *)"",
1, // period should be filled when starting the Timer using osTimerStart
- (type == osTimerPeriodic) ? pdTRUE : pdFALSE,
- (void *)argument,
- (TaskFunction_t)timer_def->ptimer);
+ (type == osTimerPeriodic) ? pdTRUE : pdFALSE, (void *)argument, (TaskFunction_t)timer_def->ptimer);
#endif
#else
@@ -445,35 +397,28 @@ osTimerId osTimerCreate(const osTimerDef_t *timer_def, os_timer_type type, void
}
/**
-* @brief Start or restart a timer.
-* @param timer_id timer ID obtained by \ref osTimerCreate.
-* @param millisec time delay value of the timer.
-* @retval status code that indicates the execution status of the function
-* @note MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osTimerStart(osTimerId timer_id, uint32_t millisec)
-{
+ * @brief Start or restart a timer.
+ * @param timer_id timer ID obtained by \ref osTimerCreate.
+ * @param millisec time delay value of the timer.
+ * @retval status code that indicates the execution status of the function
+ * @note MUST REMAIN UNCHANGED: \b osTimerStart shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osTimerStart(osTimerId timer_id, uint32_t millisec) {
osStatus result = osOK;
#if (configUSE_TIMERS == 1)
portBASE_TYPE taskWoken = pdFALSE;
- TickType_t ticks = millisec / portTICK_PERIOD_MS;
+ TickType_t ticks = millisec / portTICK_PERIOD_MS;
if (ticks == 0)
ticks = 1;
- if (inHandlerMode())
- {
- if (xTimerChangePeriodFromISR(timer_id, ticks, &taskWoken) != pdPASS)
- {
+ if (inHandlerMode()) {
+ if (xTimerChangePeriodFromISR(timer_id, ticks, &taskWoken) != pdPASS) {
result = osErrorOS;
- }
- else
- {
+ } else {
portEND_SWITCHING_ISR(taskWoken);
}
- }
- else
- {
+ } else {
if (xTimerChangePeriod(timer_id, ticks, 0) != pdPASS)
result = osErrorOS;
}
@@ -485,29 +430,23 @@ osStatus osTimerStart(osTimerId timer_id, uint32_t millisec)
}
/**
-* @brief Stop a timer.
-* @param timer_id timer ID obtained by \ref osTimerCreate
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osTimerStop shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osTimerStop(osTimerId timer_id)
-{
+ * @brief Stop a timer.
+ * @param timer_id timer ID obtained by \ref osTimerCreate
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osTimerStop shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osTimerStop(osTimerId timer_id) {
osStatus result = osOK;
#if (configUSE_TIMERS == 1)
portBASE_TYPE taskWoken = pdFALSE;
- if (inHandlerMode())
- {
- if (xTimerStopFromISR(timer_id, &taskWoken) != pdPASS)
- {
+ if (inHandlerMode()) {
+ if (xTimerStopFromISR(timer_id, &taskWoken) != pdPASS) {
return osErrorOS;
}
portEND_SWITCHING_ISR(taskWoken);
- }
- else
- {
- if (xTimerStop(timer_id, 0) != pdPASS)
- {
+ } else {
+ if (xTimerStop(timer_id, 0) != pdPASS) {
result = osErrorOS;
}
}
@@ -518,25 +457,20 @@ osStatus osTimerStop(osTimerId timer_id)
}
/**
-* @brief Delete a timer.
-* @param timer_id timer ID obtained by \ref osTimerCreate
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osTimerDelete shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osTimerDelete(osTimerId timer_id)
-{
+ * @brief Delete a timer.
+ * @param timer_id timer ID obtained by \ref osTimerCreate
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osTimerDelete shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osTimerDelete(osTimerId timer_id) {
osStatus result = osOK;
#if (configUSE_TIMERS == 1)
- if (inHandlerMode())
- {
+ if (inHandlerMode()) {
return osErrorISR;
- }
- else
- {
- if ((xTimerDelete(timer_id, osWaitForever)) != pdPASS)
- {
+ } else {
+ if ((xTimerDelete(timer_id, osWaitForever)) != pdPASS) {
result = osErrorOS;
}
}
@@ -550,26 +484,23 @@ osStatus osTimerDelete(osTimerId timer_id)
/*************************** Signal Management ********************************/
/**
-* @brief Set the specified Signal Flags of an active thread.
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
-* @param signals specifies the signal flags of the thread that should be set.
-* @retval previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters.
-* @note MUST REMAIN UNCHANGED: \b osSignalSet shall be consistent in every CMSIS-RTOS.
-*/
-int32_t osSignalSet(osThreadId thread_id, int32_t signal)
-{
+ * @brief Set the specified Signal Flags of an active thread.
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
+ * @param signals specifies the signal flags of the thread that should be set.
+ * @retval previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters.
+ * @note MUST REMAIN UNCHANGED: \b osSignalSet shall be consistent in every CMSIS-RTOS.
+ */
+int32_t osSignalSet(osThreadId thread_id, int32_t signal) {
#if (configUSE_TASK_NOTIFICATIONS == 1)
- BaseType_t xHigherPriorityTaskWoken = pdFALSE;
- uint32_t ulPreviousNotificationValue = 0;
+ BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+ uint32_t ulPreviousNotificationValue = 0;
- if (inHandlerMode())
- {
+ if (inHandlerMode()) {
if (xTaskGenericNotifyFromISR(thread_id, (uint32_t)signal, eSetBits, &ulPreviousNotificationValue, &xHigherPriorityTaskWoken) != pdPASS)
return 0x80000000;
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
- }
- else if (xTaskGenericNotify(thread_id, (uint32_t)signal, eSetBits, &ulPreviousNotificationValue) != pdPASS)
+ } else if (xTaskGenericNotify(thread_id, (uint32_t)signal, eSetBits, &ulPreviousNotificationValue) != pdPASS)
return 0x80000000;
return ulPreviousNotificationValue;
@@ -582,23 +513,22 @@ int32_t osSignalSet(osThreadId thread_id, int32_t signal)
}
/**
-* @brief Clear the specified Signal Flags of an active thread.
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
-* @param signals specifies the signal flags of the thread that shall be cleared.
-* @retval previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters.
-* @note MUST REMAIN UNCHANGED: \b osSignalClear shall be consistent in every CMSIS-RTOS.
-*/
+ * @brief Clear the specified Signal Flags of an active thread.
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
+ * @param signals specifies the signal flags of the thread that shall be cleared.
+ * @retval previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters.
+ * @note MUST REMAIN UNCHANGED: \b osSignalClear shall be consistent in every CMSIS-RTOS.
+ */
int32_t osSignalClear(osThreadId thread_id, int32_t signal);
/**
-* @brief Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread.
-* @param signals wait until all specified signal flags set or 0 for any single signal flag.
-* @param millisec timeout value or 0 in case of no time-out.
-* @retval event flag information or error code.
-* @note MUST REMAIN UNCHANGED: \b osSignalWait shall be consistent in every CMSIS-RTOS.
-*/
-osEvent osSignalWait(int32_t signals, uint32_t millisec)
-{
+ * @brief Wait for one or more Signal Flags to become signaled for the current \b RUNNING thread.
+ * @param signals wait until all specified signal flags set or 0 for any single signal flag.
+ * @param millisec timeout value or 0 in case of no time-out.
+ * @retval event flag information or error code.
+ * @note MUST REMAIN UNCHANGED: \b osSignalWait shall be consistent in every CMSIS-RTOS.
+ */
+osEvent osSignalWait(int32_t signals, uint32_t millisec) {
osEvent ret;
#if (configUSE_TASK_NOTIFICATIONS == 1)
@@ -606,38 +536,27 @@ osEvent osSignalWait(int32_t signals, uint32_t millisec)
TickType_t ticks;
ret.value.signals = 0;
- ticks = 0;
- if (millisec == osWaitForever)
- {
+ ticks = 0;
+ if (millisec == osWaitForever) {
ticks = portMAX_DELAY;
- }
- else if (millisec != 0)
- {
+ } else if (millisec != 0) {
ticks = millisec / portTICK_PERIOD_MS;
- if (ticks == 0)
- {
+ if (ticks == 0) {
ticks = 1;
}
}
- if (inHandlerMode())
- {
+ if (inHandlerMode()) {
ret.status = osErrorISR; /*Not allowed in ISR*/
- }
- else
- {
- if (xTaskNotifyWait(0, (uint32_t)signals, (uint32_t *)&ret.value.signals, ticks) != pdTRUE)
- {
+ } else {
+ if (xTaskNotifyWait(0, (uint32_t)signals, (uint32_t *)&ret.value.signals, ticks) != pdTRUE) {
if (ticks == 0)
ret.status = osOK;
else
ret.status = osEventTimeout;
- }
- else if (ret.value.signals < 0)
- {
+ } else if (ret.value.signals < 0) {
ret.status = osErrorValue;
- }
- else
+ } else
ret.status = osEventSignal;
}
#else
@@ -652,23 +571,19 @@ osEvent osSignalWait(int32_t signals, uint32_t millisec)
/**************************** Mutex Management ********************************/
/**
-* @brief Create and Initialize a Mutex object
-* @param mutex_def mutex definition referenced with \ref osMutex.
-* @retval mutex ID for reference by other functions or NULL in case of error.
-* @note MUST REMAIN UNCHANGED: \b osMutexCreate shall be consistent in every CMSIS-RTOS.
-*/
-osMutexId osMutexCreate(const osMutexDef_t *mutex_def)
-{
+ * @brief Create and Initialize a Mutex object
+ * @param mutex_def mutex definition referenced with \ref osMutex.
+ * @retval mutex ID for reference by other functions or NULL in case of error.
+ * @note MUST REMAIN UNCHANGED: \b osMutexCreate shall be consistent in every CMSIS-RTOS.
+ */
+osMutexId osMutexCreate(const osMutexDef_t *mutex_def) {
#if (configUSE_MUTEXES == 1)
#if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1)
- if (mutex_def->controlblock != NULL)
- {
+ if (mutex_def->controlblock != NULL) {
return xSemaphoreCreateMutexStatic(mutex_def->controlblock);
- }
- else
- {
+ } else {
return xSemaphoreCreateMutex();
}
#elif (configSUPPORT_STATIC_ALLOCATION == 1)
@@ -682,46 +597,36 @@ osMutexId osMutexCreate(const osMutexDef_t *mutex_def)
}
/**
-* @brief Wait until a Mutex becomes available
-* @param mutex_id mutex ID obtained by \ref osMutexCreate.
-* @param millisec timeout value or 0 in case of no time-out.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osMutexWait shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osMutexWait(osMutexId mutex_id, uint32_t millisec)
-{
- TickType_t ticks;
+ * @brief Wait until a Mutex becomes available
+ * @param mutex_id mutex ID obtained by \ref osMutexCreate.
+ * @param millisec timeout value or 0 in case of no time-out.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osMutexWait shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osMutexWait(osMutexId mutex_id, uint32_t millisec) {
+ TickType_t ticks;
portBASE_TYPE taskWoken = pdFALSE;
- if (mutex_id == NULL)
- {
+ if (mutex_id == NULL) {
return osErrorParameter;
}
ticks = 0;
- if (millisec == osWaitForever)
- {
+ if (millisec == osWaitForever) {
ticks = portMAX_DELAY;
- }
- else if (millisec != 0)
- {
+ } else if (millisec != 0) {
ticks = millisec / portTICK_PERIOD_MS;
- if (ticks == 0)
- {
+ if (ticks == 0) {
ticks = 1;
}
}
- if (inHandlerMode())
- {
- if (xSemaphoreTakeFromISR(mutex_id, &taskWoken) != pdTRUE)
- {
+ if (inHandlerMode()) {
+ if (xSemaphoreTakeFromISR(mutex_id, &taskWoken) != pdTRUE) {
return osErrorOS;
}
portEND_SWITCHING_ISR(taskWoken);
- }
- else if (xSemaphoreTake(mutex_id, ticks) != pdTRUE)
- {
+ } else if (xSemaphoreTake(mutex_id, ticks) != pdTRUE) {
return osErrorOS;
}
@@ -729,41 +634,34 @@ osStatus osMutexWait(osMutexId mutex_id, uint32_t millisec)
}
/**
-* @brief Release a Mutex that was obtained by \ref osMutexWait
-* @param mutex_id mutex ID obtained by \ref osMutexCreate.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osMutexRelease shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osMutexRelease(osMutexId mutex_id)
-{
- osStatus result = osOK;
+ * @brief Release a Mutex that was obtained by \ref osMutexWait
+ * @param mutex_id mutex ID obtained by \ref osMutexCreate.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osMutexRelease shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osMutexRelease(osMutexId mutex_id) {
+ osStatus result = osOK;
portBASE_TYPE taskWoken = pdFALSE;
- if (inHandlerMode())
- {
- if (xSemaphoreGiveFromISR(mutex_id, &taskWoken) != pdTRUE)
- {
+ if (inHandlerMode()) {
+ if (xSemaphoreGiveFromISR(mutex_id, &taskWoken) != pdTRUE) {
return osErrorOS;
}
portEND_SWITCHING_ISR(taskWoken);
- }
- else if (xSemaphoreGive(mutex_id) != pdTRUE)
- {
+ } else if (xSemaphoreGive(mutex_id) != pdTRUE) {
result = osErrorOS;
}
return result;
}
/**
-* @brief Delete a Mutex
-* @param mutex_id mutex ID obtained by \ref osMutexCreate.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osMutexDelete shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osMutexDelete(osMutexId mutex_id)
-{
- if (inHandlerMode())
- {
+ * @brief Delete a Mutex
+ * @param mutex_id mutex ID obtained by \ref osMutexCreate.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osMutexDelete shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osMutexDelete(osMutexId mutex_id) {
+ if (inHandlerMode()) {
return osErrorISR;
}
@@ -777,42 +675,32 @@ osStatus osMutexDelete(osMutexId mutex_id)
#if (defined(osFeature_Semaphore) && (osFeature_Semaphore != 0))
/**
-* @brief Create and Initialize a Semaphore object used for managing resources
-* @param semaphore_def semaphore definition referenced with \ref osSemaphore.
-* @param count number of available resources.
-* @retval semaphore ID for reference by other functions or NULL in case of error.
-* @note MUST REMAIN UNCHANGED: \b osSemaphoreCreate shall be consistent in every CMSIS-RTOS.
-*/
-osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t count)
-{
+ * @brief Create and Initialize a Semaphore object used for managing resources
+ * @param semaphore_def semaphore definition referenced with \ref osSemaphore.
+ * @param count number of available resources.
+ * @retval semaphore ID for reference by other functions or NULL in case of error.
+ * @note MUST REMAIN UNCHANGED: \b osSemaphoreCreate shall be consistent in every CMSIS-RTOS.
+ */
+osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t count) {
#if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1)
osSemaphoreId sema;
- if (semaphore_def->controlblock != NULL)
- {
- if (count == 1)
- {
+ if (semaphore_def->controlblock != NULL) {
+ if (count == 1) {
return xSemaphoreCreateBinaryStatic(semaphore_def->controlblock);
- }
- else
- {
+ } else {
#if (configUSE_COUNTING_SEMAPHORES == 1)
return xSemaphoreCreateCountingStatic(count, count, semaphore_def->controlblock);
#else
return NULL;
#endif
}
- }
- else
- {
- if (count == 1)
- {
+ } else {
+ if (count == 1) {
vSemaphoreCreateBinary(sema);
return sema;
- }
- else
- {
+ } else {
#if (configUSE_COUNTING_SEMAPHORES == 1)
return xSemaphoreCreateCounting(count, count);
#else
@@ -821,12 +709,9 @@ osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t c
}
}
#elif (configSUPPORT_STATIC_ALLOCATION == 1) // configSUPPORT_DYNAMIC_ALLOCATION == 0
- if (count == 1)
- {
+ if (count == 1) {
return xSemaphoreCreateBinaryStatic(semaphore_def->controlblock);
- }
- else
- {
+ } else {
#if (configUSE_COUNTING_SEMAPHORES == 1)
return xSemaphoreCreateCountingStatic(count, count, semaphore_def->controlblock);
#else
@@ -836,13 +721,10 @@ osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t c
#else // configSUPPORT_STATIC_ALLOCATION == 0 && configSUPPORT_DYNAMIC_ALLOCATION == 1
osSemaphoreId sema;
- if (count == 1)
- {
+ if (count == 1) {
vSemaphoreCreateBinary(sema);
return sema;
- }
- else
- {
+ } else {
#if (configUSE_COUNTING_SEMAPHORES == 1)
return xSemaphoreCreateCounting(count, count);
#else
@@ -853,46 +735,36 @@ osSemaphoreId osSemaphoreCreate(const osSemaphoreDef_t *semaphore_def, int32_t c
}
/**
-* @brief Wait until a Semaphore token becomes available
-* @param semaphore_id semaphore object referenced with \ref osSemaphore.
-* @param millisec timeout value or 0 in case of no time-out.
-* @retval number of available tokens, or -1 in case of incorrect parameters.
-* @note MUST REMAIN UNCHANGED: \b osSemaphoreWait shall be consistent in every CMSIS-RTOS.
-*/
-int32_t osSemaphoreWait(osSemaphoreId semaphore_id, uint32_t millisec)
-{
- TickType_t ticks;
+ * @brief Wait until a Semaphore token becomes available
+ * @param semaphore_id semaphore object referenced with \ref osSemaphore.
+ * @param millisec timeout value or 0 in case of no time-out.
+ * @retval number of available tokens, or -1 in case of incorrect parameters.
+ * @note MUST REMAIN UNCHANGED: \b osSemaphoreWait shall be consistent in every CMSIS-RTOS.
+ */
+int32_t osSemaphoreWait(osSemaphoreId semaphore_id, uint32_t millisec) {
+ TickType_t ticks;
portBASE_TYPE taskWoken = pdFALSE;
- if (semaphore_id == NULL)
- {
+ if (semaphore_id == NULL) {
return osErrorParameter;
}
ticks = 0;
- if (millisec == osWaitForever)
- {
+ if (millisec == osWaitForever) {
ticks = portMAX_DELAY;
- }
- else if (millisec != 0)
- {
+ } else if (millisec != 0) {
ticks = millisec / portTICK_PERIOD_MS;
- if (ticks == 0)
- {
+ if (ticks == 0) {
ticks = 1;
}
}
- if (inHandlerMode())
- {
- if (xSemaphoreTakeFromISR(semaphore_id, &taskWoken) != pdTRUE)
- {
+ if (inHandlerMode()) {
+ if (xSemaphoreTakeFromISR(semaphore_id, &taskWoken) != pdTRUE) {
return osErrorOS;
}
portEND_SWITCHING_ISR(taskWoken);
- }
- else if (xSemaphoreTake(semaphore_id, ticks) != pdTRUE)
- {
+ } else if (xSemaphoreTake(semaphore_id, ticks) != pdTRUE) {
return osErrorOS;
}
@@ -900,28 +772,22 @@ int32_t osSemaphoreWait(osSemaphoreId semaphore_id, uint32_t millisec)
}
/**
-* @brief Release a Semaphore token
-* @param semaphore_id semaphore object referenced with \ref osSemaphore.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osSemaphoreRelease shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osSemaphoreRelease(osSemaphoreId semaphore_id)
-{
- osStatus result = osOK;
+ * @brief Release a Semaphore token
+ * @param semaphore_id semaphore object referenced with \ref osSemaphore.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osSemaphoreRelease shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osSemaphoreRelease(osSemaphoreId semaphore_id) {
+ osStatus result = osOK;
portBASE_TYPE taskWoken = pdFALSE;
- if (inHandlerMode())
- {
- if (xSemaphoreGiveFromISR(semaphore_id, &taskWoken) != pdTRUE)
- {
+ if (inHandlerMode()) {
+ if (xSemaphoreGiveFromISR(semaphore_id, &taskWoken) != pdTRUE) {
return osErrorOS;
}
portEND_SWITCHING_ISR(taskWoken);
- }
- else
- {
- if (xSemaphoreGive(semaphore_id) != pdTRUE)
- {
+ } else {
+ if (xSemaphoreGive(semaphore_id) != pdTRUE) {
result = osErrorOS;
}
}
@@ -930,15 +796,13 @@ osStatus osSemaphoreRelease(osSemaphoreId semaphore_id)
}
/**
-* @brief Delete a Semaphore
-* @param semaphore_id semaphore object referenced with \ref osSemaphore.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osSemaphoreDelete shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osSemaphoreDelete(osSemaphoreId semaphore_id)
-{
- if (inHandlerMode())
- {
+ * @brief Delete a Semaphore
+ * @param semaphore_id semaphore object referenced with \ref osSemaphore.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osSemaphoreDelete shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osSemaphoreDelete(osSemaphoreId semaphore_id) {
+ if (inHandlerMode()) {
return osErrorISR;
}
@@ -953,13 +817,12 @@ osStatus osSemaphoreDelete(osSemaphoreId semaphore_id)
#if (defined(osFeature_Pool) && (osFeature_Pool != 0))
-//TODO
-//This is a primitive and inefficient wrapper around the existing FreeRTOS memory management.
-//A better implementation will have to modify heap_x.c!
+// TODO
+// This is a primitive and inefficient wrapper around the existing FreeRTOS memory management.
+// A better implementation will have to modify heap_x.c!
-typedef struct os_pool_cb
-{
- void *pool;
+typedef struct os_pool_cb {
+ void * pool;
uint8_t *markers;
uint32_t pool_sz;
uint32_t item_sz;
@@ -967,51 +830,42 @@ typedef struct os_pool_cb
} os_pool_cb_t;
/**
-* @brief Create and Initialize a memory pool
-* @param pool_def memory pool definition referenced with \ref osPool.
-* @retval memory pool ID for reference by other functions or NULL in case of error.
-* @note MUST REMAIN UNCHANGED: \b osPoolCreate shall be consistent in every CMSIS-RTOS.
-*/
-osPoolId osPoolCreate(const osPoolDef_t *pool_def)
-{
+ * @brief Create and Initialize a memory pool
+ * @param pool_def memory pool definition referenced with \ref osPool.
+ * @retval memory pool ID for reference by other functions or NULL in case of error.
+ * @note MUST REMAIN UNCHANGED: \b osPoolCreate shall be consistent in every CMSIS-RTOS.
+ */
+osPoolId osPoolCreate(const osPoolDef_t *pool_def) {
#if (configSUPPORT_DYNAMIC_ALLOCATION == 1)
osPoolId thePool;
- int itemSize = 4 * ((pool_def->item_sz + 3) / 4);
+ int itemSize = 4 * ((pool_def->item_sz + 3) / 4);
uint32_t i;
/* First have to allocate memory for the pool control block. */
thePool = pvPortMalloc(sizeof(os_pool_cb_t));
- if (thePool)
- {
- thePool->pool_sz = pool_def->pool_sz;
- thePool->item_sz = itemSize;
+ if (thePool) {
+ thePool->pool_sz = pool_def->pool_sz;
+ thePool->item_sz = itemSize;
thePool->currentIndex = 0;
/* Memory for markers */
thePool->markers = pvPortMalloc(pool_def->pool_sz);
- if (thePool->markers)
- {
+ if (thePool->markers) {
/* Now allocate the pool itself. */
thePool->pool = pvPortMalloc(pool_def->pool_sz * itemSize);
- if (thePool->pool)
- {
- for (i = 0; i < pool_def->pool_sz; i++)
- {
+ if (thePool->pool) {
+ for (i = 0; i < pool_def->pool_sz; i++) {
thePool->markers[i] = 0;
}
- }
- else
- {
+ } else {
vPortFree(thePool->markers);
vPortFree(thePool);
thePool = NULL;
}
- }
- else
- {
+ } else {
vPortFree(thePool);
thePool = NULL;
}
@@ -1025,50 +879,40 @@ osPoolId osPoolCreate(const osPoolDef_t *pool_def)
}
/**
-* @brief Allocate a memory block from a memory pool
-* @param pool_id memory pool ID obtain referenced with \ref osPoolCreate.
-* @retval address of the allocated memory block or NULL in case of no memory available.
-* @note MUST REMAIN UNCHANGED: \b osPoolAlloc shall be consistent in every CMSIS-RTOS.
-*/
-void *osPoolAlloc(osPoolId pool_id)
-{
- int dummy = 0;
- void *p = NULL;
+ * @brief Allocate a memory block from a memory pool
+ * @param pool_id memory pool ID obtain referenced with \ref osPoolCreate.
+ * @retval address of the allocated memory block or NULL in case of no memory available.
+ * @note MUST REMAIN UNCHANGED: \b osPoolAlloc shall be consistent in every CMSIS-RTOS.
+ */
+void *osPoolAlloc(osPoolId pool_id) {
+ int dummy = 0;
+ void * p = NULL;
uint32_t i;
uint32_t index;
- if (inHandlerMode())
- {
+ if (inHandlerMode()) {
dummy = portSET_INTERRUPT_MASK_FROM_ISR();
- }
- else
- {
+ } else {
vPortEnterCritical();
}
- for (i = 0; i < pool_id->pool_sz; i++)
- {
+ for (i = 0; i < pool_id->pool_sz; i++) {
index = pool_id->currentIndex + i;
- if (index >= pool_id->pool_sz)
- {
+ if (index >= pool_id->pool_sz) {
index = 0;
}
- if (pool_id->markers[index] == 0)
- {
+ if (pool_id->markers[index] == 0) {
pool_id->markers[index] = 1;
- p = (void *)((uint32_t)(pool_id->pool) + (index * pool_id->item_sz));
- pool_id->currentIndex = index;
+ p = (void *)((uint32_t)(pool_id->pool) + (index * pool_id->item_sz));
+ pool_id->currentIndex = index;
break;
}
}
- if (inHandlerMode())
- {
+ if (inHandlerMode()) {
portCLEAR_INTERRUPT_MASK_FROM_ISR(dummy);
- }
- else
- {
+ } else {
vPortExitCritical();
}
@@ -1076,17 +920,15 @@ void *osPoolAlloc(osPoolId pool_id)
}
/**
-* @brief Allocate a memory block from a memory pool and set memory block to zero
-* @param pool_id memory pool ID obtain referenced with \ref osPoolCreate.
-* @retval address of the allocated memory block or NULL in case of no memory available.
-* @note MUST REMAIN UNCHANGED: \b osPoolCAlloc shall be consistent in every CMSIS-RTOS.
-*/
-void *osPoolCAlloc(osPoolId pool_id)
-{
+ * @brief Allocate a memory block from a memory pool and set memory block to zero
+ * @param pool_id memory pool ID obtain referenced with \ref osPoolCreate.
+ * @retval address of the allocated memory block or NULL in case of no memory available.
+ * @note MUST REMAIN UNCHANGED: \b osPoolCAlloc shall be consistent in every CMSIS-RTOS.
+ */
+void *osPoolCAlloc(osPoolId pool_id) {
void *p = osPoolAlloc(pool_id);
- if (p != NULL)
- {
+ if (p != NULL) {
memset(p, 0, sizeof(pool_id->pool_sz));
}
@@ -1094,39 +936,33 @@ void *osPoolCAlloc(osPoolId pool_id)
}
/**
-* @brief Return an allocated memory block back to a specific memory pool
-* @param pool_id memory pool ID obtain referenced with \ref osPoolCreate.
-* @param block address of the allocated memory block that is returned to the memory pool.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osPoolFree shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osPoolFree(osPoolId pool_id, void *block)
-{
+ * @brief Return an allocated memory block back to a specific memory pool
+ * @param pool_id memory pool ID obtain referenced with \ref osPoolCreate.
+ * @param block address of the allocated memory block that is returned to the memory pool.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osPoolFree shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osPoolFree(osPoolId pool_id, void *block) {
uint32_t index;
- if (pool_id == NULL)
- {
+ if (pool_id == NULL) {
return osErrorParameter;
}
- if (block == NULL)
- {
+ if (block == NULL) {
return osErrorParameter;
}
- if (block < pool_id->pool)
- {
+ if (block < pool_id->pool) {
return osErrorParameter;
}
index = (uint32_t)block - (uint32_t)(pool_id->pool);
- if (index % pool_id->item_sz)
- {
+ if (index % pool_id->item_sz) {
return osErrorParameter;
}
index = index / pool_id->item_sz;
- if (index >= pool_id->pool_sz)
- {
+ if (index >= pool_id->pool_sz) {
return osErrorParameter;
}
@@ -1142,24 +978,20 @@ osStatus osPoolFree(osPoolId pool_id, void *block)
#if (defined(osFeature_MessageQ) && (osFeature_MessageQ != 0)) /* Use Message Queues */
/**
-* @brief Create and Initialize a Message Queue
-* @param queue_def queue definition referenced with \ref osMessageQ.
-* @param thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL.
-* @retval message queue ID for reference by other functions or NULL in case of error.
-* @note MUST REMAIN UNCHANGED: \b osMessageCreate shall be consistent in every CMSIS-RTOS.
-*/
-osMessageQId osMessageCreate(const osMessageQDef_t *queue_def, osThreadId thread_id)
-{
+ * @brief Create and Initialize a Message Queue
+ * @param queue_def queue definition referenced with \ref osMessageQ.
+ * @param thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL.
+ * @retval message queue ID for reference by other functions or NULL in case of error.
+ * @note MUST REMAIN UNCHANGED: \b osMessageCreate shall be consistent in every CMSIS-RTOS.
+ */
+osMessageQId osMessageCreate(const osMessageQDef_t *queue_def, osThreadId thread_id) {
(void)thread_id;
#if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1)
- if ((queue_def->buffer != NULL) && (queue_def->controlblock != NULL))
- {
+ if ((queue_def->buffer != NULL) && (queue_def->controlblock != NULL)) {
return xQueueCreateStatic(queue_def->queue_sz, queue_def->item_sz, queue_def->buffer, queue_def->controlblock);
- }
- else
- {
+ } else {
return xQueueCreate(queue_def->queue_sz, queue_def->item_sz);
}
#elif (configSUPPORT_STATIC_ALLOCATION == 1)
@@ -1170,36 +1002,29 @@ osMessageQId osMessageCreate(const osMessageQDef_t *queue_def, osThreadId thread
}
/**
-* @brief Put a Message to a Queue.
-* @param queue_id message queue ID obtained with \ref osMessageCreate.
-* @param info message information.
-* @param millisec timeout value or 0 in case of no time-out.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osMessagePut(osMessageQId queue_id, uint32_t info, uint32_t millisec)
-{
+ * @brief Put a Message to a Queue.
+ * @param queue_id message queue ID obtained with \ref osMessageCreate.
+ * @param info message information.
+ * @param millisec timeout value or 0 in case of no time-out.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osMessagePut shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osMessagePut(osMessageQId queue_id, uint32_t info, uint32_t millisec) {
portBASE_TYPE taskWoken = pdFALSE;
- TickType_t ticks;
+ TickType_t ticks;
ticks = millisec / portTICK_PERIOD_MS;
- if (ticks == 0)
- {
+ if (ticks == 0) {
ticks = 1;
}
- if (inHandlerMode())
- {
- if (xQueueSendFromISR(queue_id, &info, &taskWoken) != pdTRUE)
- {
+ if (inHandlerMode()) {
+ if (xQueueSendFromISR(queue_id, &info, &taskWoken) != pdTRUE) {
return osErrorOS;
}
portEND_SWITCHING_ISR(taskWoken);
- }
- else
- {
- if (xQueueSend(queue_id, &info, ticks) != pdTRUE)
- {
+ } else {
+ if (xQueueSend(queue_id, &info, ticks) != pdTRUE) {
return osErrorOS;
}
}
@@ -1208,23 +1033,21 @@ osStatus osMessagePut(osMessageQId queue_id, uint32_t info, uint32_t millisec)
}
/**
-* @brief Get a Message or Wait for a Message from a Queue.
-* @param queue_id message queue ID obtained with \ref osMessageCreate.
-* @param millisec timeout value or 0 in case of no time-out.
-* @retval event information that includes status code.
-* @note MUST REMAIN UNCHANGED: \b osMessageGet shall be consistent in every CMSIS-RTOS.
-*/
-osEvent osMessageGet(osMessageQId queue_id, uint32_t millisec)
-{
+ * @brief Get a Message or Wait for a Message from a Queue.
+ * @param queue_id message queue ID obtained with \ref osMessageCreate.
+ * @param millisec timeout value or 0 in case of no time-out.
+ * @retval event information that includes status code.
+ * @note MUST REMAIN UNCHANGED: \b osMessageGet shall be consistent in every CMSIS-RTOS.
+ */
+osEvent osMessageGet(osMessageQId queue_id, uint32_t millisec) {
portBASE_TYPE taskWoken;
- TickType_t ticks;
- osEvent event;
+ TickType_t ticks;
+ osEvent event;
event.def.message_id = queue_id;
- event.value.v = 0;
+ event.value.v = 0;
- if (queue_id == NULL)
- {
+ if (queue_id == NULL) {
event.status = osErrorParameter;
return event;
}
@@ -1232,41 +1055,28 @@ osEvent osMessageGet(osMessageQId queue_id, uint32_t millisec)
taskWoken = pdFALSE;
ticks = 0;
- if (millisec == osWaitForever)
- {
+ if (millisec == osWaitForever) {
ticks = portMAX_DELAY;
- }
- else if (millisec != 0)
- {
+ } else if (millisec != 0) {
ticks = millisec / portTICK_PERIOD_MS;
- if (ticks == 0)
- {
+ if (ticks == 0) {
ticks = 1;
}
}
- if (inHandlerMode())
- {
- if (xQueueReceiveFromISR(queue_id, &event.value.v, &taskWoken) == pdTRUE)
- {
+ if (inHandlerMode()) {
+ if (xQueueReceiveFromISR(queue_id, &event.value.v, &taskWoken) == pdTRUE) {
/* We have mail */
event.status = osEventMessage;
- }
- else
- {
+ } else {
event.status = osOK;
}
portEND_SWITCHING_ISR(taskWoken);
- }
- else
- {
- if (xQueueReceive(queue_id, &event.value.v, ticks) == pdTRUE)
- {
+ } else {
+ if (xQueueReceive(queue_id, &event.value.v, ticks) == pdTRUE) {
/* We have mail */
event.status = osEventMessage;
- }
- else
- {
+ } else {
event.status = (ticks == 0) ? osOK : osEventTimeout;
}
}
@@ -1279,22 +1089,20 @@ osEvent osMessageGet(osMessageQId queue_id, uint32_t millisec)
/******************** Mail Queue Management Functions ***********************/
#if (defined(osFeature_MailQ) && (osFeature_MailQ != 0)) /* Use Mail Queues */
-typedef struct os_mailQ_cb
-{
+typedef struct os_mailQ_cb {
const osMailQDef_t *queue_def;
- QueueHandle_t handle;
- osPoolId pool;
+ QueueHandle_t handle;
+ osPoolId pool;
} os_mailQ_cb_t;
/**
-* @brief Create and Initialize mail queue
-* @param queue_def reference to the mail queue definition obtain with \ref osMailQ
-* @param thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL.
-* @retval mail queue ID for reference by other functions or NULL in case of error.
-* @note MUST REMAIN UNCHANGED: \b osMailCreate shall be consistent in every CMSIS-RTOS.
-*/
-osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id)
-{
+ * @brief Create and Initialize mail queue
+ * @param queue_def reference to the mail queue definition obtain with \ref osMailQ
+ * @param thread_id thread ID (obtained by \ref osThreadCreate or \ref osThreadGetId) or NULL.
+ * @retval mail queue ID for reference by other functions or NULL in case of error.
+ * @note MUST REMAIN UNCHANGED: \b osMailCreate shall be consistent in every CMSIS-RTOS.
+ */
+osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id) {
#if (configSUPPORT_DYNAMIC_ALLOCATION == 1)
(void)thread_id;
@@ -1304,8 +1112,7 @@ osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id)
*(queue_def->cb) = pvPortMalloc(sizeof(struct os_mailQ_cb));
- if (*(queue_def->cb) == NULL)
- {
+ if (*(queue_def->cb) == NULL) {
return NULL;
}
(*(queue_def->cb))->queue_def = queue_def;
@@ -1313,17 +1120,15 @@ osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id)
/* Create a queue in FreeRTOS */
(*(queue_def->cb))->handle = xQueueCreate(queue_def->queue_sz, sizeof(void *));
- if ((*(queue_def->cb))->handle == NULL)
- {
+ if ((*(queue_def->cb))->handle == NULL) {
vPortFree(*(queue_def->cb));
return NULL;
}
/* Create a mail pool */
(*(queue_def->cb))->pool = osPoolCreate(&pool_def);
- if ((*(queue_def->cb))->pool == NULL)
- {
- //TODO: Delete queue. How to do it in FreeRTOS?
+ if ((*(queue_def->cb))->pool == NULL) {
+ // TODO: Delete queue. How to do it in FreeRTOS?
vPortFree(*(queue_def->cb));
return NULL;
}
@@ -1335,19 +1140,17 @@ osMailQId osMailCreate(const osMailQDef_t *queue_def, osThreadId thread_id)
}
/**
-* @brief Allocate a memory block from a mail
-* @param queue_id mail queue ID obtained with \ref osMailCreate.
-* @param millisec timeout value or 0 in case of no time-out.
-* @retval pointer to memory block that can be filled with mail or NULL in case error.
-* @note MUST REMAIN UNCHANGED: \b osMailAlloc shall be consistent in every CMSIS-RTOS.
-*/
-void *osMailAlloc(osMailQId queue_id, uint32_t millisec)
-{
+ * @brief Allocate a memory block from a mail
+ * @param queue_id mail queue ID obtained with \ref osMailCreate.
+ * @param millisec timeout value or 0 in case of no time-out.
+ * @retval pointer to memory block that can be filled with mail or NULL in case error.
+ * @note MUST REMAIN UNCHANGED: \b osMailAlloc shall be consistent in every CMSIS-RTOS.
+ */
+void *osMailAlloc(osMailQId queue_id, uint32_t millisec) {
(void)millisec;
void *p;
- if (queue_id == NULL)
- {
+ if (queue_id == NULL) {
return NULL;
}
@@ -1357,21 +1160,18 @@ void *osMailAlloc(osMailQId queue_id, uint32_t millisec)
}
/**
-* @brief Allocate a memory block from a mail and set memory block to zero
-* @param queue_id mail queue ID obtained with \ref osMailCreate.
-* @param millisec timeout value or 0 in case of no time-out.
-* @retval pointer to memory block that can be filled with mail or NULL in case error.
-* @note MUST REMAIN UNCHANGED: \b osMailCAlloc shall be consistent in every CMSIS-RTOS.
-*/
-void *osMailCAlloc(osMailQId queue_id, uint32_t millisec)
-{
+ * @brief Allocate a memory block from a mail and set memory block to zero
+ * @param queue_id mail queue ID obtained with \ref osMailCreate.
+ * @param millisec timeout value or 0 in case of no time-out.
+ * @retval pointer to memory block that can be filled with mail or NULL in case error.
+ * @note MUST REMAIN UNCHANGED: \b osMailCAlloc shall be consistent in every CMSIS-RTOS.
+ */
+void *osMailCAlloc(osMailQId queue_id, uint32_t millisec) {
uint32_t i;
- void *p = osMailAlloc(queue_id, millisec);
+ void * p = osMailAlloc(queue_id, millisec);
- if (p)
- {
- for (i = 0; i < queue_id->queue_def->item_sz; i++)
- {
+ if (p) {
+ for (i = 0; i < queue_id->queue_def->item_sz; i++) {
((uint8_t *)p)[i] = 0;
}
}
@@ -1380,35 +1180,28 @@ void *osMailCAlloc(osMailQId queue_id, uint32_t millisec)
}
/**
-* @brief Put a mail to a queue
-* @param queue_id mail queue ID obtained with \ref osMailCreate.
-* @param mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osMailPut shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osMailPut(osMailQId queue_id, void *mail)
-{
+ * @brief Put a mail to a queue
+ * @param queue_id mail queue ID obtained with \ref osMailCreate.
+ * @param mail memory block previously allocated with \ref osMailAlloc or \ref osMailCAlloc.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osMailPut shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osMailPut(osMailQId queue_id, void *mail) {
portBASE_TYPE taskWoken;
- if (queue_id == NULL)
- {
+ if (queue_id == NULL) {
return osErrorParameter;
}
taskWoken = pdFALSE;
- if (inHandlerMode())
- {
- if (xQueueSendFromISR(queue_id->handle, &mail, &taskWoken) != pdTRUE)
- {
+ if (inHandlerMode()) {
+ if (xQueueSendFromISR(queue_id->handle, &mail, &taskWoken) != pdTRUE) {
return osErrorOS;
}
portEND_SWITCHING_ISR(taskWoken);
- }
- else
- {
- if (xQueueSend(queue_id->handle, &mail, 0) != pdTRUE)
- {
+ } else {
+ if (xQueueSend(queue_id->handle, &mail, 0) != pdTRUE) {
return osErrorOS;
}
}
@@ -1417,22 +1210,20 @@ osStatus osMailPut(osMailQId queue_id, void *mail)
}
/**
-* @brief Get a mail from a queue
-* @param queue_id mail queue ID obtained with \ref osMailCreate.
-* @param millisec timeout value or 0 in case of no time-out
-* @retval event that contains mail information or error code.
-* @note MUST REMAIN UNCHANGED: \b osMailGet shall be consistent in every CMSIS-RTOS.
-*/
-osEvent osMailGet(osMailQId queue_id, uint32_t millisec)
-{
+ * @brief Get a mail from a queue
+ * @param queue_id mail queue ID obtained with \ref osMailCreate.
+ * @param millisec timeout value or 0 in case of no time-out
+ * @retval event that contains mail information or error code.
+ * @note MUST REMAIN UNCHANGED: \b osMailGet shall be consistent in every CMSIS-RTOS.
+ */
+osEvent osMailGet(osMailQId queue_id, uint32_t millisec) {
portBASE_TYPE taskWoken;
- TickType_t ticks;
- osEvent event;
+ TickType_t ticks;
+ osEvent event;
event.def.mail_id = queue_id;
- if (queue_id == NULL)
- {
+ if (queue_id == NULL) {
event.status = osErrorParameter;
return event;
}
@@ -1440,41 +1231,28 @@ osEvent osMailGet(osMailQId queue_id, uint32_t millisec)
taskWoken = pdFALSE;
ticks = 0;
- if (millisec == osWaitForever)
- {
+ if (millisec == osWaitForever) {
ticks = portMAX_DELAY;
- }
- else if (millisec != 0)
- {
+ } else if (millisec != 0) {
ticks = millisec / portTICK_PERIOD_MS;
- if (ticks == 0)
- {
+ if (ticks == 0) {
ticks = 1;
}
}
- if (inHandlerMode())
- {
- if (xQueueReceiveFromISR(queue_id->handle, &event.value.p, &taskWoken) == pdTRUE)
- {
+ if (inHandlerMode()) {
+ if (xQueueReceiveFromISR(queue_id->handle, &event.value.p, &taskWoken) == pdTRUE) {
/* We have mail */
event.status = osEventMail;
- }
- else
- {
+ } else {
event.status = osOK;
}
portEND_SWITCHING_ISR(taskWoken);
- }
- else
- {
- if (xQueueReceive(queue_id->handle, &event.value.p, ticks) == pdTRUE)
- {
+ } else {
+ if (xQueueReceive(queue_id->handle, &event.value.p, ticks) == pdTRUE) {
/* We have mail */
event.status = osEventMail;
- }
- else
- {
+ } else {
event.status = (ticks == 0) ? osOK : osEventTimeout;
}
}
@@ -1483,16 +1261,14 @@ osEvent osMailGet(osMailQId queue_id, uint32_t millisec)
}
/**
-* @brief Free a memory block from a mail
-* @param queue_id mail queue ID obtained with \ref osMailCreate.
-* @param mail pointer to the memory block that was obtained with \ref osMailGet.
-* @retval status code that indicates the execution status of the function.
-* @note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS.
-*/
-osStatus osMailFree(osMailQId queue_id, void *mail)
-{
- if (queue_id == NULL)
- {
+ * @brief Free a memory block from a mail
+ * @param queue_id mail queue ID obtained with \ref osMailCreate.
+ * @param mail pointer to the memory block that was obtained with \ref osMailGet.
+ * @retval status code that indicates the execution status of the function.
+ * @note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS.
+ */
+osStatus osMailFree(osMailQId queue_id, void *mail) {
+ if (queue_id == NULL) {
return osErrorParameter;
}
@@ -1502,16 +1278,14 @@ osStatus osMailFree(osMailQId queue_id, void *mail)
/*************************** Additional specific APIs to Free RTOS ************/
/**
-* @brief Handles the tick increment
-* @param none.
-* @retval none.
-*/
-void osSystickHandler(void)
-{
+ * @brief Handles the tick increment
+ * @param none.
+ * @retval none.
+ */
+void osSystickHandler(void) {
#if (INCLUDE_xTaskGetSchedulerState == 1)
- if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED)
- {
+ if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) {
#endif /* INCLUDE_xTaskGetSchedulerState */
xPortSysTickHandler();
#if (INCLUDE_xTaskGetSchedulerState == 1)
@@ -1521,19 +1295,17 @@ void osSystickHandler(void)
#if (INCLUDE_eTaskGetState == 1)
/**
-* @brief Obtain the state of any thread.
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
-* @retval the stae of the thread, states are encoded by the osThreadState enumerated type.
-*/
-osThreadState osThreadGetState(osThreadId thread_id)
-{
- eTaskState ThreadState;
+ * @brief Obtain the state of any thread.
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
+ * @retval the stae of the thread, states are encoded by the osThreadState enumerated type.
+ */
+osThreadState osThreadGetState(osThreadId thread_id) {
+ eTaskState ThreadState;
osThreadState result;
ThreadState = eTaskGetState(thread_id);
- switch (ThreadState)
- {
+ switch (ThreadState) {
case eRunning:
result = osThreadRunning;
break;
@@ -1559,12 +1331,11 @@ osThreadState osThreadGetState(osThreadId thread_id)
#if (INCLUDE_eTaskGetState == 1)
/**
-* @brief Check if a thread is already suspended or not.
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osThreadIsSuspended(osThreadId thread_id)
-{
+ * @brief Check if a thread is already suspended or not.
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osThreadIsSuspended(osThreadId thread_id) {
if (eTaskGetState(thread_id) == eSuspended)
return osOK;
else
@@ -1572,12 +1343,11 @@ osStatus osThreadIsSuspended(osThreadId thread_id)
}
#endif /* INCLUDE_eTaskGetState */
/**
-* @brief Suspend execution of a thread.
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osThreadSuspend(osThreadId thread_id)
-{
+ * @brief Suspend execution of a thread.
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osThreadSuspend(osThreadId thread_id) {
#if (INCLUDE_vTaskSuspend == 1)
vTaskSuspend(thread_id);
@@ -1588,22 +1358,17 @@ osStatus osThreadSuspend(osThreadId thread_id)
}
/**
-* @brief Resume execution of a suspended thread.
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osThreadResume(osThreadId thread_id)
-{
+ * @brief Resume execution of a suspended thread.
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId.
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osThreadResume(osThreadId thread_id) {
#if (INCLUDE_vTaskSuspend == 1)
- if (inHandlerMode())
- {
- if (xTaskResumeFromISR(thread_id) == pdTRUE)
- {
+ if (inHandlerMode()) {
+ if (xTaskResumeFromISR(thread_id) == pdTRUE) {
portYIELD_FROM_ISR(pdTRUE);
}
- }
- else
- {
+ } else {
vTaskResume(thread_id);
}
return osOK;
@@ -1613,22 +1378,20 @@ osStatus osThreadResume(osThreadId thread_id)
}
/**
-* @brief Suspend execution of a all active threads.
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osThreadSuspendAll(void)
-{
+ * @brief Suspend execution of a all active threads.
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osThreadSuspendAll(void) {
vTaskSuspendAll();
return osOK;
}
/**
-* @brief Resume execution of a all suspended threads.
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osThreadResumeAll(void)
-{
+ * @brief Resume execution of a all suspended threads.
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osThreadResumeAll(void) {
if (xTaskResumeAll() == pdTRUE)
return osOK;
else
@@ -1636,15 +1399,14 @@ osStatus osThreadResumeAll(void)
}
/**
-* @brief Delay a task until a specified time
-* @param PreviousWakeTime Pointer to a variable that holds the time at which the
-* task was last unblocked. PreviousWakeTime must be initialised with the current time
-* prior to its first use (PreviousWakeTime = osKernelSysTick() )
-* @param millisec time delay value
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osDelayUntil(uint32_t *PreviousWakeTime, uint32_t millisec)
-{
+ * @brief Delay a task until a specified time
+ * @param PreviousWakeTime Pointer to a variable that holds the time at which the
+ * task was last unblocked. PreviousWakeTime must be initialised with the current time
+ * prior to its first use (PreviousWakeTime = osKernelSysTick() )
+ * @param millisec time delay value
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osDelayUntil(uint32_t *PreviousWakeTime, uint32_t millisec) {
#if INCLUDE_vTaskDelayUntil
TickType_t ticks = (millisec / portTICK_PERIOD_MS);
vTaskDelayUntil((TickType_t *)PreviousWakeTime, ticks ? ticks : 1);
@@ -1659,12 +1421,11 @@ osStatus osDelayUntil(uint32_t *PreviousWakeTime, uint32_t millisec)
}
/**
-* @brief Abort the delay for a specific thread
-* @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osAbortDelay(osThreadId thread_id)
-{
+ * @brief Abort the delay for a specific thread
+ * @param thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osAbortDelay(osThreadId thread_id) {
#if INCLUDE_xTaskAbortDelay
xTaskAbortDelay(thread_id);
@@ -1678,14 +1439,13 @@ osStatus osAbortDelay(osThreadId thread_id)
}
/**
-* @brief Lists all the current threads, along with their current state
-* and stack usage high water mark.
-* @param buffer A buffer into which the above mentioned details
-* will be written
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osThreadList(uint8_t *buffer)
-{
+ * @brief Lists all the current threads, along with their current state
+ * and stack usage high water mark.
+ * @param buffer A buffer into which the above mentioned details
+ * will be written
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osThreadList(uint8_t *buffer) {
#if ((configUSE_TRACE_FACILITY == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS == 1))
vTaskList((char *)buffer);
#endif
@@ -1693,45 +1453,36 @@ osStatus osThreadList(uint8_t *buffer)
}
/**
-* @brief Receive an item from a queue without removing the item from the queue.
-* @param queue_id message queue ID obtained with \ref osMessageCreate.
-* @param millisec timeout value or 0 in case of no time-out.
-* @retval event information that includes status code.
-*/
-osEvent osMessagePeek(osMessageQId queue_id, uint32_t millisec)
-{
+ * @brief Receive an item from a queue without removing the item from the queue.
+ * @param queue_id message queue ID obtained with \ref osMessageCreate.
+ * @param millisec timeout value or 0 in case of no time-out.
+ * @retval event information that includes status code.
+ */
+osEvent osMessagePeek(osMessageQId queue_id, uint32_t millisec) {
TickType_t ticks;
- osEvent event;
+ osEvent event;
event.def.message_id = queue_id;
- if (queue_id == NULL)
- {
+ if (queue_id == NULL) {
event.status = osErrorParameter;
return event;
}
ticks = 0;
- if (millisec == osWaitForever)
- {
+ if (millisec == osWaitForever) {
ticks = portMAX_DELAY;
- }
- else if (millisec != 0)
- {
+ } else if (millisec != 0) {
ticks = millisec / portTICK_PERIOD_MS;
- if (ticks == 0)
- {
+ if (ticks == 0) {
ticks = 1;
}
}
- if (xQueuePeek(queue_id, &event.value.v, ticks) == pdTRUE)
- {
+ if (xQueuePeek(queue_id, &event.value.v, ticks) == pdTRUE) {
/* We have mail */
event.status = osEventMessage;
- }
- else
- {
+ } else {
event.status = (ticks == 0) ? osOK : osEventTimeout;
}
@@ -1739,41 +1490,32 @@ osEvent osMessagePeek(osMessageQId queue_id, uint32_t millisec)
}
/**
-* @brief Get the number of messaged stored in a queue.
-* @param queue_id message queue ID obtained with \ref osMessageCreate.
-* @retval number of messages stored in a queue.
-*/
-uint32_t osMessageWaiting(osMessageQId queue_id)
-{
- if (inHandlerMode())
- {
+ * @brief Get the number of messaged stored in a queue.
+ * @param queue_id message queue ID obtained with \ref osMessageCreate.
+ * @retval number of messages stored in a queue.
+ */
+uint32_t osMessageWaiting(osMessageQId queue_id) {
+ if (inHandlerMode()) {
return uxQueueMessagesWaitingFromISR(queue_id);
- }
- else
- {
+ } else {
return uxQueueMessagesWaiting(queue_id);
}
}
/**
-* @brief Get the available space in a message queue.
-* @param queue_id message queue ID obtained with \ref osMessageCreate.
-* @retval available space in a message queue.
-*/
-uint32_t osMessageAvailableSpace(osMessageQId queue_id)
-{
- return uxQueueSpacesAvailable(queue_id);
-}
+ * @brief Get the available space in a message queue.
+ * @param queue_id message queue ID obtained with \ref osMessageCreate.
+ * @retval available space in a message queue.
+ */
+uint32_t osMessageAvailableSpace(osMessageQId queue_id) { return uxQueueSpacesAvailable(queue_id); }
/**
-* @brief Delete a Message Queue
-* @param queue_id message queue ID obtained with \ref osMessageCreate.
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osMessageDelete(osMessageQId queue_id)
-{
- if (inHandlerMode())
- {
+ * @brief Delete a Message Queue
+ * @param queue_id message queue ID obtained with \ref osMessageCreate.
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osMessageDelete(osMessageQId queue_id) {
+ if (inHandlerMode()) {
return osErrorISR;
}
@@ -1783,21 +1525,17 @@ osStatus osMessageDelete(osMessageQId queue_id)
}
/**
-* @brief Create and Initialize a Recursive Mutex
-* @param mutex_def mutex definition referenced with \ref osMutex.
-* @retval mutex ID for reference by other functions or NULL in case of error..
-*/
-osMutexId osRecursiveMutexCreate(const osMutexDef_t *mutex_def)
-{
+ * @brief Create and Initialize a Recursive Mutex
+ * @param mutex_def mutex definition referenced with \ref osMutex.
+ * @retval mutex ID for reference by other functions or NULL in case of error..
+ */
+osMutexId osRecursiveMutexCreate(const osMutexDef_t *mutex_def) {
#if (configUSE_RECURSIVE_MUTEXES == 1)
#if (configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1)
- if (mutex_def->controlblock != NULL)
- {
+ if (mutex_def->controlblock != NULL) {
return xSemaphoreCreateRecursiveMutexStatic(mutex_def->controlblock);
- }
- else
- {
+ } else {
return xSemaphoreCreateRecursiveMutex();
}
#elif (configSUPPORT_STATIC_ALLOCATION == 1)
@@ -1811,17 +1549,15 @@ osMutexId osRecursiveMutexCreate(const osMutexDef_t *mutex_def)
}
/**
-* @brief Release a Recursive Mutex
-* @param mutex_id mutex ID obtained by \ref osRecursiveMutexCreate.
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osRecursiveMutexRelease(osMutexId mutex_id)
-{
+ * @brief Release a Recursive Mutex
+ * @param mutex_id mutex ID obtained by \ref osRecursiveMutexCreate.
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osRecursiveMutexRelease(osMutexId mutex_id) {
#if (configUSE_RECURSIVE_MUTEXES == 1)
osStatus result = osOK;
- if (xSemaphoreGiveRecursive(mutex_id) != pdTRUE)
- {
+ if (xSemaphoreGiveRecursive(mutex_id) != pdTRUE) {
result = osErrorOS;
}
return result;
@@ -1831,37 +1567,30 @@ osStatus osRecursiveMutexRelease(osMutexId mutex_id)
}
/**
-* @brief Release a Recursive Mutex
-* @param mutex_id mutex ID obtained by \ref osRecursiveMutexCreate.
-* @param millisec timeout value or 0 in case of no time-out.
-* @retval status code that indicates the execution status of the function.
-*/
-osStatus osRecursiveMutexWait(osMutexId mutex_id, uint32_t millisec)
-{
+ * @brief Release a Recursive Mutex
+ * @param mutex_id mutex ID obtained by \ref osRecursiveMutexCreate.
+ * @param millisec timeout value or 0 in case of no time-out.
+ * @retval status code that indicates the execution status of the function.
+ */
+osStatus osRecursiveMutexWait(osMutexId mutex_id, uint32_t millisec) {
#if (configUSE_RECURSIVE_MUTEXES == 1)
TickType_t ticks;
- if (mutex_id == NULL)
- {
+ if (mutex_id == NULL) {
return osErrorParameter;
}
ticks = 0;
- if (millisec == osWaitForever)
- {
+ if (millisec == osWaitForever) {
ticks = portMAX_DELAY;
- }
- else if (millisec != 0)
- {
+ } else if (millisec != 0) {
ticks = millisec / portTICK_PERIOD_MS;
- if (ticks == 0)
- {
+ if (ticks == 0) {
ticks = 1;
}
}
- if (xSemaphoreTakeRecursive(mutex_id, ticks) != pdTRUE)
- {
+ if (xSemaphoreTakeRecursive(mutex_id, ticks) != pdTRUE) {
return osErrorOS;
}
return osOK;
@@ -1871,11 +1600,8 @@ osStatus osRecursiveMutexWait(osMutexId mutex_id, uint32_t millisec)
}
/**
-* @brief Returns the current count value of a counting semaphore
-* @param semaphore_id semaphore_id ID obtained by \ref osSemaphoreCreate.
-* @retval count value
-*/
-uint32_t osSemaphoreGetCount(osSemaphoreId semaphore_id)
-{
- return uxSemaphoreGetCount(semaphore_id);
-}
+ * @brief Returns the current count value of a counting semaphore
+ * @param semaphore_id semaphore_id ID obtained by \ref osSemaphoreCreate.
+ * @retval count value
+ */
+uint32_t osSemaphoreGetCount(osSemaphoreId semaphore_id) { return uxSemaphoreGetCount(semaphore_id); }
diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/croutine.c b/source/Middlewares/Third_Party/FreeRTOS/Source/croutine.c
index 507e2179..1809abbc 100644
--- a/source/Middlewares/Third_Party/FreeRTOS/Source/croutine.c
+++ b/source/Middlewares/Third_Party/FreeRTOS/Source/croutine.c
@@ -25,37 +25,37 @@
* 1 tab == 4 spaces!
*/
+#include "croutine.h"
#include "FreeRTOS.h"
#include "task.h"
-#include "croutine.h"
/* Remove the whole file is co-routines are not being used. */
-#if( configUSE_CO_ROUTINES != 0 )
+#if (configUSE_CO_ROUTINES != 0)
/*
* Some kernel aware debuggers require data to be viewed to be global, rather
* than file scope.
*/
#ifdef portREMOVE_STATIC_QUALIFIER
- #define static
+#define static
#endif
-
/* Lists for ready and blocked co-routines. --------------------*/
-static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ]; /*< Prioritised ready co-routines. */
-static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */
-static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */
-static List_t * pxDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used. */
-static List_t * pxOverflowDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */
-static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */
+static List_t pxReadyCoRoutineLists[configMAX_CO_ROUTINE_PRIORITIES]; /*< Prioritised ready co-routines. */
+static List_t xDelayedCoRoutineList1; /*< Delayed co-routines. */
+static List_t xDelayedCoRoutineList2; /*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */
+static List_t *pxDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used. */
+static List_t *pxOverflowDelayedCoRoutineList; /*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */
+static List_t xPendingReadyCoRoutineList; /*< Holds co-routines that have been readied by an external event. They cannot be added directly to the ready lists as the ready lists cannot be accessed by
+ interrupts. */
/* Other file private variables. --------------------------------*/
-CRCB_t * pxCurrentCoRoutine = NULL;
+CRCB_t * pxCurrentCoRoutine = NULL;
static UBaseType_t uxTopCoRoutineReadyPriority = 0;
-static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0;
+static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0;
/* The initial state of the co-routine when it is created. */
-#define corINITIAL_STATE ( 0 )
+#define corINITIAL_STATE (0)
/*
* Place the co-routine represented by pxCRCB into the appropriate ready queue
@@ -64,20 +64,19 @@ static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0;
* This macro accesses the co-routine ready lists and therefore must not be
* used from within an ISR.
*/
-#define prvAddCoRoutineToReadyQueue( pxCRCB ) \
-{ \
- if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority ) \
- { \
- uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \
- } \
- vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) ); \
-}
+#define prvAddCoRoutineToReadyQueue(pxCRCB) \
+ { \
+ if (pxCRCB->uxPriority > uxTopCoRoutineReadyPriority) { \
+ uxTopCoRoutineReadyPriority = pxCRCB->uxPriority; \
+ } \
+ vListInsertEnd((List_t *)&(pxReadyCoRoutineLists[pxCRCB->uxPriority]), &(pxCRCB->xGenericListItem)); \
+ }
/*
* Utility to ready all the lists used by the scheduler. This is called
* automatically upon the creation of the first co-routine.
*/
-static void prvInitialiseCoRoutineLists( void );
+static void prvInitialiseCoRoutineLists(void);
/*
* Co-routines that are readied by an interrupt cannot be placed directly into
@@ -85,7 +84,7 @@ static void prvInitialiseCoRoutineLists( void );
* in the pending ready list in order that they can later be moved to the ready
* list by the co-routine scheduler.
*/
-static void prvCheckPendingReadyList( void );
+static void prvCheckPendingReadyList(void);
/*
* Macro that looks at the list of co-routines that are currently delayed to
@@ -95,259 +94,230 @@ static void prvCheckPendingReadyList( void );
* meaning once one co-routine has been found whose timer has not expired
* we need not look any further down the list.
*/
-static void prvCheckDelayedList( void );
+static void prvCheckDelayedList(void);
/*-----------------------------------------------------------*/
-BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex )
-{
-BaseType_t xReturn;
-CRCB_t *pxCoRoutine;
-
- /* Allocate the memory that will store the co-routine control block. */
- pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) );
- if( pxCoRoutine )
- {
- /* If pxCurrentCoRoutine is NULL then this is the first co-routine to
- be created and the co-routine data structures need initialising. */
- if( pxCurrentCoRoutine == NULL )
- {
- pxCurrentCoRoutine = pxCoRoutine;
- prvInitialiseCoRoutineLists();
- }
-
- /* Check the priority is within limits. */
- if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES )
- {
- uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1;
- }
-
- /* Fill out the co-routine control block from the function parameters. */
- pxCoRoutine->uxState = corINITIAL_STATE;
- pxCoRoutine->uxPriority = uxPriority;
- pxCoRoutine->uxIndex = uxIndex;
- pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode;
-
- /* Initialise all the other co-routine control block parameters. */
- vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) );
- vListInitialiseItem( &( pxCoRoutine->xEventListItem ) );
-
- /* Set the co-routine control block as a link back from the ListItem_t.
- This is so we can get back to the containing CRCB from a generic item
- in a list. */
- listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine );
- listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine );
-
- /* Event lists are always in priority order. */
- listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) );
-
- /* Now the co-routine has been initialised it can be added to the ready
- list at the correct priority. */
- prvAddCoRoutineToReadyQueue( pxCoRoutine );
-
- xReturn = pdPASS;
- }
- else
- {
- xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
- }
-
- return xReturn;
+BaseType_t xCoRoutineCreate(crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex) {
+ BaseType_t xReturn;
+ CRCB_t * pxCoRoutine;
+
+ /* Allocate the memory that will store the co-routine control block. */
+ pxCoRoutine = (CRCB_t *)pvPortMalloc(sizeof(CRCB_t));
+ if (pxCoRoutine) {
+ /* If pxCurrentCoRoutine is NULL then this is the first co-routine to
+ be created and the co-routine data structures need initialising. */
+ if (pxCurrentCoRoutine == NULL) {
+ pxCurrentCoRoutine = pxCoRoutine;
+ prvInitialiseCoRoutineLists();
+ }
+
+ /* Check the priority is within limits. */
+ if (uxPriority >= configMAX_CO_ROUTINE_PRIORITIES) {
+ uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1;
+ }
+
+ /* Fill out the co-routine control block from the function parameters. */
+ pxCoRoutine->uxState = corINITIAL_STATE;
+ pxCoRoutine->uxPriority = uxPriority;
+ pxCoRoutine->uxIndex = uxIndex;
+ pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode;
+
+ /* Initialise all the other co-routine control block parameters. */
+ vListInitialiseItem(&(pxCoRoutine->xGenericListItem));
+ vListInitialiseItem(&(pxCoRoutine->xEventListItem));
+
+ /* Set the co-routine control block as a link back from the ListItem_t.
+ This is so we can get back to the containing CRCB from a generic item
+ in a list. */
+ listSET_LIST_ITEM_OWNER(&(pxCoRoutine->xGenericListItem), pxCoRoutine);
+ listSET_LIST_ITEM_OWNER(&(pxCoRoutine->xEventListItem), pxCoRoutine);
+
+ /* Event lists are always in priority order. */
+ listSET_LIST_ITEM_VALUE(&(pxCoRoutine->xEventListItem), ((TickType_t)configMAX_CO_ROUTINE_PRIORITIES - (TickType_t)uxPriority));
+
+ /* Now the co-routine has been initialised it can be added to the ready
+ list at the correct priority. */
+ prvAddCoRoutineToReadyQueue(pxCoRoutine);
+
+ xReturn = pdPASS;
+ } else {
+ xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
+ }
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList )
-{
-TickType_t xTimeToWake;
-
- /* Calculate the time to wake - this may overflow but this is
- not a problem. */
- xTimeToWake = xCoRoutineTickCount + xTicksToDelay;
-
- /* We must remove ourselves from the ready list before adding
- ourselves to the blocked list as the same list item is used for
- both lists. */
- ( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
-
- /* The list item will be inserted in wake time order. */
- listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake );
-
- if( xTimeToWake < xCoRoutineTickCount )
- {
- /* Wake time has overflowed. Place this item in the
- overflow list. */
- vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
- }
- else
- {
- /* The wake time has not overflowed, so we can use the
- current block list. */
- vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
- }
-
- if( pxEventList )
- {
- /* Also add the co-routine to an event list. If this is done then the
- function must be called with interrupts disabled. */
- vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) );
- }
+void vCoRoutineAddToDelayedList(TickType_t xTicksToDelay, List_t *pxEventList) {
+ TickType_t xTimeToWake;
+
+ /* Calculate the time to wake - this may overflow but this is
+ not a problem. */
+ xTimeToWake = xCoRoutineTickCount + xTicksToDelay;
+
+ /* We must remove ourselves from the ready list before adding
+ ourselves to the blocked list as the same list item is used for
+ both lists. */
+ (void)uxListRemove((ListItem_t *)&(pxCurrentCoRoutine->xGenericListItem));
+
+ /* The list item will be inserted in wake time order. */
+ listSET_LIST_ITEM_VALUE(&(pxCurrentCoRoutine->xGenericListItem), xTimeToWake);
+
+ if (xTimeToWake < xCoRoutineTickCount) {
+ /* Wake time has overflowed. Place this item in the
+ overflow list. */
+ vListInsert((List_t *)pxOverflowDelayedCoRoutineList, (ListItem_t *)&(pxCurrentCoRoutine->xGenericListItem));
+ } else {
+ /* The wake time has not overflowed, so we can use the
+ current block list. */
+ vListInsert((List_t *)pxDelayedCoRoutineList, (ListItem_t *)&(pxCurrentCoRoutine->xGenericListItem));
+ }
+
+ if (pxEventList) {
+ /* Also add the co-routine to an event list. If this is done then the
+ function must be called with interrupts disabled. */
+ vListInsert(pxEventList, &(pxCurrentCoRoutine->xEventListItem));
+ }
}
/*-----------------------------------------------------------*/
-static void prvCheckPendingReadyList( void )
-{
- /* Are there any co-routines waiting to get moved to the ready list? These
- are co-routines that have been readied by an ISR. The ISR cannot access
- the ready lists itself. */
- while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE )
- {
- CRCB_t *pxUnblockedCRCB;
-
- /* The pending ready list can be accessed by an ISR. */
- portDISABLE_INTERRUPTS();
- {
- pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( (&xPendingReadyCoRoutineList) );
- ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );
- }
- portENABLE_INTERRUPTS();
-
- ( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) );
- prvAddCoRoutineToReadyQueue( pxUnblockedCRCB );
- }
+static void prvCheckPendingReadyList(void) {
+ /* Are there any co-routines waiting to get moved to the ready list? These
+ are co-routines that have been readied by an ISR. The ISR cannot access
+ the ready lists itself. */
+ while (listLIST_IS_EMPTY(&xPendingReadyCoRoutineList) == pdFALSE) {
+ CRCB_t *pxUnblockedCRCB;
+
+ /* The pending ready list can be accessed by an ISR. */
+ portDISABLE_INTERRUPTS();
+ {
+ pxUnblockedCRCB = (CRCB_t *)listGET_OWNER_OF_HEAD_ENTRY((&xPendingReadyCoRoutineList));
+ (void)uxListRemove(&(pxUnblockedCRCB->xEventListItem));
+ }
+ portENABLE_INTERRUPTS();
+
+ (void)uxListRemove(&(pxUnblockedCRCB->xGenericListItem));
+ prvAddCoRoutineToReadyQueue(pxUnblockedCRCB);
+ }
}
/*-----------------------------------------------------------*/
-static void prvCheckDelayedList( void )
-{
-CRCB_t *pxCRCB;
-
- xPassedTicks = xTaskGetTickCount() - xLastTickCount;
- while( xPassedTicks )
- {
- xCoRoutineTickCount++;
- xPassedTicks--;
-
- /* If the tick count has overflowed we need to swap the ready lists. */
- if( xCoRoutineTickCount == 0 )
- {
- List_t * pxTemp;
-
- /* Tick count has overflowed so we need to swap the delay lists. If there are
- any items in pxDelayedCoRoutineList here then there is an error! */
- pxTemp = pxDelayedCoRoutineList;
- pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList;
- pxOverflowDelayedCoRoutineList = pxTemp;
- }
-
- /* See if this tick has made a timeout expire. */
- while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE )
- {
- pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList );
-
- if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) )
- {
- /* Timeout not yet expired. */
- break;
- }
-
- portDISABLE_INTERRUPTS();
- {
- /* The event could have occurred just before this critical
- section. If this is the case then the generic list item will
- have been moved to the pending ready list and the following
- line is still valid. Also the pvContainer parameter will have
- been set to NULL so the following lines are also valid. */
- ( void ) uxListRemove( &( pxCRCB->xGenericListItem ) );
-
- /* Is the co-routine waiting on an event also? */
- if( pxCRCB->xEventListItem.pxContainer )
- {
- ( void ) uxListRemove( &( pxCRCB->xEventListItem ) );
- }
- }
- portENABLE_INTERRUPTS();
-
- prvAddCoRoutineToReadyQueue( pxCRCB );
- }
- }
-
- xLastTickCount = xCoRoutineTickCount;
+static void prvCheckDelayedList(void) {
+ CRCB_t *pxCRCB;
+
+ xPassedTicks = xTaskGetTickCount() - xLastTickCount;
+ while (xPassedTicks) {
+ xCoRoutineTickCount++;
+ xPassedTicks--;
+
+ /* If the tick count has overflowed we need to swap the ready lists. */
+ if (xCoRoutineTickCount == 0) {
+ List_t *pxTemp;
+
+ /* Tick count has overflowed so we need to swap the delay lists. If there are
+ any items in pxDelayedCoRoutineList here then there is an error! */
+ pxTemp = pxDelayedCoRoutineList;
+ pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList;
+ pxOverflowDelayedCoRoutineList = pxTemp;
+ }
+
+ /* See if this tick has made a timeout expire. */
+ while (listLIST_IS_EMPTY(pxDelayedCoRoutineList) == pdFALSE) {
+ pxCRCB = (CRCB_t *)listGET_OWNER_OF_HEAD_ENTRY(pxDelayedCoRoutineList);
+
+ if (xCoRoutineTickCount < listGET_LIST_ITEM_VALUE(&(pxCRCB->xGenericListItem))) {
+ /* Timeout not yet expired. */
+ break;
+ }
+
+ portDISABLE_INTERRUPTS();
+ {
+ /* The event could have occurred just before this critical
+ section. If this is the case then the generic list item will
+ have been moved to the pending ready list and the following
+ line is still valid. Also the pvContainer parameter will have
+ been set to NULL so the following lines are also valid. */
+ (void)uxListRemove(&(pxCRCB->xGenericListItem));
+
+ /* Is the co-routine waiting on an event also? */
+ if (pxCRCB->xEventListItem.pxContainer) {
+ (void)uxListRemove(&(pxCRCB->xEventListItem));
+ }
+ }
+ portENABLE_INTERRUPTS();
+
+ prvAddCoRoutineToReadyQueue(pxCRCB);
+ }
+ }
+
+ xLastTickCount = xCoRoutineTickCount;
}
/*-----------------------------------------------------------*/
-void vCoRoutineSchedule( void )
-{
- /* See if any co-routines readied by events need moving to the ready lists. */
- prvCheckPendingReadyList();
-
- /* See if any delayed co-routines have timed out. */
- prvCheckDelayedList();
-
- /* Find the highest priority queue that contains ready co-routines. */
- while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) )
- {
- if( uxTopCoRoutineReadyPriority == 0 )
- {
- /* No more co-routines to check. */
- return;
- }
- --uxTopCoRoutineReadyPriority;
- }
-
- /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines
- of the same priority get an equal share of the processor time. */
- listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) );
-
- /* Call the co-routine. */
- ( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex );
-
- return;
+void vCoRoutineSchedule(void) {
+ /* See if any co-routines readied by events need moving to the ready lists. */
+ prvCheckPendingReadyList();
+
+ /* See if any delayed co-routines have timed out. */
+ prvCheckDelayedList();
+
+ /* Find the highest priority queue that contains ready co-routines. */
+ while (listLIST_IS_EMPTY(&(pxReadyCoRoutineLists[uxTopCoRoutineReadyPriority]))) {
+ if (uxTopCoRoutineReadyPriority == 0) {
+ /* No more co-routines to check. */
+ return;
+ }
+ --uxTopCoRoutineReadyPriority;
+ }
+
+ /* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines
+ of the same priority get an equal share of the processor time. */
+ listGET_OWNER_OF_NEXT_ENTRY(pxCurrentCoRoutine, &(pxReadyCoRoutineLists[uxTopCoRoutineReadyPriority]));
+
+ /* Call the co-routine. */
+ (pxCurrentCoRoutine->pxCoRoutineFunction)(pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex);
+
+ return;
}
/*-----------------------------------------------------------*/
-static void prvInitialiseCoRoutineLists( void )
-{
-UBaseType_t uxPriority;
+static void prvInitialiseCoRoutineLists(void) {
+ UBaseType_t uxPriority;
- for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ )
- {
- vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) );
- }
+ for (uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++) {
+ vListInitialise((List_t *)&(pxReadyCoRoutineLists[uxPriority]));
+ }
- vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 );
- vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 );
- vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList );
+ vListInitialise((List_t *)&xDelayedCoRoutineList1);
+ vListInitialise((List_t *)&xDelayedCoRoutineList2);
+ vListInitialise((List_t *)&xPendingReadyCoRoutineList);
- /* Start with pxDelayedCoRoutineList using list1 and the
- pxOverflowDelayedCoRoutineList using list2. */
- pxDelayedCoRoutineList = &xDelayedCoRoutineList1;
- pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2;
+ /* Start with pxDelayedCoRoutineList using list1 and the
+ pxOverflowDelayedCoRoutineList using list2. */
+ pxDelayedCoRoutineList = &xDelayedCoRoutineList1;
+ pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2;
}
/*-----------------------------------------------------------*/
-BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList )
-{
-CRCB_t *pxUnblockedCRCB;
-BaseType_t xReturn;
-
- /* This function is called from within an interrupt. It can only access
- event lists and the pending ready list. This function assumes that a
- check has already been made to ensure pxEventList is not empty. */
- pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList );
- ( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );
- vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) );
-
- if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority )
- {
- xReturn = pdTRUE;
- }
- else
- {
- xReturn = pdFALSE;
- }
-
- return xReturn;
+BaseType_t xCoRoutineRemoveFromEventList(const List_t *pxEventList) {
+ CRCB_t * pxUnblockedCRCB;
+ BaseType_t xReturn;
+
+ /* This function is called from within an interrupt. It can only access
+ event lists and the pending ready list. This function assumes that a
+ check has already been made to ensure pxEventList is not empty. */
+ pxUnblockedCRCB = (CRCB_t *)listGET_OWNER_OF_HEAD_ENTRY(pxEventList);
+ (void)uxListRemove(&(pxUnblockedCRCB->xEventListItem));
+ vListInsertEnd((List_t *)&(xPendingReadyCoRoutineList), &(pxUnblockedCRCB->xEventListItem));
+
+ if (pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority) {
+ xReturn = pdTRUE;
+ } else {
+ xReturn = pdFALSE;
+ }
+
+ return xReturn;
}
#endif /* configUSE_CO_ROUTINES == 0 */
-
diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/event_groups.c b/source/Middlewares/Third_Party/FreeRTOS/Source/event_groups.c
index 0bf3b966..b98f8678 100644
--- a/source/Middlewares/Third_Party/FreeRTOS/Source/event_groups.c
+++ b/source/Middlewares/Third_Party/FreeRTOS/Source/event_groups.c
@@ -35,9 +35,9 @@ task.h is included from an application file. */
/* FreeRTOS includes. */
#include "FreeRTOS.h"
+#include "event_groups.h"
#include "task.h"
#include "timers.h"
-#include "event_groups.h"
/* Lint e961, e750 and e9021 are suppressed as a MISRA exception justified
because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined
@@ -49,29 +49,28 @@ correct privileged Vs unprivileged linkage and placement. */
item value. It is important they don't clash with the
taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */
#if configUSE_16_BIT_TICKS == 1
- #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U
- #define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U
- #define eventWAIT_FOR_ALL_BITS 0x0400U
- #define eventEVENT_BITS_CONTROL_BYTES 0xff00U
+#define eventCLEAR_EVENTS_ON_EXIT_BIT 0x0100U
+#define eventUNBLOCKED_DUE_TO_BIT_SET 0x0200U
+#define eventWAIT_FOR_ALL_BITS 0x0400U
+#define eventEVENT_BITS_CONTROL_BYTES 0xff00U
#else
- #define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL
- #define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL
- #define eventWAIT_FOR_ALL_BITS 0x04000000UL
- #define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL
+#define eventCLEAR_EVENTS_ON_EXIT_BIT 0x01000000UL
+#define eventUNBLOCKED_DUE_TO_BIT_SET 0x02000000UL
+#define eventWAIT_FOR_ALL_BITS 0x04000000UL
+#define eventEVENT_BITS_CONTROL_BYTES 0xff000000UL
#endif
-typedef struct EventGroupDef_t
-{
- EventBits_t uxEventBits;
- List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */
+typedef struct EventGroupDef_t {
+ EventBits_t uxEventBits;
+ List_t xTasksWaitingForBits; /*< List of tasks waiting for a bit to be set. */
- #if( configUSE_TRACE_FACILITY == 1 )
- UBaseType_t uxEventGroupNumber;
- #endif
+#if (configUSE_TRACE_FACILITY == 1)
+ UBaseType_t uxEventGroupNumber;
+#endif
- #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
- uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */
- #endif
+#if ((configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1))
+ uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the event group is statically allocated to ensure no attempt is made to free the memory. */
+#endif
} EventGroup_t;
/*-----------------------------------------------------------*/
@@ -84,670 +83,575 @@ typedef struct EventGroupDef_t
* wait condition is met if any of the bits set in uxBitsToWait for are also set
* in uxCurrentEventBits.
*/
-static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, const EventBits_t uxBitsToWaitFor, const BaseType_t xWaitForAllBits ) PRIVILEGED_FUNCTION;
+static BaseType_t prvTestWaitCondition(const EventBits_t uxCurrentEventBits, const EventBits_t uxBitsToWaitFor, const BaseType_t xWaitForAllBits) PRIVILEGED_FUNCTION;
/*-----------------------------------------------------------*/
-#if( configSUPPORT_STATIC_ALLOCATION == 1 )
-
- EventGroupHandle_t xEventGroupCreateStatic( StaticEventGroup_t *pxEventGroupBuffer )
- {
- EventGroup_t *pxEventBits;
-
- /* A StaticEventGroup_t object must be provided. */
- configASSERT( pxEventGroupBuffer );
-
- #if( configASSERT_DEFINED == 1 )
- {
- /* Sanity check that the size of the structure used to declare a
- variable of type StaticEventGroup_t equals the size of the real
- event group structure. */
- volatile size_t xSize = sizeof( StaticEventGroup_t );
- configASSERT( xSize == sizeof( EventGroup_t ) );
- } /*lint !e529 xSize is referenced if configASSERT() is defined. */
- #endif /* configASSERT_DEFINED */
-
- /* The user has provided a statically allocated event group - use it. */
- pxEventBits = ( EventGroup_t * ) pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and alignment requirement - checked by configASSERT(). */
-
- if( pxEventBits != NULL )
- {
- pxEventBits->uxEventBits = 0;
- vListInitialise( &( pxEventBits->xTasksWaitingForBits ) );
-
- #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
- {
- /* Both static and dynamic allocation can be used, so note that
- this event group was created statically in case the event group
- is later deleted. */
- pxEventBits->ucStaticallyAllocated = pdTRUE;
- }
- #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
-
- traceEVENT_GROUP_CREATE( pxEventBits );
- }
- else
- {
- /* xEventGroupCreateStatic should only ever be called with
- pxEventGroupBuffer pointing to a pre-allocated (compile time
- allocated) StaticEventGroup_t variable. */
- traceEVENT_GROUP_CREATE_FAILED();
- }
-
- return pxEventBits;
- }
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
+
+EventGroupHandle_t xEventGroupCreateStatic(StaticEventGroup_t *pxEventGroupBuffer) {
+ EventGroup_t *pxEventBits;
+
+ /* A StaticEventGroup_t object must be provided. */
+ configASSERT(pxEventGroupBuffer);
+
+#if (configASSERT_DEFINED == 1)
+ {
+ /* Sanity check that the size of the structure used to declare a
+ variable of type StaticEventGroup_t equals the size of the real
+ event group structure. */
+ volatile size_t xSize = sizeof(StaticEventGroup_t);
+ configASSERT(xSize == sizeof(EventGroup_t));
+ } /*lint !e529 xSize is referenced if configASSERT() is defined. */
+#endif /* configASSERT_DEFINED */
+
+ /* The user has provided a statically allocated event group - use it. */
+ pxEventBits = (EventGroup_t *)pxEventGroupBuffer; /*lint !e740 !e9087 EventGroup_t and StaticEventGroup_t are deliberately aliased for data hiding purposes and guaranteed to have the same size and
+ alignment requirement - checked by configASSERT(). */
+
+ if (pxEventBits != NULL) {
+ pxEventBits->uxEventBits = 0;
+ vListInitialise(&(pxEventBits->xTasksWaitingForBits));
+
+#if (configSUPPORT_DYNAMIC_ALLOCATION == 1)
+ {
+ /* Both static and dynamic allocation can be used, so note that
+ this event group was created statically in case the event group
+ is later deleted. */
+ pxEventBits->ucStaticallyAllocated = pdTRUE;
+ }
+#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
+
+ traceEVENT_GROUP_CREATE(pxEventBits);
+ } else {
+ /* xEventGroupCreateStatic should only ever be called with
+ pxEventGroupBuffer pointing to a pre-allocated (compile time
+ allocated) StaticEventGroup_t variable. */
+ traceEVENT_GROUP_CREATE_FAILED();
+ }
+
+ return pxEventBits;
+}
#endif /* configSUPPORT_STATIC_ALLOCATION */
/*-----------------------------------------------------------*/
-#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
-
- EventGroupHandle_t xEventGroupCreate( void )
- {
- EventGroup_t *pxEventBits;
-
- /* Allocate the event group. Justification for MISRA deviation as
- follows: pvPortMalloc() always ensures returned memory blocks are
- aligned per the requirements of the MCU stack. In this case
- pvPortMalloc() must return a pointer that is guaranteed to meet the
- alignment requirements of the EventGroup_t structure - which (if you
- follow it through) is the alignment requirements of the TickType_t type
- (EventBits_t being of TickType_t itself). Therefore, whenever the
- stack alignment requirements are greater than or equal to the
- TickType_t alignment requirements the cast is safe. In other cases,
- where the natural word size of the architecture is less than
- sizeof( TickType_t ), the TickType_t variables will be accessed in two
- or more reads operations, and the alignment requirements is only that
- of each individual read. */
- pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) ); /*lint !e9087 !e9079 see comment above. */
-
- if( pxEventBits != NULL )
- {
- pxEventBits->uxEventBits = 0;
- vListInitialise( &( pxEventBits->xTasksWaitingForBits ) );
-
- #if( configSUPPORT_STATIC_ALLOCATION == 1 )
- {
- /* Both static and dynamic allocation can be used, so note this
- event group was allocated statically in case the event group is
- later deleted. */
- pxEventBits->ucStaticallyAllocated = pdFALSE;
- }
- #endif /* configSUPPORT_STATIC_ALLOCATION */
-
- traceEVENT_GROUP_CREATE( pxEventBits );
- }
- else
- {
- traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */
- }
-
- return pxEventBits;
- }
+#if (configSUPPORT_DYNAMIC_ALLOCATION == 1)
+
+EventGroupHandle_t xEventGroupCreate(void) {
+ EventGroup_t *pxEventBits;
+
+ /* Allocate the event group. Justification for MISRA deviation as
+ follows: pvPortMalloc() always ensures returned memory blocks are
+ aligned per the requirements of the MCU stack. In this case
+ pvPortMalloc() must return a pointer that is guaranteed to meet the
+ alignment requirements of the EventGroup_t structure - which (if you
+ follow it through) is the alignment requirements of the TickType_t type
+ (EventBits_t being of TickType_t itself). Therefore, whenever the
+ stack alignment requirements are greater than or equal to the
+ TickType_t alignment requirements the cast is safe. In other cases,
+ where the natural word size of the architecture is less than
+ sizeof( TickType_t ), the TickType_t variables will be accessed in two
+ or more reads operations, and the alignment requirements is only that
+ of each individual read. */
+ pxEventBits = (EventGroup_t *)pvPortMalloc(sizeof(EventGroup_t)); /*lint !e9087 !e9079 see comment above. */
+
+ if (pxEventBits != NULL) {
+ pxEventBits->uxEventBits = 0;
+ vListInitialise(&(pxEventBits->xTasksWaitingForBits));
+
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
+ {
+ /* Both static and dynamic allocation can be used, so note this
+ event group was allocated statically in case the event group is
+ later deleted. */
+ pxEventBits->ucStaticallyAllocated = pdFALSE;
+ }
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+ traceEVENT_GROUP_CREATE(pxEventBits);
+ } else {
+ traceEVENT_GROUP_CREATE_FAILED(); /*lint !e9063 Else branch only exists to allow tracing and does not generate code if trace macros are not defined. */
+ }
+
+ return pxEventBits;
+}
#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
/*-----------------------------------------------------------*/
-EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait )
-{
-EventBits_t uxOriginalBitValue, uxReturn;
-EventGroup_t *pxEventBits = xEventGroup;
-BaseType_t xAlreadyYielded;
-BaseType_t xTimeoutOccurred = pdFALSE;
-
- configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
- configASSERT( uxBitsToWaitFor != 0 );
- #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
- {
- configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
- }
- #endif
-
- vTaskSuspendAll();
- {
- uxOriginalBitValue = pxEventBits->uxEventBits;
-
- ( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet );
-
- if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor )
- {
- /* All the rendezvous bits are now set - no need to block. */
- uxReturn = ( uxOriginalBitValue | uxBitsToSet );
-
- /* Rendezvous always clear the bits. They will have been cleared
- already unless this is the only task in the rendezvous. */
- pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
-
- xTicksToWait = 0;
- }
- else
- {
- if( xTicksToWait != ( TickType_t ) 0 )
- {
- traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor );
-
- /* Store the bits that the calling task is waiting for in the
- task's event list item so the kernel knows when a match is
- found. Then enter the blocked state. */
- vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait );
-
- /* This assignment is obsolete as uxReturn will get set after
- the task unblocks, but some compilers mistakenly generate a
- warning about uxReturn being returned without being set if the
- assignment is omitted. */
- uxReturn = 0;
- }
- else
- {
- /* The rendezvous bits were not set, but no block time was
- specified - just return the current event bit value. */
- uxReturn = pxEventBits->uxEventBits;
- xTimeoutOccurred = pdTRUE;
- }
- }
- }
- xAlreadyYielded = xTaskResumeAll();
-
- if( xTicksToWait != ( TickType_t ) 0 )
- {
- if( xAlreadyYielded == pdFALSE )
- {
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* The task blocked to wait for its required bits to be set - at this
- point either the required bits were set or the block time expired. If
- the required bits were set they will have been stored in the task's
- event list item, and they should now be retrieved then cleared. */
- uxReturn = uxTaskResetEventItemValue();
-
- if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 )
- {
- /* The task timed out, just return the current event bit value. */
- taskENTER_CRITICAL();
- {
- uxReturn = pxEventBits->uxEventBits;
-
- /* Although the task got here because it timed out before the
- bits it was waiting for were set, it is possible that since it
- unblocked another task has set the bits. If this is the case
- then it needs to clear the bits before exiting. */
- if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor )
- {
- pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- taskEXIT_CRITICAL();
-
- xTimeoutOccurred = pdTRUE;
- }
- else
- {
- /* The task unblocked because the bits were set. */
- }
-
- /* Control bits might be set as the task had blocked should not be
- returned. */
- uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;
- }
-
- traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred );
-
- /* Prevent compiler warnings when trace macros are not used. */
- ( void ) xTimeoutOccurred;
-
- return uxReturn;
+EventBits_t xEventGroupSync(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait) {
+ EventBits_t uxOriginalBitValue, uxReturn;
+ EventGroup_t *pxEventBits = xEventGroup;
+ BaseType_t xAlreadyYielded;
+ BaseType_t xTimeoutOccurred = pdFALSE;
+
+ configASSERT((uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES) == 0);
+ configASSERT(uxBitsToWaitFor != 0);
+#if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1))
+ { configASSERT(!((xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED) && (xTicksToWait != 0))); }
+#endif
+
+ vTaskSuspendAll();
+ {
+ uxOriginalBitValue = pxEventBits->uxEventBits;
+
+ (void)xEventGroupSetBits(xEventGroup, uxBitsToSet);
+
+ if (((uxOriginalBitValue | uxBitsToSet) & uxBitsToWaitFor) == uxBitsToWaitFor) {
+ /* All the rendezvous bits are now set - no need to block. */
+ uxReturn = (uxOriginalBitValue | uxBitsToSet);
+
+ /* Rendezvous always clear the bits. They will have been cleared
+ already unless this is the only task in the rendezvous. */
+ pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
+
+ xTicksToWait = 0;
+ } else {
+ if (xTicksToWait != (TickType_t)0) {
+ traceEVENT_GROUP_SYNC_BLOCK(xEventGroup, uxBitsToSet, uxBitsToWaitFor);
+
+ /* Store the bits that the calling task is waiting for in the
+ task's event list item so the kernel knows when a match is
+ found. Then enter the blocked state. */
+ vTaskPlaceOnUnorderedEventList(&(pxEventBits->xTasksWaitingForBits), (uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS), xTicksToWait);
+
+ /* This assignment is obsolete as uxReturn will get set after
+ the task unblocks, but some compilers mistakenly generate a
+ warning about uxReturn being returned without being set if the
+ assignment is omitted. */
+ uxReturn = 0;
+ } else {
+ /* The rendezvous bits were not set, but no block time was
+ specified - just return the current event bit value. */
+ uxReturn = pxEventBits->uxEventBits;
+ xTimeoutOccurred = pdTRUE;
+ }
+ }
+ }
+ xAlreadyYielded = xTaskResumeAll();
+
+ if (xTicksToWait != (TickType_t)0) {
+ if (xAlreadyYielded == pdFALSE) {
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* The task blocked to wait for its required bits to be set - at this
+ point either the required bits were set or the block time expired. If
+ the required bits were set they will have been stored in the task's
+ event list item, and they should now be retrieved then cleared. */
+ uxReturn = uxTaskResetEventItemValue();
+
+ if ((uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET) == (EventBits_t)0) {
+ /* The task timed out, just return the current event bit value. */
+ taskENTER_CRITICAL();
+ {
+ uxReturn = pxEventBits->uxEventBits;
+
+ /* Although the task got here because it timed out before the
+ bits it was waiting for were set, it is possible that since it
+ unblocked another task has set the bits. If this is the case
+ then it needs to clear the bits before exiting. */
+ if ((uxReturn & uxBitsToWaitFor) == uxBitsToWaitFor) {
+ pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ xTimeoutOccurred = pdTRUE;
+ } else {
+ /* The task unblocked because the bits were set. */
+ }
+
+ /* Control bits might be set as the task had blocked should not be
+ returned. */
+ uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;
+ }
+
+ traceEVENT_GROUP_SYNC_END(xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred);
+
+ /* Prevent compiler warnings when trace macros are not used. */
+ (void)xTimeoutOccurred;
+
+ return uxReturn;
}
/*-----------------------------------------------------------*/
-EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait )
-{
-EventGroup_t *pxEventBits = xEventGroup;
-EventBits_t uxReturn, uxControlBits = 0;
-BaseType_t xWaitConditionMet, xAlreadyYielded;
-BaseType_t xTimeoutOccurred = pdFALSE;
-
- /* Check the user is not attempting to wait on the bits used by the kernel
- itself, and that at least one bit is being requested. */
- configASSERT( xEventGroup );
- configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
- configASSERT( uxBitsToWaitFor != 0 );
- #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
- {
- configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
- }
- #endif
-
- vTaskSuspendAll();
- {
- const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits;
-
- /* Check to see if the wait condition is already met or not. */
- xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits );
-
- if( xWaitConditionMet != pdFALSE )
- {
- /* The wait condition has already been met so there is no need to
- block. */
- uxReturn = uxCurrentEventBits;
- xTicksToWait = ( TickType_t ) 0;
-
- /* Clear the wait bits if requested to do so. */
- if( xClearOnExit != pdFALSE )
- {
- pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else if( xTicksToWait == ( TickType_t ) 0 )
- {
- /* The wait condition has not been met, but no block time was
- specified, so just return the current value. */
- uxReturn = uxCurrentEventBits;
- xTimeoutOccurred = pdTRUE;
- }
- else
- {
- /* The task is going to block to wait for its required bits to be
- set. uxControlBits are used to remember the specified behaviour of
- this call to xEventGroupWaitBits() - for use when the event bits
- unblock the task. */
- if( xClearOnExit != pdFALSE )
- {
- uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- if( xWaitForAllBits != pdFALSE )
- {
- uxControlBits |= eventWAIT_FOR_ALL_BITS;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Store the bits that the calling task is waiting for in the
- task's event list item so the kernel knows when a match is
- found. Then enter the blocked state. */
- vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait );
-
- /* This is obsolete as it will get set after the task unblocks, but
- some compilers mistakenly generate a warning about the variable
- being returned without being set if it is not done. */
- uxReturn = 0;
-
- traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor );
- }
- }
- xAlreadyYielded = xTaskResumeAll();
-
- if( xTicksToWait != ( TickType_t ) 0 )
- {
- if( xAlreadyYielded == pdFALSE )
- {
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* The task blocked to wait for its required bits to be set - at this
- point either the required bits were set or the block time expired. If
- the required bits were set they will have been stored in the task's
- event list item, and they should now be retrieved then cleared. */
- uxReturn = uxTaskResetEventItemValue();
-
- if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 )
- {
- taskENTER_CRITICAL();
- {
- /* The task timed out, just return the current event bit value. */
- uxReturn = pxEventBits->uxEventBits;
-
- /* It is possible that the event bits were updated between this
- task leaving the Blocked state and running again. */
- if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE )
- {
- if( xClearOnExit != pdFALSE )
- {
- pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- xTimeoutOccurred = pdTRUE;
- }
- taskEXIT_CRITICAL();
- }
- else
- {
- /* The task unblocked because the bits were set. */
- }
-
- /* The task blocked so control bits may have been set. */
- uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;
- }
- traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred );
-
- /* Prevent compiler warnings when trace macros are not used. */
- ( void ) xTimeoutOccurred;
-
- return uxReturn;
+EventBits_t xEventGroupWaitBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait) {
+ EventGroup_t *pxEventBits = xEventGroup;
+ EventBits_t uxReturn, uxControlBits = 0;
+ BaseType_t xWaitConditionMet, xAlreadyYielded;
+ BaseType_t xTimeoutOccurred = pdFALSE;
+
+ /* Check the user is not attempting to wait on the bits used by the kernel
+ itself, and that at least one bit is being requested. */
+ configASSERT(xEventGroup);
+ configASSERT((uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES) == 0);
+ configASSERT(uxBitsToWaitFor != 0);
+#if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1))
+ { configASSERT(!((xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED) && (xTicksToWait != 0))); }
+#endif
+
+ vTaskSuspendAll();
+ {
+ const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits;
+
+ /* Check to see if the wait condition is already met or not. */
+ xWaitConditionMet = prvTestWaitCondition(uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits);
+
+ if (xWaitConditionMet != pdFALSE) {
+ /* The wait condition has already been met so there is no need to
+ block. */
+ uxReturn = uxCurrentEventBits;
+ xTicksToWait = (TickType_t)0;
+
+ /* Clear the wait bits if requested to do so. */
+ if (xClearOnExit != pdFALSE) {
+ pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else if (xTicksToWait == (TickType_t)0) {
+ /* The wait condition has not been met, but no block time was
+ specified, so just return the current value. */
+ uxReturn = uxCurrentEventBits;
+ xTimeoutOccurred = pdTRUE;
+ } else {
+ /* The task is going to block to wait for its required bits to be
+ set. uxControlBits are used to remember the specified behaviour of
+ this call to xEventGroupWaitBits() - for use when the event bits
+ unblock the task. */
+ if (xClearOnExit != pdFALSE) {
+ uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ if (xWaitForAllBits != pdFALSE) {
+ uxControlBits |= eventWAIT_FOR_ALL_BITS;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Store the bits that the calling task is waiting for in the
+ task's event list item so the kernel knows when a match is
+ found. Then enter the blocked state. */
+ vTaskPlaceOnUnorderedEventList(&(pxEventBits->xTasksWaitingForBits), (uxBitsToWaitFor | uxControlBits), xTicksToWait);
+
+ /* This is obsolete as it will get set after the task unblocks, but
+ some compilers mistakenly generate a warning about the variable
+ being returned without being set if it is not done. */
+ uxReturn = 0;
+
+ traceEVENT_GROUP_WAIT_BITS_BLOCK(xEventGroup, uxBitsToWaitFor);
+ }
+ }
+ xAlreadyYielded = xTaskResumeAll();
+
+ if (xTicksToWait != (TickType_t)0) {
+ if (xAlreadyYielded == pdFALSE) {
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* The task blocked to wait for its required bits to be set - at this
+ point either the required bits were set or the block time expired. If
+ the required bits were set they will have been stored in the task's
+ event list item, and they should now be retrieved then cleared. */
+ uxReturn = uxTaskResetEventItemValue();
+
+ if ((uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET) == (EventBits_t)0) {
+ taskENTER_CRITICAL();
+ {
+ /* The task timed out, just return the current event bit value. */
+ uxReturn = pxEventBits->uxEventBits;
+
+ /* It is possible that the event bits were updated between this
+ task leaving the Blocked state and running again. */
+ if (prvTestWaitCondition(uxReturn, uxBitsToWaitFor, xWaitForAllBits) != pdFALSE) {
+ if (xClearOnExit != pdFALSE) {
+ pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ xTimeoutOccurred = pdTRUE;
+ }
+ taskEXIT_CRITICAL();
+ } else {
+ /* The task unblocked because the bits were set. */
+ }
+
+ /* The task blocked so control bits may have been set. */
+ uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;
+ }
+ traceEVENT_GROUP_WAIT_BITS_END(xEventGroup, uxBitsToWaitFor, xTimeoutOccurred);
+
+ /* Prevent compiler warnings when trace macros are not used. */
+ (void)xTimeoutOccurred;
+
+ return uxReturn;
}
/*-----------------------------------------------------------*/
-EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear )
-{
-EventGroup_t *pxEventBits = xEventGroup;
-EventBits_t uxReturn;
+EventBits_t xEventGroupClearBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear) {
+ EventGroup_t *pxEventBits = xEventGroup;
+ EventBits_t uxReturn;
- /* Check the user is not attempting to clear the bits used by the kernel
- itself. */
- configASSERT( xEventGroup );
- configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
+ /* Check the user is not attempting to clear the bits used by the kernel
+ itself. */
+ configASSERT(xEventGroup);
+ configASSERT((uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES) == 0);
- taskENTER_CRITICAL();
- {
- traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear );
+ taskENTER_CRITICAL();
+ {
+ traceEVENT_GROUP_CLEAR_BITS(xEventGroup, uxBitsToClear);
- /* The value returned is the event group value prior to the bits being
- cleared. */
- uxReturn = pxEventBits->uxEventBits;
+ /* The value returned is the event group value prior to the bits being
+ cleared. */
+ uxReturn = pxEventBits->uxEventBits;
- /* Clear the bits. */
- pxEventBits->uxEventBits &= ~uxBitsToClear;
- }
- taskEXIT_CRITICAL();
+ /* Clear the bits. */
+ pxEventBits->uxEventBits &= ~uxBitsToClear;
+ }
+ taskEXIT_CRITICAL();
- return uxReturn;
+ return uxReturn;
}
/*-----------------------------------------------------------*/
-#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) )
+#if ((configUSE_TRACE_FACILITY == 1) && (INCLUDE_xTimerPendFunctionCall == 1) && (configUSE_TIMERS == 1))
- BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear )
- {
- BaseType_t xReturn;
+BaseType_t xEventGroupClearBitsFromISR(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear) {
+ BaseType_t xReturn;
- traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear );
- xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */
+ traceEVENT_GROUP_CLEAR_BITS_FROM_ISR(xEventGroup, uxBitsToClear);
+ xReturn = xTimerPendFunctionCallFromISR(vEventGroupClearBitsCallback, (void *)xEventGroup, (uint32_t)uxBitsToClear,
+ NULL); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */
- return xReturn;
- }
+ return xReturn;
+}
#endif
/*-----------------------------------------------------------*/
-EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup )
-{
-UBaseType_t uxSavedInterruptStatus;
-EventGroup_t const * const pxEventBits = xEventGroup;
-EventBits_t uxReturn;
+EventBits_t xEventGroupGetBitsFromISR(EventGroupHandle_t xEventGroup) {
+ UBaseType_t uxSavedInterruptStatus;
+ EventGroup_t const *const pxEventBits = xEventGroup;
+ EventBits_t uxReturn;
- uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- uxReturn = pxEventBits->uxEventBits;
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ { uxReturn = pxEventBits->uxEventBits; }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
- return uxReturn;
+ return uxReturn;
} /*lint !e818 EventGroupHandle_t is a typedef used in other functions to so can't be pointer to const. */
/*-----------------------------------------------------------*/
-EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet )
-{
-ListItem_t *pxListItem, *pxNext;
-ListItem_t const *pxListEnd;
-List_t const * pxList;
-EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits;
-EventGroup_t *pxEventBits = xEventGroup;
-BaseType_t xMatchFound = pdFALSE;
-
- /* Check the user is not attempting to set the bits used by the kernel
- itself. */
- configASSERT( xEventGroup );
- configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
-
- pxList = &( pxEventBits->xTasksWaitingForBits );
- pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
- vTaskSuspendAll();
- {
- traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet );
-
- pxListItem = listGET_HEAD_ENTRY( pxList );
-
- /* Set the bits. */
- pxEventBits->uxEventBits |= uxBitsToSet;
-
- /* See if the new bit value should unblock any tasks. */
- while( pxListItem != pxListEnd )
- {
- pxNext = listGET_NEXT( pxListItem );
- uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem );
- xMatchFound = pdFALSE;
-
- /* Split the bits waited for from the control bits. */
- uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES;
- uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES;
-
- if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 )
- {
- /* Just looking for single bit being set. */
- if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 )
- {
- xMatchFound = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor )
- {
- /* All bits are set. */
- xMatchFound = pdTRUE;
- }
- else
- {
- /* Need all bits to be set, but not all the bits were set. */
- }
-
- if( xMatchFound != pdFALSE )
- {
- /* The bits match. Should the bits be cleared on exit? */
- if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 )
- {
- uxBitsToClear |= uxBitsWaitedFor;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Store the actual event flag value in the task's event list
- item before removing the task from the event list. The
- eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows
- that is was unblocked due to its required bits matching, rather
- than because it timed out. */
- vTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET );
- }
-
- /* Move onto the next list item. Note pxListItem->pxNext is not
- used here as the list item may have been removed from the event list
- and inserted into the ready/pending reading list. */
- pxListItem = pxNext;
- }
-
- /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT
- bit was set in the control word. */
- pxEventBits->uxEventBits &= ~uxBitsToClear;
- }
- ( void ) xTaskResumeAll();
-
- return pxEventBits->uxEventBits;
+EventBits_t xEventGroupSetBits(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet) {
+ ListItem_t * pxListItem, *pxNext;
+ ListItem_t const *pxListEnd;
+ List_t const * pxList;
+ EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits;
+ EventGroup_t * pxEventBits = xEventGroup;
+ BaseType_t xMatchFound = pdFALSE;
+
+ /* Check the user is not attempting to set the bits used by the kernel
+ itself. */
+ configASSERT(xEventGroup);
+ configASSERT((uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES) == 0);
+
+ pxList = &(pxEventBits->xTasksWaitingForBits);
+ pxListEnd = listGET_END_MARKER(pxList); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
+ vTaskSuspendAll();
+ {
+ traceEVENT_GROUP_SET_BITS(xEventGroup, uxBitsToSet);
+
+ pxListItem = listGET_HEAD_ENTRY(pxList);
+
+ /* Set the bits. */
+ pxEventBits->uxEventBits |= uxBitsToSet;
+
+ /* See if the new bit value should unblock any tasks. */
+ while (pxListItem != pxListEnd) {
+ pxNext = listGET_NEXT(pxListItem);
+ uxBitsWaitedFor = listGET_LIST_ITEM_VALUE(pxListItem);
+ xMatchFound = pdFALSE;
+
+ /* Split the bits waited for from the control bits. */
+ uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES;
+ uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES;
+
+ if ((uxControlBits & eventWAIT_FOR_ALL_BITS) == (EventBits_t)0) {
+ /* Just looking for single bit being set. */
+ if ((uxBitsWaitedFor & pxEventBits->uxEventBits) != (EventBits_t)0) {
+ xMatchFound = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else if ((uxBitsWaitedFor & pxEventBits->uxEventBits) == uxBitsWaitedFor) {
+ /* All bits are set. */
+ xMatchFound = pdTRUE;
+ } else {
+ /* Need all bits to be set, but not all the bits were set. */
+ }
+
+ if (xMatchFound != pdFALSE) {
+ /* The bits match. Should the bits be cleared on exit? */
+ if ((uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT) != (EventBits_t)0) {
+ uxBitsToClear |= uxBitsWaitedFor;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Store the actual event flag value in the task's event list
+ item before removing the task from the event list. The
+ eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows
+ that is was unblocked due to its required bits matching, rather
+ than because it timed out. */
+ vTaskRemoveFromUnorderedEventList(pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET);
+ }
+
+ /* Move onto the next list item. Note pxListItem->pxNext is not
+ used here as the list item may have been removed from the event list
+ and inserted into the ready/pending reading list. */
+ pxListItem = pxNext;
+ }
+
+ /* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT
+ bit was set in the control word. */
+ pxEventBits->uxEventBits &= ~uxBitsToClear;
+ }
+ (void)xTaskResumeAll();
+
+ return pxEventBits->uxEventBits;
}
/*-----------------------------------------------------------*/
-void vEventGroupDelete( EventGroupHandle_t xEventGroup )
-{
-EventGroup_t *pxEventBits = xEventGroup;
-const List_t *pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits );
-
- vTaskSuspendAll();
- {
- traceEVENT_GROUP_DELETE( xEventGroup );
-
- while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 )
- {
- /* Unblock the task, returning 0 as the event list is being deleted
- and cannot therefore have any bits set. */
- configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( const ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) );
- vTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET );
- }
-
- #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) )
- {
- /* The event group can only have been allocated dynamically - free
- it again. */
- vPortFree( pxEventBits );
- }
- #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
- {
- /* The event group could have been allocated statically or
- dynamically, so check before attempting to free the memory. */
- if( pxEventBits->ucStaticallyAllocated == ( uint8_t ) pdFALSE )
- {
- vPortFree( pxEventBits );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
- }
- ( void ) xTaskResumeAll();
+void vEventGroupDelete(EventGroupHandle_t xEventGroup) {
+ EventGroup_t *pxEventBits = xEventGroup;
+ const List_t *pxTasksWaitingForBits = &(pxEventBits->xTasksWaitingForBits);
+
+ vTaskSuspendAll();
+ {
+ traceEVENT_GROUP_DELETE(xEventGroup);
+
+ while (listCURRENT_LIST_LENGTH(pxTasksWaitingForBits) > (UBaseType_t)0) {
+ /* Unblock the task, returning 0 as the event list is being deleted
+ and cannot therefore have any bits set. */
+ configASSERT(pxTasksWaitingForBits->xListEnd.pxNext != (const ListItem_t *)&(pxTasksWaitingForBits->xListEnd));
+ vTaskRemoveFromUnorderedEventList(pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET);
+ }
+
+#if ((configSUPPORT_DYNAMIC_ALLOCATION == 1) && (configSUPPORT_STATIC_ALLOCATION == 0))
+ {
+ /* The event group can only have been allocated dynamically - free
+ it again. */
+ vPortFree(pxEventBits);
+ }
+#elif ((configSUPPORT_DYNAMIC_ALLOCATION == 1) && (configSUPPORT_STATIC_ALLOCATION == 1))
+ {
+ /* The event group could have been allocated statically or
+ dynamically, so check before attempting to free the memory. */
+ if (pxEventBits->ucStaticallyAllocated == (uint8_t)pdFALSE) {
+ vPortFree(pxEventBits);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
+ }
+ (void)xTaskResumeAll();
}
/*-----------------------------------------------------------*/
/* For internal use only - execute a 'set bits' command that was pended from
an interrupt. */
-void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet )
-{
- ( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */
+void vEventGroupSetBitsCallback(void *pvEventGroup, const uint32_t ulBitsToSet) {
+ (void)xEventGroupSetBits(pvEventGroup, (EventBits_t)ulBitsToSet); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */
}
/*-----------------------------------------------------------*/
/* For internal use only - execute a 'clear bits' command that was pended from
an interrupt. */
-void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear )
-{
- ( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear ); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */
+void vEventGroupClearBitsCallback(void *pvEventGroup, const uint32_t ulBitsToClear) {
+ (void)xEventGroupClearBits(pvEventGroup, (EventBits_t)ulBitsToClear); /*lint !e9079 Can't avoid cast to void* as a generic timer callback prototype. Callback casts back to original type so safe. */
}
/*-----------------------------------------------------------*/
-static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, const EventBits_t uxBitsToWaitFor, const BaseType_t xWaitForAllBits )
-{
-BaseType_t xWaitConditionMet = pdFALSE;
-
- if( xWaitForAllBits == pdFALSE )
- {
- /* Task only has to wait for one bit within uxBitsToWaitFor to be
- set. Is one already set? */
- if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 )
- {
- xWaitConditionMet = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* Task has to wait for all the bits in uxBitsToWaitFor to be set.
- Are they set already? */
- if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor )
- {
- xWaitConditionMet = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- return xWaitConditionMet;
+static BaseType_t prvTestWaitCondition(const EventBits_t uxCurrentEventBits, const EventBits_t uxBitsToWaitFor, const BaseType_t xWaitForAllBits) {
+ BaseType_t xWaitConditionMet = pdFALSE;
+
+ if (xWaitForAllBits == pdFALSE) {
+ /* Task only has to wait for one bit within uxBitsToWaitFor to be
+ set. Is one already set? */
+ if ((uxCurrentEventBits & uxBitsToWaitFor) != (EventBits_t)0) {
+ xWaitConditionMet = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* Task has to wait for all the bits in uxBitsToWaitFor to be set.
+ Are they set already? */
+ if ((uxCurrentEventBits & uxBitsToWaitFor) == uxBitsToWaitFor) {
+ xWaitConditionMet = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ return xWaitConditionMet;
}
/*-----------------------------------------------------------*/
-#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) )
+#if ((configUSE_TRACE_FACILITY == 1) && (INCLUDE_xTimerPendFunctionCall == 1) && (configUSE_TIMERS == 1))
- BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken )
- {
- BaseType_t xReturn;
+BaseType_t xEventGroupSetBitsFromISR(EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken) {
+ BaseType_t xReturn;
- traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet );
- xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken ); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */
+ traceEVENT_GROUP_SET_BITS_FROM_ISR(xEventGroup, uxBitsToSet);
+ xReturn = xTimerPendFunctionCallFromISR(
+ vEventGroupSetBitsCallback, (void *)xEventGroup, (uint32_t)uxBitsToSet,
+ pxHigherPriorityTaskWoken); /*lint !e9087 Can't avoid cast to void* as a generic callback function not specific to this use case. Callback casts back to original type so safe. */
- return xReturn;
- }
+ return xReturn;
+}
#endif
/*-----------------------------------------------------------*/
#if (configUSE_TRACE_FACILITY == 1)
- UBaseType_t uxEventGroupGetNumber( void* xEventGroup )
- {
- UBaseType_t xReturn;
- EventGroup_t const *pxEventBits = ( EventGroup_t * ) xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */
+UBaseType_t uxEventGroupGetNumber(void *xEventGroup) {
+ UBaseType_t xReturn;
+ EventGroup_t const *pxEventBits
+ = (EventGroup_t *)xEventGroup; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */
- if( xEventGroup == NULL )
- {
- xReturn = 0;
- }
- else
- {
- xReturn = pxEventBits->uxEventGroupNumber;
- }
+ if (xEventGroup == NULL) {
+ xReturn = 0;
+ } else {
+ xReturn = pxEventBits->uxEventGroupNumber;
+ }
- return xReturn;
- }
+ return xReturn;
+}
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
+#if (configUSE_TRACE_FACILITY == 1)
- void vEventGroupSetNumber( void * xEventGroup, UBaseType_t uxEventGroupNumber )
- {
- ( ( EventGroup_t * ) xEventGroup )->uxEventGroupNumber = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */
- }
+void vEventGroupSetNumber(void *xEventGroup, UBaseType_t uxEventGroupNumber) {
+ ((EventGroup_t *)xEventGroup)->uxEventGroupNumber
+ = uxEventGroupNumber; /*lint !e9087 !e9079 EventGroupHandle_t is a pointer to an EventGroup_t, but EventGroupHandle_t is kept opaque outside of this file for data hiding purposes. */
+}
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
-
-
diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/list.c b/source/Middlewares/Third_Party/FreeRTOS/Source/list.c
index 0e0e72d8..069685c7 100644
--- a/source/Middlewares/Third_Party/FreeRTOS/Source/list.c
+++ b/source/Middlewares/Third_Party/FreeRTOS/Source/list.c
@@ -25,174 +25,164 @@
* 1 tab == 4 spaces!
*/
-
-#include <stdlib.h>
-#include "FreeRTOS.h"
#include "list.h"
+#include "FreeRTOS.h"
+#include <stdlib.h>
/*-----------------------------------------------------------
* PUBLIC LIST API documented in list.h
*----------------------------------------------------------*/
-void vListInitialise( List_t * const pxList )
-{
- /* The list structure contains a list item which is used to mark the
- end of the list. To initialise the list the list end is inserted
- as the only list entry. */
- pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
+void vListInitialise(List_t *const pxList) {
+ /* The list structure contains a list item which is used to mark the
+ end of the list. To initialise the list the list end is inserted
+ as the only list entry. */
+ pxList->pxIndex = (ListItem_t *)&(pxList->xListEnd); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
- /* The list end value is the highest possible value in the list to
- ensure it remains at the end of the list. */
- pxList->xListEnd.xItemValue = portMAX_DELAY;
+ /* The list end value is the highest possible value in the list to
+ ensure it remains at the end of the list. */
+ pxList->xListEnd.xItemValue = portMAX_DELAY;
- /* The list end next and previous pointers point to itself so we know
- when the list is empty. */
- pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd ); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
- pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd );/*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
+ /* The list end next and previous pointers point to itself so we know
+ when the list is empty. */
+ pxList->xListEnd.pxNext = (ListItem_t *)&(pxList->xListEnd); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
+ pxList->xListEnd.pxPrevious = (ListItem_t *)&(pxList->xListEnd); /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */
- pxList->uxNumberOfItems = ( UBaseType_t ) 0U;
+ pxList->uxNumberOfItems = (UBaseType_t)0U;
- /* Write known values into the list if
- configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
- listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList );
- listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList );
+ /* Write known values into the list if
+ configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+ listSET_LIST_INTEGRITY_CHECK_1_VALUE(pxList);
+ listSET_LIST_INTEGRITY_CHECK_2_VALUE(pxList);
}
/*-----------------------------------------------------------*/
-void vListInitialiseItem( ListItem_t * const pxItem )
-{
- /* Make sure the list item is not recorded as being on a list. */
- pxItem->pxContainer = NULL;
+void vListInitialiseItem(ListItem_t *const pxItem) {
+ /* Make sure the list item is not recorded as being on a list. */
+ pxItem->pxContainer = NULL;
- /* Write known values into the list item if
- configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
- listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem );
- listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem );
+ /* Write known values into the list item if
+ configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+ listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE(pxItem);
+ listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE(pxItem);
}
/*-----------------------------------------------------------*/
-void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem )
-{
-ListItem_t * const pxIndex = pxList->pxIndex;
+void vListInsertEnd(List_t *const pxList, ListItem_t *const pxNewListItem) {
+ ListItem_t *const pxIndex = pxList->pxIndex;
- /* Only effective when configASSERT() is also defined, these tests may catch
- the list data structures being overwritten in memory. They will not catch
- data errors caused by incorrect configuration or use of FreeRTOS. */
- listTEST_LIST_INTEGRITY( pxList );
- listTEST_LIST_ITEM_INTEGRITY( pxNewListItem );
+ /* Only effective when configASSERT() is also defined, these tests may catch
+ the list data structures being overwritten in memory. They will not catch
+ data errors caused by incorrect configuration or use of FreeRTOS. */
+ listTEST_LIST_INTEGRITY(pxList);
+ listTEST_LIST_ITEM_INTEGRITY(pxNewListItem);
- /* Insert a new list item into pxList, but rather than sort the list,
- makes the new list item the last item to be removed by a call to
- listGET_OWNER_OF_NEXT_ENTRY(). */
- pxNewListItem->pxNext = pxIndex;
- pxNewListItem->pxPrevious = pxIndex->pxPrevious;
+ /* Insert a new list item into pxList, but rather than sort the list,
+ makes the new list item the last item to be removed by a call to
+ listGET_OWNER_OF_NEXT_ENTRY(). */
+ pxNewListItem->pxNext = pxIndex;
+ pxNewListItem->pxPrevious = pxIndex->pxPrevious;
- /* Only used during decision coverage testing. */
- mtCOVERAGE_TEST_DELAY();
+ /* Only used during decision coverage testing. */
+ mtCOVERAGE_TEST_DELAY();
- pxIndex->pxPrevious->pxNext = pxNewListItem;
- pxIndex->pxPrevious = pxNewListItem;
+ pxIndex->pxPrevious->pxNext = pxNewListItem;
+ pxIndex->pxPrevious = pxNewListItem;
- /* Remember which list the item is in. */
- pxNewListItem->pxContainer = pxList;
+ /* Remember which list the item is in. */
+ pxNewListItem->pxContainer = pxList;
- ( pxList->uxNumberOfItems )++;
+ (pxList->uxNumberOfItems)++;
}
/*-----------------------------------------------------------*/
-void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem )
-{
-ListItem_t *pxIterator;
-const TickType_t xValueOfInsertion = pxNewListItem->xItemValue;
-
- /* Only effective when configASSERT() is also defined, these tests may catch
- the list data structures being overwritten in memory. They will not catch
- data errors caused by incorrect configuration or use of FreeRTOS. */
- listTEST_LIST_INTEGRITY( pxList );
- listTEST_LIST_ITEM_INTEGRITY( pxNewListItem );
-
- /* Insert the new list item into the list, sorted in xItemValue order.
-
- If the list already contains a list item with the same item value then the
- new list item should be placed after it. This ensures that TCBs which are
- stored in ready lists (all of which have the same xItemValue value) get a
- share of the CPU. However, if the xItemValue is the same as the back marker
- the iteration loop below will not end. Therefore the value is checked
- first, and the algorithm slightly modified if necessary. */
- if( xValueOfInsertion == portMAX_DELAY )
- {
- pxIterator = pxList->xListEnd.pxPrevious;
- }
- else
- {
- /* *** NOTE ***********************************************************
- If you find your application is crashing here then likely causes are
- listed below. In addition see https://www.freertos.org/FAQHelp.html for
- more tips, and ensure configASSERT() is defined!
- https://www.freertos.org/a00110.html#configASSERT
-
- 1) Stack overflow -
- see https://www.freertos.org/Stacks-and-stack-overflow-checking.html
- 2) Incorrect interrupt priority assignment, especially on Cortex-M
- parts where numerically high priority values denote low actual
- interrupt priorities, which can seem counter intuitive. See
- https://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition
- of configMAX_SYSCALL_INTERRUPT_PRIORITY on
- https://www.freertos.org/a00110.html
- 3) Calling an API function from within a critical section or when
- the scheduler is suspended, or calling an API function that does
- not end in "FromISR" from an interrupt.
- 4) Using a queue or semaphore before it has been initialised or
- before the scheduler has been started (are interrupts firing
- before vTaskStartScheduler() has been called?).
- **********************************************************************/
-
- for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. *//*lint !e440 The iterator moves to a different value, not xValueOfInsertion. */
- {
- /* There is nothing to do here, just iterating to the wanted
- insertion position. */
- }
- }
-
- pxNewListItem->pxNext = pxIterator->pxNext;
- pxNewListItem->pxNext->pxPrevious = pxNewListItem;
- pxNewListItem->pxPrevious = pxIterator;
- pxIterator->pxNext = pxNewListItem;
-
- /* Remember which list the item is in. This allows fast removal of the
- item later. */
- pxNewListItem->pxContainer = pxList;
-
- ( pxList->uxNumberOfItems )++;
+void vListInsert(List_t *const pxList, ListItem_t *const pxNewListItem) {
+ ListItem_t * pxIterator;
+ const TickType_t xValueOfInsertion = pxNewListItem->xItemValue;
+
+ /* Only effective when configASSERT() is also defined, these tests may catch
+ the list data structures being overwritten in memory. They will not catch
+ data errors caused by incorrect configuration or use of FreeRTOS. */
+ listTEST_LIST_INTEGRITY(pxList);
+ listTEST_LIST_ITEM_INTEGRITY(pxNewListItem);
+
+ /* Insert the new list item into the list, sorted in xItemValue order.
+
+ If the list already contains a list item with the same item value then the
+ new list item should be placed after it. This ensures that TCBs which are
+ stored in ready lists (all of which have the same xItemValue value) get a
+ share of the CPU. However, if the xItemValue is the same as the back marker
+ the iteration loop below will not end. Therefore the value is checked
+ first, and the algorithm slightly modified if necessary. */
+ if (xValueOfInsertion == portMAX_DELAY) {
+ pxIterator = pxList->xListEnd.pxPrevious;
+ } else {
+ /* *** NOTE ***********************************************************
+ If you find your application is crashing here then likely causes are
+ listed below. In addition see https://www.freertos.org/FAQHelp.html for
+ more tips, and ensure configASSERT() is defined!
+ https://www.freertos.org/a00110.html#configASSERT
+
+ 1) Stack overflow -
+ see https://www.freertos.org/Stacks-and-stack-overflow-checking.html
+ 2) Incorrect interrupt priority assignment, especially on Cortex-M
+ parts where numerically high priority values denote low actual
+ interrupt priorities, which can seem counter intuitive. See
+ https://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition
+ of configMAX_SYSCALL_INTERRUPT_PRIORITY on
+ https://www.freertos.org/a00110.html
+ 3) Calling an API function from within a critical section or when
+ the scheduler is suspended, or calling an API function that does
+ not end in "FromISR" from an interrupt.
+ 4) Using a queue or semaphore before it has been initialised or
+ before the scheduler has been started (are interrupts firing
+ before vTaskStartScheduler() has been called?).
+ **********************************************************************/
+
+ for (pxIterator = (ListItem_t *)&(pxList->xListEnd); pxIterator->pxNext->xItemValue <= xValueOfInsertion;
+ pxIterator
+ = pxIterator->pxNext) /*lint !e826 !e740 !e9087 The mini list structure is used as the list end to save RAM. This is checked and valid. */ /*lint !e440 The iterator moves to a
+ different value, not xValueOfInsertion. */
+ {
+ /* There is nothing to do here, just iterating to the wanted
+ insertion position. */
+ }
+ }
+
+ pxNewListItem->pxNext = pxIterator->pxNext;
+ pxNewListItem->pxNext->pxPrevious = pxNewListItem;
+ pxNewListItem->pxPrevious = pxIterator;
+ pxIterator->pxNext = pxNewListItem;
+
+ /* Remember which list the item is in. This allows fast removal of the
+ item later. */
+ pxNewListItem->pxContainer = pxList;
+
+ (pxList->uxNumberOfItems)++;
}
/*-----------------------------------------------------------*/
-UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove )
-{
-/* The list item knows which list it is in. Obtain the list from the list
-item. */
-List_t * const pxList = pxItemToRemove->pxContainer;
+UBaseType_t uxListRemove(ListItem_t *const pxItemToRemove) {
+ /* The list item knows which list it is in. Obtain the list from the list
+ item. */
+ List_t *const pxList = pxItemToRemove->pxContainer;
- pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious;
- pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext;
+ pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious;
+ pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext;
- /* Only used during decision coverage testing. */
- mtCOVERAGE_TEST_DELAY();
+ /* Only used during decision coverage testing. */
+ mtCOVERAGE_TEST_DELAY();
- /* Make sure the index is left pointing to a valid item. */
- if( pxList->pxIndex == pxItemToRemove )
- {
- pxList->pxIndex = pxItemToRemove->pxPrevious;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
+ /* Make sure the index is left pointing to a valid item. */
+ if (pxList->pxIndex == pxItemToRemove) {
+ pxList->pxIndex = pxItemToRemove->pxPrevious;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
- pxItemToRemove->pxContainer = NULL;
- ( pxList->uxNumberOfItems )--;
+ pxItemToRemove->pxContainer = NULL;
+ (pxList->uxNumberOfItems)--;
- return pxList->uxNumberOfItems;
+ return pxList->uxNumberOfItems;
}
/*-----------------------------------------------------------*/
-
diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/queue.c b/source/Middlewares/Third_Party/FreeRTOS/Source/queue.c
index e35055fa..8f3548ae 100644
--- a/source/Middlewares/Third_Party/FreeRTOS/Source/queue.c
+++ b/source/Middlewares/Third_Party/FreeRTOS/Source/queue.c
@@ -34,11 +34,11 @@ task.h is included from an application file. */
#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
#include "FreeRTOS.h"
-#include "task.h"
#include "queue.h"
+#include "task.h"
-#if ( configUSE_CO_ROUTINES == 1 )
- #include "croutine.h"
+#if (configUSE_CO_ROUTINES == 1)
+#include "croutine.h"
#endif
/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified
@@ -47,10 +47,9 @@ for the header files above, but not in this file, in order to generate the
correct privileged Vs unprivileged linkage and placement. */
#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750 !e9021. */
-
/* Constants used with the cRxLock and cTxLock structure members. */
-#define queueUNLOCKED ( ( int8_t ) -1 )
-#define queueLOCKED_UNMODIFIED ( ( int8_t ) 0 )
+#define queueUNLOCKED ((int8_t)-1)
+#define queueLOCKED_UNMODIFIED ((int8_t)0)
/* When the Queue_t structure is used to represent a base queue its pcHead and
pcTail members are used as pointers into the queue storage area. When the
@@ -61,32 +60,30 @@ names to the pcHead and structure member to ensure the readability of the code
is maintained. The QueuePointers_t and SemaphoreData_t types are used to form
a union as their usage is mutually exclusive dependent on what the queue is
being used for. */
-#define uxQueueType pcHead
-#define queueQUEUE_IS_MUTEX NULL
+#define uxQueueType pcHead
+#define queueQUEUE_IS_MUTEX NULL
-typedef struct QueuePointers
-{
- int8_t *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */
- int8_t *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */
+typedef struct QueuePointers {
+ int8_t *pcTail; /*< Points to the byte at the end of the queue storage area. Once more byte is allocated than necessary to store the queue items, this is used as a marker. */
+ int8_t *pcReadFrom; /*< Points to the last place that a queued item was read from when the structure is used as a queue. */
} QueuePointers_t;
-typedef struct SemaphoreData
-{
- TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */
- UBaseType_t uxRecursiveCallCount;/*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */
+typedef struct SemaphoreData {
+ TaskHandle_t xMutexHolder; /*< The handle of the task that holds the mutex. */
+ UBaseType_t uxRecursiveCallCount; /*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */
} SemaphoreData_t;
/* Semaphores do not actually store or copy data, so have an item size of
zero. */
-#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 )
-#define queueMUTEX_GIVE_BLOCK_TIME ( ( TickType_t ) 0U )
+#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ((UBaseType_t)0)
+#define queueMUTEX_GIVE_BLOCK_TIME ((TickType_t)0U)
-#if( configUSE_PREEMPTION == 0 )
- /* If the cooperative scheduler is being used then a yield should not be
- performed just because a higher priority task has been woken. */
- #define queueYIELD_IF_USING_PREEMPTION()
+#if (configUSE_PREEMPTION == 0)
+/* If the cooperative scheduler is being used then a yield should not be
+performed just because a higher priority task has been woken. */
+#define queueYIELD_IF_USING_PREEMPTION()
#else
- #define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API()
+#define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API()
#endif
/*
@@ -94,39 +91,38 @@ zero. */
* Items are queued by copy, not reference. See the following link for the
* rationale: https://www.freertos.org/Embedded-RTOS-Queues.html
*/
-typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */
+typedef struct QueueDefinition /* The old naming convention is used to prevent breaking kernel aware debuggers. */
{
- int8_t *pcHead; /*< Points to the beginning of the queue storage area. */
- int8_t *pcWriteTo; /*< Points to the free next place in the storage area. */
+ int8_t *pcHead; /*< Points to the beginning of the queue storage area. */
+ int8_t *pcWriteTo; /*< Points to the free next place in the storage area. */
- union
- {
- QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */
- SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */
- } u;
+ union {
+ QueuePointers_t xQueue; /*< Data required exclusively when this structure is used as a queue. */
+ SemaphoreData_t xSemaphore; /*< Data required exclusively when this structure is used as a semaphore. */
+ } u;
- List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */
- List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */
+ List_t xTasksWaitingToSend; /*< List of tasks that are blocked waiting to post onto this queue. Stored in priority order. */
+ List_t xTasksWaitingToReceive; /*< List of tasks that are blocked waiting to read from this queue. Stored in priority order. */
- volatile UBaseType_t uxMessagesWaiting;/*< The number of items currently in the queue. */
- UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */
- UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */
+ volatile UBaseType_t uxMessagesWaiting; /*< The number of items currently in the queue. */
+ UBaseType_t uxLength; /*< The length of the queue defined as the number of items it will hold, not the number of bytes. */
+ UBaseType_t uxItemSize; /*< The size of each items that the queue will hold. */
- volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */
- volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */
+ volatile int8_t cRxLock; /*< Stores the number of items received from the queue (removed from the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */
+ volatile int8_t cTxLock; /*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked. Set to queueUNLOCKED when the queue is not locked. */
- #if( ( configSUPPORT_STATIC_ALLOCATION == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
- uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */
- #endif
+#if ((configSUPPORT_STATIC_ALLOCATION == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1))
+ uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the memory used by the queue was statically allocated to ensure no attempt is made to free the memory. */
+#endif
- #if ( configUSE_QUEUE_SETS == 1 )
- struct QueueDefinition *pxQueueSetContainer;
- #endif
+#if (configUSE_QUEUE_SETS == 1)
+ struct QueueDefinition *pxQueueSetContainer;
+#endif
- #if ( configUSE_TRACE_FACILITY == 1 )
- UBaseType_t uxQueueNumber;
- uint8_t ucQueueType;
- #endif
+#if (configUSE_TRACE_FACILITY == 1)
+ UBaseType_t uxQueueNumber;
+ uint8_t ucQueueType;
+#endif
} xQUEUE;
@@ -140,26 +136,25 @@ typedef xQUEUE Queue_t;
* The queue registry is just a means for kernel aware debuggers to locate
* queue structures. It has no other purpose so is an optional component.
*/
-#if ( configQUEUE_REGISTRY_SIZE > 0 )
-
- /* The type stored within the queue registry array. This allows a name
- to be assigned to each queue making kernel aware debugging a little
- more user friendly. */
- typedef struct QUEUE_REGISTRY_ITEM
- {
- const char *pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- QueueHandle_t xHandle;
- } xQueueRegistryItem;
-
- /* The old xQueueRegistryItem name is maintained above then typedefed to the
- new xQueueRegistryItem name below to enable the use of older kernel aware
- debuggers. */
- typedef xQueueRegistryItem QueueRegistryItem_t;
-
- /* The queue registry is simply an array of QueueRegistryItem_t structures.
- The pcQueueName member of a structure being NULL is indicative of the
- array position being vacant. */
- PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ];
+#if (configQUEUE_REGISTRY_SIZE > 0)
+
+/* The type stored within the queue registry array. This allows a name
+to be assigned to each queue making kernel aware debugging a little
+more user friendly. */
+typedef struct QUEUE_REGISTRY_ITEM {
+ const char * pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ QueueHandle_t xHandle;
+} xQueueRegistryItem;
+
+/* The old xQueueRegistryItem name is maintained above then typedefed to the
+new xQueueRegistryItem name below to enable the use of older kernel aware
+debuggers. */
+typedef xQueueRegistryItem QueueRegistryItem_t;
+
+/* The queue registry is simply an array of QueueRegistryItem_t structures.
+The pcQueueName member of a structure being NULL is indicative of the
+array position being vacant. */
+PRIVILEGED_DATA QueueRegistryItem_t xQueueRegistry[configQUEUE_REGISTRY_SIZE];
#endif /* configQUEUE_REGISTRY_SIZE */
@@ -171,65 +166,65 @@ typedef xQUEUE Queue_t;
* to indicate that a task may require unblocking. When the queue in unlocked
* these lock counts are inspected, and the appropriate action taken.
*/
-static void prvUnlockQueue( Queue_t * const pxQueue ) PRIVILEGED_FUNCTION;
+static void prvUnlockQueue(Queue_t *const pxQueue) PRIVILEGED_FUNCTION;
/*
* Uses a critical section to determine if there is any data in a queue.
*
* @return pdTRUE if the queue contains no items, otherwise pdFALSE.
*/
-static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue ) PRIVILEGED_FUNCTION;
+static BaseType_t prvIsQueueEmpty(const Queue_t *pxQueue) PRIVILEGED_FUNCTION;
/*
* Uses a critical section to determine if there is any space in a queue.
*
* @return pdTRUE if there is no space, otherwise pdFALSE;
*/
-static BaseType_t prvIsQueueFull( const Queue_t *pxQueue ) PRIVILEGED_FUNCTION;
+static BaseType_t prvIsQueueFull(const Queue_t *pxQueue) PRIVILEGED_FUNCTION;
/*
* Copies an item into the queue, either at the front of the queue or the
* back of the queue.
*/
-static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition ) PRIVILEGED_FUNCTION;
+static BaseType_t prvCopyDataToQueue(Queue_t *const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition) PRIVILEGED_FUNCTION;
/*
* Copies an item out of a queue.
*/
-static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION;
-
-#if ( configUSE_QUEUE_SETS == 1 )
- /*
- * Checks to see if a queue is a member of a queue set, and if so, notifies
- * the queue set that the queue contains data.
- */
- static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION;
+static void prvCopyDataFromQueue(Queue_t *const pxQueue, void *const pvBuffer) PRIVILEGED_FUNCTION;
+
+#if (configUSE_QUEUE_SETS == 1)
+/*
+ * Checks to see if a queue is a member of a queue set, and if so, notifies
+ * the queue set that the queue contains data.
+ */
+static BaseType_t prvNotifyQueueSetContainer(const Queue_t *const pxQueue) PRIVILEGED_FUNCTION;
#endif
/*
* Called after a Queue_t structure has been allocated either statically or
* dynamically to fill in the structure's members.
*/
-static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION;
+static void prvInitialiseNewQueue(const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue) PRIVILEGED_FUNCTION;
/*
* Mutexes are a special type of queue. When a mutex is created, first the
* queue is created, then prvInitialiseMutex() is called to configure the queue
* as a mutex.
*/
-#if( configUSE_MUTEXES == 1 )
- static void prvInitialiseMutex( Queue_t *pxNewQueue ) PRIVILEGED_FUNCTION;
+#if (configUSE_MUTEXES == 1)
+static void prvInitialiseMutex(Queue_t *pxNewQueue) PRIVILEGED_FUNCTION;
#endif
-#if( configUSE_MUTEXES == 1 )
- /*
- * If a task waiting for a mutex causes the mutex holder to inherit a
- * priority, but the waiting task times out, then the holder should
- * disinherit the priority - but only down to the highest priority of any
- * other tasks that are waiting for the same mutex. This function returns
- * that priority.
- */
- static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue ) PRIVILEGED_FUNCTION;
+#if (configUSE_MUTEXES == 1)
+/*
+ * If a task waiting for a mutex causes the mutex holder to inherit a
+ * priority, but the waiting task times out, then the holder should
+ * disinherit the priority - but only down to the highest priority of any
+ * other tasks that are waiting for the same mutex. This function returns
+ * that priority.
+ */
+static UBaseType_t prvGetDisinheritPriorityAfterTimeout(const Queue_t *const pxQueue) PRIVILEGED_FUNCTION;
#endif
/*-----------------------------------------------------------*/
@@ -237,2709 +232,2205 @@ static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseT
* Macro to mark a queue as locked. Locking a queue prevents an ISR from
* accessing the queue event lists.
*/
-#define prvLockQueue( pxQueue ) \
- taskENTER_CRITICAL(); \
- { \
- if( ( pxQueue )->cRxLock == queueUNLOCKED ) \
- { \
- ( pxQueue )->cRxLock = queueLOCKED_UNMODIFIED; \
- } \
- if( ( pxQueue )->cTxLock == queueUNLOCKED ) \
- { \
- ( pxQueue )->cTxLock = queueLOCKED_UNMODIFIED; \
- } \
- } \
- taskEXIT_CRITICAL()
+#define prvLockQueue(pxQueue) \
+ taskENTER_CRITICAL(); \
+ { \
+ if ((pxQueue)->cRxLock == queueUNLOCKED) { \
+ (pxQueue)->cRxLock = queueLOCKED_UNMODIFIED; \
+ } \
+ if ((pxQueue)->cTxLock == queueUNLOCKED) { \
+ (pxQueue)->cTxLock = queueLOCKED_UNMODIFIED; \
+ } \
+ } \
+ taskEXIT_CRITICAL()
/*-----------------------------------------------------------*/
-BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue )
-{
-Queue_t * const pxQueue = xQueue;
-
- configASSERT( pxQueue );
-
- taskENTER_CRITICAL();
- {
- pxQueue->u.xQueue.pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */
- pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U;
- pxQueue->pcWriteTo = pxQueue->pcHead;
- pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - 1U ) * pxQueue->uxItemSize ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */
- pxQueue->cRxLock = queueUNLOCKED;
- pxQueue->cTxLock = queueUNLOCKED;
-
- if( xNewQueue == pdFALSE )
- {
- /* If there are tasks blocked waiting to read from the queue, then
- the tasks will remain blocked as after this function exits the queue
- will still be empty. If there are tasks blocked waiting to write to
- the queue, then one should be unblocked as after this function exits
- it will be possible to write to it. */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
- {
- queueYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* Ensure the event queues start in the correct state. */
- vListInitialise( &( pxQueue->xTasksWaitingToSend ) );
- vListInitialise( &( pxQueue->xTasksWaitingToReceive ) );
- }
- }
- taskEXIT_CRITICAL();
-
- /* A value is returned for calling semantic consistency with previous
- versions. */
- return pdPASS;
+BaseType_t xQueueGenericReset(QueueHandle_t xQueue, BaseType_t xNewQueue) {
+ Queue_t *const pxQueue = xQueue;
+
+ configASSERT(pxQueue);
+
+ taskENTER_CRITICAL();
+ {
+ pxQueue->u.xQueue.pcTail = pxQueue->pcHead + (pxQueue->uxLength * pxQueue->uxItemSize); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */
+ pxQueue->uxMessagesWaiting = (UBaseType_t)0U;
+ pxQueue->pcWriteTo = pxQueue->pcHead;
+ pxQueue->u.xQueue.pcReadFrom
+ = pxQueue->pcHead + ((pxQueue->uxLength - 1U) * pxQueue->uxItemSize); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */
+ pxQueue->cRxLock = queueUNLOCKED;
+ pxQueue->cTxLock = queueUNLOCKED;
+
+ if (xNewQueue == pdFALSE) {
+ /* If there are tasks blocked waiting to read from the queue, then
+ the tasks will remain blocked as after this function exits the queue
+ will still be empty. If there are tasks blocked waiting to write to
+ the queue, then one should be unblocked as after this function exits
+ it will be possible to write to it. */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToSend)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToSend)) != pdFALSE) {
+ queueYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* Ensure the event queues start in the correct state. */
+ vListInitialise(&(pxQueue->xTasksWaitingToSend));
+ vListInitialise(&(pxQueue->xTasksWaitingToReceive));
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ /* A value is returned for calling semantic consistency with previous
+ versions. */
+ return pdPASS;
}
/*-----------------------------------------------------------*/
-#if( configSUPPORT_STATIC_ALLOCATION == 1 )
-
- QueueHandle_t xQueueGenericCreateStatic( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType )
- {
- Queue_t *pxNewQueue;
-
- configASSERT( uxQueueLength > ( UBaseType_t ) 0 );
-
- /* The StaticQueue_t structure and the queue storage area must be
- supplied. */
- configASSERT( pxStaticQueue != NULL );
-
- /* A queue storage area should be provided if the item size is not 0, and
- should not be provided if the item size is 0. */
- configASSERT( !( ( pucQueueStorage != NULL ) && ( uxItemSize == 0 ) ) );
- configASSERT( !( ( pucQueueStorage == NULL ) && ( uxItemSize != 0 ) ) );
-
- #if( configASSERT_DEFINED == 1 )
- {
- /* Sanity check that the size of the structure used to declare a
- variable of type StaticQueue_t or StaticSemaphore_t equals the size of
- the real queue and semaphore structures. */
- volatile size_t xSize = sizeof( StaticQueue_t );
- configASSERT( xSize == sizeof( Queue_t ) );
- ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */
- }
- #endif /* configASSERT_DEFINED */
-
- /* The address of a statically allocated queue was passed in, use it.
- The address of a statically allocated storage area was also passed in
- but is already set. */
- pxNewQueue = ( Queue_t * ) pxStaticQueue; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */
-
- if( pxNewQueue != NULL )
- {
- #if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
- {
- /* Queues can be allocated wither statically or dynamically, so
- note this queue was allocated statically in case the queue is
- later deleted. */
- pxNewQueue->ucStaticallyAllocated = pdTRUE;
- }
- #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
-
- prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue );
- }
- else
- {
- traceQUEUE_CREATE_FAILED( ucQueueType );
- mtCOVERAGE_TEST_MARKER();
- }
-
- return pxNewQueue;
- }
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
+
+QueueHandle_t xQueueGenericCreateStatic(const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, StaticQueue_t *pxStaticQueue, const uint8_t ucQueueType) {
+ Queue_t *pxNewQueue;
+
+ configASSERT(uxQueueLength > (UBaseType_t)0);
+
+ /* The StaticQueue_t structure and the queue storage area must be
+ supplied. */
+ configASSERT(pxStaticQueue != NULL);
+
+ /* A queue storage area should be provided if the item size is not 0, and
+ should not be provided if the item size is 0. */
+ configASSERT(!((pucQueueStorage != NULL) && (uxItemSize == 0)));
+ configASSERT(!((pucQueueStorage == NULL) && (uxItemSize != 0)));
+
+#if (configASSERT_DEFINED == 1)
+ {
+ /* Sanity check that the size of the structure used to declare a
+ variable of type StaticQueue_t or StaticSemaphore_t equals the size of
+ the real queue and semaphore structures. */
+ volatile size_t xSize = sizeof(StaticQueue_t);
+ configASSERT(xSize == sizeof(Queue_t));
+ (void)xSize; /* Keeps lint quiet when configASSERT() is not defined. */
+ }
+#endif /* configASSERT_DEFINED */
+
+ /* The address of a statically allocated queue was passed in, use it.
+ The address of a statically allocated storage area was also passed in
+ but is already set. */
+ pxNewQueue = (Queue_t *)pxStaticQueue; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */
+
+ if (pxNewQueue != NULL) {
+#if (configSUPPORT_DYNAMIC_ALLOCATION == 1)
+ {
+ /* Queues can be allocated wither statically or dynamically, so
+ note this queue was allocated statically in case the queue is
+ later deleted. */
+ pxNewQueue->ucStaticallyAllocated = pdTRUE;
+ }
+#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
+
+ prvInitialiseNewQueue(uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue);
+ } else {
+ traceQUEUE_CREATE_FAILED(ucQueueType);
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return pxNewQueue;
+}
#endif /* configSUPPORT_STATIC_ALLOCATION */
/*-----------------------------------------------------------*/
-#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
-
- QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType )
- {
- Queue_t *pxNewQueue;
- size_t xQueueSizeInBytes;
- uint8_t *pucQueueStorage;
-
- configASSERT( uxQueueLength > ( UBaseType_t ) 0 );
-
- /* Allocate enough space to hold the maximum number of items that
- can be in the queue at any time. It is valid for uxItemSize to be
- zero in the case the queue is used as a semaphore. */
- xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
-
- /* Allocate the queue and storage area. Justification for MISRA
- deviation as follows: pvPortMalloc() always ensures returned memory
- blocks are aligned per the requirements of the MCU stack. In this case
- pvPortMalloc() must return a pointer that is guaranteed to meet the
- alignment requirements of the Queue_t structure - which in this case
- is an int8_t *. Therefore, whenever the stack alignment requirements
- are greater than or equal to the pointer to char requirements the cast
- is safe. In other cases alignment requirements are not strict (one or
- two bytes). */
- pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes ); /*lint !e9087 !e9079 see comment above. */
-
- if( pxNewQueue != NULL )
- {
- /* Jump past the queue structure to find the location of the queue
- storage area. */
- pucQueueStorage = ( uint8_t * ) pxNewQueue;
- pucQueueStorage += sizeof( Queue_t ); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */
-
- #if( configSUPPORT_STATIC_ALLOCATION == 1 )
- {
- /* Queues can be created either statically or dynamically, so
- note this task was created dynamically in case it is later
- deleted. */
- pxNewQueue->ucStaticallyAllocated = pdFALSE;
- }
- #endif /* configSUPPORT_STATIC_ALLOCATION */
-
- prvInitialiseNewQueue( uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue );
- }
- else
- {
- traceQUEUE_CREATE_FAILED( ucQueueType );
- mtCOVERAGE_TEST_MARKER();
- }
-
- return pxNewQueue;
- }
+#if (configSUPPORT_DYNAMIC_ALLOCATION == 1)
+
+QueueHandle_t xQueueGenericCreate(const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType) {
+ Queue_t *pxNewQueue;
+ size_t xQueueSizeInBytes;
+ uint8_t *pucQueueStorage;
+
+ configASSERT(uxQueueLength > (UBaseType_t)0);
+
+ /* Allocate enough space to hold the maximum number of items that
+ can be in the queue at any time. It is valid for uxItemSize to be
+ zero in the case the queue is used as a semaphore. */
+ xQueueSizeInBytes = (size_t)(uxQueueLength * uxItemSize); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+
+ /* Allocate the queue and storage area. Justification for MISRA
+ deviation as follows: pvPortMalloc() always ensures returned memory
+ blocks are aligned per the requirements of the MCU stack. In this case
+ pvPortMalloc() must return a pointer that is guaranteed to meet the
+ alignment requirements of the Queue_t structure - which in this case
+ is an int8_t *. Therefore, whenever the stack alignment requirements
+ are greater than or equal to the pointer to char requirements the cast
+ is safe. In other cases alignment requirements are not strict (one or
+ two bytes). */
+ pxNewQueue = (Queue_t *)pvPortMalloc(sizeof(Queue_t) + xQueueSizeInBytes); /*lint !e9087 !e9079 see comment above. */
+
+ if (pxNewQueue != NULL) {
+ /* Jump past the queue structure to find the location of the queue
+ storage area. */
+ pucQueueStorage = (uint8_t *)pxNewQueue;
+ pucQueueStorage += sizeof(Queue_t); /*lint !e9016 Pointer arithmetic allowed on char types, especially when it assists conveying intent. */
+
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
+ {
+ /* Queues can be created either statically or dynamically, so
+ note this task was created dynamically in case it is later
+ deleted. */
+ pxNewQueue->ucStaticallyAllocated = pdFALSE;
+ }
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+ prvInitialiseNewQueue(uxQueueLength, uxItemSize, pucQueueStorage, ucQueueType, pxNewQueue);
+ } else {
+ traceQUEUE_CREATE_FAILED(ucQueueType);
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return pxNewQueue;
+}
#endif /* configSUPPORT_STATIC_ALLOCATION */
/*-----------------------------------------------------------*/
-static void prvInitialiseNewQueue( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue )
-{
- /* Remove compiler warnings about unused parameters should
- configUSE_TRACE_FACILITY not be set to 1. */
- ( void ) ucQueueType;
-
- if( uxItemSize == ( UBaseType_t ) 0 )
- {
- /* No RAM was allocated for the queue storage area, but PC head cannot
- be set to NULL because NULL is used as a key to say the queue is used as
- a mutex. Therefore just set pcHead to point to the queue as a benign
- value that is known to be within the memory map. */
- pxNewQueue->pcHead = ( int8_t * ) pxNewQueue;
- }
- else
- {
- /* Set the head to the start of the queue storage area. */
- pxNewQueue->pcHead = ( int8_t * ) pucQueueStorage;
- }
-
- /* Initialise the queue members as described where the queue type is
- defined. */
- pxNewQueue->uxLength = uxQueueLength;
- pxNewQueue->uxItemSize = uxItemSize;
- ( void ) xQueueGenericReset( pxNewQueue, pdTRUE );
-
- #if ( configUSE_TRACE_FACILITY == 1 )
- {
- pxNewQueue->ucQueueType = ucQueueType;
- }
- #endif /* configUSE_TRACE_FACILITY */
-
- #if( configUSE_QUEUE_SETS == 1 )
- {
- pxNewQueue->pxQueueSetContainer = NULL;
- }
- #endif /* configUSE_QUEUE_SETS */
-
- traceQUEUE_CREATE( pxNewQueue );
+static void prvInitialiseNewQueue(const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, uint8_t *pucQueueStorage, const uint8_t ucQueueType, Queue_t *pxNewQueue) {
+ /* Remove compiler warnings about unused parameters should
+ configUSE_TRACE_FACILITY not be set to 1. */
+ (void)ucQueueType;
+
+ if (uxItemSize == (UBaseType_t)0) {
+ /* No RAM was allocated for the queue storage area, but PC head cannot
+ be set to NULL because NULL is used as a key to say the queue is used as
+ a mutex. Therefore just set pcHead to point to the queue as a benign
+ value that is known to be within the memory map. */
+ pxNewQueue->pcHead = (int8_t *)pxNewQueue;
+ } else {
+ /* Set the head to the start of the queue storage area. */
+ pxNewQueue->pcHead = (int8_t *)pucQueueStorage;
+ }
+
+ /* Initialise the queue members as described where the queue type is
+ defined. */
+ pxNewQueue->uxLength = uxQueueLength;
+ pxNewQueue->uxItemSize = uxItemSize;
+ (void)xQueueGenericReset(pxNewQueue, pdTRUE);
+
+#if (configUSE_TRACE_FACILITY == 1)
+ { pxNewQueue->ucQueueType = ucQueueType; }
+#endif /* configUSE_TRACE_FACILITY */
+
+#if (configUSE_QUEUE_SETS == 1)
+ { pxNewQueue->pxQueueSetContainer = NULL; }
+#endif /* configUSE_QUEUE_SETS */
+
+ traceQUEUE_CREATE(pxNewQueue);
}
/*-----------------------------------------------------------*/
-#if( configUSE_MUTEXES == 1 )
-
- static void prvInitialiseMutex( Queue_t *pxNewQueue )
- {
- if( pxNewQueue != NULL )
- {
- /* The queue create function will set all the queue structure members
- correctly for a generic queue, but this function is creating a
- mutex. Overwrite those members that need to be set differently -
- in particular the information required for priority inheritance. */
- pxNewQueue->u.xSemaphore.xMutexHolder = NULL;
- pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX;
-
- /* In case this is a recursive mutex. */
- pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0;
-
- traceCREATE_MUTEX( pxNewQueue );
-
- /* Start with the semaphore in the expected state. */
- ( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK );
- }
- else
- {
- traceCREATE_MUTEX_FAILED();
- }
- }
+#if (configUSE_MUTEXES == 1)
+
+static void prvInitialiseMutex(Queue_t *pxNewQueue) {
+ if (pxNewQueue != NULL) {
+ /* The queue create function will set all the queue structure members
+ correctly for a generic queue, but this function is creating a
+ mutex. Overwrite those members that need to be set differently -
+ in particular the information required for priority inheritance. */
+ pxNewQueue->u.xSemaphore.xMutexHolder = NULL;
+ pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX;
+
+ /* In case this is a recursive mutex. */
+ pxNewQueue->u.xSemaphore.uxRecursiveCallCount = 0;
+
+ traceCREATE_MUTEX(pxNewQueue);
+
+ /* Start with the semaphore in the expected state. */
+ (void)xQueueGenericSend(pxNewQueue, NULL, (TickType_t)0U, queueSEND_TO_BACK);
+ } else {
+ traceCREATE_MUTEX_FAILED();
+ }
+}
#endif /* configUSE_MUTEXES */
/*-----------------------------------------------------------*/
-#if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
+#if ((configUSE_MUTEXES == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1))
- QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType )
- {
- QueueHandle_t xNewQueue;
- const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0;
+QueueHandle_t xQueueCreateMutex(const uint8_t ucQueueType) {
+ QueueHandle_t xNewQueue;
+ const UBaseType_t uxMutexLength = (UBaseType_t)1, uxMutexSize = (UBaseType_t)0;
- xNewQueue = xQueueGenericCreate( uxMutexLength, uxMutexSize, ucQueueType );
- prvInitialiseMutex( ( Queue_t * ) xNewQueue );
+ xNewQueue = xQueueGenericCreate(uxMutexLength, uxMutexSize, ucQueueType);
+ prvInitialiseMutex((Queue_t *)xNewQueue);
- return xNewQueue;
- }
+ return xNewQueue;
+}
#endif /* configUSE_MUTEXES */
/*-----------------------------------------------------------*/
-#if( ( configUSE_MUTEXES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
+#if ((configUSE_MUTEXES == 1) && (configSUPPORT_STATIC_ALLOCATION == 1))
- QueueHandle_t xQueueCreateMutexStatic( const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue )
- {
- QueueHandle_t xNewQueue;
- const UBaseType_t uxMutexLength = ( UBaseType_t ) 1, uxMutexSize = ( UBaseType_t ) 0;
+QueueHandle_t xQueueCreateMutexStatic(const uint8_t ucQueueType, StaticQueue_t *pxStaticQueue) {
+ QueueHandle_t xNewQueue;
+ const UBaseType_t uxMutexLength = (UBaseType_t)1, uxMutexSize = (UBaseType_t)0;
- /* Prevent compiler warnings about unused parameters if
- configUSE_TRACE_FACILITY does not equal 1. */
- ( void ) ucQueueType;
+ /* Prevent compiler warnings about unused parameters if
+ configUSE_TRACE_FACILITY does not equal 1. */
+ (void)ucQueueType;
- xNewQueue = xQueueGenericCreateStatic( uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType );
- prvInitialiseMutex( ( Queue_t * ) xNewQueue );
+ xNewQueue = xQueueGenericCreateStatic(uxMutexLength, uxMutexSize, NULL, pxStaticQueue, ucQueueType);
+ prvInitialiseMutex((Queue_t *)xNewQueue);
- return xNewQueue;
- }
+ return xNewQueue;
+}
#endif /* configUSE_MUTEXES */
/*-----------------------------------------------------------*/
-#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) )
-
- TaskHandle_t xQueueGetMutexHolder( QueueHandle_t xSemaphore )
- {
- TaskHandle_t pxReturn;
- Queue_t * const pxSemaphore = ( Queue_t * ) xSemaphore;
-
- /* This function is called by xSemaphoreGetMutexHolder(), and should not
- be called directly. Note: This is a good way of determining if the
- calling task is the mutex holder, but not a good way of determining the
- identity of the mutex holder, as the holder may change between the
- following critical section exiting and the function returning. */
- taskENTER_CRITICAL();
- {
- if( pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX )
- {
- pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder;
- }
- else
- {
- pxReturn = NULL;
- }
- }
- taskEXIT_CRITICAL();
-
- return pxReturn;
- } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */
+#if ((configUSE_MUTEXES == 1) && (INCLUDE_xSemaphoreGetMutexHolder == 1))
+
+TaskHandle_t xQueueGetMutexHolder(QueueHandle_t xSemaphore) {
+ TaskHandle_t pxReturn;
+ Queue_t *const pxSemaphore = (Queue_t *)xSemaphore;
+
+ /* This function is called by xSemaphoreGetMutexHolder(), and should not
+ be called directly. Note: This is a good way of determining if the
+ calling task is the mutex holder, but not a good way of determining the
+ identity of the mutex holder, as the holder may change between the
+ following critical section exiting and the function returning. */
+ taskENTER_CRITICAL();
+ {
+ if (pxSemaphore->uxQueueType == queueQUEUE_IS_MUTEX) {
+ pxReturn = pxSemaphore->u.xSemaphore.xMutexHolder;
+ } else {
+ pxReturn = NULL;
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return pxReturn;
+} /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */
#endif
/*-----------------------------------------------------------*/
-#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) )
+#if ((configUSE_MUTEXES == 1) && (INCLUDE_xSemaphoreGetMutexHolder == 1))
- TaskHandle_t xQueueGetMutexHolderFromISR( QueueHandle_t xSemaphore )
- {
- TaskHandle_t pxReturn;
+TaskHandle_t xQueueGetMutexHolderFromISR(QueueHandle_t xSemaphore) {
+ TaskHandle_t pxReturn;
- configASSERT( xSemaphore );
+ configASSERT(xSemaphore);
- /* Mutexes cannot be used in interrupt service routines, so the mutex
- holder should not change in an ISR, and therefore a critical section is
- not required here. */
- if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX )
- {
- pxReturn = ( ( Queue_t * ) xSemaphore )->u.xSemaphore.xMutexHolder;
- }
- else
- {
- pxReturn = NULL;
- }
+ /* Mutexes cannot be used in interrupt service routines, so the mutex
+ holder should not change in an ISR, and therefore a critical section is
+ not required here. */
+ if (((Queue_t *)xSemaphore)->uxQueueType == queueQUEUE_IS_MUTEX) {
+ pxReturn = ((Queue_t *)xSemaphore)->u.xSemaphore.xMutexHolder;
+ } else {
+ pxReturn = NULL;
+ }
- return pxReturn;
- } /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */
+ return pxReturn;
+} /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */
#endif
/*-----------------------------------------------------------*/
-#if ( configUSE_RECURSIVE_MUTEXES == 1 )
-
- BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex )
- {
- BaseType_t xReturn;
- Queue_t * const pxMutex = ( Queue_t * ) xMutex;
-
- configASSERT( pxMutex );
-
- /* If this is the task that holds the mutex then xMutexHolder will not
- change outside of this task. If this task does not hold the mutex then
- pxMutexHolder can never coincidentally equal the tasks handle, and as
- this is the only condition we are interested in it does not matter if
- pxMutexHolder is accessed simultaneously by another task. Therefore no
- mutual exclusion is required to test the pxMutexHolder variable. */
- if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() )
- {
- traceGIVE_MUTEX_RECURSIVE( pxMutex );
-
- /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to
- the task handle, therefore no underflow check is required. Also,
- uxRecursiveCallCount is only modified by the mutex holder, and as
- there can only be one, no mutual exclusion is required to modify the
- uxRecursiveCallCount member. */
- ( pxMutex->u.xSemaphore.uxRecursiveCallCount )--;
-
- /* Has the recursive call count unwound to 0? */
- if( pxMutex->u.xSemaphore.uxRecursiveCallCount == ( UBaseType_t ) 0 )
- {
- /* Return the mutex. This will automatically unblock any other
- task that might be waiting to access the mutex. */
- ( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- xReturn = pdPASS;
- }
- else
- {
- /* The mutex cannot be given because the calling task is not the
- holder. */
- xReturn = pdFAIL;
-
- traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex );
- }
-
- return xReturn;
- }
+#if (configUSE_RECURSIVE_MUTEXES == 1)
+
+BaseType_t xQueueGiveMutexRecursive(QueueHandle_t xMutex) {
+ BaseType_t xReturn;
+ Queue_t *const pxMutex = (Queue_t *)xMutex;
+
+ configASSERT(pxMutex);
+
+ /* If this is the task that holds the mutex then xMutexHolder will not
+ change outside of this task. If this task does not hold the mutex then
+ pxMutexHolder can never coincidentally equal the tasks handle, and as
+ this is the only condition we are interested in it does not matter if
+ pxMutexHolder is accessed simultaneously by another task. Therefore no
+ mutual exclusion is required to test the pxMutexHolder variable. */
+ if (pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle()) {
+ traceGIVE_MUTEX_RECURSIVE(pxMutex);
+
+ /* uxRecursiveCallCount cannot be zero if xMutexHolder is equal to
+ the task handle, therefore no underflow check is required. Also,
+ uxRecursiveCallCount is only modified by the mutex holder, and as
+ there can only be one, no mutual exclusion is required to modify the
+ uxRecursiveCallCount member. */
+ (pxMutex->u.xSemaphore.uxRecursiveCallCount)--;
+
+ /* Has the recursive call count unwound to 0? */
+ if (pxMutex->u.xSemaphore.uxRecursiveCallCount == (UBaseType_t)0) {
+ /* Return the mutex. This will automatically unblock any other
+ task that might be waiting to access the mutex. */
+ (void)xQueueGenericSend(pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ xReturn = pdPASS;
+ } else {
+ /* The mutex cannot be given because the calling task is not the
+ holder. */
+ xReturn = pdFAIL;
+
+ traceGIVE_MUTEX_RECURSIVE_FAILED(pxMutex);
+ }
+
+ return xReturn;
+}
#endif /* configUSE_RECURSIVE_MUTEXES */
/*-----------------------------------------------------------*/
-#if ( configUSE_RECURSIVE_MUTEXES == 1 )
-
- BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait )
- {
- BaseType_t xReturn;
- Queue_t * const pxMutex = ( Queue_t * ) xMutex;
-
- configASSERT( pxMutex );
-
- /* Comments regarding mutual exclusion as per those within
- xQueueGiveMutexRecursive(). */
-
- traceTAKE_MUTEX_RECURSIVE( pxMutex );
-
- if( pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle() )
- {
- ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++;
- xReturn = pdPASS;
- }
- else
- {
- xReturn = xQueueSemaphoreTake( pxMutex, xTicksToWait );
-
- /* pdPASS will only be returned if the mutex was successfully
- obtained. The calling task may have entered the Blocked state
- before reaching here. */
- if( xReturn != pdFAIL )
- {
- ( pxMutex->u.xSemaphore.uxRecursiveCallCount )++;
- }
- else
- {
- traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex );
- }
- }
-
- return xReturn;
- }
+#if (configUSE_RECURSIVE_MUTEXES == 1)
+
+BaseType_t xQueueTakeMutexRecursive(QueueHandle_t xMutex, TickType_t xTicksToWait) {
+ BaseType_t xReturn;
+ Queue_t *const pxMutex = (Queue_t *)xMutex;
+
+ configASSERT(pxMutex);
+
+ /* Comments regarding mutual exclusion as per those within
+ xQueueGiveMutexRecursive(). */
+
+ traceTAKE_MUTEX_RECURSIVE(pxMutex);
+
+ if (pxMutex->u.xSemaphore.xMutexHolder == xTaskGetCurrentTaskHandle()) {
+ (pxMutex->u.xSemaphore.uxRecursiveCallCount)++;
+ xReturn = pdPASS;
+ } else {
+ xReturn = xQueueSemaphoreTake(pxMutex, xTicksToWait);
+
+ /* pdPASS will only be returned if the mutex was successfully
+ obtained. The calling task may have entered the Blocked state
+ before reaching here. */
+ if (xReturn != pdFAIL) {
+ (pxMutex->u.xSemaphore.uxRecursiveCallCount)++;
+ } else {
+ traceTAKE_MUTEX_RECURSIVE_FAILED(pxMutex);
+ }
+ }
+
+ return xReturn;
+}
#endif /* configUSE_RECURSIVE_MUTEXES */
/*-----------------------------------------------------------*/
-#if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
+#if ((configUSE_COUNTING_SEMAPHORES == 1) && (configSUPPORT_STATIC_ALLOCATION == 1))
- QueueHandle_t xQueueCreateCountingSemaphoreStatic( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue )
- {
- QueueHandle_t xHandle;
+QueueHandle_t xQueueCreateCountingSemaphoreStatic(const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount, StaticQueue_t *pxStaticQueue) {
+ QueueHandle_t xHandle;
- configASSERT( uxMaxCount != 0 );
- configASSERT( uxInitialCount <= uxMaxCount );
+ configASSERT(uxMaxCount != 0);
+ configASSERT(uxInitialCount <= uxMaxCount);
- xHandle = xQueueGenericCreateStatic( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE );
+ xHandle = xQueueGenericCreateStatic(uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, NULL, pxStaticQueue, queueQUEUE_TYPE_COUNTING_SEMAPHORE);
- if( xHandle != NULL )
- {
- ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount;
+ if (xHandle != NULL) {
+ ((Queue_t *)xHandle)->uxMessagesWaiting = uxInitialCount;
- traceCREATE_COUNTING_SEMAPHORE();
- }
- else
- {
- traceCREATE_COUNTING_SEMAPHORE_FAILED();
- }
+ traceCREATE_COUNTING_SEMAPHORE();
+ } else {
+ traceCREATE_COUNTING_SEMAPHORE_FAILED();
+ }
- return xHandle;
- }
+ return xHandle;
+}
#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */
/*-----------------------------------------------------------*/
-#if( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
+#if ((configUSE_COUNTING_SEMAPHORES == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1))
- QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount )
- {
- QueueHandle_t xHandle;
+QueueHandle_t xQueueCreateCountingSemaphore(const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount) {
+ QueueHandle_t xHandle;
- configASSERT( uxMaxCount != 0 );
- configASSERT( uxInitialCount <= uxMaxCount );
+ configASSERT(uxMaxCount != 0);
+ configASSERT(uxInitialCount <= uxMaxCount);
- xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE );
+ xHandle = xQueueGenericCreate(uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE);
- if( xHandle != NULL )
- {
- ( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount;
+ if (xHandle != NULL) {
+ ((Queue_t *)xHandle)->uxMessagesWaiting = uxInitialCount;
- traceCREATE_COUNTING_SEMAPHORE();
- }
- else
- {
- traceCREATE_COUNTING_SEMAPHORE_FAILED();
- }
+ traceCREATE_COUNTING_SEMAPHORE();
+ } else {
+ traceCREATE_COUNTING_SEMAPHORE_FAILED();
+ }
- return xHandle;
- }
+ return xHandle;
+}
#endif /* ( ( configUSE_COUNTING_SEMAPHORES == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */
/*-----------------------------------------------------------*/
-BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition )
-{
-BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired;
-TimeOut_t xTimeOut;
-Queue_t * const pxQueue = xQueue;
-
- configASSERT( pxQueue );
- configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
- configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) );
- #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
- {
- configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
- }
- #endif
-
-
- /*lint -save -e904 This function relaxes the coding standard somewhat to
- allow return statements within the function itself. This is done in the
- interest of execution time efficiency. */
- for( ;; )
- {
- taskENTER_CRITICAL();
- {
- /* Is there room on the queue now? The running task must be the
- highest priority task wanting to access the queue. If the head item
- in the queue is to be overwritten then it does not matter if the
- queue is full. */
- if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) )
- {
- traceQUEUE_SEND( pxQueue );
-
- #if ( configUSE_QUEUE_SETS == 1 )
- {
- const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting;
-
- xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition );
-
- if( pxQueue->pxQueueSetContainer != NULL )
- {
- if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) )
- {
- /* Do not notify the queue set as an existing item
- was overwritten in the queue so the number of items
- in the queue has not changed. */
- mtCOVERAGE_TEST_MARKER();
- }
- else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE )
- {
- /* The queue is a member of a queue set, and posting
- to the queue set caused a higher priority task to
- unblock. A context switch is required. */
- queueYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* If there was a task waiting for data to arrive on the
- queue then unblock it now. */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The unblocked task has a priority higher than
- our own so yield immediately. Yes it is ok to
- do this from within the critical section - the
- kernel takes care of that. */
- queueYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else if( xYieldRequired != pdFALSE )
- {
- /* This path is a special case that will only get
- executed if the task was holding multiple mutexes
- and the mutexes were given back in an order that is
- different to that in which they were taken. */
- queueYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- #else /* configUSE_QUEUE_SETS */
- {
- xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition );
-
- /* If there was a task waiting for data to arrive on the
- queue then unblock it now. */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The unblocked task has a priority higher than
- our own so yield immediately. Yes it is ok to do
- this from within the critical section - the kernel
- takes care of that. */
- queueYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else if( xYieldRequired != pdFALSE )
- {
- /* This path is a special case that will only get
- executed if the task was holding multiple mutexes and
- the mutexes were given back in an order that is
- different to that in which they were taken. */
- queueYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_QUEUE_SETS */
-
- taskEXIT_CRITICAL();
- return pdPASS;
- }
- else
- {
- if( xTicksToWait == ( TickType_t ) 0 )
- {
- /* The queue was full and no block time is specified (or
- the block time has expired) so leave now. */
- taskEXIT_CRITICAL();
-
- /* Return to the original privilege level before exiting
- the function. */
- traceQUEUE_SEND_FAILED( pxQueue );
- return errQUEUE_FULL;
- }
- else if( xEntryTimeSet == pdFALSE )
- {
- /* The queue was full and a block time was specified so
- configure the timeout structure. */
- vTaskInternalSetTimeOutState( &xTimeOut );
- xEntryTimeSet = pdTRUE;
- }
- else
- {
- /* Entry time was already set. */
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- taskEXIT_CRITICAL();
-
- /* Interrupts and other tasks can send to and receive from the queue
- now the critical section has been exited. */
-
- vTaskSuspendAll();
- prvLockQueue( pxQueue );
-
- /* Update the timeout state to see if it has expired yet. */
- if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE )
- {
- if( prvIsQueueFull( pxQueue ) != pdFALSE )
- {
- traceBLOCKING_ON_QUEUE_SEND( pxQueue );
- vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait );
-
- /* Unlocking the queue means queue events can effect the
- event list. It is possible that interrupts occurring now
- remove this task from the event list again - but as the
- scheduler is suspended the task will go onto the pending
- ready last instead of the actual ready list. */
- prvUnlockQueue( pxQueue );
-
- /* Resuming the scheduler will move tasks from the pending
- ready list into the ready list - so it is feasible that this
- task is already in a ready list before it yields - in which
- case the yield will not cause a context switch unless there
- is also a higher priority task in the pending ready list. */
- if( xTaskResumeAll() == pdFALSE )
- {
- portYIELD_WITHIN_API();
- }
- }
- else
- {
- /* Try again. */
- prvUnlockQueue( pxQueue );
- ( void ) xTaskResumeAll();
- }
- }
- else
- {
- /* The timeout has expired. */
- prvUnlockQueue( pxQueue );
- ( void ) xTaskResumeAll();
-
- traceQUEUE_SEND_FAILED( pxQueue );
- return errQUEUE_FULL;
- }
- } /*lint -restore */
+BaseType_t xQueueGenericSend(QueueHandle_t xQueue, const void *const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition) {
+ BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired;
+ TimeOut_t xTimeOut;
+ Queue_t *const pxQueue = xQueue;
+
+ configASSERT(pxQueue);
+ configASSERT(!((pvItemToQueue == NULL) && (pxQueue->uxItemSize != (UBaseType_t)0U)));
+ configASSERT(!((xCopyPosition == queueOVERWRITE) && (pxQueue->uxLength != 1)));
+#if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1))
+ { configASSERT(!((xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED) && (xTicksToWait != 0))); }
+#endif
+
+ /*lint -save -e904 This function relaxes the coding standard somewhat to
+ allow return statements within the function itself. This is done in the
+ interest of execution time efficiency. */
+ for (;;) {
+ taskENTER_CRITICAL();
+ {
+ /* Is there room on the queue now? The running task must be the
+ highest priority task wanting to access the queue. If the head item
+ in the queue is to be overwritten then it does not matter if the
+ queue is full. */
+ if ((pxQueue->uxMessagesWaiting < pxQueue->uxLength) || (xCopyPosition == queueOVERWRITE)) {
+ traceQUEUE_SEND(pxQueue);
+
+#if (configUSE_QUEUE_SETS == 1)
+ {
+ const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting;
+
+ xYieldRequired = prvCopyDataToQueue(pxQueue, pvItemToQueue, xCopyPosition);
+
+ if (pxQueue->pxQueueSetContainer != NULL) {
+ if ((xCopyPosition == queueOVERWRITE) && (uxPreviousMessagesWaiting != (UBaseType_t)0)) {
+ /* Do not notify the queue set as an existing item
+ was overwritten in the queue so the number of items
+ in the queue has not changed. */
+ mtCOVERAGE_TEST_MARKER();
+ } else if (prvNotifyQueueSetContainer(pxQueue) != pdFALSE) {
+ /* The queue is a member of a queue set, and posting
+ to the queue set caused a higher priority task to
+ unblock. A context switch is required. */
+ queueYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* If there was a task waiting for data to arrive on the
+ queue then unblock it now. */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The unblocked task has a priority higher than
+ our own so yield immediately. Yes it is ok to
+ do this from within the critical section - the
+ kernel takes care of that. */
+ queueYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else if (xYieldRequired != pdFALSE) {
+ /* This path is a special case that will only get
+ executed if the task was holding multiple mutexes
+ and the mutexes were given back in an order that is
+ different to that in which they were taken. */
+ queueYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+#else /* configUSE_QUEUE_SETS */
+ {
+ xYieldRequired = prvCopyDataToQueue(pxQueue, pvItemToQueue, xCopyPosition);
+
+ /* If there was a task waiting for data to arrive on the
+ queue then unblock it now. */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The unblocked task has a priority higher than
+ our own so yield immediately. Yes it is ok to do
+ this from within the critical section - the kernel
+ takes care of that. */
+ queueYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else if (xYieldRequired != pdFALSE) {
+ /* This path is a special case that will only get
+ executed if the task was holding multiple mutexes and
+ the mutexes were given back in an order that is
+ different to that in which they were taken. */
+ queueYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_QUEUE_SETS */
+
+ taskEXIT_CRITICAL();
+ return pdPASS;
+ } else {
+ if (xTicksToWait == (TickType_t)0) {
+ /* The queue was full and no block time is specified (or
+ the block time has expired) so leave now. */
+ taskEXIT_CRITICAL();
+
+ /* Return to the original privilege level before exiting
+ the function. */
+ traceQUEUE_SEND_FAILED(pxQueue);
+ return errQUEUE_FULL;
+ } else if (xEntryTimeSet == pdFALSE) {
+ /* The queue was full and a block time was specified so
+ configure the timeout structure. */
+ vTaskInternalSetTimeOutState(&xTimeOut);
+ xEntryTimeSet = pdTRUE;
+ } else {
+ /* Entry time was already set. */
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ /* Interrupts and other tasks can send to and receive from the queue
+ now the critical section has been exited. */
+
+ vTaskSuspendAll();
+ prvLockQueue(pxQueue);
+
+ /* Update the timeout state to see if it has expired yet. */
+ if (xTaskCheckForTimeOut(&xTimeOut, &xTicksToWait) == pdFALSE) {
+ if (prvIsQueueFull(pxQueue) != pdFALSE) {
+ traceBLOCKING_ON_QUEUE_SEND(pxQueue);
+ vTaskPlaceOnEventList(&(pxQueue->xTasksWaitingToSend), xTicksToWait);
+
+ /* Unlocking the queue means queue events can effect the
+ event list. It is possible that interrupts occurring now
+ remove this task from the event list again - but as the
+ scheduler is suspended the task will go onto the pending
+ ready last instead of the actual ready list. */
+ prvUnlockQueue(pxQueue);
+
+ /* Resuming the scheduler will move tasks from the pending
+ ready list into the ready list - so it is feasible that this
+ task is already in a ready list before it yields - in which
+ case the yield will not cause a context switch unless there
+ is also a higher priority task in the pending ready list. */
+ if (xTaskResumeAll() == pdFALSE) {
+ portYIELD_WITHIN_API();
+ }
+ } else {
+ /* Try again. */
+ prvUnlockQueue(pxQueue);
+ (void)xTaskResumeAll();
+ }
+ } else {
+ /* The timeout has expired. */
+ prvUnlockQueue(pxQueue);
+ (void)xTaskResumeAll();
+
+ traceQUEUE_SEND_FAILED(pxQueue);
+ return errQUEUE_FULL;
+ }
+ } /*lint -restore */
}
/*-----------------------------------------------------------*/
-BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, const void * const pvItemToQueue, BaseType_t * const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition )
-{
-BaseType_t xReturn;
-UBaseType_t uxSavedInterruptStatus;
-Queue_t * const pxQueue = xQueue;
-
- configASSERT( pxQueue );
- configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
- configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) );
-
- /* RTOS ports that support interrupt nesting have the concept of a maximum
- system call (or maximum API call) interrupt priority. Interrupts that are
- above the maximum system call priority are kept permanently enabled, even
- when the RTOS kernel is in a critical section, but cannot make any calls to
- FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
- then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
- failure if a FreeRTOS API function is called from an interrupt that has been
- assigned a priority above the configured maximum system call priority.
- Only FreeRTOS functions that end in FromISR can be called from interrupts
- that have been assigned a priority at or (logically) below the maximum
- system call interrupt priority. FreeRTOS maintains a separate interrupt
- safe API to ensure interrupt entry is as fast and as simple as possible.
- More information (albeit Cortex-M specific) is provided on the following
- link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
-
- /* Similar to xQueueGenericSend, except without blocking if there is no room
- in the queue. Also don't directly wake a task that was blocked on a queue
- read, instead return a flag to say whether a context switch is required or
- not (i.e. has a task with a higher priority than us been woken by this
- post). */
- uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) )
- {
- const int8_t cTxLock = pxQueue->cTxLock;
- const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting;
-
- traceQUEUE_SEND_FROM_ISR( pxQueue );
-
- /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a
- semaphore or mutex. That means prvCopyDataToQueue() cannot result
- in a task disinheriting a priority and prvCopyDataToQueue() can be
- called here even though the disinherit function does not check if
- the scheduler is suspended before accessing the ready lists. */
- ( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition );
-
- /* The event list is not altered if the queue is locked. This will
- be done when the queue is unlocked later. */
- if( cTxLock == queueUNLOCKED )
- {
- #if ( configUSE_QUEUE_SETS == 1 )
- {
- if( pxQueue->pxQueueSetContainer != NULL )
- {
- if( ( xCopyPosition == queueOVERWRITE ) && ( uxPreviousMessagesWaiting != ( UBaseType_t ) 0 ) )
- {
- /* Do not notify the queue set as an existing item
- was overwritten in the queue so the number of items
- in the queue has not changed. */
- mtCOVERAGE_TEST_MARKER();
- }
- else if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE )
- {
- /* The queue is a member of a queue set, and posting
- to the queue set caused a higher priority task to
- unblock. A context switch is required. */
- if( pxHigherPriorityTaskWoken != NULL )
- {
- *pxHigherPriorityTaskWoken = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The task waiting has a higher priority so
- record that a context switch is required. */
- if( pxHigherPriorityTaskWoken != NULL )
- {
- *pxHigherPriorityTaskWoken = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- #else /* configUSE_QUEUE_SETS */
- {
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The task waiting has a higher priority so record that a
- context switch is required. */
- if( pxHigherPriorityTaskWoken != NULL )
- {
- *pxHigherPriorityTaskWoken = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Not used in this path. */
- ( void ) uxPreviousMessagesWaiting;
- }
- #endif /* configUSE_QUEUE_SETS */
- }
- else
- {
- /* Increment the lock count so the task that unlocks the queue
- knows that data was posted while it was locked. */
- pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 );
- }
-
- xReturn = pdPASS;
- }
- else
- {
- traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue );
- xReturn = errQUEUE_FULL;
- }
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
-
- return xReturn;
+BaseType_t xQueueGenericSendFromISR(QueueHandle_t xQueue, const void *const pvItemToQueue, BaseType_t *const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition) {
+ BaseType_t xReturn;
+ UBaseType_t uxSavedInterruptStatus;
+ Queue_t *const pxQueue = xQueue;
+
+ configASSERT(pxQueue);
+ configASSERT(!((pvItemToQueue == NULL) && (pxQueue->uxItemSize != (UBaseType_t)0U)));
+ configASSERT(!((xCopyPosition == queueOVERWRITE) && (pxQueue->uxLength != 1)));
+
+ /* RTOS ports that support interrupt nesting have the concept of a maximum
+ system call (or maximum API call) interrupt priority. Interrupts that are
+ above the maximum system call priority are kept permanently enabled, even
+ when the RTOS kernel is in a critical section, but cannot make any calls to
+ FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
+ then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+ failure if a FreeRTOS API function is called from an interrupt that has been
+ assigned a priority above the configured maximum system call priority.
+ Only FreeRTOS functions that end in FromISR can be called from interrupts
+ that have been assigned a priority at or (logically) below the maximum
+ system call interrupt priority. FreeRTOS maintains a separate interrupt
+ safe API to ensure interrupt entry is as fast and as simple as possible.
+ More information (albeit Cortex-M specific) is provided on the following
+ link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ /* Similar to xQueueGenericSend, except without blocking if there is no room
+ in the queue. Also don't directly wake a task that was blocked on a queue
+ read, instead return a flag to say whether a context switch is required or
+ not (i.e. has a task with a higher priority than us been woken by this
+ post). */
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ if ((pxQueue->uxMessagesWaiting < pxQueue->uxLength) || (xCopyPosition == queueOVERWRITE)) {
+ const int8_t cTxLock = pxQueue->cTxLock;
+ const UBaseType_t uxPreviousMessagesWaiting = pxQueue->uxMessagesWaiting;
+
+ traceQUEUE_SEND_FROM_ISR(pxQueue);
+
+ /* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a
+ semaphore or mutex. That means prvCopyDataToQueue() cannot result
+ in a task disinheriting a priority and prvCopyDataToQueue() can be
+ called here even though the disinherit function does not check if
+ the scheduler is suspended before accessing the ready lists. */
+ (void)prvCopyDataToQueue(pxQueue, pvItemToQueue, xCopyPosition);
+
+ /* The event list is not altered if the queue is locked. This will
+ be done when the queue is unlocked later. */
+ if (cTxLock == queueUNLOCKED) {
+#if (configUSE_QUEUE_SETS == 1)
+ {
+ if (pxQueue->pxQueueSetContainer != NULL) {
+ if ((xCopyPosition == queueOVERWRITE) && (uxPreviousMessagesWaiting != (UBaseType_t)0)) {
+ /* Do not notify the queue set as an existing item
+ was overwritten in the queue so the number of items
+ in the queue has not changed. */
+ mtCOVERAGE_TEST_MARKER();
+ } else if (prvNotifyQueueSetContainer(pxQueue) != pdFALSE) {
+ /* The queue is a member of a queue set, and posting
+ to the queue set caused a higher priority task to
+ unblock. A context switch is required. */
+ if (pxHigherPriorityTaskWoken != NULL) {
+ *pxHigherPriorityTaskWoken = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The task waiting has a higher priority so
+ record that a context switch is required. */
+ if (pxHigherPriorityTaskWoken != NULL) {
+ *pxHigherPriorityTaskWoken = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+#else /* configUSE_QUEUE_SETS */
+ {
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The task waiting has a higher priority so record that a
+ context switch is required. */
+ if (pxHigherPriorityTaskWoken != NULL) {
+ *pxHigherPriorityTaskWoken = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Not used in this path. */
+ (void)uxPreviousMessagesWaiting;
+ }
+#endif /* configUSE_QUEUE_SETS */
+ } else {
+ /* Increment the lock count so the task that unlocks the queue
+ knows that data was posted while it was locked. */
+ pxQueue->cTxLock = (int8_t)(cTxLock + 1);
+ }
+
+ xReturn = pdPASS;
+ } else {
+ traceQUEUE_SEND_FROM_ISR_FAILED(pxQueue);
+ xReturn = errQUEUE_FULL;
+ }
+ }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherPriorityTaskWoken )
-{
-BaseType_t xReturn;
-UBaseType_t uxSavedInterruptStatus;
-Queue_t * const pxQueue = xQueue;
-
- /* Similar to xQueueGenericSendFromISR() but used with semaphores where the
- item size is 0. Don't directly wake a task that was blocked on a queue
- read, instead return a flag to say whether a context switch is required or
- not (i.e. has a task with a higher priority than us been woken by this
- post). */
-
- configASSERT( pxQueue );
-
- /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR()
- if the item size is not 0. */
- configASSERT( pxQueue->uxItemSize == 0 );
-
- /* Normally a mutex would not be given from an interrupt, especially if
- there is a mutex holder, as priority inheritance makes no sense for an
- interrupts, only tasks. */
- configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->u.xSemaphore.xMutexHolder != NULL ) ) );
-
- /* RTOS ports that support interrupt nesting have the concept of a maximum
- system call (or maximum API call) interrupt priority. Interrupts that are
- above the maximum system call priority are kept permanently enabled, even
- when the RTOS kernel is in a critical section, but cannot make any calls to
- FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
- then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
- failure if a FreeRTOS API function is called from an interrupt that has been
- assigned a priority above the configured maximum system call priority.
- Only FreeRTOS functions that end in FromISR can be called from interrupts
- that have been assigned a priority at or (logically) below the maximum
- system call interrupt priority. FreeRTOS maintains a separate interrupt
- safe API to ensure interrupt entry is as fast and as simple as possible.
- More information (albeit Cortex-M specific) is provided on the following
- link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
-
- uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting;
-
- /* When the queue is used to implement a semaphore no data is ever
- moved through the queue but it is still valid to see if the queue 'has
- space'. */
- if( uxMessagesWaiting < pxQueue->uxLength )
- {
- const int8_t cTxLock = pxQueue->cTxLock;
-
- traceQUEUE_SEND_FROM_ISR( pxQueue );
-
- /* A task can only have an inherited priority if it is a mutex
- holder - and if there is a mutex holder then the mutex cannot be
- given from an ISR. As this is the ISR version of the function it
- can be assumed there is no mutex holder and no need to determine if
- priority disinheritance is needed. Simply increase the count of
- messages (semaphores) available. */
- pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1;
-
- /* The event list is not altered if the queue is locked. This will
- be done when the queue is unlocked later. */
- if( cTxLock == queueUNLOCKED )
- {
- #if ( configUSE_QUEUE_SETS == 1 )
- {
- if( pxQueue->pxQueueSetContainer != NULL )
- {
- if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE )
- {
- /* The semaphore is a member of a queue set, and
- posting to the queue set caused a higher priority
- task to unblock. A context switch is required. */
- if( pxHigherPriorityTaskWoken != NULL )
- {
- *pxHigherPriorityTaskWoken = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The task waiting has a higher priority so
- record that a context switch is required. */
- if( pxHigherPriorityTaskWoken != NULL )
- {
- *pxHigherPriorityTaskWoken = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- #else /* configUSE_QUEUE_SETS */
- {
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The task waiting has a higher priority so record that a
- context switch is required. */
- if( pxHigherPriorityTaskWoken != NULL )
- {
- *pxHigherPriorityTaskWoken = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_QUEUE_SETS */
- }
- else
- {
- /* Increment the lock count so the task that unlocks the queue
- knows that data was posted while it was locked. */
- pxQueue->cTxLock = ( int8_t ) ( cTxLock + 1 );
- }
-
- xReturn = pdPASS;
- }
- else
- {
- traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue );
- xReturn = errQUEUE_FULL;
- }
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
-
- return xReturn;
+BaseType_t xQueueGiveFromISR(QueueHandle_t xQueue, BaseType_t *const pxHigherPriorityTaskWoken) {
+ BaseType_t xReturn;
+ UBaseType_t uxSavedInterruptStatus;
+ Queue_t *const pxQueue = xQueue;
+
+ /* Similar to xQueueGenericSendFromISR() but used with semaphores where the
+ item size is 0. Don't directly wake a task that was blocked on a queue
+ read, instead return a flag to say whether a context switch is required or
+ not (i.e. has a task with a higher priority than us been woken by this
+ post). */
+
+ configASSERT(pxQueue);
+
+ /* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR()
+ if the item size is not 0. */
+ configASSERT(pxQueue->uxItemSize == 0);
+
+ /* Normally a mutex would not be given from an interrupt, especially if
+ there is a mutex holder, as priority inheritance makes no sense for an
+ interrupts, only tasks. */
+ configASSERT(!((pxQueue->uxQueueType == queueQUEUE_IS_MUTEX) && (pxQueue->u.xSemaphore.xMutexHolder != NULL)));
+
+ /* RTOS ports that support interrupt nesting have the concept of a maximum
+ system call (or maximum API call) interrupt priority. Interrupts that are
+ above the maximum system call priority are kept permanently enabled, even
+ when the RTOS kernel is in a critical section, but cannot make any calls to
+ FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
+ then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+ failure if a FreeRTOS API function is called from an interrupt that has been
+ assigned a priority above the configured maximum system call priority.
+ Only FreeRTOS functions that end in FromISR can be called from interrupts
+ that have been assigned a priority at or (logically) below the maximum
+ system call interrupt priority. FreeRTOS maintains a separate interrupt
+ safe API to ensure interrupt entry is as fast and as simple as possible.
+ More information (albeit Cortex-M specific) is provided on the following
+ link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting;
+
+ /* When the queue is used to implement a semaphore no data is ever
+ moved through the queue but it is still valid to see if the queue 'has
+ space'. */
+ if (uxMessagesWaiting < pxQueue->uxLength) {
+ const int8_t cTxLock = pxQueue->cTxLock;
+
+ traceQUEUE_SEND_FROM_ISR(pxQueue);
+
+ /* A task can only have an inherited priority if it is a mutex
+ holder - and if there is a mutex holder then the mutex cannot be
+ given from an ISR. As this is the ISR version of the function it
+ can be assumed there is no mutex holder and no need to determine if
+ priority disinheritance is needed. Simply increase the count of
+ messages (semaphores) available. */
+ pxQueue->uxMessagesWaiting = uxMessagesWaiting + (UBaseType_t)1;
+
+ /* The event list is not altered if the queue is locked. This will
+ be done when the queue is unlocked later. */
+ if (cTxLock == queueUNLOCKED) {
+#if (configUSE_QUEUE_SETS == 1)
+ {
+ if (pxQueue->pxQueueSetContainer != NULL) {
+ if (prvNotifyQueueSetContainer(pxQueue) != pdFALSE) {
+ /* The semaphore is a member of a queue set, and
+ posting to the queue set caused a higher priority
+ task to unblock. A context switch is required. */
+ if (pxHigherPriorityTaskWoken != NULL) {
+ *pxHigherPriorityTaskWoken = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The task waiting has a higher priority so
+ record that a context switch is required. */
+ if (pxHigherPriorityTaskWoken != NULL) {
+ *pxHigherPriorityTaskWoken = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+#else /* configUSE_QUEUE_SETS */
+ {
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The task waiting has a higher priority so record that a
+ context switch is required. */
+ if (pxHigherPriorityTaskWoken != NULL) {
+ *pxHigherPriorityTaskWoken = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_QUEUE_SETS */
+ } else {
+ /* Increment the lock count so the task that unlocks the queue
+ knows that data was posted while it was locked. */
+ pxQueue->cTxLock = (int8_t)(cTxLock + 1);
+ }
+
+ xReturn = pdPASS;
+ } else {
+ traceQUEUE_SEND_FROM_ISR_FAILED(pxQueue);
+ xReturn = errQUEUE_FULL;
+ }
+ }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-BaseType_t xQueueReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait )
-{
-BaseType_t xEntryTimeSet = pdFALSE;
-TimeOut_t xTimeOut;
-Queue_t * const pxQueue = xQueue;
-
- /* Check the pointer is not NULL. */
- configASSERT( ( pxQueue ) );
-
- /* The buffer into which data is received can only be NULL if the data size
- is zero (so no data is copied into the buffer. */
- configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) );
-
- /* Cannot block if the scheduler is suspended. */
- #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
- {
- configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
- }
- #endif
-
-
- /*lint -save -e904 This function relaxes the coding standard somewhat to
- allow return statements within the function itself. This is done in the
- interest of execution time efficiency. */
- for( ;; )
- {
- taskENTER_CRITICAL();
- {
- const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting;
-
- /* Is there data in the queue now? To be running the calling task
- must be the highest priority task wanting to access the queue. */
- if( uxMessagesWaiting > ( UBaseType_t ) 0 )
- {
- /* Data available, remove one item. */
- prvCopyDataFromQueue( pxQueue, pvBuffer );
- traceQUEUE_RECEIVE( pxQueue );
- pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1;
-
- /* There is now space in the queue, were any tasks waiting to
- post to the queue? If so, unblock the highest priority waiting
- task. */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
- {
- queueYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- taskEXIT_CRITICAL();
- return pdPASS;
- }
- else
- {
- if( xTicksToWait == ( TickType_t ) 0 )
- {
- /* The queue was empty and no block time is specified (or
- the block time has expired) so leave now. */
- taskEXIT_CRITICAL();
- traceQUEUE_RECEIVE_FAILED( pxQueue );
- return errQUEUE_EMPTY;
- }
- else if( xEntryTimeSet == pdFALSE )
- {
- /* The queue was empty and a block time was specified so
- configure the timeout structure. */
- vTaskInternalSetTimeOutState( &xTimeOut );
- xEntryTimeSet = pdTRUE;
- }
- else
- {
- /* Entry time was already set. */
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- taskEXIT_CRITICAL();
-
- /* Interrupts and other tasks can send to and receive from the queue
- now the critical section has been exited. */
-
- vTaskSuspendAll();
- prvLockQueue( pxQueue );
-
- /* Update the timeout state to see if it has expired yet. */
- if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE )
- {
- /* The timeout has not expired. If the queue is still empty place
- the task on the list of tasks waiting to receive from the queue. */
- if( prvIsQueueEmpty( pxQueue ) != pdFALSE )
- {
- traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue );
- vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait );
- prvUnlockQueue( pxQueue );
- if( xTaskResumeAll() == pdFALSE )
- {
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* The queue contains data again. Loop back to try and read the
- data. */
- prvUnlockQueue( pxQueue );
- ( void ) xTaskResumeAll();
- }
- }
- else
- {
- /* Timed out. If there is no data in the queue exit, otherwise loop
- back and attempt to read the data. */
- prvUnlockQueue( pxQueue );
- ( void ) xTaskResumeAll();
-
- if( prvIsQueueEmpty( pxQueue ) != pdFALSE )
- {
- traceQUEUE_RECEIVE_FAILED( pxQueue );
- return errQUEUE_EMPTY;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- } /*lint -restore */
+BaseType_t xQueueReceive(QueueHandle_t xQueue, void *const pvBuffer, TickType_t xTicksToWait) {
+ BaseType_t xEntryTimeSet = pdFALSE;
+ TimeOut_t xTimeOut;
+ Queue_t *const pxQueue = xQueue;
+
+ /* Check the pointer is not NULL. */
+ configASSERT((pxQueue));
+
+ /* The buffer into which data is received can only be NULL if the data size
+ is zero (so no data is copied into the buffer. */
+ configASSERT(!(((pvBuffer) == NULL) && ((pxQueue)->uxItemSize != (UBaseType_t)0U)));
+
+/* Cannot block if the scheduler is suspended. */
+#if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1))
+ { configASSERT(!((xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED) && (xTicksToWait != 0))); }
+#endif
+
+ /*lint -save -e904 This function relaxes the coding standard somewhat to
+ allow return statements within the function itself. This is done in the
+ interest of execution time efficiency. */
+ for (;;) {
+ taskENTER_CRITICAL();
+ {
+ const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting;
+
+ /* Is there data in the queue now? To be running the calling task
+ must be the highest priority task wanting to access the queue. */
+ if (uxMessagesWaiting > (UBaseType_t)0) {
+ /* Data available, remove one item. */
+ prvCopyDataFromQueue(pxQueue, pvBuffer);
+ traceQUEUE_RECEIVE(pxQueue);
+ pxQueue->uxMessagesWaiting = uxMessagesWaiting - (UBaseType_t)1;
+
+ /* There is now space in the queue, were any tasks waiting to
+ post to the queue? If so, unblock the highest priority waiting
+ task. */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToSend)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToSend)) != pdFALSE) {
+ queueYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ taskEXIT_CRITICAL();
+ return pdPASS;
+ } else {
+ if (xTicksToWait == (TickType_t)0) {
+ /* The queue was empty and no block time is specified (or
+ the block time has expired) so leave now. */
+ taskEXIT_CRITICAL();
+ traceQUEUE_RECEIVE_FAILED(pxQueue);
+ return errQUEUE_EMPTY;
+ } else if (xEntryTimeSet == pdFALSE) {
+ /* The queue was empty and a block time was specified so
+ configure the timeout structure. */
+ vTaskInternalSetTimeOutState(&xTimeOut);
+ xEntryTimeSet = pdTRUE;
+ } else {
+ /* Entry time was already set. */
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ /* Interrupts and other tasks can send to and receive from the queue
+ now the critical section has been exited. */
+
+ vTaskSuspendAll();
+ prvLockQueue(pxQueue);
+
+ /* Update the timeout state to see if it has expired yet. */
+ if (xTaskCheckForTimeOut(&xTimeOut, &xTicksToWait) == pdFALSE) {
+ /* The timeout has not expired. If the queue is still empty place
+ the task on the list of tasks waiting to receive from the queue. */
+ if (prvIsQueueEmpty(pxQueue) != pdFALSE) {
+ traceBLOCKING_ON_QUEUE_RECEIVE(pxQueue);
+ vTaskPlaceOnEventList(&(pxQueue->xTasksWaitingToReceive), xTicksToWait);
+ prvUnlockQueue(pxQueue);
+ if (xTaskResumeAll() == pdFALSE) {
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* The queue contains data again. Loop back to try and read the
+ data. */
+ prvUnlockQueue(pxQueue);
+ (void)xTaskResumeAll();
+ }
+ } else {
+ /* Timed out. If there is no data in the queue exit, otherwise loop
+ back and attempt to read the data. */
+ prvUnlockQueue(pxQueue);
+ (void)xTaskResumeAll();
+
+ if (prvIsQueueEmpty(pxQueue) != pdFALSE) {
+ traceQUEUE_RECEIVE_FAILED(pxQueue);
+ return errQUEUE_EMPTY;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ } /*lint -restore */
}
/*-----------------------------------------------------------*/
-BaseType_t xQueueSemaphoreTake( QueueHandle_t xQueue, TickType_t xTicksToWait )
-{
-BaseType_t xEntryTimeSet = pdFALSE;
-TimeOut_t xTimeOut;
-Queue_t * const pxQueue = xQueue;
+BaseType_t xQueueSemaphoreTake(QueueHandle_t xQueue, TickType_t xTicksToWait) {
+ BaseType_t xEntryTimeSet = pdFALSE;
+ TimeOut_t xTimeOut;
+ Queue_t *const pxQueue = xQueue;
+
+#if (configUSE_MUTEXES == 1)
+ BaseType_t xInheritanceOccurred = pdFALSE;
+#endif
+
+ /* Check the queue pointer is not NULL. */
+ configASSERT((pxQueue));
+
+ /* Check this really is a semaphore, in which case the item size will be
+ 0. */
+ configASSERT(pxQueue->uxItemSize == 0);
+
+/* Cannot block if the scheduler is suspended. */
+#if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1))
+ { configASSERT(!((xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED) && (xTicksToWait != 0))); }
+#endif
+
+ /*lint -save -e904 This function relaxes the coding standard somewhat to allow return
+ statements within the function itself. This is done in the interest
+ of execution time efficiency. */
+ for (;;) {
+ taskENTER_CRITICAL();
+ {
+ /* Semaphores are queues with an item size of 0, and where the
+ number of messages in the queue is the semaphore's count value. */
+ const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting;
+
+ /* Is there data in the queue now? To be running the calling task
+ must be the highest priority task wanting to access the queue. */
+ if (uxSemaphoreCount > (UBaseType_t)0) {
+ traceQUEUE_RECEIVE(pxQueue);
+
+ /* Semaphores are queues with a data size of zero and where the
+ messages waiting is the semaphore's count. Reduce the count. */
+ pxQueue->uxMessagesWaiting = uxSemaphoreCount - (UBaseType_t)1;
+
+#if (configUSE_MUTEXES == 1)
+ {
+ if (pxQueue->uxQueueType == queueQUEUE_IS_MUTEX) {
+ /* Record the information required to implement
+ priority inheritance should it become necessary. */
+ pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_MUTEXES */
+
+ /* Check to see if other tasks are blocked waiting to give the
+ semaphore, and if so, unblock the highest priority such task. */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToSend)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToSend)) != pdFALSE) {
+ queueYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ taskEXIT_CRITICAL();
+ return pdPASS;
+ } else {
+ if (xTicksToWait == (TickType_t)0) {
+/* For inheritance to have occurred there must have been an
+initial timeout, and an adjusted timeout cannot become 0, as
+if it were 0 the function would have exited. */
+#if (configUSE_MUTEXES == 1)
+ { configASSERT(xInheritanceOccurred == pdFALSE); }
+#endif /* configUSE_MUTEXES */
-#if( configUSE_MUTEXES == 1 )
- BaseType_t xInheritanceOccurred = pdFALSE;
+ /* The semaphore count was 0 and no block time is specified
+ (or the block time has expired) so exit now. */
+ taskEXIT_CRITICAL();
+ traceQUEUE_RECEIVE_FAILED(pxQueue);
+ return errQUEUE_EMPTY;
+ } else if (xEntryTimeSet == pdFALSE) {
+ /* The semaphore count was 0 and a block time was specified
+ so configure the timeout structure ready to block. */
+ vTaskInternalSetTimeOutState(&xTimeOut);
+ xEntryTimeSet = pdTRUE;
+ } else {
+ /* Entry time was already set. */
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ /* Interrupts and other tasks can give to and take from the semaphore
+ now the critical section has been exited. */
+
+ vTaskSuspendAll();
+ prvLockQueue(pxQueue);
+
+ /* Update the timeout state to see if it has expired yet. */
+ if (xTaskCheckForTimeOut(&xTimeOut, &xTicksToWait) == pdFALSE) {
+ /* A block time is specified and not expired. If the semaphore
+ count is 0 then enter the Blocked state to wait for a semaphore to
+ become available. As semaphores are implemented with queues the
+ queue being empty is equivalent to the semaphore count being 0. */
+ if (prvIsQueueEmpty(pxQueue) != pdFALSE) {
+ traceBLOCKING_ON_QUEUE_RECEIVE(pxQueue);
+
+#if (configUSE_MUTEXES == 1)
+ {
+ if (pxQueue->uxQueueType == queueQUEUE_IS_MUTEX) {
+ taskENTER_CRITICAL();
+ { xInheritanceOccurred = xTaskPriorityInherit(pxQueue->u.xSemaphore.xMutexHolder); }
+ taskEXIT_CRITICAL();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
#endif
- /* Check the queue pointer is not NULL. */
- configASSERT( ( pxQueue ) );
-
- /* Check this really is a semaphore, in which case the item size will be
- 0. */
- configASSERT( pxQueue->uxItemSize == 0 );
-
- /* Cannot block if the scheduler is suspended. */
- #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
- {
- configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
- }
- #endif
-
-
- /*lint -save -e904 This function relaxes the coding standard somewhat to allow return
- statements within the function itself. This is done in the interest
- of execution time efficiency. */
- for( ;; )
- {
- taskENTER_CRITICAL();
- {
- /* Semaphores are queues with an item size of 0, and where the
- number of messages in the queue is the semaphore's count value. */
- const UBaseType_t uxSemaphoreCount = pxQueue->uxMessagesWaiting;
-
- /* Is there data in the queue now? To be running the calling task
- must be the highest priority task wanting to access the queue. */
- if( uxSemaphoreCount > ( UBaseType_t ) 0 )
- {
- traceQUEUE_RECEIVE( pxQueue );
-
- /* Semaphores are queues with a data size of zero and where the
- messages waiting is the semaphore's count. Reduce the count. */
- pxQueue->uxMessagesWaiting = uxSemaphoreCount - ( UBaseType_t ) 1;
-
- #if ( configUSE_MUTEXES == 1 )
- {
- if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX )
- {
- /* Record the information required to implement
- priority inheritance should it become necessary. */
- pxQueue->u.xSemaphore.xMutexHolder = pvTaskIncrementMutexHeldCount();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_MUTEXES */
-
- /* Check to see if other tasks are blocked waiting to give the
- semaphore, and if so, unblock the highest priority such task. */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
- {
- queueYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- taskEXIT_CRITICAL();
- return pdPASS;
- }
- else
- {
- if( xTicksToWait == ( TickType_t ) 0 )
- {
- /* For inheritance to have occurred there must have been an
- initial timeout, and an adjusted timeout cannot become 0, as
- if it were 0 the function would have exited. */
- #if( configUSE_MUTEXES == 1 )
- {
- configASSERT( xInheritanceOccurred == pdFALSE );
- }
- #endif /* configUSE_MUTEXES */
-
- /* The semaphore count was 0 and no block time is specified
- (or the block time has expired) so exit now. */
- taskEXIT_CRITICAL();
- traceQUEUE_RECEIVE_FAILED( pxQueue );
- return errQUEUE_EMPTY;
- }
- else if( xEntryTimeSet == pdFALSE )
- {
- /* The semaphore count was 0 and a block time was specified
- so configure the timeout structure ready to block. */
- vTaskInternalSetTimeOutState( &xTimeOut );
- xEntryTimeSet = pdTRUE;
- }
- else
- {
- /* Entry time was already set. */
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- taskEXIT_CRITICAL();
-
- /* Interrupts and other tasks can give to and take from the semaphore
- now the critical section has been exited. */
-
- vTaskSuspendAll();
- prvLockQueue( pxQueue );
-
- /* Update the timeout state to see if it has expired yet. */
- if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE )
- {
- /* A block time is specified and not expired. If the semaphore
- count is 0 then enter the Blocked state to wait for a semaphore to
- become available. As semaphores are implemented with queues the
- queue being empty is equivalent to the semaphore count being 0. */
- if( prvIsQueueEmpty( pxQueue ) != pdFALSE )
- {
- traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue );
-
- #if ( configUSE_MUTEXES == 1 )
- {
- if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX )
- {
- taskENTER_CRITICAL();
- {
- xInheritanceOccurred = xTaskPriorityInherit( pxQueue->u.xSemaphore.xMutexHolder );
- }
- taskEXIT_CRITICAL();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif
-
- vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait );
- prvUnlockQueue( pxQueue );
- if( xTaskResumeAll() == pdFALSE )
- {
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* There was no timeout and the semaphore count was not 0, so
- attempt to take the semaphore again. */
- prvUnlockQueue( pxQueue );
- ( void ) xTaskResumeAll();
- }
- }
- else
- {
- /* Timed out. */
- prvUnlockQueue( pxQueue );
- ( void ) xTaskResumeAll();
-
- /* If the semaphore count is 0 exit now as the timeout has
- expired. Otherwise return to attempt to take the semaphore that is
- known to be available. As semaphores are implemented by queues the
- queue being empty is equivalent to the semaphore count being 0. */
- if( prvIsQueueEmpty( pxQueue ) != pdFALSE )
- {
- #if ( configUSE_MUTEXES == 1 )
- {
- /* xInheritanceOccurred could only have be set if
- pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to
- test the mutex type again to check it is actually a mutex. */
- if( xInheritanceOccurred != pdFALSE )
- {
- taskENTER_CRITICAL();
- {
- UBaseType_t uxHighestWaitingPriority;
-
- /* This task blocking on the mutex caused another
- task to inherit this task's priority. Now this task
- has timed out the priority should be disinherited
- again, but only as low as the next highest priority
- task that is waiting for the same mutex. */
- uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout( pxQueue );
- vTaskPriorityDisinheritAfterTimeout( pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority );
- }
- taskEXIT_CRITICAL();
- }
- }
- #endif /* configUSE_MUTEXES */
-
- traceQUEUE_RECEIVE_FAILED( pxQueue );
- return errQUEUE_EMPTY;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- } /*lint -restore */
+ vTaskPlaceOnEventList(&(pxQueue->xTasksWaitingToReceive), xTicksToWait);
+ prvUnlockQueue(pxQueue);
+ if (xTaskResumeAll() == pdFALSE) {
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* There was no timeout and the semaphore count was not 0, so
+ attempt to take the semaphore again. */
+ prvUnlockQueue(pxQueue);
+ (void)xTaskResumeAll();
+ }
+ } else {
+ /* Timed out. */
+ prvUnlockQueue(pxQueue);
+ (void)xTaskResumeAll();
+
+ /* If the semaphore count is 0 exit now as the timeout has
+ expired. Otherwise return to attempt to take the semaphore that is
+ known to be available. As semaphores are implemented by queues the
+ queue being empty is equivalent to the semaphore count being 0. */
+ if (prvIsQueueEmpty(pxQueue) != pdFALSE) {
+#if (configUSE_MUTEXES == 1)
+ {
+ /* xInheritanceOccurred could only have be set if
+ pxQueue->uxQueueType == queueQUEUE_IS_MUTEX so no need to
+ test the mutex type again to check it is actually a mutex. */
+ if (xInheritanceOccurred != pdFALSE) {
+ taskENTER_CRITICAL();
+ {
+ UBaseType_t uxHighestWaitingPriority;
+
+ /* This task blocking on the mutex caused another
+ task to inherit this task's priority. Now this task
+ has timed out the priority should be disinherited
+ again, but only as low as the next highest priority
+ task that is waiting for the same mutex. */
+ uxHighestWaitingPriority = prvGetDisinheritPriorityAfterTimeout(pxQueue);
+ vTaskPriorityDisinheritAfterTimeout(pxQueue->u.xSemaphore.xMutexHolder, uxHighestWaitingPriority);
+ }
+ taskEXIT_CRITICAL();
+ }
+ }
+#endif /* configUSE_MUTEXES */
+
+ traceQUEUE_RECEIVE_FAILED(pxQueue);
+ return errQUEUE_EMPTY;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ } /*lint -restore */
}
/*-----------------------------------------------------------*/
-BaseType_t xQueuePeek( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait )
-{
-BaseType_t xEntryTimeSet = pdFALSE;
-TimeOut_t xTimeOut;
-int8_t *pcOriginalReadPosition;
-Queue_t * const pxQueue = xQueue;
-
- /* Check the pointer is not NULL. */
- configASSERT( ( pxQueue ) );
-
- /* The buffer into which data is received can only be NULL if the data size
- is zero (so no data is copied into the buffer. */
- configASSERT( !( ( ( pvBuffer ) == NULL ) && ( ( pxQueue )->uxItemSize != ( UBaseType_t ) 0U ) ) );
-
- /* Cannot block if the scheduler is suspended. */
- #if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
- {
- configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
- }
- #endif
-
-
- /*lint -save -e904 This function relaxes the coding standard somewhat to
- allow return statements within the function itself. This is done in the
- interest of execution time efficiency. */
- for( ;; )
- {
- taskENTER_CRITICAL();
- {
- const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting;
-
- /* Is there data in the queue now? To be running the calling task
- must be the highest priority task wanting to access the queue. */
- if( uxMessagesWaiting > ( UBaseType_t ) 0 )
- {
- /* Remember the read position so it can be reset after the data
- is read from the queue as this function is only peeking the
- data, not removing it. */
- pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom;
-
- prvCopyDataFromQueue( pxQueue, pvBuffer );
- traceQUEUE_PEEK( pxQueue );
-
- /* The data is not being removed, so reset the read pointer. */
- pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition;
-
- /* The data is being left in the queue, so see if there are
- any other tasks waiting for the data. */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The task waiting has a higher priority than this task. */
- queueYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- taskEXIT_CRITICAL();
- return pdPASS;
- }
- else
- {
- if( xTicksToWait == ( TickType_t ) 0 )
- {
- /* The queue was empty and no block time is specified (or
- the block time has expired) so leave now. */
- taskEXIT_CRITICAL();
- traceQUEUE_PEEK_FAILED( pxQueue );
- return errQUEUE_EMPTY;
- }
- else if( xEntryTimeSet == pdFALSE )
- {
- /* The queue was empty and a block time was specified so
- configure the timeout structure ready to enter the blocked
- state. */
- vTaskInternalSetTimeOutState( &xTimeOut );
- xEntryTimeSet = pdTRUE;
- }
- else
- {
- /* Entry time was already set. */
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- taskEXIT_CRITICAL();
-
- /* Interrupts and other tasks can send to and receive from the queue
- now the critical section has been exited. */
-
- vTaskSuspendAll();
- prvLockQueue( pxQueue );
-
- /* Update the timeout state to see if it has expired yet. */
- if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE )
- {
- /* Timeout has not expired yet, check to see if there is data in the
- queue now, and if not enter the Blocked state to wait for data. */
- if( prvIsQueueEmpty( pxQueue ) != pdFALSE )
- {
- traceBLOCKING_ON_QUEUE_PEEK( pxQueue );
- vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait );
- prvUnlockQueue( pxQueue );
- if( xTaskResumeAll() == pdFALSE )
- {
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* There is data in the queue now, so don't enter the blocked
- state, instead return to try and obtain the data. */
- prvUnlockQueue( pxQueue );
- ( void ) xTaskResumeAll();
- }
- }
- else
- {
- /* The timeout has expired. If there is still no data in the queue
- exit, otherwise go back and try to read the data again. */
- prvUnlockQueue( pxQueue );
- ( void ) xTaskResumeAll();
-
- if( prvIsQueueEmpty( pxQueue ) != pdFALSE )
- {
- traceQUEUE_PEEK_FAILED( pxQueue );
- return errQUEUE_EMPTY;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- } /*lint -restore */
+BaseType_t xQueuePeek(QueueHandle_t xQueue, void *const pvBuffer, TickType_t xTicksToWait) {
+ BaseType_t xEntryTimeSet = pdFALSE;
+ TimeOut_t xTimeOut;
+ int8_t * pcOriginalReadPosition;
+ Queue_t *const pxQueue = xQueue;
+
+ /* Check the pointer is not NULL. */
+ configASSERT((pxQueue));
+
+ /* The buffer into which data is received can only be NULL if the data size
+ is zero (so no data is copied into the buffer. */
+ configASSERT(!(((pvBuffer) == NULL) && ((pxQueue)->uxItemSize != (UBaseType_t)0U)));
+
+/* Cannot block if the scheduler is suspended. */
+#if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1))
+ { configASSERT(!((xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED) && (xTicksToWait != 0))); }
+#endif
+
+ /*lint -save -e904 This function relaxes the coding standard somewhat to
+ allow return statements within the function itself. This is done in the
+ interest of execution time efficiency. */
+ for (;;) {
+ taskENTER_CRITICAL();
+ {
+ const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting;
+
+ /* Is there data in the queue now? To be running the calling task
+ must be the highest priority task wanting to access the queue. */
+ if (uxMessagesWaiting > (UBaseType_t)0) {
+ /* Remember the read position so it can be reset after the data
+ is read from the queue as this function is only peeking the
+ data, not removing it. */
+ pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom;
+
+ prvCopyDataFromQueue(pxQueue, pvBuffer);
+ traceQUEUE_PEEK(pxQueue);
+
+ /* The data is not being removed, so reset the read pointer. */
+ pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition;
+
+ /* The data is being left in the queue, so see if there are
+ any other tasks waiting for the data. */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The task waiting has a higher priority than this task. */
+ queueYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ taskEXIT_CRITICAL();
+ return pdPASS;
+ } else {
+ if (xTicksToWait == (TickType_t)0) {
+ /* The queue was empty and no block time is specified (or
+ the block time has expired) so leave now. */
+ taskEXIT_CRITICAL();
+ traceQUEUE_PEEK_FAILED(pxQueue);
+ return errQUEUE_EMPTY;
+ } else if (xEntryTimeSet == pdFALSE) {
+ /* The queue was empty and a block time was specified so
+ configure the timeout structure ready to enter the blocked
+ state. */
+ vTaskInternalSetTimeOutState(&xTimeOut);
+ xEntryTimeSet = pdTRUE;
+ } else {
+ /* Entry time was already set. */
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ /* Interrupts and other tasks can send to and receive from the queue
+ now the critical section has been exited. */
+
+ vTaskSuspendAll();
+ prvLockQueue(pxQueue);
+
+ /* Update the timeout state to see if it has expired yet. */
+ if (xTaskCheckForTimeOut(&xTimeOut, &xTicksToWait) == pdFALSE) {
+ /* Timeout has not expired yet, check to see if there is data in the
+ queue now, and if not enter the Blocked state to wait for data. */
+ if (prvIsQueueEmpty(pxQueue) != pdFALSE) {
+ traceBLOCKING_ON_QUEUE_PEEK(pxQueue);
+ vTaskPlaceOnEventList(&(pxQueue->xTasksWaitingToReceive), xTicksToWait);
+ prvUnlockQueue(pxQueue);
+ if (xTaskResumeAll() == pdFALSE) {
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* There is data in the queue now, so don't enter the blocked
+ state, instead return to try and obtain the data. */
+ prvUnlockQueue(pxQueue);
+ (void)xTaskResumeAll();
+ }
+ } else {
+ /* The timeout has expired. If there is still no data in the queue
+ exit, otherwise go back and try to read the data again. */
+ prvUnlockQueue(pxQueue);
+ (void)xTaskResumeAll();
+
+ if (prvIsQueueEmpty(pxQueue) != pdFALSE) {
+ traceQUEUE_PEEK_FAILED(pxQueue);
+ return errQUEUE_EMPTY;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ } /*lint -restore */
}
/*-----------------------------------------------------------*/
-BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, void * const pvBuffer, BaseType_t * const pxHigherPriorityTaskWoken )
-{
-BaseType_t xReturn;
-UBaseType_t uxSavedInterruptStatus;
-Queue_t * const pxQueue = xQueue;
-
- configASSERT( pxQueue );
- configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
-
- /* RTOS ports that support interrupt nesting have the concept of a maximum
- system call (or maximum API call) interrupt priority. Interrupts that are
- above the maximum system call priority are kept permanently enabled, even
- when the RTOS kernel is in a critical section, but cannot make any calls to
- FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
- then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
- failure if a FreeRTOS API function is called from an interrupt that has been
- assigned a priority above the configured maximum system call priority.
- Only FreeRTOS functions that end in FromISR can be called from interrupts
- that have been assigned a priority at or (logically) below the maximum
- system call interrupt priority. FreeRTOS maintains a separate interrupt
- safe API to ensure interrupt entry is as fast and as simple as possible.
- More information (albeit Cortex-M specific) is provided on the following
- link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
-
- uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting;
-
- /* Cannot block in an ISR, so check there is data available. */
- if( uxMessagesWaiting > ( UBaseType_t ) 0 )
- {
- const int8_t cRxLock = pxQueue->cRxLock;
-
- traceQUEUE_RECEIVE_FROM_ISR( pxQueue );
-
- prvCopyDataFromQueue( pxQueue, pvBuffer );
- pxQueue->uxMessagesWaiting = uxMessagesWaiting - ( UBaseType_t ) 1;
-
- /* If the queue is locked the event list will not be modified.
- Instead update the lock count so the task that unlocks the queue
- will know that an ISR has removed data while the queue was
- locked. */
- if( cRxLock == queueUNLOCKED )
- {
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
- {
- /* The task waiting has a higher priority than us so
- force a context switch. */
- if( pxHigherPriorityTaskWoken != NULL )
- {
- *pxHigherPriorityTaskWoken = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* Increment the lock count so the task that unlocks the queue
- knows that data was removed while it was locked. */
- pxQueue->cRxLock = ( int8_t ) ( cRxLock + 1 );
- }
-
- xReturn = pdPASS;
- }
- else
- {
- xReturn = pdFAIL;
- traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue );
- }
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
-
- return xReturn;
+BaseType_t xQueueReceiveFromISR(QueueHandle_t xQueue, void *const pvBuffer, BaseType_t *const pxHigherPriorityTaskWoken) {
+ BaseType_t xReturn;
+ UBaseType_t uxSavedInterruptStatus;
+ Queue_t *const pxQueue = xQueue;
+
+ configASSERT(pxQueue);
+ configASSERT(!((pvBuffer == NULL) && (pxQueue->uxItemSize != (UBaseType_t)0U)));
+
+ /* RTOS ports that support interrupt nesting have the concept of a maximum
+ system call (or maximum API call) interrupt priority. Interrupts that are
+ above the maximum system call priority are kept permanently enabled, even
+ when the RTOS kernel is in a critical section, but cannot make any calls to
+ FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
+ then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+ failure if a FreeRTOS API function is called from an interrupt that has been
+ assigned a priority above the configured maximum system call priority.
+ Only FreeRTOS functions that end in FromISR can be called from interrupts
+ that have been assigned a priority at or (logically) below the maximum
+ system call interrupt priority. FreeRTOS maintains a separate interrupt
+ safe API to ensure interrupt entry is as fast and as simple as possible.
+ More information (albeit Cortex-M specific) is provided on the following
+ link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ const UBaseType_t uxMessagesWaiting = pxQueue->uxMessagesWaiting;
+
+ /* Cannot block in an ISR, so check there is data available. */
+ if (uxMessagesWaiting > (UBaseType_t)0) {
+ const int8_t cRxLock = pxQueue->cRxLock;
+
+ traceQUEUE_RECEIVE_FROM_ISR(pxQueue);
+
+ prvCopyDataFromQueue(pxQueue, pvBuffer);
+ pxQueue->uxMessagesWaiting = uxMessagesWaiting - (UBaseType_t)1;
+
+ /* If the queue is locked the event list will not be modified.
+ Instead update the lock count so the task that unlocks the queue
+ will know that an ISR has removed data while the queue was
+ locked. */
+ if (cRxLock == queueUNLOCKED) {
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToSend)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToSend)) != pdFALSE) {
+ /* The task waiting has a higher priority than us so
+ force a context switch. */
+ if (pxHigherPriorityTaskWoken != NULL) {
+ *pxHigherPriorityTaskWoken = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* Increment the lock count so the task that unlocks the queue
+ knows that data was removed while it was locked. */
+ pxQueue->cRxLock = (int8_t)(cRxLock + 1);
+ }
+
+ xReturn = pdPASS;
+ } else {
+ xReturn = pdFAIL;
+ traceQUEUE_RECEIVE_FROM_ISR_FAILED(pxQueue);
+ }
+ }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer )
-{
-BaseType_t xReturn;
-UBaseType_t uxSavedInterruptStatus;
-int8_t *pcOriginalReadPosition;
-Queue_t * const pxQueue = xQueue;
-
- configASSERT( pxQueue );
- configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
- configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */
-
- /* RTOS ports that support interrupt nesting have the concept of a maximum
- system call (or maximum API call) interrupt priority. Interrupts that are
- above the maximum system call priority are kept permanently enabled, even
- when the RTOS kernel is in a critical section, but cannot make any calls to
- FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
- then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
- failure if a FreeRTOS API function is called from an interrupt that has been
- assigned a priority above the configured maximum system call priority.
- Only FreeRTOS functions that end in FromISR can be called from interrupts
- that have been assigned a priority at or (logically) below the maximum
- system call interrupt priority. FreeRTOS maintains a separate interrupt
- safe API to ensure interrupt entry is as fast and as simple as possible.
- More information (albeit Cortex-M specific) is provided on the following
- link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
-
- uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- /* Cannot block in an ISR, so check there is data available. */
- if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
- {
- traceQUEUE_PEEK_FROM_ISR( pxQueue );
-
- /* Remember the read position so it can be reset as nothing is
- actually being removed from the queue. */
- pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom;
- prvCopyDataFromQueue( pxQueue, pvBuffer );
- pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition;
-
- xReturn = pdPASS;
- }
- else
- {
- xReturn = pdFAIL;
- traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue );
- }
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
-
- return xReturn;
+BaseType_t xQueuePeekFromISR(QueueHandle_t xQueue, void *const pvBuffer) {
+ BaseType_t xReturn;
+ UBaseType_t uxSavedInterruptStatus;
+ int8_t * pcOriginalReadPosition;
+ Queue_t *const pxQueue = xQueue;
+
+ configASSERT(pxQueue);
+ configASSERT(!((pvBuffer == NULL) && (pxQueue->uxItemSize != (UBaseType_t)0U)));
+ configASSERT(pxQueue->uxItemSize != 0); /* Can't peek a semaphore. */
+
+ /* RTOS ports that support interrupt nesting have the concept of a maximum
+ system call (or maximum API call) interrupt priority. Interrupts that are
+ above the maximum system call priority are kept permanently enabled, even
+ when the RTOS kernel is in a critical section, but cannot make any calls to
+ FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
+ then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+ failure if a FreeRTOS API function is called from an interrupt that has been
+ assigned a priority above the configured maximum system call priority.
+ Only FreeRTOS functions that end in FromISR can be called from interrupts
+ that have been assigned a priority at or (logically) below the maximum
+ system call interrupt priority. FreeRTOS maintains a separate interrupt
+ safe API to ensure interrupt entry is as fast and as simple as possible.
+ More information (albeit Cortex-M specific) is provided on the following
+ link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ /* Cannot block in an ISR, so check there is data available. */
+ if (pxQueue->uxMessagesWaiting > (UBaseType_t)0) {
+ traceQUEUE_PEEK_FROM_ISR(pxQueue);
+
+ /* Remember the read position so it can be reset as nothing is
+ actually being removed from the queue. */
+ pcOriginalReadPosition = pxQueue->u.xQueue.pcReadFrom;
+ prvCopyDataFromQueue(pxQueue, pvBuffer);
+ pxQueue->u.xQueue.pcReadFrom = pcOriginalReadPosition;
+
+ xReturn = pdPASS;
+ } else {
+ xReturn = pdFAIL;
+ traceQUEUE_PEEK_FROM_ISR_FAILED(pxQueue);
+ }
+ }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue )
-{
-UBaseType_t uxReturn;
+UBaseType_t uxQueueMessagesWaiting(const QueueHandle_t xQueue) {
+ UBaseType_t uxReturn;
- configASSERT( xQueue );
+ configASSERT(xQueue);
- taskENTER_CRITICAL();
- {
- uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting;
- }
- taskEXIT_CRITICAL();
+ taskENTER_CRITICAL();
+ { uxReturn = ((Queue_t *)xQueue)->uxMessagesWaiting; }
+ taskEXIT_CRITICAL();
- return uxReturn;
+ return uxReturn;
} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */
/*-----------------------------------------------------------*/
-UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue )
-{
-UBaseType_t uxReturn;
-Queue_t * const pxQueue = xQueue;
+UBaseType_t uxQueueSpacesAvailable(const QueueHandle_t xQueue) {
+ UBaseType_t uxReturn;
+ Queue_t *const pxQueue = xQueue;
- configASSERT( pxQueue );
+ configASSERT(pxQueue);
- taskENTER_CRITICAL();
- {
- uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting;
- }
- taskEXIT_CRITICAL();
+ taskENTER_CRITICAL();
+ { uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting; }
+ taskEXIT_CRITICAL();
- return uxReturn;
+ return uxReturn;
} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */
/*-----------------------------------------------------------*/
-UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue )
-{
-UBaseType_t uxReturn;
-Queue_t * const pxQueue = xQueue;
+UBaseType_t uxQueueMessagesWaitingFromISR(const QueueHandle_t xQueue) {
+ UBaseType_t uxReturn;
+ Queue_t *const pxQueue = xQueue;
- configASSERT( pxQueue );
- uxReturn = pxQueue->uxMessagesWaiting;
+ configASSERT(pxQueue);
+ uxReturn = pxQueue->uxMessagesWaiting;
- return uxReturn;
+ return uxReturn;
} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */
/*-----------------------------------------------------------*/
-void vQueueDelete( QueueHandle_t xQueue )
-{
-Queue_t * const pxQueue = xQueue;
-
- configASSERT( pxQueue );
- traceQUEUE_DELETE( pxQueue );
-
- #if ( configQUEUE_REGISTRY_SIZE > 0 )
- {
- vQueueUnregisterQueue( pxQueue );
- }
- #endif
-
- #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) )
- {
- /* The queue can only have been allocated dynamically - free it
- again. */
- vPortFree( pxQueue );
- }
- #elif( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
- {
- /* The queue could have been allocated statically or dynamically, so
- check before attempting to free the memory. */
- if( pxQueue->ucStaticallyAllocated == ( uint8_t ) pdFALSE )
- {
- vPortFree( pxQueue );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #else
- {
- /* The queue must have been statically allocated, so is not going to be
- deleted. Avoid compiler warnings about the unused parameter. */
- ( void ) pxQueue;
- }
- #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
+void vQueueDelete(QueueHandle_t xQueue) {
+ Queue_t *const pxQueue = xQueue;
+
+ configASSERT(pxQueue);
+ traceQUEUE_DELETE(pxQueue);
+
+#if (configQUEUE_REGISTRY_SIZE > 0)
+ { vQueueUnregisterQueue(pxQueue); }
+#endif
+
+#if ((configSUPPORT_DYNAMIC_ALLOCATION == 1) && (configSUPPORT_STATIC_ALLOCATION == 0))
+ {
+ /* The queue can only have been allocated dynamically - free it
+ again. */
+ vPortFree(pxQueue);
+ }
+#elif ((configSUPPORT_DYNAMIC_ALLOCATION == 1) && (configSUPPORT_STATIC_ALLOCATION == 1))
+ {
+ /* The queue could have been allocated statically or dynamically, so
+ check before attempting to free the memory. */
+ if (pxQueue->ucStaticallyAllocated == (uint8_t)pdFALSE) {
+ vPortFree(pxQueue);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#else
+ {
+ /* The queue must have been statically allocated, so is not going to be
+ deleted. Avoid compiler warnings about the unused parameter. */
+ (void)pxQueue;
+ }
+#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
}
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
+#if (configUSE_TRACE_FACILITY == 1)
- UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue )
- {
- return ( ( Queue_t * ) xQueue )->uxQueueNumber;
- }
+UBaseType_t uxQueueGetQueueNumber(QueueHandle_t xQueue) { return ((Queue_t *)xQueue)->uxQueueNumber; }
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
+#if (configUSE_TRACE_FACILITY == 1)
- void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber )
- {
- ( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber;
- }
+void vQueueSetQueueNumber(QueueHandle_t xQueue, UBaseType_t uxQueueNumber) { ((Queue_t *)xQueue)->uxQueueNumber = uxQueueNumber; }
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
+#if (configUSE_TRACE_FACILITY == 1)
- uint8_t ucQueueGetQueueType( QueueHandle_t xQueue )
- {
- return ( ( Queue_t * ) xQueue )->ucQueueType;
- }
+uint8_t ucQueueGetQueueType(QueueHandle_t xQueue) { return ((Queue_t *)xQueue)->ucQueueType; }
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
-#if( configUSE_MUTEXES == 1 )
-
- static UBaseType_t prvGetDisinheritPriorityAfterTimeout( const Queue_t * const pxQueue )
- {
- UBaseType_t uxHighestPriorityOfWaitingTasks;
-
- /* If a task waiting for a mutex causes the mutex holder to inherit a
- priority, but the waiting task times out, then the holder should
- disinherit the priority - but only down to the highest priority of any
- other tasks that are waiting for the same mutex. For this purpose,
- return the priority of the highest priority task that is waiting for the
- mutex. */
- if( listCURRENT_LIST_LENGTH( &( pxQueue->xTasksWaitingToReceive ) ) > 0U )
- {
- uxHighestPriorityOfWaitingTasks = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) listGET_ITEM_VALUE_OF_HEAD_ENTRY( &( pxQueue->xTasksWaitingToReceive ) );
- }
- else
- {
- uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY;
- }
-
- return uxHighestPriorityOfWaitingTasks;
- }
+#if (configUSE_MUTEXES == 1)
+
+static UBaseType_t prvGetDisinheritPriorityAfterTimeout(const Queue_t *const pxQueue) {
+ UBaseType_t uxHighestPriorityOfWaitingTasks;
+
+ /* If a task waiting for a mutex causes the mutex holder to inherit a
+ priority, but the waiting task times out, then the holder should
+ disinherit the priority - but only down to the highest priority of any
+ other tasks that are waiting for the same mutex. For this purpose,
+ return the priority of the highest priority task that is waiting for the
+ mutex. */
+ if (listCURRENT_LIST_LENGTH(&(pxQueue->xTasksWaitingToReceive)) > 0U) {
+ uxHighestPriorityOfWaitingTasks = (UBaseType_t)configMAX_PRIORITIES - (UBaseType_t)listGET_ITEM_VALUE_OF_HEAD_ENTRY(&(pxQueue->xTasksWaitingToReceive));
+ } else {
+ uxHighestPriorityOfWaitingTasks = tskIDLE_PRIORITY;
+ }
+
+ return uxHighestPriorityOfWaitingTasks;
+}
#endif /* configUSE_MUTEXES */
/*-----------------------------------------------------------*/
-static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition )
-{
-BaseType_t xReturn = pdFALSE;
-UBaseType_t uxMessagesWaiting;
-
- /* This function is called from a critical section. */
-
- uxMessagesWaiting = pxQueue->uxMessagesWaiting;
-
- if( pxQueue->uxItemSize == ( UBaseType_t ) 0 )
- {
- #if ( configUSE_MUTEXES == 1 )
- {
- if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX )
- {
- /* The mutex is no longer being held. */
- xReturn = xTaskPriorityDisinherit( pxQueue->u.xSemaphore.xMutexHolder );
- pxQueue->u.xSemaphore.xMutexHolder = NULL;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_MUTEXES */
- }
- else if( xPosition == queueSEND_TO_BACK )
- {
- ( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */
- pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */
- if( pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */
- {
- pxQueue->pcWriteTo = pxQueue->pcHead;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- ( void ) memcpy( ( void * ) pxQueue->u.xQueue.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */
- pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize;
- if( pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */
- {
- pxQueue->u.xQueue.pcReadFrom = ( pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- if( xPosition == queueOVERWRITE )
- {
- if( uxMessagesWaiting > ( UBaseType_t ) 0 )
- {
- /* An item is not being added but overwritten, so subtract
- one from the recorded number of items in the queue so when
- one is added again below the number of recorded items remains
- correct. */
- --uxMessagesWaiting;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- pxQueue->uxMessagesWaiting = uxMessagesWaiting + ( UBaseType_t ) 1;
-
- return xReturn;
+static BaseType_t prvCopyDataToQueue(Queue_t *const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition) {
+ BaseType_t xReturn = pdFALSE;
+ UBaseType_t uxMessagesWaiting;
+
+ /* This function is called from a critical section. */
+
+ uxMessagesWaiting = pxQueue->uxMessagesWaiting;
+
+ if (pxQueue->uxItemSize == (UBaseType_t)0) {
+#if (configUSE_MUTEXES == 1)
+ {
+ if (pxQueue->uxQueueType == queueQUEUE_IS_MUTEX) {
+ /* The mutex is no longer being held. */
+ xReturn = xTaskPriorityDisinherit(pxQueue->u.xSemaphore.xMutexHolder);
+ pxQueue->u.xSemaphore.xMutexHolder = NULL;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_MUTEXES */
+ } else if (xPosition == queueSEND_TO_BACK) {
+ (void)memcpy(
+ (void *)pxQueue->pcWriteTo, pvItemToQueue,
+ (size_t)pxQueue->uxItemSize); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to
+ memcpy() if the copy size is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */
+ pxQueue->pcWriteTo += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */
+ if (pxQueue->pcWriteTo >= pxQueue->u.xQueue.pcTail) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */
+ {
+ pxQueue->pcWriteTo = pxQueue->pcHead;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ (void)memcpy((void *)pxQueue->u.xQueue.pcReadFrom, pvItemToQueue,
+ (size_t)pxQueue->uxItemSize); /*lint !e961 !e9087 !e418 MISRA exception as the casts are only redundant for some ports. Cast to void required by function signature and safe as no
+ alignment requirement and copy length specified in bytes. Assert checks null pointer only used when length is 0. */
+ pxQueue->u.xQueue.pcReadFrom -= pxQueue->uxItemSize;
+ if (pxQueue->u.xQueue.pcReadFrom < pxQueue->pcHead) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */
+ {
+ pxQueue->u.xQueue.pcReadFrom = (pxQueue->u.xQueue.pcTail - pxQueue->uxItemSize);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ if (xPosition == queueOVERWRITE) {
+ if (uxMessagesWaiting > (UBaseType_t)0) {
+ /* An item is not being added but overwritten, so subtract
+ one from the recorded number of items in the queue so when
+ one is added again below the number of recorded items remains
+ correct. */
+ --uxMessagesWaiting;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ pxQueue->uxMessagesWaiting = uxMessagesWaiting + (UBaseType_t)1;
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer )
-{
- if( pxQueue->uxItemSize != ( UBaseType_t ) 0 )
- {
- pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */
- if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */
- {
- pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */
- }
+static void prvCopyDataFromQueue(Queue_t *const pxQueue, void *const pvBuffer) {
+ if (pxQueue->uxItemSize != (UBaseType_t)0) {
+ pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize; /*lint !e9016 Pointer arithmetic on char types ok, especially in this use case where it is the clearest way of conveying intent. */
+ if (pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */
+ {
+ pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ (void)memcpy(
+ (void *)pvBuffer, (void *)pxQueue->u.xQueue.pcReadFrom,
+ (size_t)pxQueue->uxItemSize); /*lint !e961 !e418 !e9087 MISRA exception as the casts are only redundant for some ports. Also previous logic ensures a null pointer can only be passed to
+ memcpy() when the count is 0. Cast to void required by function signature and safe as no alignment requirement and copy length specified in bytes. */
+ }
}
/*-----------------------------------------------------------*/
-static void prvUnlockQueue( Queue_t * const pxQueue )
-{
- /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */
-
- /* The lock counts contains the number of extra data items placed or
- removed from the queue while the queue was locked. When a queue is
- locked items can be added or removed, but the event lists cannot be
- updated. */
- taskENTER_CRITICAL();
- {
- int8_t cTxLock = pxQueue->cTxLock;
-
- /* See if data was added to the queue while it was locked. */
- while( cTxLock > queueLOCKED_UNMODIFIED )
- {
- /* Data was posted while the queue was locked. Are any tasks
- blocked waiting for data to become available? */
- #if ( configUSE_QUEUE_SETS == 1 )
- {
- if( pxQueue->pxQueueSetContainer != NULL )
- {
- if( prvNotifyQueueSetContainer( pxQueue ) != pdFALSE )
- {
- /* The queue is a member of a queue set, and posting to
- the queue set caused a higher priority task to unblock.
- A context switch is required. */
- vTaskMissedYield();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* Tasks that are removed from the event list will get
- added to the pending ready list as the scheduler is still
- suspended. */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The task waiting has a higher priority so record that a
- context switch is required. */
- vTaskMissedYield();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- break;
- }
- }
- }
- #else /* configUSE_QUEUE_SETS */
- {
- /* Tasks that are removed from the event list will get added to
- the pending ready list as the scheduler is still suspended. */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The task waiting has a higher priority so record that
- a context switch is required. */
- vTaskMissedYield();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- break;
- }
- }
- #endif /* configUSE_QUEUE_SETS */
-
- --cTxLock;
- }
-
- pxQueue->cTxLock = queueUNLOCKED;
- }
- taskEXIT_CRITICAL();
-
- /* Do the same for the Rx lock. */
- taskENTER_CRITICAL();
- {
- int8_t cRxLock = pxQueue->cRxLock;
-
- while( cRxLock > queueLOCKED_UNMODIFIED )
- {
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
- {
- vTaskMissedYield();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- --cRxLock;
- }
- else
- {
- break;
- }
- }
-
- pxQueue->cRxLock = queueUNLOCKED;
- }
- taskEXIT_CRITICAL();
+static void prvUnlockQueue(Queue_t *const pxQueue) {
+ /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */
+
+ /* The lock counts contains the number of extra data items placed or
+ removed from the queue while the queue was locked. When a queue is
+ locked items can be added or removed, but the event lists cannot be
+ updated. */
+ taskENTER_CRITICAL();
+ {
+ int8_t cTxLock = pxQueue->cTxLock;
+
+ /* See if data was added to the queue while it was locked. */
+ while (cTxLock > queueLOCKED_UNMODIFIED) {
+/* Data was posted while the queue was locked. Are any tasks
+blocked waiting for data to become available? */
+#if (configUSE_QUEUE_SETS == 1)
+ {
+ if (pxQueue->pxQueueSetContainer != NULL) {
+ if (prvNotifyQueueSetContainer(pxQueue) != pdFALSE) {
+ /* The queue is a member of a queue set, and posting to
+ the queue set caused a higher priority task to unblock.
+ A context switch is required. */
+ vTaskMissedYield();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* Tasks that are removed from the event list will get
+ added to the pending ready list as the scheduler is still
+ suspended. */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The task waiting has a higher priority so record that a
+ context switch is required. */
+ vTaskMissedYield();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ break;
+ }
+ }
+ }
+#else /* configUSE_QUEUE_SETS */
+ {
+ /* Tasks that are removed from the event list will get added to
+ the pending ready list as the scheduler is still suspended. */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The task waiting has a higher priority so record that
+ a context switch is required. */
+ vTaskMissedYield();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ break;
+ }
+ }
+#endif /* configUSE_QUEUE_SETS */
+
+ --cTxLock;
+ }
+
+ pxQueue->cTxLock = queueUNLOCKED;
+ }
+ taskEXIT_CRITICAL();
+
+ /* Do the same for the Rx lock. */
+ taskENTER_CRITICAL();
+ {
+ int8_t cRxLock = pxQueue->cRxLock;
+
+ while (cRxLock > queueLOCKED_UNMODIFIED) {
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToSend)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueue->xTasksWaitingToSend)) != pdFALSE) {
+ vTaskMissedYield();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ --cRxLock;
+ } else {
+ break;
+ }
+ }
+
+ pxQueue->cRxLock = queueUNLOCKED;
+ }
+ taskEXIT_CRITICAL();
}
/*-----------------------------------------------------------*/
-static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue )
-{
-BaseType_t xReturn;
-
- taskENTER_CRITICAL();
- {
- if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 )
- {
- xReturn = pdTRUE;
- }
- else
- {
- xReturn = pdFALSE;
- }
- }
- taskEXIT_CRITICAL();
-
- return xReturn;
+static BaseType_t prvIsQueueEmpty(const Queue_t *pxQueue) {
+ BaseType_t xReturn;
+
+ taskENTER_CRITICAL();
+ {
+ if (pxQueue->uxMessagesWaiting == (UBaseType_t)0) {
+ xReturn = pdTRUE;
+ } else {
+ xReturn = pdFALSE;
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue )
-{
-BaseType_t xReturn;
-Queue_t * const pxQueue = xQueue;
-
- configASSERT( pxQueue );
- if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 )
- {
- xReturn = pdTRUE;
- }
- else
- {
- xReturn = pdFALSE;
- }
-
- return xReturn;
+BaseType_t xQueueIsQueueEmptyFromISR(const QueueHandle_t xQueue) {
+ BaseType_t xReturn;
+ Queue_t *const pxQueue = xQueue;
+
+ configASSERT(pxQueue);
+ if (pxQueue->uxMessagesWaiting == (UBaseType_t)0) {
+ xReturn = pdTRUE;
+ } else {
+ xReturn = pdFALSE;
+ }
+
+ return xReturn;
} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */
/*-----------------------------------------------------------*/
-static BaseType_t prvIsQueueFull( const Queue_t *pxQueue )
-{
-BaseType_t xReturn;
-
- taskENTER_CRITICAL();
- {
- if( pxQueue->uxMessagesWaiting == pxQueue->uxLength )
- {
- xReturn = pdTRUE;
- }
- else
- {
- xReturn = pdFALSE;
- }
- }
- taskEXIT_CRITICAL();
-
- return xReturn;
+static BaseType_t prvIsQueueFull(const Queue_t *pxQueue) {
+ BaseType_t xReturn;
+
+ taskENTER_CRITICAL();
+ {
+ if (pxQueue->uxMessagesWaiting == pxQueue->uxLength) {
+ xReturn = pdTRUE;
+ } else {
+ xReturn = pdFALSE;
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue )
-{
-BaseType_t xReturn;
-Queue_t * const pxQueue = xQueue;
-
- configASSERT( pxQueue );
- if( pxQueue->uxMessagesWaiting == pxQueue->uxLength )
- {
- xReturn = pdTRUE;
- }
- else
- {
- xReturn = pdFALSE;
- }
-
- return xReturn;
+BaseType_t xQueueIsQueueFullFromISR(const QueueHandle_t xQueue) {
+ BaseType_t xReturn;
+ Queue_t *const pxQueue = xQueue;
+
+ configASSERT(pxQueue);
+ if (pxQueue->uxMessagesWaiting == pxQueue->uxLength) {
+ xReturn = pdTRUE;
+ } else {
+ xReturn = pdFALSE;
+ }
+
+ return xReturn;
} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */
/*-----------------------------------------------------------*/
-#if ( configUSE_CO_ROUTINES == 1 )
-
- BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait )
- {
- BaseType_t xReturn;
- Queue_t * const pxQueue = xQueue;
-
- /* If the queue is already full we may have to block. A critical section
- is required to prevent an interrupt removing something from the queue
- between the check to see if the queue is full and blocking on the queue. */
- portDISABLE_INTERRUPTS();
- {
- if( prvIsQueueFull( pxQueue ) != pdFALSE )
- {
- /* The queue is full - do we want to block or just leave without
- posting? */
- if( xTicksToWait > ( TickType_t ) 0 )
- {
- /* As this is called from a coroutine we cannot block directly, but
- return indicating that we need to block. */
- vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) );
- portENABLE_INTERRUPTS();
- return errQUEUE_BLOCKED;
- }
- else
- {
- portENABLE_INTERRUPTS();
- return errQUEUE_FULL;
- }
- }
- }
- portENABLE_INTERRUPTS();
-
- portDISABLE_INTERRUPTS();
- {
- if( pxQueue->uxMessagesWaiting < pxQueue->uxLength )
- {
- /* There is room in the queue, copy the data into the queue. */
- prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK );
- xReturn = pdPASS;
-
- /* Were any co-routines waiting for data to become available? */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- /* In this instance the co-routine could be placed directly
- into the ready list as we are within a critical section.
- Instead the same pending ready list mechanism is used as if
- the event were caused from within an interrupt. */
- if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The co-routine waiting has a higher priority so record
- that a yield might be appropriate. */
- xReturn = errQUEUE_YIELD;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- xReturn = errQUEUE_FULL;
- }
- }
- portENABLE_INTERRUPTS();
-
- return xReturn;
- }
+#if (configUSE_CO_ROUTINES == 1)
+
+BaseType_t xQueueCRSend(QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait) {
+ BaseType_t xReturn;
+ Queue_t *const pxQueue = xQueue;
+
+ /* If the queue is already full we may have to block. A critical section
+ is required to prevent an interrupt removing something from the queue
+ between the check to see if the queue is full and blocking on the queue. */
+ portDISABLE_INTERRUPTS();
+ {
+ if (prvIsQueueFull(pxQueue) != pdFALSE) {
+ /* The queue is full - do we want to block or just leave without
+ posting? */
+ if (xTicksToWait > (TickType_t)0) {
+ /* As this is called from a coroutine we cannot block directly, but
+ return indicating that we need to block. */
+ vCoRoutineAddToDelayedList(xTicksToWait, &(pxQueue->xTasksWaitingToSend));
+ portENABLE_INTERRUPTS();
+ return errQUEUE_BLOCKED;
+ } else {
+ portENABLE_INTERRUPTS();
+ return errQUEUE_FULL;
+ }
+ }
+ }
+ portENABLE_INTERRUPTS();
+
+ portDISABLE_INTERRUPTS();
+ {
+ if (pxQueue->uxMessagesWaiting < pxQueue->uxLength) {
+ /* There is room in the queue, copy the data into the queue. */
+ prvCopyDataToQueue(pxQueue, pvItemToQueue, queueSEND_TO_BACK);
+ xReturn = pdPASS;
+
+ /* Were any co-routines waiting for data to become available? */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ /* In this instance the co-routine could be placed directly
+ into the ready list as we are within a critical section.
+ Instead the same pending ready list mechanism is used as if
+ the event were caused from within an interrupt. */
+ if (xCoRoutineRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The co-routine waiting has a higher priority so record
+ that a yield might be appropriate. */
+ xReturn = errQUEUE_YIELD;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ xReturn = errQUEUE_FULL;
+ }
+ }
+ portENABLE_INTERRUPTS();
+
+ return xReturn;
+}
#endif /* configUSE_CO_ROUTINES */
/*-----------------------------------------------------------*/
-#if ( configUSE_CO_ROUTINES == 1 )
-
- BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait )
- {
- BaseType_t xReturn;
- Queue_t * const pxQueue = xQueue;
-
- /* If the queue is already empty we may have to block. A critical section
- is required to prevent an interrupt adding something to the queue
- between the check to see if the queue is empty and blocking on the queue. */
- portDISABLE_INTERRUPTS();
- {
- if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 )
- {
- /* There are no messages in the queue, do we want to block or just
- leave with nothing? */
- if( xTicksToWait > ( TickType_t ) 0 )
- {
- /* As this is a co-routine we cannot block directly, but return
- indicating that we need to block. */
- vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) );
- portENABLE_INTERRUPTS();
- return errQUEUE_BLOCKED;
- }
- else
- {
- portENABLE_INTERRUPTS();
- return errQUEUE_FULL;
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- portENABLE_INTERRUPTS();
-
- portDISABLE_INTERRUPTS();
- {
- if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
- {
- /* Data is available from the queue. */
- pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize;
- if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail )
- {
- pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- --( pxQueue->uxMessagesWaiting );
- ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize );
-
- xReturn = pdPASS;
-
- /* Were any co-routines waiting for space to become available? */
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
- {
- /* In this instance the co-routine could be placed directly
- into the ready list as we are within a critical section.
- Instead the same pending ready list mechanism is used as if
- the event were caused from within an interrupt. */
- if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
- {
- xReturn = errQUEUE_YIELD;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- xReturn = pdFAIL;
- }
- }
- portENABLE_INTERRUPTS();
-
- return xReturn;
- }
+#if (configUSE_CO_ROUTINES == 1)
+
+BaseType_t xQueueCRReceive(QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait) {
+ BaseType_t xReturn;
+ Queue_t *const pxQueue = xQueue;
+
+ /* If the queue is already empty we may have to block. A critical section
+ is required to prevent an interrupt adding something to the queue
+ between the check to see if the queue is empty and blocking on the queue. */
+ portDISABLE_INTERRUPTS();
+ {
+ if (pxQueue->uxMessagesWaiting == (UBaseType_t)0) {
+ /* There are no messages in the queue, do we want to block or just
+ leave with nothing? */
+ if (xTicksToWait > (TickType_t)0) {
+ /* As this is a co-routine we cannot block directly, but return
+ indicating that we need to block. */
+ vCoRoutineAddToDelayedList(xTicksToWait, &(pxQueue->xTasksWaitingToReceive));
+ portENABLE_INTERRUPTS();
+ return errQUEUE_BLOCKED;
+ } else {
+ portENABLE_INTERRUPTS();
+ return errQUEUE_FULL;
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ portENABLE_INTERRUPTS();
+
+ portDISABLE_INTERRUPTS();
+ {
+ if (pxQueue->uxMessagesWaiting > (UBaseType_t)0) {
+ /* Data is available from the queue. */
+ pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize;
+ if (pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail) {
+ pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ --(pxQueue->uxMessagesWaiting);
+ (void)memcpy((void *)pvBuffer, (void *)pxQueue->u.xQueue.pcReadFrom, (unsigned)pxQueue->uxItemSize);
+
+ xReturn = pdPASS;
+
+ /* Were any co-routines waiting for space to become available? */
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToSend)) == pdFALSE) {
+ /* In this instance the co-routine could be placed directly
+ into the ready list as we are within a critical section.
+ Instead the same pending ready list mechanism is used as if
+ the event were caused from within an interrupt. */
+ if (xCoRoutineRemoveFromEventList(&(pxQueue->xTasksWaitingToSend)) != pdFALSE) {
+ xReturn = errQUEUE_YIELD;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ xReturn = pdFAIL;
+ }
+ }
+ portENABLE_INTERRUPTS();
+
+ return xReturn;
+}
#endif /* configUSE_CO_ROUTINES */
/*-----------------------------------------------------------*/
-#if ( configUSE_CO_ROUTINES == 1 )
-
- BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken )
- {
- Queue_t * const pxQueue = xQueue;
-
- /* Cannot block within an ISR so if there is no space on the queue then
- exit without doing anything. */
- if( pxQueue->uxMessagesWaiting < pxQueue->uxLength )
- {
- prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK );
-
- /* We only want to wake one co-routine per ISR, so check that a
- co-routine has not already been woken. */
- if( xCoRoutinePreviouslyWoken == pdFALSE )
- {
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- return pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- return xCoRoutinePreviouslyWoken;
- }
+#if (configUSE_CO_ROUTINES == 1)
+
+BaseType_t xQueueCRSendFromISR(QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken) {
+ Queue_t *const pxQueue = xQueue;
+
+ /* Cannot block within an ISR so if there is no space on the queue then
+ exit without doing anything. */
+ if (pxQueue->uxMessagesWaiting < pxQueue->uxLength) {
+ prvCopyDataToQueue(pxQueue, pvItemToQueue, queueSEND_TO_BACK);
+
+ /* We only want to wake one co-routine per ISR, so check that a
+ co-routine has not already been woken. */
+ if (xCoRoutinePreviouslyWoken == pdFALSE) {
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xCoRoutineRemoveFromEventList(&(pxQueue->xTasksWaitingToReceive)) != pdFALSE) {
+ return pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return xCoRoutinePreviouslyWoken;
+}
#endif /* configUSE_CO_ROUTINES */
/*-----------------------------------------------------------*/
-#if ( configUSE_CO_ROUTINES == 1 )
-
- BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxCoRoutineWoken )
- {
- BaseType_t xReturn;
- Queue_t * const pxQueue = xQueue;
-
- /* We cannot block from an ISR, so check there is data available. If
- not then just leave without doing anything. */
- if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
- {
- /* Copy the data from the queue. */
- pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize;
- if( pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail )
- {
- pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- --( pxQueue->uxMessagesWaiting );
- ( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.xQueue.pcReadFrom, ( unsigned ) pxQueue->uxItemSize );
-
- if( ( *pxCoRoutineWoken ) == pdFALSE )
- {
- if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
- {
- if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
- {
- *pxCoRoutineWoken = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- xReturn = pdPASS;
- }
- else
- {
- xReturn = pdFAIL;
- }
-
- return xReturn;
- }
+#if (configUSE_CO_ROUTINES == 1)
+
+BaseType_t xQueueCRReceiveFromISR(QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxCoRoutineWoken) {
+ BaseType_t xReturn;
+ Queue_t *const pxQueue = xQueue;
+
+ /* We cannot block from an ISR, so check there is data available. If
+ not then just leave without doing anything. */
+ if (pxQueue->uxMessagesWaiting > (UBaseType_t)0) {
+ /* Copy the data from the queue. */
+ pxQueue->u.xQueue.pcReadFrom += pxQueue->uxItemSize;
+ if (pxQueue->u.xQueue.pcReadFrom >= pxQueue->u.xQueue.pcTail) {
+ pxQueue->u.xQueue.pcReadFrom = pxQueue->pcHead;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ --(pxQueue->uxMessagesWaiting);
+ (void)memcpy((void *)pvBuffer, (void *)pxQueue->u.xQueue.pcReadFrom, (unsigned)pxQueue->uxItemSize);
+
+ if ((*pxCoRoutineWoken) == pdFALSE) {
+ if (listLIST_IS_EMPTY(&(pxQueue->xTasksWaitingToSend)) == pdFALSE) {
+ if (xCoRoutineRemoveFromEventList(&(pxQueue->xTasksWaitingToSend)) != pdFALSE) {
+ *pxCoRoutineWoken = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ xReturn = pdPASS;
+ } else {
+ xReturn = pdFAIL;
+ }
+
+ return xReturn;
+}
#endif /* configUSE_CO_ROUTINES */
/*-----------------------------------------------------------*/
-#if ( configQUEUE_REGISTRY_SIZE > 0 )
-
- void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- {
- UBaseType_t ux;
-
- /* See if there is an empty space in the registry. A NULL name denotes
- a free slot. */
- for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ )
- {
- if( xQueueRegistry[ ux ].pcQueueName == NULL )
- {
- /* Store the information on this queue. */
- xQueueRegistry[ ux ].pcQueueName = pcQueueName;
- xQueueRegistry[ ux ].xHandle = xQueue;
-
- traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName );
- break;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
+#if (configQUEUE_REGISTRY_SIZE > 0)
+
+void vQueueAddToRegistry(QueueHandle_t xQueue, const char *pcQueueName) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+{
+ UBaseType_t ux;
+
+ /* See if there is an empty space in the registry. A NULL name denotes
+ a free slot. */
+ for (ux = (UBaseType_t)0U; ux < (UBaseType_t)configQUEUE_REGISTRY_SIZE; ux++) {
+ if (xQueueRegistry[ux].pcQueueName == NULL) {
+ /* Store the information on this queue. */
+ xQueueRegistry[ux].pcQueueName = pcQueueName;
+ xQueueRegistry[ux].xHandle = xQueue;
+
+ traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName);
+ break;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+}
#endif /* configQUEUE_REGISTRY_SIZE */
/*-----------------------------------------------------------*/
-#if ( configQUEUE_REGISTRY_SIZE > 0 )
-
- const char *pcQueueGetName( QueueHandle_t xQueue ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- {
- UBaseType_t ux;
- const char *pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
-
- /* Note there is nothing here to protect against another task adding or
- removing entries from the registry while it is being searched. */
- for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ )
- {
- if( xQueueRegistry[ ux ].xHandle == xQueue )
- {
- pcReturn = xQueueRegistry[ ux ].pcQueueName;
- break;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- return pcReturn;
- } /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */
+#if (configQUEUE_REGISTRY_SIZE > 0)
+
+const char *pcQueueGetName(QueueHandle_t xQueue) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+{
+ UBaseType_t ux;
+ const char *pcReturn = NULL; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+ /* Note there is nothing here to protect against another task adding or
+ removing entries from the registry while it is being searched. */
+ for (ux = (UBaseType_t)0U; ux < (UBaseType_t)configQUEUE_REGISTRY_SIZE; ux++) {
+ if (xQueueRegistry[ux].xHandle == xQueue) {
+ pcReturn = xQueueRegistry[ux].pcQueueName;
+ break;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ return pcReturn;
+} /*lint !e818 xQueue cannot be a pointer to const because it is a typedef. */
#endif /* configQUEUE_REGISTRY_SIZE */
/*-----------------------------------------------------------*/
-#if ( configQUEUE_REGISTRY_SIZE > 0 )
-
- void vQueueUnregisterQueue( QueueHandle_t xQueue )
- {
- UBaseType_t ux;
-
- /* See if the handle of the queue being unregistered in actually in the
- registry. */
- for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ )
- {
- if( xQueueRegistry[ ux ].xHandle == xQueue )
- {
- /* Set the name to NULL to show that this slot if free again. */
- xQueueRegistry[ ux ].pcQueueName = NULL;
-
- /* Set the handle to NULL to ensure the same queue handle cannot
- appear in the registry twice if it is added, removed, then
- added again. */
- xQueueRegistry[ ux ].xHandle = ( QueueHandle_t ) 0;
- break;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- } /*lint !e818 xQueue could not be pointer to const because it is a typedef. */
+#if (configQUEUE_REGISTRY_SIZE > 0)
+
+void vQueueUnregisterQueue(QueueHandle_t xQueue) {
+ UBaseType_t ux;
+
+ /* See if the handle of the queue being unregistered in actually in the
+ registry. */
+ for (ux = (UBaseType_t)0U; ux < (UBaseType_t)configQUEUE_REGISTRY_SIZE; ux++) {
+ if (xQueueRegistry[ux].xHandle == xQueue) {
+ /* Set the name to NULL to show that this slot if free again. */
+ xQueueRegistry[ux].pcQueueName = NULL;
+
+ /* Set the handle to NULL to ensure the same queue handle cannot
+ appear in the registry twice if it is added, removed, then
+ added again. */
+ xQueueRegistry[ux].xHandle = (QueueHandle_t)0;
+ break;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */
#endif /* configQUEUE_REGISTRY_SIZE */
/*-----------------------------------------------------------*/
-#if ( configUSE_TIMERS == 1 )
-
- void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely )
- {
- Queue_t * const pxQueue = xQueue;
-
- /* This function should not be called by application code hence the
- 'Restricted' in its name. It is not part of the public API. It is
- designed for use by kernel code, and has special calling requirements.
- It can result in vListInsert() being called on a list that can only
- possibly ever have one item in it, so the list will be fast, but even
- so it should be called with the scheduler locked and not from a critical
- section. */
-
- /* Only do anything if there are no messages in the queue. This function
- will not actually cause the task to block, just place it on a blocked
- list. It will not block until the scheduler is unlocked - at which
- time a yield will be performed. If an item is added to the queue while
- the queue is locked, and the calling task blocks on the queue, then the
- calling task will be immediately unblocked when the queue is unlocked. */
- prvLockQueue( pxQueue );
- if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U )
- {
- /* There is nothing in the queue, block for the specified period. */
- vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait, xWaitIndefinitely );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- prvUnlockQueue( pxQueue );
- }
+#if (configUSE_TIMERS == 1)
+
+void vQueueWaitForMessageRestricted(QueueHandle_t xQueue, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely) {
+ Queue_t *const pxQueue = xQueue;
+
+ /* This function should not be called by application code hence the
+ 'Restricted' in its name. It is not part of the public API. It is
+ designed for use by kernel code, and has special calling requirements.
+ It can result in vListInsert() being called on a list that can only
+ possibly ever have one item in it, so the list will be fast, but even
+ so it should be called with the scheduler locked and not from a critical
+ section. */
+
+ /* Only do anything if there are no messages in the queue. This function
+ will not actually cause the task to block, just place it on a blocked
+ list. It will not block until the scheduler is unlocked - at which
+ time a yield will be performed. If an item is added to the queue while
+ the queue is locked, and the calling task blocks on the queue, then the
+ calling task will be immediately unblocked when the queue is unlocked. */
+ prvLockQueue(pxQueue);
+ if (pxQueue->uxMessagesWaiting == (UBaseType_t)0U) {
+ /* There is nothing in the queue, block for the specified period. */
+ vTaskPlaceOnEventListRestricted(&(pxQueue->xTasksWaitingToReceive), xTicksToWait, xWaitIndefinitely);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ prvUnlockQueue(pxQueue);
+}
#endif /* configUSE_TIMERS */
/*-----------------------------------------------------------*/
-#if( ( configUSE_QUEUE_SETS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
+#if ((configUSE_QUEUE_SETS == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1))
- QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength )
- {
- QueueSetHandle_t pxQueue;
+QueueSetHandle_t xQueueCreateSet(const UBaseType_t uxEventQueueLength) {
+ QueueSetHandle_t pxQueue;
- pxQueue = xQueueGenericCreate( uxEventQueueLength, ( UBaseType_t ) sizeof( Queue_t * ), queueQUEUE_TYPE_SET );
+ pxQueue = xQueueGenericCreate(uxEventQueueLength, (UBaseType_t)sizeof(Queue_t *), queueQUEUE_TYPE_SET);
- return pxQueue;
- }
+ return pxQueue;
+}
#endif /* configUSE_QUEUE_SETS */
/*-----------------------------------------------------------*/
-#if ( configUSE_QUEUE_SETS == 1 )
-
- BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet )
- {
- BaseType_t xReturn;
-
- taskENTER_CRITICAL();
- {
- if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL )
- {
- /* Cannot add a queue/semaphore to more than one queue set. */
- xReturn = pdFAIL;
- }
- else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 )
- {
- /* Cannot add a queue/semaphore to a queue set if there are already
- items in the queue/semaphore. */
- xReturn = pdFAIL;
- }
- else
- {
- ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet;
- xReturn = pdPASS;
- }
- }
- taskEXIT_CRITICAL();
-
- return xReturn;
- }
+#if (configUSE_QUEUE_SETS == 1)
+
+BaseType_t xQueueAddToSet(QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet) {
+ BaseType_t xReturn;
+
+ taskENTER_CRITICAL();
+ {
+ if (((Queue_t *)xQueueOrSemaphore)->pxQueueSetContainer != NULL) {
+ /* Cannot add a queue/semaphore to more than one queue set. */
+ xReturn = pdFAIL;
+ } else if (((Queue_t *)xQueueOrSemaphore)->uxMessagesWaiting != (UBaseType_t)0) {
+ /* Cannot add a queue/semaphore to a queue set if there are already
+ items in the queue/semaphore. */
+ xReturn = pdFAIL;
+ } else {
+ ((Queue_t *)xQueueOrSemaphore)->pxQueueSetContainer = xQueueSet;
+ xReturn = pdPASS;
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
+}
#endif /* configUSE_QUEUE_SETS */
/*-----------------------------------------------------------*/
-#if ( configUSE_QUEUE_SETS == 1 )
-
- BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet )
- {
- BaseType_t xReturn;
- Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore;
-
- if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet )
- {
- /* The queue was not a member of the set. */
- xReturn = pdFAIL;
- }
- else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 )
- {
- /* It is dangerous to remove a queue from a set when the queue is
- not empty because the queue set will still hold pending events for
- the queue. */
- xReturn = pdFAIL;
- }
- else
- {
- taskENTER_CRITICAL();
- {
- /* The queue is no longer contained in the set. */
- pxQueueOrSemaphore->pxQueueSetContainer = NULL;
- }
- taskEXIT_CRITICAL();
- xReturn = pdPASS;
- }
-
- return xReturn;
- } /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */
+#if (configUSE_QUEUE_SETS == 1)
+
+BaseType_t xQueueRemoveFromSet(QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet) {
+ BaseType_t xReturn;
+ Queue_t *const pxQueueOrSemaphore = (Queue_t *)xQueueOrSemaphore;
+
+ if (pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet) {
+ /* The queue was not a member of the set. */
+ xReturn = pdFAIL;
+ } else if (pxQueueOrSemaphore->uxMessagesWaiting != (UBaseType_t)0) {
+ /* It is dangerous to remove a queue from a set when the queue is
+ not empty because the queue set will still hold pending events for
+ the queue. */
+ xReturn = pdFAIL;
+ } else {
+ taskENTER_CRITICAL();
+ {
+ /* The queue is no longer contained in the set. */
+ pxQueueOrSemaphore->pxQueueSetContainer = NULL;
+ }
+ taskEXIT_CRITICAL();
+ xReturn = pdPASS;
+ }
+
+ return xReturn;
+} /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */
#endif /* configUSE_QUEUE_SETS */
/*-----------------------------------------------------------*/
-#if ( configUSE_QUEUE_SETS == 1 )
+#if (configUSE_QUEUE_SETS == 1)
- QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, TickType_t const xTicksToWait )
- {
- QueueSetMemberHandle_t xReturn = NULL;
+QueueSetMemberHandle_t xQueueSelectFromSet(QueueSetHandle_t xQueueSet, TickType_t const xTicksToWait) {
+ QueueSetMemberHandle_t xReturn = NULL;
- ( void ) xQueueReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait ); /*lint !e961 Casting from one typedef to another is not redundant. */
- return xReturn;
- }
+ (void)xQueueReceive((QueueHandle_t)xQueueSet, &xReturn, xTicksToWait); /*lint !e961 Casting from one typedef to another is not redundant. */
+ return xReturn;
+}
#endif /* configUSE_QUEUE_SETS */
/*-----------------------------------------------------------*/
-#if ( configUSE_QUEUE_SETS == 1 )
+#if (configUSE_QUEUE_SETS == 1)
- QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet )
- {
- QueueSetMemberHandle_t xReturn = NULL;
+QueueSetMemberHandle_t xQueueSelectFromSetFromISR(QueueSetHandle_t xQueueSet) {
+ QueueSetMemberHandle_t xReturn = NULL;
- ( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */
- return xReturn;
- }
+ (void)xQueueReceiveFromISR((QueueHandle_t)xQueueSet, &xReturn, NULL); /*lint !e961 Casting from one typedef to another is not redundant. */
+ return xReturn;
+}
#endif /* configUSE_QUEUE_SETS */
/*-----------------------------------------------------------*/
-#if ( configUSE_QUEUE_SETS == 1 )
-
- static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue )
- {
- Queue_t *pxQueueSetContainer = pxQueue->pxQueueSetContainer;
- BaseType_t xReturn = pdFALSE;
-
- /* This function must be called form a critical section. */
-
- configASSERT( pxQueueSetContainer );
- configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength );
-
- if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength )
- {
- const int8_t cTxLock = pxQueueSetContainer->cTxLock;
-
- traceQUEUE_SEND( pxQueueSetContainer );
-
- /* The data copied is the handle of the queue that contains data. */
- xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, queueSEND_TO_BACK );
-
- if( cTxLock == queueUNLOCKED )
- {
- if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE )
- {
- if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE )
- {
- /* The task waiting has a higher priority. */
- xReturn = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- pxQueueSetContainer->cTxLock = ( int8_t ) ( cTxLock + 1 );
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- return xReturn;
- }
-
-#endif /* configUSE_QUEUE_SETS */
-
-
-
+#if (configUSE_QUEUE_SETS == 1)
+static BaseType_t prvNotifyQueueSetContainer(const Queue_t *const pxQueue) {
+ Queue_t * pxQueueSetContainer = pxQueue->pxQueueSetContainer;
+ BaseType_t xReturn = pdFALSE;
+ /* This function must be called form a critical section. */
+ configASSERT(pxQueueSetContainer);
+ configASSERT(pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength);
+ if (pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength) {
+ const int8_t cTxLock = pxQueueSetContainer->cTxLock;
+ traceQUEUE_SEND(pxQueueSetContainer);
+ /* The data copied is the handle of the queue that contains data. */
+ xReturn = prvCopyDataToQueue(pxQueueSetContainer, &pxQueue, queueSEND_TO_BACK);
+ if (cTxLock == queueUNLOCKED) {
+ if (listLIST_IS_EMPTY(&(pxQueueSetContainer->xTasksWaitingToReceive)) == pdFALSE) {
+ if (xTaskRemoveFromEventList(&(pxQueueSetContainer->xTasksWaitingToReceive)) != pdFALSE) {
+ /* The task waiting has a higher priority. */
+ xReturn = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ pxQueueSetContainer->cTxLock = (int8_t)(cTxLock + 1);
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ return xReturn;
+}
+#endif /* configUSE_QUEUE_SETS */
diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/tasks.c b/source/Middlewares/Third_Party/FreeRTOS/Source/tasks.c
index f93fca03..739f2012 100644
--- a/source/Middlewares/Third_Party/FreeRTOS/Source/tasks.c
+++ b/source/Middlewares/Third_Party/FreeRTOS/Source/tasks.c
@@ -36,9 +36,9 @@ task.h is included from an application file. */
/* FreeRTOS includes. */
#include "FreeRTOS.h"
+#include "stack_macros.h"
#include "task.h"
#include "timers.h"
-#include "stack_macros.h"
/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified
because the MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined
@@ -48,146 +48,143 @@ correct privileged Vs unprivileged linkage and placement. */
/* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting
functions but without including stdio.h here. */
-#if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 )
- /* At the bottom of this file are two optional functions that can be used
- to generate human readable text from the raw data generated by the
- uxTaskGetSystemState() function. Note the formatting functions are provided
- for convenience only, and are NOT considered part of the kernel. */
- #include <stdio.h>
+#if (configUSE_STATS_FORMATTING_FUNCTIONS == 1)
+/* At the bottom of this file are two optional functions that can be used
+to generate human readable text from the raw data generated by the
+uxTaskGetSystemState() function. Note the formatting functions are provided
+for convenience only, and are NOT considered part of the kernel. */
+#include <stdio.h>
#endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */
-#if( configUSE_PREEMPTION == 0 )
- /* If the cooperative scheduler is being used then a yield should not be
- performed just because a higher priority task has been woken. */
- #define taskYIELD_IF_USING_PREEMPTION()
+#if (configUSE_PREEMPTION == 0)
+/* If the cooperative scheduler is being used then a yield should not be
+performed just because a higher priority task has been woken. */
+#define taskYIELD_IF_USING_PREEMPTION()
#else
- #define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API()
+#define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API()
#endif
/* Values that can be assigned to the ucNotifyState member of the TCB. */
-#define taskNOT_WAITING_NOTIFICATION ( ( uint8_t ) 0 )
-#define taskWAITING_NOTIFICATION ( ( uint8_t ) 1 )
-#define taskNOTIFICATION_RECEIVED ( ( uint8_t ) 2 )
+#define taskNOT_WAITING_NOTIFICATION ((uint8_t)0)
+#define taskWAITING_NOTIFICATION ((uint8_t)1)
+#define taskNOTIFICATION_RECEIVED ((uint8_t)2)
/*
* The value used to fill the stack of a task when the task is created. This
* is used purely for checking the high water mark for tasks.
*/
-#define tskSTACK_FILL_BYTE ( 0xa5U )
+#define tskSTACK_FILL_BYTE (0xa5U)
/* Bits used to recored how a task's stack and TCB were allocated. */
-#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 0 )
-#define tskSTATICALLY_ALLOCATED_STACK_ONLY ( ( uint8_t ) 1 )
-#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ( ( uint8_t ) 2 )
+#define tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB ((uint8_t)0)
+#define tskSTATICALLY_ALLOCATED_STACK_ONLY ((uint8_t)1)
+#define tskSTATICALLY_ALLOCATED_STACK_AND_TCB ((uint8_t)2)
/* If any of the following are set then task stacks are filled with a known
value so the high water mark can be determined. If none of the following are
set then don't fill the stack so there is no unnecessary dependency on memset. */
-#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) )
- #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1
+#if ((configCHECK_FOR_STACK_OVERFLOW > 1) || (configUSE_TRACE_FACILITY == 1) || (INCLUDE_uxTaskGetStackHighWaterMark == 1) || (INCLUDE_uxTaskGetStackHighWaterMark2 == 1))
+#define tskSET_NEW_STACKS_TO_KNOWN_VALUE 1
#else
- #define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0
+#define tskSET_NEW_STACKS_TO_KNOWN_VALUE 0
#endif
/*
* Macros used by vListTask to indicate which state a task is in.
*/
-#define tskRUNNING_CHAR ( 'X' )
-#define tskBLOCKED_CHAR ( 'B' )
-#define tskREADY_CHAR ( 'R' )
-#define tskDELETED_CHAR ( 'D' )
-#define tskSUSPENDED_CHAR ( 'S' )
+#define tskRUNNING_CHAR ('X')
+#define tskBLOCKED_CHAR ('B')
+#define tskREADY_CHAR ('R')
+#define tskDELETED_CHAR ('D')
+#define tskSUSPENDED_CHAR ('S')
/*
* Some kernel aware debuggers require the data the debugger needs access to be
* global, rather than file scope.
*/
#ifdef portREMOVE_STATIC_QUALIFIER
- #define static
+#define static
#endif
/* The name allocated to the Idle task. This can be overridden by defining
configIDLE_TASK_NAME in FreeRTOSConfig.h. */
#ifndef configIDLE_TASK_NAME
- #define configIDLE_TASK_NAME "IDLE"
+#define configIDLE_TASK_NAME "IDLE"
#endif
-#if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 )
-
- /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is
- performed in a generic way that is not optimised to any particular
- microcontroller architecture. */
-
- /* uxTopReadyPriority holds the priority of the highest priority ready
- state task. */
- #define taskRECORD_READY_PRIORITY( uxPriority ) \
- { \
- if( ( uxPriority ) > uxTopReadyPriority ) \
- { \
- uxTopReadyPriority = ( uxPriority ); \
- } \
- } /* taskRECORD_READY_PRIORITY */
-
- /*-----------------------------------------------------------*/
-
- #define taskSELECT_HIGHEST_PRIORITY_TASK() \
- { \
- UBaseType_t uxTopPriority = uxTopReadyPriority; \
- \
- /* Find the highest priority queue that contains ready tasks. */ \
- while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopPriority ] ) ) ) \
- { \
- configASSERT( uxTopPriority ); \
- --uxTopPriority; \
- } \
- \
- /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \
- the same priority get an equal share of the processor time. */ \
- listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \
- uxTopReadyPriority = uxTopPriority; \
- } /* taskSELECT_HIGHEST_PRIORITY_TASK */
-
- /*-----------------------------------------------------------*/
-
- /* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as
- they are only required when a port optimised method of task selection is
- being used. */
- #define taskRESET_READY_PRIORITY( uxPriority )
- #define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority )
+#if (configUSE_PORT_OPTIMISED_TASK_SELECTION == 0)
+
+/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is
+performed in a generic way that is not optimised to any particular
+microcontroller architecture. */
+
+/* uxTopReadyPriority holds the priority of the highest priority ready
+state task. */
+#define taskRECORD_READY_PRIORITY(uxPriority) \
+ { \
+ if ((uxPriority) > uxTopReadyPriority) { \
+ uxTopReadyPriority = (uxPriority); \
+ } \
+ } /* taskRECORD_READY_PRIORITY */
+
+/*-----------------------------------------------------------*/
+
+#define taskSELECT_HIGHEST_PRIORITY_TASK() \
+ { \
+ UBaseType_t uxTopPriority = uxTopReadyPriority; \
+ \
+ /* Find the highest priority queue that contains ready tasks. */ \
+ while (listLIST_IS_EMPTY(&(pxReadyTasksLists[uxTopPriority]))) { \
+ configASSERT(uxTopPriority); \
+ --uxTopPriority; \
+ } \
+ \
+ /* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of \
+ the same priority get an equal share of the processor time. */ \
+ listGET_OWNER_OF_NEXT_ENTRY(pxCurrentTCB, &(pxReadyTasksLists[uxTopPriority])); \
+ uxTopReadyPriority = uxTopPriority; \
+ } /* taskSELECT_HIGHEST_PRIORITY_TASK */
+
+/*-----------------------------------------------------------*/
+
+/* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as
+they are only required when a port optimised method of task selection is
+being used. */
+#define taskRESET_READY_PRIORITY(uxPriority)
+#define portRESET_READY_PRIORITY(uxPriority, uxTopReadyPriority)
#else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
- /* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is
- performed in a way that is tailored to the particular microcontroller
- architecture being used. */
-
- /* A port optimised version is provided. Call the port defined macros. */
- #define taskRECORD_READY_PRIORITY( uxPriority ) portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority )
-
- /*-----------------------------------------------------------*/
-
- #define taskSELECT_HIGHEST_PRIORITY_TASK() \
- { \
- UBaseType_t uxTopPriority; \
- \
- /* Find the highest priority list that contains ready tasks. */ \
- portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority ); \
- configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 ); \
- listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) ); \
- } /* taskSELECT_HIGHEST_PRIORITY_TASK() */
-
- /*-----------------------------------------------------------*/
-
- /* A port optimised version is provided, call it only if the TCB being reset
- is being referenced from a ready list. If it is referenced from a delayed
- or suspended list then it won't be in a ready list. */
- #define taskRESET_READY_PRIORITY( uxPriority ) \
- { \
- if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 ) \
- { \
- portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) ); \
- } \
- }
+/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is
+performed in a way that is tailored to the particular microcontroller
+architecture being used. */
+
+/* A port optimised version is provided. Call the port defined macros. */
+#define taskRECORD_READY_PRIORITY(uxPriority) portRECORD_READY_PRIORITY(uxPriority, uxTopReadyPriority)
+
+/*-----------------------------------------------------------*/
+
+#define taskSELECT_HIGHEST_PRIORITY_TASK() \
+ { \
+ UBaseType_t uxTopPriority; \
+ \
+ /* Find the highest priority list that contains ready tasks. */ \
+ portGET_HIGHEST_PRIORITY(uxTopPriority, uxTopReadyPriority); \
+ configASSERT(listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[uxTopPriority])) > 0); \
+ listGET_OWNER_OF_NEXT_ENTRY(pxCurrentTCB, &(pxReadyTasksLists[uxTopPriority])); \
+ } /* taskSELECT_HIGHEST_PRIORITY_TASK() */
+
+/*-----------------------------------------------------------*/
+
+/* A port optimised version is provided, call it only if the TCB being reset
+is being referenced from a ready list. If it is referenced from a delayed
+or suspended list then it won't be in a ready list. */
+#define taskRESET_READY_PRIORITY(uxPriority) \
+ { \
+ if (listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[(uxPriority)])) == (UBaseType_t)0) { \
+ portRESET_READY_PRIORITY((uxPriority), (uxTopReadyPriority)); \
+ } \
+ }
#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
@@ -195,19 +192,19 @@ configIDLE_TASK_NAME in FreeRTOSConfig.h. */
/* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick
count overflows. */
-#define taskSWITCH_DELAYED_LISTS() \
-{ \
- List_t *pxTemp; \
- \
- /* The delayed tasks list should be empty when the lists are switched. */ \
- configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) ); \
- \
- pxTemp = pxDelayedTaskList; \
- pxDelayedTaskList = pxOverflowDelayedTaskList; \
- pxOverflowDelayedTaskList = pxTemp; \
- xNumOfOverflows++; \
- prvResetNextTaskUnblockTime(); \
-}
+#define taskSWITCH_DELAYED_LISTS() \
+ { \
+ List_t *pxTemp; \
+ \
+ /* The delayed tasks list should be empty when the lists are switched. */ \
+ configASSERT((listLIST_IS_EMPTY(pxDelayedTaskList))); \
+ \
+ pxTemp = pxDelayedTaskList; \
+ pxDelayedTaskList = pxOverflowDelayedTaskList; \
+ pxOverflowDelayedTaskList = pxTemp; \
+ xNumOfOverflows++; \
+ prvResetNextTaskUnblockTime(); \
+ }
/*-----------------------------------------------------------*/
@@ -215,11 +212,11 @@ count overflows. */
* Place the task represented by pxTCB into the appropriate ready list for
* the task. It is inserted at the end of the list.
*/
-#define prvAddTaskToReadyList( pxTCB ) \
- traceMOVED_TASK_TO_READY_STATE( pxTCB ); \
- taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority ); \
- vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xStateListItem ) ); \
- tracePOST_MOVED_TASK_TO_READY_STATE( pxTCB )
+#define prvAddTaskToReadyList(pxTCB) \
+ traceMOVED_TASK_TO_READY_STATE(pxTCB); \
+ taskRECORD_READY_PRIORITY((pxTCB)->uxPriority); \
+ vListInsertEnd(&(pxReadyTasksLists[(pxTCB)->uxPriority]), &((pxTCB)->xStateListItem)); \
+ tracePOST_MOVED_TASK_TO_READY_STATE(pxTCB)
/*-----------------------------------------------------------*/
/*
@@ -228,7 +225,7 @@ count overflows. */
* task should be used in place of the parameter. This macro simply checks to
* see if the parameter is NULL and returns a pointer to the appropriate TCB.
*/
-#define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? pxCurrentTCB : ( pxHandle ) )
+#define prvGetTCBFromHandle(pxHandle) (((pxHandle) == NULL) ? pxCurrentTCB : (pxHandle))
/* The item value of the event list item is normally used to hold the priority
of the task to which it belongs (coded to allow it to be held in reverse
@@ -238,10 +235,10 @@ being used for another purpose. The following bit definition is used to inform
the scheduler that the value should not be changed - in which case it is the
responsibility of whichever module is using the value to ensure it gets set back
to its original value when it is released. */
-#if( configUSE_16_BIT_TICKS == 1 )
- #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U
+#if (configUSE_16_BIT_TICKS == 1)
+#define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x8000U
#else
- #define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL
+#define taskEVENT_LIST_ITEM_VALUE_IN_USE 0x80000000UL
#endif
/*
@@ -249,82 +246,83 @@ to its original value when it is released. */
* and stores task state information, including a pointer to the task's context
* (the task's run time environment, including register values)
*/
-typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */
+typedef struct tskTaskControlBlock /* The old naming convention is used to prevent breaking kernel aware debuggers. */
{
- volatile StackType_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */
-
- #if ( portUSING_MPU_WRAPPERS == 1 )
- xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */
- #endif
-
- ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */
- ListItem_t xEventListItem; /*< Used to reference a task from an event list. */
- UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */
- StackType_t *pxStack; /*< Points to the start of the stack. */
- char pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
-
- #if ( ( portSTACK_GROWTH > 0 ) || ( configRECORD_STACK_HIGH_ADDRESS == 1 ) )
- StackType_t *pxEndOfStack; /*< Points to the highest valid address for the stack. */
- #endif
-
- #if ( portCRITICAL_NESTING_IN_TCB == 1 )
- UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */
- #endif
-
- #if ( configUSE_TRACE_FACILITY == 1 )
- UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */
- UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */
- #endif
-
- #if ( configUSE_MUTEXES == 1 )
- UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */
- UBaseType_t uxMutexesHeld;
- #endif
-
- #if ( configUSE_APPLICATION_TASK_TAG == 1 )
- TaskHookFunction_t pxTaskTag;
- #endif
-
- #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 )
- void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ];
- #endif
-
- #if( configGENERATE_RUN_TIME_STATS == 1 )
- uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */
- #endif
-
- #if ( configUSE_NEWLIB_REENTRANT == 1 )
- /* Allocate a Newlib reent structure that is specific to this task.
- Note Newlib support has been included by popular demand, but is not
- used by the FreeRTOS maintainers themselves. FreeRTOS is not
- responsible for resulting newlib operation. User must be familiar with
- newlib and must provide system-wide implementations of the necessary
- stubs. Be warned that (at the time of writing) the current newlib design
- implements a system-wide malloc() that must be provided with locks.
-
- See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
- for additional information. */
- struct _reent xNewLib_reent;
- #endif
-
- #if( configUSE_TASK_NOTIFICATIONS == 1 )
- volatile uint32_t ulNotifiedValue;
- volatile uint8_t ucNotifyState;
- #endif
-
- /* See the comments in FreeRTOS.h with the definition of
- tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */
- #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
- uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */
- #endif
-
- #if( INCLUDE_xTaskAbortDelay == 1 )
- uint8_t ucDelayAborted;
- #endif
-
- #if( configUSE_POSIX_ERRNO == 1 )
- int iTaskErrno;
- #endif
+ volatile StackType_t *pxTopOfStack; /*< Points to the location of the last item placed on the tasks stack. THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */
+
+#if (portUSING_MPU_WRAPPERS == 1)
+ xMPU_SETTINGS xMPUSettings; /*< The MPU settings are defined as part of the port layer. THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */
+#endif
+
+ ListItem_t xStateListItem; /*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */
+ ListItem_t xEventListItem; /*< Used to reference a task from an event list. */
+ UBaseType_t uxPriority; /*< The priority of the task. 0 is the lowest priority. */
+ StackType_t *pxStack; /*< Points to the start of the stack. */
+ char pcTaskName[configMAX_TASK_NAME_LEN];
+ /*< Descriptive name given to the task when created. Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+#if ((portSTACK_GROWTH > 0) || (configRECORD_STACK_HIGH_ADDRESS == 1))
+ StackType_t *pxEndOfStack; /*< Points to the highest valid address for the stack. */
+#endif
+
+#if (portCRITICAL_NESTING_IN_TCB == 1)
+ UBaseType_t uxCriticalNesting; /*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */
+#endif
+
+#if (configUSE_TRACE_FACILITY == 1)
+ UBaseType_t uxTCBNumber; /*< Stores a number that increments each time a TCB is created. It allows debuggers to determine when a task has been deleted and then recreated. */
+ UBaseType_t uxTaskNumber; /*< Stores a number specifically for use by third party trace code. */
+#endif
+
+#if (configUSE_MUTEXES == 1)
+ UBaseType_t uxBasePriority; /*< The priority last assigned to the task - used by the priority inheritance mechanism. */
+ UBaseType_t uxMutexesHeld;
+#endif
+
+#if (configUSE_APPLICATION_TASK_TAG == 1)
+ TaskHookFunction_t pxTaskTag;
+#endif
+
+#if (configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0)
+ void *pvThreadLocalStoragePointers[configNUM_THREAD_LOCAL_STORAGE_POINTERS];
+#endif
+
+#if (configGENERATE_RUN_TIME_STATS == 1)
+ uint32_t ulRunTimeCounter; /*< Stores the amount of time the task has spent in the Running state. */
+#endif
+
+#if (configUSE_NEWLIB_REENTRANT == 1)
+ /* Allocate a Newlib reent structure that is specific to this task.
+ Note Newlib support has been included by popular demand, but is not
+ used by the FreeRTOS maintainers themselves. FreeRTOS is not
+ responsible for resulting newlib operation. User must be familiar with
+ newlib and must provide system-wide implementations of the necessary
+ stubs. Be warned that (at the time of writing) the current newlib design
+ implements a system-wide malloc() that must be provided with locks.
+
+ See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
+ for additional information. */
+ struct _reent xNewLib_reent;
+#endif
+
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+ volatile uint32_t ulNotifiedValue;
+ volatile uint8_t ucNotifyState;
+#endif
+
+/* See the comments in FreeRTOS.h with the definition of
+tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE. */
+#if (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
+ uint8_t ucStaticallyAllocated; /*< Set to pdTRUE if the task is a statically allocated to ensure no attempt is made to free the memory. */
+#endif
+
+#if (INCLUDE_xTaskAbortDelay == 1)
+ uint8_t ucDelayAborted;
+#endif
+
+#if (configUSE_POSIX_ERRNO == 1)
+ int iTaskErrno;
+#endif
} tskTCB;
@@ -334,49 +332,49 @@ typedef tskTCB TCB_t;
/*lint -save -e956 A manual analysis and inspection has been used to determine
which static variables must be declared volatile. */
-PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL;
+PRIVILEGED_DATA TCB_t *volatile pxCurrentTCB = NULL;
/* Lists for ready and blocked tasks. --------------------
xDelayedTaskList1 and xDelayedTaskList2 could be move to function scople but
doing so breaks some kernel aware debuggers and debuggers that rely on removing
the static qualifier. */
-PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ];/*< Prioritised ready tasks. */
-PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */
-PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */
-PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */
-PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */
-PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */
+PRIVILEGED_DATA static List_t pxReadyTasksLists[configMAX_PRIORITIES]; /*< Prioritised ready tasks. */
+PRIVILEGED_DATA static List_t xDelayedTaskList1; /*< Delayed tasks. */
+PRIVILEGED_DATA static List_t xDelayedTaskList2; /*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */
+PRIVILEGED_DATA static List_t *volatile pxDelayedTaskList; /*< Points to the delayed task list currently being used. */
+PRIVILEGED_DATA static List_t *volatile pxOverflowDelayedTaskList; /*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */
+PRIVILEGED_DATA static List_t xPendingReadyList; /*< Tasks that have been readied while the scheduler was suspended. They will be moved to the ready list when the scheduler is resumed. */
-#if( INCLUDE_vTaskDelete == 1 )
+#if (INCLUDE_vTaskDelete == 1)
- PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */
- PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = ( UBaseType_t ) 0U;
+PRIVILEGED_DATA static List_t xTasksWaitingTermination; /*< Tasks that have been deleted - but their memory not yet freed. */
+PRIVILEGED_DATA static volatile UBaseType_t uxDeletedTasksWaitingCleanUp = (UBaseType_t)0U;
#endif
-#if ( INCLUDE_vTaskSuspend == 1 )
+#if (INCLUDE_vTaskSuspend == 1)
- PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */
+PRIVILEGED_DATA static List_t xSuspendedTaskList; /*< Tasks that are currently suspended. */
#endif
/* Global POSIX errno. Its value is changed upon context switching to match
the errno of the currently running task. */
-#if ( configUSE_POSIX_ERRNO == 1 )
- int FreeRTOS_errno = 0;
+#if (configUSE_POSIX_ERRNO == 1)
+int FreeRTOS_errno = 0;
#endif
/* Other file private variables. --------------------------------*/
-PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = ( UBaseType_t ) 0U;
-PRIVILEGED_DATA static volatile TickType_t xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT;
-PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY;
-PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE;
-PRIVILEGED_DATA static volatile TickType_t xPendedTicks = ( TickType_t ) 0U;
-PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE;
-PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = ( BaseType_t ) 0;
-PRIVILEGED_DATA static UBaseType_t uxTaskNumber = ( UBaseType_t ) 0U;
-PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = ( TickType_t ) 0U; /* Initialised to portMAX_DELAY before the scheduler starts. */
-PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */
+PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks = (UBaseType_t)0U;
+PRIVILEGED_DATA static volatile TickType_t xTickCount = (TickType_t)configINITIAL_TICK_COUNT;
+PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority = tskIDLE_PRIORITY;
+PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning = pdFALSE;
+PRIVILEGED_DATA static volatile TickType_t xPendedTicks = (TickType_t)0U;
+PRIVILEGED_DATA static volatile BaseType_t xYieldPending = pdFALSE;
+PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows = (BaseType_t)0;
+PRIVILEGED_DATA static UBaseType_t uxTaskNumber = (UBaseType_t)0U;
+PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime = (TickType_t)0U; /* Initialised to portMAX_DELAY before the scheduler starts. */
+PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL; /*< Holds the handle of the idle task. The idle task is created automatically when the scheduler is started. */
/* Context switches are held pending while the scheduler is suspended. Also,
interrupts must not manipulate the xStateListItem of a TCB, or any of the
@@ -386,14 +384,14 @@ moves the task's event list item into the xPendingReadyList, ready for the
kernel to move the task from the pending ready list into the real ready list
when the scheduler is unsuspended. The pending ready list itself can only be
accessed from a critical section. */
-PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t ) pdFALSE;
+PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = (UBaseType_t)pdFALSE;
-#if ( configGENERATE_RUN_TIME_STATS == 1 )
+#if (configGENERATE_RUN_TIME_STATS == 1)
- /* Do not move these variables to function scope as doing so prevents the
- code working with debuggers that need to remove the static qualifier. */
- PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */
- PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */
+/* Do not move these variables to function scope as doing so prevents the
+code working with debuggers that need to remove the static qualifier. */
+PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL; /*< Holds the value of a timer/counter the last time a task was switched in. */
+PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL; /*< Holds the total amount of execution time as defined by the run time counter clock. */
#endif
@@ -402,21 +400,22 @@ PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t
/*-----------------------------------------------------------*/
/* Callback function prototypes. --------------------------*/
-#if( configCHECK_FOR_STACK_OVERFLOW > 0 )
+#if (configCHECK_FOR_STACK_OVERFLOW > 0)
- extern void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName );
+extern void vApplicationStackOverflowHook(TaskHandle_t xTask, char *pcTaskName);
#endif
-#if( configUSE_TICK_HOOK > 0 )
+#if (configUSE_TICK_HOOK > 0)
- extern void vApplicationTickHook( void ); /*lint !e526 Symbol not defined as it is an application callback. */
+extern void vApplicationTickHook(void); /*lint !e526 Symbol not defined as it is an application callback. */
#endif
-#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
- extern void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer, uint32_t *pulIdleTaskStackSize ); /*lint !e526 Symbol not defined as it is an application callback. */
+extern void vApplicationGetIdleTaskMemory(StaticTask_t **ppxIdleTaskTCBBuffer, StackType_t **ppxIdleTaskStackBuffer,
+ uint32_t *pulIdleTaskStackSize); /*lint !e526 Symbol not defined as it is an application callback. */
#endif
@@ -427,9 +426,9 @@ PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t
* currently in the Suspended state, or pdFALSE if the task referenced by xTask
* is in any other state.
*/
-#if ( INCLUDE_vTaskSuspend == 1 )
+#if (INCLUDE_vTaskSuspend == 1)
- static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+static BaseType_t prvTaskIsTaskSuspended(const TaskHandle_t xTask) PRIVILEGED_FUNCTION;
#endif /* INCLUDE_vTaskSuspend */
@@ -437,7 +436,7 @@ PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended = ( UBaseType_t
* Utility to ready all the lists used by the scheduler. This is called
* automatically upon the creation of the first task.
*/
-static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION;
+static void prvInitialiseTaskLists(void) PRIVILEGED_FUNCTION;
/*
* The idle task, which as all tasks is implemented as a never ending loop.
@@ -450,7 +449,7 @@ static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION;
* void prvIdleTask( void *pvParameters );
*
*/
-static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters );
+static portTASK_FUNCTION_PROTO(prvIdleTask, pvParameters);
/*
* Utility to free all memory allocated by the scheduler to hold a TCB,
@@ -459,9 +458,9 @@ static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters );
* This does not free memory allocated by the task itself (i.e. memory
* allocated by calls to pvPortMalloc from within the tasks application code).
*/
-#if ( INCLUDE_vTaskDelete == 1 )
+#if (INCLUDE_vTaskDelete == 1)
- static void prvDeleteTCB( TCB_t *pxTCB ) PRIVILEGED_FUNCTION;
+static void prvDeleteTCB(TCB_t *pxTCB) PRIVILEGED_FUNCTION;
#endif
@@ -470,13 +469,13 @@ static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters );
* in the list of tasks waiting to be deleted. If so the task is cleaned up
* and its TCB deleted.
*/
-static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION;
+static void prvCheckTasksWaitingTermination(void) PRIVILEGED_FUNCTION;
/*
* The currently executing task is entering the Blocked state. Add the task to
* either the current or the overflow delayed task list.
*/
-static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseType_t xCanBlockIndefinitely ) PRIVILEGED_FUNCTION;
+static void prvAddCurrentTaskToDelayedList(TickType_t xTicksToWait, const BaseType_t xCanBlockIndefinitely) PRIVILEGED_FUNCTION;
/*
* Fills an TaskStatus_t structure with information on each task that is
@@ -486,9 +485,9 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT
* THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM
* NORMAL APPLICATION CODE.
*/
-#if ( configUSE_TRACE_FACILITY == 1 )
+#if (configUSE_TRACE_FACILITY == 1)
- static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) PRIVILEGED_FUNCTION;
+static UBaseType_t prvListTasksWithinSingleList(TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState) PRIVILEGED_FUNCTION;
#endif
@@ -496,9 +495,9 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT
* Searches pxList for a task with name pcNameToQuery - returning a handle to
* the task if it is found, or NULL if the task is not found.
*/
-#if ( INCLUDE_xTaskGetHandle == 1 )
+#if (INCLUDE_xTaskGetHandle == 1)
- static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] ) PRIVILEGED_FUNCTION;
+static TCB_t *prvSearchForNameWithinSingleList(List_t *pxList, const char pcNameToQuery[]) PRIVILEGED_FUNCTION;
#endif
@@ -507,9 +506,9 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT
* This function determines the 'high water mark' of the task stack by
* determining how much of the stack remains at the original preset value.
*/
-#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) )
+#if ((configUSE_TRACE_FACILITY == 1) || (INCLUDE_uxTaskGetStackHighWaterMark == 1) || (INCLUDE_uxTaskGetStackHighWaterMark2 == 1))
- static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION;
+static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace(const uint8_t *pucStackByte) PRIVILEGED_FUNCTION;
#endif
@@ -522,9 +521,9 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT
* defined low power mode implementations require configUSE_TICKLESS_IDLE to be
* set to a value other than 1.
*/
-#if ( configUSE_TICKLESS_IDLE != 0 )
+#if (configUSE_TICKLESS_IDLE != 0)
- static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION;
+static TickType_t prvGetExpectedIdleTime(void) PRIVILEGED_FUNCTION;
#endif
@@ -532,15 +531,15 @@ static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseT
* Set xNextTaskUnblockTime to the time at which the next Blocked state task
* will exit the Blocked state.
*/
-static void prvResetNextTaskUnblockTime( void );
+static void prvResetNextTaskUnblockTime(void);
-#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) )
+#if ((configUSE_TRACE_FACILITY == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS > 0))
- /*
- * Helper function used to pad task names with spaces when printing out
- * human readable tables of task information.
- */
- static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName ) PRIVILEGED_FUNCTION;
+/*
+ * Helper function used to pad task names with spaces when printing out
+ * human readable tables of task information.
+ */
+static char *prvWriteNameToBuffer(char *pcBuffer, const char *pcTaskName) PRIVILEGED_FUNCTION;
#endif
@@ -548,20 +547,15 @@ static void prvResetNextTaskUnblockTime( void );
* Called after a Task_t structure has been allocated either statically or
* dynamically to fill in the structure's members.
*/
-static void prvInitialiseNewTask( TaskFunction_t pxTaskCode,
- const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- const uint32_t ulStackDepth,
- void * const pvParameters,
- UBaseType_t uxPriority,
- TaskHandle_t * const pxCreatedTask,
- TCB_t *pxNewTCB,
- const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION;
+static void prvInitialiseNewTask(TaskFunction_t pxTaskCode, const char *const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pxCreatedTask, TCB_t *pxNewTCB,
+ const MemoryRegion_t *const xRegions) PRIVILEGED_FUNCTION;
/*
* Called after a new task has been created and initialised to place the task
* under the control of the scheduler.
*/
-static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) PRIVILEGED_FUNCTION;
+static void prvAddNewTaskToReadyList(TCB_t *pxNewTCB) PRIVILEGED_FUNCTION;
/*
* freertos_tasks_c_additions_init() should only be called if the user definable
@@ -570,2019 +564,1692 @@ static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB ) PRIVILEGED_FUNCTION;
*/
#ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
- static void freertos_tasks_c_additions_init( void ) PRIVILEGED_FUNCTION;
+static void freertos_tasks_c_additions_init(void) PRIVILEGED_FUNCTION;
#endif
/*-----------------------------------------------------------*/
-#if( configSUPPORT_STATIC_ALLOCATION == 1 )
-
- TaskHandle_t xTaskCreateStatic( TaskFunction_t pxTaskCode,
- const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- const uint32_t ulStackDepth,
- void * const pvParameters,
- UBaseType_t uxPriority,
- StackType_t * const puxStackBuffer,
- StaticTask_t * const pxTaskBuffer )
- {
- TCB_t *pxNewTCB;
- TaskHandle_t xReturn;
-
- configASSERT( puxStackBuffer != NULL );
- configASSERT( pxTaskBuffer != NULL );
-
- #if( configASSERT_DEFINED == 1 )
- {
- /* Sanity check that the size of the structure used to declare a
- variable of type StaticTask_t equals the size of the real task
- structure. */
- volatile size_t xSize = sizeof( StaticTask_t );
- configASSERT( xSize == sizeof( TCB_t ) );
- ( void ) xSize; /* Prevent lint warning when configASSERT() is not used. */
- }
- #endif /* configASSERT_DEFINED */
-
-
- if( ( pxTaskBuffer != NULL ) && ( puxStackBuffer != NULL ) )
- {
- /* The memory used for the task's TCB and stack are passed into this
- function - use them. */
- pxNewTCB = ( TCB_t * ) pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */
- pxNewTCB->pxStack = ( StackType_t * ) puxStackBuffer;
-
- #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
- {
- /* Tasks can be created statically or dynamically, so note this
- task was created statically in case the task is later deleted. */
- pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB;
- }
- #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
-
- prvInitialiseNewTask( pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL );
- prvAddNewTaskToReadyList( pxNewTCB );
- }
- else
- {
- xReturn = NULL;
- }
-
- return xReturn;
- }
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
+
+TaskHandle_t xTaskCreateStatic(TaskFunction_t pxTaskCode, const char *const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, StackType_t *const puxStackBuffer, StaticTask_t *const pxTaskBuffer) {
+ TCB_t * pxNewTCB;
+ TaskHandle_t xReturn;
+
+ configASSERT(puxStackBuffer != NULL);
+ configASSERT(pxTaskBuffer != NULL);
+
+#if (configASSERT_DEFINED == 1)
+ {
+ /* Sanity check that the size of the structure used to declare a
+ variable of type StaticTask_t equals the size of the real task
+ structure. */
+ volatile size_t xSize = sizeof(StaticTask_t);
+ configASSERT(xSize == sizeof(TCB_t));
+ (void)xSize; /* Prevent lint warning when configASSERT() is not used. */
+ }
+#endif /* configASSERT_DEFINED */
+
+ if ((pxTaskBuffer != NULL) && (puxStackBuffer != NULL)) {
+ /* The memory used for the task's TCB and stack are passed into this
+ function - use them. */
+ pxNewTCB = (TCB_t *)pxTaskBuffer; /*lint !e740 !e9087 Unusual cast is ok as the structures are designed to have the same alignment, and the size is checked by an assert. */
+ pxNewTCB->pxStack = (StackType_t *)puxStackBuffer;
+
+#if (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
+ {
+ /* Tasks can be created statically or dynamically, so note this
+ task was created statically in case the task is later deleted. */
+ pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB;
+ }
+#endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
+
+ prvInitialiseNewTask(pxTaskCode, pcName, ulStackDepth, pvParameters, uxPriority, &xReturn, pxNewTCB, NULL);
+ prvAddNewTaskToReadyList(pxNewTCB);
+ } else {
+ xReturn = NULL;
+ }
+
+ return xReturn;
+}
#endif /* SUPPORT_STATIC_ALLOCATION */
/*-----------------------------------------------------------*/
-#if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) )
-
- BaseType_t xTaskCreateRestrictedStatic( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask )
- {
- TCB_t *pxNewTCB;
- BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
-
- configASSERT( pxTaskDefinition->puxStackBuffer != NULL );
- configASSERT( pxTaskDefinition->pxTaskBuffer != NULL );
-
- if( ( pxTaskDefinition->puxStackBuffer != NULL ) && ( pxTaskDefinition->pxTaskBuffer != NULL ) )
- {
- /* Allocate space for the TCB. Where the memory comes from depends
- on the implementation of the port malloc function and whether or
- not static allocation is being used. */
- pxNewTCB = ( TCB_t * ) pxTaskDefinition->pxTaskBuffer;
-
- /* Store the stack location in the TCB. */
- pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer;
-
- #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 )
- {
- /* Tasks can be created statically or dynamically, so note this
- task was created statically in case the task is later deleted. */
- pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB;
- }
- #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
-
- prvInitialiseNewTask( pxTaskDefinition->pvTaskCode,
- pxTaskDefinition->pcName,
- ( uint32_t ) pxTaskDefinition->usStackDepth,
- pxTaskDefinition->pvParameters,
- pxTaskDefinition->uxPriority,
- pxCreatedTask, pxNewTCB,
- pxTaskDefinition->xRegions );
-
- prvAddNewTaskToReadyList( pxNewTCB );
- xReturn = pdPASS;
- }
-
- return xReturn;
- }
+#if ((portUSING_MPU_WRAPPERS == 1) && (configSUPPORT_STATIC_ALLOCATION == 1))
+
+BaseType_t xTaskCreateRestrictedStatic(const TaskParameters_t *const pxTaskDefinition, TaskHandle_t *pxCreatedTask) {
+ TCB_t * pxNewTCB;
+ BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
+
+ configASSERT(pxTaskDefinition->puxStackBuffer != NULL);
+ configASSERT(pxTaskDefinition->pxTaskBuffer != NULL);
+
+ if ((pxTaskDefinition->puxStackBuffer != NULL) && (pxTaskDefinition->pxTaskBuffer != NULL)) {
+ /* Allocate space for the TCB. Where the memory comes from depends
+ on the implementation of the port malloc function and whether or
+ not static allocation is being used. */
+ pxNewTCB = (TCB_t *)pxTaskDefinition->pxTaskBuffer;
+
+ /* Store the stack location in the TCB. */
+ pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer;
+
+#if (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0)
+ {
+ /* Tasks can be created statically or dynamically, so note this
+ task was created statically in case the task is later deleted. */
+ pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_AND_TCB;
+ }
+#endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
+
+ prvInitialiseNewTask(pxTaskDefinition->pvTaskCode, pxTaskDefinition->pcName, (uint32_t)pxTaskDefinition->usStackDepth, pxTaskDefinition->pvParameters, pxTaskDefinition->uxPriority, pxCreatedTask,
+ pxNewTCB, pxTaskDefinition->xRegions);
+
+ prvAddNewTaskToReadyList(pxNewTCB);
+ xReturn = pdPASS;
+ }
+
+ return xReturn;
+}
#endif /* ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) */
/*-----------------------------------------------------------*/
-#if( ( portUSING_MPU_WRAPPERS == 1 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
-
- BaseType_t xTaskCreateRestricted( const TaskParameters_t * const pxTaskDefinition, TaskHandle_t *pxCreatedTask )
- {
- TCB_t *pxNewTCB;
- BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
-
- configASSERT( pxTaskDefinition->puxStackBuffer );
-
- if( pxTaskDefinition->puxStackBuffer != NULL )
- {
- /* Allocate space for the TCB. Where the memory comes from depends
- on the implementation of the port malloc function and whether or
- not static allocation is being used. */
- pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) );
-
- if( pxNewTCB != NULL )
- {
- /* Store the stack location in the TCB. */
- pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer;
-
- #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 )
- {
- /* Tasks can be created statically or dynamically, so note
- this task had a statically allocated stack in case it is
- later deleted. The TCB was allocated dynamically. */
- pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY;
- }
- #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
-
- prvInitialiseNewTask( pxTaskDefinition->pvTaskCode,
- pxTaskDefinition->pcName,
- ( uint32_t ) pxTaskDefinition->usStackDepth,
- pxTaskDefinition->pvParameters,
- pxTaskDefinition->uxPriority,
- pxCreatedTask, pxNewTCB,
- pxTaskDefinition->xRegions );
-
- prvAddNewTaskToReadyList( pxNewTCB );
- xReturn = pdPASS;
- }
- }
-
- return xReturn;
- }
+#if ((portUSING_MPU_WRAPPERS == 1) && (configSUPPORT_DYNAMIC_ALLOCATION == 1))
+
+BaseType_t xTaskCreateRestricted(const TaskParameters_t *const pxTaskDefinition, TaskHandle_t *pxCreatedTask) {
+ TCB_t * pxNewTCB;
+ BaseType_t xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
+
+ configASSERT(pxTaskDefinition->puxStackBuffer);
+
+ if (pxTaskDefinition->puxStackBuffer != NULL) {
+ /* Allocate space for the TCB. Where the memory comes from depends
+ on the implementation of the port malloc function and whether or
+ not static allocation is being used. */
+ pxNewTCB = (TCB_t *)pvPortMalloc(sizeof(TCB_t));
+
+ if (pxNewTCB != NULL) {
+ /* Store the stack location in the TCB. */
+ pxNewTCB->pxStack = pxTaskDefinition->puxStackBuffer;
+
+#if (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0)
+ {
+ /* Tasks can be created statically or dynamically, so note
+ this task had a statically allocated stack in case it is
+ later deleted. The TCB was allocated dynamically. */
+ pxNewTCB->ucStaticallyAllocated = tskSTATICALLY_ALLOCATED_STACK_ONLY;
+ }
+#endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
+
+ prvInitialiseNewTask(pxTaskDefinition->pvTaskCode, pxTaskDefinition->pcName, (uint32_t)pxTaskDefinition->usStackDepth, pxTaskDefinition->pvParameters, pxTaskDefinition->uxPriority,
+ pxCreatedTask, pxNewTCB, pxTaskDefinition->xRegions);
+
+ prvAddNewTaskToReadyList(pxNewTCB);
+ xReturn = pdPASS;
+ }
+ }
+
+ return xReturn;
+}
#endif /* portUSING_MPU_WRAPPERS */
/*-----------------------------------------------------------*/
-#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
-
- BaseType_t xTaskCreate( TaskFunction_t pxTaskCode,
- const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- const configSTACK_DEPTH_TYPE usStackDepth,
- void * const pvParameters,
- UBaseType_t uxPriority,
- TaskHandle_t * const pxCreatedTask )
- {
- TCB_t *pxNewTCB;
- BaseType_t xReturn;
-
- /* If the stack grows down then allocate the stack then the TCB so the stack
- does not grow into the TCB. Likewise if the stack grows up then allocate
- the TCB then the stack. */
- #if( portSTACK_GROWTH > 0 )
- {
- /* Allocate space for the TCB. Where the memory comes from depends on
- the implementation of the port malloc function and whether or not static
- allocation is being used. */
- pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) );
-
- if( pxNewTCB != NULL )
- {
- /* Allocate space for the stack used by the task being created.
- The base of the stack memory stored in the TCB so the task can
- be deleted later if required. */
- pxNewTCB->pxStack = ( StackType_t * ) pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
-
- if( pxNewTCB->pxStack == NULL )
- {
- /* Could not allocate the stack. Delete the allocated TCB. */
- vPortFree( pxNewTCB );
- pxNewTCB = NULL;
- }
- }
- }
- #else /* portSTACK_GROWTH */
- {
- StackType_t *pxStack;
-
- /* Allocate space for the stack used by the task being created. */
- pxStack = pvPortMalloc( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */
-
- if( pxStack != NULL )
- {
- /* Allocate space for the TCB. */
- pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of TCB_t is always a pointer to the task's stack. */
-
- if( pxNewTCB != NULL )
- {
- /* Store the stack location in the TCB. */
- pxNewTCB->pxStack = pxStack;
- }
- else
- {
- /* The stack cannot be used as the TCB was not created. Free
- it again. */
- vPortFree( pxStack );
- }
- }
- else
- {
- pxNewTCB = NULL;
- }
- }
- #endif /* portSTACK_GROWTH */
-
- if( pxNewTCB != NULL )
- {
- #if( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */
- {
- /* Tasks can be created statically or dynamically, so note this
- task was created dynamically in case it is later deleted. */
- pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB;
- }
- #endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
-
- prvInitialiseNewTask( pxTaskCode, pcName, ( uint32_t ) usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL );
- prvAddNewTaskToReadyList( pxNewTCB );
- xReturn = pdPASS;
- }
- else
- {
- xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
- }
-
- return xReturn;
- }
+#if (configSUPPORT_DYNAMIC_ALLOCATION == 1)
+
+BaseType_t xTaskCreate(TaskFunction_t pxTaskCode, const char *const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ const configSTACK_DEPTH_TYPE usStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pxCreatedTask) {
+ TCB_t * pxNewTCB;
+ BaseType_t xReturn;
+
+/* If the stack grows down then allocate the stack then the TCB so the stack
+does not grow into the TCB. Likewise if the stack grows up then allocate
+the TCB then the stack. */
+#if (portSTACK_GROWTH > 0)
+ {
+ /* Allocate space for the TCB. Where the memory comes from depends on
+ the implementation of the port malloc function and whether or not static
+ allocation is being used. */
+ pxNewTCB = (TCB_t *)pvPortMalloc(sizeof(TCB_t));
+
+ if (pxNewTCB != NULL) {
+ /* Allocate space for the stack used by the task being created.
+ The base of the stack memory stored in the TCB so the task can
+ be deleted later if required. */
+ pxNewTCB->pxStack = (StackType_t *)pvPortMalloc((((size_t)usStackDepth) * sizeof(StackType_t))); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+
+ if (pxNewTCB->pxStack == NULL) {
+ /* Could not allocate the stack. Delete the allocated TCB. */
+ vPortFree(pxNewTCB);
+ pxNewTCB = NULL;
+ }
+ }
+ }
+#else /* portSTACK_GROWTH */
+ {
+ StackType_t *pxStack;
+
+ /* Allocate space for the stack used by the task being created. */
+ pxStack = pvPortMalloc((((size_t)usStackDepth)
+ * sizeof(StackType_t))); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation is the stack. */
+
+ if (pxStack != NULL) {
+ /* Allocate space for the TCB. */
+ pxNewTCB = (TCB_t *)pvPortMalloc(sizeof(TCB_t)); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of
+ TCB_t is always a pointer to the task's stack. */
+
+ if (pxNewTCB != NULL) {
+ /* Store the stack location in the TCB. */
+ pxNewTCB->pxStack = pxStack;
+ } else {
+ /* The stack cannot be used as the TCB was not created. Free
+ it again. */
+ vPortFree(pxStack);
+ }
+ } else {
+ pxNewTCB = NULL;
+ }
+ }
+#endif /* portSTACK_GROWTH */
+
+ if (pxNewTCB != NULL) {
+#if (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0) /*lint !e9029 !e731 Macro has been consolidated for readability reasons. */
+ {
+ /* Tasks can be created statically or dynamically, so note this
+ task was created dynamically in case it is later deleted. */
+ pxNewTCB->ucStaticallyAllocated = tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB;
+ }
+#endif /* tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE */
+
+ prvInitialiseNewTask(pxTaskCode, pcName, (uint32_t)usStackDepth, pvParameters, uxPriority, pxCreatedTask, pxNewTCB, NULL);
+ prvAddNewTaskToReadyList(pxNewTCB);
+ xReturn = pdPASS;
+ } else {
+ xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
+ }
+
+ return xReturn;
+}
#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
/*-----------------------------------------------------------*/
-static void prvInitialiseNewTask( TaskFunction_t pxTaskCode,
- const char * const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- const uint32_t ulStackDepth,
- void * const pvParameters,
- UBaseType_t uxPriority,
- TaskHandle_t * const pxCreatedTask,
- TCB_t *pxNewTCB,
- const MemoryRegion_t * const xRegions )
-{
-StackType_t *pxTopOfStack;
-UBaseType_t x;
-
- #if( portUSING_MPU_WRAPPERS == 1 )
- /* Should the task be created in privileged mode? */
- BaseType_t xRunPrivileged;
- if( ( uxPriority & portPRIVILEGE_BIT ) != 0U )
- {
- xRunPrivileged = pdTRUE;
- }
- else
- {
- xRunPrivileged = pdFALSE;
- }
- uxPriority &= ~portPRIVILEGE_BIT;
- #endif /* portUSING_MPU_WRAPPERS == 1 */
-
- /* Avoid dependency on memset() if it is not required. */
- #if( tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1 )
- {
- /* Fill the stack with a known value to assist debugging. */
- ( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) ulStackDepth * sizeof( StackType_t ) );
- }
- #endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */
-
- /* Calculate the top of stack address. This depends on whether the stack
- grows from high memory to low (as per the 80x86) or vice versa.
- portSTACK_GROWTH is used to make the result positive or negative as required
- by the port. */
- #if( portSTACK_GROWTH < 0 )
- {
- pxTopOfStack = &( pxNewTCB->pxStack[ ulStackDepth - ( uint32_t ) 1 ] );
- pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical. Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */
-
- /* Check the alignment of the calculated top of stack is correct. */
- configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) );
-
- #if( configRECORD_STACK_HIGH_ADDRESS == 1 )
- {
- /* Also record the stack's high address, which may assist
- debugging. */
- pxNewTCB->pxEndOfStack = pxTopOfStack;
- }
- #endif /* configRECORD_STACK_HIGH_ADDRESS */
- }
- #else /* portSTACK_GROWTH */
- {
- pxTopOfStack = pxNewTCB->pxStack;
-
- /* Check the alignment of the stack buffer is correct. */
- configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) );
-
- /* The other extreme of the stack space is required if stack checking is
- performed. */
- pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( ulStackDepth - ( uint32_t ) 1 );
- }
- #endif /* portSTACK_GROWTH */
-
- /* Store the task name in the TCB. */
- if( pcName != NULL )
- {
- for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ )
- {
- pxNewTCB->pcTaskName[ x ] = pcName[ x ];
-
- /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than
- configMAX_TASK_NAME_LEN characters just in case the memory after the
- string is not accessible (extremely unlikely). */
- if( pcName[ x ] == ( char ) 0x00 )
- {
- break;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- /* Ensure the name string is terminated in the case that the string length
- was greater or equal to configMAX_TASK_NAME_LEN. */
- pxNewTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0';
- }
- else
- {
- /* The task has not been given a name, so just ensure there is a NULL
- terminator when it is read out. */
- pxNewTCB->pcTaskName[ 0 ] = 0x00;
- }
-
- /* This is used as an array index so must ensure it's not too large. First
- remove the privilege bit if one is present. */
- if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES )
- {
- uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- pxNewTCB->uxPriority = uxPriority;
- #if ( configUSE_MUTEXES == 1 )
- {
- pxNewTCB->uxBasePriority = uxPriority;
- pxNewTCB->uxMutexesHeld = 0;
- }
- #endif /* configUSE_MUTEXES */
-
- vListInitialiseItem( &( pxNewTCB->xStateListItem ) );
- vListInitialiseItem( &( pxNewTCB->xEventListItem ) );
-
- /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get
- back to the containing TCB from a generic item in a list. */
- listSET_LIST_ITEM_OWNER( &( pxNewTCB->xStateListItem ), pxNewTCB );
-
- /* Event lists are always in priority order. */
- listSET_LIST_ITEM_VALUE( &( pxNewTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
- listSET_LIST_ITEM_OWNER( &( pxNewTCB->xEventListItem ), pxNewTCB );
-
- #if ( portCRITICAL_NESTING_IN_TCB == 1 )
- {
- pxNewTCB->uxCriticalNesting = ( UBaseType_t ) 0U;
- }
- #endif /* portCRITICAL_NESTING_IN_TCB */
-
- #if ( configUSE_APPLICATION_TASK_TAG == 1 )
- {
- pxNewTCB->pxTaskTag = NULL;
- }
- #endif /* configUSE_APPLICATION_TASK_TAG */
-
- #if ( configGENERATE_RUN_TIME_STATS == 1 )
- {
- pxNewTCB->ulRunTimeCounter = 0UL;
- }
- #endif /* configGENERATE_RUN_TIME_STATS */
-
- #if ( portUSING_MPU_WRAPPERS == 1 )
- {
- vPortStoreTaskMPUSettings( &( pxNewTCB->xMPUSettings ), xRegions, pxNewTCB->pxStack, ulStackDepth );
- }
- #else
- {
- /* Avoid compiler warning about unreferenced parameter. */
- ( void ) xRegions;
- }
- #endif
-
- #if( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
- {
- for( x = 0; x < ( UBaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ )
- {
- pxNewTCB->pvThreadLocalStoragePointers[ x ] = NULL;
- }
- }
- #endif
-
- #if ( configUSE_TASK_NOTIFICATIONS == 1 )
- {
- pxNewTCB->ulNotifiedValue = 0;
- pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
- }
- #endif
-
- #if ( configUSE_NEWLIB_REENTRANT == 1 )
- {
- /* Initialise this task's Newlib reent structure.
- See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
- for additional information. */
- _REENT_INIT_PTR( ( &( pxNewTCB->xNewLib_reent ) ) );
- }
- #endif
-
- #if( INCLUDE_xTaskAbortDelay == 1 )
- {
- pxNewTCB->ucDelayAborted = pdFALSE;
- }
- #endif
-
- /* Initialize the TCB stack to look as if the task was already running,
- but had been interrupted by the scheduler. The return address is set
- to the start of the task function. Once the stack has been initialised
- the top of stack variable is updated. */
- #if( portUSING_MPU_WRAPPERS == 1 )
- {
- /* If the port has capability to detect stack overflow,
- pass the stack end address to the stack initialization
- function as well. */
- #if( portHAS_STACK_OVERFLOW_CHECKING == 1 )
- {
- #if( portSTACK_GROWTH < 0 )
- {
- pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged );
- }
- #else /* portSTACK_GROWTH */
- {
- pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged );
- }
- #endif /* portSTACK_GROWTH */
- }
- #else /* portHAS_STACK_OVERFLOW_CHECKING */
- {
- pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged );
- }
- #endif /* portHAS_STACK_OVERFLOW_CHECKING */
- }
- #else /* portUSING_MPU_WRAPPERS */
- {
- /* If the port has capability to detect stack overflow,
- pass the stack end address to the stack initialization
- function as well. */
- #if( portHAS_STACK_OVERFLOW_CHECKING == 1 )
- {
- #if( portSTACK_GROWTH < 0 )
- {
- pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters );
- }
- #else /* portSTACK_GROWTH */
- {
- pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters );
- }
- #endif /* portSTACK_GROWTH */
- }
- #else /* portHAS_STACK_OVERFLOW_CHECKING */
- {
- pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters );
- }
- #endif /* portHAS_STACK_OVERFLOW_CHECKING */
- }
- #endif /* portUSING_MPU_WRAPPERS */
-
- if( pxCreatedTask != NULL )
- {
- /* Pass the handle out in an anonymous way. The handle can be used to
- change the created task's priority, delete the created task, etc.*/
- *pxCreatedTask = ( TaskHandle_t ) pxNewTCB;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
+static void prvInitialiseNewTask(TaskFunction_t pxTaskCode, const char *const pcName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ const uint32_t ulStackDepth, void *const pvParameters, UBaseType_t uxPriority, TaskHandle_t *const pxCreatedTask, TCB_t *pxNewTCB,
+ const MemoryRegion_t *const xRegions) {
+ StackType_t *pxTopOfStack;
+ UBaseType_t x;
+
+#if (portUSING_MPU_WRAPPERS == 1)
+ /* Should the task be created in privileged mode? */
+ BaseType_t xRunPrivileged;
+ if ((uxPriority & portPRIVILEGE_BIT) != 0U) {
+ xRunPrivileged = pdTRUE;
+ } else {
+ xRunPrivileged = pdFALSE;
+ }
+ uxPriority &= ~portPRIVILEGE_BIT;
+#endif /* portUSING_MPU_WRAPPERS == 1 */
+
+/* Avoid dependency on memset() if it is not required. */
+#if (tskSET_NEW_STACKS_TO_KNOWN_VALUE == 1)
+ {
+ /* Fill the stack with a known value to assist debugging. */
+ (void)memset(pxNewTCB->pxStack, (int)tskSTACK_FILL_BYTE, (size_t)ulStackDepth * sizeof(StackType_t));
+ }
+#endif /* tskSET_NEW_STACKS_TO_KNOWN_VALUE */
+
+/* Calculate the top of stack address. This depends on whether the stack
+grows from high memory to low (as per the 80x86) or vice versa.
+portSTACK_GROWTH is used to make the result positive or negative as required
+by the port. */
+#if (portSTACK_GROWTH < 0)
+ {
+ pxTopOfStack = &(pxNewTCB->pxStack[ulStackDepth - (uint32_t)1]);
+ pxTopOfStack = (StackType_t *)(((portPOINTER_SIZE_TYPE)pxTopOfStack)
+ & (~((portPOINTER_SIZE_TYPE)portBYTE_ALIGNMENT_MASK))); /*lint !e923 !e9033 !e9078 MISRA exception. Avoiding casts between pointers and integers is not practical.
+ Size differences accounted for using portPOINTER_SIZE_TYPE type. Checked by assert(). */
+
+ /* Check the alignment of the calculated top of stack is correct. */
+ configASSERT((((portPOINTER_SIZE_TYPE)pxTopOfStack & (portPOINTER_SIZE_TYPE)portBYTE_ALIGNMENT_MASK) == 0UL));
+
+#if (configRECORD_STACK_HIGH_ADDRESS == 1)
+ {
+ /* Also record the stack's high address, which may assist
+ debugging. */
+ pxNewTCB->pxEndOfStack = pxTopOfStack;
+ }
+#endif /* configRECORD_STACK_HIGH_ADDRESS */
+ }
+#else /* portSTACK_GROWTH */
+ {
+ pxTopOfStack = pxNewTCB->pxStack;
+
+ /* Check the alignment of the stack buffer is correct. */
+ configASSERT((((portPOINTER_SIZE_TYPE)pxNewTCB->pxStack & (portPOINTER_SIZE_TYPE)portBYTE_ALIGNMENT_MASK) == 0UL));
+
+ /* The other extreme of the stack space is required if stack checking is
+ performed. */
+ pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + (ulStackDepth - (uint32_t)1);
+ }
+#endif /* portSTACK_GROWTH */
+
+ /* Store the task name in the TCB. */
+ if (pcName != NULL) {
+ for (x = (UBaseType_t)0; x < (UBaseType_t)configMAX_TASK_NAME_LEN; x++) {
+ pxNewTCB->pcTaskName[x] = pcName[x];
+
+ /* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than
+ configMAX_TASK_NAME_LEN characters just in case the memory after the
+ string is not accessible (extremely unlikely). */
+ if (pcName[x] == (char)0x00) {
+ break;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ /* Ensure the name string is terminated in the case that the string length
+ was greater or equal to configMAX_TASK_NAME_LEN. */
+ pxNewTCB->pcTaskName[configMAX_TASK_NAME_LEN - 1] = '\0';
+ } else {
+ /* The task has not been given a name, so just ensure there is a NULL
+ terminator when it is read out. */
+ pxNewTCB->pcTaskName[0] = 0x00;
+ }
+
+ /* This is used as an array index so must ensure it's not too large. First
+ remove the privilege bit if one is present. */
+ if (uxPriority >= (UBaseType_t)configMAX_PRIORITIES) {
+ uxPriority = (UBaseType_t)configMAX_PRIORITIES - (UBaseType_t)1U;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ pxNewTCB->uxPriority = uxPriority;
+#if (configUSE_MUTEXES == 1)
+ {
+ pxNewTCB->uxBasePriority = uxPriority;
+ pxNewTCB->uxMutexesHeld = 0;
+ }
+#endif /* configUSE_MUTEXES */
+
+ vListInitialiseItem(&(pxNewTCB->xStateListItem));
+ vListInitialiseItem(&(pxNewTCB->xEventListItem));
+
+ /* Set the pxNewTCB as a link back from the ListItem_t. This is so we can get
+ back to the containing TCB from a generic item in a list. */
+ listSET_LIST_ITEM_OWNER(&(pxNewTCB->xStateListItem), pxNewTCB);
+
+ /* Event lists are always in priority order. */
+ listSET_LIST_ITEM_VALUE(&(pxNewTCB->xEventListItem), (TickType_t)configMAX_PRIORITIES - (TickType_t)uxPriority); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+ listSET_LIST_ITEM_OWNER(&(pxNewTCB->xEventListItem), pxNewTCB);
+
+#if (portCRITICAL_NESTING_IN_TCB == 1)
+ { pxNewTCB->uxCriticalNesting = (UBaseType_t)0U; }
+#endif /* portCRITICAL_NESTING_IN_TCB */
+
+#if (configUSE_APPLICATION_TASK_TAG == 1)
+ { pxNewTCB->pxTaskTag = NULL; }
+#endif /* configUSE_APPLICATION_TASK_TAG */
+
+#if (configGENERATE_RUN_TIME_STATS == 1)
+ { pxNewTCB->ulRunTimeCounter = 0UL; }
+#endif /* configGENERATE_RUN_TIME_STATS */
+
+#if (portUSING_MPU_WRAPPERS == 1)
+ { vPortStoreTaskMPUSettings(&(pxNewTCB->xMPUSettings), xRegions, pxNewTCB->pxStack, ulStackDepth); }
+#else
+ {
+ /* Avoid compiler warning about unreferenced parameter. */
+ (void)xRegions;
+ }
+#endif
+
+#if (configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0)
+ {
+ for (x = 0; x < (UBaseType_t)configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++) {
+ pxNewTCB->pvThreadLocalStoragePointers[x] = NULL;
+ }
+ }
+#endif
+
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+ {
+ pxNewTCB->ulNotifiedValue = 0;
+ pxNewTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ }
+#endif
+
+#if (configUSE_NEWLIB_REENTRANT == 1)
+ {
+ /* Initialise this task's Newlib reent structure.
+ See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
+ for additional information. */
+ _REENT_INIT_PTR((&(pxNewTCB->xNewLib_reent)));
+ }
+#endif
+
+#if (INCLUDE_xTaskAbortDelay == 1)
+ { pxNewTCB->ucDelayAborted = pdFALSE; }
+#endif
+
+/* Initialize the TCB stack to look as if the task was already running,
+but had been interrupted by the scheduler. The return address is set
+to the start of the task function. Once the stack has been initialised
+the top of stack variable is updated. */
+#if (portUSING_MPU_WRAPPERS == 1)
+ {
+/* If the port has capability to detect stack overflow,
+pass the stack end address to the stack initialization
+function as well. */
+#if (portHAS_STACK_OVERFLOW_CHECKING == 1)
+ {
+#if (portSTACK_GROWTH < 0)
+ { pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters, xRunPrivileged); }
+#else /* portSTACK_GROWTH */
+ { pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters, xRunPrivileged); }
+#endif /* portSTACK_GROWTH */
+ }
+#else /* portHAS_STACK_OVERFLOW_CHECKING */
+ { pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged); }
+#endif /* portHAS_STACK_OVERFLOW_CHECKING */
+ }
+#else /* portUSING_MPU_WRAPPERS */
+ {
+/* If the port has capability to detect stack overflow,
+pass the stack end address to the stack initialization
+function as well. */
+#if (portHAS_STACK_OVERFLOW_CHECKING == 1)
+ {
+#if (portSTACK_GROWTH < 0)
+ { pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxNewTCB->pxStack, pxTaskCode, pvParameters); }
+#else /* portSTACK_GROWTH */
+ { pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxNewTCB->pxEndOfStack, pxTaskCode, pvParameters); }
+#endif /* portSTACK_GROWTH */
+ }
+#else /* portHAS_STACK_OVERFLOW_CHECKING */
+ { pxNewTCB->pxTopOfStack = pxPortInitialiseStack(pxTopOfStack, pxTaskCode, pvParameters); }
+#endif /* portHAS_STACK_OVERFLOW_CHECKING */
+ }
+#endif /* portUSING_MPU_WRAPPERS */
+
+ if (pxCreatedTask != NULL) {
+ /* Pass the handle out in an anonymous way. The handle can be used to
+ change the created task's priority, delete the created task, etc.*/
+ *pxCreatedTask = (TaskHandle_t)pxNewTCB;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
}
/*-----------------------------------------------------------*/
-static void prvAddNewTaskToReadyList( TCB_t *pxNewTCB )
-{
- /* Ensure interrupts don't access the task lists while the lists are being
- updated. */
- taskENTER_CRITICAL();
- {
- uxCurrentNumberOfTasks++;
- if( pxCurrentTCB == NULL )
- {
- /* There are no other tasks, or all the other tasks are in
- the suspended state - make this the current task. */
- pxCurrentTCB = pxNewTCB;
-
- if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 )
- {
- /* This is the first task to be created so do the preliminary
- initialisation required. We will not recover if this call
- fails, but we will report the failure. */
- prvInitialiseTaskLists();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* If the scheduler is not already running, make this task the
- current task if it is the highest priority task to be created
- so far. */
- if( xSchedulerRunning == pdFALSE )
- {
- if( pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority )
- {
- pxCurrentTCB = pxNewTCB;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- uxTaskNumber++;
-
- #if ( configUSE_TRACE_FACILITY == 1 )
- {
- /* Add a counter into the TCB for tracing only. */
- pxNewTCB->uxTCBNumber = uxTaskNumber;
- }
- #endif /* configUSE_TRACE_FACILITY */
- traceTASK_CREATE( pxNewTCB );
-
- prvAddTaskToReadyList( pxNewTCB );
-
- portSETUP_TCB( pxNewTCB );
- }
- taskEXIT_CRITICAL();
-
- if( xSchedulerRunning != pdFALSE )
- {
- /* If the created task is of a higher priority than the current task
- then it should run now. */
- if( pxCurrentTCB->uxPriority < pxNewTCB->uxPriority )
- {
- taskYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
+static void prvAddNewTaskToReadyList(TCB_t *pxNewTCB) {
+ /* Ensure interrupts don't access the task lists while the lists are being
+ updated. */
+ taskENTER_CRITICAL();
+ {
+ uxCurrentNumberOfTasks++;
+ if (pxCurrentTCB == NULL) {
+ /* There are no other tasks, or all the other tasks are in
+ the suspended state - make this the current task. */
+ pxCurrentTCB = pxNewTCB;
+
+ if (uxCurrentNumberOfTasks == (UBaseType_t)1) {
+ /* This is the first task to be created so do the preliminary
+ initialisation required. We will not recover if this call
+ fails, but we will report the failure. */
+ prvInitialiseTaskLists();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* If the scheduler is not already running, make this task the
+ current task if it is the highest priority task to be created
+ so far. */
+ if (xSchedulerRunning == pdFALSE) {
+ if (pxCurrentTCB->uxPriority <= pxNewTCB->uxPriority) {
+ pxCurrentTCB = pxNewTCB;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ uxTaskNumber++;
+
+#if (configUSE_TRACE_FACILITY == 1)
+ {
+ /* Add a counter into the TCB for tracing only. */
+ pxNewTCB->uxTCBNumber = uxTaskNumber;
+ }
+#endif /* configUSE_TRACE_FACILITY */
+ traceTASK_CREATE(pxNewTCB);
+
+ prvAddTaskToReadyList(pxNewTCB);
+
+ portSETUP_TCB(pxNewTCB);
+ }
+ taskEXIT_CRITICAL();
+
+ if (xSchedulerRunning != pdFALSE) {
+ /* If the created task is of a higher priority than the current task
+ then it should run now. */
+ if (pxCurrentTCB->uxPriority < pxNewTCB->uxPriority) {
+ taskYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
}
/*-----------------------------------------------------------*/
-#if ( INCLUDE_vTaskDelete == 1 )
-
- void vTaskDelete( TaskHandle_t xTaskToDelete )
- {
- TCB_t *pxTCB;
-
- taskENTER_CRITICAL();
- {
- /* If null is passed in here then it is the calling task that is
- being deleted. */
- pxTCB = prvGetTCBFromHandle( xTaskToDelete );
-
- /* Remove task from the ready/delayed list. */
- if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
- {
- taskRESET_READY_PRIORITY( pxTCB->uxPriority );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Is the task waiting on an event also? */
- if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
- {
- ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Increment the uxTaskNumber also so kernel aware debuggers can
- detect that the task lists need re-generating. This is done before
- portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will
- not return. */
- uxTaskNumber++;
-
- if( pxTCB == pxCurrentTCB )
- {
- /* A task is deleting itself. This cannot complete within the
- task itself, as a context switch to another task is required.
- Place the task in the termination list. The idle task will
- check the termination list and free up any memory allocated by
- the scheduler for the TCB and stack of the deleted task. */
- vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xStateListItem ) );
-
- /* Increment the ucTasksDeleted variable so the idle task knows
- there is a task that has been deleted and that it should therefore
- check the xTasksWaitingTermination list. */
- ++uxDeletedTasksWaitingCleanUp;
-
- /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as
- portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */
- traceTASK_DELETE( pxTCB );
-
- /* The pre-delete hook is primarily for the Windows simulator,
- in which Windows specific clean up operations are performed,
- after which it is not possible to yield away from this task -
- hence xYieldPending is used to latch that a context switch is
- required. */
- portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending );
- }
- else
- {
- --uxCurrentNumberOfTasks;
- traceTASK_DELETE( pxTCB );
- prvDeleteTCB( pxTCB );
-
- /* Reset the next expected unblock time in case it referred to
- the task that has just been deleted. */
- prvResetNextTaskUnblockTime();
- }
- }
- taskEXIT_CRITICAL();
-
- /* Force a reschedule if it is the currently running task that has just
- been deleted. */
- if( xSchedulerRunning != pdFALSE )
- {
- if( pxTCB == pxCurrentTCB )
- {
- configASSERT( uxSchedulerSuspended == 0 );
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
+#if (INCLUDE_vTaskDelete == 1)
+
+void vTaskDelete(TaskHandle_t xTaskToDelete) {
+ TCB_t *pxTCB;
+
+ taskENTER_CRITICAL();
+ {
+ /* If null is passed in here then it is the calling task that is
+ being deleted. */
+ pxTCB = prvGetTCBFromHandle(xTaskToDelete);
+
+ /* Remove task from the ready/delayed list. */
+ if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0) {
+ taskRESET_READY_PRIORITY(pxTCB->uxPriority);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Is the task waiting on an event also? */
+ if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL) {
+ (void)uxListRemove(&(pxTCB->xEventListItem));
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Increment the uxTaskNumber also so kernel aware debuggers can
+ detect that the task lists need re-generating. This is done before
+ portPRE_TASK_DELETE_HOOK() as in the Windows port that macro will
+ not return. */
+ uxTaskNumber++;
+
+ if (pxTCB == pxCurrentTCB) {
+ /* A task is deleting itself. This cannot complete within the
+ task itself, as a context switch to another task is required.
+ Place the task in the termination list. The idle task will
+ check the termination list and free up any memory allocated by
+ the scheduler for the TCB and stack of the deleted task. */
+ vListInsertEnd(&xTasksWaitingTermination, &(pxTCB->xStateListItem));
+
+ /* Increment the ucTasksDeleted variable so the idle task knows
+ there is a task that has been deleted and that it should therefore
+ check the xTasksWaitingTermination list. */
+ ++uxDeletedTasksWaitingCleanUp;
+
+ /* Call the delete hook before portPRE_TASK_DELETE_HOOK() as
+ portPRE_TASK_DELETE_HOOK() does not return in the Win32 port. */
+ traceTASK_DELETE(pxTCB);
+
+ /* The pre-delete hook is primarily for the Windows simulator,
+ in which Windows specific clean up operations are performed,
+ after which it is not possible to yield away from this task -
+ hence xYieldPending is used to latch that a context switch is
+ required. */
+ portPRE_TASK_DELETE_HOOK(pxTCB, &xYieldPending);
+ } else {
+ --uxCurrentNumberOfTasks;
+ traceTASK_DELETE(pxTCB);
+ prvDeleteTCB(pxTCB);
+
+ /* Reset the next expected unblock time in case it referred to
+ the task that has just been deleted. */
+ prvResetNextTaskUnblockTime();
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ /* Force a reschedule if it is the currently running task that has just
+ been deleted. */
+ if (xSchedulerRunning != pdFALSE) {
+ if (pxTCB == pxCurrentTCB) {
+ configASSERT(uxSchedulerSuspended == 0);
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+}
#endif /* INCLUDE_vTaskDelete */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_vTaskDelayUntil == 1 )
-
- void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement )
- {
- TickType_t xTimeToWake;
- BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE;
-
- configASSERT( pxPreviousWakeTime );
- configASSERT( ( xTimeIncrement > 0U ) );
- configASSERT( uxSchedulerSuspended == 0 );
-
- vTaskSuspendAll();
- {
- /* Minor optimisation. The tick count cannot change in this
- block. */
- const TickType_t xConstTickCount = xTickCount;
-
- /* Generate the tick time at which the task wants to wake. */
- xTimeToWake = *pxPreviousWakeTime + xTimeIncrement;
-
- if( xConstTickCount < *pxPreviousWakeTime )
- {
- /* The tick count has overflowed since this function was
- lasted called. In this case the only time we should ever
- actually delay is if the wake time has also overflowed,
- and the wake time is greater than the tick time. When this
- is the case it is as if neither time had overflowed. */
- if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) )
- {
- xShouldDelay = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* The tick time has not overflowed. In this case we will
- delay if either the wake time has overflowed, and/or the
- tick time is less than the wake time. */
- if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) )
- {
- xShouldDelay = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- /* Update the wake time ready for the next call. */
- *pxPreviousWakeTime = xTimeToWake;
-
- if( xShouldDelay != pdFALSE )
- {
- traceTASK_DELAY_UNTIL( xTimeToWake );
-
- /* prvAddCurrentTaskToDelayedList() needs the block time, not
- the time to wake, so subtract the current tick count. */
- prvAddCurrentTaskToDelayedList( xTimeToWake - xConstTickCount, pdFALSE );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- xAlreadyYielded = xTaskResumeAll();
-
- /* Force a reschedule if xTaskResumeAll has not already done so, we may
- have put ourselves to sleep. */
- if( xAlreadyYielded == pdFALSE )
- {
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
+#if (INCLUDE_vTaskDelayUntil == 1)
+
+void vTaskDelayUntil(TickType_t *const pxPreviousWakeTime, const TickType_t xTimeIncrement) {
+ TickType_t xTimeToWake;
+ BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE;
+
+ configASSERT(pxPreviousWakeTime);
+ configASSERT((xTimeIncrement > 0U));
+ configASSERT(uxSchedulerSuspended == 0);
+
+ vTaskSuspendAll();
+ {
+ /* Minor optimisation. The tick count cannot change in this
+ block. */
+ const TickType_t xConstTickCount = xTickCount;
+
+ /* Generate the tick time at which the task wants to wake. */
+ xTimeToWake = *pxPreviousWakeTime + xTimeIncrement;
+
+ if (xConstTickCount < *pxPreviousWakeTime) {
+ /* The tick count has overflowed since this function was
+ lasted called. In this case the only time we should ever
+ actually delay is if the wake time has also overflowed,
+ and the wake time is greater than the tick time. When this
+ is the case it is as if neither time had overflowed. */
+ if ((xTimeToWake < *pxPreviousWakeTime) && (xTimeToWake > xConstTickCount)) {
+ xShouldDelay = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* The tick time has not overflowed. In this case we will
+ delay if either the wake time has overflowed, and/or the
+ tick time is less than the wake time. */
+ if ((xTimeToWake < *pxPreviousWakeTime) || (xTimeToWake > xConstTickCount)) {
+ xShouldDelay = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ /* Update the wake time ready for the next call. */
+ *pxPreviousWakeTime = xTimeToWake;
+
+ if (xShouldDelay != pdFALSE) {
+ traceTASK_DELAY_UNTIL(xTimeToWake);
+
+ /* prvAddCurrentTaskToDelayedList() needs the block time, not
+ the time to wake, so subtract the current tick count. */
+ prvAddCurrentTaskToDelayedList(xTimeToWake - xConstTickCount, pdFALSE);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ xAlreadyYielded = xTaskResumeAll();
+
+ /* Force a reschedule if xTaskResumeAll has not already done so, we may
+ have put ourselves to sleep. */
+ if (xAlreadyYielded == pdFALSE) {
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+}
#endif /* INCLUDE_vTaskDelayUntil */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_vTaskDelay == 1 )
-
- void vTaskDelay( const TickType_t xTicksToDelay )
- {
- BaseType_t xAlreadyYielded = pdFALSE;
-
- /* A delay time of zero just forces a reschedule. */
- if( xTicksToDelay > ( TickType_t ) 0U )
- {
- configASSERT( uxSchedulerSuspended == 0 );
- vTaskSuspendAll();
- {
- traceTASK_DELAY();
-
- /* A task that is removed from the event list while the
- scheduler is suspended will not get placed in the ready
- list or removed from the blocked list until the scheduler
- is resumed.
-
- This task cannot be in an event list as it is the currently
- executing task. */
- prvAddCurrentTaskToDelayedList( xTicksToDelay, pdFALSE );
- }
- xAlreadyYielded = xTaskResumeAll();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Force a reschedule if xTaskResumeAll has not already done so, we may
- have put ourselves to sleep. */
- if( xAlreadyYielded == pdFALSE )
- {
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
+#if (INCLUDE_vTaskDelay == 1)
+
+void vTaskDelay(const TickType_t xTicksToDelay) {
+ BaseType_t xAlreadyYielded = pdFALSE;
+
+ /* A delay time of zero just forces a reschedule. */
+ if (xTicksToDelay > (TickType_t)0U) {
+ configASSERT(uxSchedulerSuspended == 0);
+ vTaskSuspendAll();
+ {
+ traceTASK_DELAY();
+
+ /* A task that is removed from the event list while the
+ scheduler is suspended will not get placed in the ready
+ list or removed from the blocked list until the scheduler
+ is resumed.
+
+ This task cannot be in an event list as it is the currently
+ executing task. */
+ prvAddCurrentTaskToDelayedList(xTicksToDelay, pdFALSE);
+ }
+ xAlreadyYielded = xTaskResumeAll();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Force a reschedule if xTaskResumeAll has not already done so, we may
+ have put ourselves to sleep. */
+ if (xAlreadyYielded == pdFALSE) {
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+}
#endif /* INCLUDE_vTaskDelay */
/*-----------------------------------------------------------*/
-#if( ( INCLUDE_eTaskGetState == 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_xTaskAbortDelay == 1 ) )
-
- eTaskState eTaskGetState( TaskHandle_t xTask )
- {
- eTaskState eReturn;
- List_t const * pxStateList, *pxDelayedList, *pxOverflowedDelayedList;
- const TCB_t * const pxTCB = xTask;
-
- configASSERT( pxTCB );
-
- if( pxTCB == pxCurrentTCB )
- {
- /* The task calling this function is querying its own state. */
- eReturn = eRunning;
- }
- else
- {
- taskENTER_CRITICAL();
- {
- pxStateList = listLIST_ITEM_CONTAINER( &( pxTCB->xStateListItem ) );
- pxDelayedList = pxDelayedTaskList;
- pxOverflowedDelayedList = pxOverflowDelayedTaskList;
- }
- taskEXIT_CRITICAL();
-
- if( ( pxStateList == pxDelayedList ) || ( pxStateList == pxOverflowedDelayedList ) )
- {
- /* The task being queried is referenced from one of the Blocked
- lists. */
- eReturn = eBlocked;
- }
-
- #if ( INCLUDE_vTaskSuspend == 1 )
- else if( pxStateList == &xSuspendedTaskList )
- {
- /* The task being queried is referenced from the suspended
- list. Is it genuinely suspended or is it blocked
- indefinitely? */
- if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL )
- {
- #if( configUSE_TASK_NOTIFICATIONS == 1 )
- {
- /* The task does not appear on the event list item of
- and of the RTOS objects, but could still be in the
- blocked state if it is waiting on its notification
- rather than waiting on an object. */
- if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION )
- {
- eReturn = eBlocked;
- }
- else
- {
- eReturn = eSuspended;
- }
- }
- #else
- {
- eReturn = eSuspended;
- }
- #endif
- }
- else
- {
- eReturn = eBlocked;
- }
- }
- #endif
-
- #if ( INCLUDE_vTaskDelete == 1 )
- else if( ( pxStateList == &xTasksWaitingTermination ) || ( pxStateList == NULL ) )
- {
- /* The task being queried is referenced from the deleted
- tasks list, or it is not referenced from any lists at
- all. */
- eReturn = eDeleted;
- }
- #endif
-
- else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */
- {
- /* If the task is not in any other state, it must be in the
- Ready (including pending ready) state. */
- eReturn = eReady;
- }
- }
-
- return eReturn;
- } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
+#if ((INCLUDE_eTaskGetState == 1) || (configUSE_TRACE_FACILITY == 1) || (INCLUDE_xTaskAbortDelay == 1))
+
+eTaskState eTaskGetState(TaskHandle_t xTask) {
+ eTaskState eReturn;
+ List_t const * pxStateList, *pxDelayedList, *pxOverflowedDelayedList;
+ const TCB_t *const pxTCB = xTask;
+
+ configASSERT(pxTCB);
+
+ if (pxTCB == pxCurrentTCB) {
+ /* The task calling this function is querying its own state. */
+ eReturn = eRunning;
+ } else {
+ taskENTER_CRITICAL();
+ {
+ pxStateList = listLIST_ITEM_CONTAINER(&(pxTCB->xStateListItem));
+ pxDelayedList = pxDelayedTaskList;
+ pxOverflowedDelayedList = pxOverflowDelayedTaskList;
+ }
+ taskEXIT_CRITICAL();
+
+ if ((pxStateList == pxDelayedList) || (pxStateList == pxOverflowedDelayedList)) {
+ /* The task being queried is referenced from one of the Blocked
+ lists. */
+ eReturn = eBlocked;
+ }
+
+#if (INCLUDE_vTaskSuspend == 1)
+ else if (pxStateList == &xSuspendedTaskList) {
+ /* The task being queried is referenced from the suspended
+ list. Is it genuinely suspended or is it blocked
+ indefinitely? */
+ if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) == NULL) {
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+ {
+ /* The task does not appear on the event list item of
+ and of the RTOS objects, but could still be in the
+ blocked state if it is waiting on its notification
+ rather than waiting on an object. */
+ if (pxTCB->ucNotifyState == taskWAITING_NOTIFICATION) {
+ eReturn = eBlocked;
+ } else {
+ eReturn = eSuspended;
+ }
+ }
+#else
+ { eReturn = eSuspended; }
+#endif
+ } else {
+ eReturn = eBlocked;
+ }
+ }
+#endif
+
+#if (INCLUDE_vTaskDelete == 1)
+ else if ((pxStateList == &xTasksWaitingTermination) || (pxStateList == NULL)) {
+ /* The task being queried is referenced from the deleted
+ tasks list, or it is not referenced from any lists at
+ all. */
+ eReturn = eDeleted;
+ }
+#endif
+
+ else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */
+ {
+ /* If the task is not in any other state, it must be in the
+ Ready (including pending ready) state. */
+ eReturn = eReady;
+ }
+ }
+
+ return eReturn;
+} /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
#endif /* INCLUDE_eTaskGetState */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_uxTaskPriorityGet == 1 )
+#if (INCLUDE_uxTaskPriorityGet == 1)
- UBaseType_t uxTaskPriorityGet( const TaskHandle_t xTask )
- {
- TCB_t const *pxTCB;
- UBaseType_t uxReturn;
+UBaseType_t uxTaskPriorityGet(const TaskHandle_t xTask) {
+ TCB_t const *pxTCB;
+ UBaseType_t uxReturn;
- taskENTER_CRITICAL();
- {
- /* If null is passed in here then it is the priority of the task
- that called uxTaskPriorityGet() that is being queried. */
- pxTCB = prvGetTCBFromHandle( xTask );
- uxReturn = pxTCB->uxPriority;
- }
- taskEXIT_CRITICAL();
+ taskENTER_CRITICAL();
+ {
+ /* If null is passed in here then it is the priority of the task
+ that called uxTaskPriorityGet() that is being queried. */
+ pxTCB = prvGetTCBFromHandle(xTask);
+ uxReturn = pxTCB->uxPriority;
+ }
+ taskEXIT_CRITICAL();
- return uxReturn;
- }
+ return uxReturn;
+}
#endif /* INCLUDE_uxTaskPriorityGet */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_uxTaskPriorityGet == 1 )
-
- UBaseType_t uxTaskPriorityGetFromISR( const TaskHandle_t xTask )
- {
- TCB_t const *pxTCB;
- UBaseType_t uxReturn, uxSavedInterruptState;
-
- /* RTOS ports that support interrupt nesting have the concept of a
- maximum system call (or maximum API call) interrupt priority.
- Interrupts that are above the maximum system call priority are keep
- permanently enabled, even when the RTOS kernel is in a critical section,
- but cannot make any calls to FreeRTOS API functions. If configASSERT()
- is defined in FreeRTOSConfig.h then
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
- failure if a FreeRTOS API function is called from an interrupt that has
- been assigned a priority above the configured maximum system call
- priority. Only FreeRTOS functions that end in FromISR can be called
- from interrupts that have been assigned a priority at or (logically)
- below the maximum system call interrupt priority. FreeRTOS maintains a
- separate interrupt safe API to ensure interrupt entry is as fast and as
- simple as possible. More information (albeit Cortex-M specific) is
- provided on the following link:
- https://www.freertos.org/RTOS-Cortex-M3-M4.html */
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
-
- uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- /* If null is passed in here then it is the priority of the calling
- task that is being queried. */
- pxTCB = prvGetTCBFromHandle( xTask );
- uxReturn = pxTCB->uxPriority;
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState );
-
- return uxReturn;
- }
+#if (INCLUDE_uxTaskPriorityGet == 1)
+
+UBaseType_t uxTaskPriorityGetFromISR(const TaskHandle_t xTask) {
+ TCB_t const *pxTCB;
+ UBaseType_t uxReturn, uxSavedInterruptState;
+
+ /* RTOS ports that support interrupt nesting have the concept of a
+ maximum system call (or maximum API call) interrupt priority.
+ Interrupts that are above the maximum system call priority are keep
+ permanently enabled, even when the RTOS kernel is in a critical section,
+ but cannot make any calls to FreeRTOS API functions. If configASSERT()
+ is defined in FreeRTOSConfig.h then
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+ failure if a FreeRTOS API function is called from an interrupt that has
+ been assigned a priority above the configured maximum system call
+ priority. Only FreeRTOS functions that end in FromISR can be called
+ from interrupts that have been assigned a priority at or (logically)
+ below the maximum system call interrupt priority. FreeRTOS maintains a
+ separate interrupt safe API to ensure interrupt entry is as fast and as
+ simple as possible. More information (albeit Cortex-M specific) is
+ provided on the following link:
+ https://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ /* If null is passed in here then it is the priority of the calling
+ task that is being queried. */
+ pxTCB = prvGetTCBFromHandle(xTask);
+ uxReturn = pxTCB->uxPriority;
+ }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptState);
+
+ return uxReturn;
+}
#endif /* INCLUDE_uxTaskPriorityGet */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_vTaskPrioritySet == 1 )
-
- void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority )
- {
- TCB_t *pxTCB;
- UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry;
- BaseType_t xYieldRequired = pdFALSE;
-
- configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) );
-
- /* Ensure the new priority is valid. */
- if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES )
- {
- uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- taskENTER_CRITICAL();
- {
- /* If null is passed in here then it is the priority of the calling
- task that is being changed. */
- pxTCB = prvGetTCBFromHandle( xTask );
-
- traceTASK_PRIORITY_SET( pxTCB, uxNewPriority );
-
- #if ( configUSE_MUTEXES == 1 )
- {
- uxCurrentBasePriority = pxTCB->uxBasePriority;
- }
- #else
- {
- uxCurrentBasePriority = pxTCB->uxPriority;
- }
- #endif
-
- if( uxCurrentBasePriority != uxNewPriority )
- {
- /* The priority change may have readied a task of higher
- priority than the calling task. */
- if( uxNewPriority > uxCurrentBasePriority )
- {
- if( pxTCB != pxCurrentTCB )
- {
- /* The priority of a task other than the currently
- running task is being raised. Is the priority being
- raised above that of the running task? */
- if( uxNewPriority >= pxCurrentTCB->uxPriority )
- {
- xYieldRequired = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- /* The priority of the running task is being raised,
- but the running task must already be the highest
- priority task able to run so no yield is required. */
- }
- }
- else if( pxTCB == pxCurrentTCB )
- {
- /* Setting the priority of the running task down means
- there may now be another task of higher priority that
- is ready to execute. */
- xYieldRequired = pdTRUE;
- }
- else
- {
- /* Setting the priority of any other task down does not
- require a yield as the running task must be above the
- new priority of the task being modified. */
- }
-
- /* Remember the ready list the task might be referenced from
- before its uxPriority member is changed so the
- taskRESET_READY_PRIORITY() macro can function correctly. */
- uxPriorityUsedOnEntry = pxTCB->uxPriority;
-
- #if ( configUSE_MUTEXES == 1 )
- {
- /* Only change the priority being used if the task is not
- currently using an inherited priority. */
- if( pxTCB->uxBasePriority == pxTCB->uxPriority )
- {
- pxTCB->uxPriority = uxNewPriority;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* The base priority gets set whatever. */
- pxTCB->uxBasePriority = uxNewPriority;
- }
- #else
- {
- pxTCB->uxPriority = uxNewPriority;
- }
- #endif
-
- /* Only reset the event list item value if the value is not
- being used for anything else. */
- if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
- {
- listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* If the task is in the blocked or suspended list we need do
- nothing more than change its priority variable. However, if
- the task is in a ready list it needs to be removed and placed
- in the list appropriate to its new priority. */
- if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE )
- {
- /* The task is currently in its ready list - remove before
- adding it to it's new ready list. As we are in a critical
- section we can do this even if the scheduler is suspended. */
- if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
- {
- /* It is known that the task is in its ready list so
- there is no need to check again and the port level
- reset macro can be called directly. */
- portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- prvAddTaskToReadyList( pxTCB );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- if( xYieldRequired != pdFALSE )
- {
- taskYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Remove compiler warning about unused variables when the port
- optimised task selection is not being used. */
- ( void ) uxPriorityUsedOnEntry;
- }
- }
- taskEXIT_CRITICAL();
- }
+#if (INCLUDE_vTaskPrioritySet == 1)
+
+void vTaskPrioritySet(TaskHandle_t xTask, UBaseType_t uxNewPriority) {
+ TCB_t * pxTCB;
+ UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry;
+ BaseType_t xYieldRequired = pdFALSE;
+
+ configASSERT((uxNewPriority < configMAX_PRIORITIES));
+
+ /* Ensure the new priority is valid. */
+ if (uxNewPriority >= (UBaseType_t)configMAX_PRIORITIES) {
+ uxNewPriority = (UBaseType_t)configMAX_PRIORITIES - (UBaseType_t)1U;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ taskENTER_CRITICAL();
+ {
+ /* If null is passed in here then it is the priority of the calling
+ task that is being changed. */
+ pxTCB = prvGetTCBFromHandle(xTask);
+
+ traceTASK_PRIORITY_SET(pxTCB, uxNewPriority);
+
+#if (configUSE_MUTEXES == 1)
+ { uxCurrentBasePriority = pxTCB->uxBasePriority; }
+#else
+ { uxCurrentBasePriority = pxTCB->uxPriority; }
+#endif
+
+ if (uxCurrentBasePriority != uxNewPriority) {
+ /* The priority change may have readied a task of higher
+ priority than the calling task. */
+ if (uxNewPriority > uxCurrentBasePriority) {
+ if (pxTCB != pxCurrentTCB) {
+ /* The priority of a task other than the currently
+ running task is being raised. Is the priority being
+ raised above that of the running task? */
+ if (uxNewPriority >= pxCurrentTCB->uxPriority) {
+ xYieldRequired = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ /* The priority of the running task is being raised,
+ but the running task must already be the highest
+ priority task able to run so no yield is required. */
+ }
+ } else if (pxTCB == pxCurrentTCB) {
+ /* Setting the priority of the running task down means
+ there may now be another task of higher priority that
+ is ready to execute. */
+ xYieldRequired = pdTRUE;
+ } else {
+ /* Setting the priority of any other task down does not
+ require a yield as the running task must be above the
+ new priority of the task being modified. */
+ }
+
+ /* Remember the ready list the task might be referenced from
+ before its uxPriority member is changed so the
+ taskRESET_READY_PRIORITY() macro can function correctly. */
+ uxPriorityUsedOnEntry = pxTCB->uxPriority;
+
+#if (configUSE_MUTEXES == 1)
+ {
+ /* Only change the priority being used if the task is not
+ currently using an inherited priority. */
+ if (pxTCB->uxBasePriority == pxTCB->uxPriority) {
+ pxTCB->uxPriority = uxNewPriority;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* The base priority gets set whatever. */
+ pxTCB->uxBasePriority = uxNewPriority;
+ }
+#else
+ { pxTCB->uxPriority = uxNewPriority; }
+#endif
+
+ /* Only reset the event list item value if the value is not
+ being used for anything else. */
+ if ((listGET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem)) & taskEVENT_LIST_ITEM_VALUE_IN_USE) == 0UL) {
+ listSET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem),
+ ((TickType_t)configMAX_PRIORITIES - (TickType_t)uxNewPriority)); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* If the task is in the blocked or suspended list we need do
+ nothing more than change its priority variable. However, if
+ the task is in a ready list it needs to be removed and placed
+ in the list appropriate to its new priority. */
+ if (listIS_CONTAINED_WITHIN(&(pxReadyTasksLists[uxPriorityUsedOnEntry]), &(pxTCB->xStateListItem)) != pdFALSE) {
+ /* The task is currently in its ready list - remove before
+ adding it to it's new ready list. As we are in a critical
+ section we can do this even if the scheduler is suspended. */
+ if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0) {
+ /* It is known that the task is in its ready list so
+ there is no need to check again and the port level
+ reset macro can be called directly. */
+ portRESET_READY_PRIORITY(uxPriorityUsedOnEntry, uxTopReadyPriority);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ prvAddTaskToReadyList(pxTCB);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ if (xYieldRequired != pdFALSE) {
+ taskYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Remove compiler warning about unused variables when the port
+ optimised task selection is not being used. */
+ (void)uxPriorityUsedOnEntry;
+ }
+ }
+ taskEXIT_CRITICAL();
+}
#endif /* INCLUDE_vTaskPrioritySet */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_vTaskSuspend == 1 )
-
- void vTaskSuspend( TaskHandle_t xTaskToSuspend )
- {
- TCB_t *pxTCB;
-
- taskENTER_CRITICAL();
- {
- /* If null is passed in here then it is the running task that is
- being suspended. */
- pxTCB = prvGetTCBFromHandle( xTaskToSuspend );
-
- traceTASK_SUSPEND( pxTCB );
-
- /* Remove task from the ready/delayed list and place in the
- suspended list. */
- if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
- {
- taskRESET_READY_PRIORITY( pxTCB->uxPriority );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Is the task waiting on an event also? */
- if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
- {
- ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xStateListItem ) );
-
- #if( configUSE_TASK_NOTIFICATIONS == 1 )
- {
- if( pxTCB->ucNotifyState == taskWAITING_NOTIFICATION )
- {
- /* The task was blocked to wait for a notification, but is
- now suspended, so no notification was received. */
- pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
- }
- }
- #endif
- }
- taskEXIT_CRITICAL();
-
- if( xSchedulerRunning != pdFALSE )
- {
- /* Reset the next expected unblock time in case it referred to the
- task that is now in the Suspended state. */
- taskENTER_CRITICAL();
- {
- prvResetNextTaskUnblockTime();
- }
- taskEXIT_CRITICAL();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- if( pxTCB == pxCurrentTCB )
- {
- if( xSchedulerRunning != pdFALSE )
- {
- /* The current task has just been suspended. */
- configASSERT( uxSchedulerSuspended == 0 );
- portYIELD_WITHIN_API();
- }
- else
- {
- /* The scheduler is not running, but the task that was pointed
- to by pxCurrentTCB has just been suspended and pxCurrentTCB
- must be adjusted to point to a different task. */
- if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks ) /*lint !e931 Right has no side effect, just volatile. */
- {
- /* No other tasks are ready, so set pxCurrentTCB back to
- NULL so when the next task is created pxCurrentTCB will
- be set to point to it no matter what its relative priority
- is. */
- pxCurrentTCB = NULL;
- }
- else
- {
- vTaskSwitchContext();
- }
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
+#if (INCLUDE_vTaskSuspend == 1)
+
+void vTaskSuspend(TaskHandle_t xTaskToSuspend) {
+ TCB_t *pxTCB;
+
+ taskENTER_CRITICAL();
+ {
+ /* If null is passed in here then it is the running task that is
+ being suspended. */
+ pxTCB = prvGetTCBFromHandle(xTaskToSuspend);
+
+ traceTASK_SUSPEND(pxTCB);
+
+ /* Remove task from the ready/delayed list and place in the
+ suspended list. */
+ if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0) {
+ taskRESET_READY_PRIORITY(pxTCB->uxPriority);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Is the task waiting on an event also? */
+ if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL) {
+ (void)uxListRemove(&(pxTCB->xEventListItem));
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ vListInsertEnd(&xSuspendedTaskList, &(pxTCB->xStateListItem));
+
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+ {
+ if (pxTCB->ucNotifyState == taskWAITING_NOTIFICATION) {
+ /* The task was blocked to wait for a notification, but is
+ now suspended, so no notification was received. */
+ pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ }
+ }
+#endif
+ }
+ taskEXIT_CRITICAL();
+
+ if (xSchedulerRunning != pdFALSE) {
+ /* Reset the next expected unblock time in case it referred to the
+ task that is now in the Suspended state. */
+ taskENTER_CRITICAL();
+ { prvResetNextTaskUnblockTime(); }
+ taskEXIT_CRITICAL();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ if (pxTCB == pxCurrentTCB) {
+ if (xSchedulerRunning != pdFALSE) {
+ /* The current task has just been suspended. */
+ configASSERT(uxSchedulerSuspended == 0);
+ portYIELD_WITHIN_API();
+ } else {
+ /* The scheduler is not running, but the task that was pointed
+ to by pxCurrentTCB has just been suspended and pxCurrentTCB
+ must be adjusted to point to a different task. */
+ if (listCURRENT_LIST_LENGTH(&xSuspendedTaskList) == uxCurrentNumberOfTasks) /*lint !e931 Right has no side effect, just volatile. */
+ {
+ /* No other tasks are ready, so set pxCurrentTCB back to
+ NULL so when the next task is created pxCurrentTCB will
+ be set to point to it no matter what its relative priority
+ is. */
+ pxCurrentTCB = NULL;
+ } else {
+ vTaskSwitchContext();
+ }
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+}
#endif /* INCLUDE_vTaskSuspend */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_vTaskSuspend == 1 )
-
- static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask )
- {
- BaseType_t xReturn = pdFALSE;
- const TCB_t * const pxTCB = xTask;
-
- /* Accesses xPendingReadyList so must be called from a critical
- section. */
-
- /* It does not make sense to check if the calling task is suspended. */
- configASSERT( xTask );
-
- /* Is the task being resumed actually in the suspended list? */
- if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xStateListItem ) ) != pdFALSE )
- {
- /* Has the task already been resumed from within an ISR? */
- if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE )
- {
- /* Is it in the suspended list because it is in the Suspended
- state, or because is is blocked with no timeout? */
- if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE ) /*lint !e961. The cast is only redundant when NULL is used. */
- {
- xReturn = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- return xReturn;
- } /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
+#if (INCLUDE_vTaskSuspend == 1)
+
+static BaseType_t prvTaskIsTaskSuspended(const TaskHandle_t xTask) {
+ BaseType_t xReturn = pdFALSE;
+ const TCB_t *const pxTCB = xTask;
+
+ /* Accesses xPendingReadyList so must be called from a critical
+ section. */
+
+ /* It does not make sense to check if the calling task is suspended. */
+ configASSERT(xTask);
+
+ /* Is the task being resumed actually in the suspended list? */
+ if (listIS_CONTAINED_WITHIN(&xSuspendedTaskList, &(pxTCB->xStateListItem)) != pdFALSE) {
+ /* Has the task already been resumed from within an ISR? */
+ if (listIS_CONTAINED_WITHIN(&xPendingReadyList, &(pxTCB->xEventListItem)) == pdFALSE) {
+ /* Is it in the suspended list because it is in the Suspended
+ state, or because is is blocked with no timeout? */
+ if (listIS_CONTAINED_WITHIN(NULL, &(pxTCB->xEventListItem)) != pdFALSE) /*lint !e961. The cast is only redundant when NULL is used. */
+ {
+ xReturn = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return xReturn;
+} /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
#endif /* INCLUDE_vTaskSuspend */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_vTaskSuspend == 1 )
-
- void vTaskResume( TaskHandle_t xTaskToResume )
- {
- TCB_t * const pxTCB = xTaskToResume;
-
- /* It does not make sense to resume the calling task. */
- configASSERT( xTaskToResume );
-
- /* The parameter cannot be NULL as it is impossible to resume the
- currently executing task. */
- if( ( pxTCB != pxCurrentTCB ) && ( pxTCB != NULL ) )
- {
- taskENTER_CRITICAL();
- {
- if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE )
- {
- traceTASK_RESUME( pxTCB );
-
- /* The ready list can be accessed even if the scheduler is
- suspended because this is inside a critical section. */
- ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
- prvAddTaskToReadyList( pxTCB );
-
- /* A higher priority task may have just been resumed. */
- if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
- {
- /* This yield may not cause the task just resumed to run,
- but will leave the lists in the correct state for the
- next yield. */
- taskYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- taskEXIT_CRITICAL();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
+#if (INCLUDE_vTaskSuspend == 1)
+
+void vTaskResume(TaskHandle_t xTaskToResume) {
+ TCB_t *const pxTCB = xTaskToResume;
+
+ /* It does not make sense to resume the calling task. */
+ configASSERT(xTaskToResume);
+
+ /* The parameter cannot be NULL as it is impossible to resume the
+ currently executing task. */
+ if ((pxTCB != pxCurrentTCB) && (pxTCB != NULL)) {
+ taskENTER_CRITICAL();
+ {
+ if (prvTaskIsTaskSuspended(pxTCB) != pdFALSE) {
+ traceTASK_RESUME(pxTCB);
+
+ /* The ready list can be accessed even if the scheduler is
+ suspended because this is inside a critical section. */
+ (void)uxListRemove(&(pxTCB->xStateListItem));
+ prvAddTaskToReadyList(pxTCB);
+
+ /* A higher priority task may have just been resumed. */
+ if (pxTCB->uxPriority >= pxCurrentTCB->uxPriority) {
+ /* This yield may not cause the task just resumed to run,
+ but will leave the lists in the correct state for the
+ next yield. */
+ taskYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ taskEXIT_CRITICAL();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+}
#endif /* INCLUDE_vTaskSuspend */
/*-----------------------------------------------------------*/
-#if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) )
-
- BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume )
- {
- BaseType_t xYieldRequired = pdFALSE;
- TCB_t * const pxTCB = xTaskToResume;
- UBaseType_t uxSavedInterruptStatus;
-
- configASSERT( xTaskToResume );
-
- /* RTOS ports that support interrupt nesting have the concept of a
- maximum system call (or maximum API call) interrupt priority.
- Interrupts that are above the maximum system call priority are keep
- permanently enabled, even when the RTOS kernel is in a critical section,
- but cannot make any calls to FreeRTOS API functions. If configASSERT()
- is defined in FreeRTOSConfig.h then
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
- failure if a FreeRTOS API function is called from an interrupt that has
- been assigned a priority above the configured maximum system call
- priority. Only FreeRTOS functions that end in FromISR can be called
- from interrupts that have been assigned a priority at or (logically)
- below the maximum system call interrupt priority. FreeRTOS maintains a
- separate interrupt safe API to ensure interrupt entry is as fast and as
- simple as possible. More information (albeit Cortex-M specific) is
- provided on the following link:
- https://www.freertos.org/RTOS-Cortex-M3-M4.html */
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
-
- uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- if( prvTaskIsTaskSuspended( pxTCB ) != pdFALSE )
- {
- traceTASK_RESUME_FROM_ISR( pxTCB );
-
- /* Check the ready lists can be accessed. */
- if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
- {
- /* Ready lists can be accessed so move the task from the
- suspended list to the ready list directly. */
- if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
- {
- xYieldRequired = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
- prvAddTaskToReadyList( pxTCB );
- }
- else
- {
- /* The delayed or ready lists cannot be accessed so the task
- is held in the pending ready list until the scheduler is
- unsuspended. */
- vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
-
- return xYieldRequired;
- }
+#if ((INCLUDE_xTaskResumeFromISR == 1) && (INCLUDE_vTaskSuspend == 1))
+
+BaseType_t xTaskResumeFromISR(TaskHandle_t xTaskToResume) {
+ BaseType_t xYieldRequired = pdFALSE;
+ TCB_t *const pxTCB = xTaskToResume;
+ UBaseType_t uxSavedInterruptStatus;
+
+ configASSERT(xTaskToResume);
+
+ /* RTOS ports that support interrupt nesting have the concept of a
+ maximum system call (or maximum API call) interrupt priority.
+ Interrupts that are above the maximum system call priority are keep
+ permanently enabled, even when the RTOS kernel is in a critical section,
+ but cannot make any calls to FreeRTOS API functions. If configASSERT()
+ is defined in FreeRTOSConfig.h then
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+ failure if a FreeRTOS API function is called from an interrupt that has
+ been assigned a priority above the configured maximum system call
+ priority. Only FreeRTOS functions that end in FromISR can be called
+ from interrupts that have been assigned a priority at or (logically)
+ below the maximum system call interrupt priority. FreeRTOS maintains a
+ separate interrupt safe API to ensure interrupt entry is as fast and as
+ simple as possible. More information (albeit Cortex-M specific) is
+ provided on the following link:
+ https://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ if (prvTaskIsTaskSuspended(pxTCB) != pdFALSE) {
+ traceTASK_RESUME_FROM_ISR(pxTCB);
+
+ /* Check the ready lists can be accessed. */
+ if (uxSchedulerSuspended == (UBaseType_t)pdFALSE) {
+ /* Ready lists can be accessed so move the task from the
+ suspended list to the ready list directly. */
+ if (pxTCB->uxPriority >= pxCurrentTCB->uxPriority) {
+ xYieldRequired = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ (void)uxListRemove(&(pxTCB->xStateListItem));
+ prvAddTaskToReadyList(pxTCB);
+ } else {
+ /* The delayed or ready lists cannot be accessed so the task
+ is held in the pending ready list until the scheduler is
+ unsuspended. */
+ vListInsertEnd(&(xPendingReadyList), &(pxTCB->xEventListItem));
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
+
+ return xYieldRequired;
+}
#endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */
/*-----------------------------------------------------------*/
-void vTaskStartScheduler( void )
-{
-BaseType_t xReturn;
-
- /* Add the idle task at the lowest priority. */
- #if( configSUPPORT_STATIC_ALLOCATION == 1 )
- {
- StaticTask_t *pxIdleTaskTCBBuffer = NULL;
- StackType_t *pxIdleTaskStackBuffer = NULL;
- uint32_t ulIdleTaskStackSize;
-
- /* The Idle task is created using user provided RAM - obtain the
- address of the RAM then create the idle task. */
- vApplicationGetIdleTaskMemory( &pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize );
- xIdleTaskHandle = xTaskCreateStatic( prvIdleTask,
- configIDLE_TASK_NAME,
- ulIdleTaskStackSize,
- ( void * ) NULL, /*lint !e961. The cast is not redundant for all compilers. */
- portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
- pxIdleTaskStackBuffer,
- pxIdleTaskTCBBuffer ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
-
- if( xIdleTaskHandle != NULL )
- {
- xReturn = pdPASS;
- }
- else
- {
- xReturn = pdFAIL;
- }
- }
- #else
- {
- /* The Idle task is being created using dynamically allocated RAM. */
- xReturn = xTaskCreate( prvIdleTask,
- configIDLE_TASK_NAME,
- configMINIMAL_STACK_SIZE,
- ( void * ) NULL,
- portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
- &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
- }
- #endif /* configSUPPORT_STATIC_ALLOCATION */
-
- #if ( configUSE_TIMERS == 1 )
- {
- if( xReturn == pdPASS )
- {
- xReturn = xTimerCreateTimerTask();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_TIMERS */
-
- if( xReturn == pdPASS )
- {
- /* freertos_tasks_c_additions_init() should only be called if the user
- definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is
- the only macro called by the function. */
- #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
- {
- freertos_tasks_c_additions_init();
- }
- #endif
-
- /* Interrupts are turned off here, to ensure a tick does not occur
- before or during the call to xPortStartScheduler(). The stacks of
- the created tasks contain a status word with interrupts switched on
- so interrupts will automatically get re-enabled when the first task
- starts to run. */
- portDISABLE_INTERRUPTS();
-
- #if ( configUSE_NEWLIB_REENTRANT == 1 )
- {
- /* Switch Newlib's _impure_ptr variable to point to the _reent
- structure specific to the task that will run first.
- See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
- for additional information. */
- _impure_ptr = &( pxCurrentTCB->xNewLib_reent );
- }
- #endif /* configUSE_NEWLIB_REENTRANT */
-
- xNextTaskUnblockTime = portMAX_DELAY;
- xSchedulerRunning = pdTRUE;
- xTickCount = ( TickType_t ) configINITIAL_TICK_COUNT;
-
- /* If configGENERATE_RUN_TIME_STATS is defined then the following
- macro must be defined to configure the timer/counter used to generate
- the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS
- is set to 0 and the following line fails to build then ensure you do not
- have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your
- FreeRTOSConfig.h file. */
- portCONFIGURE_TIMER_FOR_RUN_TIME_STATS();
-
- traceTASK_SWITCHED_IN();
-
- /* Setting up the timer tick is hardware specific and thus in the
- portable interface. */
- if( xPortStartScheduler() != pdFALSE )
- {
- /* Should not reach here as if the scheduler is running the
- function will not return. */
- }
- else
- {
- /* Should only reach here if a task calls xTaskEndScheduler(). */
- }
- }
- else
- {
- /* This line will only be reached if the kernel could not be started,
- because there was not enough FreeRTOS heap to create the idle task
- or the timer task. */
- configASSERT( xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY );
- }
-
- /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0,
- meaning xIdleTaskHandle is not used anywhere else. */
- ( void ) xIdleTaskHandle;
+void vTaskStartScheduler(void) {
+ BaseType_t xReturn;
+
+/* Add the idle task at the lowest priority. */
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
+ {
+ StaticTask_t *pxIdleTaskTCBBuffer = NULL;
+ StackType_t * pxIdleTaskStackBuffer = NULL;
+ uint32_t ulIdleTaskStackSize;
+
+ /* The Idle task is created using user provided RAM - obtain the
+ address of the RAM then create the idle task. */
+ vApplicationGetIdleTaskMemory(&pxIdleTaskTCBBuffer, &pxIdleTaskStackBuffer, &ulIdleTaskStackSize);
+ xIdleTaskHandle = xTaskCreateStatic(prvIdleTask, configIDLE_TASK_NAME, ulIdleTaskStackSize, (void *)NULL, /*lint !e961. The cast is not redundant for all compilers. */
+ portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
+ pxIdleTaskStackBuffer, pxIdleTaskTCBBuffer); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
+
+ if (xIdleTaskHandle != NULL) {
+ xReturn = pdPASS;
+ } else {
+ xReturn = pdFAIL;
+ }
+ }
+#else
+ {
+ /* The Idle task is being created using dynamically allocated RAM. */
+ xReturn = xTaskCreate(prvIdleTask, configIDLE_TASK_NAME, configMINIMAL_STACK_SIZE, (void *)NULL,
+ portPRIVILEGE_BIT, /* In effect ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), but tskIDLE_PRIORITY is zero. */
+ &xIdleTaskHandle); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
+ }
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+
+#if (configUSE_TIMERS == 1)
+ {
+ if (xReturn == pdPASS) {
+ xReturn = xTimerCreateTimerTask();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_TIMERS */
+
+ if (xReturn == pdPASS) {
+/* freertos_tasks_c_additions_init() should only be called if the user
+definable macro FREERTOS_TASKS_C_ADDITIONS_INIT() is defined, as that is
+the only macro called by the function. */
+#ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
+ { freertos_tasks_c_additions_init(); }
+#endif
+
+ /* Interrupts are turned off here, to ensure a tick does not occur
+ before or during the call to xPortStartScheduler(). The stacks of
+ the created tasks contain a status word with interrupts switched on
+ so interrupts will automatically get re-enabled when the first task
+ starts to run. */
+ portDISABLE_INTERRUPTS();
+
+#if (configUSE_NEWLIB_REENTRANT == 1)
+ {
+ /* Switch Newlib's _impure_ptr variable to point to the _reent
+ structure specific to the task that will run first.
+ See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
+ for additional information. */
+ _impure_ptr = &(pxCurrentTCB->xNewLib_reent);
+ }
+#endif /* configUSE_NEWLIB_REENTRANT */
+
+ xNextTaskUnblockTime = portMAX_DELAY;
+ xSchedulerRunning = pdTRUE;
+ xTickCount = (TickType_t)configINITIAL_TICK_COUNT;
+
+ /* If configGENERATE_RUN_TIME_STATS is defined then the following
+ macro must be defined to configure the timer/counter used to generate
+ the run time counter time base. NOTE: If configGENERATE_RUN_TIME_STATS
+ is set to 0 and the following line fails to build then ensure you do not
+ have portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() defined in your
+ FreeRTOSConfig.h file. */
+ portCONFIGURE_TIMER_FOR_RUN_TIME_STATS();
+
+ traceTASK_SWITCHED_IN();
+
+ /* Setting up the timer tick is hardware specific and thus in the
+ portable interface. */
+ if (xPortStartScheduler() != pdFALSE) {
+ /* Should not reach here as if the scheduler is running the
+ function will not return. */
+ } else {
+ /* Should only reach here if a task calls xTaskEndScheduler(). */
+ }
+ } else {
+ /* This line will only be reached if the kernel could not be started,
+ because there was not enough FreeRTOS heap to create the idle task
+ or the timer task. */
+ configASSERT(xReturn != errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY);
+ }
+
+ /* Prevent compiler warnings if INCLUDE_xTaskGetIdleTaskHandle is set to 0,
+ meaning xIdleTaskHandle is not used anywhere else. */
+ (void)xIdleTaskHandle;
}
/*-----------------------------------------------------------*/
-void vTaskEndScheduler( void )
-{
- /* Stop the scheduler interrupts and call the portable scheduler end
- routine so the original ISRs can be restored if necessary. The port
- layer must ensure interrupts enable bit is left in the correct state. */
- portDISABLE_INTERRUPTS();
- xSchedulerRunning = pdFALSE;
- vPortEndScheduler();
+void vTaskEndScheduler(void) {
+ /* Stop the scheduler interrupts and call the portable scheduler end
+ routine so the original ISRs can be restored if necessary. The port
+ layer must ensure interrupts enable bit is left in the correct state. */
+ portDISABLE_INTERRUPTS();
+ xSchedulerRunning = pdFALSE;
+ vPortEndScheduler();
}
/*----------------------------------------------------------*/
-void vTaskSuspendAll( void )
-{
- /* A critical section is not required as the variable is of type
- BaseType_t. Please read Richard Barry's reply in the following link to a
- post in the FreeRTOS support forum before reporting this as a bug! -
- http://goo.gl/wu4acr */
-
- /* portSOFRWARE_BARRIER() is only implemented for emulated/simulated ports that
- do not otherwise exhibit real time behaviour. */
- portSOFTWARE_BARRIER();
-
- /* The scheduler is suspended if uxSchedulerSuspended is non-zero. An increment
- is used to allow calls to vTaskSuspendAll() to nest. */
- ++uxSchedulerSuspended;
-
- /* Enforces ordering for ports and optimised compilers that may otherwise place
- the above increment elsewhere. */
- portMEMORY_BARRIER();
+void vTaskSuspendAll(void) {
+ /* A critical section is not required as the variable is of type
+ BaseType_t. Please read Richard Barry's reply in the following link to a
+ post in the FreeRTOS support forum before reporting this as a bug! -
+ http://goo.gl/wu4acr */
+
+ /* portSOFRWARE_BARRIER() is only implemented for emulated/simulated ports that
+ do not otherwise exhibit real time behaviour. */
+ portSOFTWARE_BARRIER();
+
+ /* The scheduler is suspended if uxSchedulerSuspended is non-zero. An increment
+ is used to allow calls to vTaskSuspendAll() to nest. */
+ ++uxSchedulerSuspended;
+
+ /* Enforces ordering for ports and optimised compilers that may otherwise place
+ the above increment elsewhere. */
+ portMEMORY_BARRIER();
}
/*----------------------------------------------------------*/
-#if ( configUSE_TICKLESS_IDLE != 0 )
-
- static TickType_t prvGetExpectedIdleTime( void )
- {
- TickType_t xReturn;
- UBaseType_t uxHigherPriorityReadyTasks = pdFALSE;
-
- /* uxHigherPriorityReadyTasks takes care of the case where
- configUSE_PREEMPTION is 0, so there may be tasks above the idle priority
- task that are in the Ready state, even though the idle task is
- running. */
- #if( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 )
- {
- if( uxTopReadyPriority > tskIDLE_PRIORITY )
- {
- uxHigherPriorityReadyTasks = pdTRUE;
- }
- }
- #else
- {
- const UBaseType_t uxLeastSignificantBit = ( UBaseType_t ) 0x01;
-
- /* When port optimised task selection is used the uxTopReadyPriority
- variable is used as a bit map. If bits other than the least
- significant bit are set then there are tasks that have a priority
- above the idle priority that are in the Ready state. This takes
- care of the case where the co-operative scheduler is in use. */
- if( uxTopReadyPriority > uxLeastSignificantBit )
- {
- uxHigherPriorityReadyTasks = pdTRUE;
- }
- }
- #endif
-
- if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY )
- {
- xReturn = 0;
- }
- else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 )
- {
- /* There are other idle priority tasks in the ready state. If
- time slicing is used then the very next tick interrupt must be
- processed. */
- xReturn = 0;
- }
- else if( uxHigherPriorityReadyTasks != pdFALSE )
- {
- /* There are tasks in the Ready state that have a priority above the
- idle priority. This path can only be reached if
- configUSE_PREEMPTION is 0. */
- xReturn = 0;
- }
- else
- {
- xReturn = xNextTaskUnblockTime - xTickCount;
- }
-
- return xReturn;
- }
+#if (configUSE_TICKLESS_IDLE != 0)
+
+static TickType_t prvGetExpectedIdleTime(void) {
+ TickType_t xReturn;
+ UBaseType_t uxHigherPriorityReadyTasks = pdFALSE;
+
+/* uxHigherPriorityReadyTasks takes care of the case where
+configUSE_PREEMPTION is 0, so there may be tasks above the idle priority
+task that are in the Ready state, even though the idle task is
+running. */
+#if (configUSE_PORT_OPTIMISED_TASK_SELECTION == 0)
+ {
+ if (uxTopReadyPriority > tskIDLE_PRIORITY) {
+ uxHigherPriorityReadyTasks = pdTRUE;
+ }
+ }
+#else
+ {
+ const UBaseType_t uxLeastSignificantBit = (UBaseType_t)0x01;
+
+ /* When port optimised task selection is used the uxTopReadyPriority
+ variable is used as a bit map. If bits other than the least
+ significant bit are set then there are tasks that have a priority
+ above the idle priority that are in the Ready state. This takes
+ care of the case where the co-operative scheduler is in use. */
+ if (uxTopReadyPriority > uxLeastSignificantBit) {
+ uxHigherPriorityReadyTasks = pdTRUE;
+ }
+ }
+#endif
+
+ if (pxCurrentTCB->uxPriority > tskIDLE_PRIORITY) {
+ xReturn = 0;
+ } else if (listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[tskIDLE_PRIORITY])) > 1) {
+ /* There are other idle priority tasks in the ready state. If
+ time slicing is used then the very next tick interrupt must be
+ processed. */
+ xReturn = 0;
+ } else if (uxHigherPriorityReadyTasks != pdFALSE) {
+ /* There are tasks in the Ready state that have a priority above the
+ idle priority. This path can only be reached if
+ configUSE_PREEMPTION is 0. */
+ xReturn = 0;
+ } else {
+ xReturn = xNextTaskUnblockTime - xTickCount;
+ }
+
+ return xReturn;
+}
#endif /* configUSE_TICKLESS_IDLE */
/*----------------------------------------------------------*/
-BaseType_t xTaskResumeAll( void )
-{
-TCB_t *pxTCB = NULL;
-BaseType_t xAlreadyYielded = pdFALSE;
-
- /* If uxSchedulerSuspended is zero then this function does not match a
- previous call to vTaskSuspendAll(). */
- configASSERT( uxSchedulerSuspended );
-
- /* It is possible that an ISR caused a task to be removed from an event
- list while the scheduler was suspended. If this was the case then the
- removed task will have been added to the xPendingReadyList. Once the
- scheduler has been resumed it is safe to move all the pending ready
- tasks from this list into their appropriate ready list. */
- taskENTER_CRITICAL();
- {
- --uxSchedulerSuspended;
-
- if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
- {
- if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U )
- {
- /* Move any readied tasks from the pending list into the
- appropriate ready list. */
- while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE )
- {
- pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
- ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
- ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
- prvAddTaskToReadyList( pxTCB );
-
- /* If the moved task has a priority higher than the current
- task then a yield must be performed. */
- if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
- {
- xYieldPending = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- if( pxTCB != NULL )
- {
- /* A task was unblocked while the scheduler was suspended,
- which may have prevented the next unblock time from being
- re-calculated, in which case re-calculate it now. Mainly
- important for low power tickless implementations, where
- this can prevent an unnecessary exit from low power
- state. */
- prvResetNextTaskUnblockTime();
- }
-
- /* If any ticks occurred while the scheduler was suspended then
- they should be processed now. This ensures the tick count does
- not slip, and that any delayed tasks are resumed at the correct
- time. */
- {
- TickType_t xPendedCounts = xPendedTicks; /* Non-volatile copy. */
-
- if( xPendedCounts > ( TickType_t ) 0U )
- {
- do
- {
- if( xTaskIncrementTick() != pdFALSE )
- {
- xYieldPending = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- --xPendedCounts;
- } while( xPendedCounts > ( TickType_t ) 0U );
-
- xPendedTicks = 0;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- if( xYieldPending != pdFALSE )
- {
- #if( configUSE_PREEMPTION != 0 )
- {
- xAlreadyYielded = pdTRUE;
- }
- #endif
- taskYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- taskEXIT_CRITICAL();
-
- return xAlreadyYielded;
+BaseType_t xTaskResumeAll(void) {
+ TCB_t * pxTCB = NULL;
+ BaseType_t xAlreadyYielded = pdFALSE;
+
+ /* If uxSchedulerSuspended is zero then this function does not match a
+ previous call to vTaskSuspendAll(). */
+ configASSERT(uxSchedulerSuspended);
+
+ /* It is possible that an ISR caused a task to be removed from an event
+ list while the scheduler was suspended. If this was the case then the
+ removed task will have been added to the xPendingReadyList. Once the
+ scheduler has been resumed it is safe to move all the pending ready
+ tasks from this list into their appropriate ready list. */
+ taskENTER_CRITICAL();
+ {
+ --uxSchedulerSuspended;
+
+ if (uxSchedulerSuspended == (UBaseType_t)pdFALSE) {
+ if (uxCurrentNumberOfTasks > (UBaseType_t)0U) {
+ /* Move any readied tasks from the pending list into the
+ appropriate ready list. */
+ while (listLIST_IS_EMPTY(&xPendingReadyList) == pdFALSE) {
+ pxTCB = listGET_OWNER_OF_HEAD_ENTRY((&xPendingReadyList)); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the
+ type of the pointer stored and retrieved is the same. */
+ (void)uxListRemove(&(pxTCB->xEventListItem));
+ (void)uxListRemove(&(pxTCB->xStateListItem));
+ prvAddTaskToReadyList(pxTCB);
+
+ /* If the moved task has a priority higher than the current
+ task then a yield must be performed. */
+ if (pxTCB->uxPriority >= pxCurrentTCB->uxPriority) {
+ xYieldPending = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ if (pxTCB != NULL) {
+ /* A task was unblocked while the scheduler was suspended,
+ which may have prevented the next unblock time from being
+ re-calculated, in which case re-calculate it now. Mainly
+ important for low power tickless implementations, where
+ this can prevent an unnecessary exit from low power
+ state. */
+ prvResetNextTaskUnblockTime();
+ }
+
+ /* If any ticks occurred while the scheduler was suspended then
+ they should be processed now. This ensures the tick count does
+ not slip, and that any delayed tasks are resumed at the correct
+ time. */
+ {
+ TickType_t xPendedCounts = xPendedTicks; /* Non-volatile copy. */
+
+ if (xPendedCounts > (TickType_t)0U) {
+ do {
+ if (xTaskIncrementTick() != pdFALSE) {
+ xYieldPending = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ --xPendedCounts;
+ } while (xPendedCounts > (TickType_t)0U);
+
+ xPendedTicks = 0;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ if (xYieldPending != pdFALSE) {
+#if (configUSE_PREEMPTION != 0)
+ { xAlreadyYielded = pdTRUE; }
+#endif
+ taskYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return xAlreadyYielded;
}
/*-----------------------------------------------------------*/
-TickType_t xTaskGetTickCount( void )
-{
-TickType_t xTicks;
+TickType_t xTaskGetTickCount(void) {
+ TickType_t xTicks;
- /* Critical section required if running on a 16 bit processor. */
- portTICK_TYPE_ENTER_CRITICAL();
- {
- xTicks = xTickCount;
- }
- portTICK_TYPE_EXIT_CRITICAL();
+ /* Critical section required if running on a 16 bit processor. */
+ portTICK_TYPE_ENTER_CRITICAL();
+ { xTicks = xTickCount; }
+ portTICK_TYPE_EXIT_CRITICAL();
- return xTicks;
+ return xTicks;
}
/*-----------------------------------------------------------*/
-TickType_t xTaskGetTickCountFromISR( void )
-{
-TickType_t xReturn;
-UBaseType_t uxSavedInterruptStatus;
-
- /* RTOS ports that support interrupt nesting have the concept of a maximum
- system call (or maximum API call) interrupt priority. Interrupts that are
- above the maximum system call priority are kept permanently enabled, even
- when the RTOS kernel is in a critical section, but cannot make any calls to
- FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
- then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
- failure if a FreeRTOS API function is called from an interrupt that has been
- assigned a priority above the configured maximum system call priority.
- Only FreeRTOS functions that end in FromISR can be called from interrupts
- that have been assigned a priority at or (logically) below the maximum
- system call interrupt priority. FreeRTOS maintains a separate interrupt
- safe API to ensure interrupt entry is as fast and as simple as possible.
- More information (albeit Cortex-M specific) is provided on the following
- link: https://www.freertos.org/RTOS-Cortex-M3-M4.html */
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
-
- uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR();
- {
- xReturn = xTickCount;
- }
- portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
-
- return xReturn;
+TickType_t xTaskGetTickCountFromISR(void) {
+ TickType_t xReturn;
+ UBaseType_t uxSavedInterruptStatus;
+
+ /* RTOS ports that support interrupt nesting have the concept of a maximum
+ system call (or maximum API call) interrupt priority. Interrupts that are
+ above the maximum system call priority are kept permanently enabled, even
+ when the RTOS kernel is in a critical section, but cannot make any calls to
+ FreeRTOS API functions. If configASSERT() is defined in FreeRTOSConfig.h
+ then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+ failure if a FreeRTOS API function is called from an interrupt that has been
+ assigned a priority above the configured maximum system call priority.
+ Only FreeRTOS functions that end in FromISR can be called from interrupts
+ that have been assigned a priority at or (logically) below the maximum
+ system call interrupt priority. FreeRTOS maintains a separate interrupt
+ safe API to ensure interrupt entry is as fast and as simple as possible.
+ More information (albeit Cortex-M specific) is provided on the following
+ link: https://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR();
+ { xReturn = xTickCount; }
+ portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-UBaseType_t uxTaskGetNumberOfTasks( void )
-{
- /* A critical section is not required because the variables are of type
- BaseType_t. */
- return uxCurrentNumberOfTasks;
+UBaseType_t uxTaskGetNumberOfTasks(void) {
+ /* A critical section is not required because the variables are of type
+ BaseType_t. */
+ return uxCurrentNumberOfTasks;
}
/*-----------------------------------------------------------*/
-char *pcTaskGetName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+char *pcTaskGetName(TaskHandle_t xTaskToQuery) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
{
-TCB_t *pxTCB;
+ TCB_t *pxTCB;
- /* If null is passed in here then the name of the calling task is being
- queried. */
- pxTCB = prvGetTCBFromHandle( xTaskToQuery );
- configASSERT( pxTCB );
- return &( pxTCB->pcTaskName[ 0 ] );
+ /* If null is passed in here then the name of the calling task is being
+ queried. */
+ pxTCB = prvGetTCBFromHandle(xTaskToQuery);
+ configASSERT(pxTCB);
+ return &(pxTCB->pcTaskName[0]);
}
/*-----------------------------------------------------------*/
-#if ( INCLUDE_xTaskGetHandle == 1 )
-
- static TCB_t *prvSearchForNameWithinSingleList( List_t *pxList, const char pcNameToQuery[] )
- {
- TCB_t *pxNextTCB, *pxFirstTCB, *pxReturn = NULL;
- UBaseType_t x;
- char cNextChar;
- BaseType_t xBreakLoop;
-
- /* This function is called with the scheduler suspended. */
-
- if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 )
- {
- listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
-
- do
- {
- listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
-
- /* Check each character in the name looking for a match or
- mismatch. */
- xBreakLoop = pdFALSE;
- for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ )
- {
- cNextChar = pxNextTCB->pcTaskName[ x ];
-
- if( cNextChar != pcNameToQuery[ x ] )
- {
- /* Characters didn't match. */
- xBreakLoop = pdTRUE;
- }
- else if( cNextChar == ( char ) 0x00 )
- {
- /* Both strings terminated, a match must have been
- found. */
- pxReturn = pxNextTCB;
- xBreakLoop = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- if( xBreakLoop != pdFALSE )
- {
- break;
- }
- }
-
- if( pxReturn != NULL )
- {
- /* The handle has been found. */
- break;
- }
-
- } while( pxNextTCB != pxFirstTCB );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- return pxReturn;
- }
+#if (INCLUDE_xTaskGetHandle == 1)
+
+static TCB_t *prvSearchForNameWithinSingleList(List_t *pxList, const char pcNameToQuery[]) {
+ TCB_t * pxNextTCB, *pxFirstTCB, *pxReturn = NULL;
+ UBaseType_t x;
+ char cNextChar;
+ BaseType_t xBreakLoop;
+
+ /* This function is called with the scheduler suspended. */
+
+ if (listCURRENT_LIST_LENGTH(pxList) > (UBaseType_t)0) {
+ listGET_OWNER_OF_NEXT_ENTRY(
+ pxFirstTCB,
+ pxList); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
+
+ do {
+ listGET_OWNER_OF_NEXT_ENTRY(pxNextTCB, pxList); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the
+ pointer stored and retrieved is the same. */
+
+ /* Check each character in the name looking for a match or
+ mismatch. */
+ xBreakLoop = pdFALSE;
+ for (x = (UBaseType_t)0; x < (UBaseType_t)configMAX_TASK_NAME_LEN; x++) {
+ cNextChar = pxNextTCB->pcTaskName[x];
+
+ if (cNextChar != pcNameToQuery[x]) {
+ /* Characters didn't match. */
+ xBreakLoop = pdTRUE;
+ } else if (cNextChar == (char)0x00) {
+ /* Both strings terminated, a match must have been
+ found. */
+ pxReturn = pxNextTCB;
+ xBreakLoop = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ if (xBreakLoop != pdFALSE) {
+ break;
+ }
+ }
+
+ if (pxReturn != NULL) {
+ /* The handle has been found. */
+ break;
+ }
+
+ } while (pxNextTCB != pxFirstTCB);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return pxReturn;
+}
#endif /* INCLUDE_xTaskGetHandle */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_xTaskGetHandle == 1 )
-
- TaskHandle_t xTaskGetHandle( const char *pcNameToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- {
- UBaseType_t uxQueue = configMAX_PRIORITIES;
- TCB_t* pxTCB;
-
- /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */
- configASSERT( strlen( pcNameToQuery ) < configMAX_TASK_NAME_LEN );
-
- vTaskSuspendAll();
- {
- /* Search the ready lists. */
- do
- {
- uxQueue--;
- pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) &( pxReadyTasksLists[ uxQueue ] ), pcNameToQuery );
-
- if( pxTCB != NULL )
- {
- /* Found the handle. */
- break;
- }
-
- } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
-
- /* Search the delayed lists. */
- if( pxTCB == NULL )
- {
- pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxDelayedTaskList, pcNameToQuery );
- }
-
- if( pxTCB == NULL )
- {
- pxTCB = prvSearchForNameWithinSingleList( ( List_t * ) pxOverflowDelayedTaskList, pcNameToQuery );
- }
-
- #if ( INCLUDE_vTaskSuspend == 1 )
- {
- if( pxTCB == NULL )
- {
- /* Search the suspended list. */
- pxTCB = prvSearchForNameWithinSingleList( &xSuspendedTaskList, pcNameToQuery );
- }
- }
- #endif
-
- #if( INCLUDE_vTaskDelete == 1 )
- {
- if( pxTCB == NULL )
- {
- /* Search the deleted list. */
- pxTCB = prvSearchForNameWithinSingleList( &xTasksWaitingTermination, pcNameToQuery );
- }
- }
- #endif
- }
- ( void ) xTaskResumeAll();
-
- return pxTCB;
- }
+#if (INCLUDE_xTaskGetHandle == 1)
+
+TaskHandle_t xTaskGetHandle(const char *pcNameToQuery) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+{
+ UBaseType_t uxQueue = configMAX_PRIORITIES;
+ TCB_t * pxTCB;
+
+ /* Task names will be truncated to configMAX_TASK_NAME_LEN - 1 bytes. */
+ configASSERT(strlen(pcNameToQuery) < configMAX_TASK_NAME_LEN);
+
+ vTaskSuspendAll();
+ {
+ /* Search the ready lists. */
+ do {
+ uxQueue--;
+ pxTCB = prvSearchForNameWithinSingleList((List_t *)&(pxReadyTasksLists[uxQueue]), pcNameToQuery);
+
+ if (pxTCB != NULL) {
+ /* Found the handle. */
+ break;
+ }
+
+ } while (uxQueue > (UBaseType_t)tskIDLE_PRIORITY); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+
+ /* Search the delayed lists. */
+ if (pxTCB == NULL) {
+ pxTCB = prvSearchForNameWithinSingleList((List_t *)pxDelayedTaskList, pcNameToQuery);
+ }
+
+ if (pxTCB == NULL) {
+ pxTCB = prvSearchForNameWithinSingleList((List_t *)pxOverflowDelayedTaskList, pcNameToQuery);
+ }
+
+#if (INCLUDE_vTaskSuspend == 1)
+ {
+ if (pxTCB == NULL) {
+ /* Search the suspended list. */
+ pxTCB = prvSearchForNameWithinSingleList(&xSuspendedTaskList, pcNameToQuery);
+ }
+ }
+#endif
+
+#if (INCLUDE_vTaskDelete == 1)
+ {
+ if (pxTCB == NULL) {
+ /* Search the deleted list. */
+ pxTCB = prvSearchForNameWithinSingleList(&xTasksWaitingTermination, pcNameToQuery);
+ }
+ }
+#endif
+ }
+ (void)xTaskResumeAll();
+
+ return pxTCB;
+}
#endif /* INCLUDE_xTaskGetHandle */
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
-
- UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime )
- {
- UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES;
-
- vTaskSuspendAll();
- {
- /* Is there a space in the array for each task in the system? */
- if( uxArraySize >= uxCurrentNumberOfTasks )
- {
- /* Fill in an TaskStatus_t structure with information on each
- task in the Ready state. */
- do
- {
- uxQueue--;
- uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady );
-
- } while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
-
- /* Fill in an TaskStatus_t structure with information on each
- task in the Blocked state. */
- uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked );
- uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked );
-
- #if( INCLUDE_vTaskDelete == 1 )
- {
- /* Fill in an TaskStatus_t structure with information on
- each task that has been deleted but not yet cleaned up. */
- uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted );
- }
- #endif
-
- #if ( INCLUDE_vTaskSuspend == 1 )
- {
- /* Fill in an TaskStatus_t structure with information on
- each task in the Suspended state. */
- uxTask += prvListTasksWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended );
- }
- #endif
-
- #if ( configGENERATE_RUN_TIME_STATS == 1)
- {
- if( pulTotalRunTime != NULL )
- {
- #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
- portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) );
- #else
- *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
- #endif
- }
- }
- #else
- {
- if( pulTotalRunTime != NULL )
- {
- *pulTotalRunTime = 0;
- }
- }
- #endif
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- ( void ) xTaskResumeAll();
-
- return uxTask;
- }
+#if (configUSE_TRACE_FACILITY == 1)
+
+UBaseType_t uxTaskGetSystemState(TaskStatus_t *const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t *const pulTotalRunTime) {
+ UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES;
+
+ vTaskSuspendAll();
+ {
+ /* Is there a space in the array for each task in the system? */
+ if (uxArraySize >= uxCurrentNumberOfTasks) {
+ /* Fill in an TaskStatus_t structure with information on each
+ task in the Ready state. */
+ do {
+ uxQueue--;
+ uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), &(pxReadyTasksLists[uxQueue]), eReady);
+
+ } while (uxQueue > (UBaseType_t)tskIDLE_PRIORITY); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+
+ /* Fill in an TaskStatus_t structure with information on each
+ task in the Blocked state. */
+ uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), (List_t *)pxDelayedTaskList, eBlocked);
+ uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), (List_t *)pxOverflowDelayedTaskList, eBlocked);
+
+#if (INCLUDE_vTaskDelete == 1)
+ {
+ /* Fill in an TaskStatus_t structure with information on
+ each task that has been deleted but not yet cleaned up. */
+ uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), &xTasksWaitingTermination, eDeleted);
+ }
+#endif
+
+#if (INCLUDE_vTaskSuspend == 1)
+ {
+ /* Fill in an TaskStatus_t structure with information on
+ each task in the Suspended state. */
+ uxTask += prvListTasksWithinSingleList(&(pxTaskStatusArray[uxTask]), &xSuspendedTaskList, eSuspended);
+ }
+#endif
+
+#if (configGENERATE_RUN_TIME_STATS == 1)
+ {
+ if (pulTotalRunTime != NULL) {
+#ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
+ portALT_GET_RUN_TIME_COUNTER_VALUE((*pulTotalRunTime));
+#else
+ *pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
+#endif
+ }
+ }
+#else
+ {
+ if (pulTotalRunTime != NULL) {
+ *pulTotalRunTime = 0;
+ }
+ }
+#endif
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ (void)xTaskResumeAll();
+
+ return uxTask;
+}
#endif /* configUSE_TRACE_FACILITY */
/*----------------------------------------------------------*/
-#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 )
+#if (INCLUDE_xTaskGetIdleTaskHandle == 1)
- TaskHandle_t xTaskGetIdleTaskHandle( void )
- {
- /* If xTaskGetIdleTaskHandle() is called before the scheduler has been
- started, then xIdleTaskHandle will be NULL. */
- configASSERT( ( xIdleTaskHandle != NULL ) );
- return xIdleTaskHandle;
- }
+TaskHandle_t xTaskGetIdleTaskHandle(void) {
+ /* If xTaskGetIdleTaskHandle() is called before the scheduler has been
+ started, then xIdleTaskHandle will be NULL. */
+ configASSERT((xIdleTaskHandle != NULL));
+ return xIdleTaskHandle;
+}
#endif /* INCLUDE_xTaskGetIdleTaskHandle */
/*----------------------------------------------------------*/
@@ -2591,790 +2258,689 @@ TCB_t *pxTCB;
This is to ensure vTaskStepTick() is available when user defined low power mode
implementations require configUSE_TICKLESS_IDLE to be set to a value other than
1. */
-#if ( configUSE_TICKLESS_IDLE != 0 )
-
- void vTaskStepTick( const TickType_t xTicksToJump )
- {
- /* Correct the tick count value after a period during which the tick
- was suppressed. Note this does *not* call the tick hook function for
- each stepped tick. */
- configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime );
- xTickCount += xTicksToJump;
- traceINCREASE_TICK_COUNT( xTicksToJump );
- }
+#if (configUSE_TICKLESS_IDLE != 0)
+
+void vTaskStepTick(const TickType_t xTicksToJump) {
+ /* Correct the tick count value after a period during which the tick
+ was suppressed. Note this does *not* call the tick hook function for
+ each stepped tick. */
+ configASSERT((xTickCount + xTicksToJump) <= xNextTaskUnblockTime);
+ xTickCount += xTicksToJump;
+ traceINCREASE_TICK_COUNT(xTicksToJump);
+}
#endif /* configUSE_TICKLESS_IDLE */
/*----------------------------------------------------------*/
-BaseType_t xTaskCatchUpTicks( TickType_t xTicksToCatchUp )
-{
-BaseType_t xYieldRequired = pdFALSE;
+BaseType_t xTaskCatchUpTicks(TickType_t xTicksToCatchUp) {
+ BaseType_t xYieldRequired = pdFALSE;
- /* Must not be called with the scheduler suspended as the implementation
- relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */
- configASSERT( uxSchedulerSuspended == 0 );
+ /* Must not be called with the scheduler suspended as the implementation
+ relies on xPendedTicks being wound down to 0 in xTaskResumeAll(). */
+ configASSERT(uxSchedulerSuspended == 0);
- /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when
- the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */
- vTaskSuspendAll();
- xPendedTicks += xTicksToCatchUp;
- xYieldRequired = xTaskResumeAll();
+ /* Use xPendedTicks to mimic xTicksToCatchUp number of ticks occurring when
+ the scheduler is suspended so the ticks are executed in xTaskResumeAll(). */
+ vTaskSuspendAll();
+ xPendedTicks += xTicksToCatchUp;
+ xYieldRequired = xTaskResumeAll();
- return xYieldRequired;
+ return xYieldRequired;
}
/*----------------------------------------------------------*/
-#if ( INCLUDE_xTaskAbortDelay == 1 )
-
- BaseType_t xTaskAbortDelay( TaskHandle_t xTask )
- {
- TCB_t *pxTCB = xTask;
- BaseType_t xReturn;
-
- configASSERT( pxTCB );
-
- vTaskSuspendAll();
- {
- /* A task can only be prematurely removed from the Blocked state if
- it is actually in the Blocked state. */
- if( eTaskGetState( xTask ) == eBlocked )
- {
- xReturn = pdPASS;
-
- /* Remove the reference to the task from the blocked list. An
- interrupt won't touch the xStateListItem because the
- scheduler is suspended. */
- ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
-
- /* Is the task waiting on an event also? If so remove it from
- the event list too. Interrupts can touch the event list item,
- even though the scheduler is suspended, so a critical section
- is used. */
- taskENTER_CRITICAL();
- {
- if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
- {
- ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
-
- /* This lets the task know it was forcibly removed from the
- blocked state so it should not re-evaluate its block time and
- then block again. */
- pxTCB->ucDelayAborted = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- taskEXIT_CRITICAL();
-
- /* Place the unblocked task into the appropriate ready list. */
- prvAddTaskToReadyList( pxTCB );
-
- /* A task being unblocked cannot cause an immediate context
- switch if preemption is turned off. */
- #if ( configUSE_PREEMPTION == 1 )
- {
- /* Preemption is on, but a context switch should only be
- performed if the unblocked task has a priority that is
- equal to or higher than the currently executing task. */
- if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
- {
- /* Pend the yield to be performed when the scheduler
- is unsuspended. */
- xYieldPending = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_PREEMPTION */
- }
- else
- {
- xReturn = pdFAIL;
- }
- }
- ( void ) xTaskResumeAll();
-
- return xReturn;
- }
+#if (INCLUDE_xTaskAbortDelay == 1)
+
+BaseType_t xTaskAbortDelay(TaskHandle_t xTask) {
+ TCB_t * pxTCB = xTask;
+ BaseType_t xReturn;
+
+ configASSERT(pxTCB);
+
+ vTaskSuspendAll();
+ {
+ /* A task can only be prematurely removed from the Blocked state if
+ it is actually in the Blocked state. */
+ if (eTaskGetState(xTask) == eBlocked) {
+ xReturn = pdPASS;
+
+ /* Remove the reference to the task from the blocked list. An
+ interrupt won't touch the xStateListItem because the
+ scheduler is suspended. */
+ (void)uxListRemove(&(pxTCB->xStateListItem));
+
+ /* Is the task waiting on an event also? If so remove it from
+ the event list too. Interrupts can touch the event list item,
+ even though the scheduler is suspended, so a critical section
+ is used. */
+ taskENTER_CRITICAL();
+ {
+ if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL) {
+ (void)uxListRemove(&(pxTCB->xEventListItem));
+
+ /* This lets the task know it was forcibly removed from the
+ blocked state so it should not re-evaluate its block time and
+ then block again. */
+ pxTCB->ucDelayAborted = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ /* Place the unblocked task into the appropriate ready list. */
+ prvAddTaskToReadyList(pxTCB);
+
+/* A task being unblocked cannot cause an immediate context
+switch if preemption is turned off. */
+#if (configUSE_PREEMPTION == 1)
+ {
+ /* Preemption is on, but a context switch should only be
+ performed if the unblocked task has a priority that is
+ equal to or higher than the currently executing task. */
+ if (pxTCB->uxPriority > pxCurrentTCB->uxPriority) {
+ /* Pend the yield to be performed when the scheduler
+ is unsuspended. */
+ xYieldPending = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_PREEMPTION */
+ } else {
+ xReturn = pdFAIL;
+ }
+ }
+ (void)xTaskResumeAll();
+
+ return xReturn;
+}
#endif /* INCLUDE_xTaskAbortDelay */
/*----------------------------------------------------------*/
-BaseType_t xTaskIncrementTick( void )
-{
-TCB_t * pxTCB;
-TickType_t xItemValue;
-BaseType_t xSwitchRequired = pdFALSE;
-
- /* Called by the portable layer each time a tick interrupt occurs.
- Increments the tick then checks to see if the new tick value will cause any
- tasks to be unblocked. */
- traceTASK_INCREMENT_TICK( xTickCount );
- if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
- {
- /* Minor optimisation. The tick count cannot change in this
- block. */
- const TickType_t xConstTickCount = xTickCount + ( TickType_t ) 1;
-
- /* Increment the RTOS tick, switching the delayed and overflowed
- delayed lists if it wraps to 0. */
- xTickCount = xConstTickCount;
-
- if( xConstTickCount == ( TickType_t ) 0U ) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */
- {
- taskSWITCH_DELAYED_LISTS();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* See if this tick has made a timeout expire. Tasks are stored in
- the queue in the order of their wake time - meaning once one task
- has been found whose block time has not expired there is no need to
- look any further down the list. */
- if( xConstTickCount >= xNextTaskUnblockTime )
- {
- for( ;; )
- {
- if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
- {
- /* The delayed list is empty. Set xNextTaskUnblockTime
- to the maximum possible value so it is extremely
- unlikely that the
- if( xTickCount >= xNextTaskUnblockTime ) test will pass
- next time through. */
- xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
- break;
- }
- else
- {
- /* The delayed list is not empty, get the value of the
- item at the head of the delayed list. This is the time
- at which the task at the head of the delayed list must
- be removed from the Blocked state. */
- pxTCB = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
- xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xStateListItem ) );
-
- if( xConstTickCount < xItemValue )
- {
- /* It is not time to unblock this item yet, but the
- item value is the time at which the task at the head
- of the blocked list must be removed from the Blocked
- state - so record the item value in
- xNextTaskUnblockTime. */
- xNextTaskUnblockTime = xItemValue;
- break; /*lint !e9011 Code structure here is deedmed easier to understand with multiple breaks. */
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* It is time to remove the item from the Blocked state. */
- ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
-
- /* Is the task waiting on an event also? If so remove
- it from the event list. */
- if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
- {
- ( void ) uxListRemove( &( pxTCB->xEventListItem ) );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Place the unblocked task into the appropriate ready
- list. */
- prvAddTaskToReadyList( pxTCB );
-
- /* A task being unblocked cannot cause an immediate
- context switch if preemption is turned off. */
- #if ( configUSE_PREEMPTION == 1 )
- {
- /* Preemption is on, but a context switch should
- only be performed if the unblocked task has a
- priority that is equal to or higher than the
- currently executing task. */
- if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
- {
- xSwitchRequired = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_PREEMPTION */
- }
- }
- }
-
- /* Tasks of equal priority to the currently running task will share
- processing time (time slice) if preemption is on, and the application
- writer has not explicitly turned time slicing off. */
- #if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) )
- {
- if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 )
- {
- xSwitchRequired = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */
-
- #if ( configUSE_TICK_HOOK == 1 )
- {
- /* Guard against the tick hook being called when the pended tick
- count is being unwound (when the scheduler is being unlocked). */
- if( xPendedTicks == ( TickType_t ) 0 )
- {
- vApplicationTickHook();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_TICK_HOOK */
-
- #if ( configUSE_PREEMPTION == 1 )
- {
- if( xYieldPending != pdFALSE )
- {
- xSwitchRequired = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_PREEMPTION */
- }
- else
- {
- ++xPendedTicks;
-
- /* The tick hook gets called at regular intervals, even if the
- scheduler is locked. */
- #if ( configUSE_TICK_HOOK == 1 )
- {
- vApplicationTickHook();
- }
- #endif
- }
-
- return xSwitchRequired;
+BaseType_t xTaskIncrementTick(void) {
+ TCB_t * pxTCB;
+ TickType_t xItemValue;
+ BaseType_t xSwitchRequired = pdFALSE;
+
+ /* Called by the portable layer each time a tick interrupt occurs.
+ Increments the tick then checks to see if the new tick value will cause any
+ tasks to be unblocked. */
+ traceTASK_INCREMENT_TICK(xTickCount);
+ if (uxSchedulerSuspended == (UBaseType_t)pdFALSE) {
+ /* Minor optimisation. The tick count cannot change in this
+ block. */
+ const TickType_t xConstTickCount = xTickCount + (TickType_t)1;
+
+ /* Increment the RTOS tick, switching the delayed and overflowed
+ delayed lists if it wraps to 0. */
+ xTickCount = xConstTickCount;
+
+ if (xConstTickCount == (TickType_t)0U) /*lint !e774 'if' does not always evaluate to false as it is looking for an overflow. */
+ {
+ taskSWITCH_DELAYED_LISTS();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* See if this tick has made a timeout expire. Tasks are stored in
+ the queue in the order of their wake time - meaning once one task
+ has been found whose block time has not expired there is no need to
+ look any further down the list. */
+ if (xConstTickCount >= xNextTaskUnblockTime) {
+ for (;;) {
+ if (listLIST_IS_EMPTY(pxDelayedTaskList) != pdFALSE) {
+ /* The delayed list is empty. Set xNextTaskUnblockTime
+ to the maximum possible value so it is extremely
+ unlikely that the
+ if( xTickCount >= xNextTaskUnblockTime ) test will pass
+ next time through. */
+ xNextTaskUnblockTime = portMAX_DELAY; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+ break;
+ } else {
+ /* The delayed list is not empty, get the value of the
+ item at the head of the delayed list. This is the time
+ at which the task at the head of the delayed list must
+ be removed from the Blocked state. */
+ pxTCB = listGET_OWNER_OF_HEAD_ENTRY(pxDelayedTaskList); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the
+ type of the pointer stored and retrieved is the same. */
+ xItemValue = listGET_LIST_ITEM_VALUE(&(pxTCB->xStateListItem));
+
+ if (xConstTickCount < xItemValue) {
+ /* It is not time to unblock this item yet, but the
+ item value is the time at which the task at the head
+ of the blocked list must be removed from the Blocked
+ state - so record the item value in
+ xNextTaskUnblockTime. */
+ xNextTaskUnblockTime = xItemValue;
+ break; /*lint !e9011 Code structure here is deedmed easier to understand with multiple breaks. */
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* It is time to remove the item from the Blocked state. */
+ (void)uxListRemove(&(pxTCB->xStateListItem));
+
+ /* Is the task waiting on an event also? If so remove
+ it from the event list. */
+ if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL) {
+ (void)uxListRemove(&(pxTCB->xEventListItem));
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Place the unblocked task into the appropriate ready
+ list. */
+ prvAddTaskToReadyList(pxTCB);
+
+/* A task being unblocked cannot cause an immediate
+context switch if preemption is turned off. */
+#if (configUSE_PREEMPTION == 1)
+ {
+ /* Preemption is on, but a context switch should
+ only be performed if the unblocked task has a
+ priority that is equal to or higher than the
+ currently executing task. */
+ if (pxTCB->uxPriority >= pxCurrentTCB->uxPriority) {
+ xSwitchRequired = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_PREEMPTION */
+ }
+ }
+ }
+
+/* Tasks of equal priority to the currently running task will share
+processing time (time slice) if preemption is on, and the application
+writer has not explicitly turned time slicing off. */
+#if ((configUSE_PREEMPTION == 1) && (configUSE_TIME_SLICING == 1))
+ {
+ if (listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[pxCurrentTCB->uxPriority])) > (UBaseType_t)1) {
+ xSwitchRequired = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */
+
+#if (configUSE_TICK_HOOK == 1)
+ {
+ /* Guard against the tick hook being called when the pended tick
+ count is being unwound (when the scheduler is being unlocked). */
+ if (xPendedTicks == (TickType_t)0) {
+ vApplicationTickHook();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_TICK_HOOK */
+
+#if (configUSE_PREEMPTION == 1)
+ {
+ if (xYieldPending != pdFALSE) {
+ xSwitchRequired = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_PREEMPTION */
+ } else {
+ ++xPendedTicks;
+
+/* The tick hook gets called at regular intervals, even if the
+scheduler is locked. */
+#if (configUSE_TICK_HOOK == 1)
+ { vApplicationTickHook(); }
+#endif
+ }
+
+ return xSwitchRequired;
}
/*-----------------------------------------------------------*/
-#if ( configUSE_APPLICATION_TASK_TAG == 1 )
-
- void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction )
- {
- TCB_t *xTCB;
-
- /* If xTask is NULL then it is the task hook of the calling task that is
- getting set. */
- if( xTask == NULL )
- {
- xTCB = ( TCB_t * ) pxCurrentTCB;
- }
- else
- {
- xTCB = xTask;
- }
-
- /* Save the hook function in the TCB. A critical section is required as
- the value can be accessed from an interrupt. */
- taskENTER_CRITICAL();
- {
- xTCB->pxTaskTag = pxHookFunction;
- }
- taskEXIT_CRITICAL();
- }
+#if (configUSE_APPLICATION_TASK_TAG == 1)
+
+void vTaskSetApplicationTaskTag(TaskHandle_t xTask, TaskHookFunction_t pxHookFunction) {
+ TCB_t *xTCB;
+
+ /* If xTask is NULL then it is the task hook of the calling task that is
+ getting set. */
+ if (xTask == NULL) {
+ xTCB = (TCB_t *)pxCurrentTCB;
+ } else {
+ xTCB = xTask;
+ }
+
+ /* Save the hook function in the TCB. A critical section is required as
+ the value can be accessed from an interrupt. */
+ taskENTER_CRITICAL();
+ { xTCB->pxTaskTag = pxHookFunction; }
+ taskEXIT_CRITICAL();
+}
#endif /* configUSE_APPLICATION_TASK_TAG */
/*-----------------------------------------------------------*/
-#if ( configUSE_APPLICATION_TASK_TAG == 1 )
+#if (configUSE_APPLICATION_TASK_TAG == 1)
- TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask )
- {
- TCB_t *pxTCB;
- TaskHookFunction_t xReturn;
+TaskHookFunction_t xTaskGetApplicationTaskTag(TaskHandle_t xTask) {
+ TCB_t * pxTCB;
+ TaskHookFunction_t xReturn;
- /* If xTask is NULL then set the calling task's hook. */
- pxTCB = prvGetTCBFromHandle( xTask );
+ /* If xTask is NULL then set the calling task's hook. */
+ pxTCB = prvGetTCBFromHandle(xTask);
- /* Save the hook function in the TCB. A critical section is required as
- the value can be accessed from an interrupt. */
- taskENTER_CRITICAL();
- {
- xReturn = pxTCB->pxTaskTag;
- }
- taskEXIT_CRITICAL();
+ /* Save the hook function in the TCB. A critical section is required as
+ the value can be accessed from an interrupt. */
+ taskENTER_CRITICAL();
+ { xReturn = pxTCB->pxTaskTag; }
+ taskEXIT_CRITICAL();
- return xReturn;
- }
+ return xReturn;
+}
#endif /* configUSE_APPLICATION_TASK_TAG */
/*-----------------------------------------------------------*/
-#if ( configUSE_APPLICATION_TASK_TAG == 1 )
+#if (configUSE_APPLICATION_TASK_TAG == 1)
- TaskHookFunction_t xTaskGetApplicationTaskTagFromISR( TaskHandle_t xTask )
- {
- TCB_t *pxTCB;
- TaskHookFunction_t xReturn;
- UBaseType_t uxSavedInterruptStatus;
+TaskHookFunction_t xTaskGetApplicationTaskTagFromISR(TaskHandle_t xTask) {
+ TCB_t * pxTCB;
+ TaskHookFunction_t xReturn;
+ UBaseType_t uxSavedInterruptStatus;
- /* If xTask is NULL then set the calling task's hook. */
- pxTCB = prvGetTCBFromHandle( xTask );
+ /* If xTask is NULL then set the calling task's hook. */
+ pxTCB = prvGetTCBFromHandle(xTask);
- /* Save the hook function in the TCB. A critical section is required as
- the value can be accessed from an interrupt. */
- uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- xReturn = pxTCB->pxTaskTag;
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+ /* Save the hook function in the TCB. A critical section is required as
+ the value can be accessed from an interrupt. */
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ { xReturn = pxTCB->pxTaskTag; }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
- return xReturn;
- }
+ return xReturn;
+}
#endif /* configUSE_APPLICATION_TASK_TAG */
/*-----------------------------------------------------------*/
-#if ( configUSE_APPLICATION_TASK_TAG == 1 )
-
- BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter )
- {
- TCB_t *xTCB;
- BaseType_t xReturn;
-
- /* If xTask is NULL then we are calling our own task hook. */
- if( xTask == NULL )
- {
- xTCB = pxCurrentTCB;
- }
- else
- {
- xTCB = xTask;
- }
-
- if( xTCB->pxTaskTag != NULL )
- {
- xReturn = xTCB->pxTaskTag( pvParameter );
- }
- else
- {
- xReturn = pdFAIL;
- }
-
- return xReturn;
- }
+#if (configUSE_APPLICATION_TASK_TAG == 1)
+
+BaseType_t xTaskCallApplicationTaskHook(TaskHandle_t xTask, void *pvParameter) {
+ TCB_t * xTCB;
+ BaseType_t xReturn;
+
+ /* If xTask is NULL then we are calling our own task hook. */
+ if (xTask == NULL) {
+ xTCB = pxCurrentTCB;
+ } else {
+ xTCB = xTask;
+ }
+
+ if (xTCB->pxTaskTag != NULL) {
+ xReturn = xTCB->pxTaskTag(pvParameter);
+ } else {
+ xReturn = pdFAIL;
+ }
+
+ return xReturn;
+}
#endif /* configUSE_APPLICATION_TASK_TAG */
/*-----------------------------------------------------------*/
-void vTaskSwitchContext( void )
-{
- if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE )
- {
- /* The scheduler is currently suspended - do not allow a context
- switch. */
- xYieldPending = pdTRUE;
- }
- else
- {
- xYieldPending = pdFALSE;
- traceTASK_SWITCHED_OUT();
-
- #if ( configGENERATE_RUN_TIME_STATS == 1 )
- {
- #ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
- portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime );
- #else
- ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
- #endif
-
- /* Add the amount of time the task has been running to the
- accumulated time so far. The time the task started running was
- stored in ulTaskSwitchedInTime. Note that there is no overflow
- protection here so count values are only valid until the timer
- overflows. The guard against negative values is to protect
- against suspect run time stat counter implementations - which
- are provided by the application, not the kernel. */
- if( ulTotalRunTime > ulTaskSwitchedInTime )
- {
- pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- ulTaskSwitchedInTime = ulTotalRunTime;
- }
- #endif /* configGENERATE_RUN_TIME_STATS */
-
- /* Check for stack overflow, if configured. */
- taskCHECK_FOR_STACK_OVERFLOW();
-
- /* Before the currently running task is switched out, save its errno. */
- #if( configUSE_POSIX_ERRNO == 1 )
- {
- pxCurrentTCB->iTaskErrno = FreeRTOS_errno;
- }
- #endif
-
- /* Select a new task to run using either the generic C or port
- optimised asm code. */
- taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
- traceTASK_SWITCHED_IN();
-
- /* After the new task is switched in, update the global errno. */
- #if( configUSE_POSIX_ERRNO == 1 )
- {
- FreeRTOS_errno = pxCurrentTCB->iTaskErrno;
- }
- #endif
-
- #if ( configUSE_NEWLIB_REENTRANT == 1 )
- {
- /* Switch Newlib's _impure_ptr variable to point to the _reent
- structure specific to this task.
- See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
- for additional information. */
- _impure_ptr = &( pxCurrentTCB->xNewLib_reent );
- }
- #endif /* configUSE_NEWLIB_REENTRANT */
- }
+void vTaskSwitchContext(void) {
+ if (uxSchedulerSuspended != (UBaseType_t)pdFALSE) {
+ /* The scheduler is currently suspended - do not allow a context
+ switch. */
+ xYieldPending = pdTRUE;
+ } else {
+ xYieldPending = pdFALSE;
+ traceTASK_SWITCHED_OUT();
+
+#if (configGENERATE_RUN_TIME_STATS == 1)
+ {
+#ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
+ portALT_GET_RUN_TIME_COUNTER_VALUE(ulTotalRunTime);
+#else
+ ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
+#endif
+
+ /* Add the amount of time the task has been running to the
+ accumulated time so far. The time the task started running was
+ stored in ulTaskSwitchedInTime. Note that there is no overflow
+ protection here so count values are only valid until the timer
+ overflows. The guard against negative values is to protect
+ against suspect run time stat counter implementations - which
+ are provided by the application, not the kernel. */
+ if (ulTotalRunTime > ulTaskSwitchedInTime) {
+ pxCurrentTCB->ulRunTimeCounter += (ulTotalRunTime - ulTaskSwitchedInTime);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ ulTaskSwitchedInTime = ulTotalRunTime;
+ }
+#endif /* configGENERATE_RUN_TIME_STATS */
+
+ /* Check for stack overflow, if configured. */
+ taskCHECK_FOR_STACK_OVERFLOW();
+
+/* Before the currently running task is switched out, save its errno. */
+#if (configUSE_POSIX_ERRNO == 1)
+ { pxCurrentTCB->iTaskErrno = FreeRTOS_errno; }
+#endif
+
+ /* Select a new task to run using either the generic C or port
+ optimised asm code. */
+ taskSELECT_HIGHEST_PRIORITY_TASK(); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and
+ retrieved is the same. */
+ traceTASK_SWITCHED_IN();
+
+/* After the new task is switched in, update the global errno. */
+#if (configUSE_POSIX_ERRNO == 1)
+ { FreeRTOS_errno = pxCurrentTCB->iTaskErrno; }
+#endif
+
+#if (configUSE_NEWLIB_REENTRANT == 1)
+ {
+ /* Switch Newlib's _impure_ptr variable to point to the _reent
+ structure specific to this task.
+ See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
+ for additional information. */
+ _impure_ptr = &(pxCurrentTCB->xNewLib_reent);
+ }
+#endif /* configUSE_NEWLIB_REENTRANT */
+ }
}
/*-----------------------------------------------------------*/
-void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait )
-{
- configASSERT( pxEventList );
+void vTaskPlaceOnEventList(List_t *const pxEventList, const TickType_t xTicksToWait) {
+ configASSERT(pxEventList);
- /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE
- SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */
+ /* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE
+ SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */
- /* Place the event list item of the TCB in the appropriate event list.
- This is placed in the list in priority order so the highest priority task
- is the first to be woken by the event. The queue that contains the event
- list is locked, preventing simultaneous access from interrupts. */
- vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) );
+ /* Place the event list item of the TCB in the appropriate event list.
+ This is placed in the list in priority order so the highest priority task
+ is the first to be woken by the event. The queue that contains the event
+ list is locked, preventing simultaneous access from interrupts. */
+ vListInsert(pxEventList, &(pxCurrentTCB->xEventListItem));
- prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
+ prvAddCurrentTaskToDelayedList(xTicksToWait, pdTRUE);
}
/*-----------------------------------------------------------*/
-void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait )
-{
- configASSERT( pxEventList );
+void vTaskPlaceOnUnorderedEventList(List_t *pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait) {
+ configASSERT(pxEventList);
- /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by
- the event groups implementation. */
- configASSERT( uxSchedulerSuspended != 0 );
+ /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by
+ the event groups implementation. */
+ configASSERT(uxSchedulerSuspended != 0);
- /* Store the item value in the event list item. It is safe to access the
- event list item here as interrupts won't access the event list item of a
- task that is not in the Blocked state. */
- listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );
+ /* Store the item value in the event list item. It is safe to access the
+ event list item here as interrupts won't access the event list item of a
+ task that is not in the Blocked state. */
+ listSET_LIST_ITEM_VALUE(&(pxCurrentTCB->xEventListItem), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE);
- /* Place the event list item of the TCB at the end of the appropriate event
- list. It is safe to access the event list here because it is part of an
- event group implementation - and interrupts don't access event groups
- directly (instead they access them indirectly by pending function calls to
- the task level). */
- vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) );
+ /* Place the event list item of the TCB at the end of the appropriate event
+ list. It is safe to access the event list here because it is part of an
+ event group implementation - and interrupts don't access event groups
+ directly (instead they access them indirectly by pending function calls to
+ the task level). */
+ vListInsertEnd(pxEventList, &(pxCurrentTCB->xEventListItem));
- prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
+ prvAddCurrentTaskToDelayedList(xTicksToWait, pdTRUE);
}
/*-----------------------------------------------------------*/
-#if( configUSE_TIMERS == 1 )
+#if (configUSE_TIMERS == 1)
- void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely )
- {
- configASSERT( pxEventList );
+void vTaskPlaceOnEventListRestricted(List_t *const pxEventList, TickType_t xTicksToWait, const BaseType_t xWaitIndefinitely) {
+ configASSERT(pxEventList);
- /* This function should not be called by application code hence the
- 'Restricted' in its name. It is not part of the public API. It is
- designed for use by kernel code, and has special calling requirements -
- it should be called with the scheduler suspended. */
+ /* This function should not be called by application code hence the
+ 'Restricted' in its name. It is not part of the public API. It is
+ designed for use by kernel code, and has special calling requirements -
+ it should be called with the scheduler suspended. */
+ /* Place the event list item of the TCB in the appropriate event list.
+ In this case it is assume that this is the only task that is going to
+ be waiting on this event list, so the faster vListInsertEnd() function
+ can be used in place of vListInsert. */
+ vListInsertEnd(pxEventList, &(pxCurrentTCB->xEventListItem));
- /* Place the event list item of the TCB in the appropriate event list.
- In this case it is assume that this is the only task that is going to
- be waiting on this event list, so the faster vListInsertEnd() function
- can be used in place of vListInsert. */
- vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) );
+ /* If the task should block indefinitely then set the block time to a
+ value that will be recognised as an indefinite delay inside the
+ prvAddCurrentTaskToDelayedList() function. */
+ if (xWaitIndefinitely != pdFALSE) {
+ xTicksToWait = portMAX_DELAY;
+ }
- /* If the task should block indefinitely then set the block time to a
- value that will be recognised as an indefinite delay inside the
- prvAddCurrentTaskToDelayedList() function. */
- if( xWaitIndefinitely != pdFALSE )
- {
- xTicksToWait = portMAX_DELAY;
- }
-
- traceTASK_DELAY_UNTIL( ( xTickCount + xTicksToWait ) );
- prvAddCurrentTaskToDelayedList( xTicksToWait, xWaitIndefinitely );
- }
+ traceTASK_DELAY_UNTIL((xTickCount + xTicksToWait));
+ prvAddCurrentTaskToDelayedList(xTicksToWait, xWaitIndefinitely);
+}
#endif /* configUSE_TIMERS */
/*-----------------------------------------------------------*/
-BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList )
-{
-TCB_t *pxUnblockedTCB;
-BaseType_t xReturn;
-
- /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be
- called from a critical section within an ISR. */
-
- /* The event list is sorted in priority order, so the first in the list can
- be removed as it is known to be the highest priority. Remove the TCB from
- the delayed list, and add it to the ready list.
-
- If an event is for a queue that is locked then this function will never
- get called - the lock count on the queue will get modified instead. This
- means exclusive access to the event list is guaranteed here.
-
- This function assumes that a check has already been made to ensure that
- pxEventList is not empty. */
- pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY( pxEventList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
- configASSERT( pxUnblockedTCB );
- ( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) );
-
- if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
- {
- ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) );
- prvAddTaskToReadyList( pxUnblockedTCB );
-
- #if( configUSE_TICKLESS_IDLE != 0 )
- {
- /* If a task is blocked on a kernel object then xNextTaskUnblockTime
- might be set to the blocked task's time out time. If the task is
- unblocked for a reason other than a timeout xNextTaskUnblockTime is
- normally left unchanged, because it is automatically reset to a new
- value when the tick count equals xNextTaskUnblockTime. However if
- tickless idling is used it might be more important to enter sleep mode
- at the earliest possible time - so reset xNextTaskUnblockTime here to
- ensure it is updated at the earliest possible time. */
- prvResetNextTaskUnblockTime();
- }
- #endif
- }
- else
- {
- /* The delayed and ready lists cannot be accessed, so hold this task
- pending until the scheduler is resumed. */
- vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) );
- }
-
- if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority )
- {
- /* Return true if the task removed from the event list has a higher
- priority than the calling task. This allows the calling task to know if
- it should force a context switch now. */
- xReturn = pdTRUE;
-
- /* Mark that a yield is pending in case the user is not using the
- "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */
- xYieldPending = pdTRUE;
- }
- else
- {
- xReturn = pdFALSE;
- }
-
- return xReturn;
+BaseType_t xTaskRemoveFromEventList(const List_t *const pxEventList) {
+ TCB_t * pxUnblockedTCB;
+ BaseType_t xReturn;
+
+ /* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION. It can also be
+ called from a critical section within an ISR. */
+
+ /* The event list is sorted in priority order, so the first in the list can
+ be removed as it is known to be the highest priority. Remove the TCB from
+ the delayed list, and add it to the ready list.
+
+ If an event is for a queue that is locked then this function will never
+ get called - the lock count on the queue will get modified instead. This
+ means exclusive access to the event list is guaranteed here.
+
+ This function assumes that a check has already been made to ensure that
+ pxEventList is not empty. */
+ pxUnblockedTCB = listGET_OWNER_OF_HEAD_ENTRY(
+ pxEventList); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
+ configASSERT(pxUnblockedTCB);
+ (void)uxListRemove(&(pxUnblockedTCB->xEventListItem));
+
+ if (uxSchedulerSuspended == (UBaseType_t)pdFALSE) {
+ (void)uxListRemove(&(pxUnblockedTCB->xStateListItem));
+ prvAddTaskToReadyList(pxUnblockedTCB);
+
+#if (configUSE_TICKLESS_IDLE != 0)
+ {
+ /* If a task is blocked on a kernel object then xNextTaskUnblockTime
+ might be set to the blocked task's time out time. If the task is
+ unblocked for a reason other than a timeout xNextTaskUnblockTime is
+ normally left unchanged, because it is automatically reset to a new
+ value when the tick count equals xNextTaskUnblockTime. However if
+ tickless idling is used it might be more important to enter sleep mode
+ at the earliest possible time - so reset xNextTaskUnblockTime here to
+ ensure it is updated at the earliest possible time. */
+ prvResetNextTaskUnblockTime();
+ }
+#endif
+ } else {
+ /* The delayed and ready lists cannot be accessed, so hold this task
+ pending until the scheduler is resumed. */
+ vListInsertEnd(&(xPendingReadyList), &(pxUnblockedTCB->xEventListItem));
+ }
+
+ if (pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority) {
+ /* Return true if the task removed from the event list has a higher
+ priority than the calling task. This allows the calling task to know if
+ it should force a context switch now. */
+ xReturn = pdTRUE;
+
+ /* Mark that a yield is pending in case the user is not using the
+ "xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */
+ xYieldPending = pdTRUE;
+ } else {
+ xReturn = pdFALSE;
+ }
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-void vTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue )
-{
-TCB_t *pxUnblockedTCB;
-
- /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by
- the event flags implementation. */
- configASSERT( uxSchedulerSuspended != pdFALSE );
-
- /* Store the new item value in the event list. */
- listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );
-
- /* Remove the event list form the event flag. Interrupts do not access
- event flags. */
- pxUnblockedTCB = listGET_LIST_ITEM_OWNER( pxEventListItem ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
- configASSERT( pxUnblockedTCB );
- ( void ) uxListRemove( pxEventListItem );
-
- #if( configUSE_TICKLESS_IDLE != 0 )
- {
- /* If a task is blocked on a kernel object then xNextTaskUnblockTime
- might be set to the blocked task's time out time. If the task is
- unblocked for a reason other than a timeout xNextTaskUnblockTime is
- normally left unchanged, because it is automatically reset to a new
- value when the tick count equals xNextTaskUnblockTime. However if
- tickless idling is used it might be more important to enter sleep mode
- at the earliest possible time - so reset xNextTaskUnblockTime here to
- ensure it is updated at the earliest possible time. */
- prvResetNextTaskUnblockTime();
- }
- #endif
-
- /* Remove the task from the delayed list and add it to the ready list. The
- scheduler is suspended so interrupts will not be accessing the ready
- lists. */
- ( void ) uxListRemove( &( pxUnblockedTCB->xStateListItem ) );
- prvAddTaskToReadyList( pxUnblockedTCB );
-
- if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority )
- {
- /* The unblocked task has a priority above that of the calling task, so
- a context switch is required. This function is called with the
- scheduler suspended so xYieldPending is set so the context switch
- occurs immediately that the scheduler is resumed (unsuspended). */
- xYieldPending = pdTRUE;
- }
+void vTaskRemoveFromUnorderedEventList(ListItem_t *pxEventListItem, const TickType_t xItemValue) {
+ TCB_t *pxUnblockedTCB;
+
+ /* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. It is used by
+ the event flags implementation. */
+ configASSERT(uxSchedulerSuspended != pdFALSE);
+
+ /* Store the new item value in the event list. */
+ listSET_LIST_ITEM_VALUE(pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE);
+
+ /* Remove the event list form the event flag. Interrupts do not access
+ event flags. */
+ pxUnblockedTCB = listGET_LIST_ITEM_OWNER(pxEventListItem); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the
+ pointer stored and retrieved is the same. */
+ configASSERT(pxUnblockedTCB);
+ (void)uxListRemove(pxEventListItem);
+
+#if (configUSE_TICKLESS_IDLE != 0)
+ {
+ /* If a task is blocked on a kernel object then xNextTaskUnblockTime
+ might be set to the blocked task's time out time. If the task is
+ unblocked for a reason other than a timeout xNextTaskUnblockTime is
+ normally left unchanged, because it is automatically reset to a new
+ value when the tick count equals xNextTaskUnblockTime. However if
+ tickless idling is used it might be more important to enter sleep mode
+ at the earliest possible time - so reset xNextTaskUnblockTime here to
+ ensure it is updated at the earliest possible time. */
+ prvResetNextTaskUnblockTime();
+ }
+#endif
+
+ /* Remove the task from the delayed list and add it to the ready list. The
+ scheduler is suspended so interrupts will not be accessing the ready
+ lists. */
+ (void)uxListRemove(&(pxUnblockedTCB->xStateListItem));
+ prvAddTaskToReadyList(pxUnblockedTCB);
+
+ if (pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority) {
+ /* The unblocked task has a priority above that of the calling task, so
+ a context switch is required. This function is called with the
+ scheduler suspended so xYieldPending is set so the context switch
+ occurs immediately that the scheduler is resumed (unsuspended). */
+ xYieldPending = pdTRUE;
+ }
}
/*-----------------------------------------------------------*/
-void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut )
-{
- configASSERT( pxTimeOut );
- taskENTER_CRITICAL();
- {
- pxTimeOut->xOverflowCount = xNumOfOverflows;
- pxTimeOut->xTimeOnEntering = xTickCount;
- }
- taskEXIT_CRITICAL();
+void vTaskSetTimeOutState(TimeOut_t *const pxTimeOut) {
+ configASSERT(pxTimeOut);
+ taskENTER_CRITICAL();
+ {
+ pxTimeOut->xOverflowCount = xNumOfOverflows;
+ pxTimeOut->xTimeOnEntering = xTickCount;
+ }
+ taskEXIT_CRITICAL();
}
/*-----------------------------------------------------------*/
-void vTaskInternalSetTimeOutState( TimeOut_t * const pxTimeOut )
-{
- /* For internal use only as it does not use a critical section. */
- pxTimeOut->xOverflowCount = xNumOfOverflows;
- pxTimeOut->xTimeOnEntering = xTickCount;
+void vTaskInternalSetTimeOutState(TimeOut_t *const pxTimeOut) {
+ /* For internal use only as it does not use a critical section. */
+ pxTimeOut->xOverflowCount = xNumOfOverflows;
+ pxTimeOut->xTimeOnEntering = xTickCount;
}
/*-----------------------------------------------------------*/
-BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait )
-{
-BaseType_t xReturn;
-
- configASSERT( pxTimeOut );
- configASSERT( pxTicksToWait );
-
- taskENTER_CRITICAL();
- {
- /* Minor optimisation. The tick count cannot change in this block. */
- const TickType_t xConstTickCount = xTickCount;
- const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering;
-
- #if( INCLUDE_xTaskAbortDelay == 1 )
- if( pxCurrentTCB->ucDelayAborted != ( uint8_t ) pdFALSE )
- {
- /* The delay was aborted, which is not the same as a time out,
- but has the same result. */
- pxCurrentTCB->ucDelayAborted = pdFALSE;
- xReturn = pdTRUE;
- }
- else
- #endif
-
- #if ( INCLUDE_vTaskSuspend == 1 )
- if( *pxTicksToWait == portMAX_DELAY )
- {
- /* If INCLUDE_vTaskSuspend is set to 1 and the block time
- specified is the maximum block time then the task should block
- indefinitely, and therefore never time out. */
- xReturn = pdFALSE;
- }
- else
- #endif
-
- if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */
- {
- /* The tick count is greater than the time at which
- vTaskSetTimeout() was called, but has also overflowed since
- vTaskSetTimeOut() was called. It must have wrapped all the way
- around and gone past again. This passed since vTaskSetTimeout()
- was called. */
- xReturn = pdTRUE;
- }
- else if( xElapsedTime < *pxTicksToWait ) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */
- {
- /* Not a genuine timeout. Adjust parameters for time remaining. */
- *pxTicksToWait -= xElapsedTime;
- vTaskInternalSetTimeOutState( pxTimeOut );
- xReturn = pdFALSE;
- }
- else
- {
- *pxTicksToWait = 0;
- xReturn = pdTRUE;
- }
- }
- taskEXIT_CRITICAL();
-
- return xReturn;
+BaseType_t xTaskCheckForTimeOut(TimeOut_t *const pxTimeOut, TickType_t *const pxTicksToWait) {
+ BaseType_t xReturn;
+
+ configASSERT(pxTimeOut);
+ configASSERT(pxTicksToWait);
+
+ taskENTER_CRITICAL();
+ {
+ /* Minor optimisation. The tick count cannot change in this block. */
+ const TickType_t xConstTickCount = xTickCount;
+ const TickType_t xElapsedTime = xConstTickCount - pxTimeOut->xTimeOnEntering;
+
+#if (INCLUDE_xTaskAbortDelay == 1)
+ if (pxCurrentTCB->ucDelayAborted != (uint8_t)pdFALSE) {
+ /* The delay was aborted, which is not the same as a time out,
+ but has the same result. */
+ pxCurrentTCB->ucDelayAborted = pdFALSE;
+ xReturn = pdTRUE;
+ } else
+#endif
+
+#if (INCLUDE_vTaskSuspend == 1)
+ if (*pxTicksToWait == portMAX_DELAY) {
+ /* If INCLUDE_vTaskSuspend is set to 1 and the block time
+ specified is the maximum block time then the task should block
+ indefinitely, and therefore never time out. */
+ xReturn = pdFALSE;
+ } else
+#endif
+
+ if ((xNumOfOverflows != pxTimeOut->xOverflowCount)
+ && (xConstTickCount >= pxTimeOut->xTimeOnEntering)) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */
+ {
+ /* The tick count is greater than the time at which
+ vTaskSetTimeout() was called, but has also overflowed since
+ vTaskSetTimeOut() was called. It must have wrapped all the way
+ around and gone past again. This passed since vTaskSetTimeout()
+ was called. */
+ xReturn = pdTRUE;
+ } else if (xElapsedTime < *pxTicksToWait) /*lint !e961 Explicit casting is only redundant with some compilers, whereas others require it to prevent integer conversion errors. */
+ {
+ /* Not a genuine timeout. Adjust parameters for time remaining. */
+ *pxTicksToWait -= xElapsedTime;
+ vTaskInternalSetTimeOutState(pxTimeOut);
+ xReturn = pdFALSE;
+ } else {
+ *pxTicksToWait = 0;
+ xReturn = pdTRUE;
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-void vTaskMissedYield( void )
-{
- xYieldPending = pdTRUE;
-}
+void vTaskMissedYield(void) { xYieldPending = pdTRUE; }
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
+#if (configUSE_TRACE_FACILITY == 1)
- UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask )
- {
- UBaseType_t uxReturn;
- TCB_t const *pxTCB;
+UBaseType_t uxTaskGetTaskNumber(TaskHandle_t xTask) {
+ UBaseType_t uxReturn;
+ TCB_t const *pxTCB;
- if( xTask != NULL )
- {
- pxTCB = xTask;
- uxReturn = pxTCB->uxTaskNumber;
- }
- else
- {
- uxReturn = 0U;
- }
+ if (xTask != NULL) {
+ pxTCB = xTask;
+ uxReturn = pxTCB->uxTaskNumber;
+ } else {
+ uxReturn = 0U;
+ }
- return uxReturn;
- }
+ return uxReturn;
+}
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
+#if (configUSE_TRACE_FACILITY == 1)
- void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle )
- {
- TCB_t * pxTCB;
+void vTaskSetTaskNumber(TaskHandle_t xTask, const UBaseType_t uxHandle) {
+ TCB_t *pxTCB;
- if( xTask != NULL )
- {
- pxTCB = xTask;
- pxTCB->uxTaskNumber = uxHandle;
- }
- }
+ if (xTask != NULL) {
+ pxTCB = xTask;
+ pxTCB->uxTaskNumber = uxHandle;
+ }
+}
#endif /* configUSE_TRACE_FACILITY */
@@ -3389,1900 +2955,1644 @@ void vTaskMissedYield( void )
* void prvIdleTask( void *pvParameters );
*
*/
-static portTASK_FUNCTION( prvIdleTask, pvParameters )
-{
- /* Stop warnings. */
- ( void ) pvParameters;
-
- /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE
- SCHEDULER IS STARTED. **/
-
- /* In case a task that has a secure context deletes itself, in which case
- the idle task is responsible for deleting the task's secure context, if
- any. */
- portALLOCATE_SECURE_CONTEXT( configMINIMAL_SECURE_STACK_SIZE );
-
- for( ;; )
- {
- /* See if any tasks have deleted themselves - if so then the idle task
- is responsible for freeing the deleted task's TCB and stack. */
- prvCheckTasksWaitingTermination();
-
- #if ( configUSE_PREEMPTION == 0 )
- {
- /* If we are not using preemption we keep forcing a task switch to
- see if any other task has become available. If we are using
- preemption we don't need to do this as any task becoming available
- will automatically get the processor anyway. */
- taskYIELD();
- }
- #endif /* configUSE_PREEMPTION */
-
- #if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) )
- {
- /* When using preemption tasks of equal priority will be
- timesliced. If a task that is sharing the idle priority is ready
- to run then the idle task should yield before the end of the
- timeslice.
-
- A critical region is not required here as we are just reading from
- the list, and an occasional incorrect value will not matter. If
- the ready list at the idle priority contains more than one task
- then a task other than the idle task is ready to execute. */
- if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 )
- {
- taskYIELD();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */
-
- #if ( configUSE_IDLE_HOOK == 1 )
- {
- extern void vApplicationIdleHook( void );
-
- /* Call the user defined function from within the idle task. This
- allows the application designer to add background functionality
- without the overhead of a separate task.
- NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES,
- CALL A FUNCTION THAT MIGHT BLOCK. */
- vApplicationIdleHook();
- }
- #endif /* configUSE_IDLE_HOOK */
-
- /* This conditional compilation should use inequality to 0, not equality
- to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when
- user defined low power mode implementations require
- configUSE_TICKLESS_IDLE to be set to a value other than 1. */
- #if ( configUSE_TICKLESS_IDLE != 0 )
- {
- TickType_t xExpectedIdleTime;
-
- /* It is not desirable to suspend then resume the scheduler on
- each iteration of the idle task. Therefore, a preliminary
- test of the expected idle time is performed without the
- scheduler suspended. The result here is not necessarily
- valid. */
- xExpectedIdleTime = prvGetExpectedIdleTime();
-
- if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP )
- {
- vTaskSuspendAll();
- {
- /* Now the scheduler is suspended, the expected idle
- time can be sampled again, and this time its value can
- be used. */
- configASSERT( xNextTaskUnblockTime >= xTickCount );
- xExpectedIdleTime = prvGetExpectedIdleTime();
-
- /* Define the following macro to set xExpectedIdleTime to 0
- if the application does not want
- portSUPPRESS_TICKS_AND_SLEEP() to be called. */
- configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING( xExpectedIdleTime );
-
- if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP )
- {
- traceLOW_POWER_IDLE_BEGIN();
- portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime );
- traceLOW_POWER_IDLE_END();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- ( void ) xTaskResumeAll();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configUSE_TICKLESS_IDLE */
- }
+static portTASK_FUNCTION(prvIdleTask, pvParameters) {
+ /* Stop warnings. */
+ (void)pvParameters;
+
+ /** THIS IS THE RTOS IDLE TASK - WHICH IS CREATED AUTOMATICALLY WHEN THE
+ SCHEDULER IS STARTED. **/
+
+ /* In case a task that has a secure context deletes itself, in which case
+ the idle task is responsible for deleting the task's secure context, if
+ any. */
+ portALLOCATE_SECURE_CONTEXT(configMINIMAL_SECURE_STACK_SIZE);
+
+ for (;;) {
+ /* See if any tasks have deleted themselves - if so then the idle task
+ is responsible for freeing the deleted task's TCB and stack. */
+ prvCheckTasksWaitingTermination();
+
+#if (configUSE_PREEMPTION == 0)
+ {
+ /* If we are not using preemption we keep forcing a task switch to
+ see if any other task has become available. If we are using
+ preemption we don't need to do this as any task becoming available
+ will automatically get the processor anyway. */
+ taskYIELD();
+ }
+#endif /* configUSE_PREEMPTION */
+
+#if ((configUSE_PREEMPTION == 1) && (configIDLE_SHOULD_YIELD == 1))
+ {
+ /* When using preemption tasks of equal priority will be
+ timesliced. If a task that is sharing the idle priority is ready
+ to run then the idle task should yield before the end of the
+ timeslice.
+
+ A critical region is not required here as we are just reading from
+ the list, and an occasional incorrect value will not matter. If
+ the ready list at the idle priority contains more than one task
+ then a task other than the idle task is ready to execute. */
+ if (listCURRENT_LIST_LENGTH(&(pxReadyTasksLists[tskIDLE_PRIORITY])) > (UBaseType_t)1) {
+ taskYIELD();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */
+
+#if (configUSE_IDLE_HOOK == 1)
+ {
+ extern void vApplicationIdleHook(void);
+
+ /* Call the user defined function from within the idle task. This
+ allows the application designer to add background functionality
+ without the overhead of a separate task.
+ NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES,
+ CALL A FUNCTION THAT MIGHT BLOCK. */
+ vApplicationIdleHook();
+ }
+#endif /* configUSE_IDLE_HOOK */
+
+/* This conditional compilation should use inequality to 0, not equality
+to 1. This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when
+user defined low power mode implementations require
+configUSE_TICKLESS_IDLE to be set to a value other than 1. */
+#if (configUSE_TICKLESS_IDLE != 0)
+ {
+ TickType_t xExpectedIdleTime;
+
+ /* It is not desirable to suspend then resume the scheduler on
+ each iteration of the idle task. Therefore, a preliminary
+ test of the expected idle time is performed without the
+ scheduler suspended. The result here is not necessarily
+ valid. */
+ xExpectedIdleTime = prvGetExpectedIdleTime();
+
+ if (xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP) {
+ vTaskSuspendAll();
+ {
+ /* Now the scheduler is suspended, the expected idle
+ time can be sampled again, and this time its value can
+ be used. */
+ configASSERT(xNextTaskUnblockTime >= xTickCount);
+ xExpectedIdleTime = prvGetExpectedIdleTime();
+
+ /* Define the following macro to set xExpectedIdleTime to 0
+ if the application does not want
+ portSUPPRESS_TICKS_AND_SLEEP() to be called. */
+ configPRE_SUPPRESS_TICKS_AND_SLEEP_PROCESSING(xExpectedIdleTime);
+
+ if (xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP) {
+ traceLOW_POWER_IDLE_BEGIN();
+ portSUPPRESS_TICKS_AND_SLEEP(xExpectedIdleTime);
+ traceLOW_POWER_IDLE_END();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ (void)xTaskResumeAll();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configUSE_TICKLESS_IDLE */
+ }
}
/*-----------------------------------------------------------*/
-#if( configUSE_TICKLESS_IDLE != 0 )
-
- eSleepModeStatus eTaskConfirmSleepModeStatus( void )
- {
- /* The idle task exists in addition to the application tasks. */
- const UBaseType_t uxNonApplicationTasks = 1;
- eSleepModeStatus eReturn = eStandardSleep;
-
- /* This function must be called from a critical section. */
-
- if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 )
- {
- /* A task was made ready while the scheduler was suspended. */
- eReturn = eAbortSleep;
- }
- else if( xYieldPending != pdFALSE )
- {
- /* A yield was pended while the scheduler was suspended. */
- eReturn = eAbortSleep;
- }
- else
- {
- /* If all the tasks are in the suspended list (which might mean they
- have an infinite block time rather than actually being suspended)
- then it is safe to turn all clocks off and just wait for external
- interrupts. */
- if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) )
- {
- eReturn = eNoTasksWaitingTimeout;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- return eReturn;
- }
+#if (configUSE_TICKLESS_IDLE != 0)
+
+eSleepModeStatus eTaskConfirmSleepModeStatus(void) {
+ /* The idle task exists in addition to the application tasks. */
+ const UBaseType_t uxNonApplicationTasks = 1;
+ eSleepModeStatus eReturn = eStandardSleep;
+
+ /* This function must be called from a critical section. */
+
+ if (listCURRENT_LIST_LENGTH(&xPendingReadyList) != 0) {
+ /* A task was made ready while the scheduler was suspended. */
+ eReturn = eAbortSleep;
+ } else if (xYieldPending != pdFALSE) {
+ /* A yield was pended while the scheduler was suspended. */
+ eReturn = eAbortSleep;
+ } else {
+ /* If all the tasks are in the suspended list (which might mean they
+ have an infinite block time rather than actually being suspended)
+ then it is safe to turn all clocks off and just wait for external
+ interrupts. */
+ if (listCURRENT_LIST_LENGTH(&xSuspendedTaskList) == (uxCurrentNumberOfTasks - uxNonApplicationTasks)) {
+ eReturn = eNoTasksWaitingTimeout;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ return eReturn;
+}
#endif /* configUSE_TICKLESS_IDLE */
/*-----------------------------------------------------------*/
-#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
+#if (configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0)
- void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue )
- {
- TCB_t *pxTCB;
+void vTaskSetThreadLocalStoragePointer(TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue) {
+ TCB_t *pxTCB;
- if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS )
- {
- pxTCB = prvGetTCBFromHandle( xTaskToSet );
- configASSERT( pxTCB != NULL );
- pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue;
- }
- }
+ if (xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS) {
+ pxTCB = prvGetTCBFromHandle(xTaskToSet);
+ configASSERT(pxTCB != NULL);
+ pxTCB->pvThreadLocalStoragePointers[xIndex] = pvValue;
+ }
+}
#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
/*-----------------------------------------------------------*/
-#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
+#if (configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0)
- void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex )
- {
- void *pvReturn = NULL;
- TCB_t *pxTCB;
+void *pvTaskGetThreadLocalStoragePointer(TaskHandle_t xTaskToQuery, BaseType_t xIndex) {
+ void * pvReturn = NULL;
+ TCB_t *pxTCB;
- if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS )
- {
- pxTCB = prvGetTCBFromHandle( xTaskToQuery );
- pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ];
- }
- else
- {
- pvReturn = NULL;
- }
+ if (xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS) {
+ pxTCB = prvGetTCBFromHandle(xTaskToQuery);
+ pvReturn = pxTCB->pvThreadLocalStoragePointers[xIndex];
+ } else {
+ pvReturn = NULL;
+ }
- return pvReturn;
- }
+ return pvReturn;
+}
#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
/*-----------------------------------------------------------*/
-#if ( portUSING_MPU_WRAPPERS == 1 )
+#if (portUSING_MPU_WRAPPERS == 1)
- void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, const MemoryRegion_t * const xRegions )
- {
- TCB_t *pxTCB;
+void vTaskAllocateMPURegions(TaskHandle_t xTaskToModify, const MemoryRegion_t *const xRegions) {
+ TCB_t *pxTCB;
- /* If null is passed in here then we are modifying the MPU settings of
- the calling task. */
- pxTCB = prvGetTCBFromHandle( xTaskToModify );
+ /* If null is passed in here then we are modifying the MPU settings of
+ the calling task. */
+ pxTCB = prvGetTCBFromHandle(xTaskToModify);
- vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 );
- }
+ vPortStoreTaskMPUSettings(&(pxTCB->xMPUSettings), xRegions, NULL, 0);
+}
#endif /* portUSING_MPU_WRAPPERS */
/*-----------------------------------------------------------*/
-static void prvInitialiseTaskLists( void )
-{
-UBaseType_t uxPriority;
-
- for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ )
- {
- vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) );
- }
-
- vListInitialise( &xDelayedTaskList1 );
- vListInitialise( &xDelayedTaskList2 );
- vListInitialise( &xPendingReadyList );
-
- #if ( INCLUDE_vTaskDelete == 1 )
- {
- vListInitialise( &xTasksWaitingTermination );
- }
- #endif /* INCLUDE_vTaskDelete */
-
- #if ( INCLUDE_vTaskSuspend == 1 )
- {
- vListInitialise( &xSuspendedTaskList );
- }
- #endif /* INCLUDE_vTaskSuspend */
-
- /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList
- using list2. */
- pxDelayedTaskList = &xDelayedTaskList1;
- pxOverflowDelayedTaskList = &xDelayedTaskList2;
+static void prvInitialiseTaskLists(void) {
+ UBaseType_t uxPriority;
+
+ for (uxPriority = (UBaseType_t)0U; uxPriority < (UBaseType_t)configMAX_PRIORITIES; uxPriority++) {
+ vListInitialise(&(pxReadyTasksLists[uxPriority]));
+ }
+
+ vListInitialise(&xDelayedTaskList1);
+ vListInitialise(&xDelayedTaskList2);
+ vListInitialise(&xPendingReadyList);
+
+#if (INCLUDE_vTaskDelete == 1)
+ { vListInitialise(&xTasksWaitingTermination); }
+#endif /* INCLUDE_vTaskDelete */
+
+#if (INCLUDE_vTaskSuspend == 1)
+ { vListInitialise(&xSuspendedTaskList); }
+#endif /* INCLUDE_vTaskSuspend */
+
+ /* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList
+ using list2. */
+ pxDelayedTaskList = &xDelayedTaskList1;
+ pxOverflowDelayedTaskList = &xDelayedTaskList2;
}
/*-----------------------------------------------------------*/
-static void prvCheckTasksWaitingTermination( void )
-{
-
- /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/
-
- #if ( INCLUDE_vTaskDelete == 1 )
- {
- TCB_t *pxTCB;
-
- /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL()
- being called too often in the idle task. */
- while( uxDeletedTasksWaitingCleanUp > ( UBaseType_t ) 0U )
- {
- taskENTER_CRITICAL();
- {
- pxTCB = listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
- ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
- --uxCurrentNumberOfTasks;
- --uxDeletedTasksWaitingCleanUp;
- }
- taskEXIT_CRITICAL();
-
- prvDeleteTCB( pxTCB );
- }
- }
- #endif /* INCLUDE_vTaskDelete */
+static void prvCheckTasksWaitingTermination(void) {
+
+ /** THIS FUNCTION IS CALLED FROM THE RTOS IDLE TASK **/
+
+#if (INCLUDE_vTaskDelete == 1)
+ {
+ TCB_t *pxTCB;
+
+ /* uxDeletedTasksWaitingCleanUp is used to prevent taskENTER_CRITICAL()
+ being called too often in the idle task. */
+ while (uxDeletedTasksWaitingCleanUp > (UBaseType_t)0U) {
+ taskENTER_CRITICAL();
+ {
+ pxTCB = listGET_OWNER_OF_HEAD_ENTRY((&xTasksWaitingTermination)); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as
+ the type of the pointer stored and retrieved is the same. */
+ (void)uxListRemove(&(pxTCB->xStateListItem));
+ --uxCurrentNumberOfTasks;
+ --uxDeletedTasksWaitingCleanUp;
+ }
+ taskEXIT_CRITICAL();
+
+ prvDeleteTCB(pxTCB);
+ }
+ }
+#endif /* INCLUDE_vTaskDelete */
}
/*-----------------------------------------------------------*/
-#if( configUSE_TRACE_FACILITY == 1 )
-
- void vTaskGetInfo( TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState )
- {
- TCB_t *pxTCB;
-
- /* xTask is NULL then get the state of the calling task. */
- pxTCB = prvGetTCBFromHandle( xTask );
-
- pxTaskStatus->xHandle = ( TaskHandle_t ) pxTCB;
- pxTaskStatus->pcTaskName = ( const char * ) &( pxTCB->pcTaskName [ 0 ] );
- pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority;
- pxTaskStatus->pxStackBase = pxTCB->pxStack;
- pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber;
-
- #if ( configUSE_MUTEXES == 1 )
- {
- pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority;
- }
- #else
- {
- pxTaskStatus->uxBasePriority = 0;
- }
- #endif
-
- #if ( configGENERATE_RUN_TIME_STATS == 1 )
- {
- pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter;
- }
- #else
- {
- pxTaskStatus->ulRunTimeCounter = 0;
- }
- #endif
-
- /* Obtaining the task state is a little fiddly, so is only done if the
- value of eState passed into this function is eInvalid - otherwise the
- state is just set to whatever is passed in. */
- if( eState != eInvalid )
- {
- if( pxTCB == pxCurrentTCB )
- {
- pxTaskStatus->eCurrentState = eRunning;
- }
- else
- {
- pxTaskStatus->eCurrentState = eState;
-
- #if ( INCLUDE_vTaskSuspend == 1 )
- {
- /* If the task is in the suspended list then there is a
- chance it is actually just blocked indefinitely - so really
- it should be reported as being in the Blocked state. */
- if( eState == eSuspended )
- {
- vTaskSuspendAll();
- {
- if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
- {
- pxTaskStatus->eCurrentState = eBlocked;
- }
- }
- ( void ) xTaskResumeAll();
- }
- }
- #endif /* INCLUDE_vTaskSuspend */
- }
- }
- else
- {
- pxTaskStatus->eCurrentState = eTaskGetState( pxTCB );
- }
-
- /* Obtaining the stack space takes some time, so the xGetFreeStackSpace
- parameter is provided to allow it to be skipped. */
- if( xGetFreeStackSpace != pdFALSE )
- {
- #if ( portSTACK_GROWTH > 0 )
- {
- pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxEndOfStack );
- }
- #else
- {
- pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxTCB->pxStack );
- }
- #endif
- }
- else
- {
- pxTaskStatus->usStackHighWaterMark = 0;
- }
- }
+#if (configUSE_TRACE_FACILITY == 1)
+
+void vTaskGetInfo(TaskHandle_t xTask, TaskStatus_t *pxTaskStatus, BaseType_t xGetFreeStackSpace, eTaskState eState) {
+ TCB_t *pxTCB;
+
+ /* xTask is NULL then get the state of the calling task. */
+ pxTCB = prvGetTCBFromHandle(xTask);
+
+ pxTaskStatus->xHandle = (TaskHandle_t)pxTCB;
+ pxTaskStatus->pcTaskName = (const char *)&(pxTCB->pcTaskName[0]);
+ pxTaskStatus->uxCurrentPriority = pxTCB->uxPriority;
+ pxTaskStatus->pxStackBase = pxTCB->pxStack;
+ pxTaskStatus->xTaskNumber = pxTCB->uxTCBNumber;
+
+#if (configUSE_MUTEXES == 1)
+ { pxTaskStatus->uxBasePriority = pxTCB->uxBasePriority; }
+#else
+ { pxTaskStatus->uxBasePriority = 0; }
+#endif
+
+#if (configGENERATE_RUN_TIME_STATS == 1)
+ { pxTaskStatus->ulRunTimeCounter = pxTCB->ulRunTimeCounter; }
+#else
+ { pxTaskStatus->ulRunTimeCounter = 0; }
+#endif
+
+ /* Obtaining the task state is a little fiddly, so is only done if the
+ value of eState passed into this function is eInvalid - otherwise the
+ state is just set to whatever is passed in. */
+ if (eState != eInvalid) {
+ if (pxTCB == pxCurrentTCB) {
+ pxTaskStatus->eCurrentState = eRunning;
+ } else {
+ pxTaskStatus->eCurrentState = eState;
+
+#if (INCLUDE_vTaskSuspend == 1)
+ {
+ /* If the task is in the suspended list then there is a
+ chance it is actually just blocked indefinitely - so really
+ it should be reported as being in the Blocked state. */
+ if (eState == eSuspended) {
+ vTaskSuspendAll();
+ {
+ if (listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) != NULL) {
+ pxTaskStatus->eCurrentState = eBlocked;
+ }
+ }
+ (void)xTaskResumeAll();
+ }
+ }
+#endif /* INCLUDE_vTaskSuspend */
+ }
+ } else {
+ pxTaskStatus->eCurrentState = eTaskGetState(pxTCB);
+ }
+
+ /* Obtaining the stack space takes some time, so the xGetFreeStackSpace
+ parameter is provided to allow it to be skipped. */
+ if (xGetFreeStackSpace != pdFALSE) {
+#if (portSTACK_GROWTH > 0)
+ { pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace((uint8_t *)pxTCB->pxEndOfStack); }
+#else
+ { pxTaskStatus->usStackHighWaterMark = prvTaskCheckFreeStackSpace((uint8_t *)pxTCB->pxStack); }
+#endif
+ } else {
+ pxTaskStatus->usStackHighWaterMark = 0;
+ }
+}
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
-
- static UBaseType_t prvListTasksWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState )
- {
- configLIST_VOLATILE TCB_t *pxNextTCB, *pxFirstTCB;
- UBaseType_t uxTask = 0;
-
- if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 )
- {
- listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
-
- /* Populate an TaskStatus_t structure within the
- pxTaskStatusArray array for each task that is referenced from
- pxList. See the definition of TaskStatus_t in task.h for the
- meaning of each TaskStatus_t structure member. */
- do
- {
- listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
- vTaskGetInfo( ( TaskHandle_t ) pxNextTCB, &( pxTaskStatusArray[ uxTask ] ), pdTRUE, eState );
- uxTask++;
- } while( pxNextTCB != pxFirstTCB );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- return uxTask;
- }
+#if (configUSE_TRACE_FACILITY == 1)
+
+static UBaseType_t prvListTasksWithinSingleList(TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState) {
+ configLIST_VOLATILE TCB_t *pxNextTCB, *pxFirstTCB;
+ UBaseType_t uxTask = 0;
+
+ if (listCURRENT_LIST_LENGTH(pxList) > (UBaseType_t)0) {
+ listGET_OWNER_OF_NEXT_ENTRY(
+ pxFirstTCB,
+ pxList); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
+
+ /* Populate an TaskStatus_t structure within the
+ pxTaskStatusArray array for each task that is referenced from
+ pxList. See the definition of TaskStatus_t in task.h for the
+ meaning of each TaskStatus_t structure member. */
+ do {
+ listGET_OWNER_OF_NEXT_ENTRY(pxNextTCB, pxList); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the
+ pointer stored and retrieved is the same. */
+ vTaskGetInfo((TaskHandle_t)pxNextTCB, &(pxTaskStatusArray[uxTask]), pdTRUE, eState);
+ uxTask++;
+ } while (pxNextTCB != pxFirstTCB);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return uxTask;
+}
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
-#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) )
+#if ((configUSE_TRACE_FACILITY == 1) || (INCLUDE_uxTaskGetStackHighWaterMark == 1) || (INCLUDE_uxTaskGetStackHighWaterMark2 == 1))
- static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte )
- {
- uint32_t ulCount = 0U;
+static configSTACK_DEPTH_TYPE prvTaskCheckFreeStackSpace(const uint8_t *pucStackByte) {
+ uint32_t ulCount = 0U;
- while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE )
- {
- pucStackByte -= portSTACK_GROWTH;
- ulCount++;
- }
+ while (*pucStackByte == (uint8_t)tskSTACK_FILL_BYTE) {
+ pucStackByte -= portSTACK_GROWTH;
+ ulCount++;
+ }
- ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */
+ ulCount /= (uint32_t)sizeof(StackType_t); /*lint !e961 Casting is not redundant on smaller architectures. */
- return ( configSTACK_DEPTH_TYPE ) ulCount;
- }
+ return (configSTACK_DEPTH_TYPE)ulCount;
+}
#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 ) ) */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_uxTaskGetStackHighWaterMark2 == 1 )
-
- /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the
- same except for their return type. Using configSTACK_DEPTH_TYPE allows the
- user to determine the return type. It gets around the problem of the value
- overflowing on 8-bit types without breaking backward compatibility for
- applications that expect an 8-bit return type. */
- configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2( TaskHandle_t xTask )
- {
- TCB_t *pxTCB;
- uint8_t *pucEndOfStack;
- configSTACK_DEPTH_TYPE uxReturn;
-
- /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are
- the same except for their return type. Using configSTACK_DEPTH_TYPE
- allows the user to determine the return type. It gets around the
- problem of the value overflowing on 8-bit types without breaking
- backward compatibility for applications that expect an 8-bit return
- type. */
-
- pxTCB = prvGetTCBFromHandle( xTask );
-
- #if portSTACK_GROWTH < 0
- {
- pucEndOfStack = ( uint8_t * ) pxTCB->pxStack;
- }
- #else
- {
- pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack;
- }
- #endif
-
- uxReturn = prvTaskCheckFreeStackSpace( pucEndOfStack );
-
- return uxReturn;
- }
+#if (INCLUDE_uxTaskGetStackHighWaterMark2 == 1)
+
+/* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are the
+same except for their return type. Using configSTACK_DEPTH_TYPE allows the
+user to determine the return type. It gets around the problem of the value
+overflowing on 8-bit types without breaking backward compatibility for
+applications that expect an 8-bit return type. */
+configSTACK_DEPTH_TYPE uxTaskGetStackHighWaterMark2(TaskHandle_t xTask) {
+ TCB_t * pxTCB;
+ uint8_t * pucEndOfStack;
+ configSTACK_DEPTH_TYPE uxReturn;
+
+ /* uxTaskGetStackHighWaterMark() and uxTaskGetStackHighWaterMark2() are
+ the same except for their return type. Using configSTACK_DEPTH_TYPE
+ allows the user to determine the return type. It gets around the
+ problem of the value overflowing on 8-bit types without breaking
+ backward compatibility for applications that expect an 8-bit return
+ type. */
+
+ pxTCB = prvGetTCBFromHandle(xTask);
+
+#if portSTACK_GROWTH < 0
+ { pucEndOfStack = (uint8_t *)pxTCB->pxStack; }
+#else
+ { pucEndOfStack = (uint8_t *)pxTCB->pxEndOfStack; }
+#endif
+
+ uxReturn = prvTaskCheckFreeStackSpace(pucEndOfStack);
+
+ return uxReturn;
+}
#endif /* INCLUDE_uxTaskGetStackHighWaterMark2 */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 )
+#if (INCLUDE_uxTaskGetStackHighWaterMark == 1)
- UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask )
- {
- TCB_t *pxTCB;
- uint8_t *pucEndOfStack;
- UBaseType_t uxReturn;
+UBaseType_t uxTaskGetStackHighWaterMark(TaskHandle_t xTask) {
+ TCB_t * pxTCB;
+ uint8_t * pucEndOfStack;
+ UBaseType_t uxReturn;
- pxTCB = prvGetTCBFromHandle( xTask );
+ pxTCB = prvGetTCBFromHandle(xTask);
- #if portSTACK_GROWTH < 0
- {
- pucEndOfStack = ( uint8_t * ) pxTCB->pxStack;
- }
- #else
- {
- pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack;
- }
- #endif
+#if portSTACK_GROWTH < 0
+ { pucEndOfStack = (uint8_t *)pxTCB->pxStack; }
+#else
+ { pucEndOfStack = (uint8_t *)pxTCB->pxEndOfStack; }
+#endif
- uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack );
+ uxReturn = (UBaseType_t)prvTaskCheckFreeStackSpace(pucEndOfStack);
- return uxReturn;
- }
+ return uxReturn;
+}
#endif /* INCLUDE_uxTaskGetStackHighWaterMark */
/*-----------------------------------------------------------*/
-#if ( INCLUDE_vTaskDelete == 1 )
-
- static void prvDeleteTCB( TCB_t *pxTCB )
- {
- /* This call is required specifically for the TriCore port. It must be
- above the vPortFree() calls. The call is also used by ports/demos that
- want to allocate and clean RAM statically. */
- portCLEAN_UP_TCB( pxTCB );
-
- /* Free up the memory allocated by the scheduler for the task. It is up
- to the task to free any memory allocated at the application level.
- See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
- for additional information. */
- #if ( configUSE_NEWLIB_REENTRANT == 1 )
- {
- _reclaim_reent( &( pxTCB->xNewLib_reent ) );
- }
- #endif /* configUSE_NEWLIB_REENTRANT */
-
- #if( ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) && ( configSUPPORT_STATIC_ALLOCATION == 0 ) && ( portUSING_MPU_WRAPPERS == 0 ) )
- {
- /* The task can only have been allocated dynamically - free both
- the stack and TCB. */
- vPortFree( pxTCB->pxStack );
- vPortFree( pxTCB );
- }
- #elif( tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0 ) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
- {
- /* The task could have been allocated statically or dynamically, so
- check what was statically allocated before trying to free the
- memory. */
- if( pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB )
- {
- /* Both the stack and TCB were allocated dynamically, so both
- must be freed. */
- vPortFree( pxTCB->pxStack );
- vPortFree( pxTCB );
- }
- else if( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY )
- {
- /* Only the stack was statically allocated, so the TCB is the
- only memory that must be freed. */
- vPortFree( pxTCB );
- }
- else
- {
- /* Neither the stack nor the TCB were allocated dynamically, so
- nothing needs to be freed. */
- configASSERT( pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB );
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
- }
+#if (INCLUDE_vTaskDelete == 1)
+
+static void prvDeleteTCB(TCB_t *pxTCB) {
+ /* This call is required specifically for the TriCore port. It must be
+ above the vPortFree() calls. The call is also used by ports/demos that
+ want to allocate and clean RAM statically. */
+ portCLEAN_UP_TCB(pxTCB);
+
+/* Free up the memory allocated by the scheduler for the task. It is up
+to the task to free any memory allocated at the application level.
+See the third party link http://www.nadler.com/embedded/newlibAndFreeRTOS.html
+for additional information. */
+#if (configUSE_NEWLIB_REENTRANT == 1)
+ { _reclaim_reent(&(pxTCB->xNewLib_reent)); }
+#endif /* configUSE_NEWLIB_REENTRANT */
+
+#if ((configSUPPORT_DYNAMIC_ALLOCATION == 1) && (configSUPPORT_STATIC_ALLOCATION == 0) && (portUSING_MPU_WRAPPERS == 0))
+ {
+ /* The task can only have been allocated dynamically - free both
+ the stack and TCB. */
+ vPortFree(pxTCB->pxStack);
+ vPortFree(pxTCB);
+ }
+#elif (tskSTATIC_AND_DYNAMIC_ALLOCATION_POSSIBLE != 0) /*lint !e731 !e9029 Macro has been consolidated for readability reasons. */
+ {
+ /* The task could have been allocated statically or dynamically, so
+ check what was statically allocated before trying to free the
+ memory. */
+ if (pxTCB->ucStaticallyAllocated == tskDYNAMICALLY_ALLOCATED_STACK_AND_TCB) {
+ /* Both the stack and TCB were allocated dynamically, so both
+ must be freed. */
+ vPortFree(pxTCB->pxStack);
+ vPortFree(pxTCB);
+ } else if (pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_ONLY) {
+ /* Only the stack was statically allocated, so the TCB is the
+ only memory that must be freed. */
+ vPortFree(pxTCB);
+ } else {
+ /* Neither the stack nor the TCB were allocated dynamically, so
+ nothing needs to be freed. */
+ configASSERT(pxTCB->ucStaticallyAllocated == tskSTATICALLY_ALLOCATED_STACK_AND_TCB);
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
+}
#endif /* INCLUDE_vTaskDelete */
/*-----------------------------------------------------------*/
-static void prvResetNextTaskUnblockTime( void )
-{
-TCB_t *pxTCB;
-
- if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
- {
- /* The new current delayed list is empty. Set xNextTaskUnblockTime to
- the maximum possible value so it is extremely unlikely that the
- if( xTickCount >= xNextTaskUnblockTime ) test will pass until
- there is an item in the delayed list. */
- xNextTaskUnblockTime = portMAX_DELAY;
- }
- else
- {
- /* The new current delayed list is not empty, get the value of
- the item at the head of the delayed list. This is the time at
- which the task at the head of the delayed list should be removed
- from the Blocked state. */
- ( pxTCB ) = listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList ); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
- xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xStateListItem ) );
- }
+static void prvResetNextTaskUnblockTime(void) {
+ TCB_t *pxTCB;
+
+ if (listLIST_IS_EMPTY(pxDelayedTaskList) != pdFALSE) {
+ /* The new current delayed list is empty. Set xNextTaskUnblockTime to
+ the maximum possible value so it is extremely unlikely that the
+ if( xTickCount >= xNextTaskUnblockTime ) test will pass until
+ there is an item in the delayed list. */
+ xNextTaskUnblockTime = portMAX_DELAY;
+ } else {
+ /* The new current delayed list is not empty, get the value of
+ the item at the head of the delayed list. This is the time at
+ which the task at the head of the delayed list should be removed
+ from the Blocked state. */
+ (pxTCB) = listGET_OWNER_OF_HEAD_ENTRY(pxDelayedTaskList); /*lint !e9079 void * is used as this macro is used with timers and co-routines too. Alignment is known to be fine as the type of the
+ pointer stored and retrieved is the same. */
+ xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE(&((pxTCB)->xStateListItem));
+ }
}
/*-----------------------------------------------------------*/
-#if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) )
+#if ((INCLUDE_xTaskGetCurrentTaskHandle == 1) || (configUSE_MUTEXES == 1))
- TaskHandle_t xTaskGetCurrentTaskHandle( void )
- {
- TaskHandle_t xReturn;
+TaskHandle_t xTaskGetCurrentTaskHandle(void) {
+ TaskHandle_t xReturn;
- /* A critical section is not required as this is not called from
- an interrupt and the current TCB will always be the same for any
- individual execution thread. */
- xReturn = pxCurrentTCB;
+ /* A critical section is not required as this is not called from
+ an interrupt and the current TCB will always be the same for any
+ individual execution thread. */
+ xReturn = pxCurrentTCB;
- return xReturn;
- }
+ return xReturn;
+}
#endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */
/*-----------------------------------------------------------*/
-#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
-
- BaseType_t xTaskGetSchedulerState( void )
- {
- BaseType_t xReturn;
-
- if( xSchedulerRunning == pdFALSE )
- {
- xReturn = taskSCHEDULER_NOT_STARTED;
- }
- else
- {
- if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
- {
- xReturn = taskSCHEDULER_RUNNING;
- }
- else
- {
- xReturn = taskSCHEDULER_SUSPENDED;
- }
- }
-
- return xReturn;
- }
+#if ((INCLUDE_xTaskGetSchedulerState == 1) || (configUSE_TIMERS == 1))
+
+BaseType_t xTaskGetSchedulerState(void) {
+ BaseType_t xReturn;
+
+ if (xSchedulerRunning == pdFALSE) {
+ xReturn = taskSCHEDULER_NOT_STARTED;
+ } else {
+ if (uxSchedulerSuspended == (UBaseType_t)pdFALSE) {
+ xReturn = taskSCHEDULER_RUNNING;
+ } else {
+ xReturn = taskSCHEDULER_SUSPENDED;
+ }
+ }
+
+ return xReturn;
+}
#endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */
/*-----------------------------------------------------------*/
-#if ( configUSE_MUTEXES == 1 )
-
- BaseType_t xTaskPriorityInherit( TaskHandle_t const pxMutexHolder )
- {
- TCB_t * const pxMutexHolderTCB = pxMutexHolder;
- BaseType_t xReturn = pdFALSE;
-
- /* If the mutex was given back by an interrupt while the queue was
- locked then the mutex holder might now be NULL. _RB_ Is this still
- needed as interrupts can no longer use mutexes? */
- if( pxMutexHolder != NULL )
- {
- /* If the holder of the mutex has a priority below the priority of
- the task attempting to obtain the mutex then it will temporarily
- inherit the priority of the task attempting to obtain the mutex. */
- if( pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority )
- {
- /* Adjust the mutex holder state to account for its new
- priority. Only reset the event list item value if the value is
- not being used for anything else. */
- if( ( listGET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
- {
- listSET_LIST_ITEM_VALUE( &( pxMutexHolderTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* If the task being modified is in the ready state it will need
- to be moved into a new list. */
- if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxMutexHolderTCB->uxPriority ] ), &( pxMutexHolderTCB->xStateListItem ) ) != pdFALSE )
- {
- if( uxListRemove( &( pxMutexHolderTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
- {
- /* It is known that the task is in its ready list so
- there is no need to check again and the port level
- reset macro can be called directly. */
- portRESET_READY_PRIORITY( pxMutexHolderTCB->uxPriority, uxTopReadyPriority );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Inherit the priority before being moved into the new list. */
- pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
- prvAddTaskToReadyList( pxMutexHolderTCB );
- }
- else
- {
- /* Just inherit the priority. */
- pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
- }
-
- traceTASK_PRIORITY_INHERIT( pxMutexHolderTCB, pxCurrentTCB->uxPriority );
-
- /* Inheritance occurred. */
- xReturn = pdTRUE;
- }
- else
- {
- if( pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority )
- {
- /* The base priority of the mutex holder is lower than the
- priority of the task attempting to take the mutex, but the
- current priority of the mutex holder is not lower than the
- priority of the task attempting to take the mutex.
- Therefore the mutex holder must have already inherited a
- priority, but inheritance would have occurred if that had
- not been the case. */
- xReturn = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- return xReturn;
- }
+#if (configUSE_MUTEXES == 1)
+
+BaseType_t xTaskPriorityInherit(TaskHandle_t const pxMutexHolder) {
+ TCB_t *const pxMutexHolderTCB = pxMutexHolder;
+ BaseType_t xReturn = pdFALSE;
+
+ /* If the mutex was given back by an interrupt while the queue was
+ locked then the mutex holder might now be NULL. _RB_ Is this still
+ needed as interrupts can no longer use mutexes? */
+ if (pxMutexHolder != NULL) {
+ /* If the holder of the mutex has a priority below the priority of
+ the task attempting to obtain the mutex then it will temporarily
+ inherit the priority of the task attempting to obtain the mutex. */
+ if (pxMutexHolderTCB->uxPriority < pxCurrentTCB->uxPriority) {
+ /* Adjust the mutex holder state to account for its new
+ priority. Only reset the event list item value if the value is
+ not being used for anything else. */
+ if ((listGET_LIST_ITEM_VALUE(&(pxMutexHolderTCB->xEventListItem)) & taskEVENT_LIST_ITEM_VALUE_IN_USE) == 0UL) {
+ listSET_LIST_ITEM_VALUE(&(pxMutexHolderTCB->xEventListItem),
+ (TickType_t)configMAX_PRIORITIES - (TickType_t)pxCurrentTCB->uxPriority); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* If the task being modified is in the ready state it will need
+ to be moved into a new list. */
+ if (listIS_CONTAINED_WITHIN(&(pxReadyTasksLists[pxMutexHolderTCB->uxPriority]), &(pxMutexHolderTCB->xStateListItem)) != pdFALSE) {
+ if (uxListRemove(&(pxMutexHolderTCB->xStateListItem)) == (UBaseType_t)0) {
+ /* It is known that the task is in its ready list so
+ there is no need to check again and the port level
+ reset macro can be called directly. */
+ portRESET_READY_PRIORITY(pxMutexHolderTCB->uxPriority, uxTopReadyPriority);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Inherit the priority before being moved into the new list. */
+ pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
+ prvAddTaskToReadyList(pxMutexHolderTCB);
+ } else {
+ /* Just inherit the priority. */
+ pxMutexHolderTCB->uxPriority = pxCurrentTCB->uxPriority;
+ }
+
+ traceTASK_PRIORITY_INHERIT(pxMutexHolderTCB, pxCurrentTCB->uxPriority);
+
+ /* Inheritance occurred. */
+ xReturn = pdTRUE;
+ } else {
+ if (pxMutexHolderTCB->uxBasePriority < pxCurrentTCB->uxPriority) {
+ /* The base priority of the mutex holder is lower than the
+ priority of the task attempting to take the mutex, but the
+ current priority of the mutex holder is not lower than the
+ priority of the task attempting to take the mutex.
+ Therefore the mutex holder must have already inherited a
+ priority, but inheritance would have occurred if that had
+ not been the case. */
+ xReturn = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return xReturn;
+}
#endif /* configUSE_MUTEXES */
/*-----------------------------------------------------------*/
-#if ( configUSE_MUTEXES == 1 )
-
- BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder )
- {
- TCB_t * const pxTCB = pxMutexHolder;
- BaseType_t xReturn = pdFALSE;
-
- if( pxMutexHolder != NULL )
- {
- /* A task can only have an inherited priority if it holds the mutex.
- If the mutex is held by a task then it cannot be given from an
- interrupt, and if a mutex is given by the holding task then it must
- be the running state task. */
- configASSERT( pxTCB == pxCurrentTCB );
- configASSERT( pxTCB->uxMutexesHeld );
- ( pxTCB->uxMutexesHeld )--;
-
- /* Has the holder of the mutex inherited the priority of another
- task? */
- if( pxTCB->uxPriority != pxTCB->uxBasePriority )
- {
- /* Only disinherit if no other mutexes are held. */
- if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 )
- {
- /* A task can only have an inherited priority if it holds
- the mutex. If the mutex is held by a task then it cannot be
- given from an interrupt, and if a mutex is given by the
- holding task then it must be the running state task. Remove
- the holding task from the ready/delayed list. */
- if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
- {
- taskRESET_READY_PRIORITY( pxTCB->uxPriority );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Disinherit the priority before adding the task into the
- new ready list. */
- traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority );
- pxTCB->uxPriority = pxTCB->uxBasePriority;
-
- /* Reset the event list item value. It cannot be in use for
- any other purpose if this task is running, and it must be
- running to give back the mutex. */
- listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
- prvAddTaskToReadyList( pxTCB );
-
- /* Return true to indicate that a context switch is required.
- This is only actually required in the corner case whereby
- multiple mutexes were held and the mutexes were given back
- in an order different to that in which they were taken.
- If a context switch did not occur when the first mutex was
- returned, even if a task was waiting on it, then a context
- switch should occur when the last mutex is returned whether
- a task is waiting on it or not. */
- xReturn = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- return xReturn;
- }
+#if (configUSE_MUTEXES == 1)
+
+BaseType_t xTaskPriorityDisinherit(TaskHandle_t const pxMutexHolder) {
+ TCB_t *const pxTCB = pxMutexHolder;
+ BaseType_t xReturn = pdFALSE;
+
+ if (pxMutexHolder != NULL) {
+ /* A task can only have an inherited priority if it holds the mutex.
+ If the mutex is held by a task then it cannot be given from an
+ interrupt, and if a mutex is given by the holding task then it must
+ be the running state task. */
+ configASSERT(pxTCB == pxCurrentTCB);
+ configASSERT(pxTCB->uxMutexesHeld);
+ (pxTCB->uxMutexesHeld)--;
+
+ /* Has the holder of the mutex inherited the priority of another
+ task? */
+ if (pxTCB->uxPriority != pxTCB->uxBasePriority) {
+ /* Only disinherit if no other mutexes are held. */
+ if (pxTCB->uxMutexesHeld == (UBaseType_t)0) {
+ /* A task can only have an inherited priority if it holds
+ the mutex. If the mutex is held by a task then it cannot be
+ given from an interrupt, and if a mutex is given by the
+ holding task then it must be the running state task. Remove
+ the holding task from the ready/delayed list. */
+ if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0) {
+ taskRESET_READY_PRIORITY(pxTCB->uxPriority);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Disinherit the priority before adding the task into the
+ new ready list. */
+ traceTASK_PRIORITY_DISINHERIT(pxTCB, pxTCB->uxBasePriority);
+ pxTCB->uxPriority = pxTCB->uxBasePriority;
+
+ /* Reset the event list item value. It cannot be in use for
+ any other purpose if this task is running, and it must be
+ running to give back the mutex. */
+ listSET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem),
+ (TickType_t)configMAX_PRIORITIES - (TickType_t)pxTCB->uxPriority); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+ prvAddTaskToReadyList(pxTCB);
+
+ /* Return true to indicate that a context switch is required.
+ This is only actually required in the corner case whereby
+ multiple mutexes were held and the mutexes were given back
+ in an order different to that in which they were taken.
+ If a context switch did not occur when the first mutex was
+ returned, even if a task was waiting on it, then a context
+ switch should occur when the last mutex is returned whether
+ a task is waiting on it or not. */
+ xReturn = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return xReturn;
+}
#endif /* configUSE_MUTEXES */
/*-----------------------------------------------------------*/
-#if ( configUSE_MUTEXES == 1 )
-
- void vTaskPriorityDisinheritAfterTimeout( TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask )
- {
- TCB_t * const pxTCB = pxMutexHolder;
- UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse;
- const UBaseType_t uxOnlyOneMutexHeld = ( UBaseType_t ) 1;
-
- if( pxMutexHolder != NULL )
- {
- /* If pxMutexHolder is not NULL then the holder must hold at least
- one mutex. */
- configASSERT( pxTCB->uxMutexesHeld );
-
- /* Determine the priority to which the priority of the task that
- holds the mutex should be set. This will be the greater of the
- holding task's base priority and the priority of the highest
- priority task that is waiting to obtain the mutex. */
- if( pxTCB->uxBasePriority < uxHighestPriorityWaitingTask )
- {
- uxPriorityToUse = uxHighestPriorityWaitingTask;
- }
- else
- {
- uxPriorityToUse = pxTCB->uxBasePriority;
- }
-
- /* Does the priority need to change? */
- if( pxTCB->uxPriority != uxPriorityToUse )
- {
- /* Only disinherit if no other mutexes are held. This is a
- simplification in the priority inheritance implementation. If
- the task that holds the mutex is also holding other mutexes then
- the other mutexes may have caused the priority inheritance. */
- if( pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld )
- {
- /* If a task has timed out because it already holds the
- mutex it was trying to obtain then it cannot of inherited
- its own priority. */
- configASSERT( pxTCB != pxCurrentTCB );
-
- /* Disinherit the priority, remembering the previous
- priority to facilitate determining the subject task's
- state. */
- traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority );
- uxPriorityUsedOnEntry = pxTCB->uxPriority;
- pxTCB->uxPriority = uxPriorityToUse;
-
- /* Only reset the event list item value if the value is not
- being used for anything else. */
- if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
- {
- listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriorityToUse ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* If the running task is not the task that holds the mutex
- then the task that holds the mutex could be in either the
- Ready, Blocked or Suspended states. Only remove the task
- from its current state list if it is in the Ready state as
- the task's priority is going to change and there is one
- Ready list per priority. */
- if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xStateListItem ) ) != pdFALSE )
- {
- if( uxListRemove( &( pxTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
- {
- /* It is known that the task is in its ready list so
- there is no need to check again and the port level
- reset macro can be called directly. */
- portRESET_READY_PRIORITY( pxTCB->uxPriority, uxTopReadyPriority );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- prvAddTaskToReadyList( pxTCB );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
+#if (configUSE_MUTEXES == 1)
+
+void vTaskPriorityDisinheritAfterTimeout(TaskHandle_t const pxMutexHolder, UBaseType_t uxHighestPriorityWaitingTask) {
+ TCB_t *const pxTCB = pxMutexHolder;
+ UBaseType_t uxPriorityUsedOnEntry, uxPriorityToUse;
+ const UBaseType_t uxOnlyOneMutexHeld = (UBaseType_t)1;
+
+ if (pxMutexHolder != NULL) {
+ /* If pxMutexHolder is not NULL then the holder must hold at least
+ one mutex. */
+ configASSERT(pxTCB->uxMutexesHeld);
+
+ /* Determine the priority to which the priority of the task that
+ holds the mutex should be set. This will be the greater of the
+ holding task's base priority and the priority of the highest
+ priority task that is waiting to obtain the mutex. */
+ if (pxTCB->uxBasePriority < uxHighestPriorityWaitingTask) {
+ uxPriorityToUse = uxHighestPriorityWaitingTask;
+ } else {
+ uxPriorityToUse = pxTCB->uxBasePriority;
+ }
+
+ /* Does the priority need to change? */
+ if (pxTCB->uxPriority != uxPriorityToUse) {
+ /* Only disinherit if no other mutexes are held. This is a
+ simplification in the priority inheritance implementation. If
+ the task that holds the mutex is also holding other mutexes then
+ the other mutexes may have caused the priority inheritance. */
+ if (pxTCB->uxMutexesHeld == uxOnlyOneMutexHeld) {
+ /* If a task has timed out because it already holds the
+ mutex it was trying to obtain then it cannot of inherited
+ its own priority. */
+ configASSERT(pxTCB != pxCurrentTCB);
+
+ /* Disinherit the priority, remembering the previous
+ priority to facilitate determining the subject task's
+ state. */
+ traceTASK_PRIORITY_DISINHERIT(pxTCB, pxTCB->uxBasePriority);
+ uxPriorityUsedOnEntry = pxTCB->uxPriority;
+ pxTCB->uxPriority = uxPriorityToUse;
+
+ /* Only reset the event list item value if the value is not
+ being used for anything else. */
+ if ((listGET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem)) & taskEVENT_LIST_ITEM_VALUE_IN_USE) == 0UL) {
+ listSET_LIST_ITEM_VALUE(&(pxTCB->xEventListItem),
+ (TickType_t)configMAX_PRIORITIES - (TickType_t)uxPriorityToUse); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* If the running task is not the task that holds the mutex
+ then the task that holds the mutex could be in either the
+ Ready, Blocked or Suspended states. Only remove the task
+ from its current state list if it is in the Ready state as
+ the task's priority is going to change and there is one
+ Ready list per priority. */
+ if (listIS_CONTAINED_WITHIN(&(pxReadyTasksLists[uxPriorityUsedOnEntry]), &(pxTCB->xStateListItem)) != pdFALSE) {
+ if (uxListRemove(&(pxTCB->xStateListItem)) == (UBaseType_t)0) {
+ /* It is known that the task is in its ready list so
+ there is no need to check again and the port level
+ reset macro can be called directly. */
+ portRESET_READY_PRIORITY(pxTCB->uxPriority, uxTopReadyPriority);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ prvAddTaskToReadyList(pxTCB);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+}
#endif /* configUSE_MUTEXES */
/*-----------------------------------------------------------*/
-#if ( portCRITICAL_NESTING_IN_TCB == 1 )
-
- void vTaskEnterCritical( void )
- {
- portDISABLE_INTERRUPTS();
-
- if( xSchedulerRunning != pdFALSE )
- {
- ( pxCurrentTCB->uxCriticalNesting )++;
-
- /* This is not the interrupt safe version of the enter critical
- function so assert() if it is being called from an interrupt
- context. Only API functions that end in "FromISR" can be used in an
- interrupt. Only assert if the critical nesting count is 1 to
- protect against recursive calls if the assert function also uses a
- critical section. */
- if( pxCurrentTCB->uxCriticalNesting == 1 )
- {
- portASSERT_IF_IN_ISR();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
+#if (portCRITICAL_NESTING_IN_TCB == 1)
+
+void vTaskEnterCritical(void) {
+ portDISABLE_INTERRUPTS();
+
+ if (xSchedulerRunning != pdFALSE) {
+ (pxCurrentTCB->uxCriticalNesting)++;
+
+ /* This is not the interrupt safe version of the enter critical
+ function so assert() if it is being called from an interrupt
+ context. Only API functions that end in "FromISR" can be used in an
+ interrupt. Only assert if the critical nesting count is 1 to
+ protect against recursive calls if the assert function also uses a
+ critical section. */
+ if (pxCurrentTCB->uxCriticalNesting == 1) {
+ portASSERT_IF_IN_ISR();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+}
#endif /* portCRITICAL_NESTING_IN_TCB */
/*-----------------------------------------------------------*/
-#if ( portCRITICAL_NESTING_IN_TCB == 1 )
-
- void vTaskExitCritical( void )
- {
- if( xSchedulerRunning != pdFALSE )
- {
- if( pxCurrentTCB->uxCriticalNesting > 0U )
- {
- ( pxCurrentTCB->uxCriticalNesting )--;
-
- if( pxCurrentTCB->uxCriticalNesting == 0U )
- {
- portENABLE_INTERRUPTS();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
+#if (portCRITICAL_NESTING_IN_TCB == 1)
+
+void vTaskExitCritical(void) {
+ if (xSchedulerRunning != pdFALSE) {
+ if (pxCurrentTCB->uxCriticalNesting > 0U) {
+ (pxCurrentTCB->uxCriticalNesting)--;
+
+ if (pxCurrentTCB->uxCriticalNesting == 0U) {
+ portENABLE_INTERRUPTS();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+}
#endif /* portCRITICAL_NESTING_IN_TCB */
/*-----------------------------------------------------------*/
-#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) )
+#if ((configUSE_TRACE_FACILITY == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS > 0))
- static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName )
- {
- size_t x;
+static char *prvWriteNameToBuffer(char *pcBuffer, const char *pcTaskName) {
+ size_t x;
- /* Start by copying the entire string. */
- strcpy( pcBuffer, pcTaskName );
+ /* Start by copying the entire string. */
+ strcpy(pcBuffer, pcTaskName);
- /* Pad the end of the string with spaces to ensure columns line up when
- printed out. */
- for( x = strlen( pcBuffer ); x < ( size_t ) ( configMAX_TASK_NAME_LEN - 1 ); x++ )
- {
- pcBuffer[ x ] = ' ';
- }
+ /* Pad the end of the string with spaces to ensure columns line up when
+ printed out. */
+ for (x = strlen(pcBuffer); x < (size_t)(configMAX_TASK_NAME_LEN - 1); x++) {
+ pcBuffer[x] = ' ';
+ }
- /* Terminate. */
- pcBuffer[ x ] = ( char ) 0x00;
+ /* Terminate. */
+ pcBuffer[x] = (char)0x00;
- /* Return the new end of string. */
- return &( pcBuffer[ x ] );
- }
+ /* Return the new end of string. */
+ return &(pcBuffer[x]);
+}
#endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */
/*-----------------------------------------------------------*/
-#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
-
- void vTaskList( char * pcWriteBuffer )
- {
- TaskStatus_t *pxTaskStatusArray;
- UBaseType_t uxArraySize, x;
- char cStatus;
-
- /*
- * PLEASE NOTE:
- *
- * This function is provided for convenience only, and is used by many
- * of the demo applications. Do not consider it to be part of the
- * scheduler.
- *
- * vTaskList() calls uxTaskGetSystemState(), then formats part of the
- * uxTaskGetSystemState() output into a human readable table that
- * displays task names, states and stack usage.
- *
- * vTaskList() has a dependency on the sprintf() C library function that
- * might bloat the code size, use a lot of stack, and provide different
- * results on different platforms. An alternative, tiny, third party,
- * and limited functionality implementation of sprintf() is provided in
- * many of the FreeRTOS/Demo sub-directories in a file called
- * printf-stdarg.c (note printf-stdarg.c does not provide a full
- * snprintf() implementation!).
- *
- * It is recommended that production systems call uxTaskGetSystemState()
- * directly to get access to raw stats data, rather than indirectly
- * through a call to vTaskList().
- */
-
-
- /* Make sure the write buffer does not contain a string. */
- *pcWriteBuffer = ( char ) 0x00;
-
- /* Take a snapshot of the number of tasks in case it changes while this
- function is executing. */
- uxArraySize = uxCurrentNumberOfTasks;
-
- /* Allocate an array index for each task. NOTE! if
- configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will
- equate to NULL. */
- pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */
-
- if( pxTaskStatusArray != NULL )
- {
- /* Generate the (binary) data. */
- uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL );
-
- /* Create a human readable table from the binary data. */
- for( x = 0; x < uxArraySize; x++ )
- {
- switch( pxTaskStatusArray[ x ].eCurrentState )
- {
- case eRunning: cStatus = tskRUNNING_CHAR;
- break;
-
- case eReady: cStatus = tskREADY_CHAR;
- break;
-
- case eBlocked: cStatus = tskBLOCKED_CHAR;
- break;
-
- case eSuspended: cStatus = tskSUSPENDED_CHAR;
- break;
-
- case eDeleted: cStatus = tskDELETED_CHAR;
- break;
-
- case eInvalid: /* Fall through. */
- default: /* Should not get here, but it is included
- to prevent static checking errors. */
- cStatus = ( char ) 0x00;
- break;
- }
-
- /* Write the task name to the string, padding with spaces so it
- can be printed in tabular form more easily. */
- pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName );
-
- /* Write the rest of the string. */
- sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */
- pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */
- }
-
- /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION
- is 0 then vPortFree() will be #defined to nothing. */
- vPortFree( pxTaskStatusArray );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
+#if ((configUSE_TRACE_FACILITY == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS > 0) && (configSUPPORT_DYNAMIC_ALLOCATION == 1))
+
+void vTaskList(char *pcWriteBuffer) {
+ TaskStatus_t *pxTaskStatusArray;
+ UBaseType_t uxArraySize, x;
+ char cStatus;
+
+ /*
+ * PLEASE NOTE:
+ *
+ * This function is provided for convenience only, and is used by many
+ * of the demo applications. Do not consider it to be part of the
+ * scheduler.
+ *
+ * vTaskList() calls uxTaskGetSystemState(), then formats part of the
+ * uxTaskGetSystemState() output into a human readable table that
+ * displays task names, states and stack usage.
+ *
+ * vTaskList() has a dependency on the sprintf() C library function that
+ * might bloat the code size, use a lot of stack, and provide different
+ * results on different platforms. An alternative, tiny, third party,
+ * and limited functionality implementation of sprintf() is provided in
+ * many of the FreeRTOS/Demo sub-directories in a file called
+ * printf-stdarg.c (note printf-stdarg.c does not provide a full
+ * snprintf() implementation!).
+ *
+ * It is recommended that production systems call uxTaskGetSystemState()
+ * directly to get access to raw stats data, rather than indirectly
+ * through a call to vTaskList().
+ */
+
+ /* Make sure the write buffer does not contain a string. */
+ *pcWriteBuffer = (char)0x00;
+
+ /* Take a snapshot of the number of tasks in case it changes while this
+ function is executing. */
+ uxArraySize = uxCurrentNumberOfTasks;
+
+ /* Allocate an array index for each task. NOTE! if
+ configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will
+ equate to NULL. */
+ pxTaskStatusArray = pvPortMalloc(uxCurrentNumberOfTasks * sizeof(TaskStatus_t)); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and
+ this allocation allocates a struct that has the alignment requirements of a pointer. */
+
+ if (pxTaskStatusArray != NULL) {
+ /* Generate the (binary) data. */
+ uxArraySize = uxTaskGetSystemState(pxTaskStatusArray, uxArraySize, NULL);
+
+ /* Create a human readable table from the binary data. */
+ for (x = 0; x < uxArraySize; x++) {
+ switch (pxTaskStatusArray[x].eCurrentState) {
+ case eRunning:
+ cStatus = tskRUNNING_CHAR;
+ break;
+
+ case eReady:
+ cStatus = tskREADY_CHAR;
+ break;
+
+ case eBlocked:
+ cStatus = tskBLOCKED_CHAR;
+ break;
+
+ case eSuspended:
+ cStatus = tskSUSPENDED_CHAR;
+ break;
+
+ case eDeleted:
+ cStatus = tskDELETED_CHAR;
+ break;
+
+ case eInvalid: /* Fall through. */
+ default: /* Should not get here, but it is included
+ to prevent static checking errors. */
+ cStatus = (char)0x00;
+ break;
+ }
+
+ /* Write the task name to the string, padding with spaces so it
+ can be printed in tabular form more easily. */
+ pcWriteBuffer = prvWriteNameToBuffer(pcWriteBuffer, pxTaskStatusArray[x].pcTaskName);
+
+ /* Write the rest of the string. */
+ sprintf(pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, (unsigned int)pxTaskStatusArray[x].uxCurrentPriority, (unsigned int)pxTaskStatusArray[x].usStackHighWaterMark,
+ (unsigned int)pxTaskStatusArray[x]
+ .xTaskNumber); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */
+ pcWriteBuffer += strlen(pcWriteBuffer); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */
+ }
+
+ /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION
+ is 0 then vPortFree() will be #defined to nothing. */
+ vPortFree(pxTaskStatusArray);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+}
#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) ) */
/*----------------------------------------------------------*/
-#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_DYNAMIC_ALLOCATION == 1 ) )
-
- void vTaskGetRunTimeStats( char *pcWriteBuffer )
- {
- TaskStatus_t *pxTaskStatusArray;
- UBaseType_t uxArraySize, x;
- uint32_t ulTotalTime, ulStatsAsPercentage;
-
- #if( configUSE_TRACE_FACILITY != 1 )
- {
- #error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats().
- }
- #endif
-
- /*
- * PLEASE NOTE:
- *
- * This function is provided for convenience only, and is used by many
- * of the demo applications. Do not consider it to be part of the
- * scheduler.
- *
- * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part
- * of the uxTaskGetSystemState() output into a human readable table that
- * displays the amount of time each task has spent in the Running state
- * in both absolute and percentage terms.
- *
- * vTaskGetRunTimeStats() has a dependency on the sprintf() C library
- * function that might bloat the code size, use a lot of stack, and
- * provide different results on different platforms. An alternative,
- * tiny, third party, and limited functionality implementation of
- * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in
- * a file called printf-stdarg.c (note printf-stdarg.c does not provide
- * a full snprintf() implementation!).
- *
- * It is recommended that production systems call uxTaskGetSystemState()
- * directly to get access to raw stats data, rather than indirectly
- * through a call to vTaskGetRunTimeStats().
- */
-
- /* Make sure the write buffer does not contain a string. */
- *pcWriteBuffer = ( char ) 0x00;
-
- /* Take a snapshot of the number of tasks in case it changes while this
- function is executing. */
- uxArraySize = uxCurrentNumberOfTasks;
-
- /* Allocate an array index for each task. NOTE! If
- configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will
- equate to NULL. */
- pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) ); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and this allocation allocates a struct that has the alignment requirements of a pointer. */
-
- if( pxTaskStatusArray != NULL )
- {
- /* Generate the (binary) data. */
- uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime );
-
- /* For percentage calculations. */
- ulTotalTime /= 100UL;
-
- /* Avoid divide by zero errors. */
- if( ulTotalTime > 0UL )
- {
- /* Create a human readable table from the binary data. */
- for( x = 0; x < uxArraySize; x++ )
- {
- /* What percentage of the total run time has the task used?
- This will always be rounded down to the nearest integer.
- ulTotalRunTimeDiv100 has already been divided by 100. */
- ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime;
-
- /* Write the task name to the string, padding with
- spaces so it can be printed in tabular form more
- easily. */
- pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName );
-
- if( ulStatsAsPercentage > 0UL )
- {
- #ifdef portLU_PRINTF_SPECIFIER_REQUIRED
- {
- sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
- }
- #else
- {
- /* sizeof( int ) == sizeof( long ) so a smaller
- printf() library can be used. */
- sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */
- }
- #endif
- }
- else
- {
- /* If the percentage is zero here then the task has
- consumed less than 1% of the total run time. */
- #ifdef portLU_PRINTF_SPECIFIER_REQUIRED
- {
- sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter );
- }
- #else
- {
- /* sizeof( int ) == sizeof( long ) so a smaller
- printf() library can be used. */
- sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter ); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core kernel implementation. */
- }
- #endif
- }
-
- pcWriteBuffer += strlen( pcWriteBuffer ); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION
- is 0 then vPortFree() will be #defined to nothing. */
- vPortFree( pxTaskStatusArray );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
+#if ((configGENERATE_RUN_TIME_STATS == 1) && (configUSE_STATS_FORMATTING_FUNCTIONS > 0) && (configSUPPORT_DYNAMIC_ALLOCATION == 1))
+
+void vTaskGetRunTimeStats(char *pcWriteBuffer) {
+ TaskStatus_t *pxTaskStatusArray;
+ UBaseType_t uxArraySize, x;
+ uint32_t ulTotalTime, ulStatsAsPercentage;
+
+#if (configUSE_TRACE_FACILITY != 1)
+ {
+#error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats().
+ }
+#endif
+
+ /*
+ * PLEASE NOTE:
+ *
+ * This function is provided for convenience only, and is used by many
+ * of the demo applications. Do not consider it to be part of the
+ * scheduler.
+ *
+ * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part
+ * of the uxTaskGetSystemState() output into a human readable table that
+ * displays the amount of time each task has spent in the Running state
+ * in both absolute and percentage terms.
+ *
+ * vTaskGetRunTimeStats() has a dependency on the sprintf() C library
+ * function that might bloat the code size, use a lot of stack, and
+ * provide different results on different platforms. An alternative,
+ * tiny, third party, and limited functionality implementation of
+ * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in
+ * a file called printf-stdarg.c (note printf-stdarg.c does not provide
+ * a full snprintf() implementation!).
+ *
+ * It is recommended that production systems call uxTaskGetSystemState()
+ * directly to get access to raw stats data, rather than indirectly
+ * through a call to vTaskGetRunTimeStats().
+ */
+
+ /* Make sure the write buffer does not contain a string. */
+ *pcWriteBuffer = (char)0x00;
+
+ /* Take a snapshot of the number of tasks in case it changes while this
+ function is executing. */
+ uxArraySize = uxCurrentNumberOfTasks;
+
+ /* Allocate an array index for each task. NOTE! If
+ configSUPPORT_DYNAMIC_ALLOCATION is set to 0 then pvPortMalloc() will
+ equate to NULL. */
+ pxTaskStatusArray = pvPortMalloc(uxCurrentNumberOfTasks * sizeof(TaskStatus_t)); /*lint !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack and
+ this allocation allocates a struct that has the alignment requirements of a pointer. */
+
+ if (pxTaskStatusArray != NULL) {
+ /* Generate the (binary) data. */
+ uxArraySize = uxTaskGetSystemState(pxTaskStatusArray, uxArraySize, &ulTotalTime);
+
+ /* For percentage calculations. */
+ ulTotalTime /= 100UL;
+
+ /* Avoid divide by zero errors. */
+ if (ulTotalTime > 0UL) {
+ /* Create a human readable table from the binary data. */
+ for (x = 0; x < uxArraySize; x++) {
+ /* What percentage of the total run time has the task used?
+ This will always be rounded down to the nearest integer.
+ ulTotalRunTimeDiv100 has already been divided by 100. */
+ ulStatsAsPercentage = pxTaskStatusArray[x].ulRunTimeCounter / ulTotalTime;
+
+ /* Write the task name to the string, padding with
+ spaces so it can be printed in tabular form more
+ easily. */
+ pcWriteBuffer = prvWriteNameToBuffer(pcWriteBuffer, pxTaskStatusArray[x].pcTaskName);
+
+ if (ulStatsAsPercentage > 0UL) {
+#ifdef portLU_PRINTF_SPECIFIER_REQUIRED
+ { sprintf(pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[x].ulRunTimeCounter, ulStatsAsPercentage); }
+#else
+ {
+ /* sizeof( int ) == sizeof( long ) so a smaller
+ printf() library can be used. */
+ sprintf(pcWriteBuffer, "\t%u\t\t%u%%\r\n", (unsigned int)pxTaskStatusArray[x].ulRunTimeCounter,
+ (unsigned int)ulStatsAsPercentage); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this is a utility function only - not part of the core
+ kernel implementation. */
+ }
+#endif
+ } else {
+/* If the percentage is zero here then the task has
+consumed less than 1% of the total run time. */
+#ifdef portLU_PRINTF_SPECIFIER_REQUIRED
+ { sprintf(pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[x].ulRunTimeCounter); }
+#else
+ {
+ /* sizeof( int ) == sizeof( long ) so a smaller
+ printf() library can be used. */
+ sprintf(pcWriteBuffer, "\t%u\t\t<1%%\r\n", (unsigned int)pxTaskStatusArray[x].ulRunTimeCounter); /*lint !e586 sprintf() allowed as this is compiled with many compilers and this
+ is a utility function only - not part of the core kernel implementation. */
+ }
+#endif
+ }
+
+ pcWriteBuffer += strlen(pcWriteBuffer); /*lint !e9016 Pointer arithmetic ok on char pointers especially as in this case where it best denotes the intent of the code. */
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Free the array again. NOTE! If configSUPPORT_DYNAMIC_ALLOCATION
+ is 0 then vPortFree() will be #defined to nothing. */
+ vPortFree(pxTaskStatusArray);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+}
#endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) && ( configSUPPORT_STATIC_ALLOCATION == 1 ) ) */
/*-----------------------------------------------------------*/
-TickType_t uxTaskResetEventItemValue( void )
-{
-TickType_t uxReturn;
+TickType_t uxTaskResetEventItemValue(void) {
+ TickType_t uxReturn;
- uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) );
+ uxReturn = listGET_LIST_ITEM_VALUE(&(pxCurrentTCB->xEventListItem));
- /* Reset the event list item to its normal value - so it can be used with
- queues and semaphores. */
- listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+ /* Reset the event list item to its normal value - so it can be used with
+ queues and semaphores. */
+ listSET_LIST_ITEM_VALUE(&(pxCurrentTCB->xEventListItem),
+ ((TickType_t)configMAX_PRIORITIES - (TickType_t)pxCurrentTCB->uxPriority)); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
- return uxReturn;
+ return uxReturn;
}
/*-----------------------------------------------------------*/
-#if ( configUSE_MUTEXES == 1 )
+#if (configUSE_MUTEXES == 1)
- TaskHandle_t pvTaskIncrementMutexHeldCount( void )
- {
- /* If xSemaphoreCreateMutex() is called before any tasks have been created
- then pxCurrentTCB will be NULL. */
- if( pxCurrentTCB != NULL )
- {
- ( pxCurrentTCB->uxMutexesHeld )++;
- }
+TaskHandle_t pvTaskIncrementMutexHeldCount(void) {
+ /* If xSemaphoreCreateMutex() is called before any tasks have been created
+ then pxCurrentTCB will be NULL. */
+ if (pxCurrentTCB != NULL) {
+ (pxCurrentTCB->uxMutexesHeld)++;
+ }
- return pxCurrentTCB;
- }
+ return pxCurrentTCB;
+}
#endif /* configUSE_MUTEXES */
/*-----------------------------------------------------------*/
-#if( configUSE_TASK_NOTIFICATIONS == 1 )
-
- uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait )
- {
- uint32_t ulReturn;
-
- taskENTER_CRITICAL();
- {
- /* Only block if the notification count is not already non-zero. */
- if( pxCurrentTCB->ulNotifiedValue == 0UL )
- {
- /* Mark this task as waiting for a notification. */
- pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION;
-
- if( xTicksToWait > ( TickType_t ) 0 )
- {
- prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
- traceTASK_NOTIFY_TAKE_BLOCK();
-
- /* All ports are written to allow a yield in a critical
- section (some will yield immediately, others wait until the
- critical section exits) - but it is not something that
- application code should ever do. */
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- taskEXIT_CRITICAL();
-
- taskENTER_CRITICAL();
- {
- traceTASK_NOTIFY_TAKE();
- ulReturn = pxCurrentTCB->ulNotifiedValue;
-
- if( ulReturn != 0UL )
- {
- if( xClearCountOnExit != pdFALSE )
- {
- pxCurrentTCB->ulNotifiedValue = 0UL;
- }
- else
- {
- pxCurrentTCB->ulNotifiedValue = ulReturn - ( uint32_t ) 1;
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
- }
- taskEXIT_CRITICAL();
-
- return ulReturn;
- }
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+
+uint32_t ulTaskNotifyTake(BaseType_t xClearCountOnExit, TickType_t xTicksToWait) {
+ uint32_t ulReturn;
+
+ taskENTER_CRITICAL();
+ {
+ /* Only block if the notification count is not already non-zero. */
+ if (pxCurrentTCB->ulNotifiedValue == 0UL) {
+ /* Mark this task as waiting for a notification. */
+ pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION;
+
+ if (xTicksToWait > (TickType_t)0) {
+ prvAddCurrentTaskToDelayedList(xTicksToWait, pdTRUE);
+ traceTASK_NOTIFY_TAKE_BLOCK();
+
+ /* All ports are written to allow a yield in a critical
+ section (some will yield immediately, others wait until the
+ critical section exits) - but it is not something that
+ application code should ever do. */
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ taskENTER_CRITICAL();
+ {
+ traceTASK_NOTIFY_TAKE();
+ ulReturn = pxCurrentTCB->ulNotifiedValue;
+
+ if (ulReturn != 0UL) {
+ if (xClearCountOnExit != pdFALSE) {
+ pxCurrentTCB->ulNotifiedValue = 0UL;
+ } else {
+ pxCurrentTCB->ulNotifiedValue = ulReturn - (uint32_t)1;
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ }
+ taskEXIT_CRITICAL();
+
+ return ulReturn;
+}
#endif /* configUSE_TASK_NOTIFICATIONS */
/*-----------------------------------------------------------*/
-#if( configUSE_TASK_NOTIFICATIONS == 1 )
-
- BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait )
- {
- BaseType_t xReturn;
-
- taskENTER_CRITICAL();
- {
- /* Only block if a notification is not already pending. */
- if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED )
- {
- /* Clear bits in the task's notification value as bits may get
- set by the notifying task or interrupt. This can be used to
- clear the value to zero. */
- pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry;
-
- /* Mark this task as waiting for a notification. */
- pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION;
-
- if( xTicksToWait > ( TickType_t ) 0 )
- {
- prvAddCurrentTaskToDelayedList( xTicksToWait, pdTRUE );
- traceTASK_NOTIFY_WAIT_BLOCK();
-
- /* All ports are written to allow a yield in a critical
- section (some will yield immediately, others wait until the
- critical section exits) - but it is not something that
- application code should ever do. */
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- taskEXIT_CRITICAL();
-
- taskENTER_CRITICAL();
- {
- traceTASK_NOTIFY_WAIT();
-
- if( pulNotificationValue != NULL )
- {
- /* Output the current notification value, which may or may not
- have changed. */
- *pulNotificationValue = pxCurrentTCB->ulNotifiedValue;
- }
-
- /* If ucNotifyValue is set then either the task never entered the
- blocked state (because a notification was already pending) or the
- task unblocked because of a notification. Otherwise the task
- unblocked because of a timeout. */
- if( pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED )
- {
- /* A notification was not received. */
- xReturn = pdFALSE;
- }
- else
- {
- /* A notification was already pending or a notification was
- received while the task was waiting. */
- pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit;
- xReturn = pdTRUE;
- }
-
- pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
- }
- taskEXIT_CRITICAL();
-
- return xReturn;
- }
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+
+BaseType_t xTaskNotifyWait(uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait) {
+ BaseType_t xReturn;
+
+ taskENTER_CRITICAL();
+ {
+ /* Only block if a notification is not already pending. */
+ if (pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED) {
+ /* Clear bits in the task's notification value as bits may get
+ set by the notifying task or interrupt. This can be used to
+ clear the value to zero. */
+ pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry;
+
+ /* Mark this task as waiting for a notification. */
+ pxCurrentTCB->ucNotifyState = taskWAITING_NOTIFICATION;
+
+ if (xTicksToWait > (TickType_t)0) {
+ prvAddCurrentTaskToDelayedList(xTicksToWait, pdTRUE);
+ traceTASK_NOTIFY_WAIT_BLOCK();
+
+ /* All ports are written to allow a yield in a critical
+ section (some will yield immediately, others wait until the
+ critical section exits) - but it is not something that
+ application code should ever do. */
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ taskENTER_CRITICAL();
+ {
+ traceTASK_NOTIFY_WAIT();
+
+ if (pulNotificationValue != NULL) {
+ /* Output the current notification value, which may or may not
+ have changed. */
+ *pulNotificationValue = pxCurrentTCB->ulNotifiedValue;
+ }
+
+ /* If ucNotifyValue is set then either the task never entered the
+ blocked state (because a notification was already pending) or the
+ task unblocked because of a notification. Otherwise the task
+ unblocked because of a timeout. */
+ if (pxCurrentTCB->ucNotifyState != taskNOTIFICATION_RECEIVED) {
+ /* A notification was not received. */
+ xReturn = pdFALSE;
+ } else {
+ /* A notification was already pending or a notification was
+ received while the task was waiting. */
+ pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit;
+ xReturn = pdTRUE;
+ }
+
+ pxCurrentTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
+}
#endif /* configUSE_TASK_NOTIFICATIONS */
/*-----------------------------------------------------------*/
-#if( configUSE_TASK_NOTIFICATIONS == 1 )
-
- BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue )
- {
- TCB_t * pxTCB;
- BaseType_t xReturn = pdPASS;
- uint8_t ucOriginalNotifyState;
-
- configASSERT( xTaskToNotify );
- pxTCB = xTaskToNotify;
-
- taskENTER_CRITICAL();
- {
- if( pulPreviousNotificationValue != NULL )
- {
- *pulPreviousNotificationValue = pxTCB->ulNotifiedValue;
- }
-
- ucOriginalNotifyState = pxTCB->ucNotifyState;
-
- pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED;
-
- switch( eAction )
- {
- case eSetBits :
- pxTCB->ulNotifiedValue |= ulValue;
- break;
-
- case eIncrement :
- ( pxTCB->ulNotifiedValue )++;
- break;
-
- case eSetValueWithOverwrite :
- pxTCB->ulNotifiedValue = ulValue;
- break;
-
- case eSetValueWithoutOverwrite :
- if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED )
- {
- pxTCB->ulNotifiedValue = ulValue;
- }
- else
- {
- /* The value could not be written to the task. */
- xReturn = pdFAIL;
- }
- break;
-
- case eNoAction:
- /* The task is being notified without its notify value being
- updated. */
- break;
-
- default:
- /* Should not get here if all enums are handled.
- Artificially force an assert by testing a value the
- compiler can't assume is const. */
- configASSERT( pxTCB->ulNotifiedValue == ~0UL );
-
- break;
- }
-
- traceTASK_NOTIFY();
-
- /* If the task is in the blocked state specifically to wait for a
- notification then unblock it now. */
- if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
- {
- ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
- prvAddTaskToReadyList( pxTCB );
-
- /* The task should not have been on an event list. */
- configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
-
- #if( configUSE_TICKLESS_IDLE != 0 )
- {
- /* If a task is blocked waiting for a notification then
- xNextTaskUnblockTime might be set to the blocked task's time
- out time. If the task is unblocked for a reason other than
- a timeout xNextTaskUnblockTime is normally left unchanged,
- because it will automatically get reset to a new value when
- the tick count equals xNextTaskUnblockTime. However if
- tickless idling is used it might be more important to enter
- sleep mode at the earliest possible time - so reset
- xNextTaskUnblockTime here to ensure it is updated at the
- earliest possible time. */
- prvResetNextTaskUnblockTime();
- }
- #endif
-
- if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
- {
- /* The notified task has a priority above the currently
- executing task so a yield is required. */
- taskYIELD_IF_USING_PREEMPTION();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- taskEXIT_CRITICAL();
-
- return xReturn;
- }
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+
+BaseType_t xTaskGenericNotify(TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue) {
+ TCB_t * pxTCB;
+ BaseType_t xReturn = pdPASS;
+ uint8_t ucOriginalNotifyState;
+
+ configASSERT(xTaskToNotify);
+ pxTCB = xTaskToNotify;
+
+ taskENTER_CRITICAL();
+ {
+ if (pulPreviousNotificationValue != NULL) {
+ *pulPreviousNotificationValue = pxTCB->ulNotifiedValue;
+ }
+
+ ucOriginalNotifyState = pxTCB->ucNotifyState;
+
+ pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED;
+
+ switch (eAction) {
+ case eSetBits:
+ pxTCB->ulNotifiedValue |= ulValue;
+ break;
+
+ case eIncrement:
+ (pxTCB->ulNotifiedValue)++;
+ break;
+
+ case eSetValueWithOverwrite:
+ pxTCB->ulNotifiedValue = ulValue;
+ break;
+
+ case eSetValueWithoutOverwrite:
+ if (ucOriginalNotifyState != taskNOTIFICATION_RECEIVED) {
+ pxTCB->ulNotifiedValue = ulValue;
+ } else {
+ /* The value could not be written to the task. */
+ xReturn = pdFAIL;
+ }
+ break;
+
+ case eNoAction:
+ /* The task is being notified without its notify value being
+ updated. */
+ break;
+
+ default:
+ /* Should not get here if all enums are handled.
+ Artificially force an assert by testing a value the
+ compiler can't assume is const. */
+ configASSERT(pxTCB->ulNotifiedValue == ~0UL);
+
+ break;
+ }
+
+ traceTASK_NOTIFY();
+
+ /* If the task is in the blocked state specifically to wait for a
+ notification then unblock it now. */
+ if (ucOriginalNotifyState == taskWAITING_NOTIFICATION) {
+ (void)uxListRemove(&(pxTCB->xStateListItem));
+ prvAddTaskToReadyList(pxTCB);
+
+ /* The task should not have been on an event list. */
+ configASSERT(listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) == NULL);
+
+#if (configUSE_TICKLESS_IDLE != 0)
+ {
+ /* If a task is blocked waiting for a notification then
+ xNextTaskUnblockTime might be set to the blocked task's time
+ out time. If the task is unblocked for a reason other than
+ a timeout xNextTaskUnblockTime is normally left unchanged,
+ because it will automatically get reset to a new value when
+ the tick count equals xNextTaskUnblockTime. However if
+ tickless idling is used it might be more important to enter
+ sleep mode at the earliest possible time - so reset
+ xNextTaskUnblockTime here to ensure it is updated at the
+ earliest possible time. */
+ prvResetNextTaskUnblockTime();
+ }
+#endif
+
+ if (pxTCB->uxPriority > pxCurrentTCB->uxPriority) {
+ /* The notified task has a priority above the currently
+ executing task so a yield is required. */
+ taskYIELD_IF_USING_PREEMPTION();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
+}
#endif /* configUSE_TASK_NOTIFICATIONS */
/*-----------------------------------------------------------*/
-#if( configUSE_TASK_NOTIFICATIONS == 1 )
-
- BaseType_t xTaskGenericNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken )
- {
- TCB_t * pxTCB;
- uint8_t ucOriginalNotifyState;
- BaseType_t xReturn = pdPASS;
- UBaseType_t uxSavedInterruptStatus;
-
- configASSERT( xTaskToNotify );
-
- /* RTOS ports that support interrupt nesting have the concept of a
- maximum system call (or maximum API call) interrupt priority.
- Interrupts that are above the maximum system call priority are keep
- permanently enabled, even when the RTOS kernel is in a critical section,
- but cannot make any calls to FreeRTOS API functions. If configASSERT()
- is defined in FreeRTOSConfig.h then
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
- failure if a FreeRTOS API function is called from an interrupt that has
- been assigned a priority above the configured maximum system call
- priority. Only FreeRTOS functions that end in FromISR can be called
- from interrupts that have been assigned a priority at or (logically)
- below the maximum system call interrupt priority. FreeRTOS maintains a
- separate interrupt safe API to ensure interrupt entry is as fast and as
- simple as possible. More information (albeit Cortex-M specific) is
- provided on the following link:
- http://www.freertos.org/RTOS-Cortex-M3-M4.html */
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
-
- pxTCB = xTaskToNotify;
-
- uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- if( pulPreviousNotificationValue != NULL )
- {
- *pulPreviousNotificationValue = pxTCB->ulNotifiedValue;
- }
-
- ucOriginalNotifyState = pxTCB->ucNotifyState;
- pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED;
-
- switch( eAction )
- {
- case eSetBits :
- pxTCB->ulNotifiedValue |= ulValue;
- break;
-
- case eIncrement :
- ( pxTCB->ulNotifiedValue )++;
- break;
-
- case eSetValueWithOverwrite :
- pxTCB->ulNotifiedValue = ulValue;
- break;
-
- case eSetValueWithoutOverwrite :
- if( ucOriginalNotifyState != taskNOTIFICATION_RECEIVED )
- {
- pxTCB->ulNotifiedValue = ulValue;
- }
- else
- {
- /* The value could not be written to the task. */
- xReturn = pdFAIL;
- }
- break;
-
- case eNoAction :
- /* The task is being notified without its notify value being
- updated. */
- break;
-
- default:
- /* Should not get here if all enums are handled.
- Artificially force an assert by testing a value the
- compiler can't assume is const. */
- configASSERT( pxTCB->ulNotifiedValue == ~0UL );
- break;
- }
-
- traceTASK_NOTIFY_FROM_ISR();
-
- /* If the task is in the blocked state specifically to wait for a
- notification then unblock it now. */
- if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
- {
- /* The task should not have been on an event list. */
- configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
-
- if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
- {
- ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
- prvAddTaskToReadyList( pxTCB );
- }
- else
- {
- /* The delayed and ready lists cannot be accessed, so hold
- this task pending until the scheduler is resumed. */
- vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
- }
-
- if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
- {
- /* The notified task has a priority above the currently
- executing task so a yield is required. */
- if( pxHigherPriorityTaskWoken != NULL )
- {
- *pxHigherPriorityTaskWoken = pdTRUE;
- }
-
- /* Mark that a yield is pending in case the user is not
- using the "xHigherPriorityTaskWoken" parameter to an ISR
- safe FreeRTOS function. */
- xYieldPending = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
-
- return xReturn;
- }
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+
+BaseType_t xTaskGenericNotifyFromISR(TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue, BaseType_t *pxHigherPriorityTaskWoken) {
+ TCB_t * pxTCB;
+ uint8_t ucOriginalNotifyState;
+ BaseType_t xReturn = pdPASS;
+ UBaseType_t uxSavedInterruptStatus;
+
+ configASSERT(xTaskToNotify);
+
+ /* RTOS ports that support interrupt nesting have the concept of a
+ maximum system call (or maximum API call) interrupt priority.
+ Interrupts that are above the maximum system call priority are keep
+ permanently enabled, even when the RTOS kernel is in a critical section,
+ but cannot make any calls to FreeRTOS API functions. If configASSERT()
+ is defined in FreeRTOSConfig.h then
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+ failure if a FreeRTOS API function is called from an interrupt that has
+ been assigned a priority above the configured maximum system call
+ priority. Only FreeRTOS functions that end in FromISR can be called
+ from interrupts that have been assigned a priority at or (logically)
+ below the maximum system call interrupt priority. FreeRTOS maintains a
+ separate interrupt safe API to ensure interrupt entry is as fast and as
+ simple as possible. More information (albeit Cortex-M specific) is
+ provided on the following link:
+ http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ pxTCB = xTaskToNotify;
+
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ if (pulPreviousNotificationValue != NULL) {
+ *pulPreviousNotificationValue = pxTCB->ulNotifiedValue;
+ }
+
+ ucOriginalNotifyState = pxTCB->ucNotifyState;
+ pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED;
+
+ switch (eAction) {
+ case eSetBits:
+ pxTCB->ulNotifiedValue |= ulValue;
+ break;
+
+ case eIncrement:
+ (pxTCB->ulNotifiedValue)++;
+ break;
+
+ case eSetValueWithOverwrite:
+ pxTCB->ulNotifiedValue = ulValue;
+ break;
+
+ case eSetValueWithoutOverwrite:
+ if (ucOriginalNotifyState != taskNOTIFICATION_RECEIVED) {
+ pxTCB->ulNotifiedValue = ulValue;
+ } else {
+ /* The value could not be written to the task. */
+ xReturn = pdFAIL;
+ }
+ break;
+
+ case eNoAction:
+ /* The task is being notified without its notify value being
+ updated. */
+ break;
+
+ default:
+ /* Should not get here if all enums are handled.
+ Artificially force an assert by testing a value the
+ compiler can't assume is const. */
+ configASSERT(pxTCB->ulNotifiedValue == ~0UL);
+ break;
+ }
+
+ traceTASK_NOTIFY_FROM_ISR();
+
+ /* If the task is in the blocked state specifically to wait for a
+ notification then unblock it now. */
+ if (ucOriginalNotifyState == taskWAITING_NOTIFICATION) {
+ /* The task should not have been on an event list. */
+ configASSERT(listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) == NULL);
+
+ if (uxSchedulerSuspended == (UBaseType_t)pdFALSE) {
+ (void)uxListRemove(&(pxTCB->xStateListItem));
+ prvAddTaskToReadyList(pxTCB);
+ } else {
+ /* The delayed and ready lists cannot be accessed, so hold
+ this task pending until the scheduler is resumed. */
+ vListInsertEnd(&(xPendingReadyList), &(pxTCB->xEventListItem));
+ }
+
+ if (pxTCB->uxPriority > pxCurrentTCB->uxPriority) {
+ /* The notified task has a priority above the currently
+ executing task so a yield is required. */
+ if (pxHigherPriorityTaskWoken != NULL) {
+ *pxHigherPriorityTaskWoken = pdTRUE;
+ }
+
+ /* Mark that a yield is pending in case the user is not
+ using the "xHigherPriorityTaskWoken" parameter to an ISR
+ safe FreeRTOS function. */
+ xYieldPending = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
+
+ return xReturn;
+}
#endif /* configUSE_TASK_NOTIFICATIONS */
/*-----------------------------------------------------------*/
-#if( configUSE_TASK_NOTIFICATIONS == 1 )
-
- void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken )
- {
- TCB_t * pxTCB;
- uint8_t ucOriginalNotifyState;
- UBaseType_t uxSavedInterruptStatus;
-
- configASSERT( xTaskToNotify );
-
- /* RTOS ports that support interrupt nesting have the concept of a
- maximum system call (or maximum API call) interrupt priority.
- Interrupts that are above the maximum system call priority are keep
- permanently enabled, even when the RTOS kernel is in a critical section,
- but cannot make any calls to FreeRTOS API functions. If configASSERT()
- is defined in FreeRTOSConfig.h then
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
- failure if a FreeRTOS API function is called from an interrupt that has
- been assigned a priority above the configured maximum system call
- priority. Only FreeRTOS functions that end in FromISR can be called
- from interrupts that have been assigned a priority at or (logically)
- below the maximum system call interrupt priority. FreeRTOS maintains a
- separate interrupt safe API to ensure interrupt entry is as fast and as
- simple as possible. More information (albeit Cortex-M specific) is
- provided on the following link:
- http://www.freertos.org/RTOS-Cortex-M3-M4.html */
- portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
-
- pxTCB = xTaskToNotify;
-
- uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
- {
- ucOriginalNotifyState = pxTCB->ucNotifyState;
- pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED;
-
- /* 'Giving' is equivalent to incrementing a count in a counting
- semaphore. */
- ( pxTCB->ulNotifiedValue )++;
-
- traceTASK_NOTIFY_GIVE_FROM_ISR();
-
- /* If the task is in the blocked state specifically to wait for a
- notification then unblock it now. */
- if( ucOriginalNotifyState == taskWAITING_NOTIFICATION )
- {
- /* The task should not have been on an event list. */
- configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
-
- if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
- {
- ( void ) uxListRemove( &( pxTCB->xStateListItem ) );
- prvAddTaskToReadyList( pxTCB );
- }
- else
- {
- /* The delayed and ready lists cannot be accessed, so hold
- this task pending until the scheduler is resumed. */
- vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
- }
-
- if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
- {
- /* The notified task has a priority above the currently
- executing task so a yield is required. */
- if( pxHigherPriorityTaskWoken != NULL )
- {
- *pxHigherPriorityTaskWoken = pdTRUE;
- }
-
- /* Mark that a yield is pending in case the user is not
- using the "xHigherPriorityTaskWoken" parameter in an ISR
- safe FreeRTOS function. */
- xYieldPending = pdTRUE;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
- }
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+
+void vTaskNotifyGiveFromISR(TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken) {
+ TCB_t * pxTCB;
+ uint8_t ucOriginalNotifyState;
+ UBaseType_t uxSavedInterruptStatus;
+
+ configASSERT(xTaskToNotify);
+
+ /* RTOS ports that support interrupt nesting have the concept of a
+ maximum system call (or maximum API call) interrupt priority.
+ Interrupts that are above the maximum system call priority are keep
+ permanently enabled, even when the RTOS kernel is in a critical section,
+ but cannot make any calls to FreeRTOS API functions. If configASSERT()
+ is defined in FreeRTOSConfig.h then
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+ failure if a FreeRTOS API function is called from an interrupt that has
+ been assigned a priority above the configured maximum system call
+ priority. Only FreeRTOS functions that end in FromISR can be called
+ from interrupts that have been assigned a priority at or (logically)
+ below the maximum system call interrupt priority. FreeRTOS maintains a
+ separate interrupt safe API to ensure interrupt entry is as fast and as
+ simple as possible. More information (albeit Cortex-M specific) is
+ provided on the following link:
+ http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+ portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+ pxTCB = xTaskToNotify;
+
+ uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ ucOriginalNotifyState = pxTCB->ucNotifyState;
+ pxTCB->ucNotifyState = taskNOTIFICATION_RECEIVED;
+
+ /* 'Giving' is equivalent to incrementing a count in a counting
+ semaphore. */
+ (pxTCB->ulNotifiedValue)++;
+
+ traceTASK_NOTIFY_GIVE_FROM_ISR();
+
+ /* If the task is in the blocked state specifically to wait for a
+ notification then unblock it now. */
+ if (ucOriginalNotifyState == taskWAITING_NOTIFICATION) {
+ /* The task should not have been on an event list. */
+ configASSERT(listLIST_ITEM_CONTAINER(&(pxTCB->xEventListItem)) == NULL);
+
+ if (uxSchedulerSuspended == (UBaseType_t)pdFALSE) {
+ (void)uxListRemove(&(pxTCB->xStateListItem));
+ prvAddTaskToReadyList(pxTCB);
+ } else {
+ /* The delayed and ready lists cannot be accessed, so hold
+ this task pending until the scheduler is resumed. */
+ vListInsertEnd(&(xPendingReadyList), &(pxTCB->xEventListItem));
+ }
+
+ if (pxTCB->uxPriority > pxCurrentTCB->uxPriority) {
+ /* The notified task has a priority above the currently
+ executing task so a yield is required. */
+ if (pxHigherPriorityTaskWoken != NULL) {
+ *pxHigherPriorityTaskWoken = pdTRUE;
+ }
+
+ /* Mark that a yield is pending in case the user is not
+ using the "xHigherPriorityTaskWoken" parameter in an ISR
+ safe FreeRTOS function. */
+ xYieldPending = pdTRUE;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR(uxSavedInterruptStatus);
+}
#endif /* configUSE_TASK_NOTIFICATIONS */
/*-----------------------------------------------------------*/
-#if( configUSE_TASK_NOTIFICATIONS == 1 )
-
- BaseType_t xTaskNotifyStateClear( TaskHandle_t xTask )
- {
- TCB_t *pxTCB;
- BaseType_t xReturn;
-
- /* If null is passed in here then it is the calling task that is having
- its notification state cleared. */
- pxTCB = prvGetTCBFromHandle( xTask );
-
- taskENTER_CRITICAL();
- {
- if( pxTCB->ucNotifyState == taskNOTIFICATION_RECEIVED )
- {
- pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
- xReturn = pdPASS;
- }
- else
- {
- xReturn = pdFAIL;
- }
- }
- taskEXIT_CRITICAL();
-
- return xReturn;
- }
+#if (configUSE_TASK_NOTIFICATIONS == 1)
+
+BaseType_t xTaskNotifyStateClear(TaskHandle_t xTask) {
+ TCB_t * pxTCB;
+ BaseType_t xReturn;
+
+ /* If null is passed in here then it is the calling task that is having
+ its notification state cleared. */
+ pxTCB = prvGetTCBFromHandle(xTask);
+
+ taskENTER_CRITICAL();
+ {
+ if (pxTCB->ucNotifyState == taskNOTIFICATION_RECEIVED) {
+ pxTCB->ucNotifyState = taskNOT_WAITING_NOTIFICATION;
+ xReturn = pdPASS;
+ } else {
+ xReturn = pdFAIL;
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
+}
#endif /* configUSE_TASK_NOTIFICATIONS */
/*-----------------------------------------------------------*/
-#if( configUSE_TASK_NOTIFICATIONS == 1 )
+#if (configUSE_TASK_NOTIFICATIONS == 1)
- uint32_t ulTaskNotifyValueClear( TaskHandle_t xTask, uint32_t ulBitsToClear )
- {
- TCB_t *pxTCB;
- uint32_t ulReturn;
+uint32_t ulTaskNotifyValueClear(TaskHandle_t xTask, uint32_t ulBitsToClear) {
+ TCB_t * pxTCB;
+ uint32_t ulReturn;
- /* If null is passed in here then it is the calling task that is having
- its notification state cleared. */
- pxTCB = prvGetTCBFromHandle( xTask );
+ /* If null is passed in here then it is the calling task that is having
+ its notification state cleared. */
+ pxTCB = prvGetTCBFromHandle(xTask);
- taskENTER_CRITICAL();
- {
- /* Return the notification as it was before the bits were cleared,
- then clear the bit mask. */
- ulReturn = pxCurrentTCB->ulNotifiedValue;
- pxTCB->ulNotifiedValue &= ~ulBitsToClear;
- }
- taskEXIT_CRITICAL();
+ taskENTER_CRITICAL();
+ {
+ /* Return the notification as it was before the bits were cleared,
+ then clear the bit mask. */
+ ulReturn = pxCurrentTCB->ulNotifiedValue;
+ pxTCB->ulNotifiedValue &= ~ulBitsToClear;
+ }
+ taskEXIT_CRITICAL();
- return ulReturn;
- }
+ return ulReturn;
+}
#endif /* configUSE_TASK_NOTIFICATIONS */
/*-----------------------------------------------------------*/
-#if( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( INCLUDE_xTaskGetIdleTaskHandle == 1 ) )
+#if ((configGENERATE_RUN_TIME_STATS == 1) && (INCLUDE_xTaskGetIdleTaskHandle == 1))
- uint32_t ulTaskGetIdleRunTimeCounter( void )
- {
- return xIdleTaskHandle->ulRunTimeCounter;
- }
+uint32_t ulTaskGetIdleRunTimeCounter(void) { return xIdleTaskHandle->ulRunTimeCounter; }
#endif
/*-----------------------------------------------------------*/
-static void prvAddCurrentTaskToDelayedList( TickType_t xTicksToWait, const BaseType_t xCanBlockIndefinitely )
-{
-TickType_t xTimeToWake;
-const TickType_t xConstTickCount = xTickCount;
-
- #if( INCLUDE_xTaskAbortDelay == 1 )
- {
- /* About to enter a delayed list, so ensure the ucDelayAborted flag is
- reset to pdFALSE so it can be detected as having been set to pdTRUE
- when the task leaves the Blocked state. */
- pxCurrentTCB->ucDelayAborted = pdFALSE;
- }
- #endif
-
- /* Remove the task from the ready list before adding it to the blocked list
- as the same list item is used for both lists. */
- if( uxListRemove( &( pxCurrentTCB->xStateListItem ) ) == ( UBaseType_t ) 0 )
- {
- /* The current task must be in a ready list, so there is no need to
- check, and the port reset macro can be called directly. */
- portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority ); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority cannot change as called with scheduler suspended or in a critical section. */
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- #if ( INCLUDE_vTaskSuspend == 1 )
- {
- if( ( xTicksToWait == portMAX_DELAY ) && ( xCanBlockIndefinitely != pdFALSE ) )
- {
- /* Add the task to the suspended task list instead of a delayed task
- list to ensure it is not woken by a timing event. It will block
- indefinitely. */
- vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xStateListItem ) );
- }
- else
- {
- /* Calculate the time at which the task should be woken if the event
- does not occur. This may overflow but this doesn't matter, the
- kernel will manage it correctly. */
- xTimeToWake = xConstTickCount + xTicksToWait;
-
- /* The list item will be inserted in wake time order. */
- listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake );
-
- if( xTimeToWake < xConstTickCount )
- {
- /* Wake time has overflowed. Place this item in the overflow
- list. */
- vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
- }
- else
- {
- /* The wake time has not overflowed, so the current block list
- is used. */
- vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
-
- /* If the task entering the blocked state was placed at the
- head of the list of blocked tasks then xNextTaskUnblockTime
- needs to be updated too. */
- if( xTimeToWake < xNextTaskUnblockTime )
- {
- xNextTaskUnblockTime = xTimeToWake;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- }
- #else /* INCLUDE_vTaskSuspend */
- {
- /* Calculate the time at which the task should be woken if the event
- does not occur. This may overflow but this doesn't matter, the kernel
- will manage it correctly. */
- xTimeToWake = xConstTickCount + xTicksToWait;
-
- /* The list item will be inserted in wake time order. */
- listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xStateListItem ), xTimeToWake );
-
- if( xTimeToWake < xConstTickCount )
- {
- /* Wake time has overflowed. Place this item in the overflow list. */
- vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
- }
- else
- {
- /* The wake time has not overflowed, so the current block list is used. */
- vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xStateListItem ) );
-
- /* If the task entering the blocked state was placed at the head of the
- list of blocked tasks then xNextTaskUnblockTime needs to be updated
- too. */
- if( xTimeToWake < xNextTaskUnblockTime )
- {
- xNextTaskUnblockTime = xTimeToWake;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */
- ( void ) xCanBlockIndefinitely;
- }
- #endif /* INCLUDE_vTaskSuspend */
+static void prvAddCurrentTaskToDelayedList(TickType_t xTicksToWait, const BaseType_t xCanBlockIndefinitely) {
+ TickType_t xTimeToWake;
+ const TickType_t xConstTickCount = xTickCount;
+
+#if (INCLUDE_xTaskAbortDelay == 1)
+ {
+ /* About to enter a delayed list, so ensure the ucDelayAborted flag is
+ reset to pdFALSE so it can be detected as having been set to pdTRUE
+ when the task leaves the Blocked state. */
+ pxCurrentTCB->ucDelayAborted = pdFALSE;
+ }
+#endif
+
+ /* Remove the task from the ready list before adding it to the blocked list
+ as the same list item is used for both lists. */
+ if (uxListRemove(&(pxCurrentTCB->xStateListItem)) == (UBaseType_t)0) {
+ /* The current task must be in a ready list, so there is no need to
+ check, and the port reset macro can be called directly. */
+ portRESET_READY_PRIORITY(pxCurrentTCB->uxPriority, uxTopReadyPriority); /*lint !e931 pxCurrentTCB cannot change as it is the calling task. pxCurrentTCB->uxPriority and uxTopReadyPriority
+ cannot change as called with scheduler suspended or in a critical section. */
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+#if (INCLUDE_vTaskSuspend == 1)
+ {
+ if ((xTicksToWait == portMAX_DELAY) && (xCanBlockIndefinitely != pdFALSE)) {
+ /* Add the task to the suspended task list instead of a delayed task
+ list to ensure it is not woken by a timing event. It will block
+ indefinitely. */
+ vListInsertEnd(&xSuspendedTaskList, &(pxCurrentTCB->xStateListItem));
+ } else {
+ /* Calculate the time at which the task should be woken if the event
+ does not occur. This may overflow but this doesn't matter, the
+ kernel will manage it correctly. */
+ xTimeToWake = xConstTickCount + xTicksToWait;
+
+ /* The list item will be inserted in wake time order. */
+ listSET_LIST_ITEM_VALUE(&(pxCurrentTCB->xStateListItem), xTimeToWake);
+
+ if (xTimeToWake < xConstTickCount) {
+ /* Wake time has overflowed. Place this item in the overflow
+ list. */
+ vListInsert(pxOverflowDelayedTaskList, &(pxCurrentTCB->xStateListItem));
+ } else {
+ /* The wake time has not overflowed, so the current block list
+ is used. */
+ vListInsert(pxDelayedTaskList, &(pxCurrentTCB->xStateListItem));
+
+ /* If the task entering the blocked state was placed at the
+ head of the list of blocked tasks then xNextTaskUnblockTime
+ needs to be updated too. */
+ if (xTimeToWake < xNextTaskUnblockTime) {
+ xNextTaskUnblockTime = xTimeToWake;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ }
+ }
+#else /* INCLUDE_vTaskSuspend */
+ {
+ /* Calculate the time at which the task should be woken if the event
+ does not occur. This may overflow but this doesn't matter, the kernel
+ will manage it correctly. */
+ xTimeToWake = xConstTickCount + xTicksToWait;
+
+ /* The list item will be inserted in wake time order. */
+ listSET_LIST_ITEM_VALUE(&(pxCurrentTCB->xStateListItem), xTimeToWake);
+
+ if (xTimeToWake < xConstTickCount) {
+ /* Wake time has overflowed. Place this item in the overflow list. */
+ vListInsert(pxOverflowDelayedTaskList, &(pxCurrentTCB->xStateListItem));
+ } else {
+ /* The wake time has not overflowed, so the current block list is used. */
+ vListInsert(pxDelayedTaskList, &(pxCurrentTCB->xStateListItem));
+
+ /* If the task entering the blocked state was placed at the head of the
+ list of blocked tasks then xNextTaskUnblockTime needs to be updated
+ too. */
+ if (xTimeToWake < xNextTaskUnblockTime) {
+ xNextTaskUnblockTime = xTimeToWake;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ /* Avoid compiler warning when INCLUDE_vTaskSuspend is not 1. */
+ (void)xCanBlockIndefinitely;
+ }
+#endif /* INCLUDE_vTaskSuspend */
}
/* Code below here allows additional code to be inserted into this source file,
@@ -5290,21 +4600,15 @@ especially where access to file scope functions and data is needed (for example
when performing module tests). */
#ifdef FREERTOS_MODULE_TEST
- #include "tasks_test_access_functions.h"
+#include "tasks_test_access_functions.h"
#endif
+#if (configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1)
-#if( configINCLUDE_FREERTOS_TASK_C_ADDITIONS_H == 1 )
-
- #include "freertos_tasks_c_additions.h"
-
- #ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
- static void freertos_tasks_c_additions_init( void )
- {
- FREERTOS_TASKS_C_ADDITIONS_INIT();
- }
- #endif
+#include "freertos_tasks_c_additions.h"
+#ifdef FREERTOS_TASKS_C_ADDITIONS_INIT
+static void freertos_tasks_c_additions_init(void) { FREERTOS_TASKS_C_ADDITIONS_INIT(); }
#endif
-
+#endif
diff --git a/source/Middlewares/Third_Party/FreeRTOS/Source/timers.c b/source/Middlewares/Third_Party/FreeRTOS/Source/timers.c
index d10c8320..931446b2 100644
--- a/source/Middlewares/Third_Party/FreeRTOS/Source/timers.c
+++ b/source/Middlewares/Third_Party/FreeRTOS/Source/timers.c
@@ -34,12 +34,12 @@ task.h is included from an application file. */
#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
#include "FreeRTOS.h"
-#include "task.h"
#include "queue.h"
+#include "task.h"
#include "timers.h"
-#if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 )
- #error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available.
+#if (INCLUDE_xTimerPendFunctionCall == 1) && (configUSE_TIMERS == 0)
+#error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available.
#endif
/* Lint e9021, e961 and e750 are suppressed as a MISRA exception justified
@@ -48,39 +48,39 @@ for the header files above, but not in this file, in order to generate the
correct privileged Vs unprivileged linkage and placement. */
#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e9021 !e961 !e750. */
-
/* This entire source file will be skipped if the application is not configured
to include software timer functionality. This #if is closed at the very bottom
of this file. If you want to include software timer functionality then ensure
configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
-#if ( configUSE_TIMERS == 1 )
+#if (configUSE_TIMERS == 1)
/* Misc definitions. */
-#define tmrNO_DELAY ( TickType_t ) 0U
+#define tmrNO_DELAY (TickType_t)0U
/* The name assigned to the timer service task. This can be overridden by
defining trmTIMER_SERVICE_TASK_NAME in FreeRTOSConfig.h. */
#ifndef configTIMER_SERVICE_TASK_NAME
- #define configTIMER_SERVICE_TASK_NAME "Tmr Svc"
+#define configTIMER_SERVICE_TASK_NAME "Tmr Svc"
#endif
/* Bit definitions used in the ucStatus member of a timer structure. */
-#define tmrSTATUS_IS_ACTIVE ( ( uint8_t ) 0x01 )
-#define tmrSTATUS_IS_STATICALLY_ALLOCATED ( ( uint8_t ) 0x02 )
-#define tmrSTATUS_IS_AUTORELOAD ( ( uint8_t ) 0x04 )
+#define tmrSTATUS_IS_ACTIVE ((uint8_t)0x01)
+#define tmrSTATUS_IS_STATICALLY_ALLOCATED ((uint8_t)0x02)
+#define tmrSTATUS_IS_AUTORELOAD ((uint8_t)0x04)
/* The definition of the timers themselves. */
typedef struct tmrTimerControl /* The old naming convention is used to prevent breaking kernel aware debuggers. */
{
- const char *pcTimerName; /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */
- TickType_t xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */
- void *pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */
- TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */
- #if( configUSE_TRACE_FACILITY == 1 )
- UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */
- #endif
- uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */
+ const char *pcTimerName;
+ /*<< Text name. This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ ListItem_t xTimerListItem; /*<< Standard linked list item as used by all kernel features for event management. */
+ TickType_t xTimerPeriodInTicks; /*<< How quickly and often the timer expires. */
+ void * pvTimerID; /*<< An ID to identify the timer. This allows the timer to be identified when the same callback is used for multiple timers. */
+ TimerCallbackFunction_t pxCallbackFunction; /*<< The function that will be called when the timer expires. */
+#if (configUSE_TRACE_FACILITY == 1)
+ UBaseType_t uxTimerNumber; /*<< An ID assigned by trace tools such as FreeRTOS+Trace */
+#endif
+ uint8_t ucStatus; /*<< Holds bits to say if the timer was statically allocated or not, and if it is active or not. */
} xTIMER;
/* The old xTIMER name is maintained above then typedefed to the new Timer_t
@@ -92,35 +92,30 @@ Two types of message can be queued - messages that manipulate a software timer,
and messages that request the execution of a non-timer related callback. The
two message types are defined in two separate structures, xTimerParametersType
and xCallbackParametersType respectively. */
-typedef struct tmrTimerParameters
-{
- TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */
- Timer_t * pxTimer; /*<< The timer to which the command will be applied. */
+typedef struct tmrTimerParameters {
+ TickType_t xMessageValue; /*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */
+ Timer_t * pxTimer; /*<< The timer to which the command will be applied. */
} TimerParameter_t;
-
-typedef struct tmrCallbackParameters
-{
- PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */
- void *pvParameter1; /* << The value that will be used as the callback functions first parameter. */
- uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */
+typedef struct tmrCallbackParameters {
+ PendedFunction_t pxCallbackFunction; /* << The callback function to execute. */
+ void * pvParameter1; /* << The value that will be used as the callback functions first parameter. */
+ uint32_t ulParameter2; /* << The value that will be used as the callback functions second parameter. */
} CallbackParameters_t;
/* The structure that contains the two message types, along with an identifier
that is used to determine which message type is valid. */
-typedef struct tmrTimerQueueMessage
-{
- BaseType_t xMessageID; /*<< The command being sent to the timer service task. */
- union
- {
- TimerParameter_t xTimerParameters;
-
- /* Don't include xCallbackParameters if it is not going to be used as
- it makes the structure (and therefore the timer queue) larger. */
- #if ( INCLUDE_xTimerPendFunctionCall == 1 )
- CallbackParameters_t xCallbackParameters;
- #endif /* INCLUDE_xTimerPendFunctionCall */
- } u;
+typedef struct tmrTimerQueueMessage {
+ BaseType_t xMessageID; /*<< The command being sent to the timer service task. */
+ union {
+ TimerParameter_t xTimerParameters;
+
+/* Don't include xCallbackParameters if it is not going to be used as
+it makes the structure (and therefore the timer queue) larger. */
+#if (INCLUDE_xTimerPendFunctionCall == 1)
+ CallbackParameters_t xCallbackParameters;
+#endif /* INCLUDE_xTimerPendFunctionCall */
+ } u;
} DaemonTaskMessage_t;
/*lint -save -e956 A manual analysis and inspection has been used to determine
@@ -132,26 +127,26 @@ timer service task is allowed to access these lists.
xActiveTimerList1 and xActiveTimerList2 could be at function scope but that
breaks some kernel aware debuggers, and debuggers that reply on removing the
static qualifier. */
-PRIVILEGED_DATA static List_t xActiveTimerList1;
-PRIVILEGED_DATA static List_t xActiveTimerList2;
+PRIVILEGED_DATA static List_t xActiveTimerList1;
+PRIVILEGED_DATA static List_t xActiveTimerList2;
PRIVILEGED_DATA static List_t *pxCurrentTimerList;
PRIVILEGED_DATA static List_t *pxOverflowTimerList;
/* A queue that is used to send commands to the timer service task. */
-PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL;
-PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL;
+PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL;
+PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL;
/*lint -restore */
/*-----------------------------------------------------------*/
-#if( configSUPPORT_STATIC_ALLOCATION == 1 )
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
- /* If static allocation is supported then the application must provide the
- following callback function - which enables the application to optionally
- provide the memory that will be used by the timer task as the task's stack
- and TCB. */
- extern void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize );
+/* If static allocation is supported then the application must provide the
+following callback function - which enables the application to optionally
+provide the memory that will be used by the timer task as the task's stack
+and TCB. */
+extern void vApplicationGetTimerTaskMemory(StaticTask_t **ppxTimerTaskTCBBuffer, StackType_t **ppxTimerTaskStackBuffer, uint32_t *pulTimerTaskStackSize);
#endif
@@ -159,44 +154,44 @@ PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL;
* Initialise the infrastructure used by the timer service task if it has not
* been initialised already.
*/
-static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION;
+static void prvCheckForValidListAndQueue(void) PRIVILEGED_FUNCTION;
/*
* The timer service task (daemon). Timer functionality is controlled by this
* task. Other tasks communicate with the timer service task using the
* xTimerQueue queue.
*/
-static portTASK_FUNCTION_PROTO( prvTimerTask, pvParameters ) PRIVILEGED_FUNCTION;
+static portTASK_FUNCTION_PROTO(prvTimerTask, pvParameters) PRIVILEGED_FUNCTION;
/*
* Called by the timer service task to interpret and process a command it
* received on the timer queue.
*/
-static void prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION;
+static void prvProcessReceivedCommands(void) PRIVILEGED_FUNCTION;
/*
* Insert the timer into either xActiveTimerList1, or xActiveTimerList2,
* depending on if the expire time causes a timer counter overflow.
*/
-static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime ) PRIVILEGED_FUNCTION;
+static BaseType_t prvInsertTimerInActiveList(Timer_t *const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime) PRIVILEGED_FUNCTION;
/*
* An active timer has reached its expire time. Reload the timer if it is an
* auto-reload timer, then call its callback.
*/
-static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow ) PRIVILEGED_FUNCTION;
+static void prvProcessExpiredTimer(const TickType_t xNextExpireTime, const TickType_t xTimeNow) PRIVILEGED_FUNCTION;
/*
* The tick count has overflowed. Switch the timer lists after ensuring the
* current timer list does not still reference some timers.
*/
-static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION;
+static void prvSwitchTimerLists(void) PRIVILEGED_FUNCTION;
/*
* Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE
* if a tick count overflow occurred since prvSampleTimeNow() was last called.
*/
-static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION;
+static TickType_t prvSampleTimeNow(BaseType_t *const pxTimerListsWereSwitched) PRIVILEGED_FUNCTION;
/*
* If the timer list contains any active timers then return the expire time of
@@ -204,916 +199,774 @@ static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched
* timer list does not contain any timers then return 0 and set *pxListWasEmpty
* to pdTRUE.
*/
-static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION;
+static TickType_t prvGetNextExpireTime(BaseType_t *const pxListWasEmpty) PRIVILEGED_FUNCTION;
/*
* If a timer has expired, process it. Otherwise, block the timer service task
* until either a timer does expire or a command is received.
*/
-static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION;
+static void prvProcessTimerOrBlockTask(const TickType_t xNextExpireTime, BaseType_t xListWasEmpty) PRIVILEGED_FUNCTION;
/*
* Called after a Timer_t structure has been allocated either statically or
* dynamically to fill in the structure's members.
*/
-static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- const TickType_t xTimerPeriodInTicks,
- const UBaseType_t uxAutoReload,
- void * const pvTimerID,
- TimerCallbackFunction_t pxCallbackFunction,
- Timer_t *pxNewTimer ) PRIVILEGED_FUNCTION;
+static void prvInitialiseNewTimer(const char *const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void *const pvTimerID, TimerCallbackFunction_t pxCallbackFunction,
+ Timer_t *pxNewTimer) PRIVILEGED_FUNCTION;
/*-----------------------------------------------------------*/
-BaseType_t xTimerCreateTimerTask( void )
-{
-BaseType_t xReturn = pdFAIL;
-
- /* This function is called when the scheduler is started if
- configUSE_TIMERS is set to 1. Check that the infrastructure used by the
- timer service task has been created/initialised. If timers have already
- been created then the initialisation will already have been performed. */
- prvCheckForValidListAndQueue();
-
- if( xTimerQueue != NULL )
- {
- #if( configSUPPORT_STATIC_ALLOCATION == 1 )
- {
- StaticTask_t *pxTimerTaskTCBBuffer = NULL;
- StackType_t *pxTimerTaskStackBuffer = NULL;
- uint32_t ulTimerTaskStackSize;
-
- vApplicationGetTimerTaskMemory( &pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize );
- xTimerTaskHandle = xTaskCreateStatic( prvTimerTask,
- configTIMER_SERVICE_TASK_NAME,
- ulTimerTaskStackSize,
- NULL,
- ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT,
- pxTimerTaskStackBuffer,
- pxTimerTaskTCBBuffer );
-
- if( xTimerTaskHandle != NULL )
- {
- xReturn = pdPASS;
- }
- }
- #else
- {
- xReturn = xTaskCreate( prvTimerTask,
- configTIMER_SERVICE_TASK_NAME,
- configTIMER_TASK_STACK_DEPTH,
- NULL,
- ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT,
- &xTimerTaskHandle );
- }
- #endif /* configSUPPORT_STATIC_ALLOCATION */
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- configASSERT( xReturn );
- return xReturn;
+BaseType_t xTimerCreateTimerTask(void) {
+ BaseType_t xReturn = pdFAIL;
+
+ /* This function is called when the scheduler is started if
+ configUSE_TIMERS is set to 1. Check that the infrastructure used by the
+ timer service task has been created/initialised. If timers have already
+ been created then the initialisation will already have been performed. */
+ prvCheckForValidListAndQueue();
+
+ if (xTimerQueue != NULL) {
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
+ {
+ StaticTask_t *pxTimerTaskTCBBuffer = NULL;
+ StackType_t * pxTimerTaskStackBuffer = NULL;
+ uint32_t ulTimerTaskStackSize;
+
+ vApplicationGetTimerTaskMemory(&pxTimerTaskTCBBuffer, &pxTimerTaskStackBuffer, &ulTimerTaskStackSize);
+ xTimerTaskHandle = xTaskCreateStatic(prvTimerTask, configTIMER_SERVICE_TASK_NAME, ulTimerTaskStackSize, NULL, ((UBaseType_t)configTIMER_TASK_PRIORITY) | portPRIVILEGE_BIT,
+ pxTimerTaskStackBuffer, pxTimerTaskTCBBuffer);
+
+ if (xTimerTaskHandle != NULL) {
+ xReturn = pdPASS;
+ }
+ }
+#else
+ { xReturn = xTaskCreate(prvTimerTask, configTIMER_SERVICE_TASK_NAME, configTIMER_TASK_STACK_DEPTH, NULL, ((UBaseType_t)configTIMER_TASK_PRIORITY) | portPRIVILEGE_BIT, &xTimerTaskHandle); }
+#endif /* configSUPPORT_STATIC_ALLOCATION */
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ configASSERT(xReturn);
+ return xReturn;
}
/*-----------------------------------------------------------*/
-#if( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
+#if (configSUPPORT_DYNAMIC_ALLOCATION == 1)
- TimerHandle_t xTimerCreate( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- const TickType_t xTimerPeriodInTicks,
- const UBaseType_t uxAutoReload,
- void * const pvTimerID,
- TimerCallbackFunction_t pxCallbackFunction )
- {
- Timer_t *pxNewTimer;
+TimerHandle_t xTimerCreate(const char *const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void *const pvTimerID, TimerCallbackFunction_t pxCallbackFunction) {
+ Timer_t *pxNewTimer;
- pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) ); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of Timer_t is always a pointer to the timer's mame. */
+ pxNewTimer = (Timer_t *)pvPortMalloc(sizeof(Timer_t)); /*lint !e9087 !e9079 All values returned by pvPortMalloc() have at least the alignment required by the MCU's stack, and the first member of
+ Timer_t is always a pointer to the timer's mame. */
- if( pxNewTimer != NULL )
- {
- /* Status is thus far zero as the timer is not created statically
- and has not been started. The auto-reload bit may get set in
- prvInitialiseNewTimer. */
- pxNewTimer->ucStatus = 0x00;
- prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer );
- }
+ if (pxNewTimer != NULL) {
+ /* Status is thus far zero as the timer is not created statically
+ and has not been started. The auto-reload bit may get set in
+ prvInitialiseNewTimer. */
+ pxNewTimer->ucStatus = 0x00;
+ prvInitialiseNewTimer(pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer);
+ }
- return pxNewTimer;
- }
+ return pxNewTimer;
+}
#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
/*-----------------------------------------------------------*/
-#if( configSUPPORT_STATIC_ALLOCATION == 1 )
-
- TimerHandle_t xTimerCreateStatic( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- const TickType_t xTimerPeriodInTicks,
- const UBaseType_t uxAutoReload,
- void * const pvTimerID,
- TimerCallbackFunction_t pxCallbackFunction,
- StaticTimer_t *pxTimerBuffer )
- {
- Timer_t *pxNewTimer;
-
- #if( configASSERT_DEFINED == 1 )
- {
- /* Sanity check that the size of the structure used to declare a
- variable of type StaticTimer_t equals the size of the real timer
- structure. */
- volatile size_t xSize = sizeof( StaticTimer_t );
- configASSERT( xSize == sizeof( Timer_t ) );
- ( void ) xSize; /* Keeps lint quiet when configASSERT() is not defined. */
- }
- #endif /* configASSERT_DEFINED */
-
- /* A pointer to a StaticTimer_t structure MUST be provided, use it. */
- configASSERT( pxTimerBuffer );
- pxNewTimer = ( Timer_t * ) pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */
-
- if( pxNewTimer != NULL )
- {
- /* Timers can be created statically or dynamically so note this
- timer was created statically in case it is later deleted. The
- auto-reload bit may get set in prvInitialiseNewTimer(). */
- pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED;
-
- prvInitialiseNewTimer( pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer );
- }
-
- return pxNewTimer;
- }
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
+
+TimerHandle_t xTimerCreateStatic(const char *const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void *const pvTimerID, TimerCallbackFunction_t pxCallbackFunction,
+ StaticTimer_t *pxTimerBuffer) {
+ Timer_t *pxNewTimer;
+
+#if (configASSERT_DEFINED == 1)
+ {
+ /* Sanity check that the size of the structure used to declare a
+ variable of type StaticTimer_t equals the size of the real timer
+ structure. */
+ volatile size_t xSize = sizeof(StaticTimer_t);
+ configASSERT(xSize == sizeof(Timer_t));
+ (void)xSize; /* Keeps lint quiet when configASSERT() is not defined. */
+ }
+#endif /* configASSERT_DEFINED */
+
+ /* A pointer to a StaticTimer_t structure MUST be provided, use it. */
+ configASSERT(pxTimerBuffer);
+ pxNewTimer = (Timer_t *)pxTimerBuffer; /*lint !e740 !e9087 StaticTimer_t is a pointer to a Timer_t, so guaranteed to be aligned and sized correctly (checked by an assert()), so this is safe. */
+
+ if (pxNewTimer != NULL) {
+ /* Timers can be created statically or dynamically so note this
+ timer was created statically in case it is later deleted. The
+ auto-reload bit may get set in prvInitialiseNewTimer(). */
+ pxNewTimer->ucStatus = tmrSTATUS_IS_STATICALLY_ALLOCATED;
+
+ prvInitialiseNewTimer(pcTimerName, xTimerPeriodInTicks, uxAutoReload, pvTimerID, pxCallbackFunction, pxNewTimer);
+ }
+
+ return pxNewTimer;
+}
#endif /* configSUPPORT_STATIC_ALLOCATION */
/*-----------------------------------------------------------*/
-static void prvInitialiseNewTimer( const char * const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
- const TickType_t xTimerPeriodInTicks,
- const UBaseType_t uxAutoReload,
- void * const pvTimerID,
- TimerCallbackFunction_t pxCallbackFunction,
- Timer_t *pxNewTimer )
-{
- /* 0 is not a valid value for xTimerPeriodInTicks. */
- configASSERT( ( xTimerPeriodInTicks > 0 ) );
-
- if( pxNewTimer != NULL )
- {
- /* Ensure the infrastructure used by the timer service task has been
- created/initialised. */
- prvCheckForValidListAndQueue();
-
- /* Initialise the timer structure members using the function
- parameters. */
- pxNewTimer->pcTimerName = pcTimerName;
- pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks;
- pxNewTimer->pvTimerID = pvTimerID;
- pxNewTimer->pxCallbackFunction = pxCallbackFunction;
- vListInitialiseItem( &( pxNewTimer->xTimerListItem ) );
- if( uxAutoReload != pdFALSE )
- {
- pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD;
- }
- traceTIMER_CREATE( pxNewTimer );
- }
+static void prvInitialiseNewTimer(const char *const pcTimerName, /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+ const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void *const pvTimerID, TimerCallbackFunction_t pxCallbackFunction, Timer_t *pxNewTimer) {
+ /* 0 is not a valid value for xTimerPeriodInTicks. */
+ configASSERT((xTimerPeriodInTicks > 0));
+
+ if (pxNewTimer != NULL) {
+ /* Ensure the infrastructure used by the timer service task has been
+ created/initialised. */
+ prvCheckForValidListAndQueue();
+
+ /* Initialise the timer structure members using the function
+ parameters. */
+ pxNewTimer->pcTimerName = pcTimerName;
+ pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks;
+ pxNewTimer->pvTimerID = pvTimerID;
+ pxNewTimer->pxCallbackFunction = pxCallbackFunction;
+ vListInitialiseItem(&(pxNewTimer->xTimerListItem));
+ if (uxAutoReload != pdFALSE) {
+ pxNewTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD;
+ }
+ traceTIMER_CREATE(pxNewTimer);
+ }
}
/*-----------------------------------------------------------*/
-BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait )
-{
-BaseType_t xReturn = pdFAIL;
-DaemonTaskMessage_t xMessage;
-
- configASSERT( xTimer );
-
- /* Send a message to the timer service task to perform a particular action
- on a particular timer definition. */
- if( xTimerQueue != NULL )
- {
- /* Send a command to the timer service task to start the xTimer timer. */
- xMessage.xMessageID = xCommandID;
- xMessage.u.xTimerParameters.xMessageValue = xOptionalValue;
- xMessage.u.xTimerParameters.pxTimer = xTimer;
-
- if( xCommandID < tmrFIRST_FROM_ISR_COMMAND )
- {
- if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
- {
- xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
- }
- else
- {
- xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY );
- }
- }
- else
- {
- xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
- }
-
- traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- return xReturn;
+BaseType_t xTimerGenericCommand(TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t *const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait) {
+ BaseType_t xReturn = pdFAIL;
+ DaemonTaskMessage_t xMessage;
+
+ configASSERT(xTimer);
+
+ /* Send a message to the timer service task to perform a particular action
+ on a particular timer definition. */
+ if (xTimerQueue != NULL) {
+ /* Send a command to the timer service task to start the xTimer timer. */
+ xMessage.xMessageID = xCommandID;
+ xMessage.u.xTimerParameters.xMessageValue = xOptionalValue;
+ xMessage.u.xTimerParameters.pxTimer = xTimer;
+
+ if (xCommandID < tmrFIRST_FROM_ISR_COMMAND) {
+ if (xTaskGetSchedulerState() == taskSCHEDULER_RUNNING) {
+ xReturn = xQueueSendToBack(xTimerQueue, &xMessage, xTicksToWait);
+ } else {
+ xReturn = xQueueSendToBack(xTimerQueue, &xMessage, tmrNO_DELAY);
+ }
+ } else {
+ xReturn = xQueueSendToBackFromISR(xTimerQueue, &xMessage, pxHigherPriorityTaskWoken);
+ }
+
+ traceTIMER_COMMAND_SEND(xTimer, xCommandID, xOptionalValue, xReturn);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ return xReturn;
}
/*-----------------------------------------------------------*/
-TaskHandle_t xTimerGetTimerDaemonTaskHandle( void )
-{
- /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been
- started, then xTimerTaskHandle will be NULL. */
- configASSERT( ( xTimerTaskHandle != NULL ) );
- return xTimerTaskHandle;
+TaskHandle_t xTimerGetTimerDaemonTaskHandle(void) {
+ /* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been
+ started, then xTimerTaskHandle will be NULL. */
+ configASSERT((xTimerTaskHandle != NULL));
+ return xTimerTaskHandle;
}
/*-----------------------------------------------------------*/
-TickType_t xTimerGetPeriod( TimerHandle_t xTimer )
-{
-Timer_t *pxTimer = xTimer;
+TickType_t xTimerGetPeriod(TimerHandle_t xTimer) {
+ Timer_t *pxTimer = xTimer;
- configASSERT( xTimer );
- return pxTimer->xTimerPeriodInTicks;
+ configASSERT(xTimer);
+ return pxTimer->xTimerPeriodInTicks;
}
/*-----------------------------------------------------------*/
-void vTimerSetReloadMode( TimerHandle_t xTimer, const UBaseType_t uxAutoReload )
-{
-Timer_t * pxTimer = xTimer;
-
- configASSERT( xTimer );
- taskENTER_CRITICAL();
- {
- if( uxAutoReload != pdFALSE )
- {
- pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD;
- }
- else
- {
- pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD;
- }
- }
- taskEXIT_CRITICAL();
+void vTimerSetReloadMode(TimerHandle_t xTimer, const UBaseType_t uxAutoReload) {
+ Timer_t *pxTimer = xTimer;
+
+ configASSERT(xTimer);
+ taskENTER_CRITICAL();
+ {
+ if (uxAutoReload != pdFALSE) {
+ pxTimer->ucStatus |= tmrSTATUS_IS_AUTORELOAD;
+ } else {
+ pxTimer->ucStatus &= ~tmrSTATUS_IS_AUTORELOAD;
+ }
+ }
+ taskEXIT_CRITICAL();
}
/*-----------------------------------------------------------*/
-UBaseType_t uxTimerGetReloadMode( TimerHandle_t xTimer )
-{
-Timer_t * pxTimer = xTimer;
-UBaseType_t uxReturn;
-
- configASSERT( xTimer );
- taskENTER_CRITICAL();
- {
- if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) == 0 )
- {
- /* Not an auto-reload timer. */
- uxReturn = ( UBaseType_t ) pdFALSE;
- }
- else
- {
- /* Is an auto-reload timer. */
- uxReturn = ( UBaseType_t ) pdTRUE;
- }
- }
- taskEXIT_CRITICAL();
-
- return uxReturn;
+UBaseType_t uxTimerGetReloadMode(TimerHandle_t xTimer) {
+ Timer_t * pxTimer = xTimer;
+ UBaseType_t uxReturn;
+
+ configASSERT(xTimer);
+ taskENTER_CRITICAL();
+ {
+ if ((pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD) == 0) {
+ /* Not an auto-reload timer. */
+ uxReturn = (UBaseType_t)pdFALSE;
+ } else {
+ /* Is an auto-reload timer. */
+ uxReturn = (UBaseType_t)pdTRUE;
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return uxReturn;
}
/*-----------------------------------------------------------*/
-TickType_t xTimerGetExpiryTime( TimerHandle_t xTimer )
-{
-Timer_t * pxTimer = xTimer;
-TickType_t xReturn;
+TickType_t xTimerGetExpiryTime(TimerHandle_t xTimer) {
+ Timer_t * pxTimer = xTimer;
+ TickType_t xReturn;
- configASSERT( xTimer );
- xReturn = listGET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ) );
- return xReturn;
+ configASSERT(xTimer);
+ xReturn = listGET_LIST_ITEM_VALUE(&(pxTimer->xTimerListItem));
+ return xReturn;
}
/*-----------------------------------------------------------*/
-const char * pcTimerGetName( TimerHandle_t xTimer ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+const char *pcTimerGetName(TimerHandle_t xTimer) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
{
-Timer_t *pxTimer = xTimer;
+ Timer_t *pxTimer = xTimer;
- configASSERT( xTimer );
- return pxTimer->pcTimerName;
+ configASSERT(xTimer);
+ return pxTimer->pcTimerName;
}
/*-----------------------------------------------------------*/
-static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow )
-{
-BaseType_t xResult;
-Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
-
- /* Remove the timer from the list of active timers. A check has already
- been performed to ensure the list is not empty. */
- ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
- traceTIMER_EXPIRED( pxTimer );
-
- /* If the timer is an auto-reload timer then calculate the next
- expiry time and re-insert the timer in the list of active timers. */
- if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 )
- {
- /* The timer is inserted into a list using a time relative to anything
- other than the current time. It will therefore be inserted into the
- correct list relative to the time this task thinks it is now. */
- if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) != pdFALSE )
- {
- /* The timer expired before it was added to the active timer
- list. Reload it now. */
- xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
- configASSERT( xResult );
- ( void ) xResult;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
- mtCOVERAGE_TEST_MARKER();
- }
-
- /* Call the timer callback. */
- pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
+static void prvProcessExpiredTimer(const TickType_t xNextExpireTime, const TickType_t xTimeNow) {
+ BaseType_t xResult;
+ Timer_t *const pxTimer = (Timer_t *)listGET_OWNER_OF_HEAD_ENTRY(pxCurrentTimerList); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known
+ to be fine as the type of the pointer stored and retrieved is the same. */
+
+ /* Remove the timer from the list of active timers. A check has already
+ been performed to ensure the list is not empty. */
+ (void)uxListRemove(&(pxTimer->xTimerListItem));
+ traceTIMER_EXPIRED(pxTimer);
+
+ /* If the timer is an auto-reload timer then calculate the next
+ expiry time and re-insert the timer in the list of active timers. */
+ if ((pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD) != 0) {
+ /* The timer is inserted into a list using a time relative to anything
+ other than the current time. It will therefore be inserted into the
+ correct list relative to the time this task thinks it is now. */
+ if (prvInsertTimerInActiveList(pxTimer, (xNextExpireTime + pxTimer->xTimerPeriodInTicks), xTimeNow, xNextExpireTime) != pdFALSE) {
+ /* The timer expired before it was added to the active timer
+ list. Reload it now. */
+ xResult = xTimerGenericCommand(pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY);
+ configASSERT(xResult);
+ (void)xResult;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ /* Call the timer callback. */
+ pxTimer->pxCallbackFunction((TimerHandle_t)pxTimer);
}
/*-----------------------------------------------------------*/
-static portTASK_FUNCTION( prvTimerTask, pvParameters )
-{
-TickType_t xNextExpireTime;
-BaseType_t xListWasEmpty;
-
- /* Just to avoid compiler warnings. */
- ( void ) pvParameters;
-
- #if( configUSE_DAEMON_TASK_STARTUP_HOOK == 1 )
- {
- extern void vApplicationDaemonTaskStartupHook( void );
-
- /* Allow the application writer to execute some code in the context of
- this task at the point the task starts executing. This is useful if the
- application includes initialisation code that would benefit from
- executing after the scheduler has been started. */
- vApplicationDaemonTaskStartupHook();
- }
- #endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */
-
- for( ;; )
- {
- /* Query the timers list to see if it contains any timers, and if so,
- obtain the time at which the next timer will expire. */
- xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty );
-
- /* If a timer has expired, process it. Otherwise, block this task
- until either a timer does expire, or a command is received. */
- prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );
-
- /* Empty the command queue. */
- prvProcessReceivedCommands();
- }
+static portTASK_FUNCTION(prvTimerTask, pvParameters) {
+ TickType_t xNextExpireTime;
+ BaseType_t xListWasEmpty;
+
+ /* Just to avoid compiler warnings. */
+ (void)pvParameters;
+
+#if (configUSE_DAEMON_TASK_STARTUP_HOOK == 1)
+ {
+ extern void vApplicationDaemonTaskStartupHook(void);
+
+ /* Allow the application writer to execute some code in the context of
+ this task at the point the task starts executing. This is useful if the
+ application includes initialisation code that would benefit from
+ executing after the scheduler has been started. */
+ vApplicationDaemonTaskStartupHook();
+ }
+#endif /* configUSE_DAEMON_TASK_STARTUP_HOOK */
+
+ for (;;) {
+ /* Query the timers list to see if it contains any timers, and if so,
+ obtain the time at which the next timer will expire. */
+ xNextExpireTime = prvGetNextExpireTime(&xListWasEmpty);
+
+ /* If a timer has expired, process it. Otherwise, block this task
+ until either a timer does expire, or a command is received. */
+ prvProcessTimerOrBlockTask(xNextExpireTime, xListWasEmpty);
+
+ /* Empty the command queue. */
+ prvProcessReceivedCommands();
+ }
}
/*-----------------------------------------------------------*/
-static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, BaseType_t xListWasEmpty )
-{
-TickType_t xTimeNow;
-BaseType_t xTimerListsWereSwitched;
-
- vTaskSuspendAll();
- {
- /* Obtain the time now to make an assessment as to whether the timer
- has expired or not. If obtaining the time causes the lists to switch
- then don't process this timer as any timers that remained in the list
- when the lists were switched will have been processed within the
- prvSampleTimeNow() function. */
- xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
- if( xTimerListsWereSwitched == pdFALSE )
- {
- /* The tick count has not overflowed, has the timer expired? */
- if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) )
- {
- ( void ) xTaskResumeAll();
- prvProcessExpiredTimer( xNextExpireTime, xTimeNow );
- }
- else
- {
- /* The tick count has not overflowed, and the next expire
- time has not been reached yet. This task should therefore
- block to wait for the next expire time or a command to be
- received - whichever comes first. The following line cannot
- be reached unless xNextExpireTime > xTimeNow, except in the
- case when the current timer list is empty. */
- if( xListWasEmpty != pdFALSE )
- {
- /* The current timer list is empty - is the overflow list
- also empty? */
- xListWasEmpty = listLIST_IS_EMPTY( pxOverflowTimerList );
- }
-
- vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ), xListWasEmpty );
-
- if( xTaskResumeAll() == pdFALSE )
- {
- /* Yield to wait for either a command to arrive, or the
- block time to expire. If a command arrived between the
- critical section being exited and this yield then the yield
- will not cause the task to block. */
- portYIELD_WITHIN_API();
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- }
- else
- {
- ( void ) xTaskResumeAll();
- }
- }
+static void prvProcessTimerOrBlockTask(const TickType_t xNextExpireTime, BaseType_t xListWasEmpty) {
+ TickType_t xTimeNow;
+ BaseType_t xTimerListsWereSwitched;
+
+ vTaskSuspendAll();
+ {
+ /* Obtain the time now to make an assessment as to whether the timer
+ has expired or not. If obtaining the time causes the lists to switch
+ then don't process this timer as any timers that remained in the list
+ when the lists were switched will have been processed within the
+ prvSampleTimeNow() function. */
+ xTimeNow = prvSampleTimeNow(&xTimerListsWereSwitched);
+ if (xTimerListsWereSwitched == pdFALSE) {
+ /* The tick count has not overflowed, has the timer expired? */
+ if ((xListWasEmpty == pdFALSE) && (xNextExpireTime <= xTimeNow)) {
+ (void)xTaskResumeAll();
+ prvProcessExpiredTimer(xNextExpireTime, xTimeNow);
+ } else {
+ /* The tick count has not overflowed, and the next expire
+ time has not been reached yet. This task should therefore
+ block to wait for the next expire time or a command to be
+ received - whichever comes first. The following line cannot
+ be reached unless xNextExpireTime > xTimeNow, except in the
+ case when the current timer list is empty. */
+ if (xListWasEmpty != pdFALSE) {
+ /* The current timer list is empty - is the overflow list
+ also empty? */
+ xListWasEmpty = listLIST_IS_EMPTY(pxOverflowTimerList);
+ }
+
+ vQueueWaitForMessageRestricted(xTimerQueue, (xNextExpireTime - xTimeNow), xListWasEmpty);
+
+ if (xTaskResumeAll() == pdFALSE) {
+ /* Yield to wait for either a command to arrive, or the
+ block time to expire. If a command arrived between the
+ critical section being exited and this yield then the yield
+ will not cause the task to block. */
+ portYIELD_WITHIN_API();
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ } else {
+ (void)xTaskResumeAll();
+ }
+ }
}
/*-----------------------------------------------------------*/
-static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty )
-{
-TickType_t xNextExpireTime;
-
- /* Timers are listed in expiry time order, with the head of the list
- referencing the task that will expire first. Obtain the time at which
- the timer with the nearest expiry time will expire. If there are no
- active timers then just set the next expire time to 0. That will cause
- this task to unblock when the tick count overflows, at which point the
- timer lists will be switched and the next expiry time can be
- re-assessed. */
- *pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList );
- if( *pxListWasEmpty == pdFALSE )
- {
- xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
- }
- else
- {
- /* Ensure the task unblocks when the tick count rolls over. */
- xNextExpireTime = ( TickType_t ) 0U;
- }
-
- return xNextExpireTime;
+static TickType_t prvGetNextExpireTime(BaseType_t *const pxListWasEmpty) {
+ TickType_t xNextExpireTime;
+
+ /* Timers are listed in expiry time order, with the head of the list
+ referencing the task that will expire first. Obtain the time at which
+ the timer with the nearest expiry time will expire. If there are no
+ active timers then just set the next expire time to 0. That will cause
+ this task to unblock when the tick count overflows, at which point the
+ timer lists will be switched and the next expiry time can be
+ re-assessed. */
+ *pxListWasEmpty = listLIST_IS_EMPTY(pxCurrentTimerList);
+ if (*pxListWasEmpty == pdFALSE) {
+ xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY(pxCurrentTimerList);
+ } else {
+ /* Ensure the task unblocks when the tick count rolls over. */
+ xNextExpireTime = (TickType_t)0U;
+ }
+
+ return xNextExpireTime;
}
/*-----------------------------------------------------------*/
-static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched )
-{
-TickType_t xTimeNow;
-PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */
+static TickType_t prvSampleTimeNow(BaseType_t *const pxTimerListsWereSwitched) {
+ TickType_t xTimeNow;
+ PRIVILEGED_DATA static TickType_t xLastTime = (TickType_t)0U; /*lint !e956 Variable is only accessible to one task. */
- xTimeNow = xTaskGetTickCount();
+ xTimeNow = xTaskGetTickCount();
- if( xTimeNow < xLastTime )
- {
- prvSwitchTimerLists();
- *pxTimerListsWereSwitched = pdTRUE;
- }
- else
- {
- *pxTimerListsWereSwitched = pdFALSE;
- }
+ if (xTimeNow < xLastTime) {
+ prvSwitchTimerLists();
+ *pxTimerListsWereSwitched = pdTRUE;
+ } else {
+ *pxTimerListsWereSwitched = pdFALSE;
+ }
- xLastTime = xTimeNow;
+ xLastTime = xTimeNow;
- return xTimeNow;
+ return xTimeNow;
}
/*-----------------------------------------------------------*/
-static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime )
-{
-BaseType_t xProcessTimerNow = pdFALSE;
-
- listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime );
- listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
-
- if( xNextExpiryTime <= xTimeNow )
- {
- /* Has the expiry time elapsed between the command to start/reset a
- timer was issued, and the time the command was processed? */
- if( ( ( TickType_t ) ( xTimeNow - xCommandTime ) ) >= pxTimer->xTimerPeriodInTicks ) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
- {
- /* The time between a command being issued and the command being
- processed actually exceeds the timers period. */
- xProcessTimerNow = pdTRUE;
- }
- else
- {
- vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) );
- }
- }
- else
- {
- if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) )
- {
- /* If, since the command was issued, the tick count has overflowed
- but the expiry time has not, then the timer must have already passed
- its expiry time and should be processed immediately. */
- xProcessTimerNow = pdTRUE;
- }
- else
- {
- vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
- }
- }
-
- return xProcessTimerNow;
+static BaseType_t prvInsertTimerInActiveList(Timer_t *const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime) {
+ BaseType_t xProcessTimerNow = pdFALSE;
+
+ listSET_LIST_ITEM_VALUE(&(pxTimer->xTimerListItem), xNextExpiryTime);
+ listSET_LIST_ITEM_OWNER(&(pxTimer->xTimerListItem), pxTimer);
+
+ if (xNextExpiryTime <= xTimeNow) {
+ /* Has the expiry time elapsed between the command to start/reset a
+ timer was issued, and the time the command was processed? */
+ if (((TickType_t)(xTimeNow - xCommandTime)) >= pxTimer->xTimerPeriodInTicks) /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+ {
+ /* The time between a command being issued and the command being
+ processed actually exceeds the timers period. */
+ xProcessTimerNow = pdTRUE;
+ } else {
+ vListInsert(pxOverflowTimerList, &(pxTimer->xTimerListItem));
+ }
+ } else {
+ if ((xTimeNow < xCommandTime) && (xNextExpiryTime >= xCommandTime)) {
+ /* If, since the command was issued, the tick count has overflowed
+ but the expiry time has not, then the timer must have already passed
+ its expiry time and should be processed immediately. */
+ xProcessTimerNow = pdTRUE;
+ } else {
+ vListInsert(pxCurrentTimerList, &(pxTimer->xTimerListItem));
+ }
+ }
+
+ return xProcessTimerNow;
}
/*-----------------------------------------------------------*/
-static void prvProcessReceivedCommands( void )
-{
-DaemonTaskMessage_t xMessage;
-Timer_t *pxTimer;
-BaseType_t xTimerListsWereSwitched, xResult;
-TickType_t xTimeNow;
-
- while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */
- {
- #if ( INCLUDE_xTimerPendFunctionCall == 1 )
- {
- /* Negative commands are pended function calls rather than timer
- commands. */
- if( xMessage.xMessageID < ( BaseType_t ) 0 )
- {
- const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters );
-
- /* The timer uses the xCallbackParameters member to request a
- callback be executed. Check the callback is not NULL. */
- configASSERT( pxCallback );
-
- /* Call the function. */
- pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* INCLUDE_xTimerPendFunctionCall */
-
- /* Commands that are positive are timer commands rather than pended
- function calls. */
- if( xMessage.xMessageID >= ( BaseType_t ) 0 )
- {
- /* The messages uses the xTimerParameters member to work on a
- software timer. */
- pxTimer = xMessage.u.xTimerParameters.pxTimer;
-
- if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE ) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */
- {
- /* The timer is in a list, remove it. */
- ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
-
- traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue );
-
- /* In this case the xTimerListsWereSwitched parameter is not used, but
- it must be present in the function call. prvSampleTimeNow() must be
- called after the message is received from xTimerQueue so there is no
- possibility of a higher priority task adding a message to the message
- queue with a time that is ahead of the timer daemon task (because it
- pre-empted the timer daemon task after the xTimeNow value was set). */
- xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
-
- switch( xMessage.xMessageID )
- {
- case tmrCOMMAND_START :
- case tmrCOMMAND_START_FROM_ISR :
- case tmrCOMMAND_RESET :
- case tmrCOMMAND_RESET_FROM_ISR :
- case tmrCOMMAND_START_DONT_TRACE :
- /* Start or restart a timer. */
- pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE;
- if( prvInsertTimerInActiveList( pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) != pdFALSE )
- {
- /* The timer expired before it was added to the active
- timer list. Process it now. */
- pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
- traceTIMER_EXPIRED( pxTimer );
-
- if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 )
- {
- xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY );
- configASSERT( xResult );
- ( void ) xResult;
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- break;
-
- case tmrCOMMAND_STOP :
- case tmrCOMMAND_STOP_FROM_ISR :
- /* The timer has already been removed from the active list. */
- pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
- break;
-
- case tmrCOMMAND_CHANGE_PERIOD :
- case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR :
- pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE;
- pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
- configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) );
-
- /* The new period does not really have a reference, and can
- be longer or shorter than the old one. The command time is
- therefore set to the current time, and as the period cannot
- be zero the next expiry time can only be in the future,
- meaning (unlike for the xTimerStart() case above) there is
- no fail case that needs to be handled here. */
- ( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow );
- break;
-
- case tmrCOMMAND_DELETE :
- #if ( configSUPPORT_DYNAMIC_ALLOCATION == 1 )
- {
- /* The timer has already been removed from the active list,
- just free up the memory if the memory was dynamically
- allocated. */
- if( ( pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED ) == ( uint8_t ) 0 )
- {
- vPortFree( pxTimer );
- }
- else
- {
- pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
- }
- }
- #else
- {
- /* If dynamic allocation is not enabled, the memory
- could not have been dynamically allocated. So there is
- no need to free the memory - just mark the timer as
- "not active". */
- pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
- }
- #endif /* configSUPPORT_DYNAMIC_ALLOCATION */
- break;
-
- default :
- /* Don't expect to get here. */
- break;
- }
- }
- }
+static void prvProcessReceivedCommands(void) {
+ DaemonTaskMessage_t xMessage;
+ Timer_t * pxTimer;
+ BaseType_t xTimerListsWereSwitched, xResult;
+ TickType_t xTimeNow;
+
+ while (xQueueReceive(xTimerQueue, &xMessage, tmrNO_DELAY)
+ != pdFAIL) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */
+ {
+#if (INCLUDE_xTimerPendFunctionCall == 1)
+ {
+ /* Negative commands are pended function calls rather than timer
+ commands. */
+ if (xMessage.xMessageID < (BaseType_t)0) {
+ const CallbackParameters_t *const pxCallback = &(xMessage.u.xCallbackParameters);
+
+ /* The timer uses the xCallbackParameters member to request a
+ callback be executed. Check the callback is not NULL. */
+ configASSERT(pxCallback);
+
+ /* Call the function. */
+ pxCallback->pxCallbackFunction(pxCallback->pvParameter1, pxCallback->ulParameter2);
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* INCLUDE_xTimerPendFunctionCall */
+
+ /* Commands that are positive are timer commands rather than pended
+ function calls. */
+ if (xMessage.xMessageID >= (BaseType_t)0) {
+ /* The messages uses the xTimerParameters member to work on a
+ software timer. */
+ pxTimer = xMessage.u.xTimerParameters.pxTimer;
+
+ if (listIS_CONTAINED_WITHIN(NULL, &(pxTimer->xTimerListItem)) == pdFALSE) /*lint !e961. The cast is only redundant when NULL is passed into the macro. */
+ {
+ /* The timer is in a list, remove it. */
+ (void)uxListRemove(&(pxTimer->xTimerListItem));
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+
+ traceTIMER_COMMAND_RECEIVED(pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue);
+
+ /* In this case the xTimerListsWereSwitched parameter is not used, but
+ it must be present in the function call. prvSampleTimeNow() must be
+ called after the message is received from xTimerQueue so there is no
+ possibility of a higher priority task adding a message to the message
+ queue with a time that is ahead of the timer daemon task (because it
+ pre-empted the timer daemon task after the xTimeNow value was set). */
+ xTimeNow = prvSampleTimeNow(&xTimerListsWereSwitched);
+
+ switch (xMessage.xMessageID) {
+ case tmrCOMMAND_START:
+ case tmrCOMMAND_START_FROM_ISR:
+ case tmrCOMMAND_RESET:
+ case tmrCOMMAND_RESET_FROM_ISR:
+ case tmrCOMMAND_START_DONT_TRACE:
+ /* Start or restart a timer. */
+ pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE;
+ if (prvInsertTimerInActiveList(pxTimer, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue) != pdFALSE) {
+ /* The timer expired before it was added to the active
+ timer list. Process it now. */
+ pxTimer->pxCallbackFunction((TimerHandle_t)pxTimer);
+ traceTIMER_EXPIRED(pxTimer);
+
+ if ((pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD) != 0) {
+ xResult = xTimerGenericCommand(pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY);
+ configASSERT(xResult);
+ (void)xResult;
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ break;
+
+ case tmrCOMMAND_STOP:
+ case tmrCOMMAND_STOP_FROM_ISR:
+ /* The timer has already been removed from the active list. */
+ pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
+ break;
+
+ case tmrCOMMAND_CHANGE_PERIOD:
+ case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR:
+ pxTimer->ucStatus |= tmrSTATUS_IS_ACTIVE;
+ pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
+ configASSERT((pxTimer->xTimerPeriodInTicks > 0));
+
+ /* The new period does not really have a reference, and can
+ be longer or shorter than the old one. The command time is
+ therefore set to the current time, and as the period cannot
+ be zero the next expiry time can only be in the future,
+ meaning (unlike for the xTimerStart() case above) there is
+ no fail case that needs to be handled here. */
+ (void)prvInsertTimerInActiveList(pxTimer, (xTimeNow + pxTimer->xTimerPeriodInTicks), xTimeNow, xTimeNow);
+ break;
+
+ case tmrCOMMAND_DELETE:
+#if (configSUPPORT_DYNAMIC_ALLOCATION == 1)
+ {
+ /* The timer has already been removed from the active list,
+ just free up the memory if the memory was dynamically
+ allocated. */
+ if ((pxTimer->ucStatus & tmrSTATUS_IS_STATICALLY_ALLOCATED) == (uint8_t)0) {
+ vPortFree(pxTimer);
+ } else {
+ pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
+ }
+ }
+#else
+ {
+ /* If dynamic allocation is not enabled, the memory
+ could not have been dynamically allocated. So there is
+ no need to free the memory - just mark the timer as
+ "not active". */
+ pxTimer->ucStatus &= ~tmrSTATUS_IS_ACTIVE;
+ }
+#endif /* configSUPPORT_DYNAMIC_ALLOCATION */
+ break;
+
+ default:
+ /* Don't expect to get here. */
+ break;
+ }
+ }
+ }
}
/*-----------------------------------------------------------*/
-static void prvSwitchTimerLists( void )
-{
-TickType_t xNextExpireTime, xReloadTime;
-List_t *pxTemp;
-Timer_t *pxTimer;
-BaseType_t xResult;
-
- /* The tick count has overflowed. The timer lists must be switched.
- If there are any timers still referenced from the current timer list
- then they must have expired and should be processed before the lists
- are switched. */
- while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE )
- {
- xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
-
- /* Remove the timer from the list. */
- pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList ); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine as the type of the pointer stored and retrieved is the same. */
- ( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
- traceTIMER_EXPIRED( pxTimer );
-
- /* Execute its callback, then send a command to restart the timer if
- it is an auto-reload timer. It cannot be restarted here as the lists
- have not yet been switched. */
- pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
-
- if( ( pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD ) != 0 )
- {
- /* Calculate the reload value, and if the reload value results in
- the timer going into the same timer list then it has already expired
- and the timer should be re-inserted into the current list so it is
- processed again within this loop. Otherwise a command should be sent
- to restart the timer to ensure it is only inserted into a list after
- the lists have been swapped. */
- xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks );
- if( xReloadTime > xNextExpireTime )
- {
- listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime );
- listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
- vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
- }
- else
- {
- xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
- configASSERT( xResult );
- ( void ) xResult;
- }
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
-
- pxTemp = pxCurrentTimerList;
- pxCurrentTimerList = pxOverflowTimerList;
- pxOverflowTimerList = pxTemp;
+static void prvSwitchTimerLists(void) {
+ TickType_t xNextExpireTime, xReloadTime;
+ List_t * pxTemp;
+ Timer_t * pxTimer;
+ BaseType_t xResult;
+
+ /* The tick count has overflowed. The timer lists must be switched.
+ If there are any timers still referenced from the current timer list
+ then they must have expired and should be processed before the lists
+ are switched. */
+ while (listLIST_IS_EMPTY(pxCurrentTimerList) == pdFALSE) {
+ xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY(pxCurrentTimerList);
+
+ /* Remove the timer from the list. */
+ pxTimer = (Timer_t *)listGET_OWNER_OF_HEAD_ENTRY(pxCurrentTimerList); /*lint !e9087 !e9079 void * is used as this macro is used with tasks and co-routines too. Alignment is known to be fine
+ as the type of the pointer stored and retrieved is the same. */
+ (void)uxListRemove(&(pxTimer->xTimerListItem));
+ traceTIMER_EXPIRED(pxTimer);
+
+ /* Execute its callback, then send a command to restart the timer if
+ it is an auto-reload timer. It cannot be restarted here as the lists
+ have not yet been switched. */
+ pxTimer->pxCallbackFunction((TimerHandle_t)pxTimer);
+
+ if ((pxTimer->ucStatus & tmrSTATUS_IS_AUTORELOAD) != 0) {
+ /* Calculate the reload value, and if the reload value results in
+ the timer going into the same timer list then it has already expired
+ and the timer should be re-inserted into the current list so it is
+ processed again within this loop. Otherwise a command should be sent
+ to restart the timer to ensure it is only inserted into a list after
+ the lists have been swapped. */
+ xReloadTime = (xNextExpireTime + pxTimer->xTimerPeriodInTicks);
+ if (xReloadTime > xNextExpireTime) {
+ listSET_LIST_ITEM_VALUE(&(pxTimer->xTimerListItem), xReloadTime);
+ listSET_LIST_ITEM_OWNER(&(pxTimer->xTimerListItem), pxTimer);
+ vListInsert(pxCurrentTimerList, &(pxTimer->xTimerListItem));
+ } else {
+ xResult = xTimerGenericCommand(pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY);
+ configASSERT(xResult);
+ (void)xResult;
+ }
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+
+ pxTemp = pxCurrentTimerList;
+ pxCurrentTimerList = pxOverflowTimerList;
+ pxOverflowTimerList = pxTemp;
}
/*-----------------------------------------------------------*/
-static void prvCheckForValidListAndQueue( void )
-{
- /* Check that the list from which active timers are referenced, and the
- queue used to communicate with the timer service, have been
- initialised. */
- taskENTER_CRITICAL();
- {
- if( xTimerQueue == NULL )
- {
- vListInitialise( &xActiveTimerList1 );
- vListInitialise( &xActiveTimerList2 );
- pxCurrentTimerList = &xActiveTimerList1;
- pxOverflowTimerList = &xActiveTimerList2;
-
- #if( configSUPPORT_STATIC_ALLOCATION == 1 )
- {
- /* The timer queue is allocated statically in case
- configSUPPORT_DYNAMIC_ALLOCATION is 0. */
- static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */
- static uint8_t ucStaticTimerQueueStorage[ ( size_t ) configTIMER_QUEUE_LENGTH * sizeof( DaemonTaskMessage_t ) ]; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */
-
- xTimerQueue = xQueueCreateStatic( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, ( UBaseType_t ) sizeof( DaemonTaskMessage_t ), &( ucStaticTimerQueueStorage[ 0 ] ), &xStaticTimerQueue );
- }
- #else
- {
- xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) );
- }
- #endif
-
- #if ( configQUEUE_REGISTRY_SIZE > 0 )
- {
- if( xTimerQueue != NULL )
- {
- vQueueAddToRegistry( xTimerQueue, "TmrQ" );
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- #endif /* configQUEUE_REGISTRY_SIZE */
- }
- else
- {
- mtCOVERAGE_TEST_MARKER();
- }
- }
- taskEXIT_CRITICAL();
+static void prvCheckForValidListAndQueue(void) {
+ /* Check that the list from which active timers are referenced, and the
+ queue used to communicate with the timer service, have been
+ initialised. */
+ taskENTER_CRITICAL();
+ {
+ if (xTimerQueue == NULL) {
+ vListInitialise(&xActiveTimerList1);
+ vListInitialise(&xActiveTimerList2);
+ pxCurrentTimerList = &xActiveTimerList1;
+ pxOverflowTimerList = &xActiveTimerList2;
+
+#if (configSUPPORT_STATIC_ALLOCATION == 1)
+ {
+ /* The timer queue is allocated statically in case
+ configSUPPORT_DYNAMIC_ALLOCATION is 0. */
+ static StaticQueue_t xStaticTimerQueue; /*lint !e956 Ok to declare in this manner to prevent additional conditional compilation guards in other locations. */
+ static uint8_t ucStaticTimerQueueStorage[(size_t)configTIMER_QUEUE_LENGTH * sizeof(DaemonTaskMessage_t)]; /*lint !e956 Ok to declare in this manner to prevent additional conditional
+ compilation guards in other locations. */
+
+ xTimerQueue = xQueueCreateStatic((UBaseType_t)configTIMER_QUEUE_LENGTH, (UBaseType_t)sizeof(DaemonTaskMessage_t), &(ucStaticTimerQueueStorage[0]), &xStaticTimerQueue);
+ }
+#else
+ { xTimerQueue = xQueueCreate((UBaseType_t)configTIMER_QUEUE_LENGTH, sizeof(DaemonTaskMessage_t)); }
+#endif
+
+#if (configQUEUE_REGISTRY_SIZE > 0)
+ {
+ if (xTimerQueue != NULL) {
+ vQueueAddToRegistry(xTimerQueue, "TmrQ");
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+#endif /* configQUEUE_REGISTRY_SIZE */
+ } else {
+ mtCOVERAGE_TEST_MARKER();
+ }
+ }
+ taskEXIT_CRITICAL();
}
/*-----------------------------------------------------------*/
-BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer )
-{
-BaseType_t xReturn;
-Timer_t *pxTimer = xTimer;
-
- configASSERT( xTimer );
-
- /* Is the timer in the list of active timers? */
- taskENTER_CRITICAL();
- {
- if( ( pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE ) == 0 )
- {
- xReturn = pdFALSE;
- }
- else
- {
- xReturn = pdTRUE;
- }
- }
- taskEXIT_CRITICAL();
-
- return xReturn;
+BaseType_t xTimerIsTimerActive(TimerHandle_t xTimer) {
+ BaseType_t xReturn;
+ Timer_t * pxTimer = xTimer;
+
+ configASSERT(xTimer);
+
+ /* Is the timer in the list of active timers? */
+ taskENTER_CRITICAL();
+ {
+ if ((pxTimer->ucStatus & tmrSTATUS_IS_ACTIVE) == 0) {
+ xReturn = pdFALSE;
+ } else {
+ xReturn = pdTRUE;
+ }
+ }
+ taskEXIT_CRITICAL();
+
+ return xReturn;
} /*lint !e818 Can't be pointer to const due to the typedef. */
/*-----------------------------------------------------------*/
-void *pvTimerGetTimerID( const TimerHandle_t xTimer )
-{
-Timer_t * const pxTimer = xTimer;
-void *pvReturn;
+void *pvTimerGetTimerID(const TimerHandle_t xTimer) {
+ Timer_t *const pxTimer = xTimer;
+ void * pvReturn;
- configASSERT( xTimer );
+ configASSERT(xTimer);
- taskENTER_CRITICAL();
- {
- pvReturn = pxTimer->pvTimerID;
- }
- taskEXIT_CRITICAL();
+ taskENTER_CRITICAL();
+ { pvReturn = pxTimer->pvTimerID; }
+ taskEXIT_CRITICAL();
- return pvReturn;
+ return pvReturn;
}
/*-----------------------------------------------------------*/
-void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID )
-{
-Timer_t * const pxTimer = xTimer;
+void vTimerSetTimerID(TimerHandle_t xTimer, void *pvNewID) {
+ Timer_t *const pxTimer = xTimer;
- configASSERT( xTimer );
+ configASSERT(xTimer);
- taskENTER_CRITICAL();
- {
- pxTimer->pvTimerID = pvNewID;
- }
- taskEXIT_CRITICAL();
+ taskENTER_CRITICAL();
+ { pxTimer->pvTimerID = pvNewID; }
+ taskEXIT_CRITICAL();
}
/*-----------------------------------------------------------*/
-#if( INCLUDE_xTimerPendFunctionCall == 1 )
+#if (INCLUDE_xTimerPendFunctionCall == 1)
- BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken )
- {
- DaemonTaskMessage_t xMessage;
- BaseType_t xReturn;
+BaseType_t xTimerPendFunctionCallFromISR(PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken) {
+ DaemonTaskMessage_t xMessage;
+ BaseType_t xReturn;
- /* Complete the message with the function parameters and post it to the
- daemon task. */
- xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR;
- xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
- xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
- xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
+ /* Complete the message with the function parameters and post it to the
+ daemon task. */
+ xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR;
+ xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
+ xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
+ xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
- xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
+ xReturn = xQueueSendFromISR(xTimerQueue, &xMessage, pxHigherPriorityTaskWoken);
- tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
+ tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, xReturn);
- return xReturn;
- }
+ return xReturn;
+}
#endif /* INCLUDE_xTimerPendFunctionCall */
/*-----------------------------------------------------------*/
-#if( INCLUDE_xTimerPendFunctionCall == 1 )
+#if (INCLUDE_xTimerPendFunctionCall == 1)
- BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait )
- {
- DaemonTaskMessage_t xMessage;
- BaseType_t xReturn;
+BaseType_t xTimerPendFunctionCall(PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait) {
+ DaemonTaskMessage_t xMessage;
+ BaseType_t xReturn;
- /* This function can only be called after a timer has been created or
- after the scheduler has been started because, until then, the timer
- queue does not exist. */
- configASSERT( xTimerQueue );
+ /* This function can only be called after a timer has been created or
+ after the scheduler has been started because, until then, the timer
+ queue does not exist. */
+ configASSERT(xTimerQueue);
- /* Complete the message with the function parameters and post it to the
- daemon task. */
- xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK;
- xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
- xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
- xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
+ /* Complete the message with the function parameters and post it to the
+ daemon task. */
+ xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK;
+ xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
+ xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
+ xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
- xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
+ xReturn = xQueueSendToBack(xTimerQueue, &xMessage, xTicksToWait);
- tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
+ tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, xReturn);
- return xReturn;
- }
+ return xReturn;
+}
#endif /* INCLUDE_xTimerPendFunctionCall */
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
+#if (configUSE_TRACE_FACILITY == 1)
- UBaseType_t uxTimerGetTimerNumber( TimerHandle_t xTimer )
- {
- return ( ( Timer_t * ) xTimer )->uxTimerNumber;
- }
+UBaseType_t uxTimerGetTimerNumber(TimerHandle_t xTimer) { return ((Timer_t *)xTimer)->uxTimerNumber; }
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
-#if ( configUSE_TRACE_FACILITY == 1 )
+#if (configUSE_TRACE_FACILITY == 1)
- void vTimerSetTimerNumber( TimerHandle_t xTimer, UBaseType_t uxTimerNumber )
- {
- ( ( Timer_t * ) xTimer )->uxTimerNumber = uxTimerNumber;
- }
+void vTimerSetTimerNumber(TimerHandle_t xTimer, UBaseType_t uxTimerNumber) { ((Timer_t *)xTimer)->uxTimerNumber = uxTimerNumber; }
#endif /* configUSE_TRACE_FACILITY */
/*-----------------------------------------------------------*/
@@ -1122,6 +975,3 @@ Timer_t * const pxTimer = xTimer;
to include software timer functionality. If you want to include software timer
functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
#endif /* configUSE_TIMERS == 1 */
-
-
-