Use Timer2 to control DC motor

Forum Members, (Robin and Nick)
I hope this is not a double post.
I have seen the post on the Gammon website for the
freq counter. I need to use (or try to use) timer2 to generate an interrupt (I can get this to work),
that will send a pwm pulse (aka analogWrite(PWMpin,PWM_val) to the motor driver - in this case
it uses Arduino pin 9.

I can get this to work using a delay(myTime) statement. I thought it might be more efficient to use
a timer interrupt via timer2. I am using a pin change interrupt for the encoder - this works fine (and the PID library, etc).

I start the code for timer2 using a button push and a function (start_timer2()).
I can start the timer, and detect “counts” from the CTC, I want to send the analogWrite statemment,
say every 2 seconds (for testing). I count interrupts, but cannot seem to get the motor to move.

Here is the timer 2 code I am currently trying to use:
// start timer for step mode
void start_timer2()
{
seconds = 0;
// INITIALIZE TIMER INTERRUPTS
cli(); // disable global interrupts
TCCR2A = 0; // set entire TCCR2A register to 0
TCCR2B = 0; // same for TCCR2B

TCCR2A |= (1 << WGM22);
OCR2A = 254; // for counting to max val for Timer 2, could cont microSecs if need be.

// Reset prescalers
GTCCR = bit (PSRASY); // reset prescaler now (from Nick Gammon)

TCCR2B |= (1 << CS20); // Set CS20 and CS22 bits for 1024 prescaler,256 12=1 10 = 0
TCCR2B |= (1 << CS21); // prescale for 128 is 101, and starts the timer!
TCCR2B |= (1 << CS22);

timer2_counter = 0;
TCNT2 = timer2_counter; // preload timer
// TIMSK2 |= (1 << TOIE2); // enable timer overflow interrupt for timer 2
TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
sei(); // enable global interrupts

// RUN THE MOTOR SOME HOW!
} // end start_timer2

// timer interruppte
ISR(TIMER2_COMPA_vect)
{
seconds++;
// count these, and scale timing down to “send analogWrite(using encoder counts) every two seconds”
}

My main program start the timer with a button push - the idea is to move motor, stop, move motor again every 2 seconds (or whatever time I select.)

I do notice when I push a button to select motor direction (CW or CCW) - it stops the counts from the timer2 interrupt.

Any suggestions?

Thanks,
ewholz

ewholz:
I need to use (or try to use) timer2 to generate an interrupt (I can get this to work),
that will send a pwm pulse (aka analogWrite(PWMpin,PWM_val) to the motor driver

Do you literally mean that you want a timer interrupt to call some code that uses the analogWrite() function?

I can't imagine why it would be necessary to start analogWrite() at such a precise instant in time that an interrupt is needed.

Perhaps you can explain what you are trying to achieve?

...R