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 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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 hadc;
  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 singleStepsFor180Deg = 100; // The stepper motor needs 200 single steps for 360 deg, equals 100 steps for 180 deg
  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. typedef struct {
  68. int hours;
  69. int minutes;
  70. int seconds;
  71. int weekDay;
  72. int month;
  73. int day;
  74. int year;
  75. } timeAndDate;
  76. typedef struct {
  77. char hours[10];
  78. char minutes[10];
  79. char seconds[10];
  80. char *fullTimeStamp;
  81. } timeStamp;
  82. timeStamp time;
  83. // SD CARD Variables
  84. FATFS fs;
  85. FATFS *pfs;
  86. FIL fil;
  87. FRESULT fres;
  88. DWORD fre_clust;
  89. uint32_t totalSpace, freeSpace;
  90. char buffer[100];
  91. uint16_t AD_RES;
  92. int num;
  93. //Variable name for txt file
  94. char txtVar[19];
  95. /* USER CODE END PV */
  96. /* Private function prototypes -----------------------------------------------*/
  97. void SystemClock_Config(void);
  98. static void MX_GPIO_Init(void);
  99. static void MX_USART2_UART_Init(void);
  100. static void MX_RTC_Init(void);
  101. static void MX_SPI1_Init(void);
  102. static void MX_ADC_Init(void);
  103. static void MyFlagInterruptHandler(void);
  104. void ButtonHandler(void);
  105. /* USER CODE BEGIN PFP */
  106. /* USER CODE END PFP */
  107. /* Private user code ---------------------------------------------------------*/
  108. /* USER CODE BEGIN 0 */
  109. /*******************************************************************************
  110. * Function Name : deg_to_rad
  111. * Description : converts degrees to radians
  112. * Return : angle in radians
  113. *******************************************************************************/
  114. double deg_to_rad(double deg)
  115. {
  116. double rad = deg*(M_PI/180);
  117. return rad;
  118. }
  119. /*******************************************************************************
  120. * Function Name : rad_to_deg
  121. * Description : converts radians to degrees
  122. * Return : angle in degrees
  123. *******************************************************************************/
  124. double rad_to_deg(double rad)
  125. {
  126. double deg = rad*(180/M_PI);
  127. return deg;
  128. }
  129. /*******************************************************************************
  130. * Function Name : leap_year_check
  131. * Description : checks if year is a leap year
  132. * Return : false: no leap year, true: leap year
  133. *******************************************************************************/
  134. void leap_year_check(int initialyear)
  135. {
  136. int year = initialyear;
  137. if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
  138. {
  139. leapYear = true;
  140. }
  141. else
  142. {
  143. leapYear = false;
  144. }
  145. }
  146. /*******************************************************************************
  147. * Function Name : calc_day_of_year
  148. * Description : calculates the day of year
  149. * Return : day of year (1.1.. = 1, 2.1.. = 2,...)
  150. * Source : https://overiq.com/c-examples/c-program-to-calculate-the-day-of-year-from-the-date/
  151. *******************************************************************************/
  152. int calc_day_of_year(int day, int mon, int year)
  153. {
  154. int days_in_feb = 28;
  155. int doy = day; //day of year
  156. // check for leap year
  157. //bool leap_year = leap_year_check(year);
  158. if(leapYear == true)
  159. {
  160. days_in_feb = 29;
  161. }
  162. switch(mon)
  163. {
  164. case 2:
  165. doy += 31;
  166. break;
  167. case 3:
  168. doy += 31+days_in_feb;
  169. break;
  170. case 4:
  171. doy += days_in_feb+62;
  172. break;
  173. case 5:
  174. doy += days_in_feb+92;
  175. break;
  176. case 6:
  177. doy += days_in_feb+123;
  178. break;
  179. case 7:
  180. doy += days_in_feb+153;
  181. break;
  182. case 8:
  183. doy += days_in_feb+184;
  184. break;
  185. case 9:
  186. doy += days_in_feb+215;
  187. break;
  188. case 10:
  189. doy += days_in_feb+245;
  190. break;
  191. case 11:
  192. doy += days_in_feb+276;
  193. break;
  194. case 12:
  195. doy += days_in_feb+306;
  196. break;
  197. }
  198. return doy;
  199. }
  200. /*******************************************************************************
  201. * Function Name : calc_sunrise_sunset
  202. * Description : calculates the sunrise and sunset time of a specific date
  203. * Source : General Solar Position Calculations, NOAA Global Monitoring Division
  204. *******************************************************************************/
  205. void calc_sunrise_sunset(timeAndDate* initialDate, timeAndDate* sunriseStruct, timeAndDate* sunsetStruct, timeAndDate* tomorrowsDate)
  206. {
  207. double gamma = 0;
  208. double eqtime = 0;
  209. double decl = 0;
  210. //double decl_deg = 0;
  211. double zenith_sun = 0;
  212. double lat_nbg_rad = 0;
  213. double ha = 0;
  214. double sunrise = 0;
  215. double sunset = 0;
  216. double ha_deg = 0;
  217. int sunrise_h = 0;
  218. int sunset_h = 0;
  219. double sunrise_min = 0;
  220. double sunset_min = 0;
  221. int int_sunrise_min = 0;
  222. int int_sunset_min = 0;
  223. int day = initialDate->day;
  224. int month = initialDate->month;
  225. int year = initialDate->year;
  226. //day of year calculation
  227. int day_of_year = calc_day_of_year(day, month, year);
  228. // fractional year (γ) in radians
  229. // check for leap year
  230. //leap_year = leap_year_check(year);
  231. if(leapYear == false)
  232. {
  233. //The back part of the formula was omitted, because there is no difference in the result
  234. gamma = ((2 * M_PI)/365)*(day_of_year - 1);
  235. } else {
  236. //The back part of the formula was omitted, because there is no difference in the result
  237. gamma = ((2 * M_PI)/366)*(day_of_year - 1);
  238. }
  239. //Equation of time in minutes
  240. eqtime = 229.18*(0.000075 + 0.001868*cos(gamma) - 0.032077*sin(gamma) - 0.014615*cos(2*gamma) - 0.040849*sin(2*gamma));
  241. //Solar declination angle in radians
  242. 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);
  243. //Solar declination angle in degrees
  244. //decl_deg = rad_to_deg(decl);
  245. //Hour angle in degrees, positive number corresponds to sunrise, negative to sunset
  246. //special case of sunrise or sunset, the zenith is set to 90.833Deg
  247. zenith_sun = deg_to_rad(90.833);
  248. //Latitude of Nuernberg in rad
  249. lat_nbg_rad = deg_to_rad(latitude_nbg);
  250. ha = acos((cos(zenith_sun)/(cos(lat_nbg_rad)*cos(decl)))-(tan(lat_nbg_rad)*tan(decl)));
  251. ha_deg = rad_to_deg(ha);
  252. //UTC time of sunrise (or sunset) in minutes
  253. sunrise = (720-4*(longitude_nbg+ha_deg)-eqtime);
  254. sunset = 720-4*(longitude_nbg-ha_deg)-eqtime;
  255. //Convert sunrise (or sunset) UTC time in hours
  256. sunrise = sunrise/60;
  257. sunset = sunset/60;
  258. //Seperate hours and minutes
  259. sunrise_h = floor(sunrise);
  260. sunrise_min = sunrise - sunrise_h;
  261. //Cut off after two decimal places
  262. int_sunrise_min = floor(sunrise_min * 100.0);
  263. if (int_sunrise_min >= 60)
  264. {
  265. sunrise_h = sunrise_h + 1;
  266. int_sunrise_min = int_sunrise_min - 60;
  267. }
  268. sunset_h = floor(sunset);
  269. sunset_min = sunset - sunset_h;
  270. //Cut off after two decimal places
  271. int_sunset_min = floor(sunset_min * 100.0);
  272. if (int_sunset_min >= 60)
  273. {
  274. sunset_h = sunset_h + 1;
  275. int_sunset_min = int_sunset_min - 60;
  276. }
  277. //Add time difference from German time to UTC Time
  278. //Private variable winterTime must be initialized accordingly
  279. if (winterTime)
  280. {
  281. sunrise_h = sunrise_h + UTC_DER_win;
  282. sunset_h = sunset_h + UTC_DER_win;
  283. } else {
  284. sunrise_h = sunrise_h + UTC_DER_sum;
  285. sunset_h = sunset_h + UTC_DER_sum;
  286. }
  287. sunriseStruct->hours = sunrise_h;
  288. sunriseStruct->minutes = int_sunrise_min;
  289. sunsetStruct->hours = sunset_h;
  290. sunsetStruct->minutes = int_sunset_min;
  291. sunriseStruct->day = sunsetStruct->day = tomorrowsDate->day;
  292. sunriseStruct->weekDay = sunsetStruct->weekDay = tomorrowsDate->weekDay;
  293. sunriseStruct->month = sunsetStruct->month = tomorrowsDate->month;
  294. sunriseStruct->year = sunsetStruct->year = tomorrowsDate->year;
  295. }
  296. /*******************************************************************************
  297. * Function Name : calc_tomorrows_date
  298. * Description : calculates tomorrow's date
  299. * Source : https://github.com/vyacht/stm32/blob/master/vynmea/rtc.c
  300. *******************************************************************************/
  301. void calc_tomorrows_date(timeAndDate* initialDate, timeAndDate* tomorrowsDate)
  302. {
  303. int yearToUse[12];
  304. if (leapYear == true){
  305. memcpy(yearToUse, DaysInMonthLeapYear, sizeof yearToUse);
  306. } else {
  307. memcpy(yearToUse, DaysInMonth, sizeof yearToUse);
  308. }
  309. int day = initialDate->day;
  310. int wday = initialDate->weekDay;
  311. int month = initialDate->month;
  312. int year = initialDate->year;
  313. day++; // next day
  314. wday++; // next weekday
  315. if(wday == 8)
  316. {
  317. wday = 1; // Monday
  318. }
  319. if(day > yearToUse[month-1])
  320. { // next month
  321. day = 1;
  322. month++;
  323. }
  324. if(day > 31 && month == 12) // next year
  325. {
  326. day = 1;
  327. month = 1;
  328. year++;
  329. }
  330. tomorrowsDate->day = day;
  331. tomorrowsDate->weekDay = wday;
  332. tomorrowsDate->month = month;
  333. tomorrowsDate->year = year;
  334. }
  335. /*******************************************************************************
  336. * Function Name : set_Alarm
  337. * Description : sets the wake up Alarm
  338. *******************************************************************************/
  339. void set_alarm(int h, int min, int weekDay, char* alarm, RTC_AlarmTypeDef* alarmInstance)
  340. {
  341. /** Enable the Alarm A*/
  342. alarmInstance->AlarmTime.Hours = h;
  343. alarmInstance->AlarmTime.Minutes = min;
  344. alarmInstance->AlarmTime.Seconds = 0;
  345. alarmInstance->AlarmTime.SubSeconds = 0;
  346. alarmInstance->AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  347. alarmInstance->AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET;
  348. alarmInstance->AlarmMask = RTC_ALARMMASK_NONE; //only by specific time
  349. alarmInstance->AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
  350. alarmInstance->AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_WEEKDAY;
  351. alarmInstance->AlarmDateWeekDay = weekDay;
  352. if (strcmp("A", alarm) == 0) {
  353. alarmInstance->Alarm = RTC_ALARM_A;
  354. } else {
  355. alarmInstance->Alarm = RTC_ALARM_B;
  356. }
  357. if (HAL_RTC_SetAlarm_IT(&hrtc, alarmInstance, RTC_FORMAT_BIN) != HAL_OK)
  358. {
  359. Error_Handler();
  360. }
  361. }
  362. void get_time(timeStamp *time){
  363. char str[200];
  364. if (HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN) == HAL_OK)
  365. {
  366. sprintf(time->hours, "%d", sTime.Hours);
  367. sprintf(time->minutes, "%d", sTime.Minutes);
  368. sprintf(time->seconds, "%d", sTime.Seconds);
  369. }
  370. strcpy(str, time->hours);
  371. strcat(str, ":");
  372. strcat(str, time->minutes);
  373. strcat(str, ":");
  374. strcat(str, time->seconds);
  375. strcat(str, " | ");
  376. time->fullTimeStamp = str;
  377. }
  378. // sending to UART
  379. void transmit_uart(char *string){
  380. //char str[200];
  381. //get_time(&time);
  382. //strcat(time.fullTimeStamp, string);
  383. //strcpy(str, time.fullTimeStamp);
  384. uint8_t len = strlen(string);
  385. HAL_UART_Transmit(&huart2, (uint8_t*) string, len, 200);
  386. }
  387. void set_time_and_date(timeAndDate *timeanddate){
  388. if (HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN) == HAL_OK)
  389. {
  390. timeanddate->hours = sTime.Hours;
  391. timeanddate->minutes = sTime.Minutes;
  392. timeanddate->seconds = sTime.Seconds;
  393. }
  394. if (HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN) == HAL_OK)
  395. {
  396. timeanddate->weekDay = sDate.WeekDay;
  397. timeanddate->month = sDate.Month;
  398. timeanddate->day = sDate.Date;
  399. timeanddate->year = 2000 + sDate.Year;
  400. }
  401. }
  402. int calc_interval_duration(timeAndDate *sunrise, timeAndDate *sunset){
  403. int duration_h=0;
  404. int duration_m=0;
  405. duration_h = sunset->hours - sunrise->hours;
  406. duration_m = sunset->minutes - sunrise->minutes;
  407. if (duration_m < 0) {
  408. duration_h = duration_h - 1;
  409. duration_m = 60 - sunrise->minutes + sunset->minutes;
  410. }
  411. return (duration_h * 60 + duration_m) / leapsFor180Deg;
  412. }
  413. char int_to_char_and_concat(int amount, char* separator, ...){
  414. va_list argumentlist;
  415. va_start(argumentlist, separator);
  416. char str[200] = "";
  417. while (amount--){
  418. char arg = va_arg(argumentlist, char);
  419. strcat(str, arg);
  420. strcat(str, separator);
  421. }
  422. return str;
  423. }
  424. /* USER CODE END 0 */
  425. /**
  426. * @brief The application entry point.
  427. * @retval int
  428. */
  429. int main(void)
  430. {
  431. /* USER CODE BEGIN 1 */
  432. /* USER CODE END 1 */
  433. /* MCU Configuration--------------------------------------------------------*/
  434. /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  435. HAL_Init();
  436. /* USER CODE BEGIN Init */
  437. /* USER CODE END Init */
  438. /* Configure the system clock */
  439. SystemClock_Config();
  440. /* USER CODE BEGIN SysInit */
  441. /* USER CODE END SysInit */
  442. /* Initialize all configured peripherals */
  443. MX_GPIO_Init();
  444. MX_USART2_UART_Init();
  445. MX_RTC_Init();
  446. MX_SPI1_Init();
  447. MX_FATFS_Init();
  448. MX_ADC_Init();
  449. /* USER CODE BEGIN 2 */
  450. //######### Inits of the Motor control library #########
  451. /* Set the L6208 library to use 1 device */
  452. BSP_MotorControl_SetNbDevices(BSP_MOTOR_CONTROL_BOARD_ID_L6208, 1);
  453. BSP_MotorControl_Init(BSP_MOTOR_CONTROL_BOARD_ID_L6208, NULL);
  454. /* Attach the function MyFlagInterruptHandler (defined below) to the flag interrupt */
  455. BSP_MotorControl_AttachFlagInterrupt(MyFlagInterruptHandler);
  456. /* Attach the function MyErrorHandler (defined below) to the error Handler*/
  457. BSP_MotorControl_AttachErrorHandler(Error_Handler);
  458. /* Set Systick Interrupt priority highest to ensure no lock by using HAL_Delay */
  459. HAL_NVIC_SetPriority(SysTick_IRQn, 0x0, 0x0);
  460. /* Configure KEY Button */
  461. BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);
  462. /* Disable the power bridges after initialization */
  463. BSP_MotorControl_CmdDisable(0);
  464. //######### Mount SD-Card #########
  465. fres = f_mount(&fs, "", 0);
  466. if (fres == FR_OK) {
  467. transmit_uart("SD card is mounted successfully!\r\n");
  468. } else if (fres != FR_OK) {
  469. transmit_uart("SD card is not mounted!\r\n");
  470. }
  471. //######### Variable inits #########
  472. timeAndDate sunrise, sunset, wakeUpTimeForStep, tomorrowsDate, initialDate;
  473. sunrise = sunset = wakeUpTimeForStep = tomorrowsDate = initialDate = (timeAndDate) {\
  474. 0,
  475. 0,
  476. 0,
  477. 0,
  478. 0,
  479. 0,
  480. 0
  481. };
  482. int32_t pos=0;
  483. uint32_t freqPwm=0;
  484. uint32_t timeToNextStep_m=0;
  485. uint32_t alarmB_h = 0;
  486. uint32_t alarmB_m = 0;
  487. uint32_t alarmB_wd = 0;
  488. uint32_t stepsToMake = singleStepsFor180Deg / leapsFor180Deg; // The amount of single steps to make to complete 180/5 degrees
  489. /* USER CODE END 2 */
  490. /* Infinite loop */
  491. /* USER CODE BEGIN WHILE */
  492. while (1)
  493. {
  494. //######### Motor settings and motor test #########
  495. HAL_Delay(2000);
  496. transmit_uart("Resetting motor position and calculating new dates and times.\r\n");
  497. freqPwm = BSP_MotorControl_GetBridgeInputPwmFreq(0);
  498. BSP_MotorControl_SetBridgeInputPwmFreq(0, freqPwm>>1);
  499. pos = BSP_MotorControl_GetPosition(0);
  500. BSP_MotorControl_SetHome(0, pos);
  501. BSP_MotorControl_SelectStepMode(0, STEP_MODE_FULL);
  502. BSP_MotorControl_Move(0, FORWARD, stepsToMake);
  503. BSP_MotorControl_WaitWhileActive(0);
  504. BSP_MotorControl_Move(0, FORWARD, stepsToMake);
  505. BSP_MotorControl_WaitWhileActive(0);
  506. BSP_MotorControl_Move(0, FORWARD, stepsToMake);
  507. BSP_MotorControl_WaitWhileActive(0);
  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. //Calculate sunrise and sunset time for tomorrow
  516. calc_sunrise_sunset(&initialDate, &sunrise, &sunset, &tomorrowsDate);
  517. //Test code
  518. sunrise.hours = 14;
  519. sunrise.minutes = 0;
  520. sunrise.weekDay = 7;
  521. sunset.hours = 14;
  522. sunset.minutes = 30;
  523. sunset.weekDay = 7;
  524. //Calculate the time for next motor step in minutes
  525. timeToNextStep_m = calc_interval_duration(&sunrise, &sunset);
  526. // Set Alarm for sunrise
  527. transmit_uart("Setting alarm for sunrise.\r\n");
  528. set_alarm(sunrise.hours, sunrise.minutes, sunrise.weekDay, "A", &sAlarmA);
  529. HAL_Delay(2000);
  530. transmit_uart("Entering sleep mode.\r\n");
  531. HAL_SuspendTick();
  532. HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI);
  533. HAL_ResumeTick();
  534. if (alarmSunriseFlag == true) {
  535. transmit_uart("Sunrise statement entered.\r\n");
  536. // Reset the flags
  537. alarmSunsetFlag = false;
  538. alarmSunriseFlag = false;
  539. // The alarm for the next step is incremented from sunrise as the initial time.
  540. alarmB_h = sunrise.hours;
  541. alarmB_m = sunrise.minutes;
  542. alarmB_wd = sunrise.weekDay;
  543. // Set Alarm for sunset, it overwrites the alarm for sunrise because the sunrise already happenend
  544. // The timeframes for both alarms dont overlap so 1 alarm is enough
  545. transmit_uart("Setting alarm for sunset.\r\n");
  546. set_alarm(sunset.hours, sunset.minutes, sunset.weekDay, "A", &sAlarmA);
  547. HAL_Delay(2000);
  548. while (alarmSunsetFlag != true) {
  549. transmit_uart("|--------------------------------------------------------|\r\n\r\n");
  550. // Increment alarm time with the precalculated timeToNextStep
  551. int minAdd_tmp=0;
  552. minAdd_tmp = alarmB_m + timeToNextStep_m;
  553. // Consider minutes overflow ^= hours + 1
  554. if (minAdd_tmp > 60) {
  555. alarmB_h = alarmB_h + 1;
  556. alarmB_m = minAdd_tmp - 60;
  557. } else {
  558. alarmB_m = minAdd_tmp;
  559. }
  560. transmit_uart("Setting alarm for next step.\r\n");
  561. set_alarm(alarmB_h, alarmB_m, alarmB_wd, "B", &sAlarmB);
  562. HAL_Delay(2000);
  563. transmit_uart("Entering sleep mode.\r\n");
  564. HAL_SuspendTick();
  565. HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI);
  566. HAL_ResumeTick();
  567. if (makeStepFlag) {
  568. transmit_uart("Making a step.\r\n");
  569. BSP_MotorControl_Move(0, FORWARD, stepsToMake);
  570. BSP_MotorControl_WaitWhileActive(0);
  571. }
  572. makeStepFlag = true;
  573. transmit_uart("\r\n");
  574. };
  575. }
  576. BSP_MotorControl_GoHome(0);
  577. BSP_MotorControl_WaitWhileActive(0);
  578. }
  579. /* USER CODE END 3 */
  580. }
  581. /**
  582. * @brief System Clock Configuration
  583. * @retval None
  584. */
  585. void SystemClock_Config(void)
  586. {
  587. RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  588. RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  589. RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
  590. /** Configure the main internal regulator output voltage
  591. */
  592. __HAL_RCC_PWR_CLK_ENABLE();
  593. __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
  594. /** Initializes the RCC Oscillators according to the specified parameters
  595. * in the RCC_OscInitTypeDef structure.
  596. */
  597. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
  598. RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  599. //RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  600. RCC_OscInitStruct.HSICalibrationValue = 16;
  601. RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  602. RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  603. RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  604. RCC_OscInitStruct.PLL.PLLM = 16;
  605. RCC_OscInitStruct.PLL.PLLN = 336;
  606. RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
  607. RCC_OscInitStruct.PLL.PLLQ = 7;
  608. if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  609. {
  610. Error_Handler();
  611. }
  612. /** Initializes the CPU, AHB and APB buses clocks
  613. */
  614. RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  615. |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  616. RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  617. RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  618. RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  619. RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  620. if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  621. {
  622. Error_Handler();
  623. }
  624. PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
  625. PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
  626. if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
  627. {
  628. Error_Handler();
  629. }
  630. }
  631. /**
  632. * @brief RTC Initialization Function
  633. * @param None
  634. * @retval None
  635. */
  636. static void MX_RTC_Init(void)
  637. {
  638. /* USER CODE BEGIN RTC_Init 0 */
  639. /* USER CODE END RTC_Init 0 */
  640. RTC_TimeTypeDef sTime = {0};
  641. RTC_DateTypeDef sDate = {0};
  642. //RTC_AlarmTypeDef sAlarm = {0};
  643. /* USER CODE BEGIN RTC_Init 1 */
  644. /* USER CODE END RTC_Init 1 */
  645. /** Initialize RTC Only
  646. */
  647. hrtc.Instance = RTC;
  648. hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
  649. hrtc.Init.AsynchPrediv = 127;
  650. hrtc.Init.SynchPrediv = 255;
  651. hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
  652. hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
  653. hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
  654. if (HAL_RTC_Init(&hrtc) != HAL_OK)
  655. {
  656. Error_Handler();
  657. }
  658. /* USER CODE BEGIN Check_RTC_BKUP */
  659. /* USER CODE END Check_RTC_BKUP */
  660. /** Initialize RTC and set the Time and Date
  661. */
  662. sTime.Hours = 13;
  663. sTime.Minutes = 56;
  664. sTime.Seconds = 10;
  665. sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  666. sTime.StoreOperation = RTC_STOREOPERATION_RESET;
  667. if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN) != HAL_OK)
  668. {
  669. Error_Handler();
  670. }
  671. sDate.WeekDay = RTC_WEEKDAY_SUNDAY;
  672. sDate.Month = RTC_MONTH_FEBRUARY;
  673. sDate.Date = 21;
  674. sDate.Year = 21;
  675. if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BIN) != HAL_OK)
  676. {
  677. Error_Handler();
  678. }
  679. }
  680. /**
  681. * @brief USART2 Initialization Function
  682. * @param None
  683. * @retval None
  684. */
  685. static void MX_USART2_UART_Init(void)
  686. {
  687. /* USER CODE BEGIN USART2_Init 0 */
  688. /* USER CODE END USART2_Init 0 */
  689. /* USER CODE BEGIN USART2_Init 1 */
  690. /* USER CODE END USART2_Init 1 */
  691. huart2.Instance = USART2;
  692. huart2.Init.BaudRate = 115200;
  693. huart2.Init.WordLength = UART_WORDLENGTH_8B;
  694. huart2.Init.StopBits = UART_STOPBITS_1;
  695. huart2.Init.Parity = UART_PARITY_NONE;
  696. huart2.Init.Mode = UART_MODE_TX_RX;
  697. huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  698. huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  699. if (HAL_UART_Init(&huart2) != HAL_OK)
  700. {
  701. Error_Handler();
  702. }
  703. /* USER CODE BEGIN USART2_Init 2 */
  704. /* USER CODE END USART2_Init 2 */
  705. }
  706. /**
  707. * @brief GPIO Initialization Function
  708. * @param None
  709. * @retval None
  710. */
  711. static void MX_GPIO_Init(void)
  712. {
  713. GPIO_InitTypeDef GPIO_InitStruct = {0};
  714. /* GPIO Ports Clock Enable */
  715. __HAL_RCC_GPIOC_CLK_ENABLE();
  716. __HAL_RCC_GPIOH_CLK_ENABLE();
  717. __HAL_RCC_GPIOA_CLK_ENABLE();
  718. __HAL_RCC_GPIOB_CLK_ENABLE();
  719. /*Configure GPIO pin Output Level */
  720. //HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
  721. /*Configure GPIO pin : B1_Pin */
  722. GPIO_InitStruct.Pin = B1_Pin;
  723. GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
  724. GPIO_InitStruct.Pull = GPIO_NOPULL;
  725. HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
  726. /*Configure GPIO pin : LD2_Pin */
  727. //GPIO_InitStruct.Pin = LD2_Pin;
  728. GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  729. GPIO_InitStruct.Pull = GPIO_NOPULL;
  730. GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  731. //HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);
  732. }
  733. /* USER CODE BEGIN 4 */
  734. /**
  735. * @brief Alarm callback
  736. * @param hrtc: RTC handle
  737. * @retval None
  738. */
  739. void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
  740. {
  741. /* Alarm generation */
  742. alarmSunriseFlag = true;
  743. alarmSunsetFlag = true;
  744. transmit_uart("Alarm A Callback triggered.\r\n");
  745. transmit_uart("Setting sunrise and sunset flags.\r\n");
  746. }
  747. void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc)
  748. {
  749. /* Alarm generation */
  750. makeStepFlag = true;
  751. transmit_uart("Alarm B Callback triggered.\r\n");
  752. transmit_uart("Setting makeStep flag.\r\n");
  753. }
  754. /**
  755. * @brief This function is the User handler for the flag interrupt
  756. * @param None
  757. * @retval None
  758. */
  759. void MyFlagInterruptHandler(void)
  760. {
  761. //When EN pin is forced low by a failure, configure the GPIO as an ouput low
  762. BSP_MotorControl_CmdDisable(0);
  763. }
  764. void ButtonHandler(void)
  765. {
  766. gButtonPressed = TRUE;
  767. /* Let 200 ms before clearing the IT for key debouncing */
  768. HAL_Delay(200);
  769. __HAL_GPIO_EXTI_CLEAR_IT(KEY_BUTTON_PIN);
  770. HAL_NVIC_ClearPendingIRQ(KEY_BUTTON_EXTI_IRQn);
  771. }
  772. /* USER CODE END 4 */
  773. /**
  774. * @brief This function is executed in case of error occurrence.
  775. * @retval None
  776. */
  777. void Error_Handler(void)
  778. {
  779. /* USER CODE BEGIN Error_Handler_Debug */
  780. /* User can add his own implementation to report the HAL error return state */
  781. __disable_irq();
  782. while (1)
  783. {
  784. }
  785. /* USER CODE END Error_Handler_Debug */
  786. }
  787. #ifdef USE_FULL_ASSERT
  788. /**
  789. * @brief Reports the name of the source file and the source line number
  790. * where the assert_param error has occurred.
  791. * @param file: pointer to the source file name
  792. * @param line: assert_param error line source number
  793. * @retval None
  794. */
  795. void assert_failed(uint8_t *file, uint32_t line)
  796. {
  797. /* USER CODE BEGIN 6 */
  798. /* User can add his own implementation to report the file name and line number,
  799. ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  800. /* USER CODE END 6 */
  801. }
  802. #endif /* USE_FULL_ASSERT */
  803. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/