micros() and delay() function on timer1

Hey there,

I am working on a project, using an Arduino Uno.

I am using timer 0 and 2 to generate a PWM signal and this works fine.

I need to use the timing functions such as delay() and micros(). I understand these are controlled by timer 0 and that why they are not working properly now. I would like to use timer1 to handle this functionality, I have taken a look at:

C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino\wiring.c

As this is where the timing functions are implemented, but I just can’t get it to work.

Here is where I am so far, I would really appreciate any help you can give.

volatile unsigned long timer1_overflow_count = 0;

unsigned long myMicros() {
unsigned long m;
TCCR1B |= (1 << CS11) | (1<<CS10); //Prescaler 24
uint8_t oldSREG = SREG, t; //SREG - AVR Status register - I bit 7 (MSB - LSB), t is getting assigned as u8
uint16_t t;
cli(); // Clear interrupts - interrupts are blocked

m = timer1_overflow_count; //Hold the overflow count

#if defined(TCNT1)
t = TCNT1; // Timer/Counter Register - Holds the count
#elif defined(TCNT1L)
t = TCNT1L; // Not used
#else
#error TIMER 0 not defined
#endif

if ((TIFR1 & _BV(TOV1)) && (t < 65535)) //TOV0 - Timer/counter overflow flag - if overflow flag raised
m++; //count everytime it over flows

SREG = oldSREG; //Reset the overflow flag by setting SREG to starting value if it has been raised if not will do nothing

return ((m << 16) + t) * (64 / 16);

}

You do not need to use delay() and you should not use it.

Why are you not using the standard analogWrite() function to generate your PWM signal?

...R

timer0 is set to use 8 bit fast PWM mode so it counts 0,1,2,...,254,255,0,1,2,... timer1 and 2 are set to 8 bit phase-correct PWM mode so they count 0,1,2,...,254,255,254,...,2,1,0,1,2,...,254,255,254,...

You will need to address difference this to get timer1 to mimic the standard timer0 set-up.

Why not use timer 1 to generate the PWM signal, then your problem goes away.

Hi all,

Thanks for your responses.

Robin 2 - I am not using analogWrite as I found it slow

MarkT - Thanks for this advice I will try it out and let you know

Nick Gammon - I am using the 2 8bit timers, as I was planning to use the 16bit timer for something else. My question is a small part of my project.

Again thank you for your responses

-K

kr121: I am not using analogWrite as I found it slow

I'm curious. What are you trying to do that it can't keep up with?

...R