stm32-HB-DCMotor-Initialization&MotorFunctions

by Marwen Maghrebi
  1. /* Includes ------------------------------------------------------------------*/
  2. #include "main.h"
  3.  
  4. /* Private includes ----------------------------------------------------------*/
  5. #include<stdio.h>
  6. #include<string.h>
  7.  
  8. /* Private define ------------------------------------------------------------*/
  9. #define DEBOUNCE_DELAY 50 // ms
  10.  
  11. /* Private variables ---------------------------------------------------------*/
  12. TIM_HandleTypeDef htim2;
  13. UART_HandleTypeDef huart1;
  14.  
  15. uint8_t motorRunning = 0;
  16. uint8_t currentDutyCycle = 0; // 0: 25%, 1: 50%, 2: 75%, 3: 99%
  17. uint32_t lastDebounceTime = 0;
  18. static uint8_t lastButtonState;
  19.  
  20. /* Function prototypes -----------------------------------------------------*/
  21. void HandleStartStop(void);
  22. void HandleDutyCycle(void);
  23. void UpdatePWM(void);
  24. void SendUartMessage(char* message);
  25.  
  26. /* Function to handle start/stop button */
  27. void HandleStartStop(void) {
  28. static GPIO_PinState lastStartStopState = GPIO_PIN_SET; // Track previous state
  29. GPIO_PinState currentStartStopState = HAL_GPIO_ReadPin(START_STOP_GPIO_Port, START_STOP_Pin);
  30.  
  31. if (lastStartStopState == GPIO_PIN_SET && currentStartStopState == GPIO_PIN_RESET) {
  32. uint32_t currentTime = HAL_GetTick();
  33. if (currentTime - lastDebounceTime > DEBOUNCE_DELAY) {
  34. motorRunning = !motorRunning;
  35. SendUartMessage(motorRunning ? "Motor Started\n\r" : "Motor Stopped\n\r");
  36. UpdatePWM();
  37. lastDebounceTime = currentTime;
  38. }
  39. }
  40.  
  41. if (motorRunning) {
  42. HAL_GPIO_WritePin(DIR_GPIO_Port, DIR_Pin, GPIO_PIN_RESET); // Ensure DIR pin is set
  43. HAL_TIM_Base_Start(&htim2); // Start Timer2
  44. HAL_TIM_OC_Start(&htim2, TIM_CHANNEL_2); // Start PWM
  45. } else {
  46. HAL_TIM_Base_Stop(&htim2); // Stop Timer2
  47. HAL_TIM_OC_Stop(&htim2, TIM_CHANNEL_2); // Stop PWM
  48. }
  49.  
  50. lastStartStopState = currentStartStopState; // Update last button state
  51. }
  52.  
  53. /* Function to handle duty cycle button */
  54. void HandleDutyCycle(void) {
  55. uint8_t currentButtonState = HAL_GPIO_ReadPin(DUTY_CYCLE_GPIO_Port, DUTY_CYCLE_Pin);
  56.  
  57. if (currentButtonState != lastButtonState) {
  58. uint32_t currentTime = HAL_GetTick();
  59. if (currentTime - lastDebounceTime > DEBOUNCE_DELAY) {
  60. if (currentButtonState == GPIO_PIN_RESET) { // Button is pressed
  61. currentDutyCycle = (currentDutyCycle + 1) % 4;
  62. UpdatePWM();
  63. }
  64. lastDebounceTime = currentTime;
  65. }
  66. }
  67.  
  68. lastButtonState = currentButtonState; // Update last button state
  69. }
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
-
00:00
00:00
    -
    00:00
    00:00