Interruption and PWM

Hi:

I’m trying to send the result of an operation involving an interruption to the PIN9 as PWM. For some reason is not writing the PWM, see the code below:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <Wire.h>

int AnalogPin=0;
int Vi=0;

void setup(){
  Serial.begin(9600);
  Wire.begin();
  //digitalWrite(2,HIGH);
  cli();
  TCCR1A=0;
  TCCR1B=0;
  OCR1A=1561;
  TCCR1B |= (1<<WGM12);
  TCCR1B |= (1<<CS10);
  TCCR1B |= (0<<CS11);
  TCCR1B |= (1<<CS12);
  TIMSK1=(1<<OCIE1A);
  sei();
  
}

void loop(){
  
  double X1 = Vi*(0.004887585);
//  double NODO = 2.096*X1;
  
  double X2=(X1*255)/5.08;
  
  analogWrite(9, X2);
  
Serial.println(X2);
  
}

ISR(TIMER1_COMPA_vect){
  Vi=analogRead(AnalogPin);
  
}

I’m watching the value of X2 in the serial window and everything seems to be fine, the problem is the analogWrite, for some reason is not “wrting the value”

What could be the problem?

Thanks in advance!

Variables shared by an ISR should be declared volatile.

http://gammon.com.au/interrupts

Thanks for the reply. I already changed the variable to volatile but doesnt work yet, what could be wrong?

Analog write only takes a byte , that is from 0 to 255, you are feeding it with a float.

How are you checking that it is not producing anything, are you using a scope? Or a filter feeding into a multimeter?

ISR can't have parameters!

The float will be cast to "byte" so should not be an issue.

Suggest you drop the use of avr.io and avr/interrupt and use the methods from the reference.

Mark

Grumpy_Mike: Analog write only takes a byte , that is from 0 to 255, you are feeding it with a float.

How are you checking that it is not producing anything, are you using a scope? Or a filter feeding into a multimeter?

Indeed, Im using a multimeter to read the output voltage.

Can you post your modified code, please? Also post what you are seeing in the serial monitor.

Thanks for the help! I already figured out whats wrong. I found the answe on a blog and was exactly what was happening to me:

I've been using this tutorial to set up my interrupts for a few times. It's been working great until today. I set timer1 at 2.5khz to perform the interrupt. Mainly use it as a clock and serial reading from the console. The problem is that when I use timer1, PWM on pin 9 and 10 is dead. Pin 9 is the worst one, if I try to use it as analogWrite, arduino will stall. If I use pin 10, arduino will ignore any analogWrite request. It doesn't affect pin 3 and 5. however, if I use timer0, i think it was pin 11 and 3 will be affected in the same way.

For some reason timer1 and pwm on pin 9 doesnt work!!!

For some reason timer1 and pwm on pin 9 doesnt work!!!

No supprise, PWM is driven by the timers, two pins per timer fixed in the hardware. So if you use the timer for something else then you can't use the PWM function.

Thanks for the info! I didnt have the least idea about that!