12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142 |
- /* USER CODE BEGIN Header */
- /**
- ******************************************************************************
- * @file : main.c
- * @brief : Main program body
- ******************************************************************************
- * @attention
- *
- * <h2><center>© Copyright (c) 2021 STMicroelectronics.
- * All rights reserved.</center></h2>
- *
- * This software component is licensed by ST under BSD 3-Clause license,
- * the "License"; You may not use this file except in compliance with the
- * License. You may obtain a copy of the License at:
- * opensource.org/licenses/BSD-3-Clause
- *
- ******************************************************************************
- */
- /* USER CODE END Header */
- /* Includes ------------------------------------------------------------------*/
- #include "main.h"
- #include "fatfs.h"
-
- /* Private includes ----------------------------------------------------------*/
- /* USER CODE BEGIN Includes */
- #include "math.h"
- #include "stdbool.h"
- #include "string.h"
- #include <stdio.h>
- #include "fatfs_sd.h"
- #include <stdarg.h>
- /* USER CODE END Includes */
-
- /* Private typedef -----------------------------------------------------------*/
- /* USER CODE BEGIN PTD */
-
- /* USER CODE END PTD */
-
- /* Private define ------------------------------------------------------------*/
- /* USER CODE BEGIN PD */
-
- /* USER CODE END PD */
-
- /* Private macro -------------------------------------------------------------*/
- /* USER CODE BEGIN PM */
-
- /* USER CODE END PM */
-
- /* Private variables ---------------------------------------------------------*/
- SPI_HandleTypeDef hspi1;
- ADC_HandleTypeDef hadc1;
-
- RTC_HandleTypeDef hrtc;
-
- UART_HandleTypeDef huart2;
-
- /* USER CODE BEGIN PV */
- RTC_TimeTypeDef sTime;
- RTC_DateTypeDef sDate;
- RTC_AlarmTypeDef sAlarmA, sAlarmB;
- static volatile uint16_t gLastError;
- static volatile bool gButtonPressed = FALSE;
-
- //Nuremberg coordinates
- int latitude_nbg = 49;
- int longitude_nbg = 11;
-
- //German UTC time,summer (+2) and winter (+1)
- int UTC_DER_sum = 2;
- int UTC_DER_win = 1;
- bool winterTime = true;
-
- int DaysInMonth[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
- int DaysInMonthLeapYear[12] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
- bool leapYear = false;
- 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
- 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
- bool alarmSunriseFlag = false;
- bool alarmSunsetFlag = false;
- bool makeStepFlag = false;
-
- /* Initialization parameters. */
- l6208_Init_t initDeviceParameters =
- {
- 1500, //Acceleration rate in step/s^2 or (1/16)th step/s^2 for microstep modes
- 20, //Acceleration current torque in % (from 0 to 100)
- 1500, //Deceleration rate in step/s^2 or (1/16)th step/s^2 for microstep modes
- 20, //Deceleration current torque in % (from 0 to 100)
- 1500, //Running speed in step/s or (1/16)th step/s for microstep modes
- 10, //Running current torque in % (from 0 to 100)
- 5, //Holding current torque in % (from 0 to 100)
- STEP_MODE_1_16, //Step mode via enum motorStepMode_t
- FAST_DECAY, //Decay mode via enum motorDecayMode_t
- 0, //Dwelling time in ms
- FALSE, //Automatic HIZ STOP
- 100000 //VREFA and VREFB PWM frequency (Hz)
- };
-
- typedef struct {
- int hours;
- int minutes;
- int seconds;
- int weekDay;
- int month;
- int day;
- int year;
- } timeAndDate;
-
- // SD CARD Variables
- FATFS fs;
- FATFS *pfs;
- FIL fil;
- FRESULT fres;
- DWORD fre_clust;
- uint32_t totalSpace, freeSpace;
- char buffer[100];
- uint16_t AD_RES;
- int num;
- char filename[12];
-
- /* USER CODE END PV */
-
- /* Private function prototypes -----------------------------------------------*/
- void SystemClock_Config(void);
- static void MX_GPIO_Init(void);
- static void MX_USART2_UART_Init(void);
- static void MX_RTC_Init(void);
- static void MX_SPI1_Init(void);
- static void MX_ADC1_Init(void);
- static void MyFlagInterruptHandler(void);
- void MyErrorHandler(uint16_t error);
- void ButtonHandler(void);
- /* USER CODE BEGIN PFP */
-
- /* USER CODE END PFP */
-
- /* Private user code ---------------------------------------------------------*/
- /* USER CODE BEGIN 0 */
- /*******************************************************************************
- * Function Name : deg_to_rad
- * Description : converts degrees to radians
- * Return : angle in radians
- *******************************************************************************/
- double deg_to_rad(double deg)
- {
- double rad = deg*(M_PI/180);
- return rad;
- }
-
- /*******************************************************************************
- * Function Name : rad_to_deg
- * Description : converts radians to degrees
- * Return : angle in degrees
- *******************************************************************************/
- double rad_to_deg(double rad)
- {
- double deg = rad*(180/M_PI);
- return deg;
- }
-
- /*******************************************************************************
- * Function Name : leap_year_check
- * Description : checks if year is a leap year
- * Return : false: no leap year, true: leap year
- *******************************************************************************/
- void leap_year_check(int initialyear)
- {
- int year = initialyear;
- if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
- {
- leapYear = true;
- }
- else
- {
- leapYear = false;
- }
-
- }
-
- /*******************************************************************************
- * Function Name : calc_day_of_year
- * Description : calculates the day of year
- * Return : day of year (1.1.. = 1, 2.1.. = 2,...)
- * Source : https://overiq.com/c-examples/c-program-to-calculate-the-day-of-year-from-the-date/
- *******************************************************************************/
- int calc_day_of_year(int day, int mon, int year)
- {
- int days_in_feb = 28;
- int doy = day; //day of year
-
- // check for leap year
- //bool leap_year = leap_year_check(year);
- if(leapYear == true)
- {
- days_in_feb = 29;
- }
-
- switch(mon)
- {
- case 2:
- doy += 31;
- break;
- case 3:
- doy += 31+days_in_feb;
- break;
- case 4:
- doy += days_in_feb+62;
- break;
- case 5:
- doy += days_in_feb+92;
- break;
- case 6:
- doy += days_in_feb+123;
- break;
- case 7:
- doy += days_in_feb+153;
- break;
- case 8:
- doy += days_in_feb+184;
- break;
- case 9:
- doy += days_in_feb+215;
- break;
- case 10:
- doy += days_in_feb+245;
- break;
- case 11:
- doy += days_in_feb+276;
- break;
- case 12:
- doy += days_in_feb+306;
- break;
- }
- return doy;
- }
-
- /*******************************************************************************
- * Function Name : calc_sunrise_sunset
- * Description : calculates the sunrise and sunset time of a specific date
- * Source : General Solar Position Calculations, NOAA Global Monitoring Division
- *******************************************************************************/
- void calc_sunrise_sunset(timeAndDate* initialDate, timeAndDate* sunriseStruct, timeAndDate* sunsetStruct, timeAndDate* tomorrowsDate)
- {
- double gamma = 0;
- double eqtime = 0;
- double decl = 0;
- //double decl_deg = 0;
- double zenith_sun = 0;
- double lat_nbg_rad = 0;
- double ha = 0;
- double sunrise = 0;
- double sunset = 0;
- double ha_deg = 0;
- int sunrise_h = 0;
- int sunset_h = 0;
- double sunrise_min = 0;
- double sunset_min = 0;
- int int_sunrise_min = 0;
- int int_sunset_min = 0;
-
- int day = initialDate->day;
- int month = initialDate->month;
- int year = initialDate->year;
-
- //day of year calculation
- int day_of_year = calc_day_of_year(day, month, year);
-
- // fractional year (γ) in radians
- // check for leap year
- //leap_year = leap_year_check(year);
- if(leapYear == false)
- {
- //The back part of the formula was omitted, because there is no difference in the result
- gamma = ((2 * M_PI)/365)*(day_of_year - 1);
- } else {
- //The back part of the formula was omitted, because there is no difference in the result
- gamma = ((2 * M_PI)/366)*(day_of_year - 1);
- }
-
- //Equation of time in minutes
- eqtime = 229.18*(0.000075 + 0.001868*cos(gamma) - 0.032077*sin(gamma) - 0.014615*cos(2*gamma) - 0.040849*sin(2*gamma));
-
- //Solar declination angle in radians
- 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);
-
- //Solar declination angle in degrees
- //decl_deg = rad_to_deg(decl);
-
- //Hour angle in degrees, positive number corresponds to sunrise, negative to sunset
- //special case of sunrise or sunset, the zenith is set to 90.833Deg
- zenith_sun = deg_to_rad(90.833);
- //Latitude of Nuernberg in rad
- lat_nbg_rad = deg_to_rad(latitude_nbg);
- ha = acos((cos(zenith_sun)/(cos(lat_nbg_rad)*cos(decl)))-(tan(lat_nbg_rad)*tan(decl)));
- ha_deg = rad_to_deg(ha);
-
- //UTC time of sunrise (or sunset) in minutes
- sunrise = (720-4*(longitude_nbg+ha_deg)-eqtime);
- sunset = 720-4*(longitude_nbg-ha_deg)-eqtime;
-
- //Convert sunrise (or sunset) UTC time in hours
- sunrise = sunrise/60;
- sunset = sunset/60;
-
- //Seperate hours and minutes
- sunrise_h = floor(sunrise);
- sunrise_min = sunrise - sunrise_h;
- //Cut off after two decimal places
- int_sunrise_min = floor(sunrise_min * 100.0);
- if (int_sunrise_min >= 60)
- {
- sunrise_h = sunrise_h + 1;
- int_sunrise_min = int_sunrise_min - 60;
- }
- sunset_h = floor(sunset);
- sunset_min = sunset - sunset_h;
- //Cut off after two decimal places
- int_sunset_min = floor(sunset_min * 100.0);
- if (int_sunset_min >= 60)
- {
- sunset_h = sunset_h + 1;
- int_sunset_min = int_sunset_min - 60;
- }
-
- //Add time difference from German time to UTC Time
- //Private variable winterTime must be initialized accordingly
- if (winterTime)
- {
- sunrise_h = sunrise_h + UTC_DER_win;
- sunset_h = sunset_h + UTC_DER_win;
- } else {
- sunrise_h = sunrise_h + UTC_DER_sum;
- sunset_h = sunset_h + UTC_DER_sum;
- }
-
- sunriseStruct->hours = sunrise_h;
- sunriseStruct->minutes = int_sunrise_min;
-
- sunsetStruct->hours = sunset_h;
- sunsetStruct->minutes = int_sunset_min;
-
- sunriseStruct->day = sunsetStruct->day = tomorrowsDate->day;
- sunriseStruct->weekDay = sunsetStruct->weekDay = tomorrowsDate->weekDay;
- sunriseStruct->month = sunsetStruct->month = tomorrowsDate->month;
- sunriseStruct->year = sunsetStruct->year = tomorrowsDate->year;
- }
-
- /*******************************************************************************
- * Function Name : calc_tomorrows_date
- * Description : calculates tomorrow's date
- * Source : https://github.com/vyacht/stm32/blob/master/vynmea/rtc.c
- *******************************************************************************/
- void calc_tomorrows_date(timeAndDate* initialDate, timeAndDate* tomorrowsDate)
- {
- int yearToUse[12];
-
- if (leapYear == true){
- memcpy(yearToUse, DaysInMonthLeapYear, sizeof yearToUse);
- } else {
- memcpy(yearToUse, DaysInMonth, sizeof yearToUse);
- }
-
- int day = initialDate->day;
- int wday = initialDate->weekDay;
- int month = initialDate->month;
- int year = initialDate->year;
-
- day++; // next day
- wday++; // next weekday
- if(wday == 8)
- {
- wday = 1; // Monday
- }
- if(day > yearToUse[month-1])
- { // next month
- day = 1;
- month++;
- }
- if(day > 31 && month == 12) // next year
- {
- day = 1;
- month = 1;
- year++;
- }
-
- tomorrowsDate->day = day;
- tomorrowsDate->weekDay = wday;
- tomorrowsDate->month = month;
- tomorrowsDate->year = year;
-
- }
-
- /*******************************************************************************
- * Function Name : set_alarm
- * Description : sets alarm A or B
- *******************************************************************************/
- void set_alarm(int h, int min, int weekDay, char* alarm, RTC_AlarmTypeDef* alarmInstance)
- {
- /** Enable the Alarm A*/
-
- alarmInstance->AlarmTime.Hours = h;
- alarmInstance->AlarmTime.Minutes = min;
- alarmInstance->AlarmTime.Seconds = 0;
- alarmInstance->AlarmTime.SubSeconds = 0;
- alarmInstance->AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
- alarmInstance->AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET;
- alarmInstance->AlarmMask = RTC_ALARMMASK_NONE; //only by specific time
- alarmInstance->AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
- alarmInstance->AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_WEEKDAY;
- alarmInstance->AlarmDateWeekDay = weekDay;
-
- if (strcmp("A", alarm) == 0) {
- alarmInstance->Alarm = RTC_ALARM_A;
- } else {
- alarmInstance->Alarm = RTC_ALARM_B;
- }
-
- if (HAL_RTC_SetAlarm_IT(&hrtc, alarmInstance, RTC_FORMAT_BIN) != HAL_OK)
- {
- Error_Handler();
- }
-
-
- }
-
- /*******************************************************************************
- * Function Name : transmit_uart
- * Description : Transmit a string over uart
- *******************************************************************************/
- void transmit_uart(char *string){
- uint8_t len = strlen(string);
- HAL_UART_Transmit(&huart2, (uint8_t*) string, len, 200);
- }
-
- /***************************************************************************************************
- * Function Name : set_time_and_date
- * Description : Overwriting the date given in timeanddate with the current time and date from rtc
- ****************************************************************************************************/
- void set_time_and_date(timeAndDate *timeanddate){
-
- if (HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN) == HAL_OK)
- {
- timeanddate->hours = sTime.Hours;
- timeanddate->minutes = sTime.Minutes;
- timeanddate->seconds = sTime.Seconds;
- }
-
- if (HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN) == HAL_OK)
- {
- timeanddate->weekDay = sDate.WeekDay;
- timeanddate->month = sDate.Month;
- timeanddate->day = sDate.Date;
- timeanddate->year = 2000 + sDate.Year;
- }
- }
-
- /*******************************************************************************
- * Function Name : calc_interval_duration
- * Description : Calculate the duration between the two given time/dates
- * Return : The duration as an integer
- *******************************************************************************/
- int calc_interval_duration(timeAndDate *sunrise, timeAndDate *sunset){
- int duration_h=0;
- int duration_m=0;
- int duration=0;
-
- duration_h = sunset->hours - sunrise->hours;
- duration_m = sunset->minutes - sunrise->minutes;
-
- if (duration_m < 0) {
- duration_h = duration_h - 1;
- duration_m = 60 - sunrise->minutes + sunset->minutes;
- }
-
- duration = (duration_h * 60 + duration_m) / leapsFor180Deg;
-
- return duration;
- }
-
- /*******************************************************************************
- * Function Name : generate_filename
- * Description : Short function to generate a filename with the current date
- *******************************************************************************/
- void generate_filename(timeAndDate *date){
- sprintf(filename, "%02d%02d%02d.txt", date->year, date->month, date->day);
- }
-
- /* USER CODE END 0 */
-
- /**
- * @brief The application entry point.
- * @retval int
- */
- int main(void)
- {
- /* USER CODE BEGIN 1 */
-
- /* USER CODE END 1 */
-
- /* MCU Configuration--------------------------------------------------------*/
-
- /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
- HAL_Init();
-
- /* USER CODE BEGIN Init */
-
- /* USER CODE END Init */
-
- /* Configure the system clock */
- SystemClock_Config();
-
- /* USER CODE BEGIN SysInit */
-
- /* USER CODE END SysInit */
-
- /* Initialize all configured peripherals */
- MX_GPIO_Init();
- MX_USART2_UART_Init();
- MX_RTC_Init();
- MX_SPI1_Init();
- MX_FATFS_Init();
- MX_ADC1_Init();
- /* USER CODE BEGIN 2 */
-
- //######### Inits of the Motor control library #########
-
- /* Set the L6208 library to use 1 device */
- BSP_MotorControl_SetNbDevices(BSP_MOTOR_CONTROL_BOARD_ID_L6208, 1);
-
- BSP_MotorControl_Init(BSP_MOTOR_CONTROL_BOARD_ID_L6208, &initDeviceParameters);
-
- //BSP_MotorControl_Init(BSP_MOTOR_CONTROL_BOARD_ID_L6208, NULL); //Default params
-
- /* Attach the function MyFlagInterruptHandler (defined below) to the flag interrupt */
- BSP_MotorControl_AttachFlagInterrupt(MyFlagInterruptHandler);
-
- /* Attach the function MyErrorHandler (defined below) to the error Handler*/
- BSP_MotorControl_AttachErrorHandler(MyErrorHandler);
-
- /* Set Systick Interrupt priority highest to ensure no lock by using HAL_Delay */
- HAL_NVIC_SetPriority(SysTick_IRQn, 0x0, 0x0);
-
- /* Configure KEY Button */
- //BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI);
-
- /* Disable the power bridges after initialization */
- BSP_MotorControl_CmdDisable(0);
-
- int32_t pos=0;
- uint32_t freqPwm=0;
-
- freqPwm = BSP_MotorControl_GetBridgeInputPwmFreq(0);
-
- BSP_MotorControl_SetBridgeInputPwmFreq(0, freqPwm>>1);
-
- // current position
- pos = BSP_MotorControl_GetPosition(0);
-
- // set current position to home
- BSP_MotorControl_SetHome(0, pos);
-
- //######### Mount SD-Card #########
- /* The SD Card is not working at the moment due to getting FR_NOT_READY
- * when connecting the SD Card Pins with the SPI Pins on the mounted X-NUCLEO Motor driver.
- * When dismounting the motor driver and connecting it via cables, there is unusual behaviour of the motor mnovement.
- * The SD Card though, works when the SD Card Breakout is connected directly to the NUCLEO board.
- *
- fres = f_mount(&fs, "", 0);
- if (fres == FR_OK) {
- transmit_uart("SD card is mounted successfully!\r\n");
- } else if (fres != FR_OK) {
- transmit_uart("SD card is not mounted!\r\n");
- }
- */
-
- //######### Start ADC Conversion #########
- HAL_ADC_Start(&hadc1);
-
- //######### Variable inits #########
-
- timeAndDate sunrise, sunset, wakeUpTimeForStep, tomorrowsDate, initialDate;
- sunrise = sunset = wakeUpTimeForStep = tomorrowsDate = initialDate = (timeAndDate) {\
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0
- };
-
- uint32_t timeToNextStep=0;
- uint32_t alarmB_h = 0;
- uint32_t alarmB_m = 0;
- uint32_t alarmB_wd = 0;
- uint32_t stepsToMake = stepsFor180Deg / leapsFor180Deg; // The amount of single steps to make to complete 180/x degrees ^= 1600/x
-
- /* USER CODE END 2 */
-
- /* Infinite loop */
- /* USER CODE BEGIN WHILE */
-
- while (1)
- {
- HAL_Delay(2000);
-
- transmit_uart("Resetting motor position and calculating new dates and times.\r\n");
-
- BSP_MotorControl_GoHome(0);
- BSP_MotorControl_WaitWhileActive(0);
-
- /* USER CODE END WHILE */
-
- /* USER CODE BEGIN 3 */
- set_time_and_date(&initialDate);
-
- leap_year_check(initialDate.year);
-
- calc_tomorrows_date(&initialDate, &tomorrowsDate);
-
- generate_filename(&tomorrowsDate);
-
- //######### SD Card Write #########
-
- /* The SD Card is not working at the moment due to getting FR_NOT_READY
- * when connecting the SD Card Pins with the SPI Pins on the mounted X-NUCLEO Motor driver.
- * When dismounting the motor driver and connecting it via cables, there is unusual behaviour of the motor mnovement.
- * The SD Card though, works when the SD Card Breakout is connected directly to the NUCLEO board.
- *
-
- // Open file with tomorrows date as file name
- fres = f_open(&fil, filename, FA_OPEN_APPEND | FA_WRITE | FA_READ);
- if (fres == FR_OK) {
- transmit_uart("File opened.\r\n");
- } else if (fres != FR_OK) {
- transmit_uart("File was not opened!\r\n");
- }
-
- f_puts("Data", &fil);
-
- //Close file
- fres = f_close(&fil);
- if (fres == FR_OK) {
- transmit_uart("File is closed.\r\n");
- } else if (fres != FR_OK) {
- transmit_uart("File was not closed.\r\n");
- }
- */
-
- //Calculate sunrise and sunset time for tomorrow
- calc_sunrise_sunset(&initialDate, &sunrise, &sunset, &tomorrowsDate);
-
- //Test code
-
- sunrise.hours = 7;
- sunrise.minutes = 25;
- sunrise.weekDay = 1;
-
- sunset.hours = 18;
- sunset.minutes = 13;
- sunset.weekDay = 1;
-
-
- //Calculate the time for next motor step in minutes
- timeToNextStep = calc_interval_duration(&sunrise, &sunset);
-
- // Set Alarm for sunrise
- transmit_uart("Setting alarm for sunrise.\r\n");
- set_alarm(sunrise.hours, sunrise.minutes, sunrise.weekDay, "A", &sAlarmA);
-
- HAL_Delay(2000);
-
- transmit_uart("Entering sleep mode.\r\n");
- HAL_SuspendTick();
- HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI);
- HAL_ResumeTick();
-
- if (alarmSunriseFlag == true) {
-
- transmit_uart("Sunrise statement entered.\r\n");
- // Reset the flags
- alarmSunsetFlag = false;
- alarmSunriseFlag = false;
-
- // The alarm for the next step is incremented from sunrise as the initial time.
- alarmB_h = sunrise.hours;
- alarmB_m = sunrise.minutes;
- alarmB_wd = sunrise.weekDay;
-
- // Set Alarm for sunset, it overwrites the alarm for sunrise because the sunrise already happenend
- // The timeframes for both alarms dont overlap so 1 alarm is enough
- transmit_uart("Setting alarm for sunset.\r\n");
- set_alarm(sunset.hours, sunset.minutes, sunset.weekDay, "A", &sAlarmA);
-
- HAL_Delay(2000);
-
- while (alarmSunsetFlag != true) {
-
- transmit_uart("|--------------------------------------------------------|\r\n\r\n");
- // Increment alarm time with the precalculated timeToNextStep
- float minAdd_tmp=0;
-
- minAdd_tmp = alarmB_m + timeToNextStep;
-
- // Consider minutes overflow ^= hours + 1
- if (minAdd_tmp > 60) {
- alarmB_h = alarmB_h + 1;
- alarmB_m = minAdd_tmp - 60;
- } else {
- alarmB_m = minAdd_tmp;
- }
-
- transmit_uart("Setting alarm for next step.\r\n");
- set_alarm(alarmB_h, alarmB_m, alarmB_wd, "B", &sAlarmB);
-
- HAL_Delay(2000);
-
- transmit_uart("Entering sleep mode.\r\n");
- HAL_SuspendTick();
- HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI);
- HAL_ResumeTick();
-
- if (makeStepFlag) {
- // Poll ADC1 Perihperal & TimeOut = 1mSec
- HAL_ADC_PollForConversion(&hadc1, 1);
- // Read The ADC Conversion Result
- AD_RES = HAL_ADC_GetValue(&hadc1);
-
- transmit_uart("Making a step.\r\n");
- BSP_MotorControl_Move(0, FORWARD, stepsToMake);
- BSP_MotorControl_WaitWhileActive(0);
- }
-
- makeStepFlag = true;
-
- transmit_uart("\r\n");
-
- };
- }
-
- BSP_MotorControl_GoHome(0);
- BSP_MotorControl_WaitWhileActive(0);
- }
- /* USER CODE END 3 */
- }
-
- /**
- * @brief System Clock Configuration
- * @retval None
- */
- void SystemClock_Config(void)
- {
- RCC_OscInitTypeDef RCC_OscInitStruct = {0};
- RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
- RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0};
-
- /** Configure the main internal regulator output voltage
- */
- __HAL_RCC_PWR_CLK_ENABLE();
- __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
- /** Initializes the RCC Oscillators according to the specified parameters
- * in the RCC_OscInitTypeDef structure.
- */
- RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI|RCC_OSCILLATORTYPE_LSI;
- RCC_OscInitStruct.HSIState = RCC_HSI_ON;
- //RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
- RCC_OscInitStruct.HSICalibrationValue = 16;
- RCC_OscInitStruct.LSIState = RCC_LSI_ON;
- RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
- RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
- RCC_OscInitStruct.PLL.PLLM = 16;
- RCC_OscInitStruct.PLL.PLLN = 336;
- RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
- RCC_OscInitStruct.PLL.PLLQ = 7;
- if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
- {
- Error_Handler();
- }
- /** Initializes the CPU, AHB and APB buses clocks
- */
- RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
- |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
- RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
- RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
- RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
- RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
-
- if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
- {
- Error_Handler();
- }
- PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC;
- PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSI;
- if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK)
- {
- Error_Handler();
- }
- }
-
- /**
-
- * @brief RTC Initialization Function
- * @param None
- * @retval None
- */
- static void MX_RTC_Init(void)
- {
-
- /* USER CODE BEGIN RTC_Init 0 */
-
- /* USER CODE END RTC_Init 0 */
-
- RTC_TimeTypeDef sTime = {0};
- RTC_DateTypeDef sDate = {0};
- RTC_AlarmTypeDef sAlarm = {0};
-
- /* USER CODE BEGIN RTC_Init 1 */
-
- /* USER CODE END RTC_Init 1 */
- /** Initialize RTC Only
- */
- hrtc.Instance = RTC;
- hrtc.Init.HourFormat = RTC_HOURFORMAT_24;
- hrtc.Init.AsynchPrediv = 127;
- hrtc.Init.SynchPrediv = 255;
- hrtc.Init.OutPut = RTC_OUTPUT_DISABLE;
- hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
- hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN;
- if (HAL_RTC_Init(&hrtc) != HAL_OK)
- {
- Error_Handler();
- }
-
- /* USER CODE BEGIN Check_RTC_BKUP */
-
- /* USER CODE END Check_RTC_BKUP */
-
- /** Initialize RTC and set the Time and Date
- */
- sTime.Hours = 7;
- sTime.Minutes = 20;
- sTime.Seconds = 10;
- sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
- sTime.StoreOperation = RTC_STOREOPERATION_RESET;
- if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BIN) != HAL_OK)
- {
- Error_Handler();
- }
- sDate.WeekDay = RTC_WEEKDAY_MONDAY;
- sDate.Month = RTC_MONTH_FEBRUARY;
- sDate.Date = 21;
- sDate.Year = 21;
-
- if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BIN) != HAL_OK)
- {
- Error_Handler();
- }
- /** Enable the Alarm A
- */
- sAlarm.AlarmTime.Hours = 0;
- sAlarm.AlarmTime.Minutes = 0;
- sAlarm.AlarmTime.Seconds = 0;
- sAlarm.AlarmTime.SubSeconds = 0;
- sAlarm.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
- sAlarm.AlarmTime.StoreOperation = RTC_STOREOPERATION_RESET;
- sAlarm.AlarmMask = RTC_ALARMMASK_NONE;
- sAlarm.AlarmSubSecondMask = RTC_ALARMSUBSECONDMASK_ALL;
- sAlarm.AlarmDateWeekDaySel = RTC_ALARMDATEWEEKDAYSEL_DATE;
- sAlarm.AlarmDateWeekDay = 1;
- sAlarm.Alarm = RTC_ALARM_A;
- if (HAL_RTC_SetAlarm_IT(&hrtc, &sAlarm, RTC_FORMAT_BIN) != HAL_OK)
- {
- Error_Handler();
- }
- /** Enable the Alarm B
- */
- sAlarm.AlarmDateWeekDay = 1;
- sAlarm.Alarm = RTC_ALARM_B;
- if (HAL_RTC_SetAlarm_IT(&hrtc, &sAlarm, RTC_FORMAT_BIN) != HAL_OK)
- {
- Error_Handler();
- }
- /* USER CODE BEGIN RTC_Init 2 */
-
- /* USER CODE END RTC_Init 2 */
-
- }
-
- /**
- * @brief USART2 Initialization Function
- * @param None
- * @retval None
- */
- static void MX_USART2_UART_Init(void)
- {
-
- /* USER CODE BEGIN USART2_Init 0 */
-
- /* USER CODE END USART2_Init 0 */
-
- /* USER CODE BEGIN USART2_Init 1 */
-
- /* USER CODE END USART2_Init 1 */
- huart2.Instance = USART2;
- huart2.Init.BaudRate = 115200;
- huart2.Init.WordLength = UART_WORDLENGTH_8B;
- huart2.Init.StopBits = UART_STOPBITS_1;
- huart2.Init.Parity = UART_PARITY_NONE;
- huart2.Init.Mode = UART_MODE_TX_RX;
- huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
- huart2.Init.OverSampling = UART_OVERSAMPLING_16;
- if (HAL_UART_Init(&huart2) != HAL_OK)
- {
- Error_Handler();
- }
- /* USER CODE BEGIN USART2_Init 2 */
-
- /* USER CODE END USART2_Init 2 */
-
- }
-
- /**
- * @brief GPIO Initialization Function
- * @param None
- * @retval None
- */
- static void MX_GPIO_Init(void)
- {
- GPIO_InitTypeDef GPIO_InitStruct = {0};
-
- /* GPIO Ports Clock Enable */
- __HAL_RCC_GPIOC_CLK_ENABLE();
- __HAL_RCC_GPIOH_CLK_ENABLE();
- __HAL_RCC_GPIOA_CLK_ENABLE();
- __HAL_RCC_GPIOB_CLK_ENABLE();
-
- /*Configure GPIO pin Output Level */
- HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
-
- /*Configure GPIO pin Output Level */
- HAL_GPIO_WritePin(GPIOB, GPIO_PIN_6, GPIO_PIN_SET);
-
- /*Configure GPIO pin : B1_Pin */
- GPIO_InitStruct.Pin = B1_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
- GPIO_InitStruct.Pull = GPIO_NOPULL;
- HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
-
- /*Configure GPIO pin : LD2_Pin */
- GPIO_InitStruct.Pin = LD2_Pin;
- GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
- GPIO_InitStruct.Pull = GPIO_NOPULL;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
- HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);
-
- /*Configure GPIO pin : PB6 */
- GPIO_InitStruct.Pin = GPIO_PIN_6;
- GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
- GPIO_InitStruct.Pull = GPIO_NOPULL;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
- HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
-
- }
-
- /**
- * @brief ADC1 Initialization Function
- * @param None
- * @retval None
- */
- static void MX_ADC1_Init(void)
- {
-
- /* USER CODE BEGIN ADC1_Init 0 */
-
- /* USER CODE END ADC1_Init 0 */
-
- ADC_ChannelConfTypeDef sConfig = {0};
-
- /* USER CODE BEGIN ADC1_Init 1 */
-
- /* USER CODE END ADC1_Init 1 */
- /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
- */
- hadc1.Instance = ADC1;
- hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
- hadc1.Init.Resolution = ADC_RESOLUTION_12B;
- hadc1.Init.ScanConvMode = DISABLE;
- hadc1.Init.ContinuousConvMode = ENABLE;
- hadc1.Init.DiscontinuousConvMode = DISABLE;
- hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
- hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
- hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
- hadc1.Init.NbrOfConversion = 1;
- hadc1.Init.DMAContinuousRequests = DISABLE;
- hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
- if (HAL_ADC_Init(&hadc1) != HAL_OK)
- {
- Error_Handler();
- }
- /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
- */
- sConfig.Channel = ADC_CHANNEL_0;
- sConfig.Rank = 1;
- sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES;
- if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
- {
- Error_Handler();
- }
- /* USER CODE BEGIN ADC1_Init 2 */
-
- /* USER CODE END ADC1_Init 2 */
-
- }
-
- /**
- * @brief SPI1 Initialization Function
- * @param None
- * @retval None
- */
- static void MX_SPI1_Init(void)
- {
-
- /* USER CODE BEGIN SPI1_Init 0 */
-
- /* USER CODE END SPI1_Init 0 */
-
- /* USER CODE BEGIN SPI1_Init 1 */
-
- /* USER CODE END SPI1_Init 1 */
- /* SPI1 parameter configuration*/
- hspi1.Instance = SPI1;
- hspi1.Init.Mode = SPI_MODE_MASTER;
- hspi1.Init.Direction = SPI_DIRECTION_2LINES;
- hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
- hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
- hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
- hspi1.Init.NSS = SPI_NSS_SOFT;
- hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
- hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
- hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
- hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
- hspi1.Init.CRCPolynomial = 10;
- if (HAL_SPI_Init(&hspi1) != HAL_OK)
- {
- Error_Handler();
- }
- /* USER CODE BEGIN SPI1_Init 2 */
-
- /* USER CODE END SPI1_Init 2 */
-
- }
-
- /* USER CODE BEGIN 4 */
- /**
- * @brief Alarm callback
- * @param hrtc: RTC handle
- * @retval None
- */
- void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc)
- {
- /* Alarm generation */
- alarmSunriseFlag = true;
- alarmSunsetFlag = true;
- transmit_uart("Alarm A Callback triggered.\r\n");
- transmit_uart("Setting sunrise and sunset flags.\r\n");
- }
-
- void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc)
- {
- /* Alarm generation */
- makeStepFlag = true;
- transmit_uart("Alarm B Callback triggered.\r\n");
- transmit_uart("Setting makeStep flag.\r\n");
- }
-
- /**
- * @brief This function is the User handler for the flag interrupt
- * @param None
- * @retval None
- */
- void MyFlagInterruptHandler(void)
- {
- //When EN pin is forced low by a failure, configure the GPIO as an ouput low
- BSP_MotorControl_CmdDisable(0);
- }
-
- /* USER CODE END 4 */
-
- /**
- * @brief This function is executed in case of error occurrence.
- * @retval None
- */
- void Error_Handler(void)
- {
- /* USER CODE BEGIN Error_Handler_Debug */
- /* User can add his own implementation to report the HAL error return state */
- __disable_irq();
- while (1)
- {
- }
- /* USER CODE END Error_Handler_Debug */
- }
-
- void MyErrorHandler(uint16_t error)
- {
- // Motor error handler
- /* Backup error number */
- gLastError = error;
-
- /* Infinite loop */
- while(1)
- {
- }
- }
-
- void ButtonHandler(void)
- {
- gButtonPressed = TRUE;
- /* Let 200 ms before clearing the IT for key debouncing */
- HAL_Delay(200);
- __HAL_GPIO_EXTI_CLEAR_IT(KEY_BUTTON_PIN);
- HAL_NVIC_ClearPendingIRQ(KEY_BUTTON_EXTI_IRQn);
- }
-
- #ifdef USE_FULL_ASSERT
- /**
- * @brief Reports the name of the source file and the source line number
- * where the assert_param error has occurred.
- * @param file: pointer to the source file name
- * @param line: assert_param error line source number
- * @retval None
- */
- void assert_failed(uint8_t *file, uint32_t line)
- {
- /* USER CODE BEGIN 6 */
- /* User can add his own implementation to report the file name and line number,
- ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
- /* USER CODE END 6 */
- }
- #endif /* USE_FULL_ASSERT */
-
- /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
|