diff options
Diffstat (limited to 'app')
40 files changed, 4564 insertions, 0 deletions
diff --git a/app/button/button_handler.c b/app/button/button_handler.c new file mode 100644 index 0000000..7c3ea91 --- /dev/null +++ b/app/button/button_handler.c @@ -0,0 +1,209 @@ +#include "button_handler.h" +#include "ltimers.h" + +#include "nixie_driver_process.h" + +// FreeRTOS includes +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" + +// Обработчик нажатий представляет собой конечный автомат для обработки +// результата работы сенсорной библиотеки, обработки комбинаций и времени +// нажатий и выдачи результата во внешнюю программу + + +#define TIME_BUTTON_LONG_PRESS 1000 // 3 секунды для долгого жмака + + +// Состояние конечного автомата обработчика нажатий +typedef enum { + BUTTON_STATE_START = 0, + BUTTON_STATE_ONE_BUT_IS_PRESSING_NOW, + BUTTON_STATE_TWO_BUTS_AND_TIMER, + BUTTON_STATE_TWO_BUTS_AFTER_TIMER +} Button_FSMStates_t; + +// Комбнации нажатостей кнопушек (нажата одна, зажаты две и тд.) +enum { + BUT_COMB_NONE = 0, + BUT_COMB_BUT1 = 1, + BUT_COMB_BUT2 = 2, + BUT_COMB_BOTH = 3 +} ; + +QueueHandle_t queue_but_comb; + +// - сделать в обработчике вывода индикации ламп на нижнем уровне, +// чтобы ты отправлял цифру на индикатор, а он сам уже преобразовывал + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void ButtonInit ( void ) +{ + queue_but_comb = xQueueCreate ( 1, sizeof (ButtonCombName_t) ); + configASSERT( queue_but_comb ); +} + + +// ---------------------------------------------------------------------------- +// Конечный автомат-обработчик нажатий кнопушек +// Note: +// Антидребезг в данном автомате не нужен, т.к. обработчик сенсорной библиотеки +// уже все сделал (а вот не сделал, возможно от микродребезга есть защита, +// а вот от крупного дребезга нет защиты) +// ---------------------------------------------------------------------------- +void Button_ProcessFSM ( void ) +{ + static Button_FSMStates_t state_fsm_button = BUTTON_STATE_START; + static uint8_t still_pushed = 0; + + static uint8_t prev_button_comb; + static uint8_t curr_button_comb; + static ButtonCombName_t msg_but_comb_name; + + switch ( state_fsm_button ) + { + // ------------------------------------------------------------------------- + case BUTTON_STATE_START: + + curr_button_comb = Button_GetCurrButtons(); + + if ( curr_button_comb != BUT_COMB_NONE ) + { + prev_button_comb = curr_button_comb; + state_fsm_button = BUTTON_STATE_ONE_BUT_IS_PRESSING_NOW; + still_pushed = 0; + } + + break; + // ------------------------------------------------------------------------- + case BUTTON_STATE_ONE_BUT_IS_PRESSING_NOW: + // - 1 отпустили + // - 2 нажали вторую + // - 3 вторая кнопка, но такого не должно быть(ошибка) + + curr_button_comb = Button_GetCurrButtons(); + + // Сначала проверим, вдруг кнопушку отпустили + if ( (curr_button_comb == BUT_COMB_NONE) && (still_pushed == 0) ) + { + // - сообщ.: "Одиночный обратный жмак" + + switch ( prev_button_comb ) + { + case BUT_COMB_BUT1: + xQueueReceive ( queue_but_comb, &msg_but_comb_name, 0 ); + msg_but_comb_name = BUTTON_SINGLE_FORWARD; + xQueueSend ( queue_but_comb, &msg_but_comb_name, 0 ); + break; + case BUT_COMB_BUT2: + xQueueReceive ( queue_but_comb, &msg_but_comb_name, 0 ); + msg_but_comb_name = BUTTON_SINGLE_BACKWARD; + xQueueSend ( queue_but_comb, &msg_but_comb_name, 0 ); + break; + default: + break; + } + + state_fsm_button = BUTTON_STATE_START; + + return; + } + + if ( (curr_button_comb == BUT_COMB_NONE) && (still_pushed == 1) ) + { + state_fsm_button = BUTTON_STATE_START; + return; + } + + switch ( prev_button_comb ) + { + case BUT_COMB_BUT1: + + if ( curr_button_comb == BUT_COMB_BOTH ) + { + // - тогда сообщ.: "Зажатый прямой жмак вперед" + xQueueReceive ( queue_but_comb, &msg_but_comb_name, 0 ); + //msg_but_comb_name = BUTTON_HOLD_FORWARD; + msg_but_comb_name = BUTTON_HOLD_BACKWARD; + xQueueSend ( queue_but_comb, &msg_but_comb_name, 0 ); + StartLTimer ( LTIMER_BUTTON_LONG_PRESS ); + state_fsm_button = BUTTON_STATE_TWO_BUTS_AND_TIMER; + still_pushed = 1; + } + + break; + + case BUT_COMB_BUT2: + + if ( curr_button_comb == BUT_COMB_BOTH ) + { + // - тогда сообщ.: "Зажатый прямой жмак назад" + xQueueReceive ( queue_but_comb, &msg_but_comb_name, 0 ); + //msg_but_comb_name = BUTTON_HOLD_BACKWARD; + msg_but_comb_name = BUTTON_HOLD_FORWARD; + xQueueSend ( queue_but_comb, &msg_but_comb_name, 0 ); + + StartLTimer ( LTIMER_BUTTON_LONG_PRESS ); + state_fsm_button = BUTTON_STATE_TWO_BUTS_AND_TIMER; + still_pushed = 1; + } + + break; + + default: + state_fsm_button = BUTTON_STATE_START; + break; + } + + break; + + // ------------------------------------------------------------------------- + case BUTTON_STATE_TWO_BUTS_AND_TIMER: + + curr_button_comb = Button_GetCurrButtons(); + + if ( curr_button_comb == BUT_COMB_BOTH ) + { + if ( GetLTimer (LTIMER_BUTTON_LONG_PRESS) == TIME_BUTTON_LONG_PRESS ) + { + // - сообщ.: "Две долго" + xQueueReceive ( queue_but_comb, &msg_but_comb_name, 0 ); + msg_but_comb_name = BUTTON_LONG; + xQueueSend ( queue_but_comb, &msg_but_comb_name, 0 ); + + state_fsm_button = BUTTON_STATE_TWO_BUTS_AFTER_TIMER; + } + } + else + { + prev_button_comb = curr_button_comb; + state_fsm_button = BUTTON_STATE_ONE_BUT_IS_PRESSING_NOW; + } + + break; + + // ------------------------------------------------------------------------- + case BUTTON_STATE_TWO_BUTS_AFTER_TIMER: + + curr_button_comb = Button_GetCurrButtons(); + + if ( curr_button_comb == BUT_COMB_NONE ) + { + state_fsm_button = BUTTON_STATE_START; + } + else if ( curr_button_comb != BUT_COMB_BOTH ) + { + prev_button_comb = curr_button_comb; + state_fsm_button = BUTTON_STATE_ONE_BUT_IS_PRESSING_NOW; + } + + break; + + default: + break; + } +} diff --git a/app/button/button_handler.h b/app/button/button_handler.h new file mode 100644 index 0000000..86118fa --- /dev/null +++ b/app/button/button_handler.h @@ -0,0 +1,18 @@ +#ifndef BUTTON_HANDLER_INCLUDED +#define BUTTON_HANDLER_INCLUDED + +#include <stdint.h> + +typedef enum { + BUTTON_SINGLE_FORWARD, + BUTTON_SINGLE_BACKWARD, + BUTTON_HOLD_FORWARD, + BUTTON_HOLD_BACKWARD, + BUTTON_LONG +} ButtonCombName_t; + +void ButtonInit ( void ); +uint8_t Button_GetCurrButtons ( void ); +void Button_ProcessFSM ( void ); + +#endif //BUTTON_HANDLER_INCLUDED diff --git a/app/button/button_task.c b/app/button/button_task.c new file mode 100644 index 0000000..cc0a73f --- /dev/null +++ b/app/button/button_task.c @@ -0,0 +1,229 @@ +#include "head_task.h" +#include "tsl_user.h" +#include "nixie_driver_process.h" + +#include "button_handler.h" +#include "ltimers.h" + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +#define TKEY_NUM_1 0 +#define TKEY_NUM_2 1 + +#define TIME_SENSOR_BUT_DEBOUNCE 50 //ms + +// Эти определения пойдут в модуль обработки кнопушек уровня пользователя - Button_Module + +#define TEST_TKEY(NB) ((MyTKeys[(NB)].p_Data->StateId == TSL_STATEID_DETECT) ||\ + (MyTKeys[(NB)].p_Data->StateId == TSL_STATEID_DEB_RELEASE_DETECT)) + +#define TEST_LINROT(NB) ((MyLinRots[(NB)].p_Data->StateId == TSL_STATEID_DETECT) ||\ + (MyLinRots[(NB)].p_Data->StateId == TSL_STATEID_DEB_RELEASE_DETECT)) + +// For debug purpose with STMStudio +uint8_t DS[TSLPRM_TOTAL_TKEYS + TSLPRM_TOTAL_LNRTS]; // To store the States (one per object) +int16_t DD[TSLPRM_TOTAL_TKEYS + (TSLPRM_TOTAL_LNRTS * 3)]; // To store the Deltas (one per channel) + +// Битовая переменная, в которой будут устанавливаться соответствующие +// номерам нажатых кнопушек биты +static volatile uint8_t tkey_buttons_bits = 0; + + +static void ProcessSensors ( void ); +static void TkeyDebounce ( void ); + + +// ---------------------------------------------------------------------------- +// Ф-я которая будет возвращать значение битовой переменной +// и вызываться из модуля button_handler.c (ф-я Button_ProcessFSM ();) +// ---------------------------------------------------------------------------- +uint8_t Button_GetCurrButtons ( void ) +{ + uint8_t curr_buts_bits = tkey_buttons_bits; + return curr_buts_bits; +} + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void ProcessFSM_ButtonTask ( void ) +{ + /* Execute STMTouch Driver state machine */ + if (TSL_user_Action () == TSL_STATUS_OK) + { + ProcessSensors (); // Execute sensors related tasks + + // Обработчик нажатий кнопушек (автомат) + //Button_ProcessFSM (); + } + Button_ProcessFSM (); + taskYIELD(); +} + + +/** + * @brief Manage the activity on sensors when touched/released (example) + * @param None + * @retval None + */ +static void ProcessSensors ( void ) +{ + uint32_t idx; + uint32_t idx_ds = 0; + uint32_t idx_dd = 0; +#if USE_LCD > 0 + static uint32_t started = 0; +#endif + +#if TSLPRM_TOTAL_TKEYS > 0 + // Read all TKeys + for (idx = 0; idx < TSLPRM_TOTAL_TKEYS; idx++) + { + // STMStudio debug + DS[idx_ds++] = MyTKeys[idx].p_Data->StateId; + DD[idx_dd++] = MyTKeys[idx].p_ChD->Delta; + } +#endif + +#if TSLPRM_TOTAL_LNRTS > 0 + uint32_t idxch; + // Read all Linear and Rotary sensors + for (idx = 0; idx < TSLPRM_TOTAL_LNRTS; idx++) + { + // STMStudio debug + DS[idx_ds++] = MyLinRots[idx].p_Data->StateId; + for (idxch = 0; idxch < MyLinRots[idx].NbChannels; idxch++) + { + DD[idx_dd++] = MyLinRots[idx].p_ChD[idxch].Delta; + } + } +#endif + + // Сделаем обработчик антидребезга (вроде он есть в библе сенсорных кнопок, + // но GROUP5 почему-то сильно дергается) + + TkeyDebounce(); + + // Тут можно поменять кнопки местами +} + +/** + * @brief Executed when a sensor is in Off state + * @param None + * @retval None + */ +void MyTKeys_OffStateProcess(void) +{ + /* Add here your own processing when a sensor is in Off state */ +} + +void MyLinRots_OffStateProcess(void) +{ + /* Add here your own processing when a sensor is in Off state */ +} + +/** + * @brief Executed at each timer interruption (option must be enabled) + * @param None + * @retval None + */ +void TSL_CallBack_TimerTick(void) +{ +} + +/** + * @brief Executed when a sensor is in Error state + * @param None + * @retval None + */ +void MyTKeys_ErrorStateProcess(void) +{ + /* Add here your own processing when a sensor is in Error state */ + TSL_tkey_SetStateOff (); + while(1) + { + } +} + +void MyLinRots_ErrorStateProcess(void) +{ + /* Add here your own processing when a sensor is in Error state */ + TSL_linrot_SetStateOff(); + while(1) + { + } +} + + +// ---------------------------------------------------------------------------- +// Ф-я антидребезга для сенсорных кнопок +// ---------------------------------------------------------------------------- +void TkeyDebounce ( void ) +{ + static uint8_t tkey_db_state = 1; + static uint8_t tkey_code = 0; + static uint8_t _tkey_code = 1; // предыдущее состояние кнопок + + if (TEST_TKEY(TKEY_NUM_2)) + { + tkey_code |= 1 << TKEY_NUM_1; + } + else + { + tkey_code &= ~(1 << TKEY_NUM_1); + } + + if (TEST_TKEY(TKEY_NUM_1)) + { + tkey_code |= 1 << TKEY_NUM_2; + } + else + { + tkey_code &= ~(1 << TKEY_NUM_2); + } + + switch (tkey_db_state) + { + case 1: + if ( tkey_code != _tkey_code ) // если нажата любая сенсорная кнопушка + { + _tkey_code = tkey_code; + tkey_db_state = 2; + StartLTimer (LTIMER_SENSOR_BUT_DEBOUNCE); + } + break; + + case 2: + if( GetLTimer( LTIMER_SENSOR_BUT_DEBOUNCE ) >= TIME_SENSOR_BUT_DEBOUNCE ) + { + tkey_db_state = 3; + } + break; + + case 3: + if( _tkey_code == tkey_code ) + { + tkey_db_state = 1; + tkey_buttons_bits = _tkey_code; + + } + else { tkey_db_state = 1; } + break; + + default: + break; + } // end switch +} + + +// ---------------------------------------------------------------------------- +// Задача ОС, реализующая обработку нажатий кнопушек +// Здесь обрабатывается уже результат обработки сенсорных нажатий +// ---------------------------------------------------------------------------- +void Button_Task ( void *pvParameters ) +{ + while(1)ProcessFSM_ButtonTask (); +} diff --git a/app/button/button_task.h b/app/button/button_task.h new file mode 100644 index 0000000..c55f8c3 --- /dev/null +++ b/app/button/button_task.h @@ -0,0 +1,8 @@ +#ifndef BUTTON_TASK_INCLUDED +#define BUTTON_TASK_INCLUDED + +#include "stm32f0xx.h" + +void Button_Task ( void *pvParameters ); + +#endif //BUTTON_TASK_INCLUDED
\ No newline at end of file diff --git a/app/head_task/head_task.c b/app/head_task/head_task.c new file mode 100644 index 0000000..db693f7 --- /dev/null +++ b/app/head_task/head_task.c @@ -0,0 +1,368 @@ +#include "head_task.h" + +// FreeRTOS includes +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +#include "ltimers.h" + +#include "indicate_modes_task.h" +#include "nixie_driver_process.h" +#include "button_handler.h" +#include "stm32f0xx_rtc.h" + + +// Номера функций меню +typedef enum { + MENU_FUNC_SIMPLE_TIME_VIEW = 0, + MENU_ADJ_TIME, + MAX_MENU_FUNCTIONS +} MenuFunctionsNums_t; + +// Состояния режима меню AdjTime +typedef enum { + STATE_MENU_ADJ_TIME_START, + STATE_MENU_ADJ_TIME_TIMER_OUT +} MenuAdjTimeStates_t; + +static MenuFunctionsNums_t curr_menu_func = MENU_FUNC_SIMPLE_TIME_VIEW; + +// Прототипы функций меню +static void MenuFunc_SimpleTimeView ( void ); +static void MenuFunc_AdjTime ( void ); + + +// Массив указателей на функции-меню +typedef void ( *MenuFunctions_t ) ( void ); +static const MenuFunctions_t MenuFunctions[MAX_MENU_FUNCTIONS] = { + + MenuFunc_SimpleTimeView, + MenuFunc_AdjTime + +}; + +void GetCurrTime ( DataToIndicate_t* indic_data ); +void SetTime ( DataToIndicate_t* indic_data ); +void AdjTimeChangeTube ( ButtonCombName_t but_comb_name, uint8_t *position ); +void AdjTimeChangeValue ( ButtonCombName_t but_comb_name, IndicModesMsgBlink_t* data, uint8_t position_mask ); +void ChangeValue ( uint8_t increase, uint8_t *data, uint8_t limit ); + + +DataToIndicate_t indic_data; +extern QueueHandle_t queue_data_to_indic; // indicate_modes_task.c +extern QueueHandle_t queue_but_comb; // button_handler.c +extern QueueHandle_t queue_data_to_blink_mode; + QueueHandle_t queue_switch_indic_mode; + +static MenuAdjTimeStates_t state_adj_time = STATE_MENU_ADJ_TIME_START; + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void HeadTaskInit ( void ) +{ + queue_switch_indic_mode = xQueueCreate ( 1, sizeof (IndicModesNums_t) ); + configASSERT( queue_switch_indic_mode ); + + curr_menu_func = MENU_FUNC_SIMPLE_TIME_VIEW; +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void MenuFunc_SimpleTimeView ( void ) +{ + RTC_TimeTypeDef RTC_TimeStructure; + + /* Get the current Time */ + RTC_GetTime(RTC_Format_BCD, &RTC_TimeStructure); + GetCurrTime ( &indic_data ); + xQueueSend ( queue_data_to_indic, &indic_data, 0 ); +} + + +// ---------------------------------------------------------------------------- +// Ф-я-меню настройки времени +// ---------------------------------------------------------------------------- +void MenuFunc_AdjTime ( void ) +{ + static const uint32_t TIME_ADJ_OUT = 5000; //ms + + static IndicModesMsgBlink_t blink_data_struct; + static ButtonCombName_t but_comb_name; + IndicModesNums_t indic_mode_num; + static uint8_t position_mask; + + // - при этом нужно постоянно слать текущее время на вывод, то есть + // при настройке времени оно тикает как в обычном режиме, только + // пользователь может его изменять при этом + + switch ( state_adj_time ) + { + case STATE_MENU_ADJ_TIME_START: + + indic_mode_num = INDIC_MODE_BLINK; + // Отправляем сообщение на переключение режима индикации + xQueueSend ( queue_switch_indic_mode, &indic_mode_num, 0 ); + + // Отправляем сообщение с данными для индикации + // Но сначала, сотрем, вдруг прошлое собщение не было прочитано + xQueueReceive ( queue_data_to_blink_mode, &blink_data_struct, 0 ); + + GetCurrTime ( &blink_data_struct.data ); + blink_data_struct.mask_byte = 32; + position_mask = blink_data_struct.mask_byte; + + xQueueSend ( queue_data_to_blink_mode, &blink_data_struct, 0 ); + + state_adj_time = STATE_MENU_ADJ_TIME_TIMER_OUT; + StartLTimer ( LTIMER_MENU_ADJ_TIME_OUT ); + + break; + + case STATE_MENU_ADJ_TIME_TIMER_OUT: + + if ( GetLTimer (LTIMER_MENU_ADJ_TIME_OUT) >= TIME_ADJ_OUT ) + { + state_adj_time = STATE_MENU_ADJ_TIME_START; + // Выходим из этого меню режима + curr_menu_func = MENU_FUNC_SIMPLE_TIME_VIEW; + indic_mode_num = INDIC_MODE_STANDART; + xQueueSend ( queue_switch_indic_mode, &indic_mode_num, 0 ); + // При выходе из настройки времени нужно послать сообщ. на обновление + // данных в простой режим, т.к. фаза в моргающем режиме могла быть + // отрицательной, а данные обновляются только раз в секунду, и поэтому + // лампа может быть потухшей 1 секунду. + // - тут лучше сделать завершение фазы моргания + GetCurrTime ( &indic_data ); + xQueueSend ( queue_data_to_indic, &indic_data, 0 ); + } + else + { + // Если жмакнули кнопушку, то сбрасываем таймер, затем смотрим + // какую кнопушку жмакнули + if ( pdPASS == xQueueReceive ( queue_but_comb, &but_comb_name, 0 ) ) + { + StartLTimer ( LTIMER_MENU_ADJ_TIME_OUT ); + + // Тут в зависимости от того, какую кнопушку жмакнули + switch ( but_comb_name ) + { + case BUTTON_SINGLE_FORWARD: + case BUTTON_SINGLE_BACKWARD: + // Меняем позицию времени + AdjTimeChangeTube (but_comb_name, &position_mask); + GetCurrTime ( &blink_data_struct.data ); + blink_data_struct.mask_byte = position_mask; + xQueueSend ( queue_data_to_blink_mode, &blink_data_struct, 0 ); + break; + + case BUTTON_HOLD_FORWARD: + case BUTTON_HOLD_BACKWARD: + // Меняем значение времени + GetCurrTime ( &blink_data_struct.data ); + AdjTimeChangeValue ( but_comb_name, &blink_data_struct, position_mask ); + SetTime ( &blink_data_struct.data ); + xQueueSend ( queue_data_to_blink_mode, &blink_data_struct, 0 ); + break; + + default: + break; + } + } + else + { + // - тут, если время изменилось, то отправляем его на вывод + GetCurrTime ( &blink_data_struct.data ); + xQueueSend ( queue_data_to_blink_mode, &blink_data_struct, 0 ); + } + } + + break; + + default: + break; + } +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void ProcessFSM_Head ( void ) +{ + + // - тут можно совершать внешние переключения функций меню: + // - ловить сообщения от внешних источников для перехода в нужный пункт + // меню (сообщения от gps модуля, wifi и тд.) + + // 1. Ловим сообщение из модуля-обработчика нажатий кнопушек с командой + // на переход в меню настройки (две кнопки зажать на 3 сек) + + // - перед отправкой сообщения в режим индикации сначала стираем сообщение + + static ButtonCombName_t but_comb_name; + + if ( pdPASS == xQueuePeek ( queue_but_comb, &but_comb_name, 0 ) ) + { + if ( but_comb_name == BUTTON_LONG ) + { + // - при изменении состояния меню или режима, нужно также сбрасывать + // внутреннее состояние текущего режима + + xQueueReceive ( queue_but_comb, &but_comb_name, 0 ); + curr_menu_func = MENU_ADJ_TIME; + } + } + MenuFunctions [curr_menu_func](); + taskYIELD(); +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- + +void GetCurrTime ( DataToIndicate_t *indic_data ) +{ + RTC_TimeTypeDef RTC_TimeStructure; + + /* Get the current Time */ + RTC_GetTime ( RTC_Format_BCD, &RTC_TimeStructure ); + + indic_data->indic_1 = RTC_TimeStructure.RTC_Hours>>4; + indic_data->indic_2 = RTC_TimeStructure.RTC_Hours&0x0F; + + indic_data->indic_3 = RTC_TimeStructure.RTC_Minutes>>4; + indic_data->indic_4 = RTC_TimeStructure.RTC_Minutes&0x0F; + + indic_data->indic_5 = RTC_TimeStructure.RTC_Seconds>>4; + indic_data->indic_6 = RTC_TimeStructure.RTC_Seconds&0x0F; +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void SetTime ( DataToIndicate_t* indic_data ) +{ + RTC_TimeTypeDef RTC_TimeStructure; + + RTC_TimeStructure.RTC_Hours = indic_data->indic_1 << 4; + RTC_TimeStructure.RTC_Hours |= indic_data->indic_2 & 0x0F; + + RTC_TimeStructure.RTC_Minutes = indic_data->indic_3 << 4; + RTC_TimeStructure.RTC_Minutes |= indic_data->indic_4 & 0x0F; + + RTC_TimeStructure.RTC_Seconds = indic_data->indic_5 << 4; + RTC_TimeStructure.RTC_Seconds |= indic_data->indic_6 & 0x0F; + + RTC_SetTime ( RTC_Format_BCD, &RTC_TimeStructure ); +} + + +// ---------------------------------------------------------------------------- +// Ф-я изменения текущего положения моргающей лампы при настройке времени +// Ф-я вызывается из MenuFunc_AdjTime +// Номер лампы соотносится с номером лампы ( левый бит - нулевой, и лампа тоже ) +// ---------------------------------------------------------------------------- +void AdjTimeChangeTube ( ButtonCombName_t but_comb_name, uint8_t *position_mask ) +{ + if ( but_comb_name == BUTTON_SINGLE_FORWARD ) + { + if ( !(*position_mask & ( 1 << 0 )) ) { *position_mask >>= 1; } + else { *position_mask = 32; } // 0010 0000 + } + else + { + if ( *position_mask & ( 1 << 5 ) ) { *position_mask = 1; } + else { *position_mask <<= 1; } + } +} + + +// ---------------------------------------------------------------------------- +// Ф-я изменения значения цифры в текущем положении +// То есть тут настраиваем время "поцифирно" +// ---------------------------------------------------------------------------- +void AdjTimeChangeValue ( ButtonCombName_t but_comb_name, IndicModesMsgBlink_t *data_struct, uint8_t position_mask ) +{ + uint8_t increase; + + if ( but_comb_name == BUTTON_HOLD_FORWARD ) { increase = 1; } + else { increase = 0; } + + switch ( position_mask & 0x3F ) + { + case 0x01: // Секунды единицы + ChangeValue ( increase, &data_struct->data.indic_6, 9 ); + break; + + case 0x04: // Минуты единицы + ChangeValue ( increase, &data_struct->data.indic_4, 9 ); + break; + + case 0x02: // Секунды десятки + ChangeValue ( increase, &data_struct->data.indic_5, 5 ); + break; + + case 0x08: // Минуты десятки + ChangeValue ( increase, &data_struct->data.indic_3, 5 ); + break; + + case 0x10: // Часы единицы + if ( data_struct->data.indic_1 == 2 ) + { + ChangeValue ( increase, &data_struct->data.indic_2, 3 ); + } + else + { + ChangeValue ( increase, &data_struct->data.indic_2, 9 ); + } + break; + + case 0x20: // Часы десятки + if ( data_struct->data.indic_2 <= 3 ) + { + ChangeValue ( increase, &data_struct->data.indic_1, 2 ); + } + else + { + ChangeValue ( increase, &data_struct->data.indic_1, 1 ); + } + break; + } +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- + +void ChangeValue ( uint8_t increase, uint8_t *data, uint8_t limit ) +{ + + if ( increase ) + { + if ( *data < limit ) { *data += 1; } + else { *data = 0; } + } + else + { + if ( *data > 0 ) { *data -= 1; } + else { *data = limit; } + } +} + + +// ---------------------------------------------------------------------------- +// Задача ОС, реализующая головную задачу программы NixieClockSimply +// ---------------------------------------------------------------------------- +void Head_Task ( void *pvParameters ) +{ + while(1)ProcessFSM_Head (); +} diff --git a/app/head_task/head_task.h b/app/head_task/head_task.h new file mode 100644 index 0000000..613516c --- /dev/null +++ b/app/head_task/head_task.h @@ -0,0 +1,9 @@ +#ifndef HEAD_TASK_INCLUDED +#define HEAD_TASK_INCLUDED + +#include "stm32f0xx.h" + +void HeadTaskInit (void); +void Head_Task ( void *pvParameters ); + +#endif //HEAD_TASK_INCLUDED
\ No newline at end of file diff --git a/app/indicate/indicate_modes_task.c b/app/indicate/indicate_modes_task.c new file mode 100644 index 0000000..95d8da5 --- /dev/null +++ b/app/indicate/indicate_modes_task.c @@ -0,0 +1,285 @@ +#include "indicate_modes_task.h" +#include "nixie_driver_process.h" +#include "ltimers.h" + +// FreeRTOS includes +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + + +typedef enum { + + STATE_BLINK_START_OFF, + STATE_BLINK_TIMER_OFF, + STATE_BLINK_TIMER_ON + +} IndicModesBlinkStates_t; + +static IndicModesBlinkStates_t state_blink = STATE_BLINK_TIMER_OFF; + +static IndicModesNums_t curr_indic_mode = INDIC_MODE_STANDART; + +QueueHandle_t queue_data_to_indic; +QueueHandle_t queue_data_to_blink_mode; +extern QueueHandle_t queue_switch_indic_mode; + + +// Прототипы функций меню +static void IndicMode_Standart ( void ); +static void IndicMode_Blink ( void ); + +void DataCopyToArray ( uint8_t *data_arr, DataToIndicate_t *data_struct ); +void DataCopyToStruct ( DataToIndicate_t *data_struct, uint8_t *data_arr ); +void WriteOffByte ( uint8_t *array, uint8_t mask ); + + +// Массив указателей на функции-меню +typedef void ( *IndicModes_t ) ( void ); +static const IndicModes_t IndicModes[MAX_INDIC_MODES] = { + + IndicMode_Standart, + IndicMode_Blink + +}; + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void IndicateModesInit ( void ) +{ + queue_data_to_indic = xQueueCreate ( 1, sizeof (DataToIndicate_t) ); + configASSERT( queue_data_to_indic ); + + queue_data_to_blink_mode = xQueueCreate ( 1, sizeof (IndicModesMsgBlink_t) ); + configASSERT( queue_data_to_indic ); +} + + +// ---------------------------------------------------------------------------- +// Режим инжикации "Стандартный", когда время выводится без эффектов +// ---------------------------------------------------------------------------- +static void IndicMode_Standart ( void ) +{ + ; + + // Важное замечание! + // При передаче указателя массива через очередь ОС нужно передавать весь + // массив целиком, чтобы полученный экземпляр данных не менялся. Для передачи + // шести байт можно сделать небольшую структуру + + // - тут проверяем сообщение из очереди ОС на обновление выводимых данных + // и если они изменились, то отправляем их в модуль Никси + + static DataToIndicate_t data_struct; + + if ( pdPASS == xQueueReceive ( queue_data_to_indic, &data_struct, 0 ) ) + { + NixieDriver_SendValue2 ( data_struct ); + } +} + + +// ---------------------------------------------------------------------------- +// Режим "моргания" индикаторов +// В сообщении из очереди принимаются данные, которые нужно вывести, и +// маска-байт, которая соответствует номеру индикатора, который должен +// моргать. Если байт установлен, то индикатор моргает. Могут моргать сразу +// несколько индикаторов. Моргание синхронное. +// Останавливать задачу в этих функция нельзя +// - тут лучше было бы сделать ожидание завершения фазы моргания +// ---------------------------------------------------------------------------- +static void IndicMode_Blink ( void ) +{ + ; + // - принимаем сообщение с данными и маской, и на номер установленного + // байта записываем пустой символ, запоминая его. Затем запускаем таймер + // и отправляем массив данных с "дыркой" на вывод. После таймера + // записываем сохраненное значение и выводим с таймером "чистые" значения + + static const uint32_t TIME_BLINK_OFF = 250; // ms + static const uint32_t TIME_BLINK_ON = 250; // ms + + static DataToIndicate_t data_struct; + static IndicModesMsgBlink_t data_new_struct; + + static uint8_t indic_data_off [MAX_TUBES]; + static uint8_t prev_indic_data_off [MAX_TUBES]; + static uint8_t new_indic_data_off [MAX_TUBES]; + + static uint8_t prev_mask_byte = 0; + static uint8_t is_blink_tube = 0; + + + if ( pdPASS == xQueueReceive ( queue_data_to_blink_mode, &data_new_struct, 0 ) ) + { + DataCopyToArray ( &new_indic_data_off[0], &data_new_struct.data ); + + DataCopyToArray ( &indic_data_off[0], &data_new_struct.data ); + WriteOffByte ( &indic_data_off[0], data_new_struct.mask_byte ); // теперь можно вместо пустой цифры отправлять точку + DataCopyToStruct ( &data_struct, &indic_data_off[0] ); + + // Если изменилась только маска байта, то начинаем моргать с отрицательной + // фазы + if ( prev_mask_byte != data_new_struct.mask_byte ) + { + prev_mask_byte = data_new_struct.mask_byte; + NixieDriver_SendValue2 ( data_struct ); + StartLTimer ( LTIMER_INDIC_MODE_BLINK_OFF ); + state_blink = STATE_BLINK_TIMER_OFF; + } + else + { + // А если изменились данные моргающей лампы, то начинать с + // положительной фазы + for ( uint8_t tube_num = 0; tube_num < MAX_TUBES; tube_num++ ) + { + if ( (prev_indic_data_off[tube_num] != new_indic_data_off[tube_num]) )// В этой лампе данные не равны? + { + if ( data_new_struct.mask_byte & ( 32 >> tube_num ) ) // И эта лампа моргающая? + { + is_blink_tube = 1; + break; + } + } + } // end for + + if ( is_blink_tube == 1 ) + { + NixieDriver_SendValue2 ( data_new_struct.data ); + StartLTimer ( LTIMER_INDIC_MODE_BLINK_ON ); + state_blink = STATE_BLINK_TIMER_ON; + is_blink_tube = 0; + } + else + { + if ( state_blink == STATE_BLINK_TIMER_OFF ) + { + NixieDriver_SendValue2 ( data_struct ); + } + else + { + NixieDriver_SendValue2 ( data_new_struct.data ); + } + } + } + + DataCopyToArray ( &prev_indic_data_off[0], &data_new_struct.data ); + } + + switch ( state_blink ) + { + case STATE_BLINK_TIMER_OFF: + + if ( GetLTimer ( LTIMER_INDIC_MODE_BLINK_OFF ) >= TIME_BLINK_OFF ) + { + NixieDriver_SendValue2 ( data_new_struct.data ); + state_blink = STATE_BLINK_TIMER_ON; + StartLTimer ( LTIMER_INDIC_MODE_BLINK_ON ); + } + + break; + + case STATE_BLINK_TIMER_ON: + + if ( GetLTimer ( LTIMER_INDIC_MODE_BLINK_ON ) >= TIME_BLINK_ON ) + { + NixieDriver_SendValue2 ( data_struct ); + state_blink = STATE_BLINK_TIMER_OFF; + StartLTimer ( LTIMER_INDIC_MODE_BLINK_OFF ); + } + + break; + } +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void DataCopyToStruct ( DataToIndicate_t *data_struct, uint8_t *data_arr ) +{ + data_struct->indic_1 = data_arr[0]; + data_struct->indic_2 = data_arr[1]; + data_struct->indic_3 = data_arr[2]; + data_struct->indic_4 = data_arr[3]; + data_struct->indic_5 = data_arr[4]; + data_struct->indic_6 = data_arr[5]; +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void DataCopyToArray ( uint8_t *data_arr, DataToIndicate_t *data_struct ) +{ + data_arr[0] = data_struct->indic_1; + data_arr[1] = data_struct->indic_2; + data_arr[2] = data_struct->indic_3; + data_arr[3] = data_struct->indic_4; + data_arr[4] = data_struct->indic_5; + data_arr[5] = data_struct->indic_6; +} + + +// ---------------------------------------------------------------------------- +// Ф-я записи в массив "темной" лампы +// ---------------------------------------------------------------------------- +void WriteOffByte ( uint8_t *array, uint8_t mask ) +{ + for ( uint8_t tube_num = 0; tube_num < MAX_TUBES; tube_num++ ) + { + if ( mask & ( 32 >> tube_num ) ) + { + //array [tube_num] = TUBE_EMPTY_VALUE; // - тут цифра 10 это TUBE_DIGIT_EMPTY + // Можно поробовать здесь отправлять точку вместо пустого символа + array [tube_num] = 12; // Шлем номер значения цифры из массива tube_digits [MAX_DIGITS] + } + } +} + + +// ---------------------------------------------------------------------------- +// Режимы работы индикации (моргать, плавно переключаться и тд.) +// ---------------------------------------------------------------------------- +void ProcessFSM_IndicateModes ( void ) +{ + // - тут нужно принимать сообщения из модуля Меню и переходить в нужный режим + // индикации + // При этом нужно помнить, что режим индикации может иметь много состояний, + // поэтому нужно сбрасывать это состояние и, возможно, другие переменные + // перед переключением в другой режим. + + IndicModesNums_t indic_mode_num; + + if ( pdPASS == xQueueReceive ( queue_switch_indic_mode, &indic_mode_num, 0 ) ) + { + // Сначала переведем состояние отключаемого режима в начальное + switch ( curr_indic_mode ) + { + case INDIC_MODE_STANDART: + + break; + + case INDIC_MODE_BLINK: + state_blink = STATE_BLINK_TIMER_OFF; + break; + } + + curr_indic_mode = indic_mode_num; + } + + IndicModes [curr_indic_mode](); + taskYIELD(); +} + + +// ---------------------------------------------------------------------------- +// Задача ОС, реализующая головную задачу программы NixieClockSimply +// ---------------------------------------------------------------------------- +void IndicateModes_Task ( void *pvParameters ) +{ + while(1)ProcessFSM_IndicateModes (); +} diff --git a/app/indicate/indicate_modes_task.h b/app/indicate/indicate_modes_task.h new file mode 100644 index 0000000..e37406f --- /dev/null +++ b/app/indicate/indicate_modes_task.h @@ -0,0 +1,31 @@ +#ifndef INDICATE_MODES_TASK_INCLUDED +#define INDICATE_MODES_TASK_INCLUDED + +#include <stdint.h> +#include "nixie_driver_process.h" + +// Номера режимов индикации +typedef enum { + + INDIC_MODE_STANDART = 0, + INDIC_MODE_BLINK, + + MAX_INDIC_MODES + +} IndicModesNums_t; + + +// Структура для передачи сообщения индикации при настройке времени +// в режиме blink +typedef struct { + + DataToIndicate_t data; + uint8_t mask_byte; + +} IndicModesMsgBlink_t; + + +void IndicateModesInit ( void ); +void IndicateModes_Task ( void *pvParameters ); + +#endif //INDICATE_MODES_TASK_INCLUDED diff --git a/app/ld/_flash.ld b/app/ld/_flash.ld new file mode 100644 index 0000000..ec94ea7 --- /dev/null +++ b/app/ld/_flash.ld @@ -0,0 +1,33 @@ +SECTIONS { + . = ORIGIN(FLASH); + .text : { + KEEP(*(.stack)) + KEEP(*(.vectors)) + KEEP(*(.vectors*)) + KEEP(*(.text)) + . = ALIGN(4); + *(.text*) + . = ALIGN(4); + KEEP(*(.rodata)) + *(.rodata*) + . = ALIGN(4); + } >FLASH + + .preinit_array ALIGN(4): { + __preinit_array_start = .; + KEEP(*(.preinit_array)) + __preinit_array_end = .; + } >FLASH + + .init_array ALIGN(4): { + __init_array_start = .; + KEEP(*(.init_array)) + __init_array_end = .; + } >FLASH + + .fini_array ALIGN(4): { + __fini_array_start = .; + KEEP(*(.fini_array)) + __fini_array_end = .; + } >FLASH +} diff --git a/app/ld/_sram.ld b/app/ld/_sram.ld new file mode 100644 index 0000000..4993c63 --- /dev/null +++ b/app/ld/_sram.ld @@ -0,0 +1,26 @@ +SECTIONS { + __stacktop = ORIGIN(SRAM) + LENGTH(SRAM); + __data_load = LOADADDR(.data); + . = ORIGIN(SRAM); + + .data ALIGN(4) : { + __data_start = .; + *(.data) + *(.data*) + . = ALIGN(4); + __data_end = .; + } >SRAM AT >FLASH + + .bss ALIGN(4) (NOLOAD) : { + __bss_start = .; + *(.bss) + *(.bss*) + . = ALIGN(4); + __bss_end = .; + *(.noinit) + *(.noinit*) + } >SRAM + + . = ALIGN(4); + __heap_start = .; +} diff --git a/app/ld/stm32f072x8.ld b/app/ld/stm32f072x8.ld new file mode 100644 index 0000000..7600040 --- /dev/null +++ b/app/ld/stm32f072x8.ld @@ -0,0 +1,4 @@ +MEMORY { + FLASH(rx) : ORIGIN = 0x08000000, LENGTH = 64K + SRAM(rwx) : ORIGIN = 0x20000000, LENGTH = 16K +} diff --git a/app/led_driver/led_driver_config.c b/app/led_driver/led_driver_config.c new file mode 100644 index 0000000..3b2b081 --- /dev/null +++ b/app/led_driver/led_driver_config.c @@ -0,0 +1,138 @@ +#include "led_driver_config.h" + +static void LED_TIMConfig ( void ); +static void LED_SPIConfig ( void ); + +// ---------------------------------------------------------------------------- +// Подготовка железа, прерываний и тд для работы с RGB светодиодиками +// ---------------------------------------------------------------------------- +void LED_Driver_Config ( void ) +{ + LED_TIMConfig (); + LED_SPIConfig (); +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +static void LED_TIMConfig ( void ) +{ + NVIC_InitTypeDef NVIC_InitStructure; + TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; + + /* LED_TIMx clock enable */ + LED_RCC_APBxPeriphClockCmd ( LED_TIM_RCC, ENABLE ); + + /* Enable the LED_TIMx gloabal Interrupt */ + NVIC_InitStructure.NVIC_IRQChannel = LED_TIM_IRQx; + NVIC_InitStructure.NVIC_IRQChannelPriority = 2; // Установим приоритет ниже, чем у модуля NixieDriver + NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; + NVIC_Init ( &NVIC_InitStructure ); + + /* ----------------------------------------------------------------------- + In this example TIM7 counter clock (TIM7CLK) is set to APB1 clock (PCLK1), since + APB1 prescaler is set to 1 and TIM7 prescaler is set to 0. + + In this example TIM7 input clock (TIM7CLK) is set to APB1 clock (PCLK1), + since APB1 prescaler is set to 1. + TIM7CLK = PCLK1 = HCLK = SystemCoreClock + + With Prescaler set to 479 and Period to 24999, the TIM7 counter is updated each 250 ms + (i.e. and interrupt is generated each 250 ms) + TIM7 counter clock = TIM7CLK /((Prescaler + 1)*(Period + 1)) + = 48 MHz / ((25000)*(480)) + = 4 Hz + ==> TIM7 counter period = 250 ms + + Note: + SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f0xx.c file. + Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate() + function to update SystemCoreClock variable value. Otherwise, any configuration + based on this variable will be incorrect. + ----------------------------------------------------------------------- */ + + /* Time base configuration */ + TIM_TimeBaseStructure.TIM_Period = 1000; // Это миксросекунды //24999 + TIM_TimeBaseStructure.TIM_Prescaler = (SystemCoreClock/1000000)-1; //479; + TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; + TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; + TIM_TimeBaseInit ( LED_TIMx, &TIM_TimeBaseStructure ); + + /* LED_TIMx Interrupts enable */ + TIM_ITConfig ( LED_TIMx, TIM_IT_Update, ENABLE ); + + /* LED_TIMx enable counter */ + TIM_Cmd ( LED_TIMx, ENABLE ); +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +static void LED_SPIConfig ( void ) +{ + GPIO_InitTypeDef GPIO_InitStructure; + SPI_InitTypeDef SPI_InitStructure; + NVIC_InitTypeDef NVIC_InitStructure; + + /* Enable the SPI periph */ + LED_SPIx_RCC_APBxPeriphClockCmd ( LED_SPIx_CLK, ENABLE ); + + /* Enable SCK, MOSI, MISO and NSS GPIO clocks */ + RCC_AHBPeriphClockCmd ( LED_SPIx_SCK_GPIO_CLK | + LED_SPIx_MOSI_GPIO_CLK | + LED_SPIx_ST_GPIO_CLK, + ENABLE ); + + GPIO_PinAFConfig ( LED_SPIx_SCK_GPIO_PORT, LED_SPIx_SCK_SOURCE, LED_SPIx_SCK_AF ); + GPIO_PinAFConfig ( LED_SPIx_MOSI_GPIO_PORT, LED_SPIx_MOSI_SOURCE, LED_SPIx_MOSI_AF ); + + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + + /* SPI SCK pin configuration */ + GPIO_InitStructure.GPIO_Pin = LED_SPIx_SCK_PIN; + GPIO_Init ( LED_SPIx_SCK_GPIO_PORT, &GPIO_InitStructure ); + + /* SPI MOSI pin configuration */ + GPIO_InitStructure.GPIO_Pin = LED_SPIx_MOSI_PIN; + GPIO_Init ( LED_SPIx_MOSI_GPIO_PORT, &GPIO_InitStructure ); + + /* GPIO ST pin configuration */ + GPIO_InitStructure.GPIO_Pin = LED_SPIx_ST_PIN; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + GPIO_Init ( LED_SPIx_ST_GPIO_PORT, &GPIO_InitStructure ); + + /* SPI configuration -------------------------------------------------------*/ + SPI_I2S_DeInit ( LED_SPIx ); + SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; + SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b; + SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low; + SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge; + SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; + SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8; + SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; + SPI_InitStructure.SPI_CRCPolynomial = 7; + SPI_InitStructure.SPI_Mode = SPI_Mode_Master; + SPI_Init ( LED_SPIx, &SPI_InitStructure ); + + /* Enable the SPI peripheral */ + SPI_Cmd ( LED_SPIx, ENABLE ); + + /* Configure the SPI interrupt priority */ + NVIC_InitStructure.NVIC_IRQChannel = LED_SPIx_IRQn; + NVIC_InitStructure.NVIC_IRQChannelPriority = 0; + NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; + NVIC_Init ( &NVIC_InitStructure ); + + /* Enable the Rx buffer not empty interrupt */ + SPI_I2S_ITConfig ( LED_SPIx, SPI_I2S_IT_RXNE, ENABLE ); + + LED_ST_PIN_RESET; +} diff --git a/app/led_driver/led_driver_config.h b/app/led_driver/led_driver_config.h new file mode 100644 index 0000000..39927ec --- /dev/null +++ b/app/led_driver/led_driver_config.h @@ -0,0 +1,44 @@ +#ifndef LED_DRIVER_CONFIG_INCLUDED +#define LED_DRIVER_CONFIG_INCLUDED + +#include "stm32f0xx_conf.h" + +/* Communication boards SPIx Interface */ +#define LED_SPIx SPI2 +#define LED_SPIx_CLK RCC_APB1Periph_SPI2 +#define LED_SPIx_IRQn SPI2_IRQn +#define LED_SPIx_IRQHandler SPI2_IRQHandler + +#define LED_SPIx_SCK_PIN GPIO_Pin_10 +#define LED_SPIx_SCK_GPIO_PORT GPIOB +#define LED_SPIx_SCK_GPIO_CLK RCC_AHBPeriph_GPIOB +#define LED_SPIx_SCK_SOURCE GPIO_PinSource10 +#define LED_SPIx_SCK_AF GPIO_AF_5 + +#define LED_SPIx_MOSI_PIN GPIO_Pin_15 +#define LED_SPIx_MOSI_GPIO_PORT GPIOB +#define LED_SPIx_MOSI_GPIO_CLK RCC_AHBPeriph_GPIOB +#define LED_SPIx_MOSI_SOURCE GPIO_PinSource15 +#define LED_SPIx_MOSI_AF GPIO_AF_0 + +#define LED_SPIx_ST_PIN GPIO_Pin_9 +#define LED_SPIx_ST_GPIO_PORT GPIOB +#define LED_SPIx_ST_GPIO_CLK RCC_AHBPeriph_GPIOA +#define LED_SPIx_ST_SOURCE GPIO_PinSource9 +#define LED_SPIx_ST_AF GPIO_AF_5 + +#define LED_SPIx_RCC_APBxPeriphClockCmd RCC_APB1PeriphClockCmd + +// Определения для таймера LedRgbDriver ------------------------------------- // +#define LED_TIMx TIM3 +#define LED_TIM_IRQHandler TIM3_IRQHandler +#define LED_TIM_RCC RCC_APB1Periph_TIM3 +#define LED_TIM_IRQx TIM3_IRQn +#define LED_RCC_APBxPeriphClockCmd RCC_APB1PeriphClockCmd + +#define LED_ST_PIN_SET GPIO_SetBits ( LED_SPIx_ST_GPIO_PORT, LED_SPIx_ST_PIN ) +#define LED_ST_PIN_RESET GPIO_ResetBits ( LED_SPIx_ST_GPIO_PORT, LED_SPIx_ST_PIN ) + +void LED_Driver_Config ( void ); + +#endif //LED_DRIVER_CONFIG_INCLUDED diff --git a/app/led_driver/led_driver_process.c b/app/led_driver/led_driver_process.c new file mode 100644 index 0000000..165ef99 --- /dev/null +++ b/app/led_driver/led_driver_process.c @@ -0,0 +1,31 @@ +#include "led_driver_process.h" +#include "led_driver_config.h" +#include <stdint.h> + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void LEDDriverProcessFromISR ( void ) +{ + return; + asm volatile("cpsid i"); + LED_ST_PIN_RESET; + for (int j = 0; j < 4; j++) { + LED_SPIx->DR = 0; + while (SPI_I2S_FLAG_BSY & LED_SPIx->SR); + for (int i = 0; i < 4; i++) { + LED_SPIx->DR = 0xf8f8; + while (SPI_I2S_FLAG_BSY & LED_SPIx->SR); + } + for (int i = 0; i < 4; i++) { + LED_SPIx->DR = 0xe0e0; + while (SPI_I2S_FLAG_BSY & LED_SPIx->SR); + } + for (int i = 0; i < 4; i++) { + LED_SPIx->DR = 0xe0e0; + while (SPI_I2S_FLAG_BSY & LED_SPIx->SR); + } + } + asm volatile("cpsie i"); +} diff --git a/app/led_driver/led_driver_process.h b/app/led_driver/led_driver_process.h new file mode 100644 index 0000000..fa02241 --- /dev/null +++ b/app/led_driver/led_driver_process.h @@ -0,0 +1,6 @@ +#ifndef LED_DRIVER_PROCESS_INCLUDED +#define LED_DRIVER_PROCESS_INCLUDED + +void LEDDriverProcessFromISR ( void ); + +#endif //LED_DRIVER_PROCESS_INCLUDED diff --git a/app/led_driver/led_driver_task.c b/app/led_driver/led_driver_task.c new file mode 100644 index 0000000..d38deb4 --- /dev/null +++ b/app/led_driver/led_driver_task.c @@ -0,0 +1,26 @@ +#include "led_driver_task.h" +#include "led_driver_config.h" + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + + +void LED_DriverInit ( void ) +{ + LED_Driver_Config (); +} + +void ProcessFSM_LED_RGB ( void ) +{ + taskYIELD(); +} + +// ---------------------------------------------------------------------------- +// Задача ОС, реализующая задачу обработки светодиодиков RGB +// ---------------------------------------------------------------------------- +void LED_Driver_Task ( void *pvParameters ) +{ + while(1)ProcessFSM_LED_RGB (); +} diff --git a/app/led_driver/led_driver_task.h b/app/led_driver/led_driver_task.h new file mode 100644 index 0000000..63f3ff1 --- /dev/null +++ b/app/led_driver/led_driver_task.h @@ -0,0 +1,9 @@ +#ifndef LED_RGB_TASK_INCLUDED +#define LED_RGB_TASK_INCLUDED + +#include "stm32f0xx.h" + +void LED_DriverInit ( void ); +void LED_Driver_Task ( void *pvParameters ); + +#endif //LED_RGB_TASK_INCLUDED
\ No newline at end of file diff --git a/app/light_sensor/light_sensor_task.c b/app/light_sensor/light_sensor_task.c new file mode 100644 index 0000000..d1a0f89 --- /dev/null +++ b/app/light_sensor/light_sensor_task.c @@ -0,0 +1,202 @@ +#include "light_sensor_task.h" +#include "ltimers.h" + +// FreeRTOS includes +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +// Если используется фоторезистор: +// - калибровка датчика освещенности ? +// - добавить гистерезис +// - плавное изменение яркости +// - как будет реагировать фоторезистор на мерцание 50 Гц, 100 Гц на диодное и тд. + +// * Фоторезистор GL5516 стоит в нижнем плече делителя. В врехнем плече на питание +// +3.3В подключен резистор 10К. +// Фоторезистор в полной темноте дает сопротивление до 6МОм, на свету у окна +// в пасмурную питерскую погоду около 200 Ом, а если на ярком солнце, то и еще +// меньше. +// В итоге, чем ярче освещение, тем ниже сопротивление, тем ниже напряжение +// на АЦП. +// +// Порог переключения яркости ламп нужно в приложении настраивать под себя. +// И сделать по умолчанию. +// +// - теперь нужно опытным путем определить порог, когда лампам нужно убавить яркость +// Для начала сделать только два варианта - светло/темно. + +#define LIGHT_THREHSOLD 3300 // Значение АЦП, подобранное опытным путем +#define LIGHT 0 +#define DARK 1 + +#define TIME_LIGHT_SENSOR 3000 //ms + +static void ADC_Config(void); + +static uint16_t ADC_ConvertedValue = 0;//, ADC_ConvertedVoltage = 0; +QueueHandle_t queue_light_sensor; + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void LightSensorInit ( void ) +{ + // - ADC init + ADC_Config (); + queue_light_sensor = xQueueCreate ( 1, sizeof (LightSensorState_t) ); + configASSERT( queue_light_sensor ); +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +static void ADC_Config(void) +{ + ADC_InitTypeDef ADC_InitStructure; + GPIO_InitTypeDef GPIO_InitStructure; + + /* GPIOC Periph clock enable */ + RCC_AHBPeriphClockCmd(LIGHT_SENSOR_RCC_AHBPeriph_GPIOx, ENABLE); + + /* ADC1 Periph clock enable */ + LIGHT_SENSOR_RCC_APBxPeriphClockCmd(LIGHT_SENSOR_RCC_APBxPeriph_ADCx, ENABLE); + + /* Configure ADC Channelx as analog input */ + GPIO_InitStructure.GPIO_Pin = LIGHT_SENSOR_GPIO_PINx ; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ; + GPIO_Init(LIGHT_SENSOR_GPIOx, &GPIO_InitStructure); + + /* ADCs DeInit */ + ADC_DeInit(LIGHT_SENSOR_ADCx); + + /* Initialize ADC structure */ + ADC_StructInit(&ADC_InitStructure); + + /* Configure the ADC1 in continuous mode with a resolution equal to 12 bits */ + ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b; + ADC_InitStructure.ADC_ContinuousConvMode = ENABLE; + ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None; + ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; + ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward; + ADC_Init(LIGHT_SENSOR_ADCx, &ADC_InitStructure); + + /* Convert the ADC1 Channel 11 with 239.5 Cycles as sampling time */ + ADC_ChannelConfig(LIGHT_SENSOR_ADCx, LIGHT_SENSOR_ADC_Channelx , ADC_SampleTime_239_5Cycles); + + /* ADC Calibration */ + ADC_GetCalibrationFactor(LIGHT_SENSOR_ADCx); + + /* Enable the ADC peripheral */ + ADC_Cmd(LIGHT_SENSOR_ADCx, ENABLE); + + /* Wait the ADRDY flag */ + while(!ADC_GetFlagStatus(LIGHT_SENSOR_ADCx, ADC_FLAG_ADRDY)); + + /* ADC1 regular Software Start Conv */ + ADC_StartOfConversion(LIGHT_SENSOR_ADCx); + +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void ProcessFSM_LightSensor ( void ) +{ + static uint8_t process_light_state = 0; + LightSensorState_t light_sensor_state; + /* Test EOC flag */ + // - заменить этот файл на проверку и выход + while(ADC_GetFlagStatus(LIGHT_SENSOR_ADCx, ADC_FLAG_EOC) == RESET); + /* Get ADC1 converted data */ + ADC_ConvertedValue = ADC_GetConversionValue(LIGHT_SENSOR_ADCx); + switch ( process_light_state ) + { + case 0: // ждем когда посветлеет + if (ADC_ConvertedValue < LIGHT_THREHSOLD) // если стало светло + { + // - запускаем таймер, в течение которого проверяем освещение + StartLTimer (LTIMER_LIGHT_SENSOR); + // - переходим в состояние проверки яркости в течение таймера + process_light_state = 2; + } + break; + case 1: // ждем когда потемнет + if (ADC_ConvertedValue > LIGHT_THREHSOLD) // если стало темно + { + // - запускаем таймер, в течение которого проверяем освещение + StartLTimer (LTIMER_LIGHT_SENSOR); + // - переходим в состояние проверки яркости в течение таймера + process_light_state = 3; + } + break; + case 2: + if ( GetLTimer (LTIMER_LIGHT_SENSOR) >= TIME_LIGHT_SENSOR ) + { + // - если таймер вышел, значит подтверждается новое значение + // освещенности + // - отправляем сообщение на смену режима + light_sensor_state = LIGHT_SENSOR_STATE_LIGHT; + xQueueSend ( queue_light_sensor, &light_sensor_state, 0 ); + // - а затем идем проверять когда потемнеет + process_light_state = 1; + } + else + { + // - если таймер еще тикает, то проверяем освещенность + // и, если она изменилась, то возвращаемся в состояние 0 + // то есть в начало алгоритма проверки яркости (освещенности) + if (ADC_ConvertedValue < LIGHT_THREHSOLD) + { + // то ничего не меняем + } + else + { + process_light_state = 0; + } + } + break; + case 3: + if ( GetLTimer (LTIMER_LIGHT_SENSOR) >= TIME_LIGHT_SENSOR ) + { + // - если таймер вышел, значит подтверждается новое значение + // освещенности + // - отправляем сообщение на смену режима + light_sensor_state = LIGHT_SENSOR_STATE_DARK; + xQueueSend ( queue_light_sensor, &light_sensor_state, 0 ); + // - а затем идем проверять когда посветлеет + process_light_state = 0; + } + else + { + // - если таймер еще тикает, то проверяем освещенность + // и, если она изменилась, то возвращаемся в состояние 0 + // то есть в начало алгоритма проверки яркости (освещенности) + if (ADC_ConvertedValue > LIGHT_THREHSOLD) + { + // то ничего не меняем + } + else + { + process_light_state = 1; + } + } + break; + default: + break; + } + vTaskDelay (100); +} + + +// ---------------------------------------------------------------------------- +// Задача ОС, реализующая головную задачу программы +// ---------------------------------------------------------------------------- +void LightSensor_Task ( void *pvParameters ) +{ + while(1)ProcessFSM_LightSensor (); +} diff --git a/app/light_sensor/light_sensor_task.h b/app/light_sensor/light_sensor_task.h new file mode 100644 index 0000000..65dbba9 --- /dev/null +++ b/app/light_sensor/light_sensor_task.h @@ -0,0 +1,24 @@ +#ifndef LIGHT_SENSOR_TASK_INCLUDED +#define LIGHT_SENSOR_TASK_INCLUDED + +#include "stm32f0xx_conf.h" + +#define LIGHT_SENSOR_GPIO_PINx GPIO_Pin_6 +#define LIGHT_SENSOR_GPIOx GPIOA +#define LIGHT_SENSOR_RCC_AHBPeriph_GPIOx RCC_AHBPeriph_GPIOA + +#define LIGHT_SENSOR_ADCx ADC1 +#define LIGHT_SENSOR_ADC_Channelx ADC_Channel_6 +#define LIGHT_SENSOR_RCC_APBxPeriphClockCmd RCC_APB2PeriphClockCmd +#define LIGHT_SENSOR_RCC_APBxPeriph_ADCx RCC_APB2Periph_ADC1 + +typedef enum { + LIGHT_SENSOR_STATE_LIGHT, + LIGHT_SENSOR_STATE_DARK +} LightSensorState_t; + +void LightSensorInit ( void ); + +void LightSensor_Task ( void *pvParameters ); + +#endif //LIGHT_SENSOR_TASK_INCLUDED diff --git a/app/ltimers/ltimers.c b/app/ltimers/ltimers.c new file mode 100644 index 0000000..61c9e6f --- /dev/null +++ b/app/ltimers/ltimers.c @@ -0,0 +1,122 @@ +/* Описание модуля ltimers.c + + Этот модуль используется для создания неограниченного количества +программных таймеров для программы. Модуль использует аппаратный таймер, +который генерирует прерывание каждую 1мс (можно использовать любой другой +промежуток времени, просто 1 мс это очень удобно и хватает для многих +программных пауз, задержек, таймеров и тд. в программе). +В прерывании вызывается ф-я ProcessLTimers(), которая инкрементирует значения +всех таймеров. Таймеры создаются в файле ltimers.h. + Модуль универсален, прост и может использоваться на любой платформе, +компиляторе, любом МК. + Для подключения модуля настройте аппаратный таймер на прерывание в 1мс (или +любой другой нужный промежуток времени) и добавьте в обработчик прерывания +этого таймера ф-ю ProcessLTimers();. Затем добавьте #include "ltimers.h" в тот +файл программы, где будут использоваться ф-ии модуля. Собственно, +в всего нужны две функции для работы с таймерами: + +StartLTimer ( LTIMER_LED_BLINK ); // запустить таймер +GetLTimer ( LTIMER_LED_BLINK ); // получить текущее значение таймера + + Пример использования: +... +// Предварительно ltimers.h создаем перечисление, в котором создаем имена для +// программных таймеров, а также в конце перечисления всегда MAX_LTIMERS +#include "ltimers.h" +... + +int main () +{ + ... + // Настройка аппаратного таймера на прерывание раз в 1 мс + InitLTimersHardWare(); + + // Стартовая инициализация (просто обнуление) всех программных таймеров + InitLTimers (); + + // Запускаем таймер + StartLTimer ( LTIMER_LED_BLINK ); + + // Основной цикл программы + while (1) + { + // Проверяем значение таймера + if ( GetLTimer ( LTIMER_LED_BLINK ) >= 500 ) + { + LED_ON; + } + } +} + +***Примечание + + 1. Необходимо учитывать разрядность МК и атомарность при проверке значений +таймера. То есть, если произойдет прерывание в момент проверки полубайтов на +8-ми разрядном МК, то, возможно, могут быть трудноуловимые глюки. + + 2. Обратите внимание, что в ф-ии ProcessLTimers() значения таймеров +инкрементируются постоянно и не перестают изменяться. Ф-я StartLTimer только +сбрасывает значение таймера в ноль, а потом программа уже ловит тот момент, +когда это значение превысило или сравнялось с нужным. И когда мы провели +сравнение, то таймер все равно продолжает маслать. Но это не важно. Пусть себе +маслает. + + 3. Псевдоним для типа uint32_t можно заменить на необходимый в зависимости +от среды разработки и компилятора. +*/ + +#include "ltimers.h" +#include "ltimers_config.h" + +uint32_t LTimers [MAX_LTIMERS] = { 0 }; + + +// ---------------------------------------------------------------------------- +// Стартовая инициализация всех программных таймеров программиста. +// Ф-я вызывается при старте МК и просто устанавливает все значения таймеров +// в ноль. +// ---------------------------------------------------------------------------- +void InitLTimers (void) +{ + LTimersConfig (); +} + + +// ---------------------------------------------------------------------------- +// Ф-я получения значения программного счетчика +// Используется программистом для проверки значения запущенного таймера +// Ф-я принимает имя таймера из перечисления LTimerNum_t в файле ltimers.h +// Ф-я возвращает значение таймера, которое увеличивается каждую 1мс +// ---------------------------------------------------------------------------- +uint32_t GetLTimer ( LTimersNames_t LTimer ) +{ + return LTimers[ LTimer ]; +} + + +// ---------------------------------------------------------------------------- +// Ф-я запуска программного таймера для использования программистом для +// любых программных задержек разрешением 1мс +// Ф-я принимает имя таймера из перечисления LTimerNum_t в файле ltimers.h +// ---------------------------------------------------------------------------- +void StartLTimer ( LTimersNames_t LTimer ) +{ + LTimers[ LTimer ] = 0; +} + + +// ---------------------------------------------------------------------------- +// Ф-я, инкрементирующая значения программных таймеров. Количество этих +// программных таймеров нее ограничено и задается программистом в ltimers.h +// в тайпдефе LTimerNum_t. Просто дописываем в перечислении перед MAX_LTIMERS +// имя нового таймера. +// Вызывается эта ф-я в обреботчике TIM6_IRQHandler каждую 1 мс. +// 1 мс это удобный квант времени для разных программных задержек +// ---------------------------------------------------------------------------- +void ProcessLTimers (void) +{ + for ( uint32_t i = 0; i < MAX_LTIMERS; i++ ) + { + LTimers[i]++; + } +} diff --git a/app/ltimers/ltimers.h b/app/ltimers/ltimers.h new file mode 100644 index 0000000..4514841 --- /dev/null +++ b/app/ltimers/ltimers.h @@ -0,0 +1,29 @@ +#ifndef LTIMERS_H_INCLUDED +#define LTIMERS_H_INCLUDED + +#include <stdint.h> + +// Имена таймеров LTIMER_<TIMERNAME> ---------------------------------------- // +typedef enum { + + LTIMER_SENSE_PAD = 0, + LTIMER_PRGBAR_SPEED, + LTIMER_HL_CHANGE_BRIGHT_SPEED, + LTIMER_HL_BUT_LED, + LTIMER_BUTTON_LONG_PRESS, + LTIMER_INDIC_MODE_BLINK_OFF, + LTIMER_INDIC_MODE_BLINK_ON, + LTIMER_MENU_ADJ_TIME_OUT, + LTIMER_LIGHT_SENSOR, + LTIMER_SENSOR_BUT_DEBOUNCE, + + MAX_LTIMERS + +} LTimersNames_t; + +void InitLTimers ( void ); +void ProcessLTimers ( void ); +uint32_t GetLTimer ( LTimersNames_t LTIMER ); +void StartLTimer ( LTimersNames_t LTIMER ); + +#endif // LTIMERS_H_INCLUDED diff --git a/app/ltimers/ltimers_config.c b/app/ltimers/ltimers_config.c new file mode 100644 index 0000000..a30b36f --- /dev/null +++ b/app/ltimers/ltimers_config.c @@ -0,0 +1,56 @@ +#include "ltimers_config.h" + +#include "stm32f0xx_conf.h" + + +// ---------------------------------------------------------------------------- +// Инициализация аппаратного таймера для генерирования прерываний каждую 1мс +// ---------------------------------------------------------------------------- +void LTimersConfig ( void ) +{ + NVIC_InitTypeDef NVIC_InitStructure; + TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; + + /* LTIMER_TIMx clock enable */ + LTIMER_RCC_APBxPeriphClockCmd ( LTIMER_TIM_RCC, ENABLE ); + + /* Enable the LTIMER_TIMx gloabal Interrupt */ + NVIC_InitStructure.NVIC_IRQChannel = LTIMER_TIM_IRQx; + NVIC_InitStructure.NVIC_IRQChannelPriority = 1; + NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; + NVIC_Init ( &NVIC_InitStructure ); + + /* ----------------------------------------------------------------------- + In this example TIM7 counter clock (TIM7CLK) is set to APB1 clock (PCLK1), since + APB1 prescaler is set to 1 and TIM7 prescaler is set to 0. + + In this example TIM7 input clock (TIM7CLK) is set to APB1 clock (PCLK1), + since APB1 prescaler is set to 1. + TIM7CLK = PCLK1 = HCLK = SystemCoreClock + + With Prescaler set to 479 and Period to 24999, the TIM7 counter is updated each 250 ms + (i.e. and interrupt is generated each 250 ms) + TIM7 counter clock = TIM7CLK /((Prescaler + 1)*(Period + 1)) + = 48 MHz / ((25000)*(480)) + = 4 Hz + ==> TIM7 counter period = 250 ms + + Note: + SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f0xx.c file. + Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate() + function to update SystemCoreClock variable value. Otherwise, any configuration + based on this variable will be incorrect. + ----------------------------------------------------------------------- */ + /* Time base configuration */ + TIM_TimeBaseStructure.TIM_Period = 1000; //24999; + TIM_TimeBaseStructure.TIM_Prescaler = (SystemCoreClock/1000000)-1; //479; + TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; + TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; + TIM_TimeBaseInit ( LTIMER_TIMx, &TIM_TimeBaseStructure ); + + /* LTIMER_TIMx Interrupts enable */ + TIM_ITConfig ( LTIMER_TIMx, TIM_IT_Update, ENABLE ); + + /* LTIMER_TIMx enable counter */ + TIM_Cmd ( LTIMER_TIMx, ENABLE ); +} diff --git a/app/ltimers/ltimers_config.h b/app/ltimers/ltimers_config.h new file mode 100644 index 0000000..50a75db --- /dev/null +++ b/app/ltimers/ltimers_config.h @@ -0,0 +1,15 @@ +#ifndef LTIMERS_CONFIG_INCLUDED +#define LTIMERS_CONFIG_INCLUDED + +// Примечание +// Обратить внимание на то, что таймеры тактируются от разных шин APB1 или APB2 + +#define LTIMER_IRQHandler TIM17_IRQHandler +#define LTIMER_TIMx TIM17 +#define LTIMER_TIM_RCC RCC_APB2Periph_TIM17 +#define LTIMER_TIM_IRQx TIM17_IRQn +#define LTIMER_RCC_APBxPeriphClockCmd RCC_APB2PeriphClockCmd + +void LTimersConfig ( void ); + +#endif // LTIMERS_CONFIG_INCLUDED diff --git a/app/main.c b/app/main.c new file mode 100644 index 0000000..b71d027 --- /dev/null +++ b/app/main.c @@ -0,0 +1,288 @@ +/** + ****************************************************************************** + * @file STM32L152_Ex01_3TKeys_EVAL\src\main.c + * @author MCD Application Team + * @version V1.1.0 + * @date 24-February-2014 + * @brief Basic example of how to use the STMTouch Driver. + ****************************************************************************** + * @attention + * + * <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2> + * + * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.st.com/software_license_agreement_liberty_v2 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* + Здесь необходимо создать большой комментарий о характеристиках железа МК. Или +же лучше создать отдельный файл и сделать на него ссылку. Кстати, такой файл +создает программа STM32CubeMX. + +И вообще, нужно создать глобальную папку проекта, где будет лежать все по +полочкам ( схема, программа, текстовые файлы, документация и тд ) +*/ + +// Это программа для версии NixieClock_v2, которая является модифицированной версией предыдущей +// NixieLUT + +/* Includes ------------------------------------------------------------------*/ +#include "time.h" + +// FreeRTOS includes +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +#include "ltimers.h" +#include "head_task.h" +#include "button_task.h" +#include "button_handler.h" +#include "nixie_driver_task.h" +#include "light_sensor_task.h" + +#ifdef LED_DRIVER +#include "led_driver_task.h" +#endif + +#include "indicate_modes_task.h" +#include "tsl_user.h" +#include "time.h" +#include "stm32f0xx_usart.h" + + +/* Private typedefs ----------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ +/* Private macros ------------------------------------------------------------*/ + +// Задаем размеры кучи для каждой задачи отдельно +// - как правильно определить необходимый минимум для кучи задачи? + +#define STACK_SIZE_HEAD ((unsigned short) 230) +#define STACK_SIZE_NIXIE_DRIVER ((unsigned short) 80) +#define STACK_SIZE_BUTTON ((unsigned short) 200) +#define STACK_SIZE_LIGHT_SENSOR ((unsigned short) 70) +#ifdef LED_DRIVER +#define STACK_SIZE_LED_DRIVER ((unsigned short) 70) +#endif +#define STACK_SIZE_INDICATE_MODES ((unsigned short) 250) + +/* Private functions prototype ---------------------------------------------- */ + +static void USART1Init(void) +{ + RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); + RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE); + GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1); + GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_1); + GPIO_InitTypeDef GPIO_InitStructure; + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; + GPIO_Init(GPIOA, &GPIO_InitStructure); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; + GPIO_Init(GPIOA, &GPIO_InitStructure); + USART_InitTypeDef usart_init = {0}; + usart_init.USART_BaudRate = 115200; + usart_init.USART_WordLength = USART_WordLength_8b; + usart_init.USART_StopBits = USART_StopBits_1; + usart_init.USART_Parity = USART_Parity_No; + usart_init.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; + usart_init.USART_HardwareFlowControl = USART_HardwareFlowControl_None; + USART_Init(USART1, &usart_init); + USART_Cmd(USART1, ENABLE); +} + +static void USART4Init(void) +{ + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART4, ENABLE); + RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE); + GPIO_PinAFConfig(GPIOA, GPIO_PinSource0, GPIO_AF_4); + GPIO_PinAFConfig(GPIOA, GPIO_PinSource1, GPIO_AF_4); + GPIO_InitTypeDef GPIO_InitStructure; + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; + GPIO_Init(GPIOA, &GPIO_InitStructure); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; + GPIO_Init(GPIOA, &GPIO_InitStructure); + USART_InitTypeDef usart_init = {0}; + usart_init.USART_BaudRate = 9600; + usart_init.USART_WordLength = USART_WordLength_8b; + usart_init.USART_StopBits = USART_StopBits_1; + usart_init.USART_Parity = USART_Parity_No; + usart_init.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; + usart_init.USART_HardwareFlowControl = USART_HardwareFlowControl_None; + USART_Init(USART4, &usart_init); + USART_Cmd(USART4, ENABLE); +} + +static void WIFI_IO_GPIOInit(void) +{ + RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE); + RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE); + GPIO_InitTypeDef GPIO_InitStructure; + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_15; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; + GPIO_Init(GPIOA, &GPIO_InitStructure); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; + GPIO_Init(GPIOB, &GPIO_InitStructure); + GPIO_SetBits(GPIOB, GPIO_Pin_0); // WIFI_EN + GPIO_ResetBits(GPIOA, GPIO_Pin_15); // WIFI_IO0 +} + +static void USART3Init(void) +{ + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE); + RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE); + GPIO_PinAFConfig(GPIOB, GPIO_PinSource1, GPIO_AF_4); + GPIO_PinAFConfig(GPIOB, GPIO_PinSource10, GPIO_AF_4); + GPIO_PinAFConfig(GPIOB, GPIO_PinSource11, GPIO_AF_4); + GPIO_PinAFConfig(GPIOB, GPIO_PinSource13, GPIO_AF_4); + GPIO_InitTypeDef GPIO_InitStructure; + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; + GPIO_Init(GPIOB, &GPIO_InitStructure); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; + GPIO_Init(GPIOB, &GPIO_InitStructure); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; + GPIO_Init(GPIOB, &GPIO_InitStructure); + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13; + GPIO_Init(GPIOB, &GPIO_InitStructure); + USART_InitTypeDef usart_init = {0}; + usart_init.USART_BaudRate = 115200; + usart_init.USART_WordLength = USART_WordLength_8b; + usart_init.USART_StopBits = USART_StopBits_1; + usart_init.USART_Parity = USART_Parity_No; + usart_init.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; + usart_init.USART_HardwareFlowControl = USART_HardwareFlowControl_RTS_CTS; + USART_Init(USART3, &usart_init); + USART_Cmd(USART3, ENABLE); +} + +// ---------------------------------------------------------------------------- +// Инициализация до создания задач +// ---------------------------------------------------------------------------- +void InitAll ( void ) +{ + SystemInit(); + WIFI_IO_GPIOInit(); + USART1Init(); + USART3Init(); + USART4Init(); + InitLTimers(); + LightSensorInit(); +#if 0 + NixieDriverInit(); + HeadTaskInit(); + IndicateModesInit(); +#endif +#ifdef LED_DRIVER + LED_DriverInit(); +#endif + TSL_user_Init(); + TimeInit(); + ButtonInit(); +} + +static void TestUart(void *arg) +{ + (void) arg; + while (1) { + if (USART3->ISR & USART_ISR_RXNE) { + const uint16_t data = USART_ReceiveData(USART3); + USART_SendData(USART1, data); + } + if (USART1->ISR & USART_ISR_RXNE) { + const uint16_t data = USART_ReceiveData(USART1); + USART_SendData(USART3, data); + } + } +} + +BaseType_t TaskSuccess; + +// Главный цикл ------------------------------------------------------------- // +int main () +{ + InitAll (); + // Создаем задачи FreeRTOS ----------------------------------------------- // + + // ВНИМАНИЕ !!! + // Необходимо проверять кучу при создании задачи! ( и очереди ) + + // Если в программе используется подключаемая библиотека, которая использует + // ОСРВ, то задача должна там и создаватья. То есть это нужно оформить в + // в виде специальной функции + TaskSuccess = xTaskCreate(Button_Task, "Button_Task", STACK_SIZE_BUTTON, NULL, tskIDLE_PRIORITY + 2, NULL); + configASSERT(TaskSuccess); + TaskSuccess = xTaskCreate(LightSensor_Task, "LightSensor_Task", STACK_SIZE_LIGHT_SENSOR, NULL, tskIDLE_PRIORITY + 2, NULL); + configASSERT(TaskSuccess); +#if 0 + TaskSuccess = xTaskCreate(Head_Task, "Head_Task", STACK_SIZE_HEAD, NULL, tskIDLE_PRIORITY + 2, NULL); + configASSERT(TaskSuccess); + TaskSuccess = xTaskCreate(IndicateModes_Task, "IndicateModes_Task", STACK_SIZE_INDICATE_MODES, NULL, tskIDLE_PRIORITY + 2, NULL); + configASSERT(TaskSuccess); + TaskSuccess = xTaskCreate(NixieDriver_Task, "NixieDriver_Task", STACK_SIZE_NIXIE_DRIVER, NULL, tskIDLE_PRIORITY + 2, NULL); + configASSERT(TaskSuccess); +#endif +#ifdef LED_DRIVER + TaskSuccess = xTaskCreate(LED_Driver_Task, "LED_Driver_Task", STACK_SIZE_LED_DRIVER, NULL, tskIDLE_PRIORITY + 2, NULL); + configASSERT(TaskSuccess); +#endif + TaskSuccess = xTaskCreate(TestUart, "TestUart", 200, NULL, tskIDLE_PRIORITY + 2, NULL); + configASSERT(TaskSuccess); + vTaskStartScheduler(); // И запускаем диспетчер задач ( он же планировщик ) +} // end of main + + + +#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 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) */ + + /* Infinite loop */ + for (;;) + { + } +} +#endif + + +// Специальные ф-ии FreeRTOS ------------------------------------------------ // +void vApplicationMallocFailedHook ( void ) { for( ;; ); } +void vApplicationStackOverflowHook ( TaskHandle_t pxTask, char *pcTaskName ) { for( ;; ); } +void vApplicationIdleHook ( void ) { } + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/app/nixie_driver/nixie_driver_config.c b/app/nixie_driver/nixie_driver_config.c new file mode 100644 index 0000000..defc674 --- /dev/null +++ b/app/nixie_driver/nixie_driver_config.c @@ -0,0 +1,161 @@ +#include "nixie_driver_config.h" + +static void NixieDriver_TIMConfig ( void ); +static void NixieDriver_SPIConfig ( void ); + +void NixieDriverConfig ( void ) +{ + NixieDriver_TIMConfig (); + NixieDriver_SPIConfig (); +} + +// ---------------------------------------------------------------------------- +// Конфигурируем таймер на 100 мкс. В прерывании каждые 100 мкс будет +// проворачиваться механизм динамической индикации ламп Nixie +// ---------------------------------------------------------------------------- +static void NixieDriver_TIMConfig ( void ) +{ + NVIC_InitTypeDef NVIC_InitStructure; + TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; + + /* NIX_DRIVER_TIMx clock enable */ + NIX_DRIVER_RCC_APBxPeriphClockCmd ( NIX_DRIVER_TIM_RCC, ENABLE ); + + /* Enable the NIX_DRIVER_TIMx gloabal Interrupt */ + NVIC_InitStructure.NVIC_IRQChannel = NIX_DRIVER_TIM_IRQx; + NVIC_InitStructure.NVIC_IRQChannelPriority = 1; + NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; + NVIC_Init ( &NVIC_InitStructure ); + + /* ----------------------------------------------------------------------- + In this example TIM7 counter clock (TIM7CLK) is set to APB1 clock (PCLK1), since + APB1 prescaler is set to 1 and TIM7 prescaler is set to 0. + + In this example TIM7 input clock (TIM7CLK) is set to APB1 clock (PCLK1), + since APB1 prescaler is set to 1. + TIM7CLK = PCLK1 = HCLK = SystemCoreClock + + With Prescaler set to 479 and Period to 24999, the TIM7 counter is updated each 250 ms + (i.e. and interrupt is generated each 250 ms) + TIM7 counter clock = TIM7CLK /((Prescaler + 1)*(Period + 1)) + = 48 MHz / ((25000)*(480)) + = 4 Hz + ==> TIM7 counter period = 250 ms + + Note: + SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f0xx.c file. + Each time the core clock (HCLK) changes, user had to call SystemCoreClockUpdate() + function to update SystemCoreClock variable value. Otherwise, any configuration + based on this variable will be incorrect. + ----------------------------------------------------------------------- */ + + /* Time base configuration */ + TIM_TimeBaseStructure.TIM_Period = 100; // Это миксросекунды //24999 + TIM_TimeBaseStructure.TIM_Prescaler = (SystemCoreClock/1000000)-1; //479; + TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; + TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; + TIM_TimeBaseInit ( NIX_DRIVER_TIMx, &TIM_TimeBaseStructure ); + + /* NIX_DRIVER_TIMx Interrupts enable */ + TIM_ITConfig ( NIX_DRIVER_TIMx, TIM_IT_Update, ENABLE ); + + /* NIX_DRIVER_TIMx enable counter */ + TIM_Cmd ( NIX_DRIVER_TIMx, ENABLE ); +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +static void NixieDriver_SPIConfig ( void ) +{ + GPIO_InitTypeDef GPIO_InitStructure; + SPI_InitTypeDef SPI_InitStructure; + NVIC_InitTypeDef NVIC_InitStructure; + + /* Enable the SPI periph */ + NIX_SPIx_RCC_APBxPeriphClockCmd ( NIX_SPIx_CLK, ENABLE ); + + /* Enable SCK, MOSI, MISO and NSS GPIO clocks */ + RCC_AHBPeriphClockCmd ( NIX_SPIx_SCK_GPIO_CLK | + NIX_SPIx_MOSI_GPIO_CLK | + NIX_SPIx_ST_GPIO_CLK | + NIX_GPIOx_TUB_P1_GPIO_CLK | + NIX_GPIOx_TUB_P2_GPIO_CLK, + ENABLE ); + + GPIO_PinAFConfig ( NIX_SPIx_SCK_GPIO_PORT, NIX_SPIx_SCK_SOURCE, NIX_SPIx_SCK_AF ); + GPIO_PinAFConfig ( NIX_SPIx_MOSI_GPIO_PORT, NIX_SPIx_MOSI_SOURCE, NIX_SPIx_MOSI_AF ); + //GPIO_PinAFConfig ( NIX_SPIx_ST_GPIO_PORT, NIX_SPIx_ST_SOURCE, NIX_SPIx_ST_AF ); + + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + + /* SPI SCK pin configuration */ + GPIO_InitStructure.GPIO_Pin = NIX_SPIx_SCK_PIN; + GPIO_Init ( NIX_SPIx_SCK_GPIO_PORT, &GPIO_InitStructure ); + + /* SPI MOSI pin configuration */ + GPIO_InitStructure.GPIO_Pin = NIX_SPIx_MOSI_PIN; + GPIO_Init ( NIX_SPIx_MOSI_GPIO_PORT, &GPIO_InitStructure ); + + /* GPIO ST pin configuration */ + GPIO_InitStructure.GPIO_Pin = NIX_SPIx_ST_PIN; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; + //GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + GPIO_Init ( NIX_SPIx_ST_GPIO_PORT, &GPIO_InitStructure ); + + // Пины управления точками на лампах (не хватило ног сдвиговых редисок) + + /* GPIO tub_dp1 pin configuration */ + GPIO_InitStructure.GPIO_Pin = NIX_GPIOx_TUB_DP1_PIN; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + GPIO_Init ( NIX_GPIOx_TUB_DP1_PORT, &GPIO_InitStructure ); + + /* GPIO tub_dp2 pin configuration */ + GPIO_InitStructure.GPIO_Pin = NIX_GPIOx_TUB_DP2_PIN; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; + GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; + GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_Level_3; + GPIO_Init ( NIX_GPIOx_TUB_DP2_PORT, &GPIO_InitStructure ); + + /* SPI configuration -------------------------------------------------------*/ + SPI_I2S_DeInit ( NIX_SPIx ); + SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; + //SPI_InitStructure.SPI_Direction = SPI_Direction_1Line_Tx; + SPI_InitStructure.SPI_DataSize = SPI_DataSize_16b; + SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low; + SPI_InitStructure.SPI_CPHA = SPI_CPHA_1Edge; + SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; + //SPI_InitStructure.SPI_NSS = SPI_NSS_Hard; + SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_8; + SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; + SPI_InitStructure.SPI_CRCPolynomial = 7; + SPI_InitStructure.SPI_Mode = SPI_Mode_Master; + SPI_Init ( NIX_SPIx, &SPI_InitStructure ); + + /* Enable the SPI peripheral */ + SPI_Cmd ( NIX_SPIx, ENABLE ); + + /* Configure the SPI interrupt priority */ + NVIC_InitStructure.NVIC_IRQChannel = NIX_SPIx_IRQn; + NVIC_InitStructure.NVIC_IRQChannelPriority = 0; + NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; + NVIC_Init ( &NVIC_InitStructure ); + + // /* Enable the Tx buffer empty interrupt */ + SPI_I2S_ITConfig ( NIX_SPIx, SPI_I2S_IT_TXE, ENABLE ); + + NIX_DRIVER_RESET_ST_PIN; + NIX_DRIVER_RESET_TUB_DP1_PIN; + NIX_DRIVER_RESET_TUB_DP2_PIN; +} diff --git a/app/nixie_driver/nixie_driver_config.h b/app/nixie_driver/nixie_driver_config.h new file mode 100644 index 0000000..29f7a17 --- /dev/null +++ b/app/nixie_driver/nixie_driver_config.h @@ -0,0 +1,57 @@ +#ifndef NIXIE_DRIVER_CONFIG_INCLUDED +#define NIXIE_DRIVER_CONFIG_INCLUDED + +#include "stm32f0xx_conf.h" + +/* Communication boards SPIx Interface */ +#define NIX_SPIx SPI1 +#define NIX_SPIx_CLK RCC_APB2Periph_SPI1 +#define NIX_SPIx_IRQn SPI1_IRQn +#define NIX_SPIx_IRQHandler SPI1_IRQHandler + +#define NIX_SPIx_SCK_PIN GPIO_Pin_5 +#define NIX_SPIx_SCK_GPIO_PORT GPIOA +#define NIX_SPIx_SCK_GPIO_CLK RCC_AHBPeriph_GPIOA +#define NIX_SPIx_SCK_SOURCE GPIO_PinSource5 +#define NIX_SPIx_SCK_AF GPIO_AF_0 + +#define NIX_SPIx_MOSI_PIN GPIO_Pin_7 +#define NIX_SPIx_MOSI_GPIO_PORT GPIOA +#define NIX_SPIx_MOSI_GPIO_CLK RCC_AHBPeriph_GPIOA +#define NIX_SPIx_MOSI_SOURCE GPIO_PinSource7 +#define NIX_SPIx_MOSI_AF GPIO_AF_0 + +#define NIX_SPIx_ST_PIN GPIO_Pin_4 +#define NIX_SPIx_ST_GPIO_PORT GPIOA +#define NIX_SPIx_ST_GPIO_CLK RCC_AHBPeriph_GPIOA +#define NIX_SPIx_ST_SOURCE GPIO_PinSource4 +#define NIX_SPIx_ST_AF GPIO_AF_0 + +#define NIX_SPIx_RCC_APBxPeriphClockCmd RCC_APB2PeriphClockCmd + +// Определения для таймера NixieDriver -------------------------------------- // +#define NIX_DRIVER_TIM_IRQHandler TIM16_IRQHandler +#define NIX_DRIVER_TIMx TIM16 +#define NIX_DRIVER_TIM_RCC RCC_APB2Periph_TIM16 +#define NIX_DRIVER_TIM_IRQx TIM16_IRQn +#define NIX_DRIVER_RCC_APBxPeriphClockCmd RCC_APB2PeriphClockCmd + +#define NIX_DRIVER_SET_ST_PIN GPIO_SetBits ( NIX_SPIx_ST_GPIO_PORT, NIX_SPIx_ST_PIN ) +#define NIX_DRIVER_RESET_ST_PIN GPIO_ResetBits ( NIX_SPIx_ST_GPIO_PORT, NIX_SPIx_ST_PIN ) + +// Определения для управления точками на лампах (т.к. не хватило ног сдвиговых редисок) +#define NIX_GPIOx_TUB_P1_GPIO_CLK RCC_AHBPeriph_GPIOB +#define NIX_GPIOx_TUB_P2_GPIO_CLK RCC_AHBPeriph_GPIOB +#define NIX_GPIOx_TUB_DP1_PIN GPIO_Pin_14 +#define NIX_GPIOx_TUB_DP2_PIN GPIO_Pin_12 +#define NIX_GPIOx_TUB_DP1_PORT GPIOB +#define NIX_GPIOx_TUB_DP2_PORT GPIOB +#define NIX_DRIVER_RESET_TUB_DP1_PIN NIX_GPIOx_TUB_DP1_PORT->BRR = NIX_GPIOx_TUB_DP1_PIN +#define NIX_DRIVER_RESET_TUB_DP2_PIN NIX_GPIOx_TUB_DP2_PORT->BRR = NIX_GPIOx_TUB_DP2_PIN +#define NIX_DRIVER_SET_TUB_DP1_PIN NIX_GPIOx_TUB_DP1_PORT->BSRR = NIX_GPIOx_TUB_DP1_PIN +#define NIX_DRIVER_SET_TUB_DP2_PIN NIX_GPIOx_TUB_DP2_PORT->BSRR = NIX_GPIOx_TUB_DP2_PIN + +void NixieDriverInitProcess ( void ); +void NixieDriverConfig ( void ); + +#endif //NIXIE_DRIVER_CONFIG_INCLUDED diff --git a/app/nixie_driver/nixie_driver_process.c b/app/nixie_driver/nixie_driver_process.c new file mode 100644 index 0000000..219494e --- /dev/null +++ b/app/nixie_driver/nixie_driver_process.c @@ -0,0 +1,346 @@ +#include "nixie_driver_process.h" +#include "nixie_driver_config.h" +#include "indicate_modes_task.h" +#include "light_sensor_task.h" + +#include <stdint.h> + +// FreeRTOS includes +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + +// - массив для цифр дешифратора +// - массив для номера лампы +// - счетчик номера текущей лампы +// - таймер1 для времени горения +// - таймер2 для времени затухания + +#define TUBE_HEATING_UP 0 + +static const uint16_t tube_off_digit = 0; // Символ для дешифратора, чтобы лампа не горела + +// Массив значений цифр для дешифратора. Если старший байт вперед. +// И учтено, что все значения сдвинуты на 1 влево +const uint16_t tube_digits [MAX_DIGITS] = { + // Цифра на лампе + TUBE_DIGIT_0, // 0 + TUBE_DIGIT_1, // 1 + TUBE_DIGIT_2, // 2 + TUBE_DIGIT_3, // 3 + TUBE_DIGIT_4, // 4 + TUBE_DIGIT_5, // 5 + TUBE_DIGIT_6, // 6 + TUBE_DIGIT_7, // 7 + TUBE_DIGIT_8, // 8 + TUBE_DIGIT_9, // 9 + TUBE_DIGIT_DP1, // dp1 + TUBE_DIGIT_DP2, // dp2 + TUBE_DIGIT_EMPTY, // лампа не горит +}; + +// Лампы на плате идут слева направо. Значение ячейки массива с учетом, если +// старший байт идет вперед в SPI +// И учтено, что все значения сдвинуты на 1 влево +static const uint16_t tube_num [ MAX_TUBES ] = { + TUBE_NUM_1, // 1-я лампа + TUBE_NUM_2, // 2-я лампа + TUBE_NUM_3, // 3-я лампа + TUBE_NUM_4, // 4-я лампа + TUBE_NUM_5, // 5-я лампа + TUBE_NUM_6, // 6-я лампа +}; + + +// Текущий буфер с данными-цифрами на лампы +static uint16_t curr_tube_bufer [ MAX_TUBES ] = { + TUBE_DIGIT_1, // 0 + TUBE_DIGIT_1, // 1 + TUBE_DIGIT_1, // 2 + TUBE_DIGIT_1, // 3 + TUBE_DIGIT_1, // 4 + TUBE_DIGIT_1, // 5 +}; + + +// Яркость ------------------------------------------------------------------ // + +// горит / не горит +// time1 / time2 +// 1 9 +// 2 8 +// 3 7 +// 4 6 +// 5 6 +// 6 4 +// 7 3 +// 8 2 +// 9 1 +// 10 0 + +#define TIME_PERIOD_TCONST (uint32_t)80 // Время полного периода частоты работы ламп. Единица измерения зависит от настройки + // таймера. В данном случае таймер тикает раз в 100 мкс, значит Т = 80 => T = 80*100 = 8000мкс = 8мс +#define TIME_MIN (uint32_t)1 // Минимальный шаг времени таймера = 100 мкс. Минимальное время горения лампы + +// - добавить состояния DARK и LIGHT +// (по сути это только комбинации TIME_ON и TIME_OFF) +#define TIME_ON 2//5//20 +#define TIME_OFF 23//22 +// Время паузы после вкл/выкл всез ламп поочереди +#define TIME_OFF_BRIGHT 0 +#define TIME_OFF_DARK 100 + +#define TIME_TEST 10000 + +static uint32_t time_on = TIME_ON; // Время горения лампы +static uint32_t time_off = TIME_OFF; // Время на угасание лампы ( чтобы она успела погаснуть полностью ) +static uint32_t time_off2 = TIME_OFF_DARK; + +// Сообщения очереди ОСРВ +QueueHandle_t queue_new_value; +QueueHandle_t queue_new_data; +static LightSensorState_t light_sensor_state; +extern QueueHandle_t queue_light_sensor; + + +// Прототипы функций файла -------------------------------------------------- // +// Открытые +void NixieDriver_SendValue ( uint8_t *value_arr ); +// Закрытые +static void SwitchOnTube ( uint8_t tube_nbr ); +static void SwitchOffTube ( uint8_t tube_nbr ); + +static uint8_t LoadNextValueToTubes ( void ); + +static void UpdateValueForClock ( void ); +static void CheckLightSensor (void); + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void NixieDriverInitProcess ( void ) +{ + queue_new_value = xQueueCreate ( 1, sizeof (uint8_t*) ); + configASSERT( queue_new_value ); + queue_new_data = xQueueCreate ( 1, sizeof (DataToIndicate_t) ); + configASSERT( queue_new_value ); +} + + +// ---------------------------------------------------------------------------- +// Ф-я, реализующая беспрерывный процесс динамической индикации ламп Nixie +// Ф-я вызывается из прерывания таймера, настроенного на 100 мкс +// ---------------------------------------------------------------------------- +void ProcessNixieDriverFromISR ( void ) +{ + static uint8_t process_indic_state = 0; + static uint32_t timer = TIME_ON; + static uint8_t curr_tube_num = 0; + timer++; +#if TUBE_HEATING_UP == 0 + switch ( process_indic_state ) + { + case 0: + if ( timer >= time_off ) // Ждем время горения лампы + { + curr_tube_num = LoadNextValueToTubes (); + SwitchOnTube ( curr_tube_num ); + timer = 0; + process_indic_state = 1; + } + break; + case 1: + if ( timer >= time_on ) + { + SwitchOffTube ( curr_tube_num ); + timer = 0; + process_indic_state = 0; + + if ( curr_tube_num == (MAX_TUBES - 1) ) + { + UpdateValueForClock (); + CheckLightSensor(); + + SwitchOffTube ( curr_tube_num ); + process_indic_state = 2; + timer = 0; + + } + } + break; + case 2: + if ( timer >= time_off2 ) + { + timer = time_off; + process_indic_state = 0; + } + break; + } // end switch +#endif +} + +// ---------------------------------------------------------------------------- +// Ф-я подготовки и запуска передачи байт по SPI в сдвиговые регистры +// управеления динамической индикацией. По сути включает нужную лампу +// Ф-я принимает текущий номер лампы, для которой будет формироваться +// пакет-кадр +// ---------------------------------------------------------------------------- +static void SwitchOnTube ( uint8_t tube_nbr ) +{ + // - сначала отправляем пару байт с номером лампы + // - затем отправляем пару байт с номером цифры + static uint16_t temp; + temp = 0; + temp = tube_num [ tube_nbr ]; + temp |= curr_tube_bufer [ tube_nbr ]; + NIX_DRIVER_RESET_ST_PIN; + // Т.к. точки на лампах управляются напрямую с МК через GPIO, + // то нужно проверять вручную идет ли в пакете точка + // Маленький нюанс: + // Если мы выставим сигнал на точки раньше, чем передадим пакет на включение ламп по SPI, + // то по идее точки включатся раньше, чем подастся сигнал ST + if (curr_tube_bufer [ tube_nbr ] & TUBE_DIGIT_DP1) + { + NIX_DRIVER_SET_TUB_DP1_PIN; + } + else + { + NIX_DRIVER_RESET_TUB_DP1_PIN; + } + if (curr_tube_bufer [ tube_nbr ] & TUBE_DIGIT_DP2) + { + NIX_DRIVER_SET_TUB_DP2_PIN; + } + else + { + NIX_DRIVER_RESET_TUB_DP2_PIN; + } + SPI_I2S_SendData16 ( NIX_SPIx, temp ); + SPI_I2S_ITConfig ( NIX_SPIx, SPI_I2S_IT_TXE, ENABLE ); +} + +// ---------------------------------------------------------------------------- +// Ф-я отключает лампу +// ---------------------------------------------------------------------------- +static void SwitchOffTube ( uint8_t tube_nbr ) +{ + NIX_DRIVER_RESET_ST_PIN; + NIX_DRIVER_RESET_TUB_DP1_PIN; + NIX_DRIVER_RESET_TUB_DP2_PIN; + SPI_I2S_SendData16 ( NIX_SPIx, tube_off_digit ); + SPI_I2S_ITConfig ( NIX_SPIx, SPI_I2S_IT_TXE, ENABLE ); +} + +#if TUBE_HEATING_UP == 1 +// ---------------------------------------------------------------------------- +// Временная ф-я для прогрева каждой лампы по каждому катоду +// ---------------------------------------------------------------------------- +static uint8_t LoadNextValueToTubes ( void ) +{ + static uint8_t curr_tube_num = 0; + static uint8_t curr_digit = 0; + if ( curr_digit == 10 ) + { + if ( curr_tube_num == 5 ) + { + curr_tube_num = 0; + } + else + { + curr_tube_num++; + if ( curr_tube_num == 1 ) { curr_tube_num++; } + } + curr_digit = 0; + } + + curr_tube_bufer [ curr_tube_num ] = tube_digits [ curr_digit ]; + curr_digit++; + + return curr_tube_num; +} + +#else + +static uint8_t LoadNextValueToTubes ( void ) +{ + static uint8_t curr_tube_num = 5; + if ( curr_tube_num == 5 ) + { + curr_tube_num = 0; + } + else + { + curr_tube_num++; + } + return curr_tube_num; +} + +#endif + +// ---------------------------------------------------------------------------- +// Обновления значения выводимого на индикаторы +// Ф-я вызывается из ф-ии ProcessNixieDriverFromISR () после вывода одного +// цикла ( то есть 6-ти индикаторов ) +// ---------------------------------------------------------------------------- + +// - внимание! нужно сделать два буфера, из которых в прерывании берутся +// данные на передачу в лампы в SPI. Это нужно, чтобы не тратить время на +// заполнение данных буфера. Сделать флаг или семафор. Пока из одного +// буфера данные уходят, то в другой заполняют новые данные. А когда они +// заполнятся, то просто поменять указатель на массив. + +// - сделать защиту от выхода за границы массива tube_digits [10] +// (не больше 10) + +static void UpdateValueForClock ( void ) +{ + // - проверяем сообщение очереди с новыми данными для отображения + // если есть, то заполняем буфер curr_tube_bufer [] новыми значениями + DataToIndicate_t data_struct; + + if ( pdPASS == xQueueReceive ( queue_new_data, &data_struct, 0 ) ) + { + curr_tube_bufer [0] = tube_digits [ data_struct.indic_1 ]; + curr_tube_bufer [1] = tube_digits [ data_struct.indic_2 ]; + curr_tube_bufer [2] = tube_digits [ data_struct.indic_3 ]; + curr_tube_bufer [3] = tube_digits [ data_struct.indic_4 ]; + curr_tube_bufer [4] = tube_digits [ data_struct.indic_5 ]; + curr_tube_bufer [5] = tube_digits [ data_struct.indic_6 ]; + } +} + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +static void CheckLightSensor (void) +{ + //LightSensorState_t light_sensor_state; + if ( pdPASS == xQueueReceive ( queue_light_sensor, &light_sensor_state, 0 ) ) + { + if (light_sensor_state == LIGHT_SENSOR_STATE_LIGHT ) + { + time_on = TIME_OFF; + time_off = TIME_ON; + time_off2 = TIME_OFF_BRIGHT;//TIME_OFF_DARK; + } + else + { + time_on = TIME_ON; + time_off = TIME_OFF; + time_off2 = TIME_OFF_DARK;//TIME_OFF_BRIGHT; + } + } +} + + +// ---------------------------------------------------------------------------- +// Ф-я кладет сообщение в очередь ОС и передает указатель на массив с данными +// Размер массива всегда 6 (количество ламп) +// ---------------------------------------------------------------------------- +void NixieDriver_SendValue ( uint8_t *value_arr ) +{ + xQueueSend ( queue_new_value, &value_arr, 0 ); +} diff --git a/app/nixie_driver/nixie_driver_process.h b/app/nixie_driver/nixie_driver_process.h new file mode 100644 index 0000000..bc4b4ca --- /dev/null +++ b/app/nixie_driver/nixie_driver_process.h @@ -0,0 +1,62 @@ +#ifndef NIXIE_DRIVER_PROCESS_INCLUDED +#define NIXIE_DRIVER_PROCESS_INCLUDED + +#include <stdint.h> +#include "FreeRTOS.h" +#include "queue.h" + +// Схема драйвера Никси на трех сдвиговых 8-разрядных регистрах. +// Первые два регистра для цифр, третий регистр для выбора лампы + +#define MAX_TUBES 6 +#define MAX_DIGITS 13//11 + +// Коды цифр ламп для буфера tube_digit [] Значения 16-разрядные +#define TUBE_DIGIT_0 8192 //0010 0000 0000 0000 +#define TUBE_DIGIT_1 128 //0000 0000 1000 0000 +#define TUBE_DIGIT_2 64 //0000 0000 0100 0000 +#define TUBE_DIGIT_3 32 //0000 0000 0010 0000 +#define TUBE_DIGIT_4 16 //0000 0000 0001 0000 +#define TUBE_DIGIT_5 8 //0000 0000 0000 1000 +#define TUBE_DIGIT_6 4 //0000 0000 0000 0100 +#define TUBE_DIGIT_7 2 //0000 0000 0000 0010 +#define TUBE_DIGIT_8 32768 //1000 0000 0000 0000 +#define TUBE_DIGIT_9 16384 //0100 0000 0000 0000 +#define TUBE_DIGIT_DP1 1 //0000 0000 0000 0001 любое отличное от остальных число, т.к. точки на лампах управляются от отдельных GPIO +#define TUBE_DIGIT_DP2 256 //0000 0001 0000 0000 любое отличное от остальных число, т.к. точки на лампах управляются от отдельных GPIO +#define TUBE_DIGIT_EMPTY 0 + +#define TUBE_EMPTY_VALUE 0 // Было "10". Число, которое нужно записать в массив + // данных на вывод, чтобы получить негорящий + // индикатор + +// Коды номера лампы для буфера tube_num [ MAX_TUBES ] +#define TUBE_NUM_6 1 +#define TUBE_NUM_5 256 +#define TUBE_NUM_4 512 +#define TUBE_NUM_3 1024 +#define TUBE_NUM_2 2048 +#define TUBE_NUM_1 4096 + +// Структура данных на индикацию для передачи целиком всей структуры через +// очередь ОС +typedef struct { + uint8_t indic_1; + uint8_t indic_2; + uint8_t indic_3; + uint8_t indic_4; + uint8_t indic_5; + uint8_t indic_6; +} DataToIndicate_t; + + +void NixieDriver_SendValue ( uint8_t *value_arr ); + +extern QueueHandle_t queue_new_data; + +#define send(X) xQueueSend ( queue_new_data, &X, 0 ) +#define NixieDriver_SendValue2(X) send(X) + +void ProcessNixieDriverFromISR ( void ); + +#endif //NIXIE_DRIVER_PROCESS_INCLUDED diff --git a/app/nixie_driver/nixie_driver_task.c b/app/nixie_driver/nixie_driver_task.c new file mode 100644 index 0000000..b968128 --- /dev/null +++ b/app/nixie_driver/nixie_driver_task.c @@ -0,0 +1,36 @@ +#include "nixie_driver_task.h" +#include "nixie_driver_config.h" +#include "nixie_driver_process.h" + +#include "FreeRTOS.h" +#include "task.h" +#include "queue.h" +#include "semphr.h" + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void NixieDriverInit ( void ) +{ + NixieDriverInitProcess (); + NixieDriverConfig (); +} + + +// ---------------------------------------------------------------------------- +// - нужна ли эта задача, если все работает в прерывании? +// ---------------------------------------------------------------------------- +void ProcessFSM_NixieDriver ( void ) +{ + vTaskDelay (500); +} + + +// ---------------------------------------------------------------------------- +// Задача ОС, реализующая головную задачу программы NixieClockSimply +// ---------------------------------------------------------------------------- +void NixieDriver_Task ( void *pvParameters ) +{ + while(1)ProcessFSM_NixieDriver (); +} diff --git a/app/nixie_driver/nixie_driver_task.h b/app/nixie_driver/nixie_driver_task.h new file mode 100644 index 0000000..71546cd --- /dev/null +++ b/app/nixie_driver/nixie_driver_task.h @@ -0,0 +1,8 @@ +#ifndef NIXIE_DRIVER_TASK_INCLUDED +#define NIXIE_DRIVER_TASK_INCLUDED + +void NixieDriverInit ( void ); + +void NixieDriver_Task ( void *pvParameters ); + +#endif //NIXIE_DRIVER_TASK_INCLUDED diff --git a/app/platform/stm32f0-gcc/freertos/FreeRTOSConfig.h b/app/platform/stm32f0-gcc/freertos/FreeRTOSConfig.h new file mode 100644 index 0000000..031cb01 --- /dev/null +++ b/app/platform/stm32f0-gcc/freertos/FreeRTOSConfig.h @@ -0,0 +1,157 @@ +/* + FreeRTOS V8.0.0 - Copyright (C) 2014 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that has become a de facto standard. * + * * + * Help yourself get started quickly and support the FreeRTOS * + * project by purchasing a FreeRTOS tutorial book, reference * + * manual, or both from: http://www.FreeRTOS.org/Documentation * + * * + * Thank you! * + * * + *************************************************************************** + + This file is part of the FreeRTOS distribution. + + FreeRTOS is free software; you can redistribute it and/or modify it under + the terms of the GNU General Public License (version 2) as published by the + Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception. + + >>! NOTE: The modification to the GPL is included to allow you to distribute + >>! a combined work that includes FreeRTOS without being obliged to provide + >>! the source code for proprietary components outside of the FreeRTOS + >>! kernel. + + FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY + WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + FOR A PARTICULAR PURPOSE. Full license text is available from the following + link: http://www.freertos.org/a00114.html + + 1 tab == 4 spaces! + + *************************************************************************** + * * + * Having a problem? Start by reading the FAQ "My application does * + * not run, what could be wrong?" * + * * + * http://www.FreeRTOS.org/FAQHelp.html * + * * + *************************************************************************** + + http://www.FreeRTOS.org - Documentation, books, training, latest versions, + license and Real Time Engineers Ltd. contact details. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High + Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and middleware. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. + + 1 tab == 4 spaces! +*/ + + +/* The following #error directive is to remind users that a batch file must be + * executed prior to this project being built. The batch file *cannot* be + * executed from within CCS4! Once it has been executed, re-open or refresh + * the CCS4 project and remove the #error line below. + */ +//#error Ensure CreateProjectDirectoryStructure.bat has been executed before building. See comment immediately above. + + +#ifndef FREERTOS_CONFIG_H +#define FREERTOS_CONFIG_H + +/*----------------------------------------------------------- + * Application specific definitions. + * + * These definitions should be adjusted for your particular hardware and + * application requirements. + * + * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE + * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE. + * + * See http://www.freertos.org/a00110.html. + *----------------------------------------------------------*/ + +#define configUSE_PREEMPTION 1 // 1 - Вытесняющаяя многозадачность, 0 - Кооперативная +#define configUSE_IDLE_HOOK 1 +#define configUSE_TICK_HOOK 0 +#define configCPU_CLOCK_HZ ( 48000000UL ) // tros было 24000000UL +#define configTICK_RATE_HZ ( ( TickType_t ) 1000 ) +#define configMAX_PRIORITIES ( 5 ) + +#define configMINIMAL_STACK_SIZE ( ( unsigned short ) 70 ) // trots, was 70 +#define configTOTAL_HEAP_SIZE ( ( size_t ) ( 10 * 1024 ) ) // trots, was 10 // Уменьшил MEM_SIZE в файле lwipopts.h + +#define configMAX_TASK_NAME_LEN ( 10 ) +#define configUSE_TRACE_FACILITY 0 +#define configUSE_16_BIT_TICKS 0 +#define configIDLE_SHOULD_YIELD 1 +#define configUSE_MUTEXES 1 +#define configQUEUE_REGISTRY_SIZE 0 +#define configGENERATE_RUN_TIME_STATS 0 +#define configCHECK_FOR_STACK_OVERFLOW 2 // trots was 2 +#define configUSE_RECURSIVE_MUTEXES 0 +#define configUSE_MALLOC_FAILED_HOOK 1 +#define configUSE_APPLICATION_TASK_TAG 0 +#define configUSE_COUNTING_SEMAPHORES 0 + +/* Co-routine definitions. */ +#define configUSE_CO_ROUTINES 0 // Чтобы использовать программные таймеры, нужно единичку (там прототипы содержатся) +#define configMAX_CO_ROUTINE_PRIORITIES ( 2 ) + +/* Software timer definitions. */ +#define configUSE_TIMERS 1 +#define configTIMER_TASK_PRIORITY ( 3 ) +#define configTIMER_QUEUE_LENGTH 5 +#define configTIMER_TASK_STACK_DEPTH ( configMINIMAL_STACK_SIZE ) + +/* Set the following definitions to 1 to include the API function, or zero +to exclude the API function. */ +#define INCLUDE_vTaskPrioritySet 1 +#define INCLUDE_uxTaskPriorityGet 1 +#define INCLUDE_vTaskDelete 1 +#define INCLUDE_vTaskCleanUpResources 1 +#define INCLUDE_vTaskSuspend 1 +#define INCLUDE_vTaskDelayUntil 1 +#define INCLUDE_vTaskDelay 1 + +/* Use the system definition, if there is one */ +#ifdef __NVIC_PRIO_BITS + #define configPRIO_BITS __NVIC_PRIO_BITS +#else + #define configPRIO_BITS 4 /* 15 priority levels */ +#endif + +#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 15 +#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 11 + +/* The lowest priority. */ +#define configKERNEL_INTERRUPT_PRIORITY ( configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) +/* Priority 5, or 95 as only the top four bits are implemented. */ +/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!! +See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */ +#define configMAX_SYSCALL_INTERRUPT_PRIORITY ( configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) ) + +#define configASSERT( x ) if( ( x ) == 0 ) { taskDISABLE_INTERRUPTS(); for( ;; ); } + +#define vPortSVCHandler SVCALL_handler +#define xPortPendSVHandler PENDSV_handler +#define xPortSysTickHandler SYSTICK_handler + +#endif /* FREERTOS_CONFIG_H */ + diff --git a/app/platform/stm32f0-gcc/freertos/port.c b/app/platform/stm32f0-gcc/freertos/port.c new file mode 100644 index 0000000..423ae1e --- /dev/null +++ b/app/platform/stm32f0-gcc/freertos/port.c @@ -0,0 +1,368 @@ +/*
+ FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+ All rights reserved
+
+ VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+ This file is part of the FreeRTOS distribution.
+
+ FreeRTOS is free software; you can redistribute it and/or modify it under
+ the terms of the GNU General Public License (version 2) as published by the
+ Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+ ***************************************************************************
+ >>! NOTE: The modification to the GPL is included to allow you to !<<
+ >>! distribute a combined work that includes FreeRTOS without being !<<
+ >>! obliged to provide the source code for proprietary components !<<
+ >>! outside of the FreeRTOS kernel. !<<
+ ***************************************************************************
+
+ FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ FOR A PARTICULAR PURPOSE. Full license text is available on the following
+ link: http://www.freertos.org/a00114.html
+
+ ***************************************************************************
+ * *
+ * FreeRTOS provides completely free yet professionally developed, *
+ * robust, strictly quality controlled, supported, and cross *
+ * platform software that is more than just the market leader, it *
+ * is the industry's de facto standard. *
+ * *
+ * Help yourself get started quickly while simultaneously helping *
+ * to support the FreeRTOS project by purchasing a FreeRTOS *
+ * tutorial book, reference manual, or both: *
+ * http://www.FreeRTOS.org/Documentation *
+ * *
+ ***************************************************************************
+
+ http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
+ the FAQ page "My application does not run, what could be wrong?". Have you
+ defined configASSERT()?
+
+ http://www.FreeRTOS.org/support - In return for receiving this top quality
+ embedded software for free we request you assist our global community by
+ participating in the support forum.
+
+ http://www.FreeRTOS.org/training - Investing in training allows your team to
+ be as productive as possible as early as possible. Now you can receive
+ FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+ Ltd, and the world's leading authority on the world's leading RTOS.
+
+ http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+ including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+ compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+ http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+ Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+ http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+ Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
+ licenses offer ticketed support, indemnification and commercial middleware.
+
+ http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+ engineered and independently SIL3 certified version for use in safety and
+ mission critical applications that require provable dependability.
+
+ 1 tab == 4 spaces!
+*/
+
+/*-----------------------------------------------------------
+ * Implementation of functions defined in portable.h for the ARM CM0 port.
+ *----------------------------------------------------------*/
+
+/* Scheduler includes. */
+#include "FreeRTOS.h"
+#include "task.h"
+
+/* Constants required to manipulate the NVIC. */
+#define portNVIC_SYSTICK_CTRL ( ( volatile uint32_t *) 0xe000e010 )
+#define portNVIC_SYSTICK_LOAD ( ( volatile uint32_t *) 0xe000e014 )
+#define portNVIC_INT_CTRL ( ( volatile uint32_t *) 0xe000ed04 )
+#define portNVIC_SYSPRI2 ( ( volatile uint32_t *) 0xe000ed20 )
+#define portNVIC_SYSTICK_CLK 0x00000004
+#define portNVIC_SYSTICK_INT 0x00000002
+#define portNVIC_SYSTICK_ENABLE 0x00000001
+#define portNVIC_PENDSVSET 0x10000000
+#define portMIN_INTERRUPT_PRIORITY ( 255UL )
+#define portNVIC_PENDSV_PRI ( portMIN_INTERRUPT_PRIORITY << 16UL )
+#define portNVIC_SYSTICK_PRI ( portMIN_INTERRUPT_PRIORITY << 24UL )
+
+/* Constants required to set up the initial stack. */
+#define portINITIAL_XPSR ( 0x01000000 )
+
+/* Let the user override the pre-loading of the initial LR with the address of
+prvTaskExitError() in case is messes up unwinding of the stack in the
+debugger. */
+#ifdef configTASK_RETURN_ADDRESS
+ #define portTASK_RETURN_ADDRESS configTASK_RETURN_ADDRESS
+#else
+ #define portTASK_RETURN_ADDRESS prvTaskExitError
+#endif
+
+/* Each task maintains its own interrupt status in the critical nesting
+variable. */
+static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
+
+/*
+ * Setup the timer to generate the tick interrupts.
+ */
+static void prvSetupTimerInterrupt( void );
+
+/*
+ * Exception handlers.
+ */
+void PENDSV_handler( void ) __attribute__ (( naked ));
+void SYSTICK_handler( void );
+void SVCALL_handler( void );
+
+/*
+ * Start first task is a separate function so it can be tested in isolation.
+ */
+static void vPortStartFirstTask( void ) __attribute__ (( naked ));
+
+/*
+ * Used to catch tasks that attempt to return from their implementing function.
+ */
+static void prvTaskExitError( void );
+
+/*-----------------------------------------------------------*/
+
+/*
+ * See header file for description.
+ */
+StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
+{
+ /* Simulate the stack frame as it would be created by a context switch
+ interrupt. */
+ pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
+ *pxTopOfStack = portINITIAL_XPSR; /* xPSR */
+ pxTopOfStack--;
+ *pxTopOfStack = ( StackType_t ) pxCode; /* PC */
+ pxTopOfStack--;
+ *pxTopOfStack = ( StackType_t ) portTASK_RETURN_ADDRESS; /* LR */
+ pxTopOfStack -= 5; /* R12, R3, R2 and R1. */
+ *pxTopOfStack = ( StackType_t ) pvParameters; /* R0 */
+ pxTopOfStack -= 8; /* R11..R4. */
+
+ return pxTopOfStack;
+}
+/*-----------------------------------------------------------*/
+
+static void prvTaskExitError( void )
+{
+ /* A function that implements a task must not exit or attempt to return to
+ its caller as there is nothing to return to. If a task wants to exit it
+ should instead call vTaskDelete( NULL ).
+
+ Artificially force an assert() to be triggered if configASSERT() is
+ defined, then stop here so application writers can catch the error. */
+ configASSERT( uxCriticalNesting == ~0UL );
+ portDISABLE_INTERRUPTS();
+ for( ;; );
+}
+/*-----------------------------------------------------------*/
+
+void SVCALL_handler( void )
+{
+ /* This function is no longer used, but retained for backward
+ compatibility. */
+}
+/*-----------------------------------------------------------*/
+
+void vPortStartFirstTask( void )
+{
+ /* The MSP stack is not reset as, unlike on M3/4 parts, there is no vector
+ table offset register that can be used to locate the initial stack value.
+ Not all M0 parts have the application vector table at address 0. */
+ __asm volatile(
+ " ldr r2, pxCurrentTCBConst2 \n" /* Obtain location of pxCurrentTCB. */
+ " ldr r3, [r2] \n"
+ " ldr r0, [r3] \n" /* The first item in pxCurrentTCB is the task top of stack. */
+ " add r0, #32 \n" /* Discard everything up to r0. */
+ " msr psp, r0 \n" /* This is now the new top of stack to use in the task. */
+ " movs r0, #2 \n" /* Switch to the psp stack. */
+ " msr CONTROL, r0 \n"
+ " pop {r0-r5} \n" /* Pop the registers that are saved automatically. */
+ " mov lr, r5 \n" /* lr is now in r5. */
+ " cpsie i \n" /* The first task has its context and interrupts can be enabled. */
+ " pop {pc} \n" /* Finally, pop the PC to jump to the user defined task code. */
+ " \n"
+ " .align 2 \n"
+ "pxCurrentTCBConst2: .word pxCurrentTCB "
+ );
+}
+/*-----------------------------------------------------------*/
+
+/*
+ * See header file for description.
+ */
+BaseType_t xPortStartScheduler( void )
+{
+ /* Make PendSV, CallSV and SysTick the same priroity as the kernel. */
+ *(portNVIC_SYSPRI2) |= portNVIC_PENDSV_PRI;
+ *(portNVIC_SYSPRI2) |= portNVIC_SYSTICK_PRI;
+
+ /* Start the timer that generates the tick ISR. Interrupts are disabled
+ here already. */
+ prvSetupTimerInterrupt();
+
+ /* Initialise the critical nesting count ready for the first task. */
+ uxCriticalNesting = 0;
+
+ /* Start the first task. */
+ vPortStartFirstTask();
+
+ /* Should never get here as the tasks will now be executing! Call the task
+ exit error function to prevent compiler warnings about a static function
+ not being called in the case that the application writer overrides this
+ functionality by defining configTASK_RETURN_ADDRESS. */
+ prvTaskExitError();
+
+ /* Should not get here! */
+ return 0;
+}
+/*-----------------------------------------------------------*/
+
+void vPortEndScheduler( void )
+{
+ /* Not implemented in ports where there is nothing to return to.
+ Artificially force an assert. */
+ configASSERT( uxCriticalNesting == 1000UL );
+}
+/*-----------------------------------------------------------*/
+
+void vPortYield( void )
+{
+ /* Set a PendSV to request a context switch. */
+ *( portNVIC_INT_CTRL ) = portNVIC_PENDSVSET;
+
+ /* Barriers are normally not required but do ensure the code is completely
+ within the specified behaviour for the architecture. */
+ __asm volatile( "dsb" );
+ __asm volatile( "isb" );
+}
+/*-----------------------------------------------------------*/
+
+void vPortEnterCritical( void )
+{
+ portDISABLE_INTERRUPTS();
+ uxCriticalNesting++;
+ __asm volatile( "dsb" );
+ __asm volatile( "isb" );
+}
+/*-----------------------------------------------------------*/
+
+void vPortExitCritical( void )
+{
+ configASSERT( uxCriticalNesting );
+ uxCriticalNesting--;
+ if( uxCriticalNesting == 0 )
+ {
+ portENABLE_INTERRUPTS();
+ }
+}
+/*-----------------------------------------------------------*/
+
+uint32_t ulSetInterruptMaskFromISR( void )
+{
+ __asm volatile(
+ " mrs r0, PRIMASK \n"
+ " cpsid i \n"
+ " bx lr "
+ );
+
+ /* To avoid compiler warnings. This line will never be reached. */
+ return 0;
+}
+/*-----------------------------------------------------------*/
+
+void vClearInterruptMaskFromISR( uint32_t ulMask )
+{
+ __asm volatile(
+ " msr PRIMASK, r0 \n"
+ " bx lr "
+ );
+
+ /* Just to avoid compiler warning. */
+ ( void ) ulMask;
+}
+/*-----------------------------------------------------------*/
+
+void PENDSV_handler( void )
+{
+ /* This is a naked function. */
+
+ __asm volatile
+ (
+ " mrs r0, psp \n"
+ " \n"
+ " ldr r3, pxCurrentTCBConst \n" /* Get the location of the current TCB. */
+ " ldr r2, [r3] \n"
+ " \n"
+ " sub r0, r0, #32 \n" /* Make space for the remaining low registers. */
+ " str r0, [r2] \n" /* Save the new top of stack. */
+ " stmia r0!, {r4-r7} \n" /* Store the low registers that are not saved automatically. */
+ " mov r4, r8 \n" /* Store the high registers. */
+ " mov r5, r9 \n"
+ " mov r6, r10 \n"
+ " mov r7, r11 \n"
+ " stmia r0!, {r4-r7} \n"
+ " \n"
+ " push {r3, r14} \n"
+ " cpsid i \n"
+ " bl vTaskSwitchContext \n"
+ " cpsie i \n"
+ " pop {r2, r3} \n" /* lr goes in r3. r2 now holds tcb pointer. */
+ " \n"
+ " ldr r1, [r2] \n"
+ " ldr r0, [r1] \n" /* The first item in pxCurrentTCB is the task top of stack. */
+ " add r0, r0, #16 \n" /* Move to the high registers. */
+ " ldmia r0!, {r4-r7} \n" /* Pop the high registers. */
+ " mov r8, r4 \n"
+ " mov r9, r5 \n"
+ " mov r10, r6 \n"
+ " mov r11, r7 \n"
+ " \n"
+ " msr psp, r0 \n" /* Remember the new top of stack for the task. */
+ " \n"
+ " sub r0, r0, #32 \n" /* Go back for the low registers that are not automatically restored. */
+ " ldmia r0!, {r4-r7} \n" /* Pop low registers. */
+ " \n"
+ " bx r3 \n"
+ " \n"
+ " .align 2 \n"
+ "pxCurrentTCBConst: .word pxCurrentTCB "
+ );
+}
+/*-----------------------------------------------------------*/
+
+void SYSTICK_handler( void )
+{
+uint32_t ulPreviousMask;
+
+ ulPreviousMask = portSET_INTERRUPT_MASK_FROM_ISR();
+ {
+ /* Increment the RTOS tick. */
+ if( xTaskIncrementTick() != pdFALSE )
+ {
+ /* Pend a context switch. */
+ *(portNVIC_INT_CTRL) = portNVIC_PENDSVSET;
+ }
+ }
+ portCLEAR_INTERRUPT_MASK_FROM_ISR( ulPreviousMask );
+}
+/*-----------------------------------------------------------*/
+
+/*
+ * Setup the systick timer to generate the tick interrupts at the required
+ * frequency.
+ */
+void prvSetupTimerInterrupt( void )
+{
+ /* Configure SysTick to interrupt at the requested rate. */
+ *(portNVIC_SYSTICK_LOAD) = ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
+ *(portNVIC_SYSTICK_CTRL) = portNVIC_SYSTICK_CLK | portNVIC_SYSTICK_INT | portNVIC_SYSTICK_ENABLE;
+}
+/*-----------------------------------------------------------*/
+
diff --git a/app/platform/stm32f0-gcc/freertos/portmacro.h b/app/platform/stm32f0-gcc/freertos/portmacro.h new file mode 100644 index 0000000..54c219e --- /dev/null +++ b/app/platform/stm32f0-gcc/freertos/portmacro.h @@ -0,0 +1,157 @@ +/*
+ FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+ All rights reserved
+
+ VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+ This file is part of the FreeRTOS distribution.
+
+ FreeRTOS is free software; you can redistribute it and/or modify it under
+ the terms of the GNU General Public License (version 2) as published by the
+ Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+ ***************************************************************************
+ >>! NOTE: The modification to the GPL is included to allow you to !<<
+ >>! distribute a combined work that includes FreeRTOS without being !<<
+ >>! obliged to provide the source code for proprietary components !<<
+ >>! outside of the FreeRTOS kernel. !<<
+ ***************************************************************************
+
+ FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ FOR A PARTICULAR PURPOSE. Full license text is available on the following
+ link: http://www.freertos.org/a00114.html
+
+ ***************************************************************************
+ * *
+ * FreeRTOS provides completely free yet professionally developed, *
+ * robust, strictly quality controlled, supported, and cross *
+ * platform software that is more than just the market leader, it *
+ * is the industry's de facto standard. *
+ * *
+ * Help yourself get started quickly while simultaneously helping *
+ * to support the FreeRTOS project by purchasing a FreeRTOS *
+ * tutorial book, reference manual, or both: *
+ * http://www.FreeRTOS.org/Documentation *
+ * *
+ ***************************************************************************
+
+ http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
+ the FAQ page "My application does not run, what could be wrong?". Have you
+ defined configASSERT()?
+
+ http://www.FreeRTOS.org/support - In return for receiving this top quality
+ embedded software for free we request you assist our global community by
+ participating in the support forum.
+
+ http://www.FreeRTOS.org/training - Investing in training allows your team to
+ be as productive as possible as early as possible. Now you can receive
+ FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+ Ltd, and the world's leading authority on the world's leading RTOS.
+
+ http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+ including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+ compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+ http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+ Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+ http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+ Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
+ licenses offer ticketed support, indemnification and commercial middleware.
+
+ http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+ engineered and independently SIL3 certified version for use in safety and
+ mission critical applications that require provable dependability.
+
+ 1 tab == 4 spaces!
+*/
+
+
+#ifndef PORTMACRO_H
+#define PORTMACRO_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-----------------------------------------------------------
+ * Port specific definitions.
+ *
+ * The settings in this file configure FreeRTOS correctly for the
+ * given hardware and compiler.
+ *
+ * These settings should not be altered.
+ *-----------------------------------------------------------
+ */
+
+/* Type definitions. */
+#define portCHAR char
+#define portFLOAT float
+#define portDOUBLE double
+#define portLONG long
+#define portSHORT short
+#define portSTACK_TYPE uint32_t
+#define portBASE_TYPE long
+
+typedef portSTACK_TYPE StackType_t;
+typedef long BaseType_t;
+typedef unsigned long UBaseType_t;
+
+#if( configUSE_16_BIT_TICKS == 1 )
+ typedef uint16_t TickType_t;
+ #define portMAX_DELAY ( TickType_t ) 0xffff
+#else
+ typedef uint32_t TickType_t;
+ #define portMAX_DELAY ( TickType_t ) 0xffffffffUL
+
+ /* 32-bit tick type on a 32-bit architecture, so reads of the tick count do
+ not need to be guarded with a critical section. */
+ #define portTICK_TYPE_IS_ATOMIC 1
+#endif
+/*-----------------------------------------------------------*/
+
+/* Architecture specifics. */
+#define portSTACK_GROWTH ( -1 )
+#define portTICK_PERIOD_MS ( ( TickType_t ) 1000 / configTICK_RATE_HZ )
+#define portBYTE_ALIGNMENT 8
+/*-----------------------------------------------------------*/
+
+
+/* Scheduler utilities. */
+extern void vPortYield( void );
+#define portNVIC_INT_CTRL_REG ( * ( ( volatile uint32_t * ) 0xe000ed04 ) )
+#define portNVIC_PENDSVSET_BIT ( 1UL << 28UL )
+#define portYIELD() vPortYield()
+#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired ) portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT
+#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x )
+/*-----------------------------------------------------------*/
+
+
+/* Critical section management. */
+extern void vPortEnterCritical( void );
+extern void vPortExitCritical( void );
+extern uint32_t ulSetInterruptMaskFromISR( void ) __attribute__((naked));
+extern void vClearInterruptMaskFromISR( uint32_t ulMask ) __attribute__((naked));
+
+#define portSET_INTERRUPT_MASK_FROM_ISR() ulSetInterruptMaskFromISR()
+#define portCLEAR_INTERRUPT_MASK_FROM_ISR(x) vClearInterruptMaskFromISR( x )
+#define portDISABLE_INTERRUPTS() __asm volatile ( " cpsid i " )
+#define portENABLE_INTERRUPTS() __asm volatile ( " cpsie i " )
+#define portENTER_CRITICAL() vPortEnterCritical()
+#define portEXIT_CRITICAL() vPortExitCritical()
+
+/*-----------------------------------------------------------*/
+
+/* Task function macros as described on the FreeRTOS.org WEB site. */
+#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters )
+#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters )
+
+#define portNOP()
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PORTMACRO_H */
+
diff --git a/app/platform/stm32f0-gcc/startup/handlers_cm.c b/app/platform/stm32f0-gcc/startup/handlers_cm.c new file mode 100644 index 0000000..95b59a9 --- /dev/null +++ b/app/platform/stm32f0-gcc/startup/handlers_cm.c @@ -0,0 +1,113 @@ +/** + * Handlers setup code for Cortex-M. + */ + +typedef void (*ptr_func_t)(); + +// Undefined handler is pointing to this function, this stop MCU. +// This function name must by not mangled, so must be C, +// because alias("..") is working only with C code +void __stop() { while (1); } + +// Handlers for Cortex-M core. +// These handler are with attribute 'weak' and can be overwritten +// by non-weak function, default is __stop() function +__attribute__((weak, alias("__stop"))) void RESET_handler(); +__attribute__((weak, alias("__stop"))) void NMI_handler(); +__attribute__((weak, alias("__stop"))) void HARDFAULT_handler(); +__attribute__((weak, alias("__stop"))) void MEMMANAGE_handler(); +__attribute__((weak, alias("__stop"))) void BUSFAULT_handler(); +__attribute__((weak, alias("__stop"))) void USAGEFAULT_handler(); +__attribute__((weak, alias("__stop"))) void SVCALL_handler(); +__attribute__((weak, alias("__stop"))) void DEBUGMONITOR_handler(); +__attribute__((weak, alias("__stop"))) void PENDSV_handler(); +__attribute__((weak, alias("__stop"))) void SYSTICK_handler(); + +// Handlers for peripherals' interrupts +__attribute__((weak, alias("__stop"))) void WWDG_handler(); +__attribute__((weak, alias("__stop"))) void PVD_VDDIO2_handler(); +__attribute__((weak, alias("__stop"))) void RTC_handler(); +__attribute__((weak, alias("__stop"))) void FLASH_handler(); +__attribute__((weak, alias("__stop"))) void RCC_CRS_handler(); +__attribute__((weak, alias("__stop"))) void EXTI0_1_handler(); +__attribute__((weak, alias("__stop"))) void EXTI2_3_handler(); +__attribute__((weak, alias("__stop"))) void EXTI4_15_handler(); +__attribute__((weak, alias("__stop"))) void TSC_handler(); +__attribute__((weak, alias("__stop"))) void DMA_0064_handler(); +__attribute__((weak, alias("__stop"))) void DMA_DMA2_0068_handler(); +__attribute__((weak, alias("__stop"))) void DMA_DMA2_006C_handler(); +__attribute__((weak, alias("__stop"))) void ADC_COMP_handler(); +__attribute__((weak, alias("__stop"))) void TIM1_0074_handler(); +__attribute__((weak, alias("__stop"))) void TIM1_0078_handler(); +__attribute__((weak, alias("__stop"))) void TIM2_handler(); +__attribute__((weak, alias("__stop"))) void TIM3_handler(); +__attribute__((weak, alias("__stop"))) void TIM6_DAC_handler(); +__attribute__((weak, alias("__stop"))) void TIM7_handler(); +__attribute__((weak, alias("__stop"))) void TIM14_handler(); +__attribute__((weak, alias("__stop"))) void TIM15_handler(); +__attribute__((weak, alias("__stop"))) void TIM16_handler(); +__attribute__((weak, alias("__stop"))) void TIM17_handler(); +__attribute__((weak, alias("__stop"))) void I2C1_handler(); +__attribute__((weak, alias("__stop"))) void I2C2_handler(); +__attribute__((weak, alias("__stop"))) void SPI1_handler(); +__attribute__((weak, alias("__stop"))) void SPI2_handler(); +__attribute__((weak, alias("__stop"))) void USART1_handler(); +__attribute__((weak, alias("__stop"))) void USART2_handler(); +__attribute__((weak, alias("__stop"))) void USART_00B3_handler(); +__attribute__((weak, alias("__stop"))) void CEC_CAN_handler(); +__attribute__((weak, alias("__stop"))) void USB_handler(); + +// Dummy handler (for unused vectors) +__attribute__((weak, alias("__stop"))) void DUMMY_handler(); + +// Vector table for handlers +// This array will be placed in ".vectors" section defined in linker script. +__attribute__((section(".vectors"), used)) ptr_func_t __isr_vectors[] = { + RESET_handler, + NMI_handler, + HARDFAULT_handler, + MEMMANAGE_handler, + BUSFAULT_handler, + USAGEFAULT_handler, + DUMMY_handler, + DUMMY_handler, + DUMMY_handler, + DUMMY_handler, + SVCALL_handler, + DEBUGMONITOR_handler, + DUMMY_handler, + PENDSV_handler, + SYSTICK_handler, + WWDG_handler, + PVD_VDDIO2_handler, + RTC_handler, + FLASH_handler, + RCC_CRS_handler, + EXTI0_1_handler, + EXTI2_3_handler, + EXTI4_15_handler, + TSC_handler, + DMA_0064_handler, + DMA_DMA2_0068_handler, + DMA_DMA2_006C_handler, + ADC_COMP_handler, + TIM1_0074_handler, + TIM1_0078_handler, + TIM2_handler, + TIM3_handler, + TIM6_DAC_handler, + TIM7_handler, + TIM14_handler, + TIM15_handler, + TIM16_handler, + TIM17_handler, + I2C1_handler, + I2C2_handler, + SPI1_handler, + SPI2_handler, + USART1_handler, + USART2_handler, + USART_00B3_handler, + CEC_CAN_handler, + USB_handler, +}; diff --git a/app/platform/stm32f0-gcc/startup/stack.cpp b/app/platform/stm32f0-gcc/startup/stack.cpp new file mode 100644 index 0000000..d10595c --- /dev/null +++ b/app/platform/stm32f0-gcc/startup/stack.cpp @@ -0,0 +1,7 @@ +// stack definition code + +// top of stack +extern unsigned __stacktop; + +// initial stack pointer is first address of program +__attribute__((section(".stack"), used)) unsigned *__stack_init = &__stacktop; diff --git a/app/platform/stm32f0-gcc/startup/startup.cpp b/app/platform/stm32f0-gcc/startup/startup.cpp new file mode 100644 index 0000000..95276ae --- /dev/null +++ b/app/platform/stm32f0-gcc/startup/startup.cpp @@ -0,0 +1,96 @@ +// very simple startup code with definition of handlers for all cortex-m cores + +typedef void (*ptr_func_t)(); + +// main application +extern "C" int main(); + +// location of these variables is defined in linker script +extern unsigned __data_start; +extern unsigned __data_end; +extern unsigned __data_load; + +extern unsigned __bss_start; +extern unsigned __bss_end; + +extern unsigned __heap_start; + +extern ptr_func_t __preinit_array_start[]; +extern ptr_func_t __preinit_array_end[]; + +extern ptr_func_t __init_array_start[]; +extern ptr_func_t __init_array_end[]; + +extern ptr_func_t __fini_array_start[]; +extern ptr_func_t __fini_array_end[]; + + +/** Copy default data to DATA section + */ +void copy_data() { + unsigned *src = &__data_load; + unsigned *dst = &__data_start; + while (dst < &__data_end) { + *dst++ = *src++; + } +} + +/** Erase BSS section + */ +void zero_bss() { + unsigned *dst = &__bss_start; + while (dst < &__bss_end) { + *dst++ = 0; + } +} + +/** Fill heap memory + */ +void fill_heap(unsigned fill=0x45455246) { + unsigned *dst = &__heap_start; + unsigned *msp_reg; + __asm__("mrs %0, msp\n" : "=r" (msp_reg) ); + while (dst < msp_reg) { + *dst++ = fill; + } +} + +/** Call constructors for static objects + */ +void call_init_array() { + auto array = __preinit_array_start; + while (array < __preinit_array_end) { + (*array)(); + array++; + } + + array = __init_array_start; + while (array < __init_array_end) { + (*array)(); + array++; + } +} + +/** Call destructors for static objects + */ +void call_fini_array() { + auto array = __fini_array_start; + while (array < __fini_array_end) { + (*array)(); + array++; + } +} + +// reset handler +extern "C" void RESET_handler() { + copy_data(); + zero_bss(); + fill_heap(); + call_init_array(); + // run application + main(); + // call destructors for static instances + call_fini_array(); + // stop + while (true); +} diff --git a/app/stm32f0xx_conf.h b/app/stm32f0xx_conf.h new file mode 100644 index 0000000..adbf30b --- /dev/null +++ b/app/stm32f0xx_conf.h @@ -0,0 +1,84 @@ +/** + ****************************************************************************** + * @file Projects\Demonstration\stm32f0xx_conf.h + * @author MCD Application Team + * @version V1.0.0 + * @date 17-January-2014 + * @brief Library configuration file. + ****************************************************************************** + * @attention + * + * <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2> + * + * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.st.com/software_license_agreement_liberty_v2 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0XX_CONF_H +#define __STM32F0XX_CONF_H + + +/* Includes ------------------------------------------------------------------*/ +/* Comment the line below to disable peripheral header file inclusion */ +#include "stm32f0xx_adc.h" +//#include "stm32f0xx_can.h" +//#include "stm32f0xx_cec.h" +//#include "stm32f0xx_crc.h" +//#include "stm32f0xx_crs.h" +//#include "stm32f0xx_comp.h" +//#include "stm32f0xx_dac.h" +//#include "stm32f0xx_dbgmcu.h" +#include "stm32f0xx_dma.h" +//#include "stm32f0xx_exti.h" +//#include "stm32f0xx_flash.h" +#include "stm32f0xx_gpio.h" +#include "stm32f0xx_syscfg.h" +//#include "stm32f0xx_i2c.h" +//#include "stm32f0xx_iwdg.h" +#include "stm32f0xx_pwr.h" +#include "stm32f0xx_rcc.h" +#include "stm32f0xx_rtc.h" +#include "stm32f0xx_spi.h" +#include "stm32f0xx_tim.h" +//#include "stm32f0xx_usart.h" +//#include "stm32f0xx_wwdg.h" +#include "stm32f0xx_misc.h" /* High level functions for NVIC and SysTick (add-on to CMSIS functions) */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Uncomment the line below to expanse the "assert_param" macro in the + Standard Peripheral Library drivers code */ +/*#define USE_FULL_ASSERT 1*/ + +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT + +/** + * @brief The assert_param macro is used for function's parameters check. + * @param expr: If expr is false, it calls assert_failed function which reports + * the name of the source file and the source line number of the call + * that failed. If expr is true, it returns no value. + * @retval None + */ + #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) +/* Exported functions ------------------------------------------------------- */ + void assert_failed(uint8_t* file, uint32_t line); +#else + #define assert_param(expr) ((void)0) +#endif /* USE_FULL_ASSERT */ + +#endif /* __STM32F0XX_CONF_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/app/stm32f0xx_it.c b/app/stm32f0xx_it.c new file mode 100644 index 0000000..9327bed --- /dev/null +++ b/app/stm32f0xx_it.c @@ -0,0 +1,249 @@ +/** + ****************************************************************************** + * @file Projects\Demonstration\stm32f0xx_it.c + * @author MCD Application Team + * @version V1.0.0 + * @date 17-January-2014 + * @brief Main Interrupt Service Routines. + * This file provides template for all exceptions handler and + * peripherals interrupt service routine. + ****************************************************************************** + * @attention + * + * <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2> + * + * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.st.com/software_license_agreement_liberty_v2 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_it.h" +#include "stm32f0xx_conf.h" + +#include "ltimers.h" +#include "ltimers_config.h" + +#include "nixie_driver_config.h" +#include "nixie_driver_process.h" +#include "led_driver_process.h" +#include "led_driver_config.h" + +#include "tsl_types.h" +#include "tsl_user.h" +#include "tsl_time_stm32f0xx.h" + + +/** @addtogroup STM32F072B_DISCOVERY + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/******************************************************************************/ +/* Cortex-M0 Processor Exceptions Handlers */ +/******************************************************************************/ + +/** + * @brief This function handles NMI exception. + * @param None + * @retval None + */ +void NMI_Handler(void) +{ +} + +/** + * @brief This function handles Hard Fault exception. + * @param None + * @retval None + */ +void HardFault_Handler(void) +{ + /* Go to infinite loop when Hard Fault exception occurs */ + while (1) + { + } +} + +/** + * @brief This function handles SVCall exception. + * @param None + * @retval None + * @ Используется в файле portasm.s + */ +//void SVC_Handler(void) +//{ +//} + +/** + * @brief This function handles PendSVC exception. + * @param None + * @retval None + * @ Используется в файле portasm.s + */ +//void PendSV_Handler(void) +//{ +//} + +/** + * @brief This function handles SysTick Handler. + * @param None + * @retval None + */ +//void SysTick_Handler(void) +//{ +// TimingDelay_Decrement(); +// TSL_tim_ProcessIT(); +//} + +/******************************************************************************/ +/* STM32F0xx Peripherals Interrupt Handlers */ +/* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ +/* available peripheral interrupt handler's name please refer to the startup */ +/* file (startup_stm32f0xx.s). */ +/******************************************************************************/ + +// ---------------------------------------------------------------------------- +// Обработчик прерывания таймера общего назначения для тиков в 1 мс +// ---------------------------------------------------------------------------- +void LTIMER_IRQHandler ( void ) +{ + if ( TIM_GetITStatus ( LTIMER_TIMx, TIM_IT_Update ) != RESET ) + { + TIM_ClearITPendingBit ( LTIMER_TIMx, TIM_IT_Update ); + + ProcessLTimers (); + } +} + +void TIM17_handler(void) { LTIMER_IRQHandler(); } + + +// ---------------------------------------------------------------------------- +// Обработчик прерывания таймера для работы NixieDriver +// Это прерывание имеет самый высокий приоритет, чтобы обеспечить стабильную +// частоту динамической индикации ламп Nixie +// ---------------------------------------------------------------------------- +void NIX_DRIVER_TIM_IRQHandler ( void ) +{ + if ( TIM_GetITStatus ( NIX_DRIVER_TIMx, TIM_IT_Update ) != RESET ) + { + TIM_ClearITPendingBit ( NIX_DRIVER_TIMx, TIM_IT_Update ); + + ProcessNixieDriverFromISR (); + } +} + +void TIM16_handler(void) { NIX_DRIVER_TIM_IRQHandler(); } + + +// ---------------------------------------------------------------------------- +// Обработчик прерывания таймера для работы LED_Driver +// ---------------------------------------------------------------------------- +void LED_TIM_IRQHandler ( void ) +{ + if ( TIM_GetITStatus ( LED_TIMx, TIM_IT_Update ) != RESET ) + { + TIM_ClearITPendingBit ( LED_TIMx, TIM_IT_Update ); + + LEDDriverProcessFromISR (); + } +} + +void TIM3_handler(void) { LED_TIM_IRQHandler(); } + + +// ---------------------------------------------------------------------------- +// - поставить этому прерыванию наивысший приоритет, чтобы передавать 2 байта +// подряд гарантированно без промежутка времени (или не так важно? может ли +// между двумя байтами задержка повлиять на вывод данных на лампы?) +// ---------------------------------------------------------------------------- + +void NIX_SPIx_IRQHandler ( void ) +{ + /* SPI in Master Receiver mode--------------------------------------- */ + if ( SPI_I2S_GetITStatus ( NIX_SPIx, SPI_I2S_IT_TXE ) == SET ) + { + // Обязательно надо считать, чтобы сбросить флаг + SPI_I2S_ReceiveData16 ( NIX_SPIx ); + SPI_I2S_ITConfig ( NIX_SPIx, SPI_I2S_IT_TXE, DISABLE ); + //NixieDriverCheckDPPins(); + NIX_DRIVER_SET_ST_PIN; + } +} + +void SPI1_handler(void) { NIX_SPIx_IRQHandler(); } + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +#ifdef LED_DRIVER +void LED_SPIx_IRQHandler ( void ) +{ + /* SPI in Master Receiver mode--------------------------------------- */ + if ( SPI_I2S_GetITStatus ( LED_SPIx, SPI_I2S_IT_RXNE ) == SET ) + { + //empty_data = SPI_I2S_ReceiveData16 ( LED_SPIx ); + // Обязательно надо считать, чтобы сбросить флаг + SPI_I2S_ReceiveData16 ( LED_SPIx ); + LED_ST_PIN_SET; + } +} + +void SPI2_handler(void) { LED_SPIx_IRQHandler(); } +#endif + + +// ---------------------------------------------------------------------------- +/** + * @brief This function handles Touch Sensing Controller Handler. + * @param None + * @retval None + */ +// ---------------------------------------------------------------------------- +extern __IO uint32_t Gv_EOA; + +void TSC_IRQHandler ( void ) +{ +#if TSLPRM_TSC_IODEF > 0 // Default = Input Floating + /* Set IO default in Output PP Low to discharge all capacitors */ + TSC->CR &= (uint32_t)(~(1 << 4)); +#endif + TSC->ICR |= 0x03; /* Clear EOAF and MCEF flags */ + Gv_EOA = 1; /* To inform the main loop routine of the End Of Acquisition */ +} + +void TSC_handler(void) { TSC_IRQHandler(); } + + +// ---------------------------------------------------------------------------- +// +// ---------------------------------------------------------------------------- +void TS_TIM_IRQHandler ( void ) +{ + TIM_ClearITPendingBit ( TS_TIMx, TIM_IT_Update ); + TSL_tim_ProcessIT(); +} + +void TIM15_handler(void) { TS_TIM_IRQHandler(); } + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/app/stm32f0xx_it.h b/app/stm32f0xx_it.h new file mode 100644 index 0000000..a3dfdb3 --- /dev/null +++ b/app/stm32f0xx_it.h @@ -0,0 +1,51 @@ +/** + ****************************************************************************** + * @file Projects\Demonstration\stm32f0xx_it.h + * @author MCD Application Team + * @version V1.0.0 + * @date 17-January-2014 + * @brief This file contains the headers of the interrupt handlers. + ****************************************************************************** + * @attention + * + * <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2> + * + * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.st.com/software_license_agreement_liberty_v2 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0XX_IT_H +#define __STM32F0XX_IT_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions ------------------------------------------------------- */ + +void NMI_Handler(void); +void HardFault_Handler(void); + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0XX_IT_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/app/system_stm32f0xx.c b/app/system_stm32f0xx.c new file mode 100644 index 0000000..e9db4f2 --- /dev/null +++ b/app/system_stm32f0xx.c @@ -0,0 +1,402 @@ +/** + ****************************************************************************** + * @file system_stm32f0xx.c + * @author MCD Application Team + * @version V1.0.0 + * @date 17-January-2014 + * @brief CMSIS Cortex-M0 Device Peripheral Access Layer System Source File. + * This file contains the system clock configuration for STM32F0xx devices, + * and is customized for use with STM32F072B-DISCOVERY Kit. + * + * + * The STM32F072x is configured to run at 48 MHz, following the five + * configuration below: + * - SOURCE_HSI48 (default) : HSI48 (48MHz) used as system clock source. + * - PLL_SOURCE_HSI : HSI (~8MHz) used to clock the PLL, and + * the PLL is used as system clock source. + * - PLL_SOURCE_HSI48 : HSI48 (48MHz) used to clock the PLL, and + * the PLL is used as system clock source. + * - PLL_SOURCE_HSE : HSE (8MHz) used to clock the PLL, and + * the PLL is used as system clock source. + * - PLL_SOURCE_HSE_BYPASS : HSE bypassed with an external clock + * (8MHz, coming from ST-Link) used to clock + * the PLL, and the PLL is used as system + * clock source. + * + * + * 1. This file provides two functions and one global variable to be called from + * user application: + * - SystemInit(): Setups the system clock (System clock source, PLL Multiplier + * and Divider factors, AHB/APBx prescalers and Flash settings), + * depending on the configuration made in the clock xls tool. + * This function is called at startup just after reset and + * before branch to main program. This call is made inside + * the "startup_stm32f0xx.s" file. + * + * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used + * by the user application to setup the SysTick + * timer or configure other parameters. + * + * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must + * be called whenever the core clock is changed + * during program execution. + * + * 2. After each device reset the HSI (8 MHz Range) is used as system clock source. + * Then SystemInit() function is called, in "startup_stm32f0xx.s" file, to + * configure the system clock before to branch to main program. + * + * 3. If the system clock source selected by user fails to startup, the SystemInit() + * function will do nothing and HSI still used as system clock source. User can + * add some code to deal with this issue inside the SetSysClock() function. + * + * 4. The default value of HSE crystal is set to 8MHz, refer to "HSE_VALUE" define + * in "stm32f0xx.h" file. When HSE is used as system clock source, directly or + * through PLL, and you are using different crystal you have to adapt the HSE + * value to your own configuration. + * + ****************************************************************************** + * @attention + * + * <h2><center>© COPYRIGHT 2014 STMicroelectronics</center></h2> + * + * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); + * You may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.st.com/software_license_agreement_liberty_v2 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32f0xx_system + * @{ + */ + +/** @addtogroup STM32F0xx_System_Private_Includes + * @{ + */ + +#include "stm32f0xx.h" + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_TypesDefinitions + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_Defines + * @{ + */ +/** + * @} + */ + +/*!< Uncomment the following line if you need to relocate your vector Table in + Internal SRAM. */ +/* #define VECT_TAB_SRAM */ +#define VECT_TAB_OFFSET 0x0 /*!< Vector Table base offset field. + This value must be a multiple of 0x200. */ + +/* Select the PLL clock source */ + +//#define SOURCE_HSI48 +//#define PLL_SOURCE_HSI48 /* HSI48 (48MHz) used to clock USB, system clock and the PLL*/ +//#define PLL_SOURCE_HSI /* HSI (~8MHz) used to clock the PLL, and the PLL is used as system clock source*/ +#define PLL_SOURCE_HSE /* HSE (8MHz) used to clock the PLL, and the PLL is used as system clock source */ +//#define PLL_SOURCE_HSE_BYPASS /* HSE bypassed with an external clock (8MHz, coming from ST-Link) used to clock +// the PLL, and the PLL is used as system clock source */ + + +/** @addtogroup STM32F0xx_System_Private_Macros + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_Variables + * @{ + */ +uint32_t SystemCoreClock = 48000000; +__I uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_FunctionPrototypes + * @{ + */ + +static void SetSysClock(void); + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_Functions + * @{ + */ + +/** + * @brief Setup the microcontroller system. + * Initialize the Embedded Flash Interface, the PLL and update the + * SystemCoreClock variable. + * @param None + * @retval None + */ +void SystemInit (void) +{ + /* Set HSION bit */ + RCC->CR |= (uint32_t)0x00000001; + + /* Reset SW[1:0], HPRE[3:0], PPRE[2:0], ADCPRE and MCOSEL[3:0] bits MCOPRE[2:0] */ + RCC->CFGR &= (uint32_t)0x80FFB80C; + + /* Reset HSEON, CSSON and PLLON bits */ + RCC->CR &= (uint32_t)0xFEF6FFFF; + + /* Reset HSEBYP bit */ + RCC->CR &= (uint32_t)0xFFFBFFFF; + + /* Reset PLLSRC, PLLXTPRE and PLLMUL[3:0] bits */ + RCC->CFGR &= (uint32_t)0xFFC07FFF; + + /* Reset PREDIV1[3:0] bits */ + RCC->CFGR2 &= (uint32_t)0xFFFFFFF0; + + /* Reset USARTSW[1:0], I2CSW, CECSW and ADCSW bits */ + RCC->CFGR3 &= (uint32_t)0xFFFFFEAC; + + /* Reset HSI14 & HSI48 bit */ + RCC->CR2 &= (uint32_t)0xFFFEFFFE; + + /* Disable all interrupts */ + RCC->CIR = 0x00000000; + + /* Configure the System clock frequency, AHB/APBx prescalers and Flash settings */ + SetSysClock(); +} + +/** + * @brief Update SystemCoreClock according to Clock Register Values + * The SystemCoreClock variable contains the core clock (HCLK), it can + * be used by the user application to setup the SysTick timer or configure + * other parameters. + * + * @note Each time the core clock (HCLK) changes, this function must be called + * to update SystemCoreClock variable value. Otherwise, any configuration + * based on this variable will be incorrect. + * + * @note - The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * + * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) + * + * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) + * + * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) + * or HSI_VALUE(*) multiplied/divided by the PLL factors. + * @note - If SYSCLK source is HSI48, function returns constant HSI48_VALUE(***) + * + * (*) HSI_VALUE is a constant defined in stm32f0xx.h file (default value + * 8 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * (**) HSE_VALUE is a constant defined in stm32f0xx.h file (default value + * 8 MHz), user has to ensure that HSE_VALUE is same as the real + * frequency of the crystal used. Otherwise, this function may + * have wrong result. + * @note (***) HSI48_VALUE is a constant defined in stm32f0xx.h file (default value + * 48 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * - The result of this function could be not correct when using fractional + * value for HSE crystal. + * @param None + * @retval None + */ +void SystemCoreClockUpdate (void) +{ + uint32_t tmp = 0, pllmull = 0, pllsource = 0, prediv1factor = 0; + + /* Get SYSCLK source -------------------------------------------------------*/ + tmp = RCC->CFGR & RCC_CFGR_SWS; + + switch (tmp) + { + case 0x00: /* HSI used as system clock */ + SystemCoreClock = HSI_VALUE; + break; + case 0x04: /* HSE used as system clock */ + SystemCoreClock = HSE_VALUE; + break; + case 0x08: /* PLL used as system clock */ + /* Get PLL clock source and multiplication factor ----------------------*/ + pllmull = RCC->CFGR & RCC_CFGR_PLLMULL; + pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; + pllmull = ( pllmull >> 18) + 2; + + if (pllsource == 0x00) + { + /* HSI oscillator clock divided by 2 selected as PLL clock entry */ + SystemCoreClock = (HSI_VALUE >> 1) * pllmull; + } + else + { + prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1; + /* HSE oscillator clock selected as PREDIV1 clock entry */ + SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull; + } + break; + case 0x0C: /* HSI48 used as system clock */ + SystemCoreClock = HSI48_VALUE; + break; + default: /* HSI used as system clock */ + SystemCoreClock = HSI_VALUE; + break; + + } + /* Compute HCLK clock frequency ----------------*/ + /* Get HCLK prescaler */ + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; + /* HCLK clock frequency */ + SystemCoreClock >>= tmp; +} + +/** + * @brief Configures the System clock frequency, AHB/APBx prescalers and Flash + * settings. + * @note This function should be called only once the RCC clock configuration + * is reset to the default reset state (done in SystemInit() function). + * @param None + * @retval None + */ +static void SetSysClock(void) +{ + __IO uint32_t StartUpCounter = 0, HSEStatus = 0; + + /* SYSCLK, HCLK, PCLK configuration ----------------------------------------*/ + /* At this stage the HSI is already enabled */ + + /* Enable Prefetch Buffer and set Flash Latency */ + FLASH->ACR = FLASH_ACR_PRFTBE | FLASH_ACR_LATENCY; + + /* HCLK = SYSCLK */ + RCC->CFGR |= (uint32_t)RCC_CFGR_HPRE_DIV1; + + /* PCLK = HCLK */ + RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE_DIV1; + +#ifndef SOURCE_HSI48 + + #if defined (PLL_SOURCE_HSI) + /* PLL configuration = HSI * 6 = 48 MHz */ + RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); + RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSI_PREDIV | RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLMULL6); + #elif defined (PLL_SOURCE_HSI48) + /* Enable HSI48 */ + RCC->CR2 |= RCC_CR2_HSI48ON; + /* PLL configuration = HSI48 * 1 = 48 MHz */ + RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); + RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_HSI48_PREDIV | RCC_CFGR_PLLXTPRE_PREDIV1_Div2); + + #else + /* Enable HSE */ + RCC->CR |= ((uint32_t)RCC_CR_HSEON); + #if defined (PLL_SOURCE_HSE_BYPASS) + /* HSE oscillator bypassed with external clock */ + RCC->CR |= (uint32_t)(RCC_CR_HSEBYP); + #endif + /* Wait till HSE is ready and if Time out is reached exit */ + do + { + HSEStatus = RCC->CR & RCC_CR_HSERDY; + StartUpCounter++; + } while((HSEStatus == 0) && (StartUpCounter != HSE_STARTUP_TIMEOUT)); + + if ((RCC->CR & RCC_CR_HSERDY) != RESET) + { + HSEStatus = (uint32_t)0x01; + } + else + { + HSEStatus = (uint32_t)0x00; + } + + if (HSEStatus == (uint32_t)0x01) + { + /* PLL configuration = HSE * 6 = 48 MHz */ + RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_PLLSRC | RCC_CFGR_PLLXTPRE | RCC_CFGR_PLLMULL)); + RCC->CFGR |= (uint32_t)(RCC_CFGR_PLLSRC_PREDIV1 | RCC_CFGR_PLLXTPRE_PREDIV1 | RCC_CFGR_PLLMULL6); + + } + else + { /* If HSE fails to start-up, the application will have wrong clock + configuration. User can add here some code to deal with this error */ + } + + + + #endif /* PLL_SOURCE_HSI */ + /* Enable PLL */ + RCC->CR |= RCC_CR_PLLON; + + /* Wait till PLL is ready */ + while((RCC->CR & RCC_CR_PLLRDY) == 0) + { + } + + /* Select PLL as system clock source */ + RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); + RCC->CFGR |= (uint32_t)RCC_CFGR_SW_PLL; + + /* Wait till PLL is used as system clock source */ + while ((RCC->CFGR & (uint32_t)RCC_CFGR_SWS) != (uint32_t)RCC_CFGR_SWS_PLL) + { + } +#else + /* Enable HSI48 */ + RCC->CR2 |= RCC_CR2_HSI48ON; + /* Wait till HSI48RDY is set */ + while((RCC->CR2 & RCC_CR2_HSI48RDY) == 0) + { } + /* Select HSI48 as system clock source */ + RCC->CFGR &= (uint32_t)((uint32_t)~(RCC_CFGR_SW)); + RCC->CFGR |= (uint32_t)RCC_CFGR_SW_HSI48; + +#endif + +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ |