Control Fans and output voltage of Power Supply via PWM, please check my code

Thanks for helping.
If, during testing, I should get the feeling that there are problems because of the lowish input resolution, I will get back to you. :slight_smile:

Meanwhile, I have improved the code a little.
First problem was that I got an output not in the range of 0 to 255 for the analog pins, which is not admissable, I think.

Instead of assigning a value to the analog Pins directly, I now work with variables. At the end of the computations, the variables are checked if they are in the range of 0 to 255, and if not, they are brought to that range.
<0 -->0

255 -->255

Concerning the oscillations, I have abandoned the idea of defining a range in which the voltage is regulated according to the current.

I have defined a max treshold (150A), over which the voltage is reduced quickly with each computing cycle. The whole range (255 to 0) would be covered in 5sec.
I have also defined a min treshold (140A), under which the voltage is increased slowly with each computing cycle. The whole range (0 to 255) would be covered in 25sec.
In the range of 140A-150A no voltage change takes place. This way, the operating point is pushed into this window from both sides with different speeds, which should provide enough dampening to prevent any oscillations.

Here is the code:

int _ABVAR_1_voltage = 0 ;
int _ABVAR_2_fan = 0 ;

void setup()
{
pinMode( 5, OUTPUT);
pinMode( 6, OUTPUT);

delay( 5000 );

analogWrite(6 , 0);

analogWrite(5 , 255);

delay( 2500 );

analogWrite(6 , 255);

delay( 2000 );

_ABVAR_1_voltage = 255 ;

_ABVAR_2_fan = 255 ;

}

void loop()
{
if (( ( analogRead(1) ) < ( 140 ) ))
{
_ABVAR_2_fan = 77 ;
}
else
{
_ABVAR_2_fan = ( ( ( 178 / 163 ) * analogRead(1) ) - ( 12903 / 163 ) ) ;
}
if (( ( _ABVAR_2_fan ) < ( 0 ) ))
{
_ABVAR_2_fan = 77 ;
}
else
{
if (( ( _ABVAR_2_fan ) > ( 255 ) ))
{
_ABVAR_2_fan = 255 ;
}
}
analogWrite(5 , _ABVAR_2_fan);
if (( ( analogRead(1) ) > ( 917 ) ))
{
_ABVAR_1_voltage = 0 ;
}
else
{
if (( ( analogRead(1) ) > ( 878 ) ))
{
_ABVAR_1_voltage = ( _ABVAR_1_voltage - 1 ) ;
delay( 20 );
}
if (( ( analogRead(1) ) < ( 817 ) ))
{
_ABVAR_1_voltage = ( _ABVAR_1_voltage + 1 ) ;
delay( 100 );
}
}
if (( ( _ABVAR_1_voltage ) < ( 0 ) ))
{
_ABVAR_1_voltage = 0 ;
}
else
{
if (( ( _ABVAR_1_voltage ) > ( 255 ) ))
{
_ABVAR_1_voltage = 255 ;
}
}
analogWrite(6 , _ABVAR_1_voltage);
}