读取Atmega8 16位计数器始终返回8位值

时间:2014-03-23 21:32:57

标签: arduino avr

我正在尝试阅读Atmega8的16位计数器,但输出永远不会> 255. Atmega8配置为Arduino。我知道它必须一次读取8位,但它似乎并没有起作用。查看readCounder()函数中的代码和Serial.println的输出。

#include <Arduino.h>
#include <avr/io.h>
#include <string.h>

#define IN_BUF_LEN 65
#define OUT_BUF_LEN 128

// Pin 13 has an LED connected
int pinLed = 13;

char cmdBuf[IN_BUF_LEN];
char outBuf[128];

char *token;

void readCounter(){

  uint8_t count1, count2;
  uint16_t count;

  /* Disable interrupts */
  noInterrupts();

  count = TCNT1;

  count1 = TCNT1H;
  count2 = TCNT1L;  

  // enable interrupts
  interrupts();

  snprintf(outBuf, OUT_BUF_LEN, "Count:%d, %d, %d", count,count1,count2);
  Serial.println(outBuf);
}

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(pinLed, OUTPUT);
  Serial.begin(19200);

  // Turn on the counter, Clock on Rise
  TCCR1B |= (1 << CS12) | (1 << CS11) | (1 << CS10);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(pinLed, HIGH);
  delay(50);
  digitalWrite(pinLed, LOW);

  int bytesRead = Serial.readBytesUntil(10, cmdBuf, IN_BUF_LEN - 1);
  cmdBuf[bytesRead] = 0;

  if (bytesRead > 0){
    token = strtok(cmdBuf, " ");

    if(!strcasecmp(token, "readCounter")){
      readCounter();
    }
  }

}

当调用readCounter()时,Serial.println通常输出:

Count:30, 0, 30
Count:130, 0, 130
Count:250, 0, 250
Count:236, 0, 236
Count:72, 0, 72

1 个答案:

答案 0 :(得分:0)

验证TCCR1ATCCR1B的值,以确保定时器1不处于8位模式,例如8位PWM或CTC,TOP值小于256。