stm32-HB-DCMotor-Initialization&MotorFunctions

by Marwen Maghrebi
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
#include<stdio.h>
#include<string.h>

/* Private define ------------------------------------------------------------*/
#define DEBOUNCE_DELAY 50 // ms

/* Private variables ---------------------------------------------------------*/
TIM_HandleTypeDef htim2;
UART_HandleTypeDef huart1;

uint8_t motorRunning = 0;
uint8_t currentDutyCycle = 0; // 0: 25%, 1: 50%, 2: 75%, 3: 99%
uint32_t lastDebounceTime = 0;
static uint8_t lastButtonState;

/* Function prototypes -----------------------------------------------------*/
void HandleStartStop(void);
void HandleDutyCycle(void);
void UpdatePWM(void);
void SendUartMessage(char* message);

/* Function to handle start/stop button */
void HandleStartStop(void) {
    static GPIO_PinState lastStartStopState = GPIO_PIN_SET; // Track previous state
    GPIO_PinState currentStartStopState = HAL_GPIO_ReadPin(START_STOP_GPIO_Port, START_STOP_Pin);

    if (lastStartStopState == GPIO_PIN_SET && currentStartStopState == GPIO_PIN_RESET) {
        uint32_t currentTime = HAL_GetTick();
        if (currentTime - lastDebounceTime > DEBOUNCE_DELAY) {
            motorRunning = !motorRunning;
            SendUartMessage(motorRunning ? "Motor Started\n\r" : "Motor Stopped\n\r");
            UpdatePWM();
            lastDebounceTime = currentTime;
        }
    }

    if (motorRunning) {
        HAL_GPIO_WritePin(DIR_GPIO_Port, DIR_Pin, GPIO_PIN_RESET); // Ensure DIR pin is set
        HAL_TIM_Base_Start(&htim2); // Start Timer2
        HAL_TIM_OC_Start(&htim2, TIM_CHANNEL_2); // Start PWM
    } else {
        HAL_TIM_Base_Stop(&htim2); // Stop Timer2
        HAL_TIM_OC_Stop(&htim2, TIM_CHANNEL_2); // Stop PWM
    }

    lastStartStopState = currentStartStopState; // Update last button state
}

/* Function to handle duty cycle button */
void HandleDutyCycle(void) {
    uint8_t currentButtonState = HAL_GPIO_ReadPin(DUTY_CYCLE_GPIO_Port, DUTY_CYCLE_Pin);

    if (currentButtonState != lastButtonState) {
        uint32_t currentTime = HAL_GetTick();
        if (currentTime - lastDebounceTime > DEBOUNCE_DELAY) {
            if (currentButtonState == GPIO_PIN_RESET) { // Button is pressed
                currentDutyCycle = (currentDutyCycle + 1) % 4;
                UpdatePWM();
            }
            lastDebounceTime = currentTime;
        }
    }

    lastButtonState = currentButtonState; // Update last button state
}
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
-
00:00
00:00
Update Required Flash plugin
-
00:00
00:00