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

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