# Changing PWM Pulse and GPIO Outputs Inside a Function (STM32)

hope you are all doing well.

I am trying to learn STM32 for about two weeks now and right now I need to create a Library file which includes just one function. This function changes PWM Duty Cycle and two GPIO Output pins in order to rotate/stop/change direction of a DC Motor.

However, I am not too sure about ways to do that. I had written a main single main file for the same purpose and it worked well. Right now, I want to create a library function which can be used elsewhere.

Here is what I thought:

.h file:

#include "main.h"
#ifndef INC_RBG_H_
#define INC_RBG_H_

void RT_Seal(int direction, GPIO_InitTypeDef* GPIO, TIM_OC_InitTypeDef* sConfigOC);

#endif /* INC_RBG_H_ */


.c file (which is poorly written, sorry about that, I do not know what to do):

#include "rbg.h"

void RT_SealLock(int direction, GPIO_InitTypeDef* GPIO, TIM_OC_InitTypeDef* sConfigOC)
{
if (direction == 0)
{
//__HAL_TIM_SET_COMPARE(&htim, TIM_CHANNEL, 90);
HAL_GPIO_WritePin(GPIO, GPIO -> GPIO_PIN_5, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOB, GPIO -> GPIO_PIN_4, GPIO_PIN_SET);
}
else if (direction == 1)
{
//__HAL_TIM_SET_COMPARE(&htim, TIM_CHANNEL, 90);
HAL_GPIO_WritePin(GPIO, GPIO -> GPIO_PIN_5, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIO, GPIO -> GPIO_PIN_4, GPIO_PIN_RESET);
}
else
{
//__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, 0);
}
}


To change the PWM Duty Cycle, I thought about changing the pulse variable of sConfigOC:

sConfigOC.Pulse = 90; // something like that


However I am not too sure about either way. What approach should I follow to create this function which changes GPIO Pin states and PWM Duty Cycle inside?

• changing the topic slightly, it's not a good idea to reverse a motor that is already rotating. Think of the current involved. You would normally bring the motor to a halt, reverse then accelerate the motor. Aug 24 at 9:13

Your intention is not clear. What are your inputs?, which of them constant? What do you expect after the function called and executed? Function below gets direction, gpio port address, timer handler address. You can add new parameters such as compare value. it's recommended to reset timer counter before changing compare value.

void RT_SealLock(int direction, GPIO_TypeDef* GPIO, TIM_HandleTypeDef * tim)
{
if (direction == 0) {
__HAL_TIM_SET_COMPARE(tim, TIM_CHANNEL_1, 90);
HAL_GPIO_WritePin(GPIO, GPIO_PIN_5, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIO, GPIO_PIN_4, GPIO_PIN_SET);
} else if (direction == 1)
{
__HAL_TIM_SET_COMPARE(tim, TIM_CHANNEL_1, 90);
HAL_GPIO_WritePin(GPIO, GPIO_PIN_5, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIO, GPIO_PIN_4, GPIO_PIN_RESET);
} else {
__HAL_TIM_SET_COMPARE(tim, TIM_CHANNEL_1, 0);
}
}

• That was exactly what I was looking for, thanks! Aug 24 at 13:40