The only way to measure current with an arduino is to have the current path going through a small resistor just before ground. then you need to connect this resistor to the analogue input. However because you have a PWM signal you first need to filter it with an R&C before the analogue input. This will give you the average current.
To measure the peak current you need to synchronise your sampling to the PWM signal. This is something that is not easy to do in the arduino environment.
I think I understand. You want to measure the current being consumed on demand? you'll use an interupt to trigger the reading of the current? But are concerned that when the interupt is triggered, the normal execution flow will be interupting, interfering with your PWM output?
my question was how i can program it correct in my arduino so it is able to control the dutycycle of my PWM to get a lower Amps
Well that might have been the question in your head but it is not what you asked.
Changing the duty cycle is as easy as doing an analogWrite() to the digital pin.
I don't see why you need to measure your current sensor in an ISR. Simply as part of the main loop do the measurement and adjust the value you write to the port.
You could use a "huf and puff" algorithm. That is where you measure it and if it is too low you increase the analogue write value by one, if it is too high you decrease it by one. So eventually it will give the right value. This removes the need for any calibration between the sensor reading and the value you write.
i used the following code for my arduino and it works.
made it my self :)
/*
* Timer1 library example
* June 2010 Made by ionotos (Whit the help of other arduino programs, sampels and forums.)
*/
include "TimerOne.h"
long dutycycle=512; //set dutycycle to 50%
float IAverage=2.0;
int currentsensor_Pin = 0; //analog in put pin = 0
void setup()
{
Serial.begin(9600);
pinMode(10, OUTPUT);
Timer1.initialize(10000); // initialize timer1, and set a 1/2 second period
Timer1.pwm(9, dutycycle); // setup pwm on pin 9, 50% duty cycle
Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt
}
void callback()
{
float i=(30.0/512.0)*(analogRead(currentsensor_Pin)-512.0); //meaking measurements from current sensor more accurate
dutycycle=1024.0*IAverage/i; //making the new dutycycle
if (dutycycle>1024)dutycycle=1024; //dutycycle can't go above 1024.
Timer1.pwm(9, dutycycle); // setup pwm on pin 9, 50% duty cycle
}
void loop()
{
int incomingbyte;
incomingbyte=Serial.read();
switch(incomingbyte){
case '+': {
IAverage+=0.1;
Serial.print(IAverage);
Serial.print(" ");
Serial.println(dutycycle);
}
break;
case '-': {
IAverage-=0.1;
Serial.print(IAverage);
Serial.print(" ");
Serial.println(dutycycle);
}
break;
}