Go Down

Topic: need a global variable defined that constantly changes (Read 259 times) previous topic - next topic

eddiea6987

ok i have a feeling this might be simple but i cannot get my head around it
i am trying to make a simple pwm file which , for learning purposes will only use the 8 bit timer
along with PIN D6 (OCOA)...the code for that looks like thislooks like this
Code: [Select]

#ifndef fastPWM
#define fastPWM

void iniPWM()
{
TCCR0A |= ((1<<COM0A1) | (1<<WGM01) | (1<<WGM00)) ; //set to use pin d6 and set to fast pwm
TCCR0B |= ((1<<CS02) | (1<<CS00)) ; //set the prescaler
TIMSK0 |= ((1<<TOIE0));// set timer overflow interrupt .. not sure if its is propper to use interrupts in files outside of main program
}

void startPWM (  )
{
   
OCR0A  =((pulseWidth / 100) * 255.0); // set  output compare to a percentage of 255
}


ISR (TIMER0_OVF_vect)
{
OCR0A  =((pulseWidth / 100) * 255.0); //after the first interrupt this should just keep going and going

}

#endif


now my problem is i need to pass a pulsewidth in my main code if i use #define pulsewidth then i cant change the pulse width
and if  i use a regular deffinition then its not seen by the pwm library...
my main code looks like this
Code: [Select]

#define F_CPU 16000000L
#include <avr/io.h>
#include <eddie/fastPWM.h>
#include <avr/interrupt.h>
int pulseWidth = 50;  // <--here is the problem
int main(void)
{
sei();
iniPWM();

    while(1)
    {
       
startPWM();

    }
}


i know  i can set the start pwm function to accept a parameter but then how do i  get the ISR routine to also see that parameter if ISR accepts no parameters , only way would be to have a global variable , but then i cant change it....feels like a catch 22 , but im sure its just lack of knowledge..
can anyone enlighten me

furthermore is malpractice to use interrupts inside a .h file?
i know .h files are for definitions only , i will soon be attempting to learn about libraries . i just want to test  out what can be done in an .h file
I could print the Arduino logo on a box of cereal and sell it as "Arduin-O's"

Nick Gammon

Quote

only way would be to have a global variable , but then i cant change it....feels like a catch 22 , but im sure its just lack of knowledge..


Why can't you change it? If it can't be changed, it's not a variable, right?

However you might want to make it volatile:

Code: [Select]

volatile int pulseWidth = 50;  


Quote
furthermore is malpractice to use interrupts inside a .h file?


Definitely, you will be hearing from my lawyers. :P

You should use .h files for declarations, and .cpp files for code.
Please post technical questions on the forum, not by personal message. Thanks!

More info:
http://www.gammon.com.au/electronics

Go Up