init работает

This commit is contained in:
2026-04-12 10:50:01 +03:00
commit 76bbd4a539
1010 changed files with 600193 additions and 0 deletions

View File

@@ -0,0 +1,61 @@
#include "clock_manager.h"
#include "segment.h"
#include "rtc.h"
static uint8_t dutyValue = 5;
static time_t currentTime;
RTC_TimeTypeDef rtc_time;
// Яркость в RTC Backup Register (используем BKP_DR1)
static void SaveDuty(void) {
HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR1, dutyValue);
}
static void LoadDuty(void) {
uint32_t val = HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR1);
dutyValue = (val <= 10 && val > 0) ? (uint8_t)val : 5;
}
void ClockManager_Init(void) {
LoadDuty();
Segment_SetBrightness(dutyValue * 10);
// Если RTC не инициализирован - сброс времени
if (HAL_RTC_GetTime(&hrtc, &rtc_time, RTC_FORMAT_BIN) != HAL_OK) {
ClockManager_ResetTime();
}
}
time_t ClockManager_GetTime(void) {
HAL_RTC_GetTime(&hrtc, &rtc_time, RTC_FORMAT_BIN);
currentTime.hour = rtc_time.Hours;
currentTime.min = rtc_time.Minutes;
currentTime.sec = rtc_time.Seconds;
return currentTime;
}
void ClockManager_SetTime(uint8_t hour, uint8_t min, uint8_t sec) {
RTC_TimeTypeDef rtc_time;
rtc_time.Hours = hour;
rtc_time.Minutes = min;
rtc_time.Seconds = sec;
// rtc_time.TimeFormat = RTC_HOURFORMAT_24;
// rtc_time.DayLightSaving = RTC_DAYLIGHTSAVING_NONE;
// rtc_time.StoreOperation = RTC_STOREOPERATION_RESET;
HAL_RTC_SetTime(&hrtc, &rtc_time, RTC_FORMAT_BIN);
}
uint8_t ClockManager_GetDuty(void) {
return dutyValue;
}
void ClockManager_SetDuty(uint8_t value) {
if (value > 10) value = 10;
dutyValue = value;
Segment_SetBrightness(dutyValue * 10);
SaveDuty();
}
void ClockManager_ResetTime(void) {
ClockManager_SetTime(0, 0, 0);
}

View File

@@ -0,0 +1,26 @@
#ifndef CLOCK_MANAGER_H
#define CLOCK_MANAGER_H
#include <stdint.h>
#include <stdbool.h>
#include "main.h" // где определен time_t
// Инициализация
void ClockManager_Init(void);
// Получить текущее время из RTC
time_t ClockManager_GetTime(void);
// Установить время в RTC
void ClockManager_SetTime(uint8_t hour, uint8_t min, uint8_t sec);
// Получить яркость (0-10)
uint8_t ClockManager_GetDuty(void);
// Установить яркость (0-10) и сохранить
void ClockManager_SetDuty(uint8_t value);
// Сброс времени на 00:00:00
void ClockManager_ResetTime(void);
#endif

426
Core/Clock/menu.c Normal file
View File

@@ -0,0 +1,426 @@
#include "menu.h"
#include "segment.h"
#include "clock_manager.h"
// Время удержания кнопки (мс), после которого нажатие считается "длинным"
// Используется для входа в меню из режима часов
#define LONG_PRESS_MS 500
// Задержка перед началом автоповтора (мс)
// При удержании кнопки первые 500 мс ничего не происходит
#define REPEAT_DELAY_MS 500
// Интервал между автоповторами (мс)
// После начала повтора каждые 100 мс кнопка срабатывает заново
#define REPEAT_INTERVAL_MS 100
// Интервал мигания редактируемого разряда (мс)
// Моргает каждые 500 мс (0.5 сек вкл / 0.5 сек выкл)
#define BLINK_INTERVAL_MS 500
// Задержка антидребезга (мс)
// Изменение состояния кнопки фиксируется только если оно стабильно в течение 30 мс
#define DEBOUNCE_MS 30
typedef enum {
MAIN_MENU_SET_TIME,
MAIN_MENU_SET_DUTY,
MAIN_MENU_RESET,
MAIN_MENU_COUNT
} MainMenuItem;
typedef struct {
// Состояние
SystemState state;
MainMenuItem selectedMenuItem;
// Для SET_TIME
time_t originalTime;
time_t editTime;
uint8_t editStep;
bool blinkState;
uint32_t lastBlinkTime;
// Для SET_DUTY
uint8_t originalDuty;
uint8_t editDuty;
// Для кнопок
bool buttonPrevState[BUTTON_COUNT];
uint32_t buttonPressTime[BUTTON_COUNT];
bool longPressSent[BUTTON_COUNT];
bool repeatActive[BUTTON_COUNT];
uint32_t lastRepeatTime[BUTTON_COUNT];
uint32_t lastDebounceTime[BUTTON_COUNT];
bool buttonStableState[BUTTON_COUNT];
} MenuContext;
MenuContext menu;
// ==================== Отображение ====================
static void FormatTime(char* buf, const time_t* t) {
buf[0] = '0' + t->hour / 10;
buf[1] = '0' + t->hour % 10;
buf[2] = '0' + t->min / 10;
buf[3] = '0' + t->min % 10;
buf[4] = '0' + t->sec / 10;
buf[5] = '0' + t->sec % 10;
}
static void UpdateDisplay(void) {
switch (menu.state) {
case STATE_CLOCK: {
time_t now = ClockManager_GetTime();
char buf[7];
FormatTime(buf, &now);
Segment_SetString(buf);
break;
}
case STATE_MAIN_MENU: {
switch (menu.selectedMenuItem) {
case MAIN_MENU_SET_TIME:
Segment_SetString("SET T ");
break;
case MAIN_MENU_SET_DUTY:
Segment_SetString("SET D ");
break;
case MAIN_MENU_RESET:
Segment_SetString("RESET ");
break;
default:
break;
}
break;
}
case STATE_SET_TIME: {
char buf[7];
FormatTime(buf, &menu.editTime);
if (menu.blinkState && menu.editStep < 6) {
buf[menu.editStep] = ' ';
}
Segment_SetString(buf);
break;
}
case STATE_SET_DUTY: {
char buf[6] = {'D', 'U', 'T', 'Y', ' ' , ' '};
if (menu.editDuty == 10) {
buf[4] = '1';
buf[5] = '0';
} else {
buf[5] = '0' + menu.editDuty;
}
Segment_SetString(buf);
break;
}
case STATE_RESET_CONFIRM:
Segment_SetString("RESET ");
break;
}
}
// ==================== Логика SET_TIME ====================
static void IncreaseTimeDigit(void) {
uint8_t tens, units;
switch (menu.editStep) {
case 0: // десятки часов (0-2)
tens = menu.editTime.hour / 10;
units = menu.editTime.hour % 10;
tens++;
if (tens > 2) tens = 0;
menu.editTime.hour = tens * 10 + units;
break;
case 1: // единицы часов (0-9, но с учетом десятков)
tens = menu.editTime.hour / 10;
units = menu.editTime.hour % 10;
units++;
if (tens == 2 && units > 3) units = 0; // 23 → 20
if (units > 9) units = 0;
menu.editTime.hour = tens * 10 + units;
break;
case 2: // десятки минут (0-5)
tens = menu.editTime.min / 10;
units = menu.editTime.min % 10;
tens = (tens + 1) % 6;
menu.editTime.min = tens * 10 + units;
break;
case 3: // единицы минут (0-9)
units = (menu.editTime.min % 10 + 1) % 10;
menu.editTime.min = (menu.editTime.min / 10) * 10 + units;
break;
case 4: // десятки секунд (0-5)
tens = menu.editTime.sec / 10;
units = menu.editTime.sec % 10;
tens = (tens + 1) % 6;
menu.editTime.sec = tens * 10 + units;
break;
case 5: // единицы секунд (0-9)
units = (menu.editTime.sec % 10 + 1) % 10;
menu.editTime.sec = (menu.editTime.sec / 10) * 10 + units;
break;
}
UpdateDisplay();
}
static void DecreaseTimeDigit(void) {
uint8_t tens, units;
switch (menu.editStep) {
case 0: // десятки часов (0-2)
tens = menu.editTime.hour / 10;
units = menu.editTime.hour % 10;
if (tens == 0) tens = 2;
else tens--;
menu.editTime.hour = tens * 10 + units;
break;
case 1: // единицы часов
tens = menu.editTime.hour / 10;
units = menu.editTime.hour % 10;
if (units == 0) {
units = (tens == 2) ? 3 : 9;
} else {
units--;
}
menu.editTime.hour = tens * 10 + units;
break;
case 2: // десятки минут (0-5)
tens = menu.editTime.min / 10;
units = menu.editTime.min % 10;
tens = (tens == 0) ? 5 : tens - 1;
menu.editTime.min = tens * 10 + units;
break;
case 3: // единицы минут
units = (menu.editTime.min % 10 == 0) ? 9 : (menu.editTime.min % 10) - 1;
menu.editTime.min = (menu.editTime.min / 10) * 10 + units;
break;
case 4: // десятки секунд (0-5)
tens = menu.editTime.sec / 10;
units = menu.editTime.sec % 10;
tens = (tens == 0) ? 5 : tens - 1;
menu.editTime.sec = tens * 10 + units;
break;
case 5: // единицы секунд
units = (menu.editTime.sec % 10 == 0) ? 9 : (menu.editTime.sec % 10) - 1;
menu.editTime.sec = (menu.editTime.sec / 10) * 10 + units;
break;
}
UpdateDisplay();
}
// ==================== Обработка кнопок ====================
static void ProcessButton(Button_Type btn, bool longPress) {
// Длинное нажатие SELECT в режиме часов - вход в меню
if (menu.state == STATE_CLOCK && longPress && btn == BUTTON_SELECT) {
menu.state = STATE_MAIN_MENU;
menu.selectedMenuItem = MAIN_MENU_SET_TIME;
UpdateDisplay();
return;
}
switch (menu.state) {
case STATE_MAIN_MENU:
if (btn == BUTTON_UP) {
menu.selectedMenuItem++;
if (menu.selectedMenuItem >= MAIN_MENU_COUNT) {
menu.selectedMenuItem = 0;
}
UpdateDisplay();
}
else if (btn == BUTTON_DOWN) {
if (menu.selectedMenuItem == 0) {
menu.selectedMenuItem = MAIN_MENU_COUNT - 1;
} else {
menu.selectedMenuItem--;
}
UpdateDisplay();
}
else if (btn == BUTTON_SELECT && !longPress) {
switch (menu.selectedMenuItem) {
case MAIN_MENU_SET_TIME:
menu.state = STATE_SET_TIME;
menu.originalTime = ClockManager_GetTime();
menu.editTime = menu.originalTime;
menu.editStep = 0;
menu.blinkState = true;
menu.lastBlinkTime = HAL_GetTick();
break;
case MAIN_MENU_SET_DUTY:
menu.state = STATE_SET_DUTY;
menu.originalDuty = ClockManager_GetDuty();
menu.editDuty = menu.originalDuty;
break;
case MAIN_MENU_RESET:
menu.state = STATE_RESET_CONFIRM;
break;
default: break;
}
UpdateDisplay();
}
else if (btn == BUTTON_BACK) {
menu.state = STATE_CLOCK;
UpdateDisplay();
}
break;
case STATE_SET_TIME:
if (btn == BUTTON_UP) {
IncreaseTimeDigit();
}
else if (btn == BUTTON_DOWN) {
DecreaseTimeDigit();
}
else if (btn == BUTTON_SELECT) {
menu.editStep++;
if (menu.editStep >= 6) {
ClockManager_SetTime(menu.editTime.hour, menu.editTime.min, menu.editTime.sec);
menu.state = STATE_CLOCK;
}
UpdateDisplay();
}
else if (btn == BUTTON_BACK) {
menu.state = STATE_CLOCK;
UpdateDisplay();
}
break;
case STATE_SET_DUTY:
if (btn == BUTTON_UP && menu.editDuty < 10) {
menu.editDuty++;
Segment_SetBrightness(menu.editDuty * 10);
UpdateDisplay();
}
else if (btn == BUTTON_DOWN && menu.editDuty > 0) {
menu.editDuty--;
Segment_SetBrightness(menu.editDuty * 10);
UpdateDisplay();
}
else if (btn == BUTTON_SELECT) {
ClockManager_SetDuty(menu.editDuty);
menu.state = STATE_CLOCK;
UpdateDisplay();
}
else if (btn == BUTTON_BACK) {
menu.state = STATE_CLOCK;
Segment_SetBrightness(menu.originalDuty * 10);
UpdateDisplay();
}
break;
case STATE_RESET_CONFIRM:
if (btn == BUTTON_SELECT) {
ClockManager_ResetTime();
ClockManager_SetDuty(8);
menu.state = STATE_CLOCK;
UpdateDisplay();
}
else if (btn == BUTTON_BACK) {
menu.state = STATE_CLOCK;
UpdateDisplay();
}
break;
default:
break;
}
}
// ==================== Публичные функции ====================
void Menu_Init(void) {
menu.state = STATE_CLOCK;
menu.selectedMenuItem = MAIN_MENU_SET_TIME;
menu.editStep = 0;
menu.blinkState = false;
menu.lastBlinkTime = 0;
for (int i = 0; i < BUTTON_COUNT; i++) {
menu.buttonPrevState[i] = false;
menu.buttonPressTime[i] = 0;
menu.longPressSent[i] = false;
menu.repeatActive[i] = false;
menu.lastDebounceTime[i] = 0;
menu.buttonStableState[i] = false;
}
}
void Menu_Process(void) {
uint32_t tick = HAL_GetTick();
if (menu.state == STATE_SET_TIME) {
if (tick - menu.lastBlinkTime >= BLINK_INTERVAL_MS) {
menu.lastBlinkTime = tick;
menu.blinkState = !menu.blinkState;
UpdateDisplay();
}
}
for (int i = 0; i < BUTTON_COUNT; i++) {
bool rawPressed = ReadButton(i);
bool pressed;
// Антидребезг
if (rawPressed != menu.buttonStableState[i]) {
menu.lastDebounceTime[i] = tick;
menu.buttonStableState[i] = rawPressed;
}
if ((tick - menu.lastDebounceTime[i]) >= DEBOUNCE_MS) {
pressed = menu.buttonStableState[i];
} else {
pressed = menu.buttonPrevState[i]; // старое значение пока не стабилизировалось
}
bool wasPressed = menu.buttonPrevState[i];
if (pressed && !wasPressed) {
menu.buttonPressTime[i] = tick;
menu.longPressSent[i] = false;
menu.repeatActive[i] = false;
}
else if (pressed && wasPressed) {
if (!menu.longPressSent[i] && (tick - menu.buttonPressTime[i] >= LONG_PRESS_MS)) {
menu.longPressSent[i] = true;
ProcessButton((Button_Type)i, true);
}
else if (menu.longPressSent[i] && !menu.repeatActive[i] &&
(tick - menu.buttonPressTime[i] >= REPEAT_DELAY_MS)) {
menu.repeatActive[i] = true;
menu.lastRepeatTime[i] = tick;
ProcessButton((Button_Type)i, true);
}
else if (menu.repeatActive[i] && (tick - menu.lastRepeatTime[i] >= REPEAT_INTERVAL_MS)) {
menu.lastRepeatTime[i] = tick;
ProcessButton((Button_Type)i, true);
}
}
else if (!pressed && wasPressed) {
if (!menu.longPressSent[i]) {
ProcessButton((Button_Type)i, false);
}
menu.repeatActive[i] = false;
}
menu.buttonPrevState[i] = pressed;
}
static uint32_t lastClockUpdate = 0;
if (menu.state == STATE_CLOCK && (tick - lastClockUpdate >= 200)) {
lastClockUpdate = tick;
UpdateDisplay();
}
}
SystemState Menu_GetState(void) {
return menu.state;
}

30
Core/Clock/menu.h Normal file
View File

@@ -0,0 +1,30 @@
#ifndef MENU_H
#define MENU_H
#include <stdint.h>
#include <stdbool.h>
#include "main.h"
typedef enum {
BUTTON_UP,
BUTTON_DOWN,
BUTTON_SELECT,
BUTTON_BACK,
BUTTON_COUNT
} Button_Type;
typedef enum {
STATE_CLOCK, // режим часов
STATE_MAIN_MENU, // главное меню (выбор пункта)
STATE_SET_TIME, // настройка времени
STATE_SET_DUTY, // настройка яркости
STATE_RESET_CONFIRM // подтверждение сброса
} SystemState;
// Чтение кнопки (реализуется в main.c или hal)
int ReadButton(int btn);
void Menu_Init(void);
void Menu_Process(void);
#endif

222
Core/Clock/segment.c Normal file
View File

@@ -0,0 +1,222 @@
#include "segment.h"
#include "main.h"
// ==================== Конфигурация ====================
#define DIGITS_COUNT 6 // Количество разрядов
#define PROCESS_INTERVAL_US 10 // Интервал вызова Segment_Process в микросекундах
volatile uint32_t REFRESH_RATE = 80; // Частота обновления всех цифр в Гц (можно менять)
volatile uint8_t GLOBAL_BRIGHTNESS = 100; // Глобальная яркость в процентах (0-100)
// Маска переназначения: новый_бит = старый_бит
// Так как перепутаны бит5 (F) и бит6 (G), меняем их местами
#define SWAP_BIT5_BIT6(x) (((x) & 0x9F) | (((x) & 0x20) << 1) | (((x) & 0x40) >> 1))
// Макросы для быстрой работы с пинами (вместо HAL_GPIO_WritePin)
#define SET_SEGMENT_A(val) SEGMENT_A_GPIO_Port->BSRR = (SEGMENT_A_Pin << 16) | ((val) ? 0 : SEGMENT_A_Pin)
#define SET_SEGMENT_B(val) SEGMENT_B_GPIO_Port->BSRR = (SEGMENT_B_Pin << 16) | ((val) ? 0 : SEGMENT_B_Pin)
#define SET_SEGMENT_C(val) SEGMENT_C_GPIO_Port->BSRR = (SEGMENT_C_Pin << 16) | ((val) ? 0 : SEGMENT_C_Pin)
#define SET_SEGMENT_D(val) SEGMENT_D_GPIO_Port->BSRR = (SEGMENT_D_Pin << 16) | ((val) ? 0 : SEGMENT_D_Pin)
#define SET_SEGMENT_E(val) SEGMENT_E_GPIO_Port->BSRR = (SEGMENT_E_Pin << 16) | ((val) ? 0 : SEGMENT_E_Pin)
#define SET_SEGMENT_F(val) SEGMENT_F_GPIO_Port->BSRR = (SEGMENT_F_Pin << 16) | ((val) ? 0 : SEGMENT_F_Pin)
#define SET_SEGMENT_G(val) SEGMENT_G_GPIO_Port->BSRR = (SEGMENT_G_Pin << 16) | ((val) ? 0 : SEGMENT_G_Pin)
// ==================== Таблица символов ====================
// Для общего анода: 0 - сегмент горит, 1 - сегмент не горит
// Биты: A B C D E F G
typedef struct {
char c;
uint8_t mask;
} CharMap;
static const CharMap charTable[] = {
// ==================== Цифры ====================
{'0', 0xC0},
{'1', 0xF9},
{'2', 0xA4},
{'3', 0xB0},
{'4', 0x99},
{'5', 0x92},
{'6', 0x82},
{'7', 0xF8},
{'8', 0x80},
{'9', 0x90},
// ==================== Буквы ====================
{'A', 0x88}, {'a', 0x88},
{'B', 0x83}, {'b', 0x83},
{'C', 0xC6}, {'c', 0xC6},
{'D', 0xA1}, {'d', 0xA1},
{'E', 0x86}, {'e', 0x86},
{'F', 0x8E}, {'f', 0x8E},
{'G', 0xC2}, {'g', 0xC2},
{'H', 0x89}, {'h', 0x89},
{'I', 0xF9}, {'i', 0xF9},
{'J', 0xF1}, {'j', 0xF1},
{'L', 0xC7}, {'l', 0xC7},
{'N', 0xAB}, {'n', 0xAB},
{'O', 0xC0}, {'o', 0xC0},
{'P', 0x8C}, {'p', 0x8C},
{'Q', 0x98}, {'q', 0x98},
{'R', 0xAF}, {'r', 0xAF},
{'S', 0x92}, {'s', 0x92},
{'T', 0x87}, {'t', 0x87},
{'U', 0xC1}, {'u', 0xC1},
{'Y', 0x91}, {'y', 0x91},
// ==================== Символы ====================
{'-', 0xBF},
{'_', 0xF7},
{' ', 0xFF}
};
#define CHAR_TABLE_SIZE (sizeof(charTable)/sizeof(CharMap))
// ==================== Статические переменные ====================
static uint8_t displayBuffer[DIGITS_COUNT]; // Буфер СРАЗУ МАСОК сегментов
static uint8_t currentPos;
static uint32_t pwmCounter;
static uint32_t currentDigitTime;
static uint32_t currentPwmThreshold;
// ==================== Низкий уровень ====================
static void SetSegments(uint8_t mask) {
SET_SEGMENT_A((mask >> 0) & 1);
SET_SEGMENT_B((mask >> 1) & 1);
SET_SEGMENT_C((mask >> 2) & 1);
SET_SEGMENT_D((mask >> 3) & 1);
SET_SEGMENT_E((mask >> 4) & 1);
SET_SEGMENT_F((mask >> 5) & 1);
SET_SEGMENT_G((mask >> 6) & 1);
}
// Получить маску по символу
static uint8_t GetCharMask(char c) {
for (int i = 0; i < CHAR_TABLE_SIZE; i++) {
if (charTable[i].c == c)
return charTable[i].mask;
}
return 0xFF; // если символ неизвестен — пусто
}
// ==================== Управление разрядами ====================
void DisableAllDigits(void) {
SET_SEGMENT_A(1); SET_SEGMENT_B(1); SET_SEGMENT_C(1);
SET_SEGMENT_D(1); SET_SEGMENT_E(1); SET_SEGMENT_F(1);
SET_SEGMENT_G(1);
DIGIT_HOUR_H_GPIO_Port->BSRR = DIGIT_HOUR_H_Pin << 16;
DIGIT_HOUR_L_GPIO_Port->BSRR = DIGIT_HOUR_L_Pin << 16;
DIGIT_MIN_H_GPIO_Port->BSRR = DIGIT_MIN_H_Pin << 16;
DIGIT_MIN_L_GPIO_Port->BSRR = DIGIT_MIN_L_Pin << 16;
DIGIT_SEC_H_GPIO_Port->BSRR = DIGIT_SEC_H_Pin << 16;
DIGIT_SEC_L_GPIO_Port->BSRR = DIGIT_SEC_L_Pin << 16;
}
void EnableDigit(uint8_t pos) {
switch(pos) {
case 0: DIGIT_HOUR_H_GPIO_Port->BSRR = DIGIT_HOUR_H_Pin; break;
case 1: DIGIT_HOUR_L_GPIO_Port->BSRR = DIGIT_HOUR_L_Pin; break;
case 2: DIGIT_MIN_H_GPIO_Port->BSRR = DIGIT_MIN_H_Pin; break;
case 3: DIGIT_MIN_L_GPIO_Port->BSRR = DIGIT_MIN_L_Pin; break;
case 4: DIGIT_SEC_H_GPIO_Port->BSRR = DIGIT_SEC_H_Pin; break;
case 5: DIGIT_SEC_L_GPIO_Port->BSRR = DIGIT_SEC_L_Pin; break;
}
}
// ==================== Логика ====================
static void NextDigit(void) {
currentPos++;
if (currentPos >= DIGITS_COUNT) currentPos = 0;
if (REFRESH_RATE == 0) REFRESH_RATE = 1;
uint32_t totalCalls = (1000000UL / REFRESH_RATE) / PROCESS_INTERVAL_US;
if (totalCalls < DIGITS_COUNT) totalCalls = DIGITS_COUNT;
currentDigitTime = totalCalls / DIGITS_COUNT;
if (currentDigitTime < 1) currentDigitTime = 1;
currentPwmThreshold = (currentDigitTime * GLOBAL_BRIGHTNESS) / 100;
pwmCounter = 0;
}
static void UpdateOneDigit(void) {
if (pwmCounter == 0) {
DisableAllDigits();
__NOP(); __NOP(); // анти-гостинг
uint8_t mask = displayBuffer[currentPos];
// SWAP только для позиции 5
if (currentPos == 5)
mask = SWAP_BIT5_BIT6(mask);
SetSegments(mask);
EnableDigit(currentPos);
}
if (pwmCounter >= currentPwmThreshold) {
DisableAllDigits();
SetSegments(0xFF);
}
pwmCounter++;
if (pwmCounter >= currentDigitTime) {
NextDigit();
}
}
// ==================== Публичные функции ====================
// Инициализация модуля
void Segment_Init(void) {
currentPos = 0;
pwmCounter = 0;
currentDigitTime = 1;
currentPwmThreshold = 1;
for (int i = 0; i < DIGITS_COUNT; i++)
displayBuffer[i] = 0xFF; // пусто
NextDigit();
}
// Установить символ в разряд
void Segment_SetChar(uint8_t pos, char c) {
if (pos >= DIGITS_COUNT) return;
displayBuffer[pos] = GetCharMask(c);
}
// Установить напрямую маску сегментов
void Segment_SetRaw(uint8_t pos, uint8_t mask) {
if (pos >= DIGITS_COUNT) return;
displayBuffer[pos] = mask;
}
// Установить строку (например "HELLO ")
void Segment_SetString(const char *str) {
for (int i = 0; i < DIGITS_COUNT; i++) {
if (str[i] == 0)
displayBuffer[i] = 0xFF;
else
displayBuffer[i] = GetCharMask(str[i]);
}
}
// Установка глобальной яркости (0-100%)
void Segment_SetBrightness(uint8_t percent) {
if (percent > 100) percent = 100;
if (percent < 1) percent = 1;
GLOBAL_BRIGHTNESS = percent;
}
// Основная функция обновления дисплея
// Вызывается каждые 10 микросекунд из таймера
void Segment_Process(void) {
UpdateOneDigit();
}

34
Core/Clock/segment.h Normal file
View File

@@ -0,0 +1,34 @@
#ifndef SEGMENT_H
#define SEGMENT_H
#include <stdint.h>
#define SEG_DIGITS_COUNT 6 // Количество разрядов на дисплее
// ==================== Инициализация ====================
// Инициализация модуля (обнуляет буферы и переменные)
void Segment_Init(void);
// ==================== Отображение ====================
// Установить символ в конкретный разряд (0..SEG_DIGITS_COUNT-1)
void Segment_SetChar(uint8_t pos, char c);
// Установить сразу строку (например "HELLO ")
void Segment_SetString(const char *str);
// Установить напрямую маску сегментов для разряда
void Segment_SetRaw(uint8_t pos, uint8_t mask);
// Установка времени для отображения
void Segment_SetTime(uint8_t hours, uint8_t minutes, uint8_t seconds);
// ==================== Яркость ====================
// Установка глобальной яркости (0-100%)
void Segment_SetBrightness(uint8_t percent);
// ==================== Обновление дисплея ====================
// Основная функция обновления дисплея
// Вызывается каждые PROCESS_INTERVAL_US микросекунд или из таймера
void Segment_Process(void);
#endif

49
Core/Inc/gpio.h Normal file
View File

@@ -0,0 +1,49 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file gpio.h
* @brief This file contains all the function prototypes for
* the gpio.c file
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __GPIO_H__
#define __GPIO_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
void MX_GPIO_Init(void);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /*__ GPIO_H__ */

108
Core/Inc/main.h Normal file
View File

@@ -0,0 +1,108 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.h
* @brief : Header for main.c file.
* This file contains the common defines of the application.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __MAIN_H
#define __MAIN_H
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "stm32f1xx_hal.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
typedef struct
{
uint8_t hour;
uint8_t min;
uint8_t sec;
}time_t;
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void Error_Handler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
/* Private defines -----------------------------------------------------------*/
#define DIGIT_HOUR_H_Pin GPIO_PIN_0
#define DIGIT_HOUR_H_GPIO_Port GPIOA
#define DIGIT_HOUR_L_Pin GPIO_PIN_1
#define DIGIT_HOUR_L_GPIO_Port GPIOA
#define DIGIT_MIN_H_Pin GPIO_PIN_2
#define DIGIT_MIN_H_GPIO_Port GPIOA
#define DIGIT_MIN_L_Pin GPIO_PIN_3
#define DIGIT_MIN_L_GPIO_Port GPIOA
#define DIGIT_SEC_H_Pin GPIO_PIN_4
#define DIGIT_SEC_H_GPIO_Port GPIOA
#define DIGIT_SEC_L_Pin GPIO_PIN_5
#define DIGIT_SEC_L_GPIO_Port GPIOA
#define SEGMENT_A_Pin GPIO_PIN_15
#define SEGMENT_A_GPIO_Port GPIOB
#define SW_ENTER_Pin GPIO_PIN_9
#define SW_ENTER_GPIO_Port GPIOA
#define SW_UP_Pin GPIO_PIN_10
#define SW_UP_GPIO_Port GPIOA
#define SW_DOWN_Pin GPIO_PIN_11
#define SW_DOWN_GPIO_Port GPIOA
#define SW_BACK_Pin GPIO_PIN_12
#define SW_BACK_GPIO_Port GPIOA
#define SEGMENT_C_Pin GPIO_PIN_3
#define SEGMENT_C_GPIO_Port GPIOB
#define SEGMENT_B_Pin GPIO_PIN_4
#define SEGMENT_B_GPIO_Port GPIOB
#define SEGMENT_D_Pin GPIO_PIN_6
#define SEGMENT_D_GPIO_Port GPIOB
#define SEGMENT_E_Pin GPIO_PIN_7
#define SEGMENT_E_GPIO_Port GPIOB
#define SEGMENT_F_Pin GPIO_PIN_8
#define SEGMENT_F_GPIO_Port GPIOB
#define SEGMENT_G_Pin GPIO_PIN_9
#define SEGMENT_G_GPIO_Port GPIOB
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
#ifdef __cplusplus
}
#endif
#endif /* __MAIN_H */

52
Core/Inc/rtc.h Normal file
View File

@@ -0,0 +1,52 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file rtc.h
* @brief This file contains all the function prototypes for
* the rtc.c file
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __RTC_H__
#define __RTC_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
extern RTC_HandleTypeDef hrtc;
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
void MX_RTC_Init(void);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /* __RTC_H__ */

66
Core/Inc/segment_tim.h Normal file
View File

@@ -0,0 +1,66 @@
#ifndef SEGMENT_H
#define SEGMENT_H
#include <stdint.h>
#include "tim.h"
// Структура для хранения времени
typedef struct {
uint8_t hours;
uint8_t minutes;
uint8_t seconds;
} TimeStruct;
// Структура для управления сегментом
typedef struct {
TIM_HandleTypeDef *htim; // Указатель на таймер
uint32_t channel; // Канал (TIM_CHANNEL_1, TIM_CHANNEL_2, etc.)
uint8_t isComplementary; // 1 - комплементарный канал (CHxN), 0 - обычный
// инициализируется само
uint8_t isActive; // активен ли сегмент, 0 - выключен, 1 - шимиться
uint8_t Duty; // скваэнлсть с которой надо шимить сегмент
__IO uint32_t *ccmr_ptr; // указатель на соответствующий CCMR регистр
uint8_t ccmr_shift; // сдвиг в регистре CCMR
} SegCtrl_t;
// ==================== НАСТРОЙКА ТАЙМЕРОВ ДЛЯ СЕГМЕНТОВ ====================
// Сегмент A
#define SEG_A_CONFIG {&htim1, TIM_CHANNEL_3, 1}
// Сегмент B
#define SEG_B_CONFIG {&htim3, TIM_CHANNEL_1, 0}
// Сегмент C
#define SEG_C_CONFIG {&htim2, TIM_CHANNEL_2, 0}
// Сегмент D
#define SEG_D_CONFIG {&htim4, TIM_CHANNEL_1, 0}
// Сегмент E
#define SEG_E_CONFIG {&htim4, TIM_CHANNEL_2, 0}
// Сегмент F
#define SEG_F_CONFIG {&htim4, TIM_CHANNEL_3, 0}
// Сегмент G
#define SEG_G_CONFIG {&htim4, TIM_CHANNEL_4, 0}
// ==================== ПУБЛИЧНЫЕ ФУНКЦИИ ====================
// Инициализация модуля
void Segment_Init(void);
// Установка времени для отображения
void Segment_SetTime(uint8_t hours, uint8_t minutes, uint8_t seconds);
// Установка глобальной яркости (0-100%)
void Segment_SetBrightness(uint8_t percent);
// Основная функция обновления дисплея (вызывается из прерывания таймера)
// Внутри сама рассчитывает когда переключать разряд
void Segment_Process(void);
#endif

View File

@@ -0,0 +1,391 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f1xx_hal_conf.h
* @brief HAL configuration file.
******************************************************************************
* @attention
*
* Copyright (c) 2017 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F1xx_HAL_CONF_H
#define __STM32F1xx_HAL_CONF_H
#ifdef __cplusplus
extern "C" {
#endif
/* Exported types ------------------------------------------------------------*/
/* Exported constants --------------------------------------------------------*/
/* ########################## Module Selection ############################## */
/**
* @brief This is the list of modules to be used in the HAL driver
*/
#define HAL_MODULE_ENABLED
/*#define HAL_ADC_MODULE_ENABLED */
/*#define HAL_CRYP_MODULE_ENABLED */
/*#define HAL_CAN_MODULE_ENABLED */
/*#define HAL_CAN_LEGACY_MODULE_ENABLED */
/*#define HAL_CEC_MODULE_ENABLED */
/*#define HAL_CORTEX_MODULE_ENABLED */
/*#define HAL_CRC_MODULE_ENABLED */
/*#define HAL_DAC_MODULE_ENABLED */
/*#define HAL_DMA_MODULE_ENABLED */
/*#define HAL_ETH_MODULE_ENABLED */
/*#define HAL_FLASH_MODULE_ENABLED */
#define HAL_GPIO_MODULE_ENABLED
/*#define HAL_I2C_MODULE_ENABLED */
/*#define HAL_I2S_MODULE_ENABLED */
/*#define HAL_IRDA_MODULE_ENABLED */
/*#define HAL_IWDG_MODULE_ENABLED */
/*#define HAL_NOR_MODULE_ENABLED */
/*#define HAL_NAND_MODULE_ENABLED */
/*#define HAL_PCCARD_MODULE_ENABLED */
/*#define HAL_PCD_MODULE_ENABLED */
/*#define HAL_HCD_MODULE_ENABLED */
/*#define HAL_PWR_MODULE_ENABLED */
/*#define HAL_RCC_MODULE_ENABLED */
#define HAL_RTC_MODULE_ENABLED
/*#define HAL_SD_MODULE_ENABLED */
/*#define HAL_MMC_MODULE_ENABLED */
/*#define HAL_SDRAM_MODULE_ENABLED */
/*#define HAL_SMARTCARD_MODULE_ENABLED */
/*#define HAL_SPI_MODULE_ENABLED */
/*#define HAL_SRAM_MODULE_ENABLED */
#define HAL_TIM_MODULE_ENABLED
/*#define HAL_UART_MODULE_ENABLED */
/*#define HAL_USART_MODULE_ENABLED */
/*#define HAL_WWDG_MODULE_ENABLED */
#define HAL_CORTEX_MODULE_ENABLED
#define HAL_DMA_MODULE_ENABLED
#define HAL_FLASH_MODULE_ENABLED
#define HAL_EXTI_MODULE_ENABLED
#define HAL_GPIO_MODULE_ENABLED
#define HAL_PWR_MODULE_ENABLED
#define HAL_RCC_MODULE_ENABLED
/* ########################## Oscillator Values adaptation ####################*/
/**
* @brief Adjust the value of External High Speed oscillator (HSE) used in your application.
* This value is used by the RCC HAL module to compute the system frequency
* (when HSE is used as system clock source, directly or through the PLL).
*/
#if !defined (HSE_VALUE)
#define HSE_VALUE 8000000U /*!< Value of the External oscillator in Hz */
#endif /* HSE_VALUE */
#if !defined (HSE_STARTUP_TIMEOUT)
#define HSE_STARTUP_TIMEOUT 100U /*!< Time out for HSE start up, in ms */
#endif /* HSE_STARTUP_TIMEOUT */
/**
* @brief Internal High Speed oscillator (HSI) value.
* This value is used by the RCC HAL module to compute the system frequency
* (when HSI is used as system clock source, directly or through the PLL).
*/
#if !defined (HSI_VALUE)
#define HSI_VALUE 8000000U /*!< Value of the Internal oscillator in Hz*/
#endif /* HSI_VALUE */
/**
* @brief Internal Low Speed oscillator (LSI) value.
*/
#if !defined (LSI_VALUE)
#define LSI_VALUE 40000U /*!< LSI Typical Value in Hz */
#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz
The real value may vary depending on the variations
in voltage and temperature. */
/**
* @brief External Low Speed oscillator (LSE) value.
* This value is used by the UART, RTC HAL module to compute the system frequency
*/
#if !defined (LSE_VALUE)
#define LSE_VALUE 32768U /*!< Value of the External oscillator in Hz*/
#endif /* LSE_VALUE */
#if !defined (LSE_STARTUP_TIMEOUT)
#define LSE_STARTUP_TIMEOUT 5000U /*!< Time out for LSE start up, in ms */
#endif /* LSE_STARTUP_TIMEOUT */
/* Tip: To avoid modifying this file each time you need to use different HSE,
=== you can define the HSE value in your toolchain compiler preprocessor. */
/* ########################### System Configuration ######################### */
/**
* @brief This is the HAL system configuration section
*/
#define VDD_VALUE 3300U /*!< Value of VDD in mv */
#define TICK_INT_PRIORITY 15U /*!< tick interrupt priority (lowest by default) */
#define USE_RTOS 0U
#define PREFETCH_ENABLE 1U
#define USE_HAL_ADC_REGISTER_CALLBACKS 0U /* ADC register callback disabled */
#define USE_HAL_CAN_REGISTER_CALLBACKS 0U /* CAN register callback disabled */
#define USE_HAL_CEC_REGISTER_CALLBACKS 0U /* CEC register callback disabled */
#define USE_HAL_DAC_REGISTER_CALLBACKS 0U /* DAC register callback disabled */
#define USE_HAL_ETH_REGISTER_CALLBACKS 0U /* ETH register callback disabled */
#define USE_HAL_HCD_REGISTER_CALLBACKS 0U /* HCD register callback disabled */
#define USE_HAL_I2C_REGISTER_CALLBACKS 0U /* I2C register callback disabled */
#define USE_HAL_I2S_REGISTER_CALLBACKS 0U /* I2S register callback disabled */
#define USE_HAL_MMC_REGISTER_CALLBACKS 0U /* MMC register callback disabled */
#define USE_HAL_NAND_REGISTER_CALLBACKS 0U /* NAND register callback disabled */
#define USE_HAL_NOR_REGISTER_CALLBACKS 0U /* NOR register callback disabled */
#define USE_HAL_PCCARD_REGISTER_CALLBACKS 0U /* PCCARD register callback disabled */
#define USE_HAL_PCD_REGISTER_CALLBACKS 0U /* PCD register callback disabled */
#define USE_HAL_RTC_REGISTER_CALLBACKS 0U /* RTC register callback disabled */
#define USE_HAL_SD_REGISTER_CALLBACKS 0U /* SD register callback disabled */
#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U /* SMARTCARD register callback disabled */
#define USE_HAL_IRDA_REGISTER_CALLBACKS 0U /* IRDA register callback disabled */
#define USE_HAL_SRAM_REGISTER_CALLBACKS 0U /* SRAM register callback disabled */
#define USE_HAL_SPI_REGISTER_CALLBACKS 0U /* SPI register callback disabled */
#define USE_HAL_TIM_REGISTER_CALLBACKS 0U /* TIM register callback disabled */
#define USE_HAL_UART_REGISTER_CALLBACKS 0U /* UART register callback disabled */
#define USE_HAL_USART_REGISTER_CALLBACKS 0U /* USART register callback disabled */
#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U /* WWDG register callback disabled */
/* ########################## Assert Selection ############################## */
/**
* @brief Uncomment the line below to expanse the "assert_param" macro in the
* HAL drivers code
*/
/* #define USE_FULL_ASSERT 1U */
/* ################## Ethernet peripheral configuration ##################### */
/* Section 1 : Ethernet peripheral configuration */
/* MAC ADDRESS: MAC_ADDR0:MAC_ADDR1:MAC_ADDR2:MAC_ADDR3:MAC_ADDR4:MAC_ADDR5 */
#define MAC_ADDR0 2U
#define MAC_ADDR1 0U
#define MAC_ADDR2 0U
#define MAC_ADDR3 0U
#define MAC_ADDR4 0U
#define MAC_ADDR5 0U
/* Definition of the Ethernet driver buffers size and count */
#define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for receive */
#define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE /* buffer size for transmit */
#define ETH_RXBUFNB 8U /* 4 Rx buffers of size ETH_RX_BUF_SIZE */
#define ETH_TXBUFNB 4U /* 4 Tx buffers of size ETH_TX_BUF_SIZE */
/* Section 2: PHY configuration section */
/* DP83848_PHY_ADDRESS Address*/
#define DP83848_PHY_ADDRESS 0x01U
/* PHY Reset delay these values are based on a 1 ms Systick interrupt*/
#define PHY_RESET_DELAY 0x000000FFU
/* PHY Configuration delay */
#define PHY_CONFIG_DELAY 0x00000FFFU
#define PHY_READ_TO 0x0000FFFFU
#define PHY_WRITE_TO 0x0000FFFFU
/* Section 3: Common PHY Registers */
#define PHY_BCR ((uint16_t)0x00) /*!< Transceiver Basic Control Register */
#define PHY_BSR ((uint16_t)0x01) /*!< Transceiver Basic Status Register */
#define PHY_RESET ((uint16_t)0x8000) /*!< PHY Reset */
#define PHY_LOOPBACK ((uint16_t)0x4000) /*!< Select loop-back mode */
#define PHY_FULLDUPLEX_100M ((uint16_t)0x2100) /*!< Set the full-duplex mode at 100 Mb/s */
#define PHY_HALFDUPLEX_100M ((uint16_t)0x2000) /*!< Set the half-duplex mode at 100 Mb/s */
#define PHY_FULLDUPLEX_10M ((uint16_t)0x0100) /*!< Set the full-duplex mode at 10 Mb/s */
#define PHY_HALFDUPLEX_10M ((uint16_t)0x0000) /*!< Set the half-duplex mode at 10 Mb/s */
#define PHY_AUTONEGOTIATION ((uint16_t)0x1000) /*!< Enable auto-negotiation function */
#define PHY_RESTART_AUTONEGOTIATION ((uint16_t)0x0200) /*!< Restart auto-negotiation function */
#define PHY_POWERDOWN ((uint16_t)0x0800) /*!< Select the power down mode */
#define PHY_ISOLATE ((uint16_t)0x0400) /*!< Isolate PHY from MII */
#define PHY_AUTONEGO_COMPLETE ((uint16_t)0x0020) /*!< Auto-Negotiation process completed */
#define PHY_LINKED_STATUS ((uint16_t)0x0004) /*!< Valid link established */
#define PHY_JABBER_DETECTION ((uint16_t)0x0002) /*!< Jabber condition detected */
/* Section 4: Extended PHY Registers */
#define PHY_SR ((uint16_t)0x10U) /*!< PHY status register Offset */
#define PHY_SPEED_STATUS ((uint16_t)0x0002U) /*!< PHY Speed mask */
#define PHY_DUPLEX_STATUS ((uint16_t)0x0004U) /*!< PHY Duplex mask */
/* ################## SPI peripheral configuration ########################## */
/* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver
* Activated: CRC code is present inside driver
* Deactivated: CRC code cleaned from driver
*/
#define USE_SPI_CRC 0U
/* Includes ------------------------------------------------------------------*/
/**
* @brief Include module's header file
*/
#ifdef HAL_RCC_MODULE_ENABLED
#include "stm32f1xx_hal_rcc.h"
#endif /* HAL_RCC_MODULE_ENABLED */
#ifdef HAL_GPIO_MODULE_ENABLED
#include "stm32f1xx_hal_gpio.h"
#endif /* HAL_GPIO_MODULE_ENABLED */
#ifdef HAL_EXTI_MODULE_ENABLED
#include "stm32f1xx_hal_exti.h"
#endif /* HAL_EXTI_MODULE_ENABLED */
#ifdef HAL_DMA_MODULE_ENABLED
#include "stm32f1xx_hal_dma.h"
#endif /* HAL_DMA_MODULE_ENABLED */
#ifdef HAL_ETH_MODULE_ENABLED
#include "stm32f1xx_hal_eth.h"
#endif /* HAL_ETH_MODULE_ENABLED */
#ifdef HAL_CAN_MODULE_ENABLED
#include "stm32f1xx_hal_can.h"
#endif /* HAL_CAN_MODULE_ENABLED */
#ifdef HAL_CAN_LEGACY_MODULE_ENABLED
#include "Legacy/stm32f1xx_hal_can_legacy.h"
#endif /* HAL_CAN_LEGACY_MODULE_ENABLED */
#ifdef HAL_CEC_MODULE_ENABLED
#include "stm32f1xx_hal_cec.h"
#endif /* HAL_CEC_MODULE_ENABLED */
#ifdef HAL_CORTEX_MODULE_ENABLED
#include "stm32f1xx_hal_cortex.h"
#endif /* HAL_CORTEX_MODULE_ENABLED */
#ifdef HAL_ADC_MODULE_ENABLED
#include "stm32f1xx_hal_adc.h"
#endif /* HAL_ADC_MODULE_ENABLED */
#ifdef HAL_CRC_MODULE_ENABLED
#include "stm32f1xx_hal_crc.h"
#endif /* HAL_CRC_MODULE_ENABLED */
#ifdef HAL_DAC_MODULE_ENABLED
#include "stm32f1xx_hal_dac.h"
#endif /* HAL_DAC_MODULE_ENABLED */
#ifdef HAL_FLASH_MODULE_ENABLED
#include "stm32f1xx_hal_flash.h"
#endif /* HAL_FLASH_MODULE_ENABLED */
#ifdef HAL_SRAM_MODULE_ENABLED
#include "stm32f1xx_hal_sram.h"
#endif /* HAL_SRAM_MODULE_ENABLED */
#ifdef HAL_NOR_MODULE_ENABLED
#include "stm32f1xx_hal_nor.h"
#endif /* HAL_NOR_MODULE_ENABLED */
#ifdef HAL_I2C_MODULE_ENABLED
#include "stm32f1xx_hal_i2c.h"
#endif /* HAL_I2C_MODULE_ENABLED */
#ifdef HAL_I2S_MODULE_ENABLED
#include "stm32f1xx_hal_i2s.h"
#endif /* HAL_I2S_MODULE_ENABLED */
#ifdef HAL_IWDG_MODULE_ENABLED
#include "stm32f1xx_hal_iwdg.h"
#endif /* HAL_IWDG_MODULE_ENABLED */
#ifdef HAL_PWR_MODULE_ENABLED
#include "stm32f1xx_hal_pwr.h"
#endif /* HAL_PWR_MODULE_ENABLED */
#ifdef HAL_RTC_MODULE_ENABLED
#include "stm32f1xx_hal_rtc.h"
#endif /* HAL_RTC_MODULE_ENABLED */
#ifdef HAL_PCCARD_MODULE_ENABLED
#include "stm32f1xx_hal_pccard.h"
#endif /* HAL_PCCARD_MODULE_ENABLED */
#ifdef HAL_SD_MODULE_ENABLED
#include "stm32f1xx_hal_sd.h"
#endif /* HAL_SD_MODULE_ENABLED */
#ifdef HAL_NAND_MODULE_ENABLED
#include "stm32f1xx_hal_nand.h"
#endif /* HAL_NAND_MODULE_ENABLED */
#ifdef HAL_SPI_MODULE_ENABLED
#include "stm32f1xx_hal_spi.h"
#endif /* HAL_SPI_MODULE_ENABLED */
#ifdef HAL_TIM_MODULE_ENABLED
#include "stm32f1xx_hal_tim.h"
#endif /* HAL_TIM_MODULE_ENABLED */
#ifdef HAL_UART_MODULE_ENABLED
#include "stm32f1xx_hal_uart.h"
#endif /* HAL_UART_MODULE_ENABLED */
#ifdef HAL_USART_MODULE_ENABLED
#include "stm32f1xx_hal_usart.h"
#endif /* HAL_USART_MODULE_ENABLED */
#ifdef HAL_IRDA_MODULE_ENABLED
#include "stm32f1xx_hal_irda.h"
#endif /* HAL_IRDA_MODULE_ENABLED */
#ifdef HAL_SMARTCARD_MODULE_ENABLED
#include "stm32f1xx_hal_smartcard.h"
#endif /* HAL_SMARTCARD_MODULE_ENABLED */
#ifdef HAL_WWDG_MODULE_ENABLED
#include "stm32f1xx_hal_wwdg.h"
#endif /* HAL_WWDG_MODULE_ENABLED */
#ifdef HAL_PCD_MODULE_ENABLED
#include "stm32f1xx_hal_pcd.h"
#endif /* HAL_PCD_MODULE_ENABLED */
#ifdef HAL_HCD_MODULE_ENABLED
#include "stm32f1xx_hal_hcd.h"
#endif /* HAL_HCD_MODULE_ENABLED */
#ifdef HAL_MMC_MODULE_ENABLED
#include "stm32f1xx_hal_mmc.h"
#endif /* HAL_MMC_MODULE_ENABLED */
/* 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)0U : assert_failed((uint8_t *)__FILE__, __LINE__))
/* Exported functions ------------------------------------------------------- */
void assert_failed(uint8_t* file, uint32_t line);
#else
#define assert_param(expr) ((void)0U)
#endif /* USE_FULL_ASSERT */
#ifdef __cplusplus
}
#endif
#endif /* __STM32F1xx_HAL_CONF_H */

67
Core/Inc/stm32f1xx_it.h Normal file
View File

@@ -0,0 +1,67 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f1xx_it.h
* @brief This file contains the headers of the interrupt handlers.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __STM32F1xx_IT_H
#define __STM32F1xx_IT_H
#ifdef __cplusplus
extern "C" {
#endif
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Exported types ------------------------------------------------------------*/
/* USER CODE BEGIN ET */
/* USER CODE END ET */
/* Exported constants --------------------------------------------------------*/
/* USER CODE BEGIN EC */
/* USER CODE END EC */
/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */
/* USER CODE END EM */
/* Exported functions prototypes ---------------------------------------------*/
void NMI_Handler(void);
void HardFault_Handler(void);
void MemManage_Handler(void);
void BusFault_Handler(void);
void UsageFault_Handler(void);
void SVC_Handler(void);
void DebugMon_Handler(void);
void PendSV_Handler(void);
void SysTick_Handler(void);
void TIM2_IRQHandler(void);
/* USER CODE BEGIN EFP */
/* USER CODE END EFP */
#ifdef __cplusplus
}
#endif
#endif /* __STM32F1xx_IT_H */

52
Core/Inc/tim.h Normal file
View File

@@ -0,0 +1,52 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file tim.h
* @brief This file contains all the function prototypes for
* the tim.c file
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __TIM_H__
#define __TIM_H__
#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
extern TIM_HandleTypeDef htim2;
/* USER CODE BEGIN Private defines */
/* USER CODE END Private defines */
void MX_TIM2_Init(void);
/* USER CODE BEGIN Prototypes */
/* USER CODE END Prototypes */
#ifdef __cplusplus
}
#endif
#endif /* __TIM_H__ */

89
Core/Src/gpio.c Normal file
View File

@@ -0,0 +1,89 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file gpio.c
* @brief This file provides code for the configuration
* of all used GPIO pins.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "gpio.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/*----------------------------------------------------------------------------*/
/* Configure GPIO */
/*----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/** Configure pins as
* Analog
* Input
* Output
* EVENT_OUT
* EXTI
*/
void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOA, DIGIT_HOUR_H_Pin|DIGIT_HOUR_L_Pin|DIGIT_MIN_H_Pin|DIGIT_MIN_L_Pin
|DIGIT_SEC_H_Pin|DIGIT_SEC_L_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, SEGMENT_A_Pin|SEGMENT_C_Pin|SEGMENT_B_Pin|SEGMENT_D_Pin
|SEGMENT_E_Pin|SEGMENT_F_Pin|SEGMENT_G_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : PAPin PAPin PAPin PAPin
PAPin PAPin */
GPIO_InitStruct.Pin = DIGIT_HOUR_H_Pin|DIGIT_HOUR_L_Pin|DIGIT_MIN_H_Pin|DIGIT_MIN_L_Pin
|DIGIT_SEC_H_Pin|DIGIT_SEC_L_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : PBPin PBPin PBPin PBPin
PBPin PBPin PBPin */
GPIO_InitStruct.Pin = SEGMENT_A_Pin|SEGMENT_C_Pin|SEGMENT_B_Pin|SEGMENT_D_Pin
|SEGMENT_E_Pin|SEGMENT_F_Pin|SEGMENT_G_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : PAPin PAPin PAPin PAPin */
GPIO_InitStruct.Pin = SW_ENTER_Pin|SW_UP_Pin|SW_DOWN_Pin|SW_BACK_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
}
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */

216
Core/Src/main.c Normal file
View File

@@ -0,0 +1,216 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "rtc.h"
#include "tim.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "clock_manager.h"
#include "menu.h"
#include "segment.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
int ReadButton(int i){
switch(i)
{
case BUTTON_UP:
return !HAL_GPIO_ReadPin(SW_UP_GPIO_Port, SW_UP_Pin);
case BUTTON_DOWN:
return !HAL_GPIO_ReadPin(SW_DOWN_GPIO_Port, SW_DOWN_Pin);
case BUTTON_SELECT:
return !HAL_GPIO_ReadPin(SW_ENTER_GPIO_Port, SW_ENTER_Pin);
case BUTTON_BACK:
return !HAL_GPIO_ReadPin(SW_BACK_GPIO_Port, SW_BACK_Pin);
}
return 0;
}
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) {
if (htim->Instance == TIM2) {
Segment_Process();
}
}
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_RTC_Init();
MX_TIM2_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
Segment_Init();
ClockManager_Init();
Menu_Init();
HAL_TIM_Base_Start_IT(&htim2);
while (1)
{
Menu_Process();
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE|RCC_OSCILLATORTYPE_LSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.LSEState = RCC_LSE_ON;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_RTC;
PeriphClkInit.RTCClockSelection = RCC_RTCCLKSOURCE_LSE;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

93
Core/Src/rtc.c Normal file
View File

@@ -0,0 +1,93 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file rtc.c
* @brief This file provides code for the configuration
* of the RTC instances.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "rtc.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
RTC_HandleTypeDef hrtc;
/* RTC init function */
void MX_RTC_Init(void)
{
/* USER CODE BEGIN RTC_Init 0 */
/* USER CODE END RTC_Init 0 */
/* USER CODE BEGIN RTC_Init 1 */
/* USER CODE END RTC_Init 1 */
/** Initialize RTC Only
*/
hrtc.Instance = RTC;
hrtc.Init.AsynchPrediv = RTC_AUTO_1_SECOND;
hrtc.Init.OutPut = RTC_OUTPUTSOURCE_ALARM;
if (HAL_RTC_Init(&hrtc) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN RTC_Init 2 */
/* USER CODE END RTC_Init 2 */
}
void HAL_RTC_MspInit(RTC_HandleTypeDef* rtcHandle)
{
if(rtcHandle->Instance==RTC)
{
/* USER CODE BEGIN RTC_MspInit 0 */
/* USER CODE END RTC_MspInit 0 */
HAL_PWR_EnableBkUpAccess();
/* Enable BKP CLK enable for backup registers */
__HAL_RCC_BKP_CLK_ENABLE();
/* RTC clock enable */
__HAL_RCC_RTC_ENABLE();
/* USER CODE BEGIN RTC_MspInit 1 */
/* USER CODE END RTC_MspInit 1 */
}
}
void HAL_RTC_MspDeInit(RTC_HandleTypeDef* rtcHandle)
{
if(rtcHandle->Instance==RTC)
{
/* USER CODE BEGIN RTC_MspDeInit 0 */
/* USER CODE END RTC_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_RTC_DISABLE();
/* USER CODE BEGIN RTC_MspDeInit 1 */
/* USER CODE END RTC_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */

331
Core/Src/segment_tim.c Normal file
View File

@@ -0,0 +1,331 @@
#include "segment.h"
#include "main.h"
// ==================== ТАЙМЕР ДЛЯ ПРЕРЫВАНИЙ ====================
#define SEGMENT_PROCESS_TIMER htim1
// ==================== КОНФИГУРАЦИЯ ДИСПЛЕЯ ====================
#define DIGITS_COUNT 6
#define MULTIPLEX_FREQ_HZ 10000
#define PWM_FREQUENCY_HZ 10000
#define PWM_RESOLUTION 100
#define TIMER_BUS_FREQ_MHZ 72
#define SWAP_BIT5_BIT6(x) (((x) & 0x9F) | (((x) & 0x20) << 1) | (((x) & 0x40) >> 1))
// ==================== ИНИЦИАЛИЗАЦИЯ СЕГМЕНТОВ ====================
SegCtrl_t segments[7] = {
SEG_A_CONFIG,
SEG_B_CONFIG,
SEG_C_CONFIG,
SEG_D_CONFIG,
SEG_E_CONFIG,
SEG_F_CONFIG,
SEG_G_CONFIG
};
// ==================== ТАБЛИЦА СЕГМЕНТОВ ====================
// 1 - сегмент включен, 0 - выключен
static const uint8_t segmentTable[10] = {
0x3F, // 0: 0011 1111 - A,B,C,D,E,F
0x06, // 1: 0000 0110 - B,C
0x5B, // 2: 0101 1011 - A,B,D,E,G
0x4F, // 3: 0100 1111 - A,B,C,D,G
0x66, // 4: 0110 0110 - B,C,F,G
0x6D, // 5: 0110 1101 - A,C,D,F,G
0x7D, // 6: 0111 1101 - A,C,D,E,F,G
0x07, // 7: 0000 0111 - A,B,C
0x7F, // 8: 0111 1111 - все сегменты
0x6F // 9: 0110 1111 - A,B,C,D,F,G
};
static const uint8_t activeSegmentsCount[10] = {
6, 2, 5, 5, 4, 5, 6, 3, 7, 6
};
// ==================== ПЕРЕМЕННЫЕ ====================
static uint8_t displayBuffer[DIGITS_COUNT];
static uint8_t currentPos = 0;
static TimeStruct currentTime;
static uint8_t globalBrightness = 100;
static uint8_t digitCompensation[10];
static uint32_t switchIntervalTicks;
static uint32_t tickCounter = 0;
// ==================== ФУНКЦИИ УПРАВЛЕНИЯ РАЗРЯДАМИ ====================
static void DisableAllDigits(void) {
DIGIT_HOUR_H_GPIO_Port->BSRR = DIGIT_HOUR_H_Pin << 16;
DIGIT_HOUR_L_GPIO_Port->BSRR = DIGIT_HOUR_L_Pin << 16;
DIGIT_MIN_H_GPIO_Port->BSRR = DIGIT_MIN_H_Pin << 16;
DIGIT_MIN_L_GPIO_Port->BSRR = DIGIT_MIN_L_Pin << 16;
DIGIT_SEC_H_GPIO_Port->BSRR = DIGIT_SEC_H_Pin << 16;
DIGIT_SEC_L_GPIO_Port->BSRR = DIGIT_SEC_L_Pin << 16;
}
static void EnableDigit(uint8_t pos) {
switch(pos) {
case 0: DIGIT_HOUR_H_GPIO_Port->BSRR = DIGIT_HOUR_H_Pin; break;
case 1: DIGIT_HOUR_L_GPIO_Port->BSRR = DIGIT_HOUR_L_Pin; break;
case 2: DIGIT_MIN_H_GPIO_Port->BSRR = DIGIT_MIN_H_Pin; break;
case 3: DIGIT_MIN_L_GPIO_Port->BSRR = DIGIT_MIN_L_Pin; break;
case 4: DIGIT_SEC_H_GPIO_Port->BSRR = DIGIT_SEC_H_Pin; break;
case 5: DIGIT_SEC_L_GPIO_Port->BSRR = DIGIT_SEC_L_Pin; break;
}
}
// ==================== ИНИЦИАЛИЗАЦИЯ CCMR ДЛЯ КАЖДОГО СЕГМЕНТА ====================
static void InitChannel(SegCtrl_t *seg) {
// Определяем указатель на CCMR регистр и сдвиг в зависимости от канала
if (seg->channel == TIM_CHANNEL_1) {
seg->ccmr_ptr = (uint32_t*)&seg->htim->Instance->CCMR1;
seg->ccmr_shift = 0;
if(!seg->isComplementary)
seg->htim->Instance->CCER &= ~TIM_CCER_CC1P; // Сброс бита CC1P
else
seg->htim->Instance->CCER |= TIM_CCER_CC1P; // Установка бита CC1P
} else if (seg->channel == TIM_CHANNEL_2) {
seg->ccmr_ptr = (uint32_t*)&seg->htim->Instance->CCMR1;
seg->ccmr_shift = 8;
if(!seg->isComplementary)
seg->htim->Instance->CCER &= ~TIM_CCER_CC2P; // Сброс бита CC2P
else
seg->htim->Instance->CCER |= TIM_CCER_CC2P; // Установка бита CC2P
} else if (seg->channel == TIM_CHANNEL_3) {
seg->ccmr_ptr = (uint32_t*)&seg->htim->Instance->CCMR2;
seg->ccmr_shift = 0;
if(!seg->isComplementary)
seg->htim->Instance->CCER &= ~TIM_CCER_CC3P; // Сброс бита CC3P
else
seg->htim->Instance->CCER |= TIM_CCER_CC3P; // Установка бита CC3P
} else if (seg->channel == TIM_CHANNEL_4) {
seg->ccmr_ptr = (uint32_t*)&seg->htim->Instance->CCMR2;
seg->ccmr_shift = 8;
if(!seg->isComplementary)
seg->htim->Instance->CCER &= ~TIM_CCER_CC4P; // Сброс бита CC4P
else
seg->htim->Instance->CCER |= TIM_CCER_CC4P; // Установка бита CC4P
}
}
// ==================== ФУНКЦИИ УПРАВЛЕНИЯ ШИМ ====================
static inline void PWM_StartChannel(SegCtrl_t *seg) {
if (seg->isComplementary) {
HAL_TIMEx_PWMN_Start(seg->htim, seg->channel);
} else {
HAL_TIM_PWM_Start(seg->htim, seg->channel);
}
}
static inline void PWM_SetMode(SegCtrl_t *seg, uint32_t mode) {
uint32_t mask = 0x7 << (seg->ccmr_shift+4);
*seg->ccmr_ptr &= ~mask;
*seg->ccmr_ptr |= (mode << seg->ccmr_shift);
}
static inline void PWM_SetDuty(SegCtrl_t *seg, uint32_t duty) {
uint32_t final_duty = duty;
if (duty > PWM_RESOLUTION) duty = PWM_RESOLUTION;
if (final_duty == 0) {
PWM_SetMode(seg, TIM_OCMODE_FORCED_INACTIVE);
} else {
PWM_SetMode(seg, TIM_OCMODE_PWM1);
__HAL_TIM_SET_COMPARE(seg->htim, seg->channel, final_duty);
}
}
// ==================== АВТОНАСТРОЙКА ТАЙМЕРА ====================
static void TimerAutoConfig(TIM_HandleTypeDef *htim) {
uint32_t timer_clock_hz = TIMER_BUS_FREQ_MHZ * 1000000;
uint32_t arr = PWM_RESOLUTION - 1;
uint32_t prescaler_plus1 = timer_clock_hz / (PWM_FREQUENCY_HZ * PWM_RESOLUTION);
if (prescaler_plus1 < 1) prescaler_plus1 = 1;
if (prescaler_plus1 > 65535) prescaler_plus1 = 65535;
uint32_t prescaler = prescaler_plus1 - 1;
__HAL_TIM_SET_PRESCALER(htim, prescaler);
__HAL_TIM_SET_AUTORELOAD(htim, arr);
}
// ==================== ФУНКЦИИ УПРАВЛЕНИЯ СЕГМЕНТАМИ ====================
static void SetSegment(uint8_t segIndex, uint8_t state) {
SegCtrl_t *seg = &segments[segIndex];
seg->isActive = state;
if (state) {
PWM_SetDuty(seg, seg->Duty);
} else {
PWM_SetDuty(seg, 0);
}
}
static void SetSegmentBrightness(uint8_t segIndex, uint8_t percent) {
SegCtrl_t *seg = &segments[segIndex];
if (percent > 100) percent = 100;
seg->Duty = (percent * PWM_RESOLUTION) / 100;
}
static void DisplayDigit(uint8_t digit, uint8_t pos) {
if (digit > 9) digit = 0;
uint8_t segmentMask = segmentTable[digit];
if (pos == 5) {
segmentMask = SWAP_BIT5_BIT6(segmentMask);
}
// Применяем компенсацию для текущей цифры
uint8_t comp = digitCompensation[digit];
uint8_t finalBrightness = (globalBrightness * comp) / 100;
for (int i = 0; i < 7; i++) {
SetSegmentBrightness(i, finalBrightness);
if ((segmentMask >> i) & 1) {
SetSegment(i, 1);
} else {
SetSegment(i, 0);
}
}
}
// ==================== ФУНКЦИИ ОБНОВЛЕНИЯ БУФЕРА ====================
static void UpdateDisplayBuffer(void) {
uint8_t hours = currentTime.hours;
uint8_t minutes = currentTime.minutes;
uint8_t seconds = currentTime.seconds;
static const uint8_t div10[100] = {
0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3,
4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9
};
static const uint8_t mod10[100] = {
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9
};
displayBuffer[0] = div10[hours];
displayBuffer[1] = mod10[hours];
displayBuffer[2] = div10[minutes];
displayBuffer[3] = mod10[minutes];
displayBuffer[4] = div10[seconds];
displayBuffer[5] = mod10[seconds];
}
static void NextDigit(void) {
DisableAllDigits();
currentPos++;
if (currentPos >= DIGITS_COUNT) {
currentPos = 0;
}
DisplayDigit(displayBuffer[currentPos], currentPos);
EnableDigit(currentPos);
}
// ==================== ПУБЛИЧНЫЕ ФУНКЦИИ ====================
void Segment_Init(void) {
TIM_HandleTypeDef* configuredTimers[10] = {0};
int timerCount = 0;
// Инициализируем CCMR для каждого сегмента
for (int i = 0; i < 7; i++) {
InitChannel(&segments[i]);
}
// Настраиваем и запускаем все уникальные таймеры для ШИМ
for (int i = 0; i < 7; i++) {
TIM_HandleTypeDef *htim = segments[i].htim;
int alreadyConfigured = 0;
for (int j = 0; j < timerCount; j++) {
if (configuredTimers[j] == htim) {
alreadyConfigured = 1;
break;
}
}
if (!alreadyConfigured) {
TimerAutoConfig(htim);
configuredTimers[timerCount++] = htim;
}
PWM_StartChannel(&segments[i]);
}
// Инициализация сегментов
for (int i = 0; i < 7; i++) {
segments[i].Duty = 0;
segments[i].isActive = 0;
PWM_SetDuty(&segments[i], 0);
}
// Рассчитываем компенсацию яркости для каждой цифры
// Чем меньше сегментов у цифры, тем ярче должен гореть каждый сегмент
for (int i = 0; i < 10; i++) {
// Максимальное количество сегментов = 7 (цифра 8)
// Коэффициент = (7 / количество_сегментов_у_цифры) * 100
digitCompensation[i] = (activeSegmentsCount[i] * 100) / 7;
if (digitCompensation[i] > 200) digitCompensation[i] = 200; // Ограничиваем
}
currentTime.hours = 0;
currentTime.minutes = 0;
currentTime.seconds = 0;
UpdateDisplayBuffer();
switchIntervalTicks = PWM_FREQUENCY_HZ / MULTIPLEX_FREQ_HZ;
if (switchIntervalTicks < 1) switchIntervalTicks = 1;
tickCounter = 0;
DisplayDigit(displayBuffer[0], 0);
EnableDigit(0);
// Запускаем таймер прерываний
HAL_TIM_Base_Start_IT(&SEGMENT_PROCESS_TIMER);
}
void Segment_SetBrightness(uint8_t percent) {
if (percent > 100) percent = 100;
globalBrightness = percent;
DisplayDigit(displayBuffer[currentPos], currentPos);
}
void Segment_SetTime(uint8_t hours, uint8_t minutes, uint8_t seconds) {
if (hours > 23) hours = 23;
if (minutes > 59) minutes = 59;
if (seconds > 59) seconds = 59;
currentTime.hours = hours;
currentTime.minutes = minutes;
currentTime.seconds = seconds;
UpdateDisplayBuffer();
}
void Segment_Process(void) {
tickCounter++;
if (tickCounter >= switchIntervalTicks) {
tickCounter = 0;
NextDigit();
}
}

View File

@@ -0,0 +1,87 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f1xx_hal_msp.c
* @brief This file provides code for the MSP Initialization
* and de-Initialization codes.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN Define */
/* USER CODE END Define */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN Macro */
/* USER CODE END Macro */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* External functions --------------------------------------------------------*/
/* USER CODE BEGIN ExternalFunctions */
/* USER CODE END ExternalFunctions */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void)
{
/* USER CODE BEGIN MspInit 0 */
/* USER CODE END MspInit 0 */
__HAL_RCC_AFIO_CLK_ENABLE();
__HAL_RCC_PWR_CLK_ENABLE();
/* System interrupt init*/
/** NOJTAG: JTAG-DP Disabled and SW-DP Enabled
*/
__HAL_AFIO_REMAP_SWJ_NOJTAG();
/* USER CODE BEGIN MspInit 1 */
/* USER CODE END MspInit 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */

218
Core/Src/stm32f1xx_it.c Normal file
View File

@@ -0,0 +1,218 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f1xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f1xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "segment.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern TIM_HandleTypeDef htim2;
/* USER CODE BEGIN EV */
/* USER CODE END EV */
/******************************************************************************/
/* Cortex-M3 Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
while (1)
{
}
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_HardFault_IRQn 0 */
/* USER CODE END W1_HardFault_IRQn 0 */
}
}
/**
* @brief This function handles Memory management fault.
*/
void MemManage_Handler(void)
{
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
/* USER CODE END W1_MemoryManagement_IRQn 0 */
}
}
/**
* @brief This function handles Prefetch fault, memory access fault.
*/
void BusFault_Handler(void)
{
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_BusFault_IRQn 0 */
/* USER CODE END W1_BusFault_IRQn 0 */
}
}
/**
* @brief This function handles Undefined instruction or illegal state.
*/
void UsageFault_Handler(void)
{
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_UsageFault_IRQn 0 */
/* USER CODE END W1_UsageFault_IRQn 0 */
}
}
/**
* @brief This function handles System service call via SWI instruction.
*/
void SVC_Handler(void)
{
/* USER CODE BEGIN SVCall_IRQn 0 */
/* USER CODE END SVCall_IRQn 0 */
/* USER CODE BEGIN SVCall_IRQn 1 */
/* USER CODE END SVCall_IRQn 1 */
}
/**
* @brief This function handles Debug monitor.
*/
void DebugMon_Handler(void)
{
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
/* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */
}
/**
* @brief This function handles Pendable request for system service.
*/
void PendSV_Handler(void)
{
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32F1xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32f1xx.s). */
/******************************************************************************/
/**
* @brief This function handles TIM2 global interrupt.
*/
void TIM2_IRQHandler(void)
{
/* USER CODE BEGIN TIM2_IRQn 0 */
/* USER CODE END TIM2_IRQn 0 */
HAL_TIM_IRQHandler(&htim2);
/* USER CODE BEGIN TIM2_IRQn 1 */
/* USER CODE END TIM2_IRQn 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */

406
Core/Src/system_stm32f1xx.c Normal file
View File

@@ -0,0 +1,406 @@
/**
******************************************************************************
* @file system_stm32f1xx.c
* @author MCD Application Team
* @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File.
*
* 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
* factors, AHB/APBx prescalers and Flash settings).
* This function is called at startup just after reset and
* before branch to main program. This call is made inside
* the "startup_stm32f1xx_xx.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) is used as system clock source.
* Then SystemInit() function is called, in "startup_stm32f1xx_xx.s" file, to
* configure the system clock before to branch to main program.
*
* 4. The default value of HSE crystal is set to 8 MHz (or 25 MHz, depending on
* the product used), refer to "HSE_VALUE".
* 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
*
* Copyright (c) 2017-2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32f1xx_system
* @{
*/
/** @addtogroup STM32F1xx_System_Private_Includes
* @{
*/
#include "stm32f1xx.h"
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_Defines
* @{
*/
#if !defined (HSE_VALUE)
#define HSE_VALUE 8000000U /*!< Default value of the External oscillator in Hz.
This value can be provided and adapted by the user application. */
#endif /* HSE_VALUE */
#if !defined (HSI_VALUE)
#define HSI_VALUE 8000000U /*!< Default value of the Internal oscillator in Hz.
This value can be provided and adapted by the user application. */
#endif /* HSI_VALUE */
/*!< Uncomment the following line if you need to use external SRAM */
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
/* #define DATA_IN_ExtSRAM */
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
/* Note: Following vector table addresses must be defined in line with linker
configuration. */
/*!< Uncomment the following line if you need to relocate the vector table
anywhere in Flash or Sram, else the vector table is kept at the automatic
remap of boot address selected */
/* #define USER_VECT_TAB_ADDRESS */
#if defined(USER_VECT_TAB_ADDRESS)
/*!< Uncomment the following line if you need to relocate your vector Table
in Sram else user remap will be done in Flash. */
/* #define VECT_TAB_SRAM */
#if defined(VECT_TAB_SRAM)
#define VECT_TAB_BASE_ADDRESS SRAM_BASE /*!< Vector Table base address field.
This value must be a multiple of 0x200. */
#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
#else
#define VECT_TAB_BASE_ADDRESS FLASH_BASE /*!< Vector Table base address field.
This value must be a multiple of 0x200. */
#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
#endif /* VECT_TAB_SRAM */
#endif /* USER_VECT_TAB_ADDRESS */
/******************************************************************************/
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_Variables
* @{
*/
/* This variable is updated in three ways:
1) by calling CMSIS function SystemCoreClockUpdate()
2) by calling HAL API function HAL_RCC_GetHCLKFreq()
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
Note: If you use this function to configure the system clock; then there
is no need to call the 2 first functions listed above, since SystemCoreClock
variable is updated automatically.
*/
uint32_t SystemCoreClock = 8000000;
const uint8_t AHBPrescTable[16U] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
const uint8_t APBPrescTable[8U] = {0, 0, 0, 0, 1, 2, 3, 4};
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_FunctionPrototypes
* @{
*/
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
#ifdef DATA_IN_ExtSRAM
static void SystemInit_ExtMemCtl(void);
#endif /* DATA_IN_ExtSRAM */
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_Functions
* @{
*/
/**
* @brief Setup the microcontroller system
* Initialize the Embedded Flash Interface, the PLL and update the
* SystemCoreClock variable.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
void SystemInit (void)
{
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
#ifdef DATA_IN_ExtSRAM
SystemInit_ExtMemCtl();
#endif /* DATA_IN_ExtSRAM */
#endif
/* Configure the Vector Table location -------------------------------------*/
#if defined(USER_VECT_TAB_ADDRESS)
SCB->VTOR = VECT_TAB_BASE_ADDRESS | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */
#endif /* USER_VECT_TAB_ADDRESS */
}
/**
* @brief Update SystemCoreClock variable 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 by the PLL factors.
*
* (*) HSI_VALUE is a constant defined in stm32f1xx.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 stm32f1xx.h file (default value
* 8 MHz or 25 MHz, depending on the product used), user has to ensure
* that HSE_VALUE is same as the real frequency of the crystal used.
* Otherwise, this function may have wrong result.
*
* - 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 = 0U, pllmull = 0U, pllsource = 0U;
#if defined(STM32F105xC) || defined(STM32F107xC)
uint32_t prediv1source = 0U, prediv1factor = 0U, prediv2factor = 0U, pll2mull = 0U;
#endif /* STM32F105xC */
#if defined(STM32F100xB) || defined(STM32F100xE)
uint32_t prediv1factor = 0U;
#endif /* STM32F100xB or STM32F100xE */
/* Get SYSCLK source -------------------------------------------------------*/
tmp = RCC->CFGR & RCC_CFGR_SWS;
switch (tmp)
{
case 0x00U: /* HSI used as system clock */
SystemCoreClock = HSI_VALUE;
break;
case 0x04U: /* HSE used as system clock */
SystemCoreClock = HSE_VALUE;
break;
case 0x08U: /* PLL used as system clock */
/* Get PLL clock source and multiplication factor ----------------------*/
pllmull = RCC->CFGR & RCC_CFGR_PLLMULL;
pllsource = RCC->CFGR & RCC_CFGR_PLLSRC;
#if !defined(STM32F105xC) && !defined(STM32F107xC)
pllmull = ( pllmull >> 18U) + 2U;
if (pllsource == 0x00U)
{
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
}
else
{
#if defined(STM32F100xB) || defined(STM32F100xE)
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
/* HSE oscillator clock selected as PREDIV1 clock entry */
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
#else
/* HSE selected as PLL clock entry */
if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET)
{/* HSE oscillator clock divided by 2 */
SystemCoreClock = (HSE_VALUE >> 1U) * pllmull;
}
else
{
SystemCoreClock = HSE_VALUE * pllmull;
}
#endif
}
#else
pllmull = pllmull >> 18U;
if (pllmull != 0x0DU)
{
pllmull += 2U;
}
else
{ /* PLL multiplication factor = PLL input clock * 6.5 */
pllmull = 13U / 2U;
}
if (pllsource == 0x00U)
{
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
}
else
{/* PREDIV1 selected as PLL clock entry */
/* Get PREDIV1 clock source and division factor */
prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC;
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
if (prediv1source == 0U)
{
/* HSE oscillator clock selected as PREDIV1 clock entry */
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
}
else
{/* PLL2 clock selected as PREDIV1 clock entry */
/* Get PREDIV2 division factor and PLL2 multiplication factor */
prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4U) + 1U;
pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8U) + 2U;
SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull;
}
}
#endif /* STM32F105xC */
break;
default:
SystemCoreClock = HSI_VALUE;
break;
}
/* Compute HCLK clock frequency ----------------*/
/* Get HCLK prescaler */
tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)];
/* HCLK clock frequency */
SystemCoreClock >>= tmp;
}
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
/**
* @brief Setup the external memory controller. Called in startup_stm32f1xx.s
* before jump to __main
* @param None
* @retval None
*/
#ifdef DATA_IN_ExtSRAM
/**
* @brief Setup the external memory controller.
* Called in startup_stm32f1xx_xx.s/.c before jump to main.
* This function configures the external SRAM mounted on STM3210E-EVAL
* board (STM32 High density devices). This SRAM will be used as program
* data memory (including heap and stack).
* @param None
* @retval None
*/
void SystemInit_ExtMemCtl(void)
{
__IO uint32_t tmpreg;
/*!< FSMC Bank1 NOR/SRAM3 is used for the STM3210E-EVAL, if another Bank is
required, then adjust the Register Addresses */
/* Enable FSMC clock */
RCC->AHBENR = 0x00000114U;
/* Delay after an RCC peripheral clock enabling */
tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FSMCEN);
/* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */
RCC->APB2ENR = 0x000001E0U;
/* Delay after an RCC peripheral clock enabling */
tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPDEN);
(void)(tmpreg);
/* --------------- SRAM Data lines, NOE and NWE configuration ---------------*/
/*---------------- SRAM Address lines configuration -------------------------*/
/*---------------- NOE and NWE configuration --------------------------------*/
/*---------------- NE3 configuration ----------------------------------------*/
/*---------------- NBL0, NBL1 configuration ---------------------------------*/
GPIOD->CRL = 0x44BB44BBU;
GPIOD->CRH = 0xBBBBBBBBU;
GPIOE->CRL = 0xB44444BBU;
GPIOE->CRH = 0xBBBBBBBBU;
GPIOF->CRL = 0x44BBBBBBU;
GPIOF->CRH = 0xBBBB4444U;
GPIOG->CRL = 0x44BBBBBBU;
GPIOG->CRH = 0x444B4B44U;
/*---------------- FSMC Configuration ---------------------------------------*/
/*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/
FSMC_Bank1->BTCR[4U] = 0x00001091U;
FSMC_Bank1->BTCR[5U] = 0x00110212U;
}
#endif /* DATA_IN_ExtSRAM */
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/

111
Core/Src/tim.c Normal file
View File

@@ -0,0 +1,111 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file tim.c
* @brief This file provides code for the configuration
* of the TIM instances.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "tim.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
TIM_HandleTypeDef htim2;
/* TIM2 init function */
void MX_TIM2_Init(void)
{
/* USER CODE BEGIN TIM2_Init 0 */
/* USER CODE END TIM2_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
/* USER CODE BEGIN TIM2_Init 1 */
/* USER CODE END TIM2_Init 1 */
htim2.Instance = TIM2;
htim2.Init.Prescaler = 0;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 72*10-1;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM2_Init 2 */
/* USER CODE END TIM2_Init 2 */
}
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
{
if(tim_baseHandle->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspInit 0 */
/* USER CODE END TIM2_MspInit 0 */
/* TIM2 clock enable */
__HAL_RCC_TIM2_CLK_ENABLE();
/* TIM2 interrupt Init */
HAL_NVIC_SetPriority(TIM2_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(TIM2_IRQn);
/* USER CODE BEGIN TIM2_MspInit 1 */
/* USER CODE END TIM2_MspInit 1 */
}
}
void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* tim_baseHandle)
{
if(tim_baseHandle->Instance==TIM2)
{
/* USER CODE BEGIN TIM2_MspDeInit 0 */
/* USER CODE END TIM2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_TIM2_CLK_DISABLE();
/* TIM2 interrupt Deinit */
HAL_NVIC_DisableIRQ(TIM2_IRQn);
/* USER CODE BEGIN TIM2_MspDeInit 1 */
/* USER CODE END TIM2_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */