Question

I am trying to read the Atmega8's 16-bit counter, but the output is never > 255. The Atmega8 is configured as an Arduino. I know it has to be read 8-bits at a time, but it doesn't seem to be working. Look at the code in readCounder() function, and the output from 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();
    }
  }

}

When readCounter() is called, Serial.println typically outputs:

Count:30, 0, 30
Count:130, 0, 130
Count:250, 0, 250
Count:236, 0, 236
Count:72, 0, 72
Était-ce utile?

La solution

Verify the values of TCCR1A and TCCR1B to make sure timer 1 isn't in a 8-bit mode such as 8-bit PWM or CTC with a TOP value less than 256.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top