cancel
Showing results for 
Search instead for 
Did you mean: 

Problem with class constructor and GPIO

Gzini.6
Associate II

hi everyone

i'm writing some code to control an RC car.

while implementing the code for the motors, i've decided to assign the peripherals information (PORT, GPIO, timer ecc) directly in the class constructor.

but if i do so, motors wont respond, it seems like peripherals aren't correctly initialized.

//DC Motors-----------------------------------------
Motors::Motors(float w_max, uint32_t ARR,GPIO_TypeDef* M_PORT_DirPin, uint16_t M_GPIO_DirPin,
                                                TIM_HandleTypeDef M_htim, uint32_t M_Channel){
	m_map=ARR/w_max;
	PORT_DirPin=M_PORT_DirPin;
	GPIO_DirPin=M_GPIO_DirPin;
	htim=M_htim;
	Channel=M_Channel;
 
 
}
 
void Motors::setMotorSpeed(float w){
 
	if(w<0){//CCW
		w=-1*w;
		HAL_GPIO_WritePin(PORT_DirPin,GPIO_DirPin,GPIO_PIN_RESET);
	}else{  //CW
		HAL_GPIO_WritePin(PORT_DirPin,GPIO_DirPin,GPIO_PIN_SET);
	}
 
    switch(Channel){
    case TIM_CHANNEL_1:
   	 htim.Instance->CCR1=uint32_t(w*m_map);
   	 break;
    case TIM_CHANNEL_2:
   	 htim.Instance->CCR2=uint32_t(w*m_map);
   	 break;
    case TIM_CHANNEL_3:
   	 htim.Instance->CCR3=uint32_t(w*m_map);
   	 break;
    case TIM_CHANNEL_4:
   	 htim.Instance->CCR4=uint32_t(w*m_map);
   	 break;
    default:
 
   	 break;
    }
 
}
//DC motors
Motors Motor_L(Car.W_max,500,GPIOB,Dir_B_Pin,htim3,TIM_CHANNEL_1);   //w_max,ARR,GPIO,timer
Motors Motor_R(Car.W_max,500,GPIOA,Dir_A_Pin,htim2,TIM_CHANNEL_3);
 
...
 
 

as you can see i've passed the ARR value in a numerical way, instead of htim.Init.Period

If i pass them in the method motors works:

void Motors::setMotorSpeed(float w, GPIO_TypeDef* PORT_DirPin, uint16_t GPIO_DirPin,
                                           TIM_HandleTypeDef htim, uint32_t Channel){
 
	if(w<0){//CCW
		w=-1*w;
		HAL_GPIO_WritePin(PORT_DirPin,GPIO_DirPin,GPIO_PIN_RESET);
	}else{  //CW
		HAL_GPIO_WritePin(PORT_DirPin,GPIO_DirPin,GPIO_PIN_SET);
	}
 
    switch(Channel){
    case TIM_CHANNEL_1:
     ...

however also in this case i've to pass the ARR in a numerical way, if i take it form the real storing variable ( htim.Init.Period), pwm isn't generated correctly.

STM32F446RE

EDIT:

it seems .cpp files are executed before the main.c

3 REPLIES 3

> it seems like peripherals aren't correctly initialized.

And how do you initialize them?

JW

with cubeMX

Gzini.6
Associate II

actually i may found the problem.

the .cpp file is executed before the main.c, and the classes are defined before the peripherals initialization.

i could call some function from the main that define the classes in the cpp file but then i would have some problems with visibility