please anyone help me understanding each line of this code.
this code is a part of arduino mppt solar charge controller
void perturb(boolean init=false)
{
static byte pulseWidth = 0;
static boolean trackDirection = false; //counts down / pwm increases
// static int loopCounter = 0;
if (init)
{
pulseWidth = 255;
trackDirection = false;
}
else
{
if (!trackDirection)
{
if (pulseWidth != 0)
{
pulseWidth--;
}
else
{
trackDirection = true;
}
}
else
{
if (pulseWidth != 255)
{
pulseWidth++;
}
else
{
trackDirection = false;
}
}
}
pwmWrite(3, pulseWidth); //write perturbed PWM value to PWM hardware
if ((panelWatts - lastPanelWatts) < -0.1)
trackDirection = !trackDirection;
}
In the first line boolean init is assigned a value. the there is a if statement with test condition initif(init) How and when this loop is executed?[/li]
To help you understand something, we must first explore what it is you don't understand.
void perturb(boolean init=false)
{
This defines a void function, taking one boolean argument called "init", which is defaulted to false.
So, if you call perturb with no argument, the compiler will provide a default argument.
A ‘boolean’ variable, like ‘init’, can contain either ‘false’ (0) or ‘true’ (1). Other data types, when used in a boolean expression like in an ‘if’ or ‘while’, evaluate to ‘false’ if they are 0 and ‘true’ if they are not 0. The constant ‘false’ is defined to be 0 and the constant ‘true’ is defined to be 1. In the Arduino libraries, HIGH is defined as 1 and LOW is defined as 0. It is safe to compare against 0/false/LOW in a boolean expression but not safe to compare against 1/true/HIGH since 1 is not the only value that evaluates to ‘true’. For example:
int variable = 10;
if (variable) This executes because variable is != 0
if (variable != false) This executes because variable is != 0
if (variable == true) This DOES NOT execute because 10 != 1
OP: the function is defined with a default argument. If you explicitly pass an agrgument like peterub(true), then the if will get executed.
Everyone else: the init parameter does not appear to intended to be the result of a digital read. It appears to be intended to be used something like so: