"Coding Badly" suggested in another post that I "post questions" when I mentioned that I was having trouble with capture feature. So...
Why does this only return "0"s?
// Capture servo PWM on pin 48 (ICP5 input) using timer 5 capture register ICR5
word cap_first;
word cap_second;
word cap_cycles;
void setup(){
Serial.begin(9600);
TCCR5A = 0x00; // Normal counting mode
TCCR5B = 0x01; // Turn Timer5 ON - no prescaling
TCCR5B |= (1<<ICES5); // Looking for high
while (!digitalRead(48)); // Wait for high
}
void loop(){
cap_first = ICR5; // Capture high time stamp
TCCR5B |= (0<<ICES5); // Change to looking for low
while (digitalRead(48)); // Wait until PWM goes low
cap_second = ICR5; // Capture low time stamp
TCCR5B |= (1<<ICES5); // Change to look for high
cap_cycles = cap_second - cap_first;
Serial.println(cap_cycles);
while (!digitalRead(48)); // wait until PWM goes high
}
My bad.... I was setting bit 5, not bit 6 of TCCR5B. Doah!
I changed the code to this and I'm now getting data. I really don't understand C++, especially bit manipulation.
This is working:
word cap_first; // First captured time
word cap_second; // Second captured time
word cap_cycles; // Working PWM time variable
void setup(){ // Setup function
Serial.begin(9600);
TCCR5A = 0x00; // Normal counting mode
TCCR5B = B01000001; // Timer on, PS/8, rising edge
while (digitalRead(48));
while (!digitalRead(48)); // Wait for high
}
void loop(){ // Looping function
cap_first = ICR5; // Capture high time stamp
//TCCR5B = B00000001; // Old way to: Change to looking for low
TCCR5B ^= (1<<6); // Change to looking for low (toggle ES bit)
while (digitalRead(48)); // Wait until PWM goes low
cap_second = ICR5; // Capture low time stamp
//TCCR5B = B01000001; // Old way to : Change to look for high
TCCR5B ^= (1<<6); // Change to looking for low (toggle ES bit)
cap_cycles = cap_second - cap_first; // Calculate cycles passed
cap_cycles = map(cap_cycles, 16000, 32000, 1000, 2000); // Map to 1000 to 2000
Serial.println(cap_cycles); // Debug
while (!digitalRead(48)); // wait until PWM goes high
EDIT: Ok, I think I see:
TCCR5B ^= (1<<ICES6); // Is the same as isolating bit 6 and flipping it. (ICES6 = "6")
(ICES6 is not defined, though I could, but I just use "6")
ICES5 equates to "5" somewhere in the device files.
I'm still not sure what this does:
TCCR5B &= ~(1<<ICES5); // is this the same as?: TCCR5B AND (NOT TCCR5B(bit 5))?