My speed control is not working properly, I am not such were I am going wrong
I have potentiometer to control the speed of my dc motor, when I try to adjust the speed will not change. When I restart the arduino the speed will change one time it will be slow, next time it will be faster and etc.
const int Push_Button = 2;
const int Limit_S_1 = 4;
const int Limit_S_2 = 3;
int sensorPin = A0;
int sensorValue_1 = 0;
int sensorValue_2 = 0;
//---------------------------------------------
const int A = 10; // motor direction pins
const int B = 11; //motor direction pins
int motor_pwm = 9 ; // motor pwm pin
//---------------------------------------------
int Speed=150;
void setup()
{
pinMode(Push_Button, INPUT);
pinMode(Limit_S_1, INPUT);
pinMode(Limit_S_2, INPUT);
pinMode(A, OUTPUT);
pinMode(B, OUTPUT);
sensorValue_1 = analogRead(sensorPin);
}
void loop()
{
if(digitalRead(Push_Button) == HIGH)
{
forward();
}
}
void forward()
{
while(1)
{
sensorValue_2 = analogRead(sensorPin);
if(sensorValue_1 < sensorValue_2)
{
Speed=Speed+10;
sensorValue_1=sensorValue_2;
}
if(sensorValue_1 > sensorValue_2)
{
Speed=Speed-10;
sensorValue_1=sensorValue_2;
}
if (Speed>255){Speed=255;}
if (Speed<1){Speed=0;}
digitalWrite(A, HIGH);
digitalWrite(B, LOW);
analogWrite(motor_pwm,Speed);
if(digitalRead(Limit_S_1) == HIGH)
{
backward();
}
}
}
void backward()
{
while(1)
{
sensorValue_2 = analogRead(sensorPin);
if(sensorValue_1 < sensorValue_2)
{
Speed=Speed+10;
sensorValue_1=sensorValue_2;
}
if(sensorValue_1 > sensorValue_2)
{
Speed=Speed-10;
sensorValue_1=sensorValue_2;
}
if (Speed>255){Speed=255;}
if (Speed<1){Speed=0;}
digitalWrite(B, HIGH);
digitalWrite(A, LOW);
analogWrite(motor_pwm,Speed);
if(digitalRead(Limit_S_2) == HIGH)
{
STOP();
}
}
}
void STOP()
{
digitalWrite(B, HIGH);
digitalWrite(A, HIGH);
analogWrite(motor_pwm,0);
loop();
}