I have solved my problem, but am looking for a pointer to the relevant part of the documentation.
I am planning to use an Elegoo Mega2650 board to drive ( amongst other things) the leadscrew motor for a micro lathe. The motor is a 100rpm 12v DC brushless geared motor. It has an open collector pulse signal to give speed feedback. As it's 1:60 geared, and 9 pulses/rev of the basic motor; counting the pulses in 1 second and dividing by 9 gives the output shaft rpm.
I only need to know the speed each second (900 pulses at full speed) so I have wired the pulse output to pin 47 on the Mega 2560 and am using timer 5 to count the pulses. The program loops once per second (approx.) using delay (1000).
I am setting up the counter by setting
byte FGpulsepin = 47;
pinMode (FGpulsepin, INPUT_PULLUP); //input pin for timer
TCCR5A = B00000000; //Ensure normal mode
TCCR5B = TCCR5B & B11111000 | B10000111 ; //clock timer 5 on external rising edge for speed pulses high bit enables noise suppressio
and reading the data by
// check the leadscrew motor speed
thismillisec = millis(); // time now - may overflow after 50 days running!!
t5count = TCNT5; //grab the count
TCNT5 = 0; //reset to zero
elapsed = thismillisec - lastmillisec;
lsrpm = (t5count * (111 / elapsed)); // calculate speed
lastmillisec = thismillisec; //remember the time
dtostrf(lsrpm, 5, 1, lsrpmstring); //output shaft speed to one decimal place for display
According to the documentation (Atmel datasheet page 154), the default for TCCR5A is B00000000.
However unless I explicitly set TCCR5A to all zeros as above, the counter behaves as if it were an 8 bit counter and rolls over after 256 pulses. Explicitly reading TCNT5H always returns zero.
Explicitly setting TCCR5A to all zeros makes the timer work as documented.
I appreciate that being explicit is a good idea, but I am wondering if I have missed something somewhere else in the detailed documentation that defines the 8 bit behaviour, or is setting pinMode switching the mode of the counter behind the pin?
Can anyone with more expertise give me a pointer as to where I should look, and are there any other timer registers I need to be setting explicitly?
Thanks in advance.