0

我有一个关于如何读取 RPM 并使用串行发送值的问题这是我的代码:

char init(void)
{
  UBRRH=(uint8_t) (UBRR_CALC>>8);
  UBRRL=(uint8_t) UBRR_CALC;
  UCSRB=(1<<RXEN)|(1<<TXEN);
  UCSRC=(1<<URSEL)|(3<<UCSZ0);
  return 0;
}

void send(unsigned char x)
{
  while(!(UCSRA&(1<<UDRE))){}
  UDR=x;
}

void sendstring(char *s)
{
  while(*s)
  {
    send(*s);
    s++;
  }
}

volatile uint16_t count=0;    //Main revolution counter   
volatile uint16_t rps=0;    //Revolution per second

void Wait()
{
  uint8_t i;

  for(i=0;i<2;i++)
  {
    _delay_loop_2(0);
  }
}

int main(void)
{
  Wait();
  Wait();
  Wait();
  Wait();

  //Init INT0
  MCUCR|=(1<<ISC01);   //Falling edge on INT0 triggers interrupt.
  GICR|=(1<<INT0);  //Enable INT0 interrupt

  //Timer1 is used as 1 sec time base
  //Timer Clock = 1/1024 of sys clock
  //Mode = CTC (Clear Timer On Compare)
  TCCR1B|=((1<<WGM12)|(1<<CS12)|(1<<CS10));

  //Compare value=976
  OCR1A=976;
  TIMSK|=(1<<OCIE1A);  //Output compare 1A interrupt enable

  //Enable interrupts globaly
  sei();

  while(1)
  {
  }
}

ISR(INT0_vect)
{
  //CPU Jumps here automatically when INT0 pin detect a falling edge
  count++;
}

ISR(TIMER1_COMPA_vect)
{
  //CPU Jumps here every 1 sec exactly!
  rps=count;
  send(rps);
  count=0;
}

我们可以在中断计数器和定时器时发送串行数据吗,我尝试时出错?

什么是读取 RPM 并使用串行发送值的最佳方法

4

1 回答 1

0

一个潜在的问题是 rps 被定义为 int16_t 并且您的发送例程需要一个无符号字符。

0-255 的范围对于您的 RPS 是否足够高?

您希望 RPS 具有人类可读性,还是要将其发送到另一台计算机或微控制器?

可以在您的中断例程中发送串行,但您需要小心,因为串行例程通常不是可重入的。

于 2016-01-01T16:19:11.740 回答