Skip to content

Commit

Permalink
Set timer2 for DCC's 58us cycle period.
Browse files Browse the repository at this point in the history
  • Loading branch information
Marty committed Oct 2, 2010
1 parent a71300c commit a5e1257
Showing 1 changed file with 34 additions and 13 deletions.
47 changes: 34 additions & 13 deletions src/timer2_dcc_gen/timer2_dcc_gen.pde
Original file line number Diff line number Diff line change
Expand Up @@ -18,37 +18,58 @@ unsigned int mycount = 0;

void setup() {

// Enable Timer2
OCR2A = timer2_target;
bitSet(TCCR2B, CS22);
bitSet(TCCR2B, CS21);
bitSet(TCCR2B, CS20);
// Setup Timer2
configure_for_dcc_timing();

pinMode(13,OUTPUT);
pinMode(9,OUTPUT);
pinMode(12,OUTPUT);

digitalWrite(9,LOW);
// Enable Timer2 interrupt
bitSet(TIMSK2, OCIE2A);
sei();

sei(); // Enable interrupts
}


ISR( TIMER2_COMPA_vect ){
mycount += 1;

if( mycount == 2 ) {
if( (mycount & 1 ) == HIGH ) {
LED_OFF();
LED1_ON();
} else if (mycount == 4 ) {
} else {
LED_ON();
LED1_OFF();
mycount = 0;
}
TCNT2 = 0;

TCNT2 = 0; // Reset Timer2 counter to divide...

};

void configure_for_dcc_timing() {

/* DCC timing requires that the data toggles every 58us
for a '1'. So, we set up timer2 to fire an interrupt every
58us, and we'll change the output in the interrupt service
routine.
Prescaler: set to divide-by-8 (B'010)
Compare target: 58us / ( 1 / ( 16MHz/8) ) = 116
*/

byte timer2_target = 114; // remember off-by-one -> count starts at 0

// Set prescaler to div-by-8
bitClear(TCCR2B, CS22);
bitSet(TCCR2B, CS21);
bitClear(TCCR2B, CS20);

// Set counter target
OCR2A = timer2_target;

// Enable Timer2 interrupt
bitSet(TIMSK2, OCIE2A);
}


void loop(){
}
Expand Down

0 comments on commit a5e1257

Please sign in to comment.