I have a PWM signal input on an interrupt pin on an Arduino Pro Micro.
This is my code:
#define SW_PIN 6
#define OUT_PIN 9
#define PWM_IN_PIN 7
#define PWM_MAX 799
#define PWM_MIN 0
#define PERIOD 2000 //in uS for 1kHz
volatile int pwm_value = 0;
volatile int prev_time = 0;
int interruptPin;
void setup() {
interruptPin = digitalPinToInterrupt(PWM_IN_PIN);
pinMode(OUT_PIN, OUTPUT);
pinMode(SW_PIN, INPUT_PULLUP);
pinMode (PWM_IN_PIN, INPUT);
attachInterrupt(interruptPin, rising, RISING);
Serial.begin(9600);
TCCR1A = 0;
TCCR1B = 0;
TCCR1A = bit (COM1A1) | bit (WGM11);
TCCR1B = bit (WGM13) | bit (WGM12) | bit (CS10);
ICR1 = PWM_MAX; //sets to 20kHz
OCR1A = 0; // Set this to change duty cycle
}
void rising() {
attachInterrupt(interruptPin, falling, FALLING);
prev_time = micros();
}
void falling() {
attachInterrupt(interruptPin, rising, RISING);
int tmp = micros()-prev_time; //HERE
Serial.println(tmp);
tmp = (int)((float)tmp/PERIOD*PWM_MAX);
if(tmp < PWM_MIN || tmp > PWM_MAX){
tmp = 0;
}
pwm_value = tmp;
}
void loop() {
Serial.println(micros()-prev_time); //AND HERE
OCR1A = pwm_value;
analogWrite(OUT_PIN, pwm_value);
}
The volatile variable prev_time is updated by the interrupt function rising() and reading it in falling() works as expected. However, reading it in the main loop doesn't. It's not updating. Why is this?
Times should be unsigned long, aka uint32_t.
These variables cannot be accessed atomically on the eight bit AVRs and should be copied in a critical section in non-interrupt context
Don't do serial I/O in interrupt context.
Thanks. How would i create a critical section?
Just with noInterrupts() and interrupts()? Would that make me miss PWM cycles?
The serial I/O was just for debugging to check that i'm not going crazy.
'CHANGE' will work just fine if your first check when entering the interrupt is the 'pinstate' If that is HIGH then it was rising and do what is appropriate and if it is LOW idem.
I think that loop is not updating tmp_time fast enough since the value rises over time.
Also, I'm not using the critical section for the pwm_value and it's read just fine?
What i'm really trying to do here is check if the PWM went to 0 ie. more than PERIOD time has passed since last interrupt. Could i make a workaround for this?
That is unfortunate, Well i guess in that case the Serial prints may be disturbing the measurements. How about you store a few of them in an array, and print those out in one go. Also you may try a higher baud-rate.
Well i guess in that case the Serial prints may be disturbing the measurements.
The measurement is fine since i'm getting correct values in pwm_value. But when i copy prev_time into main loop it does weird stuff. My only explanation so far is black magic. But more likely something is messing with timings.