Browse Source

Encoders bring up

Bartosz Jakubski 4 months ago
parent
commit
cc27eb942a
33 changed files with 127318 additions and 119450 deletions
  1. 3 2
      OZE_Main/Core/Inc/interprocess_data.h
  2. 2 1
      OZE_Main/Core/Inc/measurements.h
  3. 15 9
      OZE_Main/Core/Inc/serial_protocol.h
  4. 16 14
      OZE_Main/Core/Src/main.c
  5. 2 1
      OZE_Main/Core/Src/mock_tasks.c
  6. 178 144
      OZE_Main/Core/Src/mqtt_client.c
  7. 12 19
      OZE_Main/Core/Src/uart_tasks.c
  8. 75687 74895
      OZE_Main/Debug/OZE_Main.list
  9. 2689 2681
      OZE_Main/Debug/OZE_Main.map
  10. 2 2
      OZE_Main/OZE_Main.ioc
  11. 2 2
      OZE_Sensor/.mxproject
  12. 3 3
      OZE_Sensor/Core/Inc/interprocess_data.h
  13. 24 9
      OZE_Sensor/Core/Inc/meas_tasks.h
  14. 2 1
      OZE_Sensor/Core/Inc/measurements.h
  15. 3 0
      OZE_Sensor/Core/Inc/node-red-config.h
  16. 15 9
      OZE_Sensor/Core/Inc/serial_protocol.h
  17. 1 1
      OZE_Sensor/Core/Inc/stm32h7xx_hal_conf.h
  18. 1 0
      OZE_Sensor/Core/Inc/stm32h7xx_it.h
  19. 205 5
      OZE_Sensor/Core/Src/main.c
  20. 95 69
      OZE_Sensor/Core/Src/meas_tasks.c
  21. 2 1
      OZE_Sensor/Core/Src/mock_tasks.c
  22. 73 100
      OZE_Sensor/Core/Src/peripherial.c
  23. 128 0
      OZE_Sensor/Core/Src/stm32h7xx_hal_msp.c
  24. 15 0
      OZE_Sensor/Core/Src/stm32h7xx_it.c
  25. 107 51
      OZE_Sensor/Core/Src/uart_tasks.c
  26. 5 2
      OZE_Sensor/Debug/Drivers/STM32H7xx_HAL_Driver/Src/subdir.mk
  27. 42698 39595
      OZE_Sensor/Debug/OZE_Sensor.list
  28. 2096 1775
      OZE_Sensor/Debug/OZE_Sensor.map
  29. 1 0
      OZE_Sensor/Debug/objects.list
  30. 953 0
      OZE_Sensor/Drivers/STM32H7xx_HAL_Driver/Inc/stm32h7xx_hal_comp.h
  31. 941 0
      OZE_Sensor/Drivers/STM32H7xx_HAL_Driver/Inc/stm32h7xx_ll_comp.h
  32. 1247 0
      OZE_Sensor/Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_comp.c
  33. 95 59
      OZE_Sensor/OZE_Sensor.ioc

+ 3 - 2
OZE_Main/Core/Inc/interprocess_data.h

@@ -12,17 +12,18 @@
 #include "stdint.h"
 
 struct _IntegerValues {
-    int32_t value[2];
+    int32_t value[3];
 };
 
 
 struct _FloatValues {
-    float value[2];
+    float value[3];
 };
 
 struct _MixedValues {
     int32_t value1;
     float value2;
+    uint32_t value3;
 };
 
 typedef struct _FloatValues FloatValues;

+ 2 - 1
OZE_Main/Core/Inc/measurements.h

@@ -24,7 +24,8 @@ struct _RESMeasurements {
 struct _SesnorsInfo {
     float pvTemperature[TEMPERATURE_QTY];
     float fanVoltage;
-    float pvEncoder;
+    float pvEncoderX;
+    float pvEncoderY;
     uint8_t motorXStatus;
     uint8_t motorYStatus;
     float motorXAveCurrent;

+ 15 - 9
OZE_Main/Core/Inc/serial_protocol.h

@@ -29,15 +29,21 @@
 #define FRAME_TIMEOUT_MS 2000
 
 enum _SerialProtocolCommands {
-	spGetElectricalMeasurments,
-	spGetSensorMeasurments,
-	spSetFanSpeed,
-	spSetMotorXOn,
-	spSetMotorYOn,
-	spSetmotorXMaxCurrent,
-	spSetmotorYMaxCurrent,
-	spSetDiodeOn,
-	spClearPeakMeasurments,
+    spGetElectricalMeasurments,
+    spGetSensorMeasurments,
+    spSetFanSpeed,
+    spSetMotorXOn,
+    spSetMotorYOn,
+    spSetmotorXMaxCurrent,
+    spSetmotorYMaxCurrent,
+    spSetDiodeOn,
+    spClearPeakMeasurments,
+    spSetEncoderXValue,
+    spSetEncoderYValue,
+    spSetVoltageMeasGains,
+    spSetVoltageMeasOffsets,
+    spSetCurrentMeasGains,
+    spSetCurrentMeasOffsets,
     spUnknown
 };
 

+ 16 - 14
OZE_Main/Core/Src/main.c

@@ -117,6 +117,7 @@ void StartDefaultTask(void *argument);
 void relay1TimerCallback(void *argument);
 void relay2TimerCallback(void *argument);
 void relay3TimerCallback(void *argument);
+void relay4TimerCallback(void *argument);
 
 /* USER CODE BEGIN PFP */
 
@@ -131,8 +132,10 @@ void relay3TimerCallback(void *argument);
 
 int __io_putchar(int ch)
 {
+#ifdef UART_TASK_LOGS
   HAL_UART_Transmit(&huart8, (uint8_t *)&ch, 1, 0xFFFF); // Use UART8 as debug interface
 //  ITM_SendChar(ch);	// Use SWV as debug interface
+#endif
   return ch;
 }
 /* USER CODE END 0 */
@@ -214,7 +217,7 @@ int main(void)
   relay3TimerHandle = osTimerNew(relay3TimerCallback, osTimerOnce, NULL, &relay3Timer_attributes);
 
   /* creation of relay4Timer */
-  relay4TimerHandle = osTimerNew(relay1TimerCallback, osTimerOnce, NULL, &relay4Timer_attributes);
+  relay4TimerHandle = osTimerNew(relay4TimerCallback, osTimerOnce, NULL, &relay4Timer_attributes);
 
   /* USER CODE BEGIN RTOS_TIMERS */
   /* start timers, add new ones, ... */
@@ -689,6 +692,7 @@ static void MX_GPIO_Init(void)
   HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
 
 /* USER CODE BEGIN MX_GPIO_Init_2 */
+  HAL_GPIO_WritePin(GPIOE, GPIO_PIN_2|GPIO_PIN_3|GPIO_PIN_4|GPIO_PIN_5, GPIO_PIN_RESET);
   GPIO_InitStruct.Pin = GPIO_PIN_14|GPIO_PIN_15;
   GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
   GPIO_InitStruct.Pull = GPIO_PULLUP;
@@ -698,16 +702,6 @@ static void MX_GPIO_Init(void)
   HAL_Delay(100);
   HAL_GPIO_WritePin(GPIOE, GPIO_PIN_14, GPIO_PIN_SET);
   HAL_GPIO_WritePin(GPIOE, GPIO_PIN_15, GPIO_PIN_SET);
-
-//  	GPIO_InitStruct.Pin = GPIO_PIN_14;
-//	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
-//	GPIO_InitStruct.Pull = GPIO_PULLUP;
-//	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
-//	HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
-//	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, GPIO_PIN_RESET);
-//	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, GPIO_PIN_SET);
-//	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, GPIO_PIN_RESET);
-//	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_14, GPIO_PIN_SET);
 /* USER CODE END MX_GPIO_Init_2 */
 }
 
@@ -739,7 +733,7 @@ void StartDefaultTask(void *argument)
 void relay1TimerCallback(void *argument)
 {
   /* USER CODE BEGIN relay1TimerCallback */
-
+	HAL_GPIO_WritePin(GPIOE, GPIO_PIN_5, GPIO_PIN_RESET);
   /* USER CODE END relay1TimerCallback */
 }
 
@@ -747,7 +741,7 @@ void relay1TimerCallback(void *argument)
 void relay2TimerCallback(void *argument)
 {
   /* USER CODE BEGIN relay2TimerCallback */
-
+	HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET);
   /* USER CODE END relay2TimerCallback */
 }
 
@@ -755,10 +749,18 @@ void relay2TimerCallback(void *argument)
 void relay3TimerCallback(void *argument)
 {
   /* USER CODE BEGIN relay3TimerCallback */
-
+  HAL_GPIO_WritePin(GPIOE, GPIO_PIN_4, GPIO_PIN_RESET);
   /* USER CODE END relay3TimerCallback */
 }
 
+/* relay4TimerCallback function */
+void relay4TimerCallback(void *argument)
+{
+  /* USER CODE BEGIN relay4TimerCallback */
+  HAL_GPIO_WritePin(GPIOE, GPIO_PIN_2, GPIO_PIN_RESET);
+  /* USER CODE END relay4TimerCallback */
+}
+
  /* MPU Configuration */
 
 void MPU_Config(void)

+ 2 - 1
OZE_Main/Core/Src/mock_tasks.c

@@ -76,7 +76,8 @@ void MockMeasurmetsTask (void* argument) {
 			sensors->pvTemperature[0] = 50 + (0.01 * (counter % 100));
 			sensors->pvTemperature[1] = 51 + (0.01 * (counter % 100));
 			sensors->fanVoltage = 12 + (0.01 * (counter % 100));
-			sensors->pvEncoder = 15 + (0.01 * (counter % 100));
+			sensors->pvEncoderX = 15 + (0.01 * (counter % 100));
+			sensors->pvEncoderY = 10 + (0.01 * (counter % 100));
 			sensors->motorXStatus = (counter % 100) > 50 ? 1 : 0;
 			sensors->motorYStatus = (counter % 100) > 75 ? 1 : 0;
 			sensors->motorXAveCurrent = 3 + (0.01 * (counter % 100));

+ 178 - 144
OZE_Main/Core/Src/mqtt_client.c

@@ -5,7 +5,6 @@
  *      Author: jakubski
  */
 #include <stdio.h>
-#if 1
 #include "FreeRTOS.h"
 #include "task.h"
 #include "main.h"
@@ -25,8 +24,27 @@
 #define MQTT_BUFSIZE	1024
 
 char* const subscribeTopicNames[MASTER_BOARD + SLAVES_COUNT] = { "Set/0", "Set/1", "Set/2", "Set/3", "Set/4" };
-#define MAX_COMMANDS_IN_MQTT_PAYLOAD 9
-char* const topicCommands[MAX_COMMANDS_IN_MQTT_PAYLOAD] = {"fanSpeed", "motorXon", "motorYon", "diode", "motorXMaxCurrent", "motorYMaxCurrent", "clearPeakElectricalMeasurements", "mainBoardRelay"};
+#define MAX_COMMANDS_IN_MQTT_PAYLOAD 14
+char* const topicCommands[MAX_COMMANDS_IN_MQTT_PAYLOAD] = { "fanSpeed", "motorXon", "motorYon", "diode", "motorXMaxCurrent", "motorYMaxCurrent", "clearPeakElectricalMeasurements", "mainBoardRelay",
+    "setEncoderXValue", "setEncoderYValue", "setVoltageMeasGains", "setVoltageMeasOffsets", "setCurrentMeasGains", "setCurrentMeasOffsets" };
+
+enum _Topics
+{
+	fanSpeedTopic = 0,
+	motorXonTopic,
+	motorYonTopic,
+	diodeTopic,
+	motorXMaxCurrentTopic,
+	motorYMaxCurrentTopic,
+	clearPeakElectricalMeasurementsTopic,
+	mainBoardRelayTopic,
+	setEncoderXValue,
+	setEncoderYValue,
+	setVoltageMeasGains,
+	setVoltageMeasOffsets,
+	setCurrentMeasGains,
+	setCurrentMeasOffsets
+};
 
 enum _BoardNoOverTopic
 {
@@ -48,6 +66,11 @@ extern UartTaskData uart6TaskData;  // Board 3
 extern UartTaskData uart2TaskData;  // Board 4
 extern UartTaskData uart8TaskData;  // Debug
 
+extern osTimerId_t relay1TimerHandle;
+extern osTimerId_t relay2TimerHandle;
+extern osTimerId_t relay3TimerHandle;
+extern osTimerId_t relay4TimerHandle;
+
 const osThreadAttr_t mqttClientSubTaskAttr =
 { .name = "mqttClientSubTask", .stack_size = configMINIMAL_STACK_SIZE * 4,
 		.priority = (osPriority_t) osPriorityNormal, };
@@ -65,10 +88,11 @@ MQTTClient mqttClient; //mqtt client
 uint8_t sndBuffer[MQTT_BUFSIZE]; //mqtt send buffer
 uint8_t rcvBuffer[MQTT_BUFSIZE]; //mqtt receive buffer
 
-void MqttClientSubTask(void *argument); //mqtt client subscribe task function
-void MqttClientPubTask(void *argument); //mqtt client publish task function
-int MqttConnectBroker(void); 				//mqtt broker connect function
-void MqttMessageArrived(MessageData *msg); //mqtt message callback function
+void RelayCtrl(int32_t relayNumber, int32_t relayTimeOn);
+void MqttClientSubTask (void* argument);    // mqtt client subscribe task function
+void MqttClientPubTask (void* argument);    // mqtt client publish task function
+uint32_t MqttConnectBroker (void);          // mqtt broker connect function
+void MqttMessageArrived (MessageData* msg); // mqtt message callback function
 
 void MqttClientSubTask (void* argument) {
     while (1) {
@@ -122,28 +146,34 @@ void MqttClientPubTask (void* argument) {
                     MQTTPublish (&mqttClient, topicTextBuffer, &message); // publish a message
                 }
 
-                for (boardNumber = 0; boardNumber < SLAVES_COUNT; boardNumber++) {
-                    osMutexAcquire (sensorsInfoMutex, osWaitForever);
-                    SesnorsInfo* sensors = &sensorsInfo[boardNumber];
-                    sprintf (topicTextBuffer, "Sensors/%d", boardNumber + 1);
-                    bytesInBuffer = sprintf (messageBuffer, "{\"pvTemperature\":[%.1f, %.1f], ", sensors->pvTemperature[0], sensors->pvTemperature[1]);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"fanVoltage\":%.2f, ", sensors->fanVoltage);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"pvEncoder\":%.2f, ", sensors->pvEncoder);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorXStatus\":%d, ", sensors->motorXStatus);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorYStatus\":%d, ", sensors->motorYStatus);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorXAveCurrent\":%.3f, ", sensors->motorXAveCurrent);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorYAveCurrent\":%.3f, ", sensors->motorYAveCurrent);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorXPeakCurrent\":%.3f, ", sensors->motorXPeakCurrent);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorYPeakCurrent\":%.3f, ", sensors->motorYPeakCurrent);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitXSwitchUp\":%d, ", sensors->limitXSwitchUp);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitXSwitchDown\":%d, ", sensors->limitXSwitchDown);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitXSwitchCenter\":%d, ", sensors->limitXSwitchCenter);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitYSwitchUp\":%d, ", sensors->limitYSwitchUp);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitYSwitchDown\":%d, ", sensors->limitYSwitchDown);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitYSwitchCenter\":%d, ", sensors->limitYSwitchCenter);
-                    bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"powerSupplyFailMask\":%d}", sensors->powerSupplyFailMask);
-
-                    osMutexRelease (sensorsInfoMutex);
+                for (boardNumber = 0; boardNumber < SLAVES_COUNT + 1; boardNumber++) {
+                    if (boardNumber > 0) {
+                        osMutexAcquire (sensorsInfoMutex, osWaitForever);
+                        SesnorsInfo* sensors = &sensorsInfo[boardNumber - 1];
+                        sprintf (topicTextBuffer, "Sensors/%d", boardNumber);
+                        bytesInBuffer = sprintf (messageBuffer, "{\"pvTemperature\":[%.1f, %.1f], ", sensors->pvTemperature[0], sensors->pvTemperature[1]);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"fanVoltage\":%.2f, ", sensors->fanVoltage);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"pvEncoderX\":%.2f, ", sensors->pvEncoderX);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"pvEncoderY\":%.2f, ", sensors->pvEncoderY);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorXStatus\":%d, ", sensors->motorXStatus);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorYStatus\":%d, ", sensors->motorYStatus);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorXAveCurrent\":%.3f, ", sensors->motorXAveCurrent);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorYAveCurrent\":%.3f, ", sensors->motorYAveCurrent);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorXPeakCurrent\":%.3f, ", sensors->motorXPeakCurrent);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"motorYPeakCurrent\":%.3f, ", sensors->motorYPeakCurrent);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitXSwitchUp\":%d, ", sensors->limitXSwitchUp);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitXSwitchDown\":%d, ", sensors->limitXSwitchDown);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitXSwitchCenter\":%d, ", sensors->limitXSwitchCenter);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitYSwitchUp\":%d, ", sensors->limitYSwitchUp);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitYSwitchDown\":%d, ", sensors->limitYSwitchDown);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"limitYSwitchCenter\":%d, ", sensors->limitYSwitchCenter);
+                        bytesInBuffer += sprintf (&messageBuffer[bytesInBuffer], "\"powerSupplyFailMask\":%d}", sensors->powerSupplyFailMask);
+                        osMutexRelease (sensorsInfoMutex);
+                    } else {
+                        sprintf (topicTextBuffer, "Sensors/%d", boardNumber);
+                        uint8_t mainBoardPowerSupplyFailMask = ~((HAL_GPIO_ReadPin (GPIOD, GPIO_PIN_4) << 1) | HAL_GPIO_ReadPin (GPIOD, GPIO_PIN_2)) & 0x3;
+                        bytesInBuffer = sprintf (messageBuffer, "{\"powerSupplyFailMask\":%d}", mainBoardPowerSupplyFailMask);
+                    }
                     message.payload    = (void*)messageBuffer;
                     message.payloadlen = strlen (messageBuffer);
                     MQTTPublish (&mqttClient, topicTextBuffer, &message); // publish a message
@@ -155,7 +185,7 @@ void MqttClientPubTask (void* argument) {
     }
 }
 
-int MqttConnectBroker () {
+uint32_t MqttConnectBroker () {
     uint8_t boardNumber = 0;
     int ret;
 
@@ -197,6 +227,60 @@ int MqttConnectBroker () {
     return MQTT_SUCCESS;
 }
 
+void RelayCtrl (int32_t relayNumber, int32_t relayTimeOn) {
+    switch (relayNumber) {
+    case 1:
+        if (relayTimeOn > 0) {
+            osTimerStart (relay1TimerHandle, relayTimeOn * 1000);
+        } else {
+            osTimerStop (relay1TimerHandle);
+        }
+        if (relayTimeOn != 0) {
+            HAL_GPIO_WritePin (GPIOE, GPIO_PIN_5, GPIO_PIN_SET);
+        } else {
+            HAL_GPIO_WritePin (GPIOE, GPIO_PIN_5, GPIO_PIN_RESET);
+        }
+        break;
+    case 2:
+        if (relayTimeOn > 0) {
+            osTimerStart (relay2TimerHandle, relayTimeOn * 1000);
+        } else {
+            osTimerStop (relay2TimerHandle);
+        }
+        if (relayTimeOn != 0) {
+            HAL_GPIO_WritePin (GPIOE, GPIO_PIN_3, GPIO_PIN_SET);
+        } else {
+            HAL_GPIO_WritePin (GPIOE, GPIO_PIN_3, GPIO_PIN_RESET);
+        }
+        break;
+    case 3:
+        if (relayTimeOn > 0) {
+            osTimerStart (relay3TimerHandle, relayTimeOn * 1000);
+        } else {
+            osTimerStop (relay3TimerHandle);
+        }
+        if (relayTimeOn != 0) {
+            HAL_GPIO_WritePin (GPIOE, GPIO_PIN_4, GPIO_PIN_SET);
+        } else {
+            HAL_GPIO_WritePin (GPIOE, GPIO_PIN_4, GPIO_PIN_RESET);
+        }
+        break;
+    case 4:
+        if (relayTimeOn > 0) {
+            osTimerStart (relay4TimerHandle, relayTimeOn * 1000);
+        } else {
+            osTimerStop (relay4TimerHandle);
+        }
+        if (relayTimeOn != 0) {
+            HAL_GPIO_WritePin (GPIOE, GPIO_PIN_2, GPIO_PIN_SET);
+        } else {
+            HAL_GPIO_WritePin (GPIOE, GPIO_PIN_2, GPIO_PIN_RESET);
+        }
+        break;
+    default: break;
+    }
+}
+
 void MqttMessageArrived (MessageData* msg) {
     SerialProtocolCommands spCommand = spUnknown;
     BoardNoOverTopic topicForBoard   = unknownBoard;
@@ -215,23 +299,24 @@ void MqttMessageArrived (MessageData* msg) {
     cJSON* json             = cJSON_Parse (message->payload);
     const cJSON* objectItem = NULL;
     InterProcessData data   = { 0 };
+    uint32_t arraySize      = 0;
     for (int topicCmdNumber = 0; topicCmdNumber < MAX_COMMANDS_IN_MQTT_PAYLOAD; topicCmdNumber++) {
         spCommand  = spUnknown;
         objectItem = cJSON_GetObjectItemCaseSensitive (json, topicCommands[topicCmdNumber]);
         if (objectItem != NULL) {
             switch (topicCmdNumber) {
-            case 0: spCommand = spSetFanSpeed;
-            case 1:
+            case fanSpeedTopic: spCommand = spSetFanSpeed;
+            case motorXonTopic:
                 if (spCommand == spUnknown) {
                     spCommand = spSetMotorXOn;
                 }
-            case 2:
+            case motorYonTopic:
                 if (spCommand == spUnknown) {
                     spCommand = spSetMotorYOn;
                 }
                 if (cJSON_IsArray (objectItem)) {
                     data.spCommand = spCommand;
-                    int arraySize  = cJSON_GetArraySize (objectItem);
+                    arraySize      = cJSON_GetArraySize (objectItem);
                     if (arraySize == 2) {
                         for (int i = 0; i < arraySize; i++) {
                             cJSON* item = cJSON_GetArrayItem (objectItem, i);
@@ -242,13 +327,13 @@ void MqttMessageArrived (MessageData* msg) {
                     }
                 }
                 break;
-            case 3:
+            case diodeTopic:
                 data.spCommand                     = spSetDiodeOn;
                 data.values.integerValues.value[0] = objectItem->valueint;
                 data.values.integerValues.value[1] = 0;
                 break;
-            case 4: spCommand = spSetmotorXMaxCurrent;
-            case 5:
+            case motorXMaxCurrentTopic: spCommand = spSetmotorXMaxCurrent;
+            case motorYMaxCurrentTopic:
                 if (spCommand == spUnknown) {
                     spCommand = spSetmotorYMaxCurrent;
                 }
@@ -256,27 +341,71 @@ void MqttMessageArrived (MessageData* msg) {
                 data.values.flaotValues.value[0] = objectItem->valuedouble;
                 data.values.flaotValues.value[1] = 0.0;
                 break;
-            case 6:
-            	data.spCommand = spClearPeakMeasurments;
-            	break;
-            case 7:
+            case clearPeakElectricalMeasurementsTopic: data.spCommand = spClearPeakMeasurments; break;
+            case mainBoardRelayTopic:
+                if (cJSON_IsArray (objectItem)) {
+                    arraySize = cJSON_GetArraySize (objectItem);
+                    if (arraySize == 2) {
+                        int32_t relayNumber = -1;
+                        cJSON* item         = cJSON_GetArrayItem (objectItem, 0);
+                        if (cJSON_IsNumber (item)) {
+                            relayNumber = item->valueint;
+                        }
+                        int32_t relayTimeOn = 0;
+                        item                = cJSON_GetArrayItem (objectItem, 1);
+                        if (cJSON_IsNumber (item)) {
+                            relayTimeOn = item->valueint;
+                        }
+                        RelayCtrl (relayNumber, relayTimeOn);
+                    }
+                }
+                break;
+            case setEncoderXValue:
+                data.spCommand                   = spSetEncoderXValue;
+                data.values.flaotValues.value[0] = objectItem->valuedouble;
+                data.values.flaotValues.value[1] = 0;
+                break;
+            case setEncoderYValue:
+                data.spCommand                   = spSetEncoderYValue;
+                data.values.flaotValues.value[0] = objectItem->valuedouble;
+                data.values.flaotValues.value[1] = 0;
+                break;
+            case setVoltageMeasGains:
+            	spCommand = spSetVoltageMeasGains;
+            case setVoltageMeasOffsets:
+                if (spCommand == spUnknown) {
+                    spCommand = spSetVoltageMeasOffsets;
+                }
+            case setCurrentMeasGains:
+                if (spCommand == spUnknown) {
+                    spCommand = spSetCurrentMeasGains;
+                }
+            case setCurrentMeasOffsets:
+                if (spCommand == spUnknown) {
+                    spCommand = spSetCurrentMeasOffsets;
+                }
+                if (cJSON_IsArray (objectItem)) {
+                    data.spCommand = spCommand;
+                    arraySize      = cJSON_GetArraySize (objectItem);
+                    if (arraySize == 3) {
+                        for (int i = 0; i < arraySize; i++) {
+                            cJSON* item = cJSON_GetArrayItem (objectItem, i);
+                            if (cJSON_IsNumber (item)) {
+                                data.values.flaotValues.value[i] = item->valuedouble;
+                            }
+                        }
+                    }
+                }
             	break;
             default: break;
             }
 
             switch (topicForBoard) {
-            case main_board:
-            	break;
+            case main_board: break;
             case board_1:
-#if 1
                 if (uart1TaskData.sendCmdToSlaveQueue != NULL) {
                     osMessageQueuePut (uart1TaskData.sendCmdToSlaveQueue, &data, 0, (TickType_t)100);
                 }
-#else
-                if (uart8TaskData.sendCmdToSlaveQueue != NULL) {
-                    osMessageQueuePut (uart8TaskData.sendCmdToSlaveQueue, &data, 0, (TickType_t)100);
-                }
-#endif
                 printf ("Send cmd to board 1\n");
                 break;
             case board_2:
@@ -309,98 +438,3 @@ void mqtt_cli_init (void) {
     mqttClientSubTaskHandle = osThreadNew (MqttClientSubTask, NULL, &mqttClientSubTaskAttr); // subscribe task
     mqttClientPubTaskHandle = osThreadNew (MqttClientPubTask, NULL, &mqttClientPubTaskAttr); // publish task
 }
-
-#else
-#include "lwip/opt.h"
-#include "lwip/arch.h"
-#include "lwip/api.h"
-#include "lwip/apps/mqtt.h"
-
-#include "cmsis_os.h"
-
-#define MQTT_CLI_THREAD_PRIO    ( tskIDLE_PRIORITY + 4 )
-
-#ifndef LWIP_MQTT_EXAMPLE_IPADDR_INIT
-#if LWIP_IPV4
-#define LWIP_MQTT_EXAMPLE_IPADDR_INIT = IPADDR4_INIT(PP_HTONL(IPADDR_LOOPBACK))
-#else
-#define LWIP_MQTT_EXAMPLE_IPADDR_INIT
-#endif
-#endif
-
-static ip_addr_t mqtt_ip LWIP_MQTT_EXAMPLE_IPADDR_INIT;
-
-static const struct mqtt_connect_client_info_t mqtt_client_info =
-{
-	"test_user1",
-	"test_user1", /* user */
-	"1234", /* pass */
-	100,  /* keep alive */
-	NULL, /* will_topic */
-	NULL, /* will_msg */
-	0,    /* will_qos */
-	0     /* will_retain */
-	#if LWIP_ALTCP && LWIP_ALTCP_TLS
-	, NULL
-	#endif
-};
-
-static void mqtt_incoming_data_cb(void *arg, const u8_t *data, u16_t len, u8_t flags)
-{
-	const struct mqtt_connect_client_info_t* client_info = (const struct mqtt_connect_client_info_t*)arg;
-//	LWIP_UNUSED_ARG(data);
-
-	LWIP_PLATFORM_DIAG(("MQTT client \"%s\" data cb: len %d, flags %d\n", client_info->client_id, (int)len, (int)flags));
-	LWIP_PLATFORM_DIAG(("Data:\n%s\n", data));
-}
-
-static void mqtt_incoming_publish_cb(void *arg, const char *topic, u32_t tot_len)
-{
-	const struct mqtt_connect_client_info_t* client_info = (const struct mqtt_connect_client_info_t*)arg;
-
-	LWIP_PLATFORM_DIAG(("MQTT client \"%s\" publish cb: topic %s, len %d\n", client_info->client_id, topic, (int)tot_len));
-}
-
-static void mqtt_request_cb(void *arg, err_t err)
-{
-	const struct mqtt_connect_client_info_t* client_info = (const struct mqtt_connect_client_info_t*)arg;
-
-	LWIP_PLATFORM_DIAG(("MQTT client \"%s\" request cb: err %d\n", client_info->client_id, (int)err));
-}VES_COUNT; boardNumber++)
-			{
-
-static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status)
-{
-	const struct mqtt_connect_client_info_t* client_info = (const struct mqtt_connect_client_info_t*)arg;
-//	LWIP_UNUSED_ARG(client);
-
-	LWIP_PLATFORM_DIAG(("MQTT client \"%s\" connection cb: status %d\n", client_info->client_id, (int)status));
-
-	if (status == MQTT_CONNECT_ACCEPTED)
-	{
-		mqtt_sub_unsub(client, "topic_qos1", 1, mqtt_request_cb, LWIP_CONST_CAST(void*, client_info), 1);
-		mqtt_sub_unsub(client, "topic_qos0", 0, mqtt_request_cb, LWIP_CONST_CAST(void*, client_info), 1);
-	}
-}
-
-void mqtt_cli_thread(void *arg)
-{
-	mqtt_client_t* mqtt_client;
-	osDelay(pdMS_TO_TICKS(7000));
-	ipaddr_aton("192.168.1.34", &mqtt_ip);
-	LOCK_TCPIP_CORE();
-	mqtt_client = mqtt_client_new();
-	mqtt_client_connect(mqtt_client, &mqtt_ip, MQTT_PORT, mqtt_connection_cb, LWIP_CONST_CAST(void*, &mqtt_client_info), &mqtt_client_info);
-	mqtt_set_inpub_callback(mqtt_client, mqtt_incoming_publish_cb, mqtt_incoming_data_cb, LWIP_CONST_CAST(void*, &mqtt_client_info));
-	UNLOCK_TCPIP_CORE();
-	while(1)
-	{
-		osDelay(pdMS_TO_TICKS(100));
-	}
-}
-
-void mqtt_cli_init(void)
-{
-	sys_thread_new("mqtt_cli_netconn", mqtt_cli_thread, NULL, DEFAULT_THREAD_STACKSIZE, MQTT_CLI_THREAD_PRIO);
-}
-#endif

+ 12 - 19
OZE_Main/Core/Src/uart_tasks.c

@@ -199,11 +199,7 @@ void UartRxTask (void* argument) {
 
     uartTaskData->rxDataBufferMutex = osMutexNew (NULL);
     HAL_UARTEx_ReceiveToIdle_IT (uartTaskData->huart, uartTaskData->uartRxBuffer, uartTaskData->uartRxBufferLen);
-    //	HAL_UARTEx_ReceiveToIdle_DMA(&huart8, uart8RxBuffer, 32);
     while (pdTRUE) {
-        //		HAL_UART_Receive_IT(&huart8, uart8RxBuffer, 1);
-        //		if(osSemaphoreAcquire(uart8RxSemaphore, pdMS_TO_TICKS(1000)) !=
-        // osOK) 		if(xTaskNotifyWait(0, 0, &bytesRec, portMAX_DELAY) == pdTrue)
         frameTimeout = !(xTaskNotifyWait (0, 0, &bytesRec, pdMS_TO_TICKS (FRAME_TIMEOUT_MS)));
 
         osMutexAcquire (uartTaskData->rxDataBufferMutex, osWaitForever);
@@ -215,9 +211,7 @@ void UartRxTask (void* argument) {
         } else {
             if (frameTimeout == pdFALSE) {
                 proceed = pdTRUE;
-#if UART_TASK_LOGS
                 printf ("Uart%d: RX bytes received: %ld\n", uartTaskData->uartNumber, bytesRec);
-#endif
             } else {
                 if (uartTaskData->huart->RxState == HAL_UART_STATE_READY) {
                     HAL_UARTEx_ReceiveToIdle_IT (uartTaskData->huart, uartTaskData->uartRxBuffer, uartTaskData->uartRxBufferLen);
@@ -272,9 +266,7 @@ void UartRxTask (void* argument) {
                 osMutexRelease (uartTaskData->rxDataBufferMutex);
                 crcPass = frameCrc == crc;
                 if (crcPass) {
-#if UART_TASK_LOGS
                     printf ("Uart%d: Frame CRC PASS\n", uartTaskData->uartNumber);
-#endif
                     receverState = srExecuteCmd;
                 } else {
                     receverState = srFail;
@@ -302,14 +294,10 @@ void UartRxTask (void* argument) {
                 dataToSend = 0;
                 if ((frameTimeout == pdTRUE) && (frameBytesCount > 2)) {
                     dataToSend = PrepareRespFrame (uartTaskData->uartTxBuffer, spFrameData.frameHeader.frameId, spFrameData.frameHeader.frameCommand, spTimeout, NULL, 0);
-#if UART_TASK_LOGS
                     printf ("Uart%d: RX data receiver timeout!\n", uartTaskData->uartNumber);
-#endif
                 } else if (!crcPass) {
                     dataToSend = PrepareRespFrame (uartTaskData->uartTxBuffer, spFrameData.frameHeader.frameId, spFrameData.frameHeader.frameCommand, spCrcFail, NULL, 0);
-#if UART_TASK_LOGS
                     printf ("Uart%d: Frame CRC FAIL\n", uartTaskData->uartNumber);
-#endif
                 }
                 else
                 {
@@ -318,9 +306,7 @@ void UartRxTask (void* argument) {
                 if (dataToSend > 0) {
                     HAL_UART_Transmit_IT (uartTaskData->huart, uartTaskData->uartTxBuffer, dataToSend);
                 }
-#if UART_TASK_LOGS
                 printf ("Uart%d: TX bytes sent: %d\n", dataToSend, uartTaskData->uartNumber);
-#endif
                 receverState = srFinish;
                 break;
             case srFinish:
@@ -380,6 +366,16 @@ void UartTxTask (void* argument) {
             case spGetElectricalMeasurments:
             case spGetSensorMeasurments: break;
             case spClearPeakMeasurments: break;
+            case spSetEncoderXValue: WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &data.values.flaotValues.value[0], sizeof (float)); break;
+            case spSetEncoderYValue: WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &data.values.flaotValues.value[0], sizeof (float)); break;
+            case spSetVoltageMeasGains:
+            case spSetVoltageMeasOffsets:
+            case spSetCurrentMeasGains:
+            case spSetCurrentMeasOffsets:
+            	WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &data.values.flaotValues.value[0], sizeof (float));
+            	WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &data.values.flaotValues.value[1], sizeof (float));
+            	WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &data.values.flaotValues.value[2], sizeof (float));
+            	break;
             default: continue; break;
             }
 
@@ -400,14 +396,10 @@ void UartTxTask (void* argument) {
                 	slaveLastSeen[boardNumber]++;
                 	osMutexRelease(resMeasurementsMutex);
                 }
-#if UART_TASK_LOGS
                 printf ("Uart%d: Response timeout for frameId 0x%x\n", uartTaskData->uartNumber, frameId);
-#endif
             } else {
                 if ((frameId == frameData.frameHeader.frameId) && (frameData.frameHeader.respStatus == spOK)) {
-#if UART_TASK_LOGS
                     printf ("Uart%d: Response for frameId 0x%x OK\n", uartTaskData->uartNumber, frameId);
-#endif
                     slaveLastSeen[boardNumber] = 0;
                     switch(frameData.frameHeader.frameCommand)
                     {
@@ -429,7 +421,8 @@ void UartTxTask (void* argument) {
                     	ReadFloatFromBuffer(frameData.dataBuffer, &inputDataBufferPos, &sensors->pvTemperature[0]);
                     	ReadFloatFromBuffer(frameData.dataBuffer, &inputDataBufferPos, &sensors->pvTemperature[1]);
                     	ReadFloatFromBuffer(frameData.dataBuffer, &inputDataBufferPos, &sensors->fanVoltage);
-                    	ReadFloatFromBuffer(frameData.dataBuffer, &inputDataBufferPos, &sensors->pvEncoder);
+                    	ReadFloatFromBuffer(frameData.dataBuffer, &inputDataBufferPos, &sensors->pvEncoderX);
+                    	ReadFloatFromBuffer(frameData.dataBuffer, &inputDataBufferPos, &sensors->pvEncoderY);
                     	ReadByteFromBufer(frameData.dataBuffer, &inputDataBufferPos, &sensors->motorXStatus);
                     	ReadByteFromBufer(frameData.dataBuffer, &inputDataBufferPos, &sensors->motorYStatus);
                     	ReadFloatFromBuffer(frameData.dataBuffer, &inputDataBufferPos, &sensors->motorXAveCurrent);

File diff suppressed because it is too large
+ 75687 - 74895
OZE_Main/Debug/OZE_Main.list


File diff suppressed because it is too large
+ 2689 - 2681
OZE_Main/Debug/OZE_Main.map


File diff suppressed because it is too large
+ 2 - 2
OZE_Main/OZE_Main.ioc


File diff suppressed because it is too large
+ 2 - 2
OZE_Sensor/.mxproject


+ 3 - 3
OZE_Sensor/Core/Inc/interprocess_data.h

@@ -12,17 +12,17 @@
 #include "stdint.h"
 
 struct _IntegerValues {
-    int32_t value[2];
+    int32_t value[3];
 };
 
-
 struct _FloatValues {
-    float value[2];
+    float value[3];
 };
 
 struct _MixedValues {
     int32_t value1;
     float value2;
+    uint32_t value3;
 };
 
 typedef struct _FloatValues FloatValues;

+ 24 - 9
OZE_Sensor/Core/Inc/meas_tasks.h

@@ -10,32 +10,47 @@
 
 #include "FreeRTOS.h"
 #include "FreeRTOSConfig.h"
-#include "task.h"
 #include "cmsis_os.h"
 #include "stm32h7xx_hal.h"
+#include "task.h"
 
 #define GAIN_AUTO_CORRECTION
 
-struct _LimiterSwitchData
-{
-	uint16_t gpioPin;
-	GPIO_PinState pinState;
+struct _LimiterSwitchData {
+    uint16_t gpioPin;
+    GPIO_PinState pinState;
 };
 
 typedef struct _LimiterSwitchData LimiterSwitchData;
 
+enum _EncoderDirection { encoderCW, encoderCCW };
+typedef enum _EncoderDirection EncoderDirection;
+
+enum _EncoderAxe { encoderAxeX, encoderAxeY };
+typedef enum _EncoderAxe EncoderAxe;
+
+struct _EncoderData {
+    EncoderAxe axe;
+    EncoderDirection direction;
+};
+
+typedef struct _EncoderData EncoderData;
+
 extern osMessageQueueId_t adc1MeasDataQueue;
 extern osMessageQueueId_t adc2MeasDataQueue;
 extern osMessageQueueId_t adc3MeasDataQueue;
 extern osMessageQueueId_t limiterSwitchDataQueue;
+extern osMessageQueueId_t encoderXDataQueue;
+extern osMessageQueueId_t encoderYDataQueue;
 
 extern osMutexId_t resMeasurementsMutex;
 extern osMutexId_t sensorsInfoMutex;
 
-void MeasTasksInit(void);
-void ADC1MeasTask(void *arg);
-void ADC2MeasTask(void *arg);
-void ADC3MeasTask(void *arg);
+void MeasTasksInit (void);
+void ADC1MeasTask (void* arg);
+void ADC2MeasTask (void* arg);
+void ADC3MeasTask (void* arg);
 void LimiterSwitchTask (void* arg);
+void EncoderTask (void* arg);
 
 #endif /* INC_MEAS_TASKS_H_ */

+ 2 - 1
OZE_Sensor/Core/Inc/measurements.h

@@ -23,7 +23,8 @@ struct _RESMeasurements {
 struct _SesnorsInfo {
     float pvTemperature[TEMPERATURE_QTY];
     float fanVoltage;
-    float pvEncoder;
+    float pvEncoderX;
+    float pvEncoderY;
     uint8_t motorXStatus;
     uint8_t motorYStatus;
     float motorXAveCurrent;

+ 3 - 0
OZE_Sensor/Core/Inc/node-red-config.h

@@ -15,6 +15,9 @@
 
 #define UART_TASK_LOGS FEATURE_ON
 
+#define ENCODER_X_IMP_PER_TURN 20
+#define ENCODER_Y_IMP_PER_TURN 20
+
 //#define USER_MOCKS
 
 #endif /* INC_NODE_RED_CONFIG_H_ */

+ 15 - 9
OZE_Sensor/Core/Inc/serial_protocol.h

@@ -29,15 +29,21 @@
 #define FRAME_TIMEOUT_MS 2000
 
 enum _SerialProtocolCommands {
-	spGetElectricalMeasurments,
-	spGetSensorMeasurments,
-	spSetFanSpeed,
-	spSetMotorXOn,
-	spSetMotorYOn,
-	spSetmotorXMaxCurrent,
-	spSetmotorYMaxCurrent,
-	spSetDiodeOn,
-	spClearPeakMeasurments,
+    spGetElectricalMeasurments,
+    spGetSensorMeasurments,
+    spSetFanSpeed,
+    spSetMotorXOn,
+    spSetMotorYOn,
+    spSetmotorXMaxCurrent,
+    spSetmotorYMaxCurrent,
+    spSetDiodeOn,
+    spClearPeakMeasurments,
+    spSetEncoderXValue,
+    spSetEncoderYValue,
+    spSetVoltageMeasGains,
+    spSetVoltageMeasOffsets,
+    spSetCurrentMeasGains,
+    spSetCurrentMeasOffsets,
     spUnknown
 };
 

+ 1 - 1
OZE_Sensor/Core/Inc/stm32h7xx_hal_conf.h

@@ -38,7 +38,7 @@
 /* #define HAL_FDCAN_MODULE_ENABLED   */
 /* #define HAL_FMAC_MODULE_ENABLED   */
 /* #define HAL_CEC_MODULE_ENABLED   */
-/* #define HAL_COMP_MODULE_ENABLED   */
+#define HAL_COMP_MODULE_ENABLED
 /* #define HAL_CORDIC_MODULE_ENABLED   */
 #define HAL_CRC_MODULE_ENABLED
 /* #define HAL_CRYP_MODULE_ENABLED   */

+ 1 - 0
OZE_Sensor/Core/Inc/stm32h7xx_it.h

@@ -58,6 +58,7 @@ void DMA1_Stream1_IRQHandler(void);
 void DMA1_Stream2_IRQHandler(void);
 void EXTI9_5_IRQHandler(void);
 void TIM2_IRQHandler(void);
+void TIM4_IRQHandler(void);
 void USART1_IRQHandler(void);
 void EXTI15_10_IRQHandler(void);
 void TIM6_DAC_IRQHandler(void);

+ 205 - 5
OZE_Sensor/Core/Src/main.c

@@ -57,6 +57,8 @@ DMA_HandleTypeDef hdma_adc1;
 DMA_HandleTypeDef hdma_adc2;
 DMA_HandleTypeDef hdma_adc3;
 
+COMP_HandleTypeDef hcomp1;
+
 CRC_HandleTypeDef hcrc;
 
 DAC_HandleTypeDef hdac1;
@@ -66,6 +68,7 @@ RNG_HandleTypeDef hrng;
 TIM_HandleTypeDef htim1;
 TIM_HandleTypeDef htim2;
 TIM_HandleTypeDef htim3;
+TIM_HandleTypeDef htim4;
 
 UART_HandleTypeDef huart8;
 UART_HandleTypeDef huart1;
@@ -114,6 +117,10 @@ TIM_OC_InitTypeDef fanTimerConfigOC = { 0 };
 TIM_OC_InitTypeDef motorXYTimerConfigOC = { 0 };
 extern RESMeasurements resMeasurements;
 extern SesnorsInfo sensorsInfo;
+volatile int32_t encoderXChannelA = 0;
+volatile int32_t encoderXChannelB = 0;
+volatile int32_t encoderYChannelA = 0;
+volatile int32_t encoderYChannelB = 0;
 
 /* USER CODE END PV */
 
@@ -134,6 +141,8 @@ static void MX_TIM2_Init(void);
 static void MX_TIM1_Init(void);
 static void MX_TIM3_Init(void);
 static void MX_DAC1_Init(void);
+static void MX_COMP1_Init(void);
+static void MX_TIM4_Init(void);
 void StartDefaultTask(void *argument);
 void debugLedTimerCallback(void *argument);
 void fanTimerCallback(void *argument);
@@ -148,8 +157,10 @@ void motorYTimerCallback(void *argument);
 /* USER CODE BEGIN 0 */
 int __io_putchar(int ch)
 {
+#if UART_TASK_LOGS
   HAL_UART_Transmit(&huart8, (uint8_t *)&ch, 1, 0xFFFF); // Use UART8 as debug interface
 //  ITM_SendChar(ch);	// Use SWV as debug interface
+#endif
   return ch;
 }
 
@@ -217,6 +228,8 @@ int main(void)
   MX_TIM1_Init();
   MX_TIM3_Init();
   MX_DAC1_Init();
+  MX_COMP1_Init();
+  MX_TIM4_Init();
   /* USER CODE BEGIN 2 */
 
   /* USER CODE END 2 */
@@ -676,6 +689,40 @@ static void MX_ADC3_Init(void)
 }
 
 /**
+  * @brief COMP1 Initialization Function
+  * @param None
+  * @retval None
+  */
+static void MX_COMP1_Init(void)
+{
+
+  /* USER CODE BEGIN COMP1_Init 0 */
+
+  /* USER CODE END COMP1_Init 0 */
+
+  /* USER CODE BEGIN COMP1_Init 1 */
+
+  /* USER CODE END COMP1_Init 1 */
+  hcomp1.Instance = COMP1;
+  hcomp1.Init.InvertingInput = COMP_INPUT_MINUS_3_4VREFINT;
+  hcomp1.Init.NonInvertingInput = COMP_INPUT_PLUS_IO2;
+  hcomp1.Init.OutputPol = COMP_OUTPUTPOL_NONINVERTED;
+  hcomp1.Init.Hysteresis = COMP_HYSTERESIS_NONE;
+  hcomp1.Init.BlankingSrce = COMP_BLANKINGSRC_NONE;
+  hcomp1.Init.Mode = COMP_POWERMODE_HIGHSPEED;
+  hcomp1.Init.WindowMode = COMP_WINDOWMODE_DISABLE;
+  hcomp1.Init.TriggerMode = COMP_TRIGGERMODE_NONE;
+  if (HAL_COMP_Init(&hcomp1) != HAL_OK)
+  {
+    Error_Handler();
+  }
+  /* USER CODE BEGIN COMP1_Init 2 */
+
+  /* USER CODE END COMP1_Init 2 */
+
+}
+
+/**
   * @brief CRC Initialization Function
   * @param None
   * @retval None
@@ -869,6 +916,7 @@ static void MX_TIM2_Init(void)
 
   TIM_ClockConfigTypeDef sClockSourceConfig = {0};
   TIM_MasterConfigTypeDef sMasterConfig = {0};
+  TIM_IC_InitTypeDef sConfigIC = {0};
 
   /* USER CODE BEGIN TIM2_Init 1 */
 
@@ -888,12 +936,28 @@ static void MX_TIM2_Init(void)
   {
     Error_Handler();
   }
+  if (HAL_TIM_IC_Init(&htim2) != HAL_OK)
+  {
+    Error_Handler();
+  }
   sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
   sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_ENABLE;
   if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
   {
     Error_Handler();
   }
+  sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING;
+  sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;
+  sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;
+  sConfigIC.ICFilter = 0;
+  if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_3) != HAL_OK)
+  {
+    Error_Handler();
+  }
+  if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_4) != HAL_OK)
+  {
+    Error_Handler();
+  }
   /* USER CODE BEGIN TIM2_Init 2 */
 
   /* USER CODE END TIM2_Init 2 */
@@ -967,6 +1031,68 @@ static void MX_TIM3_Init(void)
 }
 
 /**
+  * @brief TIM4 Initialization Function
+  * @param None
+  * @retval None
+  */
+static void MX_TIM4_Init(void)
+{
+
+  /* USER CODE BEGIN TIM4_Init 0 */
+
+  /* USER CODE END TIM4_Init 0 */
+
+  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
+  TIM_MasterConfigTypeDef sMasterConfig = {0};
+  TIM_IC_InitTypeDef sConfigIC = {0};
+
+  /* USER CODE BEGIN TIM4_Init 1 */
+
+  /* USER CODE END TIM4_Init 1 */
+  htim4.Instance = TIM4;
+  htim4.Init.Prescaler = 19999;
+  htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
+  htim4.Init.Period = 9999;
+  htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
+  htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;
+  if (HAL_TIM_Base_Init(&htim4) != HAL_OK)
+  {
+    Error_Handler();
+  }
+  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
+  if (HAL_TIM_ConfigClockSource(&htim4, &sClockSourceConfig) != HAL_OK)
+  {
+    Error_Handler();
+  }
+  if (HAL_TIM_IC_Init(&htim4) != HAL_OK)
+  {
+    Error_Handler();
+  }
+  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
+  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
+  if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK)
+  {
+    Error_Handler();
+  }
+  sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING;
+  sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;
+  sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;
+  sConfigIC.ICFilter = 0;
+  if (HAL_TIM_IC_ConfigChannel(&htim4, &sConfigIC, TIM_CHANNEL_3) != HAL_OK)
+  {
+    Error_Handler();
+  }
+  if (HAL_TIM_IC_ConfigChannel(&htim4, &sConfigIC, TIM_CHANNEL_4) != HAL_OK)
+  {
+    Error_Handler();
+  }
+  /* USER CODE BEGIN TIM4_Init 2 */
+
+  /* USER CODE END TIM4_Init 2 */
+
+}
+
+/**
   * @brief UART8 Initialization Function
   * @param None
   * @retval None
@@ -1194,6 +1320,47 @@ void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc)
 	}osTimerStop (debugLedTimerHandle);
 }
 
+void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
+{
+	if (htim->Instance == TIM4)
+	{
+		if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_3)
+		{
+			encoderXChannelA = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_3);
+		} else if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4)
+		{
+			encoderXChannelB = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_4);
+		}
+		if((encoderXChannelA != 0) && (encoderXChannelB != 0))
+		{
+			EncoderData encoderData = { 0 };
+			encoderData.axe = encoderAxeX;
+			encoderData.direction = encoderXChannelA - encoderXChannelB < 0 ? encoderCW : encoderCCW;
+			osMessageQueuePut(encoderXDataQueue, &encoderData, 0, 0);
+			encoderXChannelA = 0;
+			encoderXChannelB = 0;
+		}
+	} else if (htim->Instance == TIM2)
+	{
+		if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_3)
+		{
+			encoderYChannelA = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_3);
+		} else if(htim->Channel == HAL_TIM_ACTIVE_CHANNEL_4)
+		{
+			encoderYChannelB = HAL_TIM_ReadCapturedValue(htim, TIM_CHANNEL_4);
+		}
+		if((encoderYChannelA != 0) && (encoderYChannelB != 0))
+		{
+			EncoderData encoderData = { 0 };
+			encoderData.axe = encoderAxeY;
+			encoderData.direction = encoderYChannelA - encoderYChannelB < 0 ? encoderCW : encoderCCW;
+			osMessageQueuePut(encoderYDataQueue, &encoderData, 0, 0);
+			encoderYChannelA = 0;
+			encoderYChannelB = 0;
+		}
+	}
+}
+
 /* USER CODE END 4 */
 
 /* USER CODE BEGIN Header_StartDefaultTask */
@@ -1215,10 +1382,26 @@ void StartDefaultTask(void *argument)
   {
 	  Error_Handler();
   }
-//  if(HAL_ADC_Start_IT(&hadc1) != HAL_OK)
-//  {
-//	  Error_Handler();
-//  }
+  if(HAL_TIM_Base_Start_IT(&htim4) != HAL_OK)
+  {
+	  Error_Handler();
+  }
+  if(HAL_TIM_IC_Start_IT(&htim4, TIM_CHANNEL_3) != HAL_OK)
+  {
+	  Error_Handler();
+  }
+  if(HAL_TIM_IC_Start_IT(&htim4, TIM_CHANNEL_4) != HAL_OK)
+  {
+	  Error_Handler();
+  }
+  if(HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_3) != HAL_OK)
+  {
+	  Error_Handler();
+  }
+  if(HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_4) != HAL_OK)
+  {
+	  Error_Handler();
+  }
   if(HAL_ADC_Start_DMA(&hadc1, (uint32_t *)adc1Data.adcDataBuffer, ADC1LastData) != HAL_OK)
   {
 	  Error_Handler();
@@ -1231,6 +1414,7 @@ void StartDefaultTask(void *argument)
   {
 	  Error_Handler();
   }
+  HAL_COMP_Start(&hcomp1);
   /* Infinite loop */
   for(;;)
   {
@@ -1362,9 +1546,25 @@ void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
     HAL_IncTick();
   }
   /* USER CODE BEGIN Callback 1 */
+  else if (htim->Instance == TIM4)
+  {
+	  if(encoderXChannelA > 0)
+	  {
+		  encoderXChannelB += htim->Instance->ARR;
+	  } else if(encoderXChannelB > 0)
+	  {
+		  encoderXChannelA += htim->Instance->ARR;
+	  }
+  }
   else if (htim->Instance == TIM2)
   {
-
+	  if(encoderYChannelA > 0)
+	  {
+		  encoderYChannelB += htim->Instance->ARR;
+	  } else if(encoderYChannelB > 0)
+	  {
+		  encoderYChannelA += htim->Instance->ARR;
+	  }
   }
 
   /* USER CODE END Callback 1 */

+ 95 - 69
OZE_Sensor/Core/Src/meas_tasks.c

@@ -8,8 +8,8 @@
 #include "meas_tasks.h"
 #include "adc_buffers.h"
 #include "measurements.h"
-#include "peripherial.h"
 #include "node-red-config.h"
+#include "peripherial.h"
 
 #include "cmsis_os.h"
 #include "main.h"
@@ -24,15 +24,19 @@
 
 #define CIRC_BUFF_LEN 10
 
-osThreadId_t adc1MeasTaskHandle = NULL;
-osThreadId_t adc2MeasTaskHandle = NULL;
-osThreadId_t adc3MeasTaskHandle = NULL;
+osThreadId_t adc1MeasTaskHandle      = NULL;
+osThreadId_t adc2MeasTaskHandle      = NULL;
+osThreadId_t adc3MeasTaskHandle      = NULL;
 osThreadId_t limiterSwitchTaskHandle = NULL;
+osThreadId_t encoderXTaskHandle      = NULL;
+osThreadId_t encoderYTaskHandle      = NULL;
 
-osMessageQueueId_t adc1MeasDataQueue = NULL;
-osMessageQueueId_t adc2MeasDataQueue = NULL;
-osMessageQueueId_t adc3MeasDataQueue = NULL;
+osMessageQueueId_t adc1MeasDataQueue      = NULL;
+osMessageQueueId_t adc2MeasDataQueue      = NULL;
+osMessageQueueId_t adc3MeasDataQueue      = NULL;
 osMessageQueueId_t limiterSwitchDataQueue = NULL;
+osMessageQueueId_t encoderXDataQueue      = NULL;
+osMessageQueueId_t encoderYDataQueue      = NULL;
 
 osMutexId_t vRefmVMutex;
 osMutexId_t resMeasurementsMutex;
@@ -56,7 +60,7 @@ void MeasTasksInit (void) {
     vRefmVMutex          = osMutexNew (NULL);
     resMeasurementsMutex = osMutexNew (NULL);
     sensorsInfoMutex     = osMutexNew (NULL);
-    ILxRefMutex			 = osMutexNew (NULL);
+    ILxRefMutex          = osMutexNew (NULL);
     adc1MeasDataQueue    = osMessageQueueNew (8, sizeof (ADC1_Data), NULL);
     adc2MeasDataQueue    = osMessageQueueNew (8, sizeof (ADC2_Data), NULL);
     adc3MeasDataQueue    = osMessageQueueNew (8, sizeof (ADC3_Data), NULL);
@@ -81,14 +85,28 @@ void MeasTasksInit (void) {
     limiterSwitchDataQueue = osMessageQueueNew (8, sizeof (LimiterSwitchData), NULL);
 
     osThreadAttr_t osThreadAttradc1LimiterSwitchTask = { 0 };
-    osThreadAttradc1LimiterSwitchTask.stack_size = configMINIMAL_STACK_SIZE * 2;
-    osThreadAttradc1LimiterSwitchTask.priority   = (osPriority_t)osPriorityNormal;
-    limiterSwitchTaskHandle = osThreadNew (LimiterSwitchTask, NULL, &osThreadAttradc1LimiterSwitchTask);
+    osThreadAttradc1LimiterSwitchTask.stack_size     = configMINIMAL_STACK_SIZE * 2;
+    osThreadAttradc1LimiterSwitchTask.priority       = (osPriority_t)osPriorityNormal;
+    limiterSwitchTaskHandle                          = osThreadNew (LimiterSwitchTask, NULL, &osThreadAttradc1LimiterSwitchTask);
+
+    encoderXDataQueue = osMessageQueueNew (8, sizeof (EncoderData), NULL);
+    encoderYDataQueue = osMessageQueueNew (8, sizeof (EncoderData), NULL);
+
+    osThreadAttr_t osThreadAttrEncoderXTask = { 0 };
+    osThreadAttrEncoderXTask.stack_size     = configMINIMAL_STACK_SIZE * 2;
+    osThreadAttrEncoderXTask.priority       = (osPriority_t)osPriorityNormal;
+    encoderXTaskHandle                      = osThreadNew (EncoderTask, encoderXDataQueue, &osThreadAttrEncoderXTask);
+
+    osThreadAttr_t osThreadAttrEncoderYTask = { 0 };
+    osThreadAttrEncoderYTask.stack_size     = configMINIMAL_STACK_SIZE * 2;
+    osThreadAttrEncoderYTask.priority       = (osPriority_t)osPriorityNormal;
+    encoderYTaskHandle                      = osThreadNew (EncoderTask, encoderYDataQueue, &osThreadAttrEncoderYTask);
 }
 
 void ADC1MeasTask (void* arg) {
-    float circBuffer[VOLTAGES_COUNT][CIRC_BUFF_LEN] = {0};
-    float rms[VOLTAGES_COUNT] = {0};;
+    float circBuffer[VOLTAGES_COUNT][CIRC_BUFF_LEN] = { 0 };
+    float rms[VOLTAGES_COUNT]                       = { 0 };
+    ;
     ADC1_Data adcData    = { 0 };
     uint32_t circBuffPos = 0;
     float gainCorrection = 1.0;
@@ -110,7 +128,7 @@ void ADC1MeasTask (void* arg) {
             }
             rms[i] = rms[i] / CIRC_BUFF_LEN;
             if (osMutexAcquire (resMeasurementsMutex, osWaitForever) == osOK) {
-                if (fabs(resMeasurements.voltagePeak[i]) < fabs(val)) {
+                if (fabs (resMeasurements.voltagePeak[i]) < fabs (val)) {
                     resMeasurements.voltagePeak[i] = val;
                 }
                 resMeasurements.voltageRMS[i] = rms[i];
@@ -131,18 +149,18 @@ void ADC1MeasTask (void* arg) {
 
         float fanFBVoltage = adcData.adcDataBuffer[FanFB] * deltaADC * -4.35 + 12;
         if (osMutexAcquire (sensorsInfoMutex, osWaitForever) == osOK) {
-        	sensorsInfo.fanVoltage = fanFBVoltage;
-        	osMutexRelease(sensorsInfoMutex);
+            sensorsInfo.fanVoltage = fanFBVoltage;
+            osMutexRelease (sensorsInfoMutex);
         }
     }
 }
 
 void ADC2MeasTask (void* arg) {
-    float circBuffer[CURRENTS_COUNT][CIRC_BUFF_LEN] = {0};
-    float rms[CURRENTS_COUNT] = {0};
-    ADC2_Data adcData    = { 0 };
-    uint32_t circBuffPos = 0;
-    float gainCorrection = 1.0;
+    float circBuffer[CURRENTS_COUNT][CIRC_BUFF_LEN] = { 0 };
+    float rms[CURRENTS_COUNT]                       = { 0 };
+    ADC2_Data adcData                               = { 0 };
+    uint32_t circBuffPos                            = 0;
+    float gainCorrection                            = 1.0;
     while (pdTRUE) {
         osMessageQueueGet (adc2MeasDataQueue, &adcData, 0, osWaitForever);
         if (osMutexAcquire (vRefmVMutex, osWaitForever) == osOK) {
@@ -206,8 +224,10 @@ void ADC3MeasTask (void* arg) {
         for (uint8_t i = 0; i < CIRC_BUFF_LEN; i++) {
             motorXAveCurrent += motorXSensCircBuffer[i];
             motorYAveCurrent += motorYSensCircBuffer[i];
+#ifdef PV_BOARD
             pvT1AveTemp += pvT1CircBuffer[i];
             pvT2AveTemp += pvT2CircBuffer[i];
+#endif
         }
         motorXAveCurrent /= CIRC_BUFF_LEN;
         motorYAveCurrent /= CIRC_BUFF_LEN;
@@ -236,52 +256,58 @@ void ADC3MeasTask (void* arg) {
 }
 
 void LimiterSwitchTask (void* arg) {
-	LimiterSwitchData limiterSwitchData = { 0 };
-	limiterSwitchData.gpioPin = GPIO_PIN_8;
-	for(uint8_t i = 0; i < 6; i++)
-	{
-		limiterSwitchData.pinState = HAL_GPIO_ReadPin(GPIOD, limiterSwitchData.gpioPin);
-		osMessageQueuePut(limiterSwitchDataQueue, &limiterSwitchData, 0, 0);
-		limiterSwitchData.gpioPin = limiterSwitchData.gpioPin << 1;
-	}
-	while (pdTRUE) {
-		osMessageQueueGet (limiterSwitchDataQueue, &limiterSwitchData, 0, osWaitForever);
-		if(osMutexAcquire(sensorsInfoMutex, osWaitForever) == osOK)
-		{
-			switch(limiterSwitchData.gpioPin)
-			{
-			case GPIO_PIN_8:
-				sensorsInfo.limitYSwitchCenter = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1;
-				break;
-			case GPIO_PIN_9:
-				sensorsInfo.limitYSwitchDown = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1;
-				break;
-			case GPIO_PIN_10:
-				sensorsInfo.limitXSwitchCenter = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1;
-				break;
-			case GPIO_PIN_11:
-				sensorsInfo.limitYSwitchUp = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1;
-				break;
-			case GPIO_PIN_12:
-				sensorsInfo.limitXSwitchUp = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1;
-				break;
-			case GPIO_PIN_13:
-				sensorsInfo.limitXSwitchDown = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1;
-				break;
-			default:
-				break;
-			}
-			if((sensorsInfo.limitXSwitchDown == 1) ||(sensorsInfo.limitXSwitchUp == 1))
-			{
-				sensorsInfo.motorXStatus = motorControl(&htim3, &motorXYTimerConfigOC, TIM_CHANNEL_1, TIM_CHANNEL_2, motorXTimerHandle, 0, 0, sensorsInfo.limitXSwitchUp, sensorsInfo.limitXSwitchDown);
-			}
-			if((sensorsInfo.limitYSwitchDown == 1) ||(sensorsInfo.limitYSwitchUp == 1))
-			{
-				sensorsInfo.motorYStatus = motorControl(&htim3, &motorXYTimerConfigOC, TIM_CHANNEL_3, TIM_CHANNEL_4, motorYTimerHandle, 0, 0, sensorsInfo.limitYSwitchUp, sensorsInfo.limitYSwitchDown);
-			}
-//			sensorsInfo.motorXStatus = motorControl(&htim3, &motorXYTimerConfigOC, TIM_CHANNEL_1, TIM_CHANNEL_2, motorXTimerHandle, 0, 0, sensorsInfo.limitXSwitchUp, sensorsInfo.limitXSwitchDown);
-//			sensorsInfo.motorYStatus = motorControl(&htim3, &motorXYTimerConfigOC, TIM_CHANNEL_3, TIM_CHANNEL_4, motorYTimerHandle, 0, 0, sensorsInfo.limitYSwitchUp, sensorsInfo.limitYSwitchDown);
-			osMutexRelease(sensorsInfoMutex);
-		}
-	}
+    LimiterSwitchData limiterSwitchData = { 0 };
+    limiterSwitchData.gpioPin           = GPIO_PIN_8;
+    for (uint8_t i = 0; i < 6; i++) {
+        limiterSwitchData.pinState = HAL_GPIO_ReadPin (GPIOD, limiterSwitchData.gpioPin);
+        osMessageQueuePut (limiterSwitchDataQueue, &limiterSwitchData, 0, 0);
+        limiterSwitchData.gpioPin = limiterSwitchData.gpioPin << 1;
+    }
+    while (pdTRUE) {
+        osMessageQueueGet (limiterSwitchDataQueue, &limiterSwitchData, 0, osWaitForever);
+        if (osMutexAcquire (sensorsInfoMutex, osWaitForever) == osOK) {
+            switch (limiterSwitchData.gpioPin) {
+            case GPIO_PIN_8: sensorsInfo.limitYSwitchCenter = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1; break;
+            case GPIO_PIN_9: sensorsInfo.limitYSwitchDown = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1; break;
+            case GPIO_PIN_10: sensorsInfo.limitXSwitchCenter = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1; break;
+            case GPIO_PIN_11: sensorsInfo.limitYSwitchUp = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1; break;
+            case GPIO_PIN_12: sensorsInfo.limitXSwitchUp = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1; break;
+            case GPIO_PIN_13: sensorsInfo.limitXSwitchDown = limiterSwitchData.pinState == GPIO_PIN_SET ? 0 : 1; break;
+            default: break;
+            }
+            if ((sensorsInfo.limitXSwitchDown == 1) || (sensorsInfo.limitXSwitchUp == 1)) {
+                sensorsInfo.motorXStatus = motorControl (&htim3, &motorXYTimerConfigOC, TIM_CHANNEL_1, TIM_CHANNEL_2, motorXTimerHandle, 0, 0, sensorsInfo.limitXSwitchUp, sensorsInfo.limitXSwitchDown);
+            }
+            if ((sensorsInfo.limitYSwitchDown == 1) || (sensorsInfo.limitYSwitchUp == 1)) {
+                sensorsInfo.motorYStatus = motorControl (&htim3, &motorXYTimerConfigOC, TIM_CHANNEL_3, TIM_CHANNEL_4, motorYTimerHandle, 0, 0, sensorsInfo.limitYSwitchUp, sensorsInfo.limitYSwitchDown);
+            }
+            osMutexRelease (sensorsInfoMutex);
+        }
+    }
+}
+
+void EncoderTask (void* arg) {
+    EncoderData encoderData         = { 0 };
+    osMessageQueueId_t encoderQueue = (osMessageQueueId_t)arg;
+    while (pdTRUE) {
+        osMessageQueueGet (encoderQueue, &encoderData, 0, osWaitForever);
+        if (osMutexAcquire (sensorsInfoMutex, osWaitForever) == osOK) {
+            if (encoderData.axe == encoderAxeX) {
+                if (encoderData.direction == encoderCW) {
+                    sensorsInfo.pvEncoderX += 360.0 / ENCODER_X_IMP_PER_TURN;
+                } else {
+                    sensorsInfo.pvEncoderX -= 360.0 / ENCODER_X_IMP_PER_TURN;
+                }
+                DbgLEDToggle(DBG_LED2);
+            } else {
+                if (encoderData.direction == encoderCW) {
+                    sensorsInfo.pvEncoderY += 360.0 / ENCODER_Y_IMP_PER_TURN;
+                } else {
+                    sensorsInfo.pvEncoderY -= 360.0 / ENCODER_Y_IMP_PER_TURN;
+                }
+                DbgLEDToggle(DBG_LED3);
+            }
+            osMutexRelease (sensorsInfoMutex);
+        }
+    }
 }

+ 2 - 1
OZE_Sensor/Core/Src/mock_tasks.c

@@ -70,7 +70,8 @@ void MockMeasurmetsTask (void* argument) {
 		sensorsInfo.pvTemperature[0] = 50 + (0.01 * (counter % 100));
 		sensorsInfo.pvTemperature[1] = 51 + (0.01 * (counter % 100));
 		sensorsInfo.fanVoltage = 12 + (0.01 * (counter % 100));
-		sensorsInfo.pvEncoder = 15 + (0.01 * (counter % 100));
+		sensorsInfo.pvEncoderX = 15 + (0.01 * (counter % 100));
+		sensorsInfo.pvEncoderY = 10 + (0.01 * (counter % 100));
 		sensorsInfo.motorXStatus = (counter % 100) > 50 ? 1 : 0;
 		sensorsInfo.motorYStatus = (counter % 100) > 75 ? 1 : 0;
 		sensorsInfo.motorXAveCurrent = 3 + (0.01 * (counter % 100));

+ 73 - 100
OZE_Sensor/Core/Src/peripherial.c

@@ -9,62 +9,47 @@
 
 #include "peripherial.h"
 
-void DbgLEDOn(uint8_t ledNumber)
-{
-	HAL_GPIO_WritePin(GPIOD, ledNumber, GPIO_PIN_SET);
+void DbgLEDOn (uint8_t ledNumber) {
+    HAL_GPIO_WritePin (GPIOD, ledNumber, GPIO_PIN_SET);
 }
 
-void DbgLEDOff(uint8_t ledNumber)
-{
-	HAL_GPIO_WritePin(GPIOD, ledNumber, GPIO_PIN_RESET);
+void DbgLEDOff (uint8_t ledNumber) {
+    HAL_GPIO_WritePin (GPIOD, ledNumber, GPIO_PIN_RESET);
 }
 
-void DbgLEDToggle(uint8_t ledNumber)
-{
-	HAL_GPIO_TogglePin(GPIOD, ledNumber);
+void DbgLEDToggle (uint8_t ledNumber) {
+    HAL_GPIO_TogglePin (GPIOD, ledNumber);
 }
 
-void EnableCurrentSensors(void)
-{
-	HAL_GPIO_WritePin(GPIOE, MCU_CS_PWR_EN, GPIO_PIN_SET);
+void EnableCurrentSensors (void) {
+    HAL_GPIO_WritePin (GPIOE, MCU_CS_PWR_EN, GPIO_PIN_SET);
 }
 
-void DisableCurrentSensors(void)
-{
-	HAL_GPIO_WritePin(GPIOE, MCU_CS_PWR_EN, GPIO_PIN_RESET);
+void DisableCurrentSensors (void) {
+    HAL_GPIO_WritePin (GPIOE, MCU_CS_PWR_EN, GPIO_PIN_RESET);
 }
 
-void SelectCurrentSensorGain(CurrentSensor sensor, CurrentSensorGain gain)
-{
-	uint8_t gpioOffset = 0;
-	switch(sensor)
-	{
-	case CurrentSensorL1:
-		gpioOffset = CURRENT_SENSOR_L1_GPIO_OFFSET;
-		break;
-	case CurrentSensorL2:
-		gpioOffset = CURRENT_SENSOR_L2_GPIO_OFFSET;
-		break;
-	case CurrentSensorL3:
-		gpioOffset = CURRENT_SENSOR_L3_GPIO_OFFSET;
-		break;
-	default:
-		break;
-	}
-	if(gpioOffset > 0)
-	{
-		uint16_t gain0Gpio = 1 << gpioOffset;
-		uint16_t gain1Gpio = 1 << (gpioOffset + 1);
-		uint16_t gpioState = ((uint16_t)gain) & 0x0001;
-		HAL_GPIO_WritePin(GPIOE, gain0Gpio, gpioState);
-		gpioState = (((uint16_t)gain) >> 1) & 0x0001;
-		HAL_GPIO_WritePin(GPIOE, gain1Gpio, gpioState);
-	}
+void SelectCurrentSensorGain (CurrentSensor sensor, CurrentSensorGain gain) {
+    uint8_t gpioOffset = 0;
+    switch (sensor) {
+    case CurrentSensorL1: gpioOffset = CURRENT_SENSOR_L1_GPIO_OFFSET; break;
+    case CurrentSensorL2: gpioOffset = CURRENT_SENSOR_L2_GPIO_OFFSET; break;
+    case CurrentSensorL3: gpioOffset = CURRENT_SENSOR_L3_GPIO_OFFSET; break;
+    default: break;
+    }
+    if (gpioOffset > 0) {
+        uint16_t gain0Gpio = 1 << gpioOffset;
+        uint16_t gain1Gpio = 1 << (gpioOffset + 1);
+        uint16_t gpioState = ((uint16_t)gain) & 0x0001;
+        HAL_GPIO_WritePin (GPIOE, gain0Gpio, gpioState);
+        gpioState = (((uint16_t)gain) >> 1) & 0x0001;
+        HAL_GPIO_WritePin (GPIOE, gain1Gpio, gpioState);
+    }
 }
 
-uint8_t motorControl (TIM_HandleTypeDef* htim, TIM_OC_InitTypeDef* motorTimerConfigOC, uint8_t channel1, uint8_t channel2, osTimerId_t motorTimerHandle, int32_t motorPWMPulse,
-		int32_t motorTimerPeriod, uint8_t switchLimiterUpStat, uint8_t switchLimiterDownStat) {
-    uint32_t motorStatus           = 0;
+uint8_t
+motorControl (TIM_HandleTypeDef* htim, TIM_OC_InitTypeDef* motorTimerConfigOC, uint8_t channel1, uint8_t channel2, osTimerId_t motorTimerHandle, int32_t motorPWMPulse, int32_t motorTimerPeriod, uint8_t switchLimiterUpStat, uint8_t switchLimiterDownStat) {
+    uint32_t motorStatus            = 0;
     MotorDriverState setMotorYState = HiZ;
 
     HAL_TIM_PWM_Stop (htim, channel1);
@@ -76,12 +61,9 @@ uint8_t motorControl (TIM_HandleTypeDef* htim, TIM_OC_InitTypeDef* motorTimerCon
                 setMotorYState = Forward;
                 motorAction (htim, motorTimerConfigOC, channel1, channel2, setMotorYState, abs (motorPWMPulse) * 10);
                 HAL_TIM_PWM_Start (htim, channel1);
-//                HAL_TIM_PWM_Stop (htim, channel2);
                 motorStatus = 1;
-            }
-            else
-            {
-            	HAL_TIM_PWM_Stop (htim, channel1);
+            } else {
+                HAL_TIM_PWM_Stop (htim, channel1);
             }
             HAL_TIM_PWM_Stop (htim, channel2);
         } else if (motorPWMPulse < 0) {
@@ -91,10 +73,8 @@ uint8_t motorControl (TIM_HandleTypeDef* htim, TIM_OC_InitTypeDef* motorTimerCon
                 motorAction (htim, motorTimerConfigOC, channel1, channel2, setMotorYState, abs (motorPWMPulse) * 10);
                 HAL_TIM_PWM_Start (htim, channel2);
                 motorStatus = 1;
-            }
-            else
-            {
-            	HAL_TIM_PWM_Stop (htim, channel2);
+            } else {
+                HAL_TIM_PWM_Stop (htim, channel2);
             }
             HAL_TIM_PWM_Stop (htim, channel1);
         } else {
@@ -120,10 +100,8 @@ uint8_t motorControl (TIM_HandleTypeDef* htim, TIM_OC_InitTypeDef* motorTimerCon
                 motorAction (htim, motorTimerConfigOC, channel1, channel2, setMotorYState, abs (motorPWMPulse) * 10);
                 HAL_TIM_PWM_Start (htim, channel1);
                 motorStatus = 1;
-            }
-            else
-            {
-            	HAL_TIM_PWM_Stop (htim, channel1);
+            } else {
+                HAL_TIM_PWM_Stop (htim, channel1);
             }
             HAL_TIM_PWM_Stop (htim, channel2);
         } else {
@@ -133,10 +111,8 @@ uint8_t motorControl (TIM_HandleTypeDef* htim, TIM_OC_InitTypeDef* motorTimerCon
                 motorAction (htim, motorTimerConfigOC, channel1, channel2, setMotorYState, abs (motorPWMPulse) * 10);
                 HAL_TIM_PWM_Start (htim, channel2);
                 motorStatus = 1;
-            }
-            else
-            {
-            	HAL_TIM_PWM_Stop (htim, channel2);
+            } else {
+                HAL_TIM_PWM_Stop (htim, channel2);
             }
             HAL_TIM_PWM_Stop (htim, channel1);
         }
@@ -144,43 +120,40 @@ uint8_t motorControl (TIM_HandleTypeDef* htim, TIM_OC_InitTypeDef* motorTimerCon
     return motorStatus;
 }
 
-void motorAction(TIM_HandleTypeDef *tim, TIM_OC_InitTypeDef *timerConf, uint32_t channel1, uint32_t channel2, MotorDriverState setState, uint32_t pulse)
-{
-	timerConf->Pulse = pulse;
-	switch(setState)
-	{
-	case Forward:
-	case Reverse:
-	case HiZ:
-		timerConf->OCPolarity = TIM_OCPOLARITY_HIGH;
-	    if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel1) != HAL_OK) {
-	        Error_Handler ();
-	    }
-		timerConf->OCPolarity = TIM_OCPOLARITY_HIGH;
-	    if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel2) != HAL_OK) {
-	        Error_Handler ();
-	    }
-		break;
-	case Brake:
-		timerConf->OCPolarity = TIM_OCPOLARITY_LOW;
-	    if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel1) != HAL_OK) {
-	        Error_Handler ();
-	    }
-		timerConf->OCPolarity = TIM_OCPOLARITY_LOW;
-	    if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel2) != HAL_OK) {
-	        Error_Handler ();
-	    }
-		break;
-	default:
-		timerConf->OCPolarity = TIM_OCPOLARITY_HIGH;
-	    if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel1) != HAL_OK) {
-	        Error_Handler ();
-	    }
-		timerConf->OCPolarity = TIM_OCPOLARITY_HIGH;
-	    if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel2) != HAL_OK) {
-	        Error_Handler ();
-	    }
-		break;
-	}
-
+void motorAction (TIM_HandleTypeDef* tim, TIM_OC_InitTypeDef* timerConf, uint32_t channel1, uint32_t channel2, MotorDriverState setState, uint32_t pulse) {
+    timerConf->Pulse = pulse;
+    switch (setState) {
+    case Forward:
+    case Reverse:
+    case HiZ:
+        timerConf->OCPolarity = TIM_OCPOLARITY_HIGH;
+        if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel1) != HAL_OK) {
+            Error_Handler ();
+        }
+        timerConf->OCPolarity = TIM_OCPOLARITY_HIGH;
+        if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel2) != HAL_OK) {
+            Error_Handler ();
+        }
+        break;
+    case Brake:
+        timerConf->OCPolarity = TIM_OCPOLARITY_LOW;
+        if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel1) != HAL_OK) {
+            Error_Handler ();
+        }
+        timerConf->OCPolarity = TIM_OCPOLARITY_LOW;
+        if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel2) != HAL_OK) {
+            Error_Handler ();
+        }
+        break;
+    default:
+        timerConf->OCPolarity = TIM_OCPOLARITY_HIGH;
+        if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel1) != HAL_OK) {
+            Error_Handler ();
+        }
+        timerConf->OCPolarity = TIM_OCPOLARITY_HIGH;
+        if (HAL_TIM_PWM_ConfigChannel (tim, timerConf, channel2) != HAL_OK) {
+            Error_Handler ();
+        }
+        break;
+    }
 }

+ 128 - 0
OZE_Sensor/Core/Src/stm32h7xx_hal_msp.c

@@ -399,6 +399,67 @@ void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc)
 }
 
 /**
+* @brief COMP MSP Initialization
+* This function configures the hardware resources used in this example
+* @param hcomp: COMP handle pointer
+* @retval None
+*/
+void HAL_COMP_MspInit(COMP_HandleTypeDef* hcomp)
+{
+  GPIO_InitTypeDef GPIO_InitStruct = {0};
+  if(hcomp->Instance==COMP1)
+  {
+  /* USER CODE BEGIN COMP1_MspInit 0 */
+
+  /* USER CODE END COMP1_MspInit 0 */
+    /* Peripheral clock enable */
+    __HAL_RCC_COMP12_CLK_ENABLE();
+
+    __HAL_RCC_GPIOB_CLK_ENABLE();
+    /**COMP1 GPIO Configuration
+    PB2     ------> COMP1_INP
+    */
+    GPIO_InitStruct.Pin = GPIO_PIN_2;
+    GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
+    GPIO_InitStruct.Pull = GPIO_NOPULL;
+    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
+
+  /* USER CODE BEGIN COMP1_MspInit 1 */
+
+  /* USER CODE END COMP1_MspInit 1 */
+  }
+
+}
+
+/**
+* @brief COMP MSP De-Initialization
+* This function freeze the hardware resources used in this example
+* @param hcomp: COMP handle pointer
+* @retval None
+*/
+void HAL_COMP_MspDeInit(COMP_HandleTypeDef* hcomp)
+{
+  if(hcomp->Instance==COMP1)
+  {
+  /* USER CODE BEGIN COMP1_MspDeInit 0 */
+
+  /* USER CODE END COMP1_MspDeInit 0 */
+    /* Peripheral clock disable */
+    __HAL_RCC_COMP12_CLK_DISABLE();
+
+    /**COMP1 GPIO Configuration
+    PB2     ------> COMP1_INP
+    */
+    HAL_GPIO_DeInit(GPIOB, GPIO_PIN_2);
+
+  /* USER CODE BEGIN COMP1_MspDeInit 1 */
+
+  /* USER CODE END COMP1_MspDeInit 1 */
+  }
+
+}
+
+/**
 * @brief CRC MSP Initialization
 * This function configures the hardware resources used in this example
 * @param hcrc: CRC handle pointer
@@ -606,6 +667,7 @@ void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef* htim_pwm)
 */
 void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base)
 {
+  GPIO_InitTypeDef GPIO_InitStruct = {0};
   if(htim_base->Instance==TIM2)
   {
   /* USER CODE BEGIN TIM2_MspInit 0 */
@@ -613,6 +675,19 @@ void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base)
   /* USER CODE END TIM2_MspInit 0 */
     /* Peripheral clock enable */
     __HAL_RCC_TIM2_CLK_ENABLE();
+
+    __HAL_RCC_GPIOB_CLK_ENABLE();
+    /**TIM2 GPIO Configuration
+    PB10     ------> TIM2_CH3
+    PB11     ------> TIM2_CH4
+    */
+    GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11;
+    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
+    GPIO_InitStruct.Pull = GPIO_NOPULL;
+    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
+    GPIO_InitStruct.Alternate = GPIO_AF1_TIM2;
+    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
+
     /* TIM2 interrupt Init */
     HAL_NVIC_SetPriority(TIM2_IRQn, 5, 0);
     HAL_NVIC_EnableIRQ(TIM2_IRQn);
@@ -620,6 +695,33 @@ void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base)
 
   /* USER CODE END TIM2_MspInit 1 */
   }
+  else if(htim_base->Instance==TIM4)
+  {
+  /* USER CODE BEGIN TIM4_MspInit 0 */
+
+  /* USER CODE END TIM4_MspInit 0 */
+    /* Peripheral clock enable */
+    __HAL_RCC_TIM4_CLK_ENABLE();
+
+    __HAL_RCC_GPIOD_CLK_ENABLE();
+    /**TIM4 GPIO Configuration
+    PD14     ------> TIM4_CH3
+    PD15     ------> TIM4_CH4
+    */
+    GPIO_InitStruct.Pin = GPIO_PIN_14|GPIO_PIN_15;
+    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
+    GPIO_InitStruct.Pull = GPIO_NOPULL;
+    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
+    GPIO_InitStruct.Alternate = GPIO_AF2_TIM4;
+    HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);
+
+    /* TIM4 interrupt Init */
+    HAL_NVIC_SetPriority(TIM4_IRQn, 5, 0);
+    HAL_NVIC_EnableIRQ(TIM4_IRQn);
+  /* USER CODE BEGIN TIM4_MspInit 1 */
+
+  /* USER CODE END TIM4_MspInit 1 */
+  }
 
 }
 
@@ -721,12 +823,38 @@ void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* htim_base)
     /* Peripheral clock disable */
     __HAL_RCC_TIM2_CLK_DISABLE();
 
+    /**TIM2 GPIO Configuration
+    PB10     ------> TIM2_CH3
+    PB11     ------> TIM2_CH4
+    */
+    HAL_GPIO_DeInit(GPIOB, GPIO_PIN_10|GPIO_PIN_11);
+
     /* TIM2 interrupt DeInit */
     HAL_NVIC_DisableIRQ(TIM2_IRQn);
   /* USER CODE BEGIN TIM2_MspDeInit 1 */
 
   /* USER CODE END TIM2_MspDeInit 1 */
   }
+  else if(htim_base->Instance==TIM4)
+  {
+  /* USER CODE BEGIN TIM4_MspDeInit 0 */
+
+  /* USER CODE END TIM4_MspDeInit 0 */
+    /* Peripheral clock disable */
+    __HAL_RCC_TIM4_CLK_DISABLE();
+
+    /**TIM4 GPIO Configuration
+    PD14     ------> TIM4_CH3
+    PD15     ------> TIM4_CH4
+    */
+    HAL_GPIO_DeInit(GPIOD, GPIO_PIN_14|GPIO_PIN_15);
+
+    /* TIM4 interrupt DeInit */
+    HAL_NVIC_DisableIRQ(TIM4_IRQn);
+  /* USER CODE BEGIN TIM4_MspDeInit 1 */
+
+  /* USER CODE END TIM4_MspDeInit 1 */
+  }
 
 }
 

+ 15 - 0
OZE_Sensor/Core/Src/stm32h7xx_it.c

@@ -60,6 +60,7 @@ extern DMA_HandleTypeDef hdma_adc2;
 extern DMA_HandleTypeDef hdma_adc3;
 extern DAC_HandleTypeDef hdac1;
 extern TIM_HandleTypeDef htim2;
+extern TIM_HandleTypeDef htim4;
 extern UART_HandleTypeDef huart8;
 extern UART_HandleTypeDef huart1;
 extern TIM_HandleTypeDef htim6;
@@ -251,6 +252,20 @@ void TIM2_IRQHandler(void)
 }
 
 /**
+  * @brief This function handles TIM4 global interrupt.
+  */
+void TIM4_IRQHandler(void)
+{
+  /* USER CODE BEGIN TIM4_IRQn 0 */
+
+  /* USER CODE END TIM4_IRQn 0 */
+  HAL_TIM_IRQHandler(&htim4);
+  /* USER CODE BEGIN TIM4_IRQn 1 */
+
+  /* USER CODE END TIM4_IRQn 1 */
+}
+
+/**
   * @brief This function handles USART1 global interrupt.
   */
 void USART1_IRQHandler(void)

+ 107 - 51
OZE_Sensor/Core/Src/uart_tasks.c

@@ -12,13 +12,13 @@
 #include <stdlib.h>
 #include <string.h>
 
+#include "adc_buffers.h"
 #include "interprocess_data.h"
+#include "meas_tasks.h"
 #include "measurements.h"
 #include "mock_tasks.h"
-#include "uart_tasks.h"
-#include "meas_tasks.h"
 #include "peripherial.h"
-#include "adc_buffers.h"
+#include "uart_tasks.h"
 
 enum SerialReceiverStates { srWaitForHeader, srCheckCrc, srRecieveData, srExecuteCmd, srFail, srFinish, srLast };
 
@@ -36,6 +36,7 @@ extern TIM_HandleTypeDef htim1;
 extern TIM_HandleTypeDef htim3;
 extern TIM_OC_InitTypeDef fanTimerConfigOC;
 extern TIM_OC_InitTypeDef motorXYTimerConfigOC;
+extern COMP_HandleTypeDef hcomp1;
 
 uint8_t uart1RxBuffer[UART1_RX_BUFF_SIZE]        = { 0 };
 uint8_t uart1TxBuffer[UART1_TX_BUFF_SIZE]        = { 0 };
@@ -62,25 +63,25 @@ uint32_t slaveLastSeen[SLAVES_COUNT] = { 0 };
 
 extern RNG_HandleTypeDef hrng;
 
-void UartTasksInit(void) {
-  uart1TaskData.uartRxBuffer = uart1RxBuffer;
-  uart1TaskData.uartRxBufferLen = UART1_RX_BUFF_SIZE;
-  uart1TaskData.uartTxBuffer = uart1TxBuffer;
-  uart1TaskData.uartRxBufferLen = UART1_TX_BUFF_SIZE;
-  uart1TaskData.frameData = uart1TaskFrameData;
-  uart1TaskData.frameDataLen = UART1_RX_BUFF_SIZE;
-  uart1TaskData.huart = &huart1;
-  uart1TaskData.uartNumber = 1;
-  uart1TaskData.processDataCb = Uart1ReceivedDataProcessCallback;
-  uart1TaskData.processRxDataMsgBuffer = NULL;
-
-  UartTaskCreate(&uart1TaskData);
+void UartTasksInit (void) {
+    uart1TaskData.uartRxBuffer           = uart1RxBuffer;
+    uart1TaskData.uartRxBufferLen        = UART1_RX_BUFF_SIZE;
+    uart1TaskData.uartTxBuffer           = uart1TxBuffer;
+    uart1TaskData.uartRxBufferLen        = UART1_TX_BUFF_SIZE;
+    uart1TaskData.frameData              = uart1TaskFrameData;
+    uart1TaskData.frameDataLen           = UART1_RX_BUFF_SIZE;
+    uart1TaskData.huart                  = &huart1;
+    uart1TaskData.uartNumber             = 1;
+    uart1TaskData.processDataCb          = Uart1ReceivedDataProcessCallback;
+    uart1TaskData.processRxDataMsgBuffer = NULL;
+
+    UartTaskCreate (&uart1TaskData);
 }
 
 void UartTaskCreate (UartTaskData* uartTaskData) {
-    osThreadAttr_t osThreadAttrRxUart = { 0 };
-    osThreadAttrRxUart.stack_size = configMINIMAL_STACK_SIZE * 2;
-    osThreadAttrRxUart.priority   = (osPriority_t)osPriorityHigh;
+    osThreadAttr_t osThreadAttrRxUart   = { 0 };
+    osThreadAttrRxUart.stack_size       = configMINIMAL_STACK_SIZE * 2;
+    osThreadAttrRxUart.priority         = (osPriority_t)osPriorityHigh;
     uartTaskData->uartRecieveTaskHandle = osThreadNew (UartRxTask, uartTaskData, &osThreadAttrRxUart);
 }
 
@@ -105,15 +106,14 @@ void Uart8TasksInit (void) {
 }
 
 void HAL_UART_RxCpltCallback (UART_HandleTypeDef* huart) {
-
 }
 
-void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef* huart, uint16_t Size) {
-  if (huart->Instance == USART1) {
-    HandleUartRxCallback(&uart1TaskData, huart, Size);
-  } else if (huart->Instance == UART8) {
-    HandleUartRxCallback(&uart8TaskData, huart, Size);
-  }
+void HAL_UARTEx_RxEventCallback (UART_HandleTypeDef* huart, uint16_t Size) {
+    if (huart->Instance == USART1) {
+        HandleUartRxCallback (&uart1TaskData, huart, Size);
+    } else if (huart->Instance == UART8) {
+        HandleUartRxCallback (&uart8TaskData, huart, Size);
+    }
 }
 
 void HAL_UART_TxCpltCallback (UART_HandleTypeDef* huart) {
@@ -161,9 +161,7 @@ void UartRxTask (void* argument) {
         } else {
             if (frameTimeout == pdFALSE) {
                 proceed = pdTRUE;
-#if UART_TASK_LOGS
                 printf ("Uart%d: RX bytes received: %ld\n", uartTaskData->uartNumber, bytesRec);
-#endif
             } else {
                 if (uartTaskData->huart->RxState == HAL_UART_STATE_READY) {
                     HAL_UARTEx_ReceiveToIdle_IT (uartTaskData->huart, uartTaskData->uartRxBuffer, uartTaskData->uartRxBufferLen);
@@ -218,9 +216,7 @@ void UartRxTask (void* argument) {
                 osMutexRelease (uartTaskData->rxDataBufferMutex);
                 crcPass = frameCrc == crc;
                 if (crcPass) {
-#if UART_TASK_LOGS
                     printf ("Uart%d: Frame CRC PASS\n", uartTaskData->uartNumber);
-#endif
                     receverState = srExecuteCmd;
                 } else {
                     receverState = srFail;
@@ -234,10 +230,9 @@ void UartRxTask (void* argument) {
                 }
 
                 if (uartTaskData->processRxDataMsgBuffer != NULL) {
-                    if(xMessageBufferSend (uartTaskData->processRxDataMsgBuffer, &spFrameData, sizeof (SerialProtocolFrameHeader) + spFrameData.frameHeader.frameDataLength, pdMS_TO_TICKS (200)) == pdFALSE)
-                    {
-                    	receverState = srFail;
-                    	break;
+                    if (xMessageBufferSend (uartTaskData->processRxDataMsgBuffer, &spFrameData, sizeof (SerialProtocolFrameHeader) + spFrameData.frameHeader.frameDataLength, pdMS_TO_TICKS (200)) == pdFALSE) {
+                        receverState = srFail;
+                        break;
                     }
                 }
                 if (uartTaskData->processDataCb != NULL) {
@@ -249,25 +244,17 @@ void UartRxTask (void* argument) {
                 dataToSend = 0;
                 if ((frameTimeout == pdTRUE) && (frameBytesCount > 2)) {
                     dataToSend = PrepareRespFrame (uartTaskData->uartTxBuffer, spFrameData.frameHeader.frameId, spFrameData.frameHeader.frameCommand, spTimeout, NULL, 0);
-#if UART_TASK_LOGS
                     printf ("Uart%d: RX data receiver timeout!\n", uartTaskData->uartNumber);
-#endif
                 } else if (!crcPass) {
                     dataToSend = PrepareRespFrame (uartTaskData->uartTxBuffer, spFrameData.frameHeader.frameId, spFrameData.frameHeader.frameCommand, spCrcFail, NULL, 0);
-#if UART_TASK_LOGS
                     printf ("Uart%d: Frame CRC FAIL\n", uartTaskData->uartNumber);
-#endif
-                }
-                else
-                {
-                	dataToSend = PrepareRespFrame (uartTaskData->uartTxBuffer, spFrameData.frameHeader.frameId, spFrameData.frameHeader.frameCommand, spInternalError, NULL, 0);
+                } else {
+                    dataToSend = PrepareRespFrame (uartTaskData->uartTxBuffer, spFrameData.frameHeader.frameId, spFrameData.frameHeader.frameCommand, spInternalError, NULL, 0);
                 }
                 if (dataToSend > 0) {
                     HAL_UART_Transmit_IT (uartTaskData->huart, uartTaskData->uartTxBuffer, dataToSend);
                 }
-#if UART_TASK_LOGS
                 printf ("Uart%d: TX bytes sent: %d\n", dataToSend, uartTaskData->uartNumber);
-#endif
                 receverState = srFinish;
                 break;
             case srFinish:
@@ -286,9 +273,8 @@ void UartRxTask (void* argument) {
     }
 }
 
-void Uart8ReceivedDataProcessCallback (void* arg, SerialProtocolFrameData* spFrameData)
-{
-	Uart1ReceivedDataProcessCallback(arg, spFrameData);
+void Uart8ReceivedDataProcessCallback (void* arg, SerialProtocolFrameData* spFrameData) {
+    Uart1ReceivedDataProcessCallback (arg, spFrameData);
 }
 
 void Uart1ReceivedDataProcessCallback (void* arg, SerialProtocolFrameData* spFrameData) {
@@ -326,7 +312,8 @@ void Uart1ReceivedDataProcessCallback (void* arg, SerialProtocolFrameData* spFra
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.pvTemperature[0], sizeof (float));
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.pvTemperature[1], sizeof (float));
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.fanVoltage, sizeof (float));
-            WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.pvEncoder, sizeof (float));
+            WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.pvEncoderX, sizeof (float));
+            WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.pvEncoderY, sizeof (float));
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.motorXStatus, sizeof (uint8_t));
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.motorYStatus, sizeof (uint8_t));
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.motorXAveCurrent, sizeof (float));
@@ -339,6 +326,8 @@ void Uart1ReceivedDataProcessCallback (void* arg, SerialProtocolFrameData* spFra
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.limitYSwitchUp, sizeof (uint8_t));
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.limitYSwitchDown, sizeof (uint8_t));
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.limitYSwitchCenter, sizeof (uint8_t));
+            uint8_t comparatorOutput        = HAL_COMP_GetOutputLevel (&hcomp1) == COMP_OUTPUT_LEVEL_HIGH ? 1 : 0;
+            sensorsInfo.powerSupplyFailMask = ~((comparatorOutput << 1) | HAL_GPIO_ReadPin (GPIOD, GPIO_PIN_3)) & 0x01;
             WriteDataToBuffer (outputDataBuffer, &outputDataBufferPos, &sensorsInfo.powerSupplyFailMask, sizeof (uint8_t));
             osMutexRelease (sensorsInfoMutex);
             respStatus = spOK;
@@ -363,6 +352,7 @@ void Uart1ReceivedDataProcessCallback (void* arg, SerialProtocolFrameData* spFra
             osTimerStop (fanTimerHandle);
             HAL_TIM_PWM_Stop (&htim1, TIM_CHANNEL_2);
         } else if (fanTimerPeriod == -1) {
+            osTimerStop (fanTimerHandle);
             HAL_TIM_PWM_Start (&htim1, TIM_CHANNEL_2);
         }
         respStatus = spOK;
@@ -413,8 +403,10 @@ void Uart1ReceivedDataProcessCallback (void* arg, SerialProtocolFrameData* spFra
             osTimerStart (debugLedTimerHandle, dbgLedTimerPeriod * 1000);
             DbgLEDOn (DBG_LED1);
         } else if (dbgLedTimerPeriod == 0) {
+            osTimerStop (debugLedTimerHandle);
             DbgLEDOff (DBG_LED1);
         } else if (dbgLedTimerPeriod == -1) {
+            osTimerStop (debugLedTimerHandle);
             DbgLEDOn (DBG_LED1);
         }
         respStatus = spOK;
@@ -447,21 +439,85 @@ void Uart1ReceivedDataProcessCallback (void* arg, SerialProtocolFrameData* spFra
             respStatus = spInternalError;
         }
         break;
+    case spSetEncoderXValue:
+        float enocoderXValue = 0;
+        ReadWordFromBufer (spFrameData->dataBuffer, &inputDataBufferPos, (uint32_t*)&enocoderXValue);
+        if (osMutexAcquire (sensorsInfoMutex, osWaitForever) == osOK) {
+            sensorsInfo.pvEncoderX = enocoderXValue;
+            osMutexRelease (sensorsInfoMutex);
+            respStatus = spOK;
+        } else {
+            respStatus = spInternalError;
+        }
+        break;
+    case spSetEncoderYValue:
+        float enocoderYValue = 0;
+        ReadWordFromBufer (spFrameData->dataBuffer, &inputDataBufferPos, (uint32_t*)&enocoderYValue);
+        if (osMutexAcquire (sensorsInfoMutex, osWaitForever) == osOK) {
+            sensorsInfo.pvEncoderY = enocoderYValue;
+            osMutexRelease (sensorsInfoMutex);
+            respStatus = spOK;
+        } else {
+            respStatus = spInternalError;
+        }
+        break;
+    case spSetVoltageMeasGains:
+        if (osMutexAcquire (resMeasurementsMutex, osWaitForever) == osOK) {
+            for (uint8_t i = 0; i < 3; i++) {
+                ReadWordFromBufer (spFrameData->dataBuffer, &inputDataBufferPos, (uint32_t*)&U_MeasCorrectionData[i].gain);
+            }
+            osMutexRelease (resMeasurementsMutex);
+            respStatus = spOK;
+        } else {
+            respStatus = spInternalError;
+        }
+        break;
+    case spSetVoltageMeasOffsets:
+        if (osMutexAcquire (resMeasurementsMutex, osWaitForever) == osOK) {
+            for (uint8_t i = 0; i < 3; i++) {
+                ReadWordFromBufer (spFrameData->dataBuffer, &inputDataBufferPos, (uint32_t*)&U_MeasCorrectionData[i].offset);
+            }
+            osMutexRelease (resMeasurementsMutex);
+            respStatus = spOK;
+        } else {
+            respStatus = spInternalError;
+        }
+        break;
+    case spSetCurrentMeasGains:
+        if (osMutexAcquire (resMeasurementsMutex, osWaitForever) == osOK) {
+            for (uint8_t i = 0; i < 3; i++) {
+                ReadWordFromBufer (spFrameData->dataBuffer, &inputDataBufferPos, (uint32_t*)&I_MeasCorrectionData[i].gain);
+            }
+            osMutexRelease (resMeasurementsMutex);
+            respStatus = spOK;
+        } else {
+            respStatus = spInternalError;
+        }
+        break;
+    case spSetCurrentMeasOffsets:
+        if (osMutexAcquire (resMeasurementsMutex, osWaitForever) == osOK) {
+            for (uint8_t i = 0; i < 3; i++) {
+                ReadWordFromBufer (spFrameData->dataBuffer, &inputDataBufferPos, (uint32_t*)&I_MeasCorrectionData[i].offset);
+            }
+            osMutexRelease (resMeasurementsMutex);
+            respStatus = spOK;
+        } else {
+            respStatus = spInternalError;
+        }
+        break;
     default: respStatus = spUnknownCommand; break;
     }
     dataToSend = PrepareRespFrame (uartTaskData->uartTxBuffer, spFrameData->frameHeader.frameId, spFrameData->frameHeader.frameCommand, respStatus, outputDataBuffer, outputDataBufferPos);
     if (dataToSend > 0) {
         HAL_UART_Transmit_IT (uartTaskData->huart, uartTaskData->uartTxBuffer, dataToSend);
     }
-#if UART_TASK_LOGS
     printf ("Uart%d: TX bytes sent: %d\n", uartTaskData->uartNumber, dataToSend);
-#endif
 }
 
 
 void UartTxTask (void* argument) {
     while (pdTRUE) {
 
-            osDelay (pdMS_TO_TICKS (1000));
+        osDelay (pdMS_TO_TICKS (1000));
     }
 }

File diff suppressed because it is too large
+ 5 - 2
OZE_Sensor/Debug/Drivers/STM32H7xx_HAL_Driver/Src/subdir.mk


File diff suppressed because it is too large
+ 42698 - 39595
OZE_Sensor/Debug/OZE_Sensor.list


File diff suppressed because it is too large
+ 2096 - 1775
OZE_Sensor/Debug/OZE_Sensor.map


+ 1 - 0
OZE_Sensor/Debug/objects.list

@@ -16,6 +16,7 @@
 "./Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal.o"
 "./Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_adc.o"
 "./Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_adc_ex.o"
+"./Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_comp.o"
 "./Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_cortex.o"
 "./Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_crc.o"
 "./Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_crc_ex.o"

+ 953 - 0
OZE_Sensor/Drivers/STM32H7xx_HAL_Driver/Inc/stm32h7xx_hal_comp.h

@@ -0,0 +1,953 @@
+/**
+  ******************************************************************************
+  * @file    stm32h7xx_hal_comp.h
+  * @author  MCD Application Team
+  * @brief   Header file of COMP HAL module.
+  ******************************************************************************
+  * @attention
+  *
+  * Copyright (c) 2017 STMicroelectronics.
+  * All rights reserved.
+  *
+  * This software is licensed under terms that can be found in the LICENSE file
+  * in the root directory of this software component.
+  * If no LICENSE file comes with this software, it is provided AS-IS.
+  *
+  ******************************************************************************
+  */
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef STM32H7xx_HAL_COMP_H
+#define STM32H7xx_HAL_COMP_H
+
+#ifdef __cplusplus
+ extern "C" {
+#endif
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32h7xx_hal_def.h"
+
+/** @addtogroup STM32H7xx_HAL_Driver
+  * @{
+  */
+
+/** @addtogroup COMP
+  * @{
+  */
+
+/* Exported types ------------------------------------------------------------*/ 
+/** @defgroup COMP_Exported_Types COMP Exported Types
+  * @{
+  */
+
+/** 
+  * @brief  COMP Init structure definition  
+  */
+typedef struct
+{
+
+  uint32_t WindowMode;         /*!< Set window mode of a pair of comparators instances
+                                    (2 consecutive instances odd and even COMP<x> and COMP<x+1>).
+                                    Note: HAL COMP driver allows to set window mode from any COMP instance of the pair of COMP instances composing window mode.
+                                    This parameter can be a value of @ref COMP_WindowMode */
+
+  uint32_t Mode;               /*!< Set comparator operating mode to adjust power and speed.
+                                    Note: For the characteritics of comparator power modes
+                                          (propagation delay and power consumption), refer to device datasheet.
+                                    This parameter can be a value of @ref COMP_PowerMode */
+
+  uint32_t NonInvertingInput;  /*!< Set comparator input plus (non-inverting input).
+                                    This parameter can be a value of @ref COMP_InputPlus */
+
+  uint32_t InvertingInput;     /*!< Set comparator input minus (inverting input).
+                                    This parameter can be a value of @ref COMP_InputMinus */
+
+  uint32_t Hysteresis;         /*!< Set comparator hysteresis mode of the input minus.
+                                    This parameter can be a value of @ref COMP_Hysteresis */
+
+  uint32_t OutputPol;          /*!< Set comparator output polarity.
+                                    This parameter can be a value of @ref COMP_OutputPolarity */
+
+  uint32_t BlankingSrce;       /*!< Set comparator blanking source.
+                                    This parameter can be a value of @ref COMP_BlankingSrce */
+
+  uint32_t TriggerMode;        /*!< Set the comparator output triggering External Interrupt Line (EXTI).
+                                    This parameter can be a value of @ref COMP_EXTI_TriggerMode */
+
+}COMP_InitTypeDef;
+
+/**
+  * @brief  HAL COMP state machine: HAL COMP states definition
+  */
+#define COMP_STATE_BITFIELD_LOCK  ((uint32_t)0x10)
+typedef enum
+{
+  HAL_COMP_STATE_RESET             = 0x00,                                              /*!< COMP not yet initialized                             */
+  HAL_COMP_STATE_RESET_LOCKED      = (HAL_COMP_STATE_RESET | COMP_STATE_BITFIELD_LOCK), /*!< COMP not yet initialized and configuration is locked */
+  HAL_COMP_STATE_READY             = 0x01,                                              /*!< COMP initialized and ready for use                   */
+  HAL_COMP_STATE_READY_LOCKED      = (HAL_COMP_STATE_READY | COMP_STATE_BITFIELD_LOCK), /*!< COMP initialized but configuration is locked         */
+  HAL_COMP_STATE_BUSY              = 0x02,                                              /*!< COMP is running                                      */
+  HAL_COMP_STATE_BUSY_LOCKED       = (HAL_COMP_STATE_BUSY | COMP_STATE_BITFIELD_LOCK)   /*!< COMP is running and configuration is locked          */
+}HAL_COMP_StateTypeDef;
+
+/** 
+  * @brief  COMP Handle Structure definition
+  */
+#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
+typedef struct __COMP_HandleTypeDef
+#else
+typedef struct
+#endif /* USE_HAL_COMP_REGISTER_CALLBACKS */
+{
+  COMP_TypeDef       *Instance;       /*!< Register base address    */
+  COMP_InitTypeDef   Init;            /*!< COMP required parameters */
+  HAL_LockTypeDef    Lock;            /*!< Locking object           */
+  __IO HAL_COMP_StateTypeDef  State;  /*!< COMP communication state */
+  __IO uint32_t      ErrorCode;       /*!< COMP error code */
+#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
+  void (* TriggerCallback)(struct __COMP_HandleTypeDef *hcomp);   /*!< COMP trigger callback */
+  void (* MspInitCallback)(struct __COMP_HandleTypeDef *hcomp);   /*!< COMP Msp Init callback */
+  void (* MspDeInitCallback)(struct __COMP_HandleTypeDef *hcomp); /*!< COMP Msp DeInit callback */
+#endif /* USE_HAL_COMP_REGISTER_CALLBACKS */
+
+} COMP_HandleTypeDef;
+
+#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
+/**
+  * @brief  HAL COMP Callback ID enumeration definition
+  */
+typedef enum
+{
+  HAL_COMP_TRIGGER_CB_ID                = 0x00U,  /*!< COMP trigger callback ID */
+  HAL_COMP_MSPINIT_CB_ID                = 0x01U,  /*!< COMP Msp Init callback ID */
+  HAL_COMP_MSPDEINIT_CB_ID              = 0x02U   /*!< COMP Msp DeInit callback ID */
+} HAL_COMP_CallbackIDTypeDef;
+
+/**
+  * @brief  HAL COMP Callback pointer definition
+  */
+typedef  void (*pCOMP_CallbackTypeDef)(COMP_HandleTypeDef *hcomp); /*!< pointer to a COMP callback function */
+
+#endif /* USE_HAL_COMP_REGISTER_CALLBACKS */
+/**
+  * @}
+  */
+
+/* Exported constants --------------------------------------------------------*/
+/** @defgroup COMP_Exported_Constants COMP Exported Constants
+  * @{
+  */
+  
+/** @defgroup COMP_Error_Code COMP Error Code
+  * @{
+  */
+#define HAL_COMP_ERROR_NONE             (0x00U)   /*!< No error */
+#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
+#define HAL_COMP_ERROR_INVALID_CALLBACK (0x01U)   /*!< Invalid Callback error */
+#endif /* USE_HAL_COMP_REGISTER_CALLBACKS */
+/**
+  * @}
+  */
+  
+/** @defgroup COMP_WindowMode COMP Window Mode
+  * @{
+  */
+#define COMP_WINDOWMODE_DISABLE                 ((uint32_t)0x00000000)   /*!< Window mode disable: Comparators instances pair COMP1 and COMP2 are independent */
+#define COMP_WINDOWMODE_COMP1_INPUT_PLUS_COMMON (COMP_CFGRx_WINMODE)     /*!< Window mode enable: Comparators instances pair COMP1 and COMP2 have their input plus connected together. The common input is COMP1 input plus (COMP2 input plus is no more accessible). */
+
+/**
+  * @}
+  */
+
+/** @defgroup COMP_PowerMode COMP power mode
+  * @{
+  */
+/* Note: For the characteritics of comparator power modes                     */
+/*       (propagation delay and power consumption),                           */
+/*       refer to device datasheet.                                           */
+#define COMP_POWERMODE_HIGHSPEED       ((uint32_t)0x00000000)   /*!< High Speed */
+#define COMP_POWERMODE_MEDIUMSPEED     (COMP_CFGRx_PWRMODE_0)   /*!< Medium Speed */
+#define COMP_POWERMODE_ULTRALOWPOWER   (COMP_CFGRx_PWRMODE)     /*!< Ultra-low power mode */
+/**
+  * @}
+  */
+
+/** @defgroup COMP_InputPlus COMP input plus (non-inverting input)
+  * @{
+  */
+#define COMP_INPUT_PLUS_IO1            ((uint32_t)0x00000000) /*!< Comparator input plus connected to IO1 (pin PB0 for COMP1, pin PE9 for COMP2) */
+#define COMP_INPUT_PLUS_IO2            (COMP_CFGRx_INPSEL)    /*!< Comparator input plus connected to IO2 (pin PB2 for COMP1, pin PE11 for COMP2) */
+#if defined (COMP_CFGRx_INP2SEL)
+#define COMP_INPUT_PLUS_DAC2_CH1       (COMP_CFGRx_INP2SEL)   /*!< Comparator input plus 2 connected to (DAC2_CH1 for COMP1) */
+#endif
+/**
+  * @}
+  */
+
+/** @defgroup COMP_InputMinus COMP input minus (inverting input)
+  * @{
+  */
+#define COMP_INPUT_MINUS_1_4VREFINT     (                                                                                        COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN)    /*!< Comparator input minus connected to 1/4 VrefInt */
+#define COMP_INPUT_MINUS_1_2VREFINT     (                                                                  COMP_CFGRx_INMSEL_0 | COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN)    /*!< Comparator input minus connected to 1/2 VrefInt */
+#define COMP_INPUT_MINUS_3_4VREFINT     (                                            COMP_CFGRx_INMSEL_1                       | COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN)    /*!< Comparator input minus connected to 3/4 VrefInt */
+#define COMP_INPUT_MINUS_VREFINT        (                                            COMP_CFGRx_INMSEL_1 | COMP_CFGRx_INMSEL_0 | COMP_CFGRx_SCALEN                   )    /*!< Comparator input minus connected to VrefInt */
+#define COMP_INPUT_MINUS_DAC1_CH1       (                      COMP_CFGRx_INMSEL_2                                                                                   )    /*!< Comparator input minus connected to DAC1 channel 1 (DAC_OUT1) */
+#define COMP_INPUT_MINUS_DAC1_CH2       (                      COMP_CFGRx_INMSEL_2                       | COMP_CFGRx_INMSEL_0                                       )    /*!< Comparator input minus connected to DAC1 channel 2 (DAC_OUT2) */
+#define COMP_INPUT_MINUS_IO1            (                      COMP_CFGRx_INMSEL_2 | COMP_CFGRx_INMSEL_1                                                             )    /*!< Comparator input minus connected to IO1 (pin PB1 for COMP1, pin PE10 for COMP2) */
+#define COMP_INPUT_MINUS_IO2            (                      COMP_CFGRx_INMSEL_2 | COMP_CFGRx_INMSEL_1 | COMP_CFGRx_INMSEL_0                                       )    /*!< Comparator input minus connected to IO2 (pin PC4 for COMP1, pin PE7 for COMP2) */
+#if defined (COMP_CFGRx_INMSEL_3)
+#define COMP_INPUT_MINUS_TPSENS_DAC2CH1 (COMP_CFGRx_INMSEL_3                                                                                                         )    /*!< Comparator input minus connected to (temp sensor which is exist in ADC for COMP1, DAC2_CH1 for COMP2) */
+#define COMP_INPUT_MINUS_VBAT_VDDAP     (COMP_CFGRx_INMSEL_3                                             | COMP_CFGRx_INMSEL_0                                       )    /*!< Comparator input minus connected to (VBAT/4 for COMP1, VDDAP for COMP2) */
+#endif
+/**
+  * @}
+  */
+
+/** @defgroup COMP_Hysteresis COMP hysteresis
+  * @{
+  */
+#define COMP_HYSTERESIS_NONE           ((uint32_t)0x00000000)   /*!< No hysteresis */
+#define COMP_HYSTERESIS_LOW            (COMP_CFGRx_HYST_0)      /*!< Hysteresis level low */
+#define COMP_HYSTERESIS_MEDIUM         (COMP_CFGRx_HYST_1)      /*!< Hysteresis level medium */
+#define COMP_HYSTERESIS_HIGH           (COMP_CFGRx_HYST)        /*!< Hysteresis level high */
+/**
+  * @}
+  */
+
+/** @defgroup COMP_OutputPolarity COMP Output Polarity
+  * @{
+  */
+#define COMP_OUTPUTPOL_NONINVERTED     ((uint32_t)0x00000000)  /*!< COMP output level is not inverted (comparator output is high when the input plus is at a higher voltage than the input minus) */
+#define COMP_OUTPUTPOL_INVERTED        (COMP_CFGRx_POLARITY)   /*!< COMP output level is inverted     (comparator output is low  when the input plus is at a higher voltage than the input minus) */
+/**
+  * @}
+  */
+
+
+/** @defgroup COMP_BlankingSrce  COMP Blanking Source
+  * @{
+  */
+/* Any blanking source can be selected for all comparators */
+#define COMP_BLANKINGSRC_NONE             ((uint32_t)0x00000000)                           /*!< No blanking source */
+#define COMP_BLANKINGSRC_TIM1_OC5         (COMP_CFGRx_BLANKING_0)                          /*!< TIM1 OC5 selected as blanking source for comparator */
+#define COMP_BLANKINGSRC_TIM2_OC3         (COMP_CFGRx_BLANKING_1)                          /*!< TIM2 OC3 selected as blanking source for comparator */
+#define COMP_BLANKINGSRC_TIM3_OC3         (COMP_CFGRx_BLANKING_0 |COMP_CFGRx_BLANKING_1)   /*!< TIM3 OC3 selected as blanking source for compartor */
+#define COMP_BLANKINGSRC_TIM3_OC4         (COMP_CFGRx_BLANKING_2)                          /*!< TIM3 OC4 selected as blanking source for comparator */
+#define COMP_BLANKINGSRC_TIM8_OC5         (COMP_CFGRx_BLANKING_2|COMP_CFGRx_BLANKING_0)    /*!< TIM8 OC5 selected as blanking source for comparator */
+#define COMP_BLANKINGSRC_TIM15_OC1        (COMP_CFGRx_BLANKING_2|COMP_CFGRx_BLANKING_1)    /*!< TIM15 OC1 selected as blanking source for comparator */
+/**
+  * @}
+  */
+
+
+
+
+/** @defgroup COMP_OutputLevel COMP Output Level
+  * @{
+  */ 
+
+/* Note: Comparator output level values are fixed to "0" and "1",             */
+/* corresponding COMP register bit is managed by HAL function to match        */
+/* with these values (independently of bit position in register).             */
+
+/* When output polarity is not inverted, comparator output is low when
+   the input plus is at a lower voltage than the input minus */
+#define COMP_OUTPUT_LEVEL_LOW              ((uint32_t)0x00000000)
+/* When output polarity is not inverted, comparator output is high when
+   the input plus is at a higher voltage than the input minus */
+#define COMP_OUTPUT_LEVEL_HIGH             ((uint32_t)0x00000001)
+
+/**
+  * @}
+  */
+
+/** @defgroup COMP_EXTI_TriggerMode COMP output to EXTI
+  * @{
+  */
+#define COMP_TRIGGERMODE_NONE                 ((uint32_t)0x00000000)                                    /*!< Comparator output triggering no External Interrupt Line */
+#define COMP_TRIGGERMODE_IT_RISING            (COMP_EXTI_IT | COMP_EXTI_RISING)                         /*!< Comparator output triggering External Interrupt Line event with interruption, on rising edge */
+#define COMP_TRIGGERMODE_IT_FALLING           (COMP_EXTI_IT | COMP_EXTI_FALLING)                        /*!< Comparator output triggering External Interrupt Line event with interruption, on falling edge */
+#define COMP_TRIGGERMODE_IT_RISING_FALLING    (COMP_EXTI_IT | COMP_EXTI_RISING | COMP_EXTI_FALLING)     /*!< Comparator output triggering External Interrupt Line event with interruption, on both rising and falling edges */
+#define COMP_TRIGGERMODE_EVENT_RISING         (COMP_EXTI_EVENT | COMP_EXTI_RISING)                      /*!< Comparator output triggering External Interrupt Line event only (without interruption), on rising edge */
+#define COMP_TRIGGERMODE_EVENT_FALLING        (COMP_EXTI_EVENT | COMP_EXTI_FALLING)                     /*!< Comparator output triggering External Interrupt Line event only (without interruption), on falling edge */
+#define COMP_TRIGGERMODE_EVENT_RISING_FALLING (COMP_EXTI_EVENT | COMP_EXTI_RISING | COMP_EXTI_FALLING)  /*!< Comparator output triggering External Interrupt Line event only (without interruption), on both rising and falling edges */
+
+/**
+  * @}
+  */
+
+/** @defgroup COMP_Flag COMP Flag
+  * @{
+  */
+#define COMP_FLAG_C1I           COMP_SR_C1IF           /*!< Comparator 1 Interrupt Flag */
+#define COMP_FLAG_C2I           COMP_SR_C2IF           /*!< Comparator 2 Interrupt Flag */
+#define COMP_FLAG_LOCK          COMP_CFGRx_LOCK        /*!< Lock flag */
+/**
+  * @}
+  */
+/** @defgroup COMP_IT_CLEAR_Flags  COMP Interruption Clear Flags
+  * @{
+  */
+#define COMP_CLEAR_C1IF          COMP_ICFR_C1IF     /*!< Clear Comparator 1 Interrupt Flag */
+#define COMP_CLEAR_C2IF          COMP_ICFR_C2IF     /*!< Clear Comparator 2 Interrupt Flag */
+/**
+  * @}
+  */
+/** @defgroup COMP_Interrupts_Definitions COMP Interrupts Definitions
+  * @{
+  */
+#define COMP_IT_EN               COMP_CFGRx_ITEN 
+
+/**
+  * @}
+  */
+  
+
+/**
+  * @}
+  */
+ 
+/* Exported macros -----------------------------------------------------------*/
+/** @defgroup COMP_Exported_Macros COMP Exported Macros
+  * @{
+  */
+/** @defgroup COMP_Handle_Management  COMP Handle Management
+ * @{
+  */
+
+/** @brief  Reset COMP handle state.
+  * @param  __HANDLE__  COMP handle
+  * @retval None
+  */
+#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
+#define __HAL_COMP_RESET_HANDLE_STATE(__HANDLE__) do{                                                 \
+                                                     (__HANDLE__)->State = HAL_COMP_STATE_RESET;      \
+                                                     (__HANDLE__)->MspInitCallback = NULL;            \
+                                                     (__HANDLE__)->MspDeInitCallback = NULL;          \
+                                                    } while(0)
+#else
+#define __HAL_COMP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_COMP_STATE_RESET)
+#endif
+
+/**
+  * @brief Clear COMP error code (set it to no error code "HAL_COMP_ERROR_NONE").
+  * @param __HANDLE__ COMP handle
+  * @retval None
+  */
+#define COMP_CLEAR_ERRORCODE(__HANDLE__) ((__HANDLE__)->ErrorCode = HAL_COMP_ERROR_NONE) 
+
+/**
+  * @brief  Enable the specified comparator.
+  * @param  __HANDLE__ COMP handle
+  * @retval None
+  */
+#define __HAL_COMP_ENABLE(__HANDLE__)                 SET_BIT((__HANDLE__)->Instance->CFGR, COMP_CFGRx_EN)
+
+/**
+  * @brief  Disable the specified comparator.
+  * @param  __HANDLE__ COMP handle
+  * @retval None
+  */
+#define __HAL_COMP_DISABLE(__HANDLE__)                CLEAR_BIT((__HANDLE__)->Instance->CFGR, COMP_CFGRx_EN)
+
+/**
+  * @brief  Lock the specified comparator configuration.
+  * @note   Using this macro induce HAL COMP handle state machine being no
+  *         more in line with COMP instance state.
+  *         To keep HAL COMP handle state machine updated, it is recommended
+  *         to use function "HAL_COMP_Lock')".
+  * @param  __HANDLE__ COMP handle
+  * @retval None
+  */
+#define __HAL_COMP_LOCK(__HANDLE__)                   SET_BIT((__HANDLE__)->Instance->CFGR, COMP_CFGRx_LOCK)
+
+/**
+  * @brief  Check whether the specified comparator is locked.
+  * @param  __HANDLE__  COMP handle
+  * @retval Value 0 if COMP instance is not locked, value 1 if COMP instance is locked
+  */
+#define __HAL_COMP_IS_LOCKED(__HANDLE__)           (READ_BIT((__HANDLE__)->Instance->CFGR, COMP_CFGRx_LOCK) == COMP_CFGRx_LOCK)
+
+/**
+  * @}
+  */
+  
+/** @defgroup COMP_Exti_Management  COMP external interrupt line management
+  * @{
+  */
+
+/**
+  * @brief  Enable the COMP1 EXTI line rising edge trigger. 
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE()    SET_BIT(EXTI->RTSR1, COMP_EXTI_LINE_COMP1)
+
+
+/**
+  * @brief  Disable the COMP1 EXTI line rising edge trigger. 
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP1_EXTI_DISABLE_RISING_EDGE()    CLEAR_BIT(EXTI->RTSR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Enable the COMP1 EXTI line falling edge trigger. 
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE()    SET_BIT(EXTI->FTSR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Disable the COMP1 EXTI line falling edge trigger.
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP1_EXTI_DISABLE_FALLING_EDGE()    CLEAR_BIT(EXTI->FTSR1, COMP_EXTI_LINE_COMP1)
+
+
+/**
+  * @brief  Enable the COMP1 EXTI line rising & falling edge trigger. 
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP1_EXTI_ENABLE_RISING_FALLING_EDGE()   do {                                           \
+                                                               __HAL_COMP_COMP1_EXTI_ENABLE_RISING_EDGE();  \
+                                                               __HAL_COMP_COMP1_EXTI_ENABLE_FALLING_EDGE(); \
+                                                             } while(0)
+
+
+/**
+  * @brief  Disable the COMP1 EXTI line rising & falling edge trigger. 
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP1_EXTI_DISABLE_RISING_FALLING_EDGE()  do {                                            \
+                                                               __HAL_COMP_COMP1_EXTI_DISABLE_RISING_EDGE();  \
+                                                               __HAL_COMP_COMP1_EXTI_DISABLE_FALLING_EDGE(); \
+                                                             } while(0)
+
+
+/**
+  * @brief  Enable the COMP1 EXTI line in interrupt mode.
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP1_EXTI_ENABLE_IT()             SET_BIT(EXTI_D1->IMR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Disable the COMP1 EXTI line in interrupt mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTI_DISABLE_IT()            CLEAR_BIT(EXTI_D1->IMR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Enable the COMP1 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTI_ENABLE_EVENT()           SET_BIT(EXTI_D1->EMR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Disable the COMP1 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTI_DISABLE_EVENT()          CLEAR_BIT(EXTI_D1->EMR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Check whether the COMP1 EXTI line flag is set or not.
+  * @retval RESET or SET
+  */
+#define __HAL_COMP_COMP1_EXTI_GET_FLAG()              READ_BIT(EXTI_D1->PR1, COMP_EXTI_LINE_COMP1)
+/**
+  * @brief  Clear the COMP1 EXTI flag.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTI_CLEAR_FLAG()            WRITE_REG(EXTI_D1->PR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Generate a software interrupt on the COMP1 EXTI line.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTI_GENERATE_SWIT()         SET_BIT(EXTI->SWIER1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Enable the COMP1 D3 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTID3_ENABLE_EVENT()        SET_BIT(EXTI->D3PMR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Disable the COMP1 D3 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTID3_DISABLE_EVENT()        CLEAR_BIT(EXTI->D3PMR1, COMP_EXTI_LINE_COMP1)
+
+#if defined(DUAL_CORE)
+/**
+  * @brief  Enable the COMP1 D2 EXTI line in interrupt mode.
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP1_EXTID2_ENABLE_IT()           SET_BIT(EXTI_D2->IMR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Disable the COMP1 D2 EXTI line in interrupt mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTID2_DISABLE_IT()          CLEAR_BIT(EXTI_D2->IMR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Enable the COMP1 D2 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTID2_ENABLE_EVENT()         SET_BIT(EXTI_D2->EMR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Disable the COMP1 D2 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTID2_DISABLE_EVENT()        CLEAR_BIT(EXTI_D2->EMR1, COMP_EXTI_LINE_COMP1)
+
+/**
+  * @brief  Check whether the COMP1 D2 EXTI line flag is set or not.
+  * @retval RESET or SET
+  */
+#define __HAL_COMP_COMP1_EXTID2_GET_FLAG()              READ_BIT(EXTI_D2->PR1, COMP_EXTI_LINE_COMP1)     
+
+/**
+  * @brief  Clear the COMP1 D2 EXTI flag.
+  * @retval None
+  */
+#define __HAL_COMP_COMP1_EXTID2_CLEAR_FLAG()            WRITE_REG(EXTI_D2->PR1, COMP_EXTI_LINE_COMP1)
+
+#endif
+
+/**
+  * @brief  Enable the COMP2 EXTI line rising edge trigger.
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE()    SET_BIT(EXTI->RTSR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Disable the COMP2 EXTI line rising edge trigger.
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP2_EXTI_DISABLE_RISING_EDGE()   CLEAR_BIT(EXTI->RTSR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Enable the COMP2 EXTI line falling edge trigger.
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP2_EXTI_ENABLE_FALLING_EDGE()   SET_BIT(EXTI->FTSR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Disable the COMP2 EXTI line falling edge trigger. 
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP2_EXTI_DISABLE_FALLING_EDGE()  CLEAR_BIT(EXTI->FTSR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Enable the COMP2 EXTI line rising & falling edge trigger.
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP2_EXTI_ENABLE_RISING_FALLING_EDGE()   do {                                           \
+                                                               __HAL_COMP_COMP2_EXTI_ENABLE_RISING_EDGE();  \
+                                                               __HAL_COMP_COMP2_EXTI_ENABLE_FALLING_EDGE(); \
+                                                             } while(0)
+
+/**
+  * @brief  Disable the COMP2 EXTI line rising & falling edge trigger.
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP2_EXTI_DISABLE_RISING_FALLING_EDGE()   do {                                           \
+                                                               __HAL_COMP_COMP2_EXTI_DISABLE_RISING_EDGE();  \
+                                                               __HAL_COMP_COMP2_EXTI_DISABLE_FALLING_EDGE(); \
+                                                             } while(0)
+/**
+  * @brief  Enable the COMP2 EXTI line.
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP2_EXTI_ENABLE_IT()             SET_BIT(EXTI_D1->IMR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Disable the COMP2 EXTI line.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTI_DISABLE_IT()            CLEAR_BIT(EXTI_D1->IMR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Enable the COMP2 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTI_ENABLE_EVENT()          SET_BIT(EXTI_D1->EMR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Disable the COMP2 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTI_DISABLE_EVENT()          CLEAR_BIT(EXTI_D1->EMR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Check whether the COMP2 EXTI line flag is set or not.
+  * @retval RESET or SET
+  */
+#define __HAL_COMP_COMP2_EXTI_GET_FLAG()              READ_BIT(EXTI_D1->PR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Clear the the COMP2 EXTI flag.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTI_CLEAR_FLAG()            WRITE_REG(EXTI_D1->PR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Enable the COMP2 D3 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTID3_ENABLE_EVENT()        SET_BIT(EXTI->D3PMR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Disable the COMP2 D3 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTID3_DISABLE_EVENT()       CLEAR_BIT(EXTI->D3PMR1, COMP_EXTI_LINE_COMP2)
+
+/**
+  * @brief  Generate a software interrupt on the COMP2 EXTI line.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTI_GENERATE_SWIT()         SET_BIT(EXTI->SWIER1, COMP_EXTI_LINE_COMP2)
+
+#if defined(DUAL_CORE)
+/**
+  * @brief  Enable the COMP2 D2 EXTI line
+  * @retval None
+  */                                         
+#define __HAL_COMP_COMP2_EXTID2_ENABLE_IT()           SET_BIT(EXTI_D2->IMR1, COMP_EXTI_LINE_COMP2)
+
+
+/**
+  * @brief  Disable the COMP2 D2 EXTI line.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTID2_DISABLE_IT()          CLEAR_BIT(EXTI_D2->IMR1, COMP_EXTI_LINE_COMP2)
+
+
+
+/**
+  * @brief  Enable the COMP2 D2 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTID2_ENABLE_EVENT()         SET_BIT(EXTI_D2->EMR1, COMP_EXTI_LINE_COMP2)
+
+
+
+/**
+  * @brief  Disable the COMP2 D2 EXTI Line in event mode.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTID2_DISABLE_EVENT()        CLEAR_BIT(EXTI_D2->EMR1, COMP_EXTI_LINE_COMP2)
+
+
+/**
+  * @brief  Check whether the COMP2 D2 EXTI line flag is set or not.
+  * @retval RESET or SET
+  */
+#define __HAL_COMP_COMP2_EXTID2_GET_FLAG()            READ_BIT(EXTI_D2->PR1, COMP_EXTI_LINE_COMP2)     
+
+/**
+  * @brief  Clear the the COMP2 D2 EXTI flag.
+  * @retval None
+  */
+#define __HAL_COMP_COMP2_EXTID2_CLEAR_FLAG()          WRITE_REG(EXTI_D2->PR1, COMP_EXTI_LINE_COMP2)
+
+#endif
+/** @brief  Checks if the specified COMP interrupt source is enabled or disabled.
+  * @param  __HANDLE__: specifies the COMP Handle.
+  *         This parameter can be COMP1 where x: 1 or 2 to select the COMP peripheral.
+  * @param  __INTERRUPT__: specifies the COMP interrupt source to check.
+  *          This parameter can be one of the following values:
+  *            @arg COMP_IT_EN: Comparator interrupt enable
+  *   
+  * @retval The new state of __IT__ (TRUE or FALSE)
+  */
+#define __HAL_COMP_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CFGR & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET)
+
+/** @brief  Checks whether the specified COMP flag is set or not.
+  * @param  __FLAG__: specifies the flag to check.
+  *        This parameter can be one of the following values:
+  *            @arg COMP_FLAG_C1I:  Comparator 1 Interrupt Flag
+  *            @arg COMP_FLAG_C2I:  Comparator 2 Interrupt Flag
+  *            @retval The new state of __FLAG__ (TRUE or FALSE)
+  */
+#define __HAL_COMP_GET_FLAG(__FLAG__)     ((COMP12->SR & (__FLAG__)) == (__FLAG__))   
+
+/** @brief  Clears the specified COMP pending flag.
+  * @param  __FLAG__: specifies the flag to check.
+  *          This parameter can be any combination of the following values:
+  *            @arg COMP_CLEAR_C1IF  : Clear Comparator 1 Interrupt Flag
+  *            @arg COMP_CLEAR_C2IF  : Clear Comparator 2 Interrupt Flag
+  * @retval None
+  */
+#define __HAL_COMP_CLEAR_FLAG(__FLAG__)   (COMP12->ICFR = (__FLAG__))
+
+/** @brief  Clear the COMP C1I  flag.
+  * @retval None
+  */
+#define __HAL_COMP_CLEAR_C1IFLAG()   __HAL_COMP_CLEAR_FLAG( COMP_CLEAR_C1IF)
+
+/** @brief  Clear the COMP C2I  flag.
+  * @retval None
+  */
+#define __HAL_COMP_CLEAR_C2IFLAG()   __HAL_COMP_CLEAR_FLAG( COMP_CLEAR_C2IF)
+
+/** @brief  Enable the specified COMP interrupt.
+  * @param  __HANDLE__: specifies the COMP Handle.
+  * @param  __INTERRUPT__: specifies the COMP interrupt source to enable.
+  *          This parameter can be one of the following values:
+  *            @arg COMP_CFGRx_ITEN :  Comparator  interrupt
+  * @retval None
+  */
+#define __HAL_COMP_ENABLE_IT(__HANDLE__, __INTERRUPT__)   ( ((__HANDLE__)->Instance->CFGR) |= (__INTERRUPT__) )
+
+/** @brief  Disable the specified COMP interrupt.
+  * @param  __HANDLE__: specifies the COMP Handle.
+  * @param  __INTERRUPT__: specifies the COMP interrupt source to enable.
+  *          This parameter can be one of the following values:
+  *            @arg COMP_CFGRx_ITEN :  Comparator  interrupt
+  * @retval None
+  */
+#define __HAL_COMP_DISABLE_IT(__HANDLE__,__INTERRUPT__) (((__HANDLE__)->Instance->CFGR) &= ~(__INTERRUPT__))
+
+/**
+  * @}
+  */
+/** @brief  Enable the specified bit in the Option register.
+  * @param  __AF__: specifies the Alternate Function source selection .
+  *          This parameter can be one of the following values:
+  *            @arg COMP_OR_AFOPA6  :  Alternate Function PA6 source selection
+  *            @arg COMP_OR_AFOPA8  :  Alternate Function PA8 source selection
+  *            @arg COMP_OR_AFOPB12 :  Alternate Function PB12 source selection
+  *            @arg COMP_OR_AFOPE6  :  Alternate Function PE6 source selection
+  *            @arg COMP_OR_AFOPE15 :  Alternate Function PE15 source selection
+  *            @arg COMP_OR_AFOPG2  :  Alternate Function PG2 source selection
+  *            @arg COMP_OR_AFOPG3  :  Alternate Function PG3 source selection
+  *            @arg COMP_OR_AFOPG4  :  Alternate Function PG4 source selection
+  *            @arg COMP_OR_AFOPI1  :  Alternate Function PI1 source selection
+  *            @arg COMP_OR_AFOPI4  :  Alternate Function PI4 source selection 
+  *            @arg COMP_OR_AFOPK2  :  Alternate Function PK2 source selection
+  * @retval None
+  */
+#define __HAL_COMP_ENABLE_OR(__AF__) SET_BIT(COMP12->OR, (__AF__))
+
+/** @brief  Disable the specified bit in the Option register.
+  * @param  __AF__: specifies the Alternate Function source selection .
+  *          This parameter can be one of the following values:
+  *            @arg COMP_OR_AFOPA6  :  Alternate Function PA6 source selection
+  *            @arg COMP_OR_AFOPA8  :  Alternate Function PA8 source selection
+  *            @arg COMP_OR_AFOPB12 :  Alternate Function PB12 source selection
+  *            @arg COMP_OR_AFOPE6  :  Alternate Function PE6 source selection
+  *            @arg COMP_OR_AFOPE15 :  Alternate Function PE15 source selection
+  *            @arg COMP_OR_AFOPG2  :  Alternate Function PG2 source selection
+  *            @arg COMP_OR_AFOPG3  :  Alternate Function PG3 source selection
+  *            @arg COMP_OR_AFOPG4  :  Alternate Function PG4 source selection
+  *            @arg COMP_OR_AFOPI1  :  Alternate Function PI1 source selection
+  *            @arg COMP_OR_AFOPI4  :  Alternate Function PI4 source selection
+  *            @arg COMP_OR_AFOPK2  :  Alternate Function PK2 source selection  
+  * @retval None
+  */
+#define __HAL_COMP_DISABLE_OR(__AF__) CLEAR_BIT(COMP12->OR, (__AF__))
+/**
+  * @}
+  */
+
+/* Private types -------------------------------------------------------------*/
+/* Private constants ---------------------------------------------------------*/
+/** @defgroup COMP_Private_Constants COMP Private Constants
+  * @{
+  */
+/** @defgroup COMP_ExtiLine COMP EXTI Lines
+  * @{
+  */
+#define COMP_EXTI_LINE_COMP1           (EXTI_IMR1_IM20)  /*!< EXTI line 20 connected to COMP1 output */
+#define COMP_EXTI_LINE_COMP2           (EXTI_IMR1_IM21)  /*!< EXTI line 21 connected to COMP2 output */
+/**
+  * @}
+  */
+/** @defgroup COMP_ExtiLine COMP EXTI Lines
+  * @{
+  */
+#define COMP_EXTI_IT                        ((uint32_t) 0x01)  /*!< EXTI line event with interruption */
+#define COMP_EXTI_EVENT                     ((uint32_t) 0x02)  /*!< EXTI line event only (without interruption) */
+#define COMP_EXTI_RISING                    ((uint32_t) 0x10)  /*!< EXTI line event on rising edge */
+#define COMP_EXTI_FALLING                   ((uint32_t) 0x20)  /*!< EXTI line event on falling edge */
+/**
+  * @}
+  */
+/**
+  * @}
+  */
+
+/* Private macros ------------------------------------------------------------*/
+/** @defgroup COMP_Private_Macros COMP Private Macros
+  * @{
+  */
+/** @defgroup COMP_GET_EXTI_LINE COMP Private macros to get EXTI line associated with Comparators 
+  * @{
+  */
+/**
+  * @brief  Get the specified EXTI line for a comparator instance.
+  * @param  __INSTANCE__: specifies the COMP instance.
+  * @retval value of @ref COMP_ExtiLine
+  */
+#define COMP_GET_EXTI_LINE(__INSTANCE__)             (((__INSTANCE__) == COMP1) ? COMP_EXTI_LINE_COMP1 : \
+                                                      COMP_EXTI_LINE_COMP2)
+/**
+  * @}
+  */
+/** @defgroup COMP_IS_COMP_Definitions COMP private macros to check input parameters
+  * @{
+  */
+#define IS_COMP_WINDOWMODE(__WINDOWMODE__)  (((__WINDOWMODE__) == COMP_WINDOWMODE_DISABLE)                || \
+                                             ((__WINDOWMODE__) == COMP_WINDOWMODE_COMP1_INPUT_PLUS_COMMON)  )
+
+#define IS_COMP_POWERMODE(__POWERMODE__)    (((__POWERMODE__) == COMP_POWERMODE_HIGHSPEED)    || \
+                                             ((__POWERMODE__) == COMP_POWERMODE_MEDIUMSPEED)  || \
+                                             ((__POWERMODE__) == COMP_POWERMODE_ULTRALOWPOWER)  )
+
+#if defined (COMP_CFGRx_INP2SEL)
+#define IS_COMP_INPUT_PLUS(__COMP_INSTANCE__, __INPUT_PLUS__) (((__INPUT_PLUS__) == COMP_INPUT_PLUS_IO1) || \
+                                                               ((__INPUT_PLUS__) == COMP_INPUT_PLUS_IO2) || \
+                                                               ((__INPUT_PLUS__) == COMP_INPUT_PLUS_DAC2_CH1))
+#else
+#define IS_COMP_INPUT_PLUS(__COMP_INSTANCE__, __INPUT_PLUS__) (((__INPUT_PLUS__) == COMP_INPUT_PLUS_IO1) || \
+                                                               ((__INPUT_PLUS__) == COMP_INPUT_PLUS_IO2))                                                              
+#endif                                                             
+
+
+#if defined (COMP_CFGRx_INMSEL_3)
+#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT)     || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT)     || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT)     || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT)        || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1)       || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH2)       || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1)            || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO2)            || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_TPSENS_DAC2CH1) || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VBAT_VDDAP))
+#else                                          
+#define IS_COMP_INPUT_MINUS(__COMP_INSTANCE__, __INPUT_MINUS__) (((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_4VREFINT)  || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_1_2VREFINT)  || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_3_4VREFINT)  || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_VREFINT)     || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH1)    || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_DAC1_CH2)    || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO1)         || \
+                                                                 ((__INPUT_MINUS__) == COMP_INPUT_MINUS_IO2))                                                                  
+#endif
+
+#define IS_COMP_HYSTERESIS(__HYSTERESIS__)  (((__HYSTERESIS__) == COMP_HYSTERESIS_NONE)   || \
+                                             ((__HYSTERESIS__) == COMP_HYSTERESIS_LOW)    || \
+                                             ((__HYSTERESIS__) == COMP_HYSTERESIS_MEDIUM) || \
+                                             ((__HYSTERESIS__) == COMP_HYSTERESIS_HIGH))
+
+#define IS_COMP_OUTPUTPOL(__POL__)          (((__POL__) == COMP_OUTPUTPOL_NONINVERTED) || \
+                                             ((__POL__) == COMP_OUTPUTPOL_INVERTED))
+
+#define IS_COMP_BLANKINGSRCE(__SOURCE__)    (((__SOURCE__) == COMP_BLANKINGSRC_NONE)      || \
+                                             ((__SOURCE__) == COMP_BLANKINGSRC_TIM1_OC5)  || \
+                                             ((__SOURCE__) == COMP_BLANKINGSRC_TIM2_OC3)  || \
+                                             ((__SOURCE__) == COMP_BLANKINGSRC_TIM3_OC3)  || \
+                                             ((__SOURCE__) == COMP_BLANKINGSRC_TIM3_OC4)  || \
+                                             ((__SOURCE__) == COMP_BLANKINGSRC_TIM8_OC5)  || \
+                                             ((__SOURCE__) == COMP_BLANKINGSRC_TIM15_OC1))
+
+
+#define IS_COMP_TRIGGERMODE(__MODE__)       (((__MODE__) == COMP_TRIGGERMODE_NONE)                 || \
+                                             ((__MODE__) == COMP_TRIGGERMODE_IT_RISING)            || \
+                                             ((__MODE__) == COMP_TRIGGERMODE_IT_FALLING)           || \
+                                             ((__MODE__) == COMP_TRIGGERMODE_IT_RISING_FALLING)    || \
+                                             ((__MODE__) == COMP_TRIGGERMODE_EVENT_RISING)         || \
+                                             ((__MODE__) == COMP_TRIGGERMODE_EVENT_FALLING)        || \
+                                             ((__MODE__) == COMP_TRIGGERMODE_EVENT_RISING_FALLING))
+
+#define IS_COMP_OUTPUT_LEVEL(__OUTPUT_LEVEL__) (((__OUTPUT_LEVEL__) == COMP_OUTPUT_LEVEL_LOW)     || \
+                                                ((__OUTPUT_LEVEL__) == COMP_OUTPUT_LEVEL_HIGH))
+
+/**
+  * @}
+  */
+
+/**
+  * @}
+  */
+
+/* Exported functions --------------------------------------------------------*/
+/** @addtogroup COMP_Exported_Functions
+  * @{
+  */
+
+/** @addtogroup COMP_Exported_Functions_Group1
+  * @{
+  */
+/* Initialization and de-initialization functions  **********************************/
+HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp);
+HAL_StatusTypeDef HAL_COMP_DeInit (COMP_HandleTypeDef *hcomp);
+void              HAL_COMP_MspInit(COMP_HandleTypeDef *hcomp);
+void              HAL_COMP_MspDeInit(COMP_HandleTypeDef *hcomp);
+#if (USE_HAL_COMP_REGISTER_CALLBACKS == 1)
+/* Callbacks Register/UnRegister functions  ***********************************/
+HAL_StatusTypeDef HAL_COMP_RegisterCallback(COMP_HandleTypeDef *hcomp, HAL_COMP_CallbackIDTypeDef CallbackID, pCOMP_CallbackTypeDef pCallback);
+HAL_StatusTypeDef HAL_COMP_UnRegisterCallback(COMP_HandleTypeDef *hcomp, HAL_COMP_CallbackIDTypeDef CallbackID);
+#endif /* USE_HAL_COMP_REGISTER_CALLBACKS */
+/**
+  * @}
+  */
+
+/* IO operation functions  *****************************************************/
+/** @addtogroup COMP_Exported_Functions_Group2
+  * @{
+  */
+HAL_StatusTypeDef HAL_COMP_Start(COMP_HandleTypeDef *hcomp);
+HAL_StatusTypeDef HAL_COMP_Stop(COMP_HandleTypeDef *hcomp);
+HAL_StatusTypeDef HAL_COMP_Start_IT(COMP_HandleTypeDef *hcomp);
+HAL_StatusTypeDef HAL_COMP_Stop_IT(COMP_HandleTypeDef *hcomp);
+void              HAL_COMP_IRQHandler(COMP_HandleTypeDef *hcomp);
+
+/**
+  * @}
+  */
+
+/* Peripheral Control functions  ************************************************/
+/** @addtogroup COMP_Exported_Functions_Group3
+  * @{
+  */
+HAL_StatusTypeDef HAL_COMP_Lock(COMP_HandleTypeDef *hcomp);
+uint32_t          HAL_COMP_GetOutputLevel(COMP_HandleTypeDef *hcomp);
+/* Callback in Interrupt mode */
+void              HAL_COMP_TriggerCallback(COMP_HandleTypeDef *hcomp);
+/**
+  * @}
+  */
+
+/* Peripheral State functions  **************************************************/
+/** @addtogroup COMP_Exported_Functions_Group4
+  * @{
+  */
+HAL_COMP_StateTypeDef HAL_COMP_GetState(COMP_HandleTypeDef *hcomp);
+uint32_t              HAL_COMP_GetError(COMP_HandleTypeDef *hcomp);
+/**
+  * @}
+  */
+
+/**
+  * @}
+  */
+
+
+/**
+  * @}
+  */
+
+/**
+  * @}
+  */
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* STM32H7xx_HAL_COMP_H */
+
+

+ 941 - 0
OZE_Sensor/Drivers/STM32H7xx_HAL_Driver/Inc/stm32h7xx_ll_comp.h

@@ -0,0 +1,941 @@
+/**
+  ******************************************************************************
+  * @file    stm32h7xx_ll_comp.h
+  * @author  MCD Application Team
+  * @brief   Header file of COMP LL module.
+  ******************************************************************************
+  * @attention
+  *
+  * Copyright (c) 2017 STMicroelectronics.
+  * All rights reserved.
+  *
+  * This software is licensed under terms that can be found in the LICENSE file
+  * in the root directory of this software component.
+  * If no LICENSE file comes with this software, it is provided AS-IS.
+  *
+  ******************************************************************************
+  */
+
+/* Define to prevent recursive inclusion -------------------------------------*/
+#ifndef __STM32H7xx_LL_COMP_H
+#define __STM32H7xx_LL_COMP_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Includes ------------------------------------------------------------------*/
+#include "stm32h7xx.h"
+
+/** @addtogroup STM32H7xx_LL_Driver
+  * @{
+  */
+
+#if defined (COMP1) || defined (COMP2)
+
+/** @defgroup COMP_LL COMP
+  * @{
+  */
+
+/* Private types -------------------------------------------------------------*/
+/* Private variables ---------------------------------------------------------*/
+/* Private constants ---------------------------------------------------------*/
+/** @defgroup COMP_LL_Private_Constants COMP Private Constants
+  * @{
+  */
+
+/* COMP registers bits positions */
+#define LL_COMP_OUTPUT_LEVEL_BITOFFSET_POS (30U) /* Value equivalent to POSITION_VAL(COMP_CSR_VALUE) */
+
+/**
+  * @}
+  */
+
+/* Private macros ------------------------------------------------------------*/
+/** @defgroup COMP_LL_Private_Macros COMP Private Macros
+  * @{
+  */
+/**
+  * @}
+  */
+/* Exported types ------------------------------------------------------------*/
+#if defined(USE_FULL_LL_DRIVER)
+/** @defgroup COMP_LL_ES_INIT COMP Exported Init structure
+  * @{
+  */
+
+/**
+  * @brief  Structure definition of some features of COMP instance.
+  */
+typedef struct
+{
+  uint32_t PowerMode;                   /*!< Set comparator operating mode to adjust power and speed.
+                                             This parameter can be a value of @ref COMP_LL_EC_POWERMODE
+                                             
+                                             This feature can be modified afterwards using unitary function @ref LL_COMP_SetPowerMode(). */
+
+  uint32_t InputPlus;                   /*!< Set comparator input plus (non-inverting input).
+                                             This parameter can be a value of @ref COMP_LL_EC_INPUT_PLUS
+                                             
+                                             This feature can be modified afterwards using unitary function @ref LL_COMP_SetInputPlus(). */
+
+  uint32_t InputMinus;                  /*!< Set comparator input minus (inverting input).
+                                             This parameter can be a value of @ref COMP_LL_EC_INPUT_MINUS
+                                             
+                                             This feature can be modified afterwards using unitary function @ref LL_COMP_SetInputMinus(). */
+
+  uint32_t InputHysteresis;             /*!< Set comparator hysteresis mode of the input minus.
+                                             This parameter can be a value of @ref COMP_LL_EC_INPUT_HYSTERESIS
+                                             
+                                             This feature can be modified afterwards using unitary function @ref LL_COMP_SetInputHysteresis(). */
+
+  uint32_t OutputPolarity;              /*!< Set comparator output polarity.
+                                             This parameter can be a value of @ref COMP_LL_EC_OUTPUT_POLARITY
+                                             
+                                             This feature can be modified afterwards using unitary function @ref LL_COMP_SetOutputPolarity(). */
+
+  uint32_t OutputBlankingSource;        /*!< Set comparator blanking source.
+                                             This parameter can be a value of @ref COMP_LL_EC_OUTPUT_BLANKING_SOURCE
+                                             
+                                             This feature can be modified afterwards using unitary function @ref LL_COMP_SetOutputBlankingSource(). */
+
+} LL_COMP_InitTypeDef;
+
+/**
+  * @}
+  */
+#endif /* USE_FULL_LL_DRIVER */
+
+/* Exported constants --------------------------------------------------------*/
+/** @defgroup COMP_LL_Exported_Constants COMP Exported Constants
+  * @{
+  */
+
+/** @defgroup COMP_LL_EC_COMMON_WINDOWMODE Comparator common modes - Window mode
+  * @{
+  */
+#define LL_COMP_WINDOWMODE_DISABLE                 (0x00000000UL)          /*!< Window mode disable: Comparators 1 and 2 are independent */
+#define LL_COMP_WINDOWMODE_COMP1_INPUT_PLUS_COMMON (COMP_CFGRx_WINMODE)    /*!< Window mode enable: Comparators instances pair COMP1 and COMP2 have their input plus connected together. The common input is COMP1 input plus (COMP2 input plus is no more accessible). */
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EC_POWERMODE Comparator modes - Power mode
+  * @{
+  */
+#define LL_COMP_POWERMODE_HIGHSPEED     (0x00000000UL)                                /*!< COMP power mode to high speed */
+#define LL_COMP_POWERMODE_MEDIUMSPEED   (COMP_CFGRx_PWRMODE_0)                        /*!< COMP power mode to medium speed */
+#define LL_COMP_POWERMODE_ULTRALOWPOWER (COMP_CFGRx_PWRMODE_1 | COMP_CFGRx_PWRMODE_0) /*!< COMP power mode to ultra-low power */
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EC_INPUT_PLUS Comparator inputs - Input plus (input non-inverting) selection
+  * @{
+  */
+#define LL_COMP_INPUT_PLUS_IO1          (0x00000000UL)                           /*!< Comparator input plus connected to IO1 (pin PB0 for COMP1, pin PE9 for COMP2) */
+#define LL_COMP_INPUT_PLUS_IO2          (COMP_CFGRx_INPSEL)                      /*!< Comparator input plus connected to IO2 (pin PB2 for COMP1, pin PE11 for COMP2) */
+#if defined (COMP_CFGRx_INP2SEL)
+#define LL_COMP_INPUT_PLUS_DAC2_CH1     (COMP_CFGRx_INP2SEL)                     /*!< Comparator input plus 2 connected to (DAC2_CH1 for COMP1)                      */
+#endif
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EC_INPUT_MINUS Comparator inputs - Input minus (input inverting) selection
+  * @{
+  */
+#define LL_COMP_INPUT_MINUS_1_4VREFINT      (                                                                                        COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN)   /*!< Comparator input minus connected to 1/4 VrefInt  */
+#define LL_COMP_INPUT_MINUS_1_2VREFINT      (                                                                  COMP_CFGRx_INMSEL_0 | COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN)   /*!< Comparator input minus connected to 1/2 VrefInt  */
+#define LL_COMP_INPUT_MINUS_3_4VREFINT      (                                            COMP_CFGRx_INMSEL_1                       | COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN)   /*!< Comparator input minus connected to 3/4 VrefInt  */
+#define LL_COMP_INPUT_MINUS_VREFINT         (                                            COMP_CFGRx_INMSEL_1 | COMP_CFGRx_INMSEL_0 | COMP_CFGRx_SCALEN                   )   /*!< Comparator input minus connected to VrefInt */
+#define LL_COMP_INPUT_MINUS_DAC1_CH1        (                      COMP_CFGRx_INMSEL_2                                                                                   )   /*!< Comparator input minus connected to DAC1 channel 1 (DAC_OUT1)  */
+#define LL_COMP_INPUT_MINUS_DAC1_CH2        (                      COMP_CFGRx_INMSEL_2                       | COMP_CFGRx_INMSEL_0                                       )   /*!< Comparator input minus connected to DAC1 channel 2 (DAC_OUT2)  */
+#define LL_COMP_INPUT_MINUS_IO1             (                      COMP_CFGRx_INMSEL_2 | COMP_CFGRx_INMSEL_1                                                             )   /*!< Comparator input minus connected to IO1 (pin PB1 for COMP1, pin PE10 for COMP2) */
+#define LL_COMP_INPUT_MINUS_IO2             (                      COMP_CFGRx_INMSEL_2 | COMP_CFGRx_INMSEL_1 | COMP_CFGRx_INMSEL_0                                       )   /*!< Comparator input minus connected to IO2 (pin PC4 for COMP1, pin PE7 for COMP2) */
+#if defined (COMP_CFGRx_INMSEL_3)
+#define LL_COMP_INPUT_MINUS_TPSENS_DAC2CH1  (COMP_CFGRx_INMSEL_3                                                                                                         )   /*!< Comparator input minus connected to  (temp sensor which is exist in ADC for COMP1, DAC2_CH1 for COMP2) */
+#define LL_COMP_INPUT_MINUS_VBAT_VDDAP      (COMP_CFGRx_INMSEL_3                                             | COMP_CFGRx_INMSEL_0                                       )   /*!< Comparator input minus connected to  (VBAT/4 for COMP1, VDDAP for COMP2) */
+#endif
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EC_INPUT_HYSTERESIS Comparator input - Hysteresis
+  * @{
+  */
+#define LL_COMP_HYSTERESIS_NONE         (0x00000000UL)                            /*!< No hysteresis */
+#define LL_COMP_HYSTERESIS_LOW          (                    COMP_CFGRx_HYST_0)   /*!< Hysteresis level low */
+#define LL_COMP_HYSTERESIS_MEDIUM       (COMP_CFGRx_HYST_1                    )   /*!< Hysteresis level medium */
+#define LL_COMP_HYSTERESIS_HIGH         (COMP_CFGRx_HYST_1 | COMP_CFGRx_HYST_0)   /*!< Hysteresis level high */
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EC_OUTPUT_POLARITY Comparator output - Output polarity
+  * @{
+  */
+#define LL_COMP_OUTPUTPOL_NONINVERTED   (0x00000000UL)          /*!< COMP output polarity is not inverted: comparator output is high when the plus (non-inverting) input is at a higher voltage than the minus (inverting) input */
+#define LL_COMP_OUTPUTPOL_INVERTED      (COMP_CFGRx_POLARITY)   /*!< COMP output polarity is inverted: comparator output is low when the plus (non-inverting) input is at a lower voltage than the minus (inverting) input */
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EC_OUTPUT_BLANKING_SOURCE Comparator output - Blanking source
+  * @{
+  */
+#define LL_COMP_BLANKINGSRC_NONE      (0x00000000UL)                                  /*!<Comparator output without blanking */
+#define LL_COMP_BLANKINGSRC_TIM1_OC5  (COMP_CFGRx_BLANKING_0)                         /*!< Comparator output blanking source TIM1 OC5 (common to all COMP instances: COMP1, COMP2) */
+#define LL_COMP_BLANKINGSRC_TIM2_OC3  (COMP_CFGRx_BLANKING_1)                         /*!< Comparator output blanking source TIM2 OC3 (common to all COMP instances: COMP1, COMP2) */
+#define LL_COMP_BLANKINGSRC_TIM3_OC3  (COMP_CFGRx_BLANKING_0 |COMP_CFGRx_BLANKING_1)  /*!< Comparator output blanking source TIM3 OC3 (common to all COMP instances: COMP1, COMP2) */
+#define LL_COMP_BLANKINGSRC_TIM3_OC4  (COMP_CFGRx_BLANKING_2)                         /*!< Comparator output blanking source TIM3 OC4 (common to all COMP instances: COMP1, COMP2) */
+#define LL_COMP_BLANKINGSRC_TIM8_OC5  (COMP_CFGRx_BLANKING_2|COMP_CFGRx_BLANKING_0)   /*!< Comparator output blanking source TIM8 OC5 (common to all COMP instances: COMP1, COMP2) */
+#define LL_COMP_BLANKINGSRC_TIM15_OC1 (COMP_CFGRx_BLANKING_2|COMP_CFGRx_BLANKING_1)   /*!< Comparator output blanking source TIM15 OC1 (common to all COMP instances: COMP1, COMP2) */
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EC_OUTPUT_LEVEL Comparator output - Output level
+  * @{
+  */
+#define LL_COMP_OUTPUT_LEVEL_LOW        (0x00000000UL)           /*!< Comparator output level low (if the polarity is not inverted, otherwise to be complemented) */
+#define LL_COMP_OUTPUT_LEVEL_HIGH       (0x00000001UL)           /*!< Comparator output level high (if the polarity is not inverted, otherwise to be complemented) */
+/**
+  * @}
+  */
+/** @defgroup COMP_LL_EC_OUTPUT_BKIN_TIMER Comparator output - Output to BKIN timer
+  * @{
+  */
+#define LL_COMP_AF_PA6          COMP_OR_AFOPA6       /*!< Comparator Alternate Function PA6 source selected to timer BKIN input  */
+#define LL_COMP_AF_PA8          COMP_OR_AFOPA8       /*!< Comparator Alternate Function PA8 source selected to timer BKIN input  */
+#define LL_COMP_AF_PB12         COMP_OR_AFOPB12      /*!< Comparator Alternate Function PB12 source selected to timer BKIN input */
+#define LL_COMP_AF_PE6          COMP_OR_AFOPE6       /*!< Comparator Alternate Function PE6 source selected to timer BKIN input  */
+#define LL_COMP_AF_PE15         COMP_OR_AFOPE15      /*!< Comparator Alternate Function PE15 source selected to timer BKIN input */
+#define LL_COMP_AF_PG2          COMP_OR_AFOPG2       /*!< Comparator Alternate Function PG2 source selected to timer BKIN input  */
+#define LL_COMP_AF_PG3          COMP_OR_AFOPG3       /*!< Comparator Alternate Function PG3 source selected to timer BKIN input  */
+#define LL_COMP_AF_PG4          COMP_OR_AFOPG4       /*!< Comparator Alternate Function PG4 source selected to timer BKIN input  */
+#define LL_COMP_AF_PI1          COMP_OR_AFOPI1       /*!< Comparator Alternate Function PI1 source selected to timer BKIN input  */
+#define LL_COMP_AF_PI4          COMP_OR_AFOPI4       /*!< Comparator Alternate Function PI4 source selected to timer BKIN input  */
+#define LL_COMP_AF_PK2          COMP_OR_AFOPK2       /*!< Comparator Alternate Function PK2 source selected to timer BKIN input  */
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EC_HW_DELAYS  Definitions of COMP hardware constraints delays
+  * @note   Only COMP IP HW delays are defined in COMP LL driver driver,
+  *         not timeout values.
+  *         For details on delays values, refer to descriptions in source code
+  *         above each literal definition.
+  * @{
+  */
+
+/* Delay for comparator startup time.                                         */
+/* Note: Delay required to reach propagation delay specification.             */
+/* Literal set to maximum value (refer to device datasheet,                   */
+/* parameter "tSTART").                                                       */
+/* Unit: us                                                                   */
+#define LL_COMP_DELAY_STARTUP_US          ( 80UL)  /*!< Delay for COMP startup time */
+
+/* Delay for comparator voltage scaler stabilization time.                    */
+/* Note: Voltage scaler is used when selecting comparator input               */
+/*       based on VrefInt: VrefInt or subdivision of VrefInt.                 */
+/* Literal set to maximum value (refer to device datasheet,                   */
+/* parameter "tSTART_SCALER").                                                */
+/* Unit: us                                                                   */
+#define LL_COMP_DELAY_VOLTAGE_SCALER_STAB_US ( 200UL)  /*!< Delay for COMP voltage scaler stabilization time */
+
+/**
+  * @}
+  */
+
+/**
+  * @}
+  */
+
+/* Exported macro ------------------------------------------------------------*/
+/** @defgroup COMP_LL_Exported_Macros COMP Exported Macros
+  * @{
+  */
+/** @defgroup COMP_LL_EM_WRITE_READ Common write and read registers macro
+  * @{
+  */
+
+/**
+  * @brief  Write a value in COMP register
+  * @param  __INSTANCE__ comparator instance
+  * @param  __REG__ Register to be written
+  * @param  __VALUE__ Value to be written in the register
+  * @retval None
+  */
+#define LL_COMP_WriteReg(__INSTANCE__, __REG__, __VALUE__) WRITE_REG(__INSTANCE__->__REG__, (__VALUE__))
+
+/**
+  * @brief  Read a value in COMP register
+  * @param  __INSTANCE__ comparator instance
+  * @param  __REG__ Register to be read
+  * @retval Register value
+  */
+#define LL_COMP_ReadReg(__INSTANCE__, __REG__) READ_REG(__INSTANCE__->__REG__)
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EM_HELPER_MACRO COMP helper macro
+  * @{
+  */
+
+/**
+  * @brief  Helper macro to select the COMP common instance
+  *         to which is belonging the selected COMP instance.
+  * @note   COMP common register instance can be used to
+  *         set parameters common to several COMP instances.
+  *         Refer to functions having argument "COMPxy_COMMON" as parameter.
+  * @param  __COMPx__ COMP instance
+  * @retval COMP common instance or value "0" if there is no COMP common instance.
+  */
+#define __LL_COMP_COMMON_INSTANCE(__COMPx__)                                   \
+  (COMP12_COMMON)
+
+/**
+  * @}
+  */
+
+/**
+  * @}
+  */
+
+/* Exported functions --------------------------------------------------------*/
+/** @defgroup COMP_LL_Exported_Functions COMP Exported Functions
+  * @{
+  */
+
+/** @defgroup COMP_LL_EF_Configuration_comparator_common Configuration of COMP hierarchical scope: common to several COMP instances
+  * @{
+  */
+
+/**
+  * @brief  Set window mode of a pair of comparators instances
+  *         (2 consecutive COMP instances odd and even COMP<x> and COMP<x+1>).
+  * @rmtoll CFGRx    WINMODE        LL_COMP_SetCommonWindowMode
+  * @param  COMPxy_COMMON Comparator common instance
+  *         (can be set directly from CMSIS definition or by using helper macro @ref __LL_COMP_COMMON_INSTANCE() )
+  * @param  WindowMode This parameter can be one of the following values:
+  *         @arg @ref LL_COMP_WINDOWMODE_DISABLE
+  *         @arg @ref LL_COMP_WINDOWMODE_COMP1_INPUT_PLUS_COMMON
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_SetCommonWindowMode(COMP_Common_TypeDef *COMPxy_COMMON, uint32_t WindowMode)
+{
+  /* Note: On this STM32 series, window mode can be set only                   */
+  /*       from COMP instance: COMP2.                                         */
+  MODIFY_REG(COMPxy_COMMON->CFGR, COMP_CFGRx_WINMODE, WindowMode);
+}
+
+/**
+  * @brief  Get window mode of a pair of comparators instances
+  *         (2 consecutive COMP instances odd and even COMP<x> and COMP<x+1>).
+  * @rmtoll CFGRx    WINMODE        LL_COMP_GetCommonWindowMode
+  * @param  COMPxy_COMMON Comparator common instance
+  *         (can be set directly from CMSIS definition or by using helper macro @ref __LL_COMP_COMMON_INSTANCE() )
+  * @retval Returned value can be one of the following values:
+  *         @arg @ref LL_COMP_WINDOWMODE_DISABLE
+  *         @arg @ref LL_COMP_WINDOWMODE_COMP1_INPUT_PLUS_COMMON
+  */
+__STATIC_INLINE uint32_t LL_COMP_GetCommonWindowMode(COMP_Common_TypeDef *COMPxy_COMMON)
+{
+  return (uint32_t)(READ_BIT(COMPxy_COMMON->CFGR, COMP_CFGRx_WINMODE));
+}
+
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EF_Configuration_comparator_modes Configuration of comparator modes
+  * @{
+  */
+
+/**
+  * @brief  Set comparator instance operating mode to adjust power and speed.
+  * @rmtoll CFGRx    PWRMODE        LL_COMP_SetPowerMode
+  * @param  COMPx Comparator instance
+  * @param  PowerMode This parameter can be one of the following values:
+  *         @arg @ref LL_COMP_POWERMODE_HIGHSPEED
+  *         @arg @ref LL_COMP_POWERMODE_MEDIUMSPEED
+  *         @arg @ref LL_COMP_POWERMODE_ULTRALOWPOWER
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_SetPowerMode(COMP_TypeDef *COMPx, uint32_t PowerMode)
+{
+  MODIFY_REG(COMPx->CFGR, COMP_CFGRx_PWRMODE, PowerMode);
+}
+
+/**
+  * @brief  Get comparator instance operating mode to adjust power and speed.
+  * @rmtoll CFGRx    PWRMODE        LL_COMP_GetPowerMode
+  * @param  COMPx Comparator instance
+  * @retval Returned value can be one of the following values:
+  *         @arg @ref LL_COMP_POWERMODE_HIGHSPEED
+  *         @arg @ref LL_COMP_POWERMODE_MEDIUMSPEED
+  *         @arg @ref LL_COMP_POWERMODE_ULTRALOWPOWER
+  */
+__STATIC_INLINE uint32_t LL_COMP_GetPowerMode(COMP_TypeDef *COMPx)
+{
+  return (uint32_t)(READ_BIT(COMPx->CFGR, COMP_CFGRx_PWRMODE));
+}
+
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EF_Configuration_comparator_inputs Configuration of comparator inputs
+  * @{
+  */
+
+/**
+  * @brief  Set comparator inputs minus (inverting) and plus (non-inverting).
+  * @note   In case of comparator input selected to be connected to IO:
+  *         GPIO pins are specific to each comparator instance.
+  *         Refer to description of parameters or to reference manual.
+  * @note   On this STM32 series, scaler bridge is configurable:
+  *         to optimize power consumption, this function enables the
+  *         voltage scaler bridge only when required
+  *         (when selecting comparator input based on VrefInt: VrefInt or
+  *         subdivision of VrefInt).
+  *         - For scaler bridge power consumption values, 
+  *           refer to device datasheet, parameter "IDDA(SCALER)".
+  *         - Voltage scaler requires a delay for voltage stabilization.
+  *           Refer to device datasheet, parameter "tSTART_SCALER".
+  *         - Scaler bridge is common for all comparator instances,
+  *           therefore if at least one of the comparator instance
+  *           is requiring the scaler bridge, it remains enabled.
+  * @rmtoll CFGRx      INMSEL         LL_COMP_ConfigInputs\n
+  *         CFGRx      INPSEL         LL_COMP_ConfigInputs\n
+  *         CFGRx      BRGEN          LL_COMP_ConfigInputs\n
+  *         CFGRx      SCALEN         LL_COMP_ConfigInputs
+  * @param  COMPx Comparator instance
+  * @param  InputMinus This parameter can be one of the following values:
+  *         @arg @ref LL_COMP_INPUT_MINUS_1_4VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_1_2VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_3_4VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_DAC1_CH1
+  *         @arg @ref LL_COMP_INPUT_MINUS_DAC1_CH2 
+  *         @arg @ref LL_COMP_INPUT_MINUS_IO1
+  *         @arg @ref LL_COMP_INPUT_MINUS_IO2
+  *         @arg @ref LL_COMP_INPUT_MINUS_TPSENS_DAC2CH1
+  *         @arg @ref LL_COMP_INPUT_MINUS_VBAT_VDDAP
+  * @param  InputPlus This parameter can be one of the following values:
+  *         @arg @ref LL_COMP_INPUT_PLUS_IO1
+  *         @arg @ref LL_COMP_INPUT_PLUS_IO2
+  *         @arg @ref LL_COMP_INPUT_PLUS_DAC2_CH1
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_ConfigInputs(COMP_TypeDef *COMPx, uint32_t InputMinus, uint32_t InputPlus)
+{
+#if defined (COMP_CFGRx_INP2SEL)
+  MODIFY_REG(COMPx->CFGR,
+             COMP_CFGRx_INMSEL | COMP_CFGRx_INPSEL | 
+             COMP_CFGRx_INP2SEL | 
+             COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN,
+             InputMinus | InputPlus);
+#else
+  MODIFY_REG(COMPx->CFGR,
+             COMP_CFGRx_INMSEL | COMP_CFGRx_INPSEL | 
+             COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN,
+             InputMinus | InputPlus);
+#endif
+}
+
+/**
+  * @brief  Set comparator input plus (non-inverting).
+  * @note   In case of comparator input selected to be connected to IO:
+  *         GPIO pins are specific to each comparator instance.
+  *         Refer to description of parameters or to reference manual.
+  * @rmtoll CFGRx    INPSEL         LL_COMP_SetInputPlus
+  * @param  COMPx Comparator instance
+  * @param  InputPlus This parameter can be one of the following values:
+  *         @arg @ref LL_COMP_INPUT_PLUS_IO1
+  *         @arg @ref LL_COMP_INPUT_PLUS_IO2
+  *         @arg @ref LL_COMP_INPUT_PLUS_DAC2_CH1
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_SetInputPlus(COMP_TypeDef *COMPx, uint32_t InputPlus)
+{
+#if defined (COMP_CFGRx_INP2SEL)
+  MODIFY_REG(COMPx->CFGR, COMP_CFGRx_INPSEL | COMP_CFGRx_INP2SEL , InputPlus);
+#else
+  MODIFY_REG(COMPx->CFGR, COMP_CFGRx_INPSEL , InputPlus);
+#endif
+}
+
+/**
+  * @brief  Get comparator input plus (non-inverting).
+  * @note   In case of comparator input selected to be connected to IO:
+  *         GPIO pins are specific to each comparator instance.
+  *         Refer to description of parameters or to reference manual.
+  * @rmtoll CFGRx    INPSEL         LL_COMP_GetInputPlus
+  * @param  COMPx Comparator instance
+  * @retval Returned value can be one of the following values:
+  *         @arg @ref LL_COMP_INPUT_PLUS_IO1
+  *         @arg @ref LL_COMP_INPUT_PLUS_IO2
+  *         @arg @ref LL_COMP_INPUT_PLUS_DAC2_CH1
+  */
+__STATIC_INLINE uint32_t LL_COMP_GetInputPlus(COMP_TypeDef *COMPx)
+{
+#if defined (COMP_CFGRx_INP2SEL)
+  return (uint32_t)(READ_BIT(COMPx->CFGR, COMP_CFGRx_INPSEL | COMP_CFGRx_INP2SEL));
+#else
+  return (uint32_t)(READ_BIT(COMPx->CFGR, COMP_CFGRx_INPSEL));
+#endif
+}
+
+/**
+  * @brief  Set comparator input minus (inverting).
+  * @note   In case of comparator input selected to be connected to IO:
+  *         GPIO pins are specific to each comparator instance.
+  *         Refer to description of parameters or to reference manual.
+  * @note   On this STM32 series, scaler bridge is configurable:
+  *         to optimize power consumption, this function enables the
+  *         voltage scaler bridge only when required
+  *         (when selecting comparator input based on VrefInt: VrefInt or
+  *         subdivision of VrefInt).
+  *         - For scaler bridge power consumption values, 
+  *           refer to device datasheet, parameter "IDDA(SCALER)".
+  *         - Voltage scaler requires a delay for voltage stabilization.
+  *           Refer to device datasheet, parameter "tSTART_SCALER".
+  *         - Scaler bridge is common for all comparator instances,
+  *           therefore if at least one of the comparator instance
+  *           is requiring the scaler bridge, it remains enabled.
+  * @rmtoll CFGRx     INMSEL         LL_COMP_SetInputMinus\n
+  *         CFGRx     BRGEN          LL_COMP_SetInputMinus\n
+  *         CFGRx     SCALEN         LL_COMP_SetInputMinus
+  * @param  COMPx Comparator instance
+  * @param  InputMinus This parameter can be one of the following values:
+  *         @arg @ref LL_COMP_INPUT_MINUS_1_4VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_1_2VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_3_4VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_DAC1_CH1
+  *         @arg @ref LL_COMP_INPUT_MINUS_DAC1_CH2
+  *         @arg @ref LL_COMP_INPUT_MINUS_IO1
+  *         @arg @ref LL_COMP_INPUT_MINUS_IO2
+  *         @arg @ref LL_COMP_INPUT_MINUS_TPSENS_DAC2CH1
+  *         @arg @ref LL_COMP_INPUT_MINUS_VBAT_VDDAP
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_SetInputMinus(COMP_TypeDef *COMPx, uint32_t InputMinus)
+{
+  MODIFY_REG(COMPx->CFGR, COMP_CFGRx_INMSEL | COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN, InputMinus);
+}
+
+/**
+  * @brief  Get comparator input minus (inverting).
+  * @note   In case of comparator input selected to be connected to IO:
+  *         GPIO pins are specific to each comparator instance.
+  *         Refer to description of parameters or to reference manual.
+  * @rmtoll CFGRx     INMSEL         LL_COMP_GetInputMinus\n
+  *         CFGRx     BRGEN          LL_COMP_GetInputMinus\n
+  *         CFGRx     SCALEN         LL_COMP_GetInputMinus
+  * @param  COMPx Comparator instance
+  * @retval Returned value can be one of the following values:
+  *         @arg @ref LL_COMP_INPUT_MINUS_1_4VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_1_2VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_3_4VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_VREFINT
+  *         @arg @ref LL_COMP_INPUT_MINUS_DAC1_CH1
+  *         @arg @ref LL_COMP_INPUT_MINUS_DAC1_CH2  
+  *         @arg @ref LL_COMP_INPUT_MINUS_IO1
+  *         @arg @ref LL_COMP_INPUT_MINUS_IO2
+  *         @arg @ref LL_COMP_INPUT_MINUS_TPSENS_DAC2CH1
+  *         @arg @ref LL_COMP_INPUT_MINUS_VBAT_VDDAP
+  */
+__STATIC_INLINE uint32_t LL_COMP_GetInputMinus(COMP_TypeDef *COMPx)
+{
+  return (uint32_t)(READ_BIT(COMPx->CFGR, COMP_CFGRx_INMSEL | COMP_CFGRx_SCALEN | COMP_CFGRx_BRGEN));
+}
+
+/**
+  * @brief  Set comparator instance hysteresis mode of the input minus (inverting input).
+  * @rmtoll CFGRx    HYST           LL_COMP_SetInputHysteresis
+  * @param  COMPx Comparator instance
+  * @param  InputHysteresis This parameter can be one of the following values:
+  *         @arg @ref LL_COMP_HYSTERESIS_NONE
+  *         @arg @ref LL_COMP_HYSTERESIS_LOW
+  *         @arg @ref LL_COMP_HYSTERESIS_MEDIUM
+  *         @arg @ref LL_COMP_HYSTERESIS_HIGH
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_SetInputHysteresis(COMP_TypeDef *COMPx, uint32_t InputHysteresis)
+{
+  MODIFY_REG(COMPx->CFGR, COMP_CFGRx_HYST, InputHysteresis);
+}
+
+/**
+  * @brief  Get comparator instance hysteresis mode of the minus (inverting) input.
+  * @rmtoll CSR      HYST           LL_COMP_GetInputHysteresis
+  * @param  COMPx Comparator instance
+  * @retval Returned value can be one of the following values:
+  *         @arg @ref LL_COMP_HYSTERESIS_NONE
+  *         @arg @ref LL_COMP_HYSTERESIS_LOW
+  *         @arg @ref LL_COMP_HYSTERESIS_MEDIUM
+  *         @arg @ref LL_COMP_HYSTERESIS_HIGH
+  */
+__STATIC_INLINE uint32_t LL_COMP_GetInputHysteresis(COMP_TypeDef *COMPx)
+{
+  return (uint32_t)(READ_BIT(COMPx->CFGR, COMP_CFGRx_HYST));
+}
+
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EF_Configuration_comparator_output Configuration of comparator output
+  * @{
+  */
+
+/**
+  * @brief  Set comparator instance output polarity.
+  * @rmtoll CFGRx    POLARITY       LL_COMP_SetOutputPolarity
+  * @param  COMPx Comparator instance
+  * @param  OutputPolarity This parameter can be one of the following values:
+  *         @arg @ref LL_COMP_OUTPUTPOL_NONINVERTED
+  *         @arg @ref LL_COMP_OUTPUTPOL_INVERTED
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_SetOutputPolarity(COMP_TypeDef *COMPx, uint32_t OutputPolarity)
+{
+  MODIFY_REG(COMPx->CFGR, COMP_CFGRx_POLARITY, OutputPolarity);
+}
+
+/**
+  * @brief  Get comparator instance output polarity.
+  * @rmtoll CFGRx    POLARITY       LL_COMP_GetOutputPolarity
+  * @param  COMPx Comparator instance
+  * @retval Returned value can be one of the following values:
+  *         @arg @ref LL_COMP_OUTPUTPOL_NONINVERTED
+  *         @arg @ref LL_COMP_OUTPUTPOL_INVERTED
+  */
+__STATIC_INLINE uint32_t LL_COMP_GetOutputPolarity(COMP_TypeDef *COMPx)
+{
+  return (uint32_t)(READ_BIT(COMPx->CFGR, COMP_CFGRx_POLARITY));
+}
+
+/**
+  * @brief  Set comparator instance blanking source.
+  * @note   Blanking source may be specific to each comparator instance.
+  *         Refer to description of parameters or to reference manual.
+  * @note   Availability of parameters of blanking source from timer
+  *         depends on timers availability on the selected device.
+  * @rmtoll CFGR     BLANKING       LL_COMP_SetOutputBlankingSource
+  * @param  COMPx Comparator instance
+  * @param  BlankingSource This parameter can be one of the following values:
+  *         @arg @ref LL_COMP_BLANKINGSRC_NONE
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM1_OC5  
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM2_OC3
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM3_OC3
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM3_OC4
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM8_OC5
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM15_OC1 
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_SetOutputBlankingSource(COMP_TypeDef *COMPx, uint32_t BlankingSource)
+{
+  MODIFY_REG(COMPx->CFGR, COMP_CFGRx_BLANKING, BlankingSource);
+}
+
+/**
+  * @brief  Get comparator instance blanking source.
+  * @note   Availability of parameters of blanking source from timer
+  *         depends on timers availability on the selected device.
+  * @note   Blanking source may be specific to each comparator instance.
+  *         Refer to description of parameters or to reference manual.
+  * @rmtoll CFGR     BLANKING       LL_COMP_GetOutputBlankingSource
+  * @param  COMPx Comparator instance
+  * @retval Returned value can be one of the following values:
+  *         @arg @ref LL_COMP_BLANKINGSRC_NONE
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM1_OC5 
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM2_OC3 
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM3_OC3
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM3_OC4 
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM8_OC5  
+  *         @arg @ref LL_COMP_BLANKINGSRC_TIM15_OC1  
+  */
+__STATIC_INLINE uint32_t LL_COMP_GetOutputBlankingSource(COMP_TypeDef *COMPx)
+{
+  return (uint32_t)(READ_BIT(COMPx->CFGR, COMP_CFGRx_BLANKING));
+}
+
+/** @brief  Set the output alternate function in the Option register
+  *         in order to be used with the alternate function
+  *         of the timer break input.
+  * @rmtoll OR    AFOP       COMP_LL_EC_OUTPUT_BKIN_TIMER
+  * @param  COMPx specifies the instance.
+  * @param  CompAFx specifies the Alternate Function source selection.
+  *          This parameter can be one of the following values:
+  *            @arg @ref LL_COMP_AF_PA6
+  *            @arg @ref LL_COMP_AF_PA8
+  *            @arg @ref LL_COMP_AF_PB12
+  *            @arg @ref LL_COMP_AF_PE6
+  *            @arg @ref LL_COMP_AF_PE15
+  *            @arg @ref LL_COMP_AF_PG2
+  *            @arg @ref LL_COMP_AF_PG3
+  *            @arg @ref LL_COMP_AF_PG4
+  *            @arg @ref LL_COMP_AF_PI1
+  *            @arg @ref LL_COMP_AF_PI4
+  *            @arg @ref LL_COMP_AF_PK2
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_SetOutputAlternateFunction(COMP_TypeDef *COMPx, uint32_t CompAFx)
+{
+  MODIFY_REG(COMP12->OR, 0x7FFUL, (COMPx == COMP1) ? ((~CompAFx) & 0x7FFUL) : CompAFx);
+}
+
+/** @brief  Get the output alternate function from the Option register.
+  * @rmtoll OR     AFOP       COMP_LL_EC_OUTPUT_BKIN_TIMER
+  * @param  COMPx specifies the Comparator instance.
+  * @retval Returned value can be one of the following values:
+  *            @arg @ref LL_COMP_AF_PA6
+  *            @arg @ref LL_COMP_AF_PA8
+  *            @arg @ref LL_COMP_AF_PB12
+  *            @arg @ref LL_COMP_AF_PE6
+  *            @arg @ref LL_COMP_AF_PE15
+  *            @arg @ref LL_COMP_AF_PG2
+  *            @arg @ref LL_COMP_AF_PG3
+  *            @arg @ref LL_COMP_AF_PG4
+  *            @arg @ref LL_COMP_AF_PI1
+  *            @arg @ref LL_COMP_AF_PI4
+  *            @arg @ref LL_COMP_AF_PK2
+  */
+__STATIC_INLINE uint32_t LL_COMP_GetOutputAlternateFunction(COMP_TypeDef *COMPx )
+{
+  return (uint32_t) ((COMPx == COMP1) ? ((~COMP12->OR) & 0x7FFUL) : (COMP12->OR &  0x7FFUL));
+}
+
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EF_Operation Operation on comparator instance
+  * @{
+  */
+
+/**
+  * @brief  Enable comparator instance.
+  * @note   After enable from off state, comparator requires a delay
+  *         to reach reach propagation delay specification.
+  *         Refer to device datasheet, parameter "tSTART".
+  * @rmtoll CFGR     EN             LL_COMP_Enable
+  * @param  COMPx Comparator instance
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_Enable(COMP_TypeDef *COMPx)
+{
+  SET_BIT(COMPx->CFGR, COMP_CFGRx_EN);
+}
+
+/**
+  * @brief  Disable comparator instance.
+  * @rmtoll CFGR     EN             LL_COMP_Disable
+  * @param  COMPx Comparator instance
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_Disable(COMP_TypeDef *COMPx)
+{
+  CLEAR_BIT(COMPx->CFGR, COMP_CFGRx_EN);
+}
+
+/**
+  * @brief  Get comparator enable state
+  *         (0: COMP is disabled, 1: COMP is enabled)
+  * @rmtoll CFGR     EN             LL_COMP_IsEnabled
+  * @param  COMPx Comparator instance
+  * @retval State of bit (1 or 0).
+  */
+__STATIC_INLINE uint32_t LL_COMP_IsEnabled(COMP_TypeDef *COMPx)
+{
+  return ((READ_BIT(COMPx->CFGR, COMP_CFGRx_EN) == (COMP_CFGRx_EN)) ? 1UL : 0UL);
+}
+
+/**
+  * @brief  Lock comparator instance.
+  * @note   Once locked, comparator configuration can be accessed in read-only.
+  * @note   The only way to unlock the comparator is a device hardware reset.
+  * @rmtoll CFGR     LOCK           LL_COMP_Lock
+  * @param  COMPx Comparator instance
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_Lock(COMP_TypeDef *COMPx)
+{
+  SET_BIT(COMPx->CFGR, COMP_CFGRx_LOCK);
+}
+
+/**
+  * @brief  Get comparator lock state
+  *         (0: COMP is unlocked, 1: COMP is locked).
+  * @note   Once locked, comparator configuration can be accessed in read-only.
+  * @note   The only way to unlock the comparator is a device hardware reset.
+  * @rmtoll CFGR     LOCK           LL_COMP_IsLocked
+  * @param  COMPx Comparator instance
+  * @retval State of bit (1 or 0).
+  */
+__STATIC_INLINE uint32_t LL_COMP_IsLocked(COMP_TypeDef *COMPx)
+{
+  return ((READ_BIT(COMPx->CFGR, COMP_CFGRx_LOCK) == (COMP_CFGRx_LOCK)) ? 1UL : 0UL);
+}
+
+/**
+  * @brief  Read comparator instance output level.
+  * @note   The comparator output level depends on the selected polarity
+  *         (Refer to function @ref LL_COMP_SetOutputPolarity()).
+  *         If the comparator polarity is not inverted:
+  *          - Comparator output is low when the input plus
+  *            is at a lower voltage than the input minus
+  *          - Comparator output is high when the input plus
+  *            is at a higher voltage than the input minus
+  *         If the comparator polarity is inverted:
+  *          - Comparator output is high when the input plus
+  *            is at a lower voltage than the input minus
+  *          - Comparator output is low when the input plus
+  *            is at a higher voltage than the input minus
+  * @rmtoll CFGR     VALUE          LL_COMP_ReadOutputLevel
+  * @param  COMPx Comparator instance
+  * @retval Returned value can be one of the following values:
+  *         @arg @ref LL_COMP_OUTPUT_LEVEL_LOW
+  *         @arg @ref LL_COMP_OUTPUT_LEVEL_HIGH
+  */
+__STATIC_INLINE uint32_t LL_COMP_ReadOutputLevel(COMP_TypeDef *COMPx)
+{
+  if (COMPx == COMP1)
+  {
+    return (uint32_t)(READ_BIT(COMP12->SR, COMP_SR_C1VAL));
+  }
+  else
+  {
+    return (uint32_t)((READ_BIT(COMP12->SR, COMP_SR_C2VAL))>> 1); 
+  }
+}
+
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EF_FLAG_Management Comparator flag Management
+  * @{
+  */
+
+/**
+  * @brief  Get comparator output trigger flag (latched)
+  * @rmtoll SR       C1IF           LL_COMP_IsActiveFlag_OutputTrig
+  * @param  COMPx Comparator instance
+  * @retval State of bit (1 or 0).
+  */
+__STATIC_INLINE uint32_t LL_COMP_IsActiveFlag_OutputTrig(COMP_TypeDef *COMPx)
+{
+   if (COMPx == COMP1)
+  {
+    return ((READ_BIT(COMP12->SR, COMP_SR_C1IF) == (COMP_SR_C1IF)) ? 1UL : 0UL);
+  }
+  else
+  {
+    return ((READ_BIT(COMP12->SR, COMP_SR_C2IF) == (COMP_SR_C2IF)) ? 1UL : 0UL);
+  }
+}
+
+/**
+  * @brief  Clear comparator comparator output trigger flag (latched)
+  * @rmtoll ICFR     CC1IF          LL_COMP_ClearFlag_OutputTrig
+  * @param  COMPx Comparator instance
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_ClearFlag_OutputTrig(COMP_TypeDef *COMPx)
+{
+  if (COMPx == COMP1)
+  {
+    SET_BIT(COMP12->ICFR, COMP_ICFR_C1IF);
+  }
+  else
+  {
+    SET_BIT(COMP12->ICFR, COMP_ICFR_C2IF);
+  }
+}
+
+/**
+  * @}
+  */
+
+/** @defgroup COMP_LL_EF_IT_Management Comparartor IT management
+  * @{
+  */
+
+/**
+  * @brief  Enable comparator output trigger interrupt
+  * @rmtoll ICFR     ITEN           LL_COMP_EnableIT_OutputTrig
+  * @param  COMPx Comparator instance
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_EnableIT_OutputTrig(COMP_TypeDef *COMPx)
+{
+  SET_BIT(COMPx->CFGR, COMP_CFGRx_ITEN);
+}
+
+/**
+  * @brief  Disable comparator output trigger interrupt
+  * @rmtoll ICFR     ITEN           LL_COMP_DisableIT_OutputTrig
+  * @param  COMPx Comparator instance
+  * @retval None
+  */
+__STATIC_INLINE void LL_COMP_DisableIT_OutputTrig(COMP_TypeDef *COMPx)
+{
+  CLEAR_BIT(COMPx->CFGR, COMP_CFGRx_ITEN);
+}
+
+/**
+  * @brief  Get comparator output trigger interrupt state
+  * @rmtoll ICFR     ITEN           LL_COMP_IsEnabledIT_OutputTrig
+  * @param  COMPx Comparator instance
+  * @retval State of bit (1 or 0).
+  */
+__STATIC_INLINE uint32_t LL_COMP_IsEnabledIT_OutputTrig(COMP_TypeDef *COMPx)
+{
+  return ((READ_BIT(COMPx->CFGR, COMP_CFGRx_ITEN) == (COMP_CFGRx_ITEN)) ? 1UL : 0UL);
+}
+
+/**
+  * @}
+  */
+  
+#if defined(USE_FULL_LL_DRIVER)
+/** @defgroup COMP_LL_EF_Init Initialization and de-initialization functions
+  * @{
+  */
+
+ErrorStatus LL_COMP_DeInit(COMP_TypeDef *COMPx);
+ErrorStatus LL_COMP_Init(COMP_TypeDef *COMPx, LL_COMP_InitTypeDef *COMP_InitStruct);
+void        LL_COMP_StructInit(LL_COMP_InitTypeDef *COMP_InitStruct);
+
+/**
+  * @}
+  */
+#endif /* USE_FULL_LL_DRIVER */
+
+/**
+  * @}
+  */
+
+/**
+  * @}
+  */
+
+#endif /* COMP1 || COMP2 */
+
+/**
+  * @}
+  */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __STM32H7xx_LL_COMP_H */
+
+

File diff suppressed because it is too large
+ 1247 - 0
OZE_Sensor/Drivers/STM32H7xx_HAL_Driver/Src/stm32h7xx_hal_comp.c


File diff suppressed because it is too large
+ 95 - 59
OZE_Sensor/OZE_Sensor.ioc