You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

main.c 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. /* USER CODE BEGIN Header */
  2. /**
  3. ******************************************************************************
  4. * @file : main.c
  5. * @brief : Main program body
  6. ******************************************************************************
  7. * @attention
  8. *
  9. * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  10. * All rights reserved.</center></h2>
  11. *
  12. * This software component is licensed by ST under BSD 3-Clause license,
  13. * the "License"; You may not use this file except in compliance with the
  14. * License. You may obtain a copy of the License at:
  15. * opensource.org/licenses/BSD-3-Clause
  16. *
  17. ******************************************************************************
  18. */
  19. /* USER CODE END Header */
  20. /* Includes ------------------------------------------------------------------*/
  21. #include "main.h"
  22. #include "fatfs.h"
  23. /* Private includes ----------------------------------------------------------*/
  24. /* USER CODE BEGIN Includes */
  25. #include "math.h"
  26. #include "stdbool.h"
  27. #include "string.h"
  28. #include <stdio.h>
  29. #include "fatfs_sd.h"
  30. #include <stdarg.h>
  31. /* USER CODE END Includes */
  32. /* Private typedef -----------------------------------------------------------*/
  33. /* USER CODE BEGIN PTD */
  34. /* USER CODE END PTD */
  35. /* Private define ------------------------------------------------------------*/
  36. /* USER CODE BEGIN PD */
  37. /* USER CODE END PD */
  38. /* Private macro -------------------------------------------------------------*/
  39. /* USER CODE BEGIN PM */
  40. /* USER CODE END PM */
  41. /* Private variables ---------------------------------------------------------*/
  42. SPI_HandleTypeDef hspi1;
  43. ADC_HandleTypeDef hadc1;
  44. RTC_HandleTypeDef hrtc;
  45. UART_HandleTypeDef huart2;
  46. /* USER CODE BEGIN PV */
  47. RTC_TimeTypeDef sTime;
  48. RTC_DateTypeDef sDate;
  49. RTC_AlarmTypeDef sAlarmA, sAlarmB;
  50. static volatile uint16_t gLastError;
  51. static volatile bool gButtonPressed = FALSE;
  52. //Nuremberg coordinates
  53. int latitude_nbg = 49;
  54. int longitude_nbg = 11;
  55. //German UTC time,summer (+2) and winter (+1)
  56. int UTC_DER_sum = 2;
  57. int UTC_DER_win = 1;
  58. bool winterTime = true;
  59. int DaysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  60. int DaysInMonthLeapYear[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
  61. bool leapYear = false;
  62. int stepsFor180Deg = 1600; // The stepper motor needs 200 single steps for 360 deg, equals 100 steps for 180 deg, 180 Deg in 1/16 steps equals 1600 1/16 steps
  63. int leapsFor180Deg = 5; // Determines how big the amount of single steps is to complete 180 degrees of rotation
  64. bool alarmSunriseFlag = false;
  65. bool alarmSunsetFlag = false;
  66. bool makeStepFlag = false;
  67. /* Initialization parameters. */
  68. l6208_Init_t initDeviceParameters =
  69. {
  70. 1500, //Acceleration rate in step/s^2 or (1/16)th step/s^2 for microstep modes
  71. 20, //Acceleration current torque in % (from 0 to 100)
  72. 1500, //Deceleration rate in step/s^2 or (1/16)th step/s^2 for microstep modes
  73. 20, //Deceleration current torque in % (from 0 to 100)
  74. 1500, //Running speed in step/s or (1/16)th step/s for microstep modes
  75. 10, //Running current torque in % (from 0 to 100)
  76. 5, //Holding current torque in % (from 0 to 100)
  77. STEP_MODE_1_16, //Step mode via enum motorStepMode_t
  78. FAST_DECAY, //Decay mode via enum motorDecayMode_t
  79. 0, //Dwelling time in ms
  80. FALSE, //Automatic HIZ STOP
  81. 100000 //VREFA and VREFB PWM frequency (Hz)
  82. };
  83. typedef struct {
  84. int hours;
  85. int minutes;
  86. int seconds;
  87. int weekDay;
  88. int month;
  89. int day;
  90. int year;
  91. } timeAndDate;
  92. // SD CARD Variables
  93. FATFS fs;
  94. FATFS *pfs;
  95. FIL fil;
  96. FRESULT fres;
  97. DWORD fre_clust;
  98. uint32_t totalSpace, freeSpace;
  99. char buffer[100];
  100. uint16_t AD_RES;
  101. int num;
  102. char filename[12];
  103. /* USER CODE END PV */
  104. /* Private function prototypes -----------------------------------------------*/
  105. void SystemClock_Config(void);
  106. static void MX_GPIO_Init(void);
  107. static void MX_USART2_UART_Init(void);
  108. static void MX_RTC_Init(void);
  109. static void MX_SPI1_Init(void);
  110. static void MX_ADC1_Init(void);
  111. static void MyFlagInterruptHandler(void);
  112. void MyErrorHandler(uint16_t error);
  113. void ButtonHandler(void);
  114. /* USER CODE BEGIN PFP */
  115. /* USER CODE END PFP */
  116. /* Private user code ---------------------------------------------------------*/
  117. /* USER CODE BEGIN 0 */
  118. /*******************************************************************************
  119. * Function Name : deg_to_rad
  120. * Description : converts degrees to radians
  121. * Return : angle in radians
  122. *******************************************************************************/
  123. double deg_to_rad(double deg)
  124. {
  125. double rad = deg*(M_PI/180);
  126. return rad;
  127. }
  128. /*******************************************************************************
  129. * Function Name : rad_to_deg
  130. * Description : converts radians to degrees
  131. * Return : angle in degrees
  132. *******************************************************************************/
  133. double rad_to_deg(double rad)
  134. {
  135. double deg = rad*(180/M_PI);
  136. return deg;
  137. }
  138. /*******************************************************************************
  139. * Function Name : leap_year_check
  140. * Description : checks if year is a leap year
  141. * Return : false: no leap year, true: leap year
  142. *******************************************************************************/
  143. void leap_year_check(int initialyear)
  144. {
  145. int year = initialyear;
  146. if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
  147. {
  148. leapYear = true;
  149. }
  150. else
  151. {
  152. leapYear = false;
  153. }
  154. }
  155. /*******************************************************************************
  156. * Function Name : calc_day_of_year
  157. * Description : calculates the day of year
  158. * Return : day of year (1.1.. = 1, 2.1.. = 2,...)
  159. * Source : https://overiq.com/c-examples/c-program-to-calculate-the-day-of-year-from-the-date/
  160. *******************************************************************************/
  161. int calc_day_of_year(int day, int mon, int year)
  162. {
  163. int days_in_feb = 28;
  164. int doy = day; //day of year
  165. // check for leap year
  166. //bool leap_year = leap_year_check(year);
  167. if(leapYear == true)
  168. {
  169. days_in_feb = 29;
  170. }
  171. switch(mon)
  172. {
  173. case 2:
  174. doy += 31;
  175. break;
  176. case 3:
  177. doy += 31+days_in_feb;
  178. break;
  179. case 4:
  180. doy += days_in_feb+62;
  181. break;
  182. case 5:
  183. doy += days_in_feb+92;
  184. break;
  185. case 6:
  186. doy += days_in_feb+123;
  187. break;
  188. case 7:
  189. doy += days_in_feb+153;
  190. break;
  191. case 8:
  192. doy += days_in_feb+184;
  193. break;
  194. case 9:
  195. doy += days_in_feb+215;
  196. break;
  197. case 10:
  198. doy += days_in_feb+245;
  199. break;
  200. case 11:
  201. doy += days_in_feb+276;
  202. break;
  203. case 12:
  204. doy += days_in_feb+306;
  205. break;
  206. }
  207. return doy;
  208. }
  209. /*******************************************************************************
  210. * Function Name : calc_sunrise_sunset
  211. * Description : calculates the sunrise and sunset time of a specific date
  212. * Source : General Solar Position Calculations, NOAA Global Monitoring Division
  213. *******************************************************************************/
  214. void calc_sunrise_sunset(timeAndDate* initialDate, timeAndDate* sunriseStruct, timeAndDate* sunsetStruct, timeAndDate* tomorrowsDate)
  215. {
  216. double gamma = 0;
  217. double eqtime = 0;
  218. double decl = 0;
  219. //double decl_deg = 0;
  220. double zenith_sun = 0;
  221. double lat_nbg_rad = 0;
  222. double ha = 0;
  223. double sunrise = 0;
  224. double sunset = 0;
  225. double ha_deg = 0;
  226. int sunrise_h = 0;
  227. int sunset_h = 0;
  228. double sunrise_min = 0;
  229. double sunset_min = 0;
  230. int int_sunrise_min = 0;
  231. int int_sunset_min = 0;
  232. int day = initialDate->day;
  233. int month = initialDate->month;
  234. int year = initialDate->year;
  235. //day of year calculation
  236. int day_of_year = calc_day_of_year(day, month, year);
  237. // fractional year (γ) in radians
  238. // check for leap year
  239. //leap_year = leap_year_check(year);
  240. if(leapYear == false)
  241. {
  242. //The back part of the formula was omitted, because there is no difference in the result
  243. gamma = ((2 * M_PI)/365)*(day_of_year - 1);
  244. } else {
  245. //The back part of the formula was omitted, because there is no difference in the result
  246. gamma = ((2 * M_PI)/366)*(day_of_year - 1);
  247. }
  248. //Equation of time in minutes
  249. eqtime = 229.18*(0.000075 + 0.001868*cos(gamma) - 0.032077*sin(gamma) - 0.014615*cos(2*gamma) - 0.040849*sin(2*gamma));
  250. //Solar declination angle in radians
  251. decl = 0.006918 - 0.399912*cos(gamma) + 0.070257*sin(gamma) - 0.006758*cos(2*gamma) + 0.000907*sin(2*gamma) - 0.002697*cos(3*gamma) + 0.00148*sin(3*gamma);
  252. //Solar declination angle in degrees
  253. //decl_deg = rad_to_deg(decl);
  254. //Hour angle in degrees, positive number corresponds to sunrise, negative to sunset
  255. //special case of sunrise or sunset, the zenith is set to 90.833Deg
  256. zenith_sun = deg_to_rad(90.833);
  257. //Latitude of Nuernberg in rad
  258. lat_nbg_rad = deg_to_rad(latitude_nbg);
  259. ha = acos((cos(zenith_sun)/(cos(lat_nbg_rad)*cos(decl)))-(tan(lat_nbg_rad)*tan(decl)));
  260. ha_deg = rad_to_deg(ha);
  261. //UTC time of sunrise (or sunset) in minutes
  262. sunrise = (720-4*(longitude_nbg+ha_deg)-eqtime);
  263. sunset = 720-4*(longitude_nbg-ha_deg)-eqtime;
  264. //Convert sunrise (or sunset) UTC time in hours
  265. sunrise = sunrise/60;
  266. sunset = sunset/60;
  267. //Seperate hours and minutes
  268. sunrise_h = floor(sunrise);
  269. sunrise_min = sunrise - sunrise_h;
  270. //Cut off after two decimal places
  271. int_sunrise_min = floor(sunrise_min * 100.0);
  272. if (int_sunrise_min >= 60)
  273. {
  274. sunrise_h = sunrise_h + 1;
  275. int_sunrise_min = int_sunrise_min - 60;
  276. }
  277. sunset_h = floor(sunset);
  278. sunset_min = sunset - sunset_h;
  279. //Cut off after two decimal places
  280. int_sunset_min = floor(sunset_min * 100.0);
  281. if (int_sunset_min >= 60)
  282. {
  283. sunset_h = sunset_h + 1;
  284. int_sunset_min = int_sunset_min - 60;
  285. }
  286. //Add time difference from German time to UTC Time
  287. //Private variable winterTime must be initialized accordingly
  288. if (winterTime)
  289. {
  290. sunrise_h = sunrise_h + UTC_DER_win;
  291. sunset_h = sunset_h + UTC_DER_win;
  292. } else {
  293. sunrise_h = sunrise_h + UTC_DER_sum;
  294. sunset_h = sunset_h + UTC_DER_sum;
  295. }
  296. sunriseStruct->hours = sunrise_h;
  297. sunriseStruct->minutes = int_sunrise_min;
  298. sunsetStruct->hours = sunset_h;
  299. sunsetStruct->minutes = int_sunset_min;
  300. sunriseStruct->day = sunsetStruct->day = tomorrowsDate->day;
  301. sunriseStruct->weekDay = sunsetStruct->weekDay = tomorrowsDate->weekDay;
  302. sunriseStruct->month = sunsetStruct->month = tomorrowsDate->month;
  303. sunriseStruct->year = sunsetStruct->year = tomorrowsDate->year;
  304. }
  305. /*******************************************************************************
  306. * Function Name : calc_tomorrows_date
  307. * Description : calculates tomorrow's date
  308. * Source : https://github.com/vyacht/stm32/blob/master/vynmea/rtc.c
  309. *******************************************************************************/
  310. void calc_tomorrows_date(timeAndDate* initialDate, timeAndDate* tomorrowsDate)
  311. {
  312. int yearToUse[12];
  313. if (leapYear == true){
  314. memcpy(yearToUse, DaysInMonthLeapYear, sizeof yearToUse);
  315. } else {
  316. memcpy(yearToUse, DaysInMonth, sizeof yearToUse);
  317. }
  318. int day = initialDate->day;
  319. int wday = initialDate->weekDay;
  320. int month = initialDate->month;
  321. int year = initialDate->year;
  322. day++; // next day
  323. wday++; // next weekday
  324. if(wday == 8)
  325. {
  326. wday = 1; // Monday
  327. }
  328. if(day > yearToUse[month-1])
  329. { // next month
  330. day = 1;
  331. month++;
  332. }
  333. if(day > 31 && month == 12) // next year
  334. {
  335. day = 1;
  336. month = 1;
  337. year++;
  338. }
  339. tomorrowsDate->day = day;
  340. tomorrowsDate->weekDay = wday;
  341. tomorrowsDate->month = month;
  342. tomorrowsDate->year = year;
  343. }
  344. /*******************************************************************************
  345. * Function Name : set_alarm
  346. * Description : sets alarm A or B
  347. *******************************************************************************/
  348. void set_alarm(int h, int min, int weekDay, char* alarm, RTC_AlarmTypeDef* alarmInstance)
  349. {
  350. /** Enable the Alarm A*/
  351. alarmInstance->AlarmTime.Hours = h;
  352. alarmInstance->AlarmTime.Minutes = min;
  353. alarmInstance->AlarmTime.Seconds = 0;
  354. alarmInstance->AlarmTime.SubSeconds = 0;
  355. alarmInstance->AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  356. alarmInstance->AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET;
  357. alarmInstance->AlarmMask = RTC_ALARMMASK_NONE; //only by specific time
  358. alarmInstance->AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
  359. alarmInstance->AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_WEEKDAY;
  360. alarmInstance->AlarmDateWeekDay = weekDay;
  361. if (strcmp("A", alarm) == 0) {
  362. alarmInstance->Alarm = RTC_ALARM_A;
  363. } else {
  364. alarmInstance->Alarm = RTC_ALARM_B;
  365. }
  366. if (HAL_RTC_SetAlarm_IT(&hrtc, alarmInstance, RTC_FORMAT_BIN) != HAL_OK)
  367. {
  368. Error_Handler();
  369. }
  370. }
  371. /*******************************************************************************
  372. * Function Name : transmit_uart
  373. * Description : Transmit a string over uart
  374. *******************************************************************************/
  375. void transmit_uart(char *string){
  376. uint8_t len = strlen(string);
  377. HAL_UART_Transmit(&huart2, (uint8_t*) string, len, 200);
  378. }
  379. /***************************************************************************************************
  380. * Function Name : set_time_and_date
  381. * Description : Overwriting the date given in timeanddate with the current time and date from rtc
  382. ****************************************************************************************************/
  383. void set_time_and_date(timeAndDate *timeanddate){
  384. if (HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN) == HAL_OK)
  385. {
  386. timeanddate->hours = sTime.Hours;
  387. timeanddate->minutes = sTime.Minutes;
  388. timeanddate->seconds = sTime.Seconds;
  389. }
  390. if (HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN) == HAL_OK)
  391. {
  392. timeanddate->weekDay = sDate.WeekDay;
  393. timeanddate->month = sDate.Month;
  394. timeanddate->day = sDate.Date;
  395. timeanddate->year = 2000 + sDate.Year;
  396. }
  397. }
  398. /*******************************************************************************
  399. * Function Name : calc_interval_duration
  400. * Description : Calculate the duration between the two given time/dates
  401. * Return : The duration as an integer
  402. *******************************************************************************/
  403. int calc_interval_duration(timeAndDate *sunrise, timeAndDate *sunset){
  404. int duration_h=0;
  405. int duration_m=0;
  406. duration_h = sunset->hours - sunrise->hours;
  407. duration_m = sunset->minutes - sunrise->minutes;
  408. if (duration_m < 0) {
  409. duration_h = duration_h - 1;
  410. duration_m = 60 - sunrise->minutes + sunset->minutes;
  411. }
  412. return (duration_h * 60 + duration_m) / leapsFor180Deg;
  413. }
  414. /*******************************************************************************
  415. * Function Name : generate_filename
  416. * Description : Short function to generate a filename with the current date
  417. *******************************************************************************/
  418. void generate_filename(timeAndDate *date){
  419. sprintf(filename, "%02d%02d%02d.txt", date->year, date->month, date->day);
  420. }
  421. /* USER CODE END 0 */
  422. /**
  423. * @brief The application entry point.
  424. * @retval int
  425. */
  426. int main(void)
  427. {
  428. /* USER CODE BEGIN 1 */
  429. /* USER CODE END 1 */
  430. /* MCU Configuration--------------------------------------------------------*/
  431. /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  432. HAL_Init();
  433. /* USER CODE BEGIN Init */
  434. /* USER CODE END Init */
  435. /* Configure the system clock */
  436. SystemClock_Config();
  437. /* USER CODE BEGIN SysInit */
  438. /* USER CODE END SysInit */
  439. /* Initialize all configured peripherals */
  440. MX_GPIO_Init();
  441. MX_USART2_UART_Init();
  442. MX_RTC_Init();
  443. MX_SPI1_Init();
  444. MX_FATFS_Init();
  445. MX_ADC1_Init();
  446. /* USER CODE BEGIN 2 */
  447. //######### Inits of the Motor control library #########
  448. /* Set the L6208 library to use 1 device */
  449. BSP_MotorControl_SetNbDevices(BSP_MOTOR_CONTROL_BOARD_ID_L6208, 1);
  450. BSP_MotorControl_Init(BSP_MOTOR_CONTROL_BOARD_ID_L6208, &initDeviceParameters);
  451. //BSP_MotorControl_Init(BSP_MOTOR_CONTROL_BOARD_ID_L6208, NULL); //Default params
  452. /* Attach the function MyFlagInterruptHandler (defined below) to the flag interrupt */
  453. BSP_MotorControl_AttachFlagInterrupt(MyFlagInterruptHandler);
  454. /* Attach the function MyErrorHandler (defined below) to the error Handler*/
  455. BSP_MotorControl_AttachErrorHandler(MyErrorHandler);
  456. /* Set Systick Interrupt priority highest to ensure no lock by using HAL_Delay */
  457. HAL_NVIC_SetPriority(SysTick_IRQn, 0x0, 0x0);
  458. /* Configure KEY Button */
  459. //BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);
  460. /* Disable the power bridges after initialization */
  461. BSP_MotorControl_CmdDisable(0);
  462. int32_t pos=0;
  463. uint32_t freqPwm=0;
  464. freqPwm = BSP_MotorControl_GetBridgeInputPwmFreq(0);
  465. BSP_MotorControl_SetBridgeInputPwmFreq(0, freqPwm>>1);
  466. // current position
  467. pos = BSP_MotorControl_GetPosition(0);
  468. // set current position to home
  469. BSP_MotorControl_SetHome(0, pos);
  470. //######### Mount SD-Card #########
  471. /* The SD Card is not working at the moment due to getting FR_NOT_READY
  472. * when connecting the SD Card Pins with the SPI Pins on the mounted X-NUCLEO Motor driver.
  473. * When dismounting the motor driver and connecting it via cables, there is unusual behaviour of the motor mnovement.
  474. * The SD Card though, works when the SD Card Breakout is connected directly to the NUCLEO board.
  475. *
  476. fres = f_mount(&fs, "", 0);
  477. if (fres == FR_OK) {
  478. transmit_uart("SD card is mounted successfully!\r\n");
  479. } else if (fres != FR_OK) {
  480. transmit_uart("SD card is not mounted!\r\n");
  481. }
  482. */
  483. //######### Start ADC Conversion #########
  484. HAL_ADC_Start(&hadc1);
  485. //######### Variable inits #########
  486. timeAndDate sunrise, sunset, wakeUpTimeForStep, tomorrowsDate, initialDate;
  487. sunrise = sunset = wakeUpTimeForStep = tomorrowsDate = initialDate = (timeAndDate) {\
  488. 0,
  489. 0,
  490. 0,
  491. 0,
  492. 0,
  493. 0,
  494. 0
  495. };
  496. uint32_t timeToNextStep_m=0;
  497. uint32_t alarmB_h = 0;
  498. uint32_t alarmB_m = 0;
  499. uint32_t alarmB_wd = 0;
  500. uint32_t stepsToMake = stepsFor180Deg / leapsFor180Deg; // The amount of single steps to make to complete 180/x degrees ^= 1600/x
  501. /* USER CODE END 2 */
  502. /* Infinite loop */
  503. /* USER CODE BEGIN WHILE */
  504. while (1)
  505. {
  506. HAL_Delay(2000);
  507. transmit_uart("Resetting motor position and calculating new dates and times.\r\n");
  508. BSP_MotorControl_GoHome(0);
  509. BSP_MotorControl_WaitWhileActive(0);
  510. /* USER CODE END WHILE */
  511. /* USER CODE BEGIN 3 */
  512. set_time_and_date(&initialDate);
  513. leap_year_check(initialDate.year);
  514. calc_tomorrows_date(&initialDate, &tomorrowsDate);
  515. generate_filename(&tomorrowsDate);
  516. //######### SD Card Write #########
  517. /* The SD Card is not working at the moment due to getting FR_NOT_READY
  518. * when connecting the SD Card Pins with the SPI Pins on the mounted X-NUCLEO Motor driver.
  519. * When dismounting the motor driver and connecting it via cables, there is unusual behaviour of the motor mnovement.
  520. * The SD Card though, works when the SD Card Breakout is connected directly to the NUCLEO board.
  521. *
  522. // Open file with tomorrows date as file name
  523. fres = f_open(&fil, filename, FA_OPEN_APPEND | FA_WRITE | FA_READ);
  524. if (fres == FR_OK) {
  525. transmit_uart("File opened.\r\n");
  526. } else if (fres != FR_OK) {
  527. transmit_uart("File was not opened!\r\n");
  528. }
  529. f_puts("Data", &fil);
  530. //Close file
  531. fres = f_close(&fil);
  532. if (fres == FR_OK) {
  533. transmit_uart("File is closed.\r\n");
  534. } else if (fres != FR_OK) {
  535. transmit_uart("File was not closed.\r\n");
  536. }
  537. */
  538. //Calculate sunrise and sunset time for tomorrow
  539. calc_sunrise_sunset(&initialDate, &sunrise, &sunset, &tomorrowsDate);
  540. //Test code
  541. sunrise.hours = 14;
  542. sunrise.minutes = 0;
  543. sunrise.weekDay = 7;
  544. sunset.hours = 16;
  545. sunset.minutes = 00;
  546. sunset.weekDay = 7;
  547. //Calculate the time for next motor step in minutes
  548. timeToNextStep_m = calc_interval_duration(&sunrise, &sunset);
  549. // Set Alarm for sunrise
  550. transmit_uart("Setting alarm for sunrise.\r\n");
  551. set_alarm(sunrise.hours, sunrise.minutes, sunrise.weekDay, "A", &sAlarmA);
  552. HAL_Delay(2000);
  553. transmit_uart("Entering sleep mode.\r\n");
  554. HAL_SuspendTick();
  555. HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI);
  556. HAL_ResumeTick();
  557. if (alarmSunriseFlag == true) {
  558. transmit_uart("Sunrise statement entered.\r\n");
  559. // Reset the flags
  560. alarmSunsetFlag = false;
  561. alarmSunriseFlag = false;
  562. // The alarm for the next step is incremented from sunrise as the initial time.
  563. alarmB_h = sunrise.hours;
  564. alarmB_m = sunrise.minutes;
  565. alarmB_wd = sunrise.weekDay;
  566. // Set Alarm for sunset, it overwrites the alarm for sunrise because the sunrise already happenend
  567. // The timeframes for both alarms dont overlap so 1 alarm is enough
  568. transmit_uart("Setting alarm for sunset.\r\n");
  569. set_alarm(sunset.hours, sunset.minutes, sunset.weekDay, "A", &sAlarmA);
  570. HAL_Delay(2000);
  571. while (alarmSunsetFlag != true) {
  572. transmit_uart("|--------------------------------------------------------|\r\n\r\n");
  573. // Increment alarm time with the precalculated timeToNextStep
  574. int minAdd_tmp=0;
  575. minAdd_tmp = alarmB_m + timeToNextStep_m;
  576. // Consider minutes overflow ^= hours + 1
  577. if (minAdd_tmp > 60) {
  578. alarmB_h = alarmB_h + 1;
  579. alarmB_m = minAdd_tmp - 60;
  580. } else {
  581. alarmB_m = minAdd_tmp;
  582. }
  583. transmit_uart("Setting alarm for next step.\r\n");
  584. set_alarm(alarmB_h, alarmB_m, alarmB_wd, "B", &sAlarmB);
  585. HAL_Delay(2000);
  586. transmit_uart("Entering sleep mode.\r\n");
  587. HAL_SuspendTick();
  588. HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI);
  589. HAL_ResumeTick();
  590. if (makeStepFlag) {
  591. // Poll ADC1 Perihperal & TimeOut = 1mSec
  592. HAL_ADC_PollForConversion(&hadc1, 1);
  593. // Read The ADC Conversion Result
  594. AD_RES = HAL_ADC_GetValue(&hadc1);
  595. transmit_uart("Making a step.\r\n");
  596. BSP_MotorControl_Move(0, FORWARD, stepsToMake);
  597. BSP_MotorControl_WaitWhileActive(0);
  598. }
  599. makeStepFlag = true;
  600. transmit_uart("\r\n");
  601. };
  602. }
  603. BSP_MotorControl_GoHome(0);
  604. BSP_MotorControl_WaitWhileActive(0);
  605. }
  606. /* USER CODE END 3 */
  607. }
  608. /**
  609. * @brief System Clock Configuration
  610. * @retval None
  611. */
  612. void SystemClock_Config(void)
  613. {
  614. RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  615. RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  616. RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
  617. /** Configure the main internal regulator output voltage
  618. */
  619. __HAL_RCC_PWR_CLK_ENABLE();
  620. __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
  621. /** Initializes the RCC Oscillators according to the specified parameters
  622. * in the RCC_OscInitTypeDef structure.
  623. */
  624. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
  625. RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  626. //RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  627. RCC_OscInitStruct.HSICalibrationValue = 16;
  628. RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  629. RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  630. RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  631. RCC_OscInitStruct.PLL.PLLM = 16;
  632. RCC_OscInitStruct.PLL.PLLN = 336;
  633. RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
  634. RCC_OscInitStruct.PLL.PLLQ = 7;
  635. if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  636. {
  637. Error_Handler();
  638. }
  639. /** Initializes the CPU, AHB and APB buses clocks
  640. */
  641. RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  642. |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  643. RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  644. RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  645. RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  646. RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  647. if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  648. {
  649. Error_Handler();
  650. }
  651. PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
  652. PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
  653. if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
  654. {
  655. Error_Handler();
  656. }
  657. }
  658. /**
  659. * @brief RTC Initialization Function
  660. * @param None
  661. * @retval None
  662. */
  663. static void MX_RTC_Init(void)
  664. {
  665. /* USER CODE BEGIN RTC_Init 0 */
  666. /* USER CODE END RTC_Init 0 */
  667. RTC_TimeTypeDef sTime = {0};
  668. RTC_DateTypeDef sDate = {0};
  669. RTC_AlarmTypeDef sAlarm = {0};
  670. /* USER CODE BEGIN RTC_Init 1 */
  671. /* USER CODE END RTC_Init 1 */
  672. /** Initialize RTC Only
  673. */
  674. hrtc.Instance = RTC;
  675. hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
  676. hrtc.Init.AsynchPrediv = 127;
  677. hrtc.Init.SynchPrediv = 255;
  678. hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
  679. hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
  680. hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
  681. if (HAL_RTC_Init(&hrtc) != HAL_OK)
  682. {
  683. Error_Handler();
  684. }
  685. /* USER CODE BEGIN Check_RTC_BKUP */
  686. /* USER CODE END Check_RTC_BKUP */
  687. /** Initialize RTC and set the Time and Date
  688. */
  689. sTime.Hours = 13;
  690. sTime.Minutes = 56;
  691. sTime.Seconds = 10;
  692. sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  693. sTime.StoreOperation = RTC_STOREOPERATION_RESET;
  694. if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN) != HAL_OK)
  695. {
  696. Error_Handler();
  697. }
  698. sDate.WeekDay = RTC_WEEKDAY_SUNDAY;
  699. sDate.Month = RTC_MONTH_FEBRUARY;
  700. sDate.Date = 21;
  701. sDate.Year = 21;
  702. if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BIN) != HAL_OK)
  703. {
  704. Error_Handler();
  705. }
  706. /** Enable the Alarm A
  707. */
  708. sAlarm.AlarmTime.Hours = 0;
  709. sAlarm.AlarmTime.Minutes = 0;
  710. sAlarm.AlarmTime.Seconds = 0;
  711. sAlarm.AlarmTime.SubSeconds = 0;
  712. sAlarm.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  713. sAlarm.AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET;
  714. sAlarm.AlarmMask = RTC_ALARMMASK_NONE;
  715. sAlarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
  716. sAlarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE;
  717. sAlarm.AlarmDateWeekDay = 1;
  718. sAlarm.Alarm = RTC_ALARM_A;
  719. if (HAL_RTC_SetAlarm_IT(&hrtc, &sAlarm, RTC_FORMAT_BIN) != HAL_OK)
  720. {
  721. Error_Handler();
  722. }
  723. /** Enable the Alarm B
  724. */
  725. sAlarm.AlarmDateWeekDay = 1;
  726. sAlarm.Alarm = RTC_ALARM_B;
  727. if (HAL_RTC_SetAlarm_IT(&hrtc, &sAlarm, RTC_FORMAT_BIN) != HAL_OK)
  728. {
  729. Error_Handler();
  730. }
  731. /* USER CODE BEGIN RTC_Init 2 */
  732. /* USER CODE END RTC_Init 2 */
  733. }
  734. /**
  735. * @brief USART2 Initialization Function
  736. * @param None
  737. * @retval None
  738. */
  739. static void MX_USART2_UART_Init(void)
  740. {
  741. /* USER CODE BEGIN USART2_Init 0 */
  742. /* USER CODE END USART2_Init 0 */
  743. /* USER CODE BEGIN USART2_Init 1 */
  744. /* USER CODE END USART2_Init 1 */
  745. huart2.Instance = USART2;
  746. huart2.Init.BaudRate = 115200;
  747. huart2.Init.WordLength = UART_WORDLENGTH_8B;
  748. huart2.Init.StopBits = UART_STOPBITS_1;
  749. huart2.Init.Parity = UART_PARITY_NONE;
  750. huart2.Init.Mode = UART_MODE_TX_RX;
  751. huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  752. huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  753. if (HAL_UART_Init(&huart2) != HAL_OK)
  754. {
  755. Error_Handler();
  756. }
  757. /* USER CODE BEGIN USART2_Init 2 */
  758. /* USER CODE END USART2_Init 2 */
  759. }
  760. /**
  761. * @brief GPIO Initialization Function
  762. * @param None
  763. * @retval None
  764. */
  765. static void MX_GPIO_Init(void)
  766. {
  767. GPIO_InitTypeDef GPIO_InitStruct = {0};
  768. /* GPIO Ports Clock Enable */
  769. __HAL_RCC_GPIOC_CLK_ENABLE();
  770. __HAL_RCC_GPIOH_CLK_ENABLE();
  771. __HAL_RCC_GPIOA_CLK_ENABLE();
  772. __HAL_RCC_GPIOB_CLK_ENABLE();
  773. /*Configure GPIO pin Output Level */
  774. HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
  775. /*Configure GPIO pin Output Level */
  776. HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);
  777. /*Configure GPIO pin : B1_Pin */
  778. GPIO_InitStruct.Pin = B1_Pin;
  779. GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
  780. GPIO_InitStruct.Pull = GPIO_NOPULL;
  781. HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
  782. /*Configure GPIO pin : LD2_Pin */
  783. GPIO_InitStruct.Pin = LD2_Pin;
  784. GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  785. GPIO_InitStruct.Pull = GPIO_NOPULL;
  786. GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  787. HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);
  788. /*Configure GPIO pin : PB6 */
  789. GPIO_InitStruct.Pin = GPIO_PIN_6;
  790. GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  791. GPIO_InitStruct.Pull = GPIO_NOPULL;
  792. GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
  793. HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
  794. }
  795. /**
  796. * @brief ADC1 Initialization Function
  797. * @param None
  798. * @retval None
  799. */
  800. static void MX_ADC1_Init(void)
  801. {
  802. /* USER CODE BEGIN ADC1_Init 0 */
  803. /* USER CODE END ADC1_Init 0 */
  804. ADC_ChannelConfTypeDef sConfig = {0};
  805. /* USER CODE BEGIN ADC1_Init 1 */
  806. /* USER CODE END ADC1_Init 1 */
  807. /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
  808. */
  809. hadc1.Instance = ADC1;
  810. hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
  811. hadc1.Init.Resolution = ADC_RESOLUTION_12B;
  812. hadc1.Init.ScanConvMode = DISABLE;
  813. hadc1.Init.ContinuousConvMode = ENABLE;
  814. hadc1.Init.DiscontinuousConvMode = DISABLE;
  815. hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  816. hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  817. hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  818. hadc1.Init.NbrOfConversion = 1;
  819. hadc1.Init.DMAContinuousRequests = DISABLE;
  820. hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  821. if (HAL_ADC_Init(&hadc1) != HAL_OK)
  822. {
  823. Error_Handler();
  824. }
  825. /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
  826. */
  827. sConfig.Channel = ADC_CHANNEL_0;
  828. sConfig.Rank = 1;
  829. sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
  830. if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  831. {
  832. Error_Handler();
  833. }
  834. /* USER CODE BEGIN ADC1_Init 2 */
  835. /* USER CODE END ADC1_Init 2 */
  836. }
  837. /**
  838. * @brief SPI1 Initialization Function
  839. * @param None
  840. * @retval None
  841. */
  842. static void MX_SPI1_Init(void)
  843. {
  844. /* USER CODE BEGIN SPI1_Init 0 */
  845. /* USER CODE END SPI1_Init 0 */
  846. /* USER CODE BEGIN SPI1_Init 1 */
  847. /* USER CODE END SPI1_Init 1 */
  848. /* SPI1 parameter configuration*/
  849. hspi1.Instance = SPI1;
  850. hspi1.Init.Mode = SPI_MODE_MASTER;
  851. hspi1.Init.Direction = SPI_DIRECTION_2LINES;
  852. hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  853. hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
  854. hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
  855. hspi1.Init.NSS = SPI_NSS_SOFT;
  856. hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
  857. hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  858. hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  859. hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  860. hspi1.Init.CRCPolynomial = 10;
  861. if (HAL_SPI_Init(&hspi1) != HAL_OK)
  862. {
  863. Error_Handler();
  864. }
  865. /* USER CODE BEGIN SPI1_Init 2 */
  866. /* USER CODE END SPI1_Init 2 */
  867. }
  868. /* USER CODE BEGIN 4 */
  869. /**
  870. * @brief Alarm callback
  871. * @param hrtc: RTC handle
  872. * @retval None
  873. */
  874. void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
  875. {
  876. /* Alarm generation */
  877. alarmSunriseFlag = true;
  878. alarmSunsetFlag = true;
  879. transmit_uart("Alarm A Callback triggered.\r\n");
  880. transmit_uart("Setting sunrise and sunset flags.\r\n");
  881. }
  882. void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc)
  883. {
  884. /* Alarm generation */
  885. makeStepFlag = true;
  886. transmit_uart("Alarm B Callback triggered.\r\n");
  887. transmit_uart("Setting makeStep flag.\r\n");
  888. }
  889. /**
  890. * @brief This function is the User handler for the flag interrupt
  891. * @param None
  892. * @retval None
  893. */
  894. void MyFlagInterruptHandler(void)
  895. {
  896. //When EN pin is forced low by a failure, configure the GPIO as an ouput low
  897. BSP_MotorControl_CmdDisable(0);
  898. }
  899. /* USER CODE END 4 */
  900. /**
  901. * @brief This function is executed in case of error occurrence.
  902. * @retval None
  903. */
  904. void Error_Handler(void)
  905. {
  906. /* USER CODE BEGIN Error_Handler_Debug */
  907. /* User can add his own implementation to report the HAL error return state */
  908. __disable_irq();
  909. while (1)
  910. {
  911. }
  912. /* USER CODE END Error_Handler_Debug */
  913. }
  914. void MyErrorHandler(uint16_t error)
  915. {
  916. // Motor error handler
  917. /* Backup error number */
  918. gLastError = error;
  919. /* Infinite loop */
  920. while(1)
  921. {
  922. }
  923. }
  924. void ButtonHandler(void)
  925. {
  926. gButtonPressed = TRUE;
  927. /* Let 200 ms before clearing the IT for key debouncing */
  928. HAL_Delay(200);
  929. __HAL_GPIO_EXTI_CLEAR_IT(KEY_BUTTON_PIN);
  930. HAL_NVIC_ClearPendingIRQ(KEY_BUTTON_EXTI_IRQn);
  931. }
  932. #ifdef USE_FULL_ASSERT
  933. /**
  934. * @brief Reports the name of the source file and the source line number
  935. * where the assert_param error has occurred.
  936. * @param file: pointer to the source file name
  937. * @param line: assert_param error line source number
  938. * @retval None
  939. */
  940. void assert_failed(uint8_t *file, uint32_t line)
  941. {
  942. /* USER CODE BEGIN 6 */
  943. /* User can add his own implementation to report the file name and line number,
  944. ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  945. /* USER CODE END 6 */
  946. }
  947. #endif /* USE_FULL_ASSERT */
  948. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/