How to add variable for prescale_factor to wiring.h

Dear all,

I want to adjust the precale factor on Timer0. Using Arduino Playground - TimerPWMCheatsheet I find I can do this with:

In the beginning of wiring.c you can find:
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

You need to modify the prescale factor in this function to the corresponding line

For fast PWM (default):
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(PRESCALE_FACTOR* 256))
For phase-correct PWM :
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(PRESCALE_FACTOR * 510))

What I would like to do is replace PRESCALE_FACTOR with a global variable in the appropriate core file, so I can change this value in my sketch if I change the prescaler there. The variable needs to have a default value of 64. I tried to replace it with an unsigned long variable, but no matter where I put the variable (wiring.c, wiring_private.h, arduino.h) I get errors the variable has multiple defines.

I would like to change the prescaler to 1, because I need the extra PWM on pin 5. I realize the timer ISR will be called much more often (64 times I guess), I hope that doesn't intrude too much.

Any tips how to tackle this are welcome.

Cheers,

Jack

I tried to replace it with an unsigned long variable, but no matter where I put the variable (wiring.c, wiring_private.h, arduino.h) I get errors the variable has multiple defines.

If you want to use a global variable, the variable has to be declared in the sketch. The library (or libraries) then need to be told that the value is extern to them.

Ah I see, might it be a better idea to declare a variable in the library and set it with a global function?

CaptainJack:
Ah I see, might it be a better idea to declare a variable in the library and set it with a global function?

That certainly seems like a better approach. That way, it can have a default value that matches the standard value, unless the sketch changes it.

The only challenge I can see is making sure that the value is changed BEFORE any code that needs it defined is executed.

Well, that would be the case I guess. I wanted to see if I could use PWM on timer 0 (pin 5 I believe) while still maintaining millis() and such. It sort of seems to work, but I need to change the prescaler for my project. So I would adapt the prescaler with TCCR0B, and set the prescaler variable with a function. There might be a small glitch in the millis() function, but that won't be a problem.

I'll try this weekend, thanks for your input !