source: trunk/fw_g473rct/SES/src/main.c @ 24

Last change on this file since 24 was 24, checked in by f.jahn, 3 days ago

Shunt Temperatursensor aktiviert

File size: 17.2 KB
Line 
1/* USER CODE BEGIN Header */
2/**
3  ******************************************************************************
4  * @file           : main.c
5  * @brief          : Main program body
6  ******************************************************************************
7  * @attention
8  *
9  * Copyright (c) 2025 STMicroelectronics.
10  * All rights reserved.
11  *
12  * This software is licensed under terms that can be found in the LICENSE file
13  * in the root directory of this software component.
14  * If no LICENSE file comes with this software, it is provided AS-IS.
15  *
16  ******************************************************************************
17  */
18/* USER CODE END Header */
19/* Includes ------------------------------------------------------------------*/
20#include "main.h"
21#include "adc.h"
22#include "dma.h"
23#include "fdcan.h"
24#include "i2c.h"
25#include "spi.h"
26#include "usart.h"
27#include "usb.h"
28#include "gpio.h"
29
30/* Private includes ----------------------------------------------------------*/
31/* USER CODE BEGIN Includes */
32#include <stdio.h>
33#include "sysdata.h"
34#include "wh_counter.h"
35#include "ah_counter.h"
36#include "eeprom.h"
37#include "modbus.h"
38#include "chip_temperature.h"
39#include "battery_voltage.h"
40#include "ads1260.h"
41#include "shunt_voltage.h"
42#include "fast_current.h"
43#include "int_bat_voltage.h"
44#include "chip_temperature.h"
45#include "shunt_temperature.h"
46/* USER CODE END Includes */
47
48/* Private typedef -----------------------------------------------------------*/
49/* USER CODE BEGIN PTD */
50
51/* USER CODE END PTD */
52
53/* Private define ------------------------------------------------------------*/
54/* USER CODE BEGIN PD */
55
56/* USER CODE END PD */
57
58/* Private macro -------------------------------------------------------------*/
59/* USER CODE BEGIN PM */
60
61/* USER CODE END PM */
62
63/* Private variables ---------------------------------------------------------*/
64
65/* USER CODE BEGIN PV */
66modbus_t modbusData __attribute__((section(".RAM1")));
67
68__IO uint16_t adc12Data[100][2] __attribute__((section(".RAM1")));
69__IO uint32_t adc1Data[1] __attribute__((section(".RAM1")));
70__IO uint32_t adc2Data[1] __attribute__((section(".RAM1")));
71__IO uint32_t adc3Data[3] __attribute__((section(".RAM1")));
72__IO uint32_t adc4Data[1] __attribute__((section(".RAM1")));
73__IO uint32_t adc5Data[4] __attribute__((section(".RAM1")));
74int silentmode =0;
75static volatile uint32_t newADC12Data = 0;
76static volatile uint32_t newADC3Data = 0;
77static volatile uint32_t newADC4Data = 0;
78static volatile uint32_t newADC5Data = 0;
79/* USER CODE END PV */
80
81/* Private function prototypes -----------------------------------------------*/
82void SystemClock_Config(void);
83/* USER CODE BEGIN PFP */
84bool SetFlashReadProtection(bool state);
85uint8_t printprotectionstate(void);
86bool SetBootFromFlashAndReadOutProtection(void);
87/* USER CODE END PFP */
88
89/* Private user code ---------------------------------------------------------*/
90/* USER CODE BEGIN 0 */
91
92/* USER CODE END 0 */
93
94/**
95  * @brief  The application entry point.
96  * @retval int
97  */
98int main(void)
99{
100
101  /* USER CODE BEGIN 1 */
102    uint8_t firstStartCatcher;
103        int mode_button_disable_time=0;
104        uint32_t adc12_time;
105        uint32_t adc12_lasttime;
106  /* USER CODE END 1 */
107
108  /* MCU Configuration--------------------------------------------------------*/
109
110  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
111  HAL_Init();
112
113  /* USER CODE BEGIN Init */
114
115  /* USER CODE END Init */
116
117  /* Configure the system clock */
118  SystemClock_Config();
119
120  /* USER CODE BEGIN SysInit */
121
122  /* USER CODE END SysInit */
123
124  /* Initialize all configured peripherals */
125  MX_GPIO_Init();
126  MX_DMA_Init();
127  MX_ADC1_Init();
128  MX_ADC2_Init();
129  MX_ADC3_Init();
130  MX_ADC4_Init();
131  MX_ADC5_Init();
132  MX_FDCAN2_Init();
133  MX_FDCAN3_Init();
134  MX_I2C3_Init();
135  MX_I2C4_Init();
136  MX_SPI3_Init();
137  MX_USART1_UART_Init();
138  MX_USART2_UART_Init();
139  MX_USB_PCD_Init();
140  /* USER CODE BEGIN 2 */
141  printf("Test debug io\r\n");
142  SYS_DATA_Init();
143  WH_COUNTER_Init();
144  AH_COUNTER_Init();
145
146
147  startType_t startType = EEPROM_isFirstStart();
148
149  switch(startType)
150  {
151          case FIRST_START_AFTER_ERASE:                                 EEPROM_fullRestore(&sys_data);            break;
152          case FIRST_START_AFTER_COMPARTIBLE_UPDATE:    EEPROM_readConfig(&sys_data);             break;
153          case FIRST_START_AFTER_INCOMPARTIBLE_UPDATE:  EEPROM_factoryRestore(&sys_data, 0);  break;  // Preserving calibration and settings
154          case FIRST_START_ERROR:                                               EEPROM_fullRestore(&sys_data);            break;
155  }
156
157  if(HAL_GPIO_ReadPin(GPIO_INPUT_BTN_MODE_GPIO_Port, GPIO_INPUT_BTN_MODE_Pin) == GPIO_PIN_RESET)
158  {
159    HAL_Delay(50);
160    if(HAL_GPIO_ReadPin(GPIO_INPUT_BTN_MODE_GPIO_Port, GPIO_INPUT_BTN_MODE_Pin) == GPIO_PIN_RESET)
161    {
162      printf("factory restore...\n");
163      EEPROM_factoryRestore(&sys_data, 1);
164    }
165  }
166
167    // Modbus Initialisierung
168  mbInit(&modbusData, sys_data.s.parameter.baudrate, sys_data.s.parameter.parityMode, sys_data.s.parameter.stopBit, &huart2);
169
170    // STM32G0 Chiptemperatur Kalibrierung
171  CHIP_TEMPERATURE_Calibration();
172
173  HAL_ADCEx_Calibration_Start(&hadc1, ADC_DIFFERENTIAL_ENDED);
174  HAL_ADCEx_Calibration_Start(&hadc2, ADC_DIFFERENTIAL_ENDED);
175  HAL_ADCEx_Calibration_Start(&hadc3, ADC_SINGLE_ENDED);
176  HAL_ADCEx_Calibration_Start(&hadc4, ADC_DIFFERENTIAL_ENDED);
177  HAL_ADCEx_Calibration_Start(&hadc5, ADC_SINGLE_ENDED);
178
179
180  //SET_BIT(hadc2.Instance->CFGR, ADC_CFGR_DMAEN); //Enable DMA transfer for ADC slave (ADC12_CCR.MDMA = 0b00 -> MDMA mode disabled)
181  //HAL_DMA_Start(hadc2.DMA_Handle,(uint32_t)&hadc2.Instance->DR, (uint32_t)adc2Data,1); //Start ADC slave DMA
182  //SET_BIT(hadc1.Instance->CFGR, ADC_CFGR_DMAEN); //Enable DMA transfer for ADC master (ADC12_CCR.MDMA = 0b00 -> MDMA mode disabled)
183 
184    //HAL_ADC_Start_DMA(&hadc2, (uint32_t*)adc2Data, 1);
185  if (HAL_ADCEx_MultiModeStart_DMA(&hadc1,(uint32_t *)adc12Data,100))  //Start ADC interleaved mode
186  {
187     /* Start Error */
188     Error_Handler();
189  }
190
191  if (HAL_ADC_Start_DMA(&hadc3, (uint32_t *) adc3Data , 3))
192  {
193     /* Start Error */
194     Error_Handler();
195  }
196
197  if (HAL_ADC_Start_DMA(&hadc4, (uint32_t *) adc4Data , 1))
198  {
199     /* Start Error */
200     Error_Handler();
201  }
202
203
204  if (HAL_ADC_Start_DMA(&hadc5, (uint32_t *) adc5Data , 4))
205  {
206     /* Start Error */
207     Error_Handler();
208  }
209
210  /* USER CODE END 2 */
211
212  /* Infinite loop */
213  /* USER CODE BEGIN WHILE */
214  while (1)
215  {
216    /* USER CODE END WHILE */
217
218    /* USER CODE BEGIN 3 */
219        if (newADC12Data == 1)
220    {
221          //Mit ADC_DIV2,Sample time 12,5Cycklen, ADC Clock 50Mhz, Oversampling 256
222          //Tconv = 6400 Takte = 0,128ms Pro Konvertierung. Also für 100 messwerte 12,8mS
223          BATTERY_VOLTAGE_Exec( adc12Data[0][1]);
224          FAST_CURRENT_Exec(adc12Data[0][0]); 
225          newADC12Data = 0;
226          adc12_time = HAL_GetTick() - adc12_lasttime;
227          adc12_lasttime = HAL_GetTick();
228
229        }
230
231
232        if (newADC3Data == 1)
233    {
234          SHUNT_TEMPERATURE_Exec(adc3Data[0]);
235        }
236
237
238        if (newADC4Data == 1)
239    {
240          SHUNT_VOLTAGE_Exec( adc4Data[0]);
241        }
242
243
244        if (newADC5Data == 1)
245    {
246          CHIP_TEMPERATURE_Exec(adc5Data[0]);
247          INT_BAT_VOLTAGE_Exec( adc5Data[1]);
248          sys_data.s.values.ovp_sense =  (adc5Data[2] * VREF * 21 ) / 65536.0;
249      sys_data.s.values.lvp_sense =  (adc5Data[3] * VREF * 21 ) / 65536.0;
250        }
251
252        if(sys_data.s.parameter.command != 0)
253    {
254      if  (modbusData.current_query ==  MB_QUERY_NOTHING)
255      {
256        //printf("CMD = %d\n", sys_data.s.parameter.command);
257        switch (sys_data.s.parameter.command )
258        {
259          case COMMAND_STORE_CONFIG:                          EEPROM_storeConfig(&sys_data,0);                                                                                    break;
260          case COMMAND_FULL_RESTORE:                          EEPROM_fullRestore(&sys_data);                                                                                      break;
261          case COMMAND_FACTORY_RESTORE:                       EEPROM_factoryRestore(&sys_data, 1);                                                                                break;
262          case COMMAND_RESTORE_LAST_SAVED_VALUES:             EEPROM_readConfig(&sys_data);                                                                                               break;
263          case COMMAND_STORE_WITH_SERIAL_NUMBER:              EEPROM_storeConfig(&sys_data,1);                                                                                    break;        // Seriennummer schreiben
264          case COMMAND_RESTART:                               NVIC_SystemReset();                                                                                                                 break;
265          case COMMAND_BATTERY_CURRENT_OFFSET_CAL:            ADS_1260_BatteryCurrentOffsetCalibrationStart(&sys_data);                                   break;
266          case COMMAND_BATTERY_CURRENT_OFFSET_COMMONMODE_CAL: ADS_1260_BatteryCurrentOffsetCommonModeErrorComepensationStart(&sys_data);  break;
267          case COMMAND_BATTERY_CURRENT_OFFSET_TEMP_CAL:       ADS_1260_BatteryCurrentOffsetTemperatureErrorComepensationStart();                  break;
268          case COMMAND_BATTERY_CURRENT_GAIN_CAL:              ADS_1260_BatteryCurrentGainCalibrationStart(&sys_data);                                     break;
269          case COMMAND_BATTERY_CURRENT_GAIN_TEMP_SHUNT_CAL:   ADS_1260_BatteryCurrentGainTemperatureCalibrationShuntStart();                      break;
270//        case COMMAND_BATTERY_CURRENT_GAIN_TEMP_CHIP_CAL:    ADS_1260_BatteryCurrentGainTemperatureCalibrationChipStart(); break;
271          case COMMAND_SET_RDP_LEVEL0:                        SetFlashReadProtection(false);                                                                                      break;
272          case COMMAND_SET_RDP_LEVEL1:                        SetFlashReadProtection(true);                                                                                               break;
273          case COMMAND_SET_RDP_LEVEL1_AND_BOOTSEL:            SetBootFromFlashAndReadOutProtection();                                                                     break;
274          default:                                            printf("UNKNOWN COMMAND\n");
275        }
276        sys_data.s.parameter.command = 0;
277      }
278      else
279      {
280        //printf("wait with execution till modbus communnikation finished\n");
281      }
282    }
283
284    if((HAL_GPIO_ReadPin(GPIO_INPUT_BTN_MODE_GPIO_Port, GPIO_INPUT_BTN_MODE_Pin) == GPIO_PIN_RESET) && (mode_button_disable_time == 0))
285    {
286      HAL_Delay(10);
287      //Taste weiterhin gedrckt?
288      if(HAL_GPIO_ReadPin(GPIO_INPUT_BTN_MODE_GPIO_Port, GPIO_INPUT_BTN_MODE_Pin) == GPIO_PIN_RESET)
289      {
290        //Ja, dann Silent Mode umschalten
291        mode_button_disable_time=500;
292        if (silentmode == 0)
293        {
294          silentmode = 1;
295          HAL_GPIO_WritePin(LED_FUNC_GPIO_Port, LED_FUNC_Pin,GPIO_PIN_SET);
296        }
297        else
298        {
299          silentmode = 0;
300        }
301       }
302    }
303
304        // Modbus Kommunikation
305
306//      printf("data12d1=%d,data12d2=%d,data5=%d\r\n", adc12Data[0], adc12Data[1] , adc5Data[2]);
307    if (mbGetFrameComplete(&modbusData) == true)
308    {
309      if (mbSlaveCheckModbusRtuQuery(&modbusData) == RESPOND_TO_QUERY)
310      {
311          if (silentmode == 0)
312          {
313            mbSlaveProcessRtuQuery(&modbusData);
314          }
315      }
316      else
317      {
318        huart1.RxState = HAL_UART_STATE_BUSY_RX;
319      }
320    }
321
322  }
323  /* USER CODE END 3 */
324}
325
326/**
327  * @brief System Clock Configuration
328  * @retval None
329  */
330void SystemClock_Config(void)
331{
332  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
333  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
334
335  /** Configure the main internal regulator output voltage
336  */
337  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);
338
339  /** Initializes the RCC Oscillators according to the specified parameters
340  * in the RCC_OscInitTypeDef structure.
341  */
342  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48|RCC_OSCILLATORTYPE_HSE;
343  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
344  RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;
345  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
346  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
347  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV2;
348  RCC_OscInitStruct.PLL.PLLN = 16;
349  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
350  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
351  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
352  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
353  {
354    Error_Handler();
355  }
356
357  /** Initializes the CPU, AHB and APB buses clocks
358  */
359  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
360                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
361  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
362  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
363  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
364  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
365
366  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK)
367  {
368    Error_Handler();
369  }
370}
371
372/* USER CODE BEGIN 4 */
373 void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc)
374 {
375    if (hadc->Instance==ADC1)
376        {
377          newADC12Data=1;
378        }
379
380        if (hadc->Instance==ADC3)
381        {
382          newADC3Data=1;
383        }
384
385
386        if (hadc->Instance==ADC4)
387        {
388          newADC4Data=1;
389        }
390
391        if (hadc->Instance==ADC5)
392        {
393          newADC5Data=1;
394        }
395 }
396
397
398 
399/**
400
401  * @brief  Set flash read protection.
402
403  * @param  [in] state: Flash read protection state, true: enable protection, false: disable protection.
404
405  * @retval true:  Successful operation.
406
407  * @retval false: Operation failed.
408
409  */
410
411bool SetFlashReadProtection(bool state)
412{
413
414  FLASH_OBProgramInitTypeDef OptionsBytesStruct = {0};
415  HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);
416
417  if(state == true)
418  {
419    printf("Start enable readout protection\n");
420    if(OptionsBytesStruct.RDPLevel == OB_RDP_LEVEL_0)
421    {
422      OptionsBytesStruct.OptionType = OPTIONBYTE_RDP;
423      OptionsBytesStruct.RDPLevel   = OB_RDP_LEVEL_1;
424      if (HAL_FLASH_Unlock() != HAL_OK)
425      {
426        printf("Flash unlock error\n");
427      }
428      if (HAL_FLASH_OB_Unlock() != HAL_OK)
429      {
430        printf("Flash ob unlock error\n");
431      }
432
433      printf("...Flash unlock\n");
434      if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
435      {
436        printf("...Enable lock error\n");
437        HAL_FLASH_OB_Lock();
438        return false;
439      }
440      HAL_FLASH_OB_Lock();
441      printf("Flash Optionbyte locked\n");
442      HAL_FLASH_Lock();
443      printf("Flash  locked\n");
444      printf("...Enable lock process finished\n");
445    }
446    else
447    {
448      printf("...Flash lock already active\n");
449    }
450  }
451  else
452  {
453    if(OptionsBytesStruct.RDPLevel == OB_RDP_LEVEL_1)
454    {
455      OptionsBytesStruct.OptionType = OPTIONBYTE_RDP;
456      OptionsBytesStruct.RDPLevel   = OB_RDP_LEVEL_0;
457
458      if (HAL_FLASH_Unlock() != HAL_OK)
459      {
460        printf("Flash unlock error\n");
461        return false;
462      }
463      printf("...Flash unlocked\n");
464
465      if (HAL_FLASH_OB_Unlock() != HAL_OK)
466      {
467        printf("Flash ob unlock error\n");
468        return false;
469      }
470      printf("...Flash ob unlocked\n");
471
472      if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
473      {
474        HAL_FLASH_OB_Lock();
475        printf("Flash Optionbyte programm failed\n");
476        return false;
477      }
478
479      printf("Flash Optionbyte programmed\n");
480      HAL_FLASH_OB_Lock();
481      printf("Flash Optionbyte locked\n");
482      HAL_FLASH_Lock();
483      printf("Flash  locked\n");
484      printf("...Disable lock process finished\n");
485
486;
487    }
488  }
489  return true;
490}
491
492bool SetBootFromFlashAndReadOutProtection(void)
493{
494
495  FLASH_OBProgramInitTypeDef OptionsBytesStruct = {0};
496  HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);
497
498  //Konfiguriere RDP fr Readoutprotection and USER OPTION BYTE FR Boot from Flash
499  OptionsBytesStruct.OptionType = OPTIONBYTE_USER | OPTIONBYTE_RDP;
500
501  //Set Readout Protection Level 1
502  OptionsBytesStruct.OptionType = OPTIONBYTE_USER|OPTIONBYTE_RDP;
503  OptionsBytesStruct.RDPLevel   = OB_RDP_LEVEL_1;
504
505  //Selecting Boot from Main Flash Memory
506  OptionsBytesStruct.USERType =    OB_USER_nBOOT0 | OB_USER_nSWBOOT0 | OB_USER_nBOOT1 ;
507  OptionsBytesStruct.USERConfig  = OB_USER_nBOOT0 | OB_USER_nSWBOOT0;
508
509  if (HAL_FLASH_Unlock() != HAL_OK)
510  {
511    printf("Flash unlock error\n");
512  }
513  if (HAL_FLASH_OB_Unlock() != HAL_OK)
514  {
515    printf("Flash ob unlock error\n");
516  }
517
518  printf("...Flash unlock\n");
519  if(HAL_FLASHEx_OBProgram(&OptionsBytesStruct) != HAL_OK)
520  {
521    printf("...Enable lock error\n");
522    HAL_FLASH_OB_Lock();
523    return false;
524  }
525  HAL_FLASH_OB_Lock();
526  printf("Flash Optionbyte locked\n");
527  HAL_FLASH_Lock();
528  printf("Flash  locked\n");
529  printf("...Enable lock process finished\n");
530
531  return true;
532}
533uint8_t printprotectionstate(void)
534{
535  FLASH_OBProgramInitTypeDef OptionsBytesStruct = {0};
536  HAL_FLASHEx_OBGetConfig(&OptionsBytesStruct);
537  uint8_t result = 0;
538
539  if(OptionsBytesStruct.RDPLevel == OB_RDP_LEVEL_0)
540  {
541    //OptionsBytesStruct.OptionType = OPTIONBYTE_RDP;
542    //OptionsBytesStruct.RDPLevel   = OB_RDP_LEVEL_1;
543    printf("PROTECTION: OB_RDP_LEVEL_0\n");
544    result = 0;
545  }
546  else if(OptionsBytesStruct.RDPLevel == OB_RDP_LEVEL_1)
547  {
548    printf("PROTECTION: OB_RDP_LEVEL_1\n");
549    result = 1;
550  }
551  else if(OptionsBytesStruct.RDPLevel == OB_RDP_LEVEL_2)
552  {
553    printf("PROTECTION: OB_RDP_LEVEL_2\n");
554    result = 2;
555  }
556  return  result;
557}
558
559/* USER CODE END 4 */
560
561/**
562  * @brief  This function is executed in case of error occurrence.
563  * @retval None
564  */
565void Error_Handler(void)
566{
567  /* USER CODE BEGIN Error_Handler_Debug */
568  /* User can add his own implementation to report the HAL error return state */
569  __disable_irq();
570  printf("error handler!\r\n");
571  while (1)
572  {
573  }
574  /* USER CODE END Error_Handler_Debug */
575}
576#ifdef USE_FULL_ASSERT
577/**
578  * @brief  Reports the name of the source file and the source line number
579  *         where the assert_param error has occurred.
580  * @param  file: pointer to the source file name
581  * @param  line: assert_param error line source number
582  * @retval None
583  */
584void assert_failed(uint8_t *file, uint32_t line)
585{
586  /* USER CODE BEGIN 6 */
587  /* User can add his own implementation to report the file name and line number,
588     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
589         printf("Wrong parameters value: file %s on line %d\r\n", file, line);
590  /* USER CODE END 6 */
591}
592#endif /* USE_FULL_ASSERT */
Note: See TracBrowser for help on using the repository browser.