For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle).
I looked into interrupts and learned about them that there are 2 types of interrupts in Arduino namely "external", and "pin change". So i downloaded the "PinChangeInt Library" to test it. I wrote a small test program where a PWM of 62.5kHz is being generated on pin3, and i am calling rising and falling edge triggered interrupts on this pin, i.e to display one value when rising edge occurs, and other value when falling edge occurs. My code looks like following:
#include <PinChangeInt.h>
#define pw 3
int pwm;
void setup() {
// put your setup code here, to run once:
pinMode(pw, OUTPUT) ;
pwm_setup(); // Set PWM to a frequency of 62.5kHz
PCintPort::attachInterrupt(pw,rise,RISING); // call void rise() when PWM is HIGH
PCintPort::attachInterrupt(pw,fall,FALLING); // call void fall() when PWM is LOW
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
pwm = 127; // 50% duty cycle
pwm_on(pwm);
}
void pwm_setup()
{
TCCR2A = 0x23 ;
TCCR2B = 0x09 ; // mode 7, clock prescale by 1
OCR2A = 256-1 ; // 256 clock periods = 16us per cycle
OCR2B =0 ;
TCNT2 =0 ;
}
void pwm_on(double)
{
OCR2B = pwm ;
}
void rise()
{
Serial.println("RISE");
}
void fall()
{
Serial.println("fall");
}
But it is not working the way i think it should. It keeps on displaying "fall" every time, whereas according to me it should display "RISE" and "fall" alternatively, right ? However if i remove the "PCintPort::attachInterrupt(pw,fall,FALLING); " line, it starts to display "RISE" as it is supposed to.
Since its my first time programming with Arduino, and i am just a beginning level programmer, i might be making some stupid mistake here. So can anyone point it out please ?
Your helpful comments and suggestions would be appreciated. Thankyou!