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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  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 = 80; // Determines how big the amount of single steps is to complete 180 degrees of rotation, 80 ^= 1600/80 1/16 Steps tom complete 180 deg
  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. int duration=0;
  407. duration_h = sunset->hours - sunrise->hours;
  408. duration_m = sunset->minutes - sunrise->minutes;
  409. if (duration_m < 0) {
  410. duration_h = duration_h - 1;
  411. duration_m = 60 - sunrise->minutes + sunset->minutes;
  412. }
  413. duration = (duration_h * 60 + duration_m) / leapsFor180Deg;
  414. return duration;
  415. }
  416. /*******************************************************************************
  417. * Function Name : generate_filename
  418. * Description : Short function to generate a filename with the current date
  419. *******************************************************************************/
  420. void generate_filename(timeAndDate *date){
  421. sprintf(filename, "%02d%02d%02d.txt", date->year, date->month, date->day);
  422. }
  423. /* USER CODE END 0 */
  424. /**
  425. * @brief The application entry point.
  426. * @retval int
  427. */
  428. int main(void)
  429. {
  430. /* USER CODE BEGIN 1 */
  431. /* USER CODE END 1 */
  432. /* MCU Configuration--------------------------------------------------------*/
  433. /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  434. HAL_Init();
  435. /* USER CODE BEGIN Init */
  436. /* USER CODE END Init */
  437. /* Configure the system clock */
  438. SystemClock_Config();
  439. /* USER CODE BEGIN SysInit */
  440. /* USER CODE END SysInit */
  441. /* Initialize all configured peripherals */
  442. MX_GPIO_Init();
  443. MX_USART2_UART_Init();
  444. MX_RTC_Init();
  445. MX_SPI1_Init();
  446. MX_FATFS_Init();
  447. MX_ADC1_Init();
  448. /* USER CODE BEGIN 2 */
  449. //######### Inits of the Motor control library #########
  450. /* Set the L6208 library to use 1 device */
  451. BSP_MotorControl_SetNbDevices(BSP_MOTOR_CONTROL_BOARD_ID_L6208, 1);
  452. BSP_MotorControl_Init(BSP_MOTOR_CONTROL_BOARD_ID_L6208, &initDeviceParameters);
  453. //BSP_MotorControl_Init(BSP_MOTOR_CONTROL_BOARD_ID_L6208, NULL); //Default params
  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(MyErrorHandler);
  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. int32_t pos=0;
  465. uint32_t freqPwm=0;
  466. freqPwm = BSP_MotorControl_GetBridgeInputPwmFreq(0);
  467. BSP_MotorControl_SetBridgeInputPwmFreq(0, freqPwm>>1);
  468. // current position
  469. pos = BSP_MotorControl_GetPosition(0);
  470. // set current position to home
  471. BSP_MotorControl_SetHome(0, pos);
  472. //######### Mount SD-Card #########
  473. /* The SD Card is not working at the moment due to getting FR_NOT_READY
  474. * when connecting the SD Card Pins with the SPI Pins on the mounted X-NUCLEO Motor driver.
  475. * When dismounting the motor driver and connecting it via cables, there is unusual behaviour of the motor mnovement.
  476. * The SD Card though, works when the SD Card Breakout is connected directly to the NUCLEO board.
  477. *
  478. fres = f_mount(&fs, "", 0);
  479. if (fres == FR_OK) {
  480. transmit_uart("SD card is mounted successfully!\r\n");
  481. } else if (fres != FR_OK) {
  482. transmit_uart("SD card is not mounted!\r\n");
  483. }
  484. */
  485. //######### Start ADC Conversion #########
  486. HAL_ADC_Start(&hadc1);
  487. //######### Variable inits #########
  488. timeAndDate sunrise, sunset, wakeUpTimeForStep, tomorrowsDate, initialDate;
  489. sunrise = sunset = wakeUpTimeForStep = tomorrowsDate = initialDate = (timeAndDate) {\
  490. 0,
  491. 0,
  492. 0,
  493. 0,
  494. 0,
  495. 0,
  496. 0
  497. };
  498. uint32_t timeToNextStep=0;
  499. uint32_t alarmB_h = 0;
  500. uint32_t alarmB_m = 0;
  501. uint32_t alarmB_wd = 0;
  502. uint32_t stepsToMake = stepsFor180Deg / leapsFor180Deg; // The amount of single steps to make to complete 180/x degrees ^= 1600/x
  503. /* USER CODE END 2 */
  504. /* Infinite loop */
  505. /* USER CODE BEGIN WHILE */
  506. while (1)
  507. {
  508. HAL_Delay(2000);
  509. transmit_uart("Resetting motor position and calculating new dates and times.\r\n");
  510. BSP_MotorControl_GoHome(0);
  511. BSP_MotorControl_WaitWhileActive(0);
  512. /* USER CODE END WHILE */
  513. /* USER CODE BEGIN 3 */
  514. set_time_and_date(&initialDate);
  515. leap_year_check(initialDate.year);
  516. calc_tomorrows_date(&initialDate, &tomorrowsDate);
  517. generate_filename(&tomorrowsDate);
  518. //######### SD Card Write #########
  519. /* The SD Card is not working at the moment due to getting FR_NOT_READY
  520. * when connecting the SD Card Pins with the SPI Pins on the mounted X-NUCLEO Motor driver.
  521. * When dismounting the motor driver and connecting it via cables, there is unusual behaviour of the motor mnovement.
  522. * The SD Card though, works when the SD Card Breakout is connected directly to the NUCLEO board.
  523. *
  524. // Open file with tomorrows date as file name
  525. fres = f_open(&fil, filename, FA_OPEN_APPEND | FA_WRITE | FA_READ);
  526. if (fres == FR_OK) {
  527. transmit_uart("File opened.\r\n");
  528. } else if (fres != FR_OK) {
  529. transmit_uart("File was not opened!\r\n");
  530. }
  531. f_puts("Data", &fil);
  532. //Close file
  533. fres = f_close(&fil);
  534. if (fres == FR_OK) {
  535. transmit_uart("File is closed.\r\n");
  536. } else if (fres != FR_OK) {
  537. transmit_uart("File was not closed.\r\n");
  538. }
  539. */
  540. //Calculate sunrise and sunset time for tomorrow
  541. calc_sunrise_sunset(&initialDate, &sunrise, &sunset, &tomorrowsDate);
  542. //Test code
  543. sunrise.hours = 7;
  544. sunrise.minutes = 25;
  545. sunrise.weekDay = 1;
  546. sunset.hours = 18;
  547. sunset.minutes = 13;
  548. sunset.weekDay = 1;
  549. //Calculate the time for next motor step in minutes
  550. timeToNextStep = calc_interval_duration(&sunrise, &sunset);
  551. // Set Alarm for sunrise
  552. transmit_uart("Setting alarm for sunrise.\r\n");
  553. set_alarm(sunrise.hours, sunrise.minutes, sunrise.weekDay, "A", &sAlarmA);
  554. HAL_Delay(2000);
  555. transmit_uart("Entering sleep mode.\r\n");
  556. HAL_SuspendTick();
  557. HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI);
  558. HAL_ResumeTick();
  559. if (alarmSunriseFlag == true) {
  560. transmit_uart("Sunrise statement entered.\r\n");
  561. // Reset the flags
  562. alarmSunsetFlag = false;
  563. alarmSunriseFlag = false;
  564. // The alarm for the next step is incremented from sunrise as the initial time.
  565. alarmB_h = sunrise.hours;
  566. alarmB_m = sunrise.minutes;
  567. alarmB_wd = sunrise.weekDay;
  568. // Set Alarm for sunset, it overwrites the alarm for sunrise because the sunrise already happenend
  569. // The timeframes for both alarms dont overlap so 1 alarm is enough
  570. transmit_uart("Setting alarm for sunset.\r\n");
  571. set_alarm(sunset.hours, sunset.minutes, sunset.weekDay, "A", &sAlarmA);
  572. HAL_Delay(2000);
  573. while (alarmSunsetFlag != true) {
  574. transmit_uart("|--------------------------------------------------------|\r\n\r\n");
  575. // Increment alarm time with the precalculated timeToNextStep
  576. float minAdd_tmp=0;
  577. minAdd_tmp = alarmB_m + timeToNextStep;
  578. // Consider minutes overflow ^= hours + 1
  579. if (minAdd_tmp > 60) {
  580. alarmB_h = alarmB_h + 1;
  581. alarmB_m = minAdd_tmp - 60;
  582. } else {
  583. alarmB_m = minAdd_tmp;
  584. }
  585. transmit_uart("Setting alarm for next step.\r\n");
  586. set_alarm(alarmB_h, alarmB_m, alarmB_wd, "B", &sAlarmB);
  587. HAL_Delay(2000);
  588. transmit_uart("Entering sleep mode.\r\n");
  589. HAL_SuspendTick();
  590. HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI);
  591. HAL_ResumeTick();
  592. if (makeStepFlag) {
  593. // Poll ADC1 Perihperal & TimeOut = 1mSec
  594. HAL_ADC_PollForConversion(&hadc1, 1);
  595. // Read The ADC Conversion Result
  596. AD_RES = HAL_ADC_GetValue(&hadc1);
  597. transmit_uart("Making a step.\r\n");
  598. BSP_MotorControl_Move(0, FORWARD, stepsToMake);
  599. BSP_MotorControl_WaitWhileActive(0);
  600. }
  601. makeStepFlag = true;
  602. transmit_uart("\r\n");
  603. };
  604. }
  605. BSP_MotorControl_GoHome(0);
  606. BSP_MotorControl_WaitWhileActive(0);
  607. }
  608. /* USER CODE END 3 */
  609. }
  610. /**
  611. * @brief System Clock Configuration
  612. * @retval None
  613. */
  614. void SystemClock_Config(void)
  615. {
  616. RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  617. RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  618. RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
  619. /** Configure the main internal regulator output voltage
  620. */
  621. __HAL_RCC_PWR_CLK_ENABLE();
  622. __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
  623. /** Initializes the RCC Oscillators according to the specified parameters
  624. * in the RCC_OscInitTypeDef structure.
  625. */
  626. RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
  627. RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  628. //RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  629. RCC_OscInitStruct.HSICalibrationValue = 16;
  630. RCC_OscInitStruct.LSIState = RCC_LSI_ON;
  631. RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  632. RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  633. RCC_OscInitStruct.PLL.PLLM = 16;
  634. RCC_OscInitStruct.PLL.PLLN = 336;
  635. RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
  636. RCC_OscInitStruct.PLL.PLLQ = 7;
  637. if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  638. {
  639. Error_Handler();
  640. }
  641. /** Initializes the CPU, AHB and APB buses clocks
  642. */
  643. RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  644. |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  645. RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  646. RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  647. RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  648. RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  649. if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  650. {
  651. Error_Handler();
  652. }
  653. PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
  654. PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
  655. if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
  656. {
  657. Error_Handler();
  658. }
  659. }
  660. /**
  661. * @brief RTC Initialization Function
  662. * @param None
  663. * @retval None
  664. */
  665. static void MX_RTC_Init(void)
  666. {
  667. /* USER CODE BEGIN RTC_Init 0 */
  668. /* USER CODE END RTC_Init 0 */
  669. RTC_TimeTypeDef sTime = {0};
  670. RTC_DateTypeDef sDate = {0};
  671. RTC_AlarmTypeDef sAlarm = {0};
  672. /* USER CODE BEGIN RTC_Init 1 */
  673. /* USER CODE END RTC_Init 1 */
  674. /** Initialize RTC Only
  675. */
  676. hrtc.Instance = RTC;
  677. hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
  678. hrtc.Init.AsynchPrediv = 127;
  679. hrtc.Init.SynchPrediv = 255;
  680. hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
  681. hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
  682. hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
  683. if (HAL_RTC_Init(&hrtc) != HAL_OK)
  684. {
  685. Error_Handler();
  686. }
  687. /* USER CODE BEGIN Check_RTC_BKUP */
  688. /* USER CODE END Check_RTC_BKUP */
  689. /** Initialize RTC and set the Time and Date
  690. */
  691. sTime.Hours = 7;
  692. sTime.Minutes = 20;
  693. sTime.Seconds = 10;
  694. sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  695. sTime.StoreOperation = RTC_STOREOPERATION_RESET;
  696. if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN) != HAL_OK)
  697. {
  698. Error_Handler();
  699. }
  700. sDate.WeekDay = RTC_WEEKDAY_MONDAY;
  701. sDate.Month = RTC_MONTH_FEBRUARY;
  702. sDate.Date = 21;
  703. sDate.Year = 21;
  704. if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BIN) != HAL_OK)
  705. {
  706. Error_Handler();
  707. }
  708. /** Enable the Alarm A
  709. */
  710. sAlarm.AlarmTime.Hours = 0;
  711. sAlarm.AlarmTime.Minutes = 0;
  712. sAlarm.AlarmTime.Seconds = 0;
  713. sAlarm.AlarmTime.SubSeconds = 0;
  714. sAlarm.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
  715. sAlarm.AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET;
  716. sAlarm.AlarmMask = RTC_ALARMMASK_NONE;
  717. sAlarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
  718. sAlarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE;
  719. sAlarm.AlarmDateWeekDay = 1;
  720. sAlarm.Alarm = RTC_ALARM_A;
  721. if (HAL_RTC_SetAlarm_IT(&hrtc, &sAlarm, RTC_FORMAT_BIN) != HAL_OK)
  722. {
  723. Error_Handler();
  724. }
  725. /** Enable the Alarm B
  726. */
  727. sAlarm.AlarmDateWeekDay = 1;
  728. sAlarm.Alarm = RTC_ALARM_B;
  729. if (HAL_RTC_SetAlarm_IT(&hrtc, &sAlarm, RTC_FORMAT_BIN) != HAL_OK)
  730. {
  731. Error_Handler();
  732. }
  733. /* USER CODE BEGIN RTC_Init 2 */
  734. /* USER CODE END RTC_Init 2 */
  735. }
  736. /**
  737. * @brief USART2 Initialization Function
  738. * @param None
  739. * @retval None
  740. */
  741. static void MX_USART2_UART_Init(void)
  742. {
  743. /* USER CODE BEGIN USART2_Init 0 */
  744. /* USER CODE END USART2_Init 0 */
  745. /* USER CODE BEGIN USART2_Init 1 */
  746. /* USER CODE END USART2_Init 1 */
  747. huart2.Instance = USART2;
  748. huart2.Init.BaudRate = 115200;
  749. huart2.Init.WordLength = UART_WORDLENGTH_8B;
  750. huart2.Init.StopBits = UART_STOPBITS_1;
  751. huart2.Init.Parity = UART_PARITY_NONE;
  752. huart2.Init.Mode = UART_MODE_TX_RX;
  753. huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  754. huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  755. if (HAL_UART_Init(&huart2) != HAL_OK)
  756. {
  757. Error_Handler();
  758. }
  759. /* USER CODE BEGIN USART2_Init 2 */
  760. /* USER CODE END USART2_Init 2 */
  761. }
  762. /**
  763. * @brief GPIO Initialization Function
  764. * @param None
  765. * @retval None
  766. */
  767. static void MX_GPIO_Init(void)
  768. {
  769. GPIO_InitTypeDef GPIO_InitStruct = {0};
  770. /* GPIO Ports Clock Enable */
  771. __HAL_RCC_GPIOC_CLK_ENABLE();
  772. __HAL_RCC_GPIOH_CLK_ENABLE();
  773. __HAL_RCC_GPIOA_CLK_ENABLE();
  774. __HAL_RCC_GPIOB_CLK_ENABLE();
  775. /*Configure GPIO pin Output Level */
  776. HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
  777. /*Configure GPIO pin Output Level */
  778. HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);
  779. /*Configure GPIO pin : B1_Pin */
  780. GPIO_InitStruct.Pin = B1_Pin;
  781. GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
  782. GPIO_InitStruct.Pull = GPIO_NOPULL;
  783. HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
  784. /*Configure GPIO pin : LD2_Pin */
  785. GPIO_InitStruct.Pin = LD2_Pin;
  786. GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  787. GPIO_InitStruct.Pull = GPIO_NOPULL;
  788. GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  789. HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);
  790. /*Configure GPIO pin : PB6 */
  791. GPIO_InitStruct.Pin = GPIO_PIN_6;
  792. GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  793. GPIO_InitStruct.Pull = GPIO_NOPULL;
  794. GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
  795. HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
  796. }
  797. /**
  798. * @brief ADC1 Initialization Function
  799. * @param None
  800. * @retval None
  801. */
  802. static void MX_ADC1_Init(void)
  803. {
  804. /* USER CODE BEGIN ADC1_Init 0 */
  805. /* USER CODE END ADC1_Init 0 */
  806. ADC_ChannelConfTypeDef sConfig = {0};
  807. /* USER CODE BEGIN ADC1_Init 1 */
  808. /* USER CODE END ADC1_Init 1 */
  809. /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
  810. */
  811. hadc1.Instance = ADC1;
  812. hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
  813. hadc1.Init.Resolution = ADC_RESOLUTION_12B;
  814. hadc1.Init.ScanConvMode = DISABLE;
  815. hadc1.Init.ContinuousConvMode = ENABLE;
  816. hadc1.Init.DiscontinuousConvMode = DISABLE;
  817. hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  818. hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  819. hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  820. hadc1.Init.NbrOfConversion = 1;
  821. hadc1.Init.DMAContinuousRequests = DISABLE;
  822. hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  823. if (HAL_ADC_Init(&hadc1) != HAL_OK)
  824. {
  825. Error_Handler();
  826. }
  827. /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
  828. */
  829. sConfig.Channel = ADC_CHANNEL_0;
  830. sConfig.Rank = 1;
  831. sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
  832. if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  833. {
  834. Error_Handler();
  835. }
  836. /* USER CODE BEGIN ADC1_Init 2 */
  837. /* USER CODE END ADC1_Init 2 */
  838. }
  839. /**
  840. * @brief SPI1 Initialization Function
  841. * @param None
  842. * @retval None
  843. */
  844. static void MX_SPI1_Init(void)
  845. {
  846. /* USER CODE BEGIN SPI1_Init 0 */
  847. /* USER CODE END SPI1_Init 0 */
  848. /* USER CODE BEGIN SPI1_Init 1 */
  849. /* USER CODE END SPI1_Init 1 */
  850. /* SPI1 parameter configuration*/
  851. hspi1.Instance = SPI1;
  852. hspi1.Init.Mode = SPI_MODE_MASTER;
  853. hspi1.Init.Direction = SPI_DIRECTION_2LINES;
  854. hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  855. hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
  856. hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
  857. hspi1.Init.NSS = SPI_NSS_SOFT;
  858. hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
  859. hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  860. hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  861. hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  862. hspi1.Init.CRCPolynomial = 10;
  863. if (HAL_SPI_Init(&hspi1) != HAL_OK)
  864. {
  865. Error_Handler();
  866. }
  867. /* USER CODE BEGIN SPI1_Init 2 */
  868. /* USER CODE END SPI1_Init 2 */
  869. }
  870. /* USER CODE BEGIN 4 */
  871. /**
  872. * @brief Alarm callback
  873. * @param hrtc: RTC handle
  874. * @retval None
  875. */
  876. void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
  877. {
  878. /* Alarm generation */
  879. alarmSunriseFlag = true;
  880. alarmSunsetFlag = true;
  881. transmit_uart("Alarm A Callback triggered.\r\n");
  882. transmit_uart("Setting sunrise and sunset flags.\r\n");
  883. }
  884. void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc)
  885. {
  886. /* Alarm generation */
  887. makeStepFlag = true;
  888. transmit_uart("Alarm B Callback triggered.\r\n");
  889. transmit_uart("Setting makeStep flag.\r\n");
  890. }
  891. /**
  892. * @brief This function is the User handler for the flag interrupt
  893. * @param None
  894. * @retval None
  895. */
  896. void MyFlagInterruptHandler(void)
  897. {
  898. //When EN pin is forced low by a failure, configure the GPIO as an ouput low
  899. BSP_MotorControl_CmdDisable(0);
  900. }
  901. /* USER CODE END 4 */
  902. /**
  903. * @brief This function is executed in case of error occurrence.
  904. * @retval None
  905. */
  906. void Error_Handler(void)
  907. {
  908. /* USER CODE BEGIN Error_Handler_Debug */
  909. /* User can add his own implementation to report the HAL error return state */
  910. __disable_irq();
  911. while (1)
  912. {
  913. }
  914. /* USER CODE END Error_Handler_Debug */
  915. }
  916. void MyErrorHandler(uint16_t error)
  917. {
  918. // Motor error handler
  919. /* Backup error number */
  920. gLastError = error;
  921. /* Infinite loop */
  922. while(1)
  923. {
  924. }
  925. }
  926. void ButtonHandler(void)
  927. {
  928. gButtonPressed = TRUE;
  929. /* Let 200 ms before clearing the IT for key debouncing */
  930. HAL_Delay(200);
  931. __HAL_GPIO_EXTI_CLEAR_IT(KEY_BUTTON_PIN);
  932. HAL_NVIC_ClearPendingIRQ(KEY_BUTTON_EXTI_IRQn);
  933. }
  934. #ifdef USE_FULL_ASSERT
  935. /**
  936. * @brief Reports the name of the source file and the source line number
  937. * where the assert_param error has occurred.
  938. * @param file: pointer to the source file name
  939. * @param line: assert_param error line source number
  940. * @retval None
  941. */
  942. void assert_failed(uint8_t *file, uint32_t line)
  943. {
  944. /* USER CODE BEGIN 6 */
  945. /* User can add his own implementation to report the file name and line number,
  946. ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  947. /* USER CODE END 6 */
  948. }
  949. #endif /* USE_FULL_ASSERT */
  950. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/