Arturia Forums

Hardware Instruments => MiniBrute 2S => MiniBrute 2S - General Discussions => Topic started by: Spencers on July 16, 2021, 06:33:23 am

Title: STM8 Pulse Counter
Post by: Spencers on July 16, 2021, 06:33:23 am
I am developing a control for a DC motor. This motor has an encoder that generates pulses according to its movement.

I need to control the number of turns of the motor shaft by monitoring the number of pulses.

I am using SMT8S103F3 for this application.

The idea is to use Timer1 as a pulse counter. For this, I configured the Timer to receive an external signal, in this case the encoder pulses, and with each pulse the counter must be increased.

I followed the document ST RM0016 chapter 17.4.3. However the application is not working. The counter is not incrementing.

Follows the developed code.

Code: [Select]
void config_counter(){
  TIM1_PSCRH = 0;
  TIM1_PSCRL = 0; //Prescalar 1 division
  TIM1_ARRH = 0;
  TIM1_ARRL = 0;  //Auto counter disabled
  TIM1_CNTRH = 0;
  TIM1_CNTRL = 0; //Reset counter
  TIM1_IER = 0; //Interrupt disabled
  TIM1_SR1 = 0; //Clear Interrupt
  TIM1_CCMR2 |= 1<<0; //External pulse source T1C2
  TIM1_CCER1 |= ~(1<<5); //Rising edge
  TIM1_SMCR |= 3; //T1C2 input
  TIM1_CR1 |= ~(1<<0); //Counter disabled
 
  return;
}

void set_counter_enable(uint8_t enable){
  if(enable==1)
    TIM1_CR1 |= 1<<0;
  else
    TIM1_CR1 |= ~(1<<0);

  return;
}

void set_counter_updown(uint8_t updown){
  if(updown==1)
    TIM1_CR1 |= ~(1<<4);
  else
    TIM1_CR1 |= 1<<4;

  return;
}

uint8_t start_movement_monitor(uint8_t dir){

  while(1){
    if(dir == 1){
      if(((TIM1_CNTRH<<8)+TIM1_CNTRL)>200)
        return 1;
    }else if(dir == 2){
      if(((TIM1_CNTRH<<8)+TIM1_CNTRL)<50)
        return 1;
    }
    else{
      return 1;
    }
  }

  return 1;
}


int main() {

  config_gpio();
  config_counter();
  set_counter_updown(0);
  set_counter_enable(0);

  set_counter_enable(1);
  set_motor_enable(1);
  set_motor_movement(1);

  start_movement_monitor(1);

  set_motor_movement(0);
  set_motor_enable(0);
  set_counter_enable(0);
  return 0;
}