I am using the potentiometer to control the duty cycle of a PWM signal to the MOSFET trigger switch module, thus controlling the motor speed.
In my code, I have used the map function to utilize the full resolution of my potentiometer (0 - 1023) and thus create a proportional PWM signal using analogWrite function (0 - 255).
However, in my setup I want to limit the speed of the motor from going beyond a MAX_RPM value, despite any further increase in analog value input from the potentiometer.
This means I have to continously check the RPM value (the RPM code works fine, so I will not include it).
If the motor speed hits the MAX_RPM value, any further potentiometer input should be ignored. To achieve this, I figured I need to hold the analogWrite function value constant thus holding the speed constant.
In the event that I turn the potentiometer in the reverse direction, this should decrease the PWM value thus also decreasing the speed.
I have written the code to achieve the process described above to no avail i.e., increasing potentiometer input causes the speed to go beyond the MAX_RPM value which is undesired.
In this project, I am developing a rev limiter of sorts.
Please help me figure out the problem in my code.
#define MAX_RPM 500
#define MAX_RPM_PWM_MAPPED_VALUE 15
//In this case, I first ran the motor while monitoring the speed and the potentiometer value
//While doing this, I noted the potentiometer value at which the MAX_RPM is obtained
//I then defined this potentiometer value as MAX_RPM_PWM_MAPPED_VALUE
//With MAX_RPM_PWM_MAPPED_VALUE, I would directly limit the value written to the analogWrite function
//
MOSFETMODULE = 4;
potentiometer = AO;
void setup()
{
pinMode(MOSFETMODULE, OUTPUT);
}
void loop()
{
val = analogRead(potentiometer); //Read potentiometer value - represents accelerator input
mappedValue = map(val, 0, 1023, 0, 255); //Map the 10 bit value to 8 bit equivalent
if(RPM >= MAX_RPM)
{
analogWrite(MOSFETMODULE, MAX_RPM_PWM_MAPPED_VALUE);
}
else
{
mappedValue = constrain(mappedValue, 0, MAX_RPM_PWM_MAPPED_VALUE);
analogWrite(MOSFETMODULE, mappedValue); //Output a PWM signal to the MOSFET trigger module
}
}
analogWrite(MOSFETMODULE, 0);
when the RPM exceeds the maximum value. Of maybe use1
instead of0
. That way the code will throttle way back, if the RPM ever exceeds it's maximum. If will return to using the pot value, when the RPM goes back down. It may result in some weird oscillations, but cars make some weird noises too, when they are at their max RPM, so +1 for realism.