Hi,
I have code for 2 position switch to control the direction of one dc motor , and it works perfectly. When I am trying to add a potentiometer in position 1 or 2 to control the speed, , it doesn't change the speed ( increase or decrease).
Code:
int switchPos1 = 2;
int switchPos2 = 4;
int ENA = 8;
int In1 = 9;
int In2 = 7;
int SPEED = 200;
int potVal =A0;
int potState=0;
int switchState1 = 0;
int switchState2 = 0;
void setup() {
// put your setup code here, to run once:
pinMode (switchPos1, INPUT);
pinMode (switchPos2, INPUT);
Serial.begin (9600);
//pinMode(led1,OUTPUT);
// pinMode (led2,OUTPUT);
pinMode(In1, OUTPUT);
pinMode (In2, OUTPUT);
pinMode(ENA, OUTPUT);
}
void posOne()
{
switchState1 = digitalRead (switchPos1);
if ( switchState1 == HIGH )
{
SPEED = analogRead(A0); // Read potentiometer value
SPEED =SPEED/4;
analogWrite(ENA, SPEED); // Send PWM signal to L298N Enable pin
//digitalWrite (led1,HIGH);
digitalWrite (In1, HIGH);
digitalWrite (In2, LOW);
digitalWrite (ENA, HIGH);
Serial.println("on");
Serial.print("Position1: ");
}
else {
Serial.println("off");
// digitalWrite (led1,LOW);
digitalWrite (In2, LOW);
digitalWrite (In1, LOW);
digitalWrite (ENA, LOW);
}
}
void posTwo()
{
switchState2 = digitalRead (switchPos2);
if ( switchState2 == HIGH)
{
analogWrite(ENA, SPEED); // Send PWM signal to L298N Enable pin
//digitalWrite (led2,HIGH);
digitalWrite (In1, LOW);
digitalWrite (In2, HIGH);
digitalWrite (ENA, HIGH);
Serial.println("on");
Serial.print("Position2: ");
}
else {
Serial.println("off");
//digitalWrite (led2,LOW);
digitalWrite (In1, LOW);
digitalWrite (In2, LOW);
digitalWrite (ENA, LOW);
}
}
void loop() {
// put your main code here, to run repeatedly:
posOne();
posTwo();
}