cancel
Showing results for 
Search instead for 
Did you mean: 

How to implement micros() function on stm8s003?

carlogulliani
Associate III

I need to decode ASK/OOK signal, for this aim I need to know the period in microseconds between several edges. I decided to use TIM1 for this purpose, here is my code

    // Set fCPU = 16MHz
    CLK_CKDIVR = 0;
    CLK_PCKENR1 = 0xFF;
    CLK_PCKENR2 = 0;
 
uint16_t micros() {
    return (uint16_t) ((TIM1_CNTRH << 8) | TIM1_CNTRL);
}
 
void tim1_init(void) {
    // 1MHz = 1uS
    TIM1_PSCRH = 0x00;
    TIM1_PSCRL = 0x10;
 
    TIM1_IER = 0x00; // disable interrupts
    TIM1_CR1 = 0x01;
}

and to get signal I use

ISR_PORTD(handlerD) {
	state = PinRead(GD0_PORT, GD0_PIN);
  uint16_t m = micros();
  if (state == HIGH) {
    lolen = abs(m - prevtime);
  }
  else {
    hilen = abs(m - prevtime);
  }
  prevtime = abs(m);
  if (state == HIGH)
  {
    if (flag == 0) {
      // the end of packet
      if (CheckValue(Pe, hilen) && CheckValue(Pe2, lolen)) // valid 1
      {
        if (bcounter < 32)
          code1 = (code1 << 1) | 1;
        else if (bcounter < 64)
          code2 = (code2 << 1) | 1;
        bcounter++;
      }
      else if (CheckValue(Pe2, hilen) && CheckValue(Pe, lolen)) // valid 0
      {
        if (bcounter < 32)
          code1 = (code1 << 1) | 0;
        else if (bcounter < 64)
          code2 = (code2 << 1) | 0; bcounter++;
      }
      else
        bcounter = 0;
    }
    else {
      if (bcounter < 32)
          code1 = (code1 << 1) | 1;
        else if (bcounter < 64)
          code2 = (code2 << 1) | 1;
        bcounter++;
    }
  }
  //printf("bcounter: %d\r\n", bcounter);
  if (bcounter >= 65)
  {
    printf("Got: %x %x\r\n", code1, code2);
    Pe2 = lolen;
    Pe = hilen;
    flag = 1;
    bcounter = 0;
    code1 = 0;
    code2 = 0;
  }
}

but get the values not I expected

0 REPLIES 0