Dear GGE5
Thanks. This code worked well for me. Thanks for sharing.
GGE5:
I modified your code a bit to work. I had to set the pinMode of 9 to output before anything else. I had to erase your line setting TCCR4C because there is no Timer4 on my ATMEGA328 (and it was throwing an error), but also because TCCRxC is only active in non-PWM modes.Also, when using C code, you don't have to set the HIGH and LOW registers separately, as the compiler takes care of that for you.
Here is the working code:
//12-Bit PWM on PIN9 using direct access to Timer1
//Fade in and out an LED connected to that pin
#define LEDValue OCR1A
const int PWMMax = 4095;
int value = 1;
int direction = 1;
void setup() {
pinMode(9,OUTPUT);
TCCR1A = (1 << COM1A1) | (1 << WGM11); // Enable Fast PWM on OC1A (Pin 9)
TCCR1B = (1 << WGM13) | (1 << WGM12) | (1 << CS10); // Mode 14 Fast PWM/ (TOP = ICR1), pre-scale = 1
ICR1 = PWMMax; //Set the TOP value for 12-bit PWM
LEDValue = 0; //Set the PWM output to full off.
}
void loop() {
//Fade the LED between 0 and PWMMax and then back to 0
value += direction;
if (value <=0){
direction = 1;
}
else if (value >= PWMMax){
direction = -1;
}
LEDValue = value;
delay(1);
}
Thank you so much for your help!