When I turn on DC motor with a button I get a a fixed PWM value that goes into a loop till button state changes.
What should I change that I could change X value with potentiometer in a loop?
int X = A0;
int SW = 2;
int Xval=5;
int SWval;
int buttonNew;
int buttonOld = 1;
int buttonState= 1;
int engine = 6;
void setup() { // This executes once
Serial.begin(9600);
pinMode(X, INPUT);
pinMode(SW, INPUT_PULLUP);
}
void loop() { // This loops continuously
Xval = analogRead(X);
buttonNew = digitalRead(SW);
if (buttonOld == 0 && buttonNew == 1) {
if (buttonState == 0) {
analogWrite(engine, Xval);
buttonState = 1;
}
else {
digitalWrite(engine, LOW);
buttonState = 0;
}
}
buttonOld = buttonNew;
delay(1);
Serial.print("button");
Serial.print(SWval);
Serial.print(" X=");
Serial.println(Xval);
}
1 Answer 1
Move the analogWrite out of the button-state-change code, and it will update the PWM continually, instead of only when the button is pressed.
See the code below.
I also change the variable name buttonState
to motorState
, as it indicates the state of the motor (On/Off). And I inverted it, so 1
means the motor is ON.
The other thing I did was to increase the delay to 10ms, so you don't get any issues with switch-bounce.
int X = A0;
int SW = 2;
int Xval=5;
int SWval;
int buttonNew;
int buttonOld = 1;
int motorState= 0;//indicates whether the motor is on/off
int engine = 6;
void setup() { // This executes once
Serial.begin(9600);
pinMode(X, INPUT);
pinMode(SW, INPUT_PULLUP);
}
void loop() { // This loops continuously
buttonNew = digitalRead(SW);
if (buttonOld == 0 && buttonNew == 1) {
if (motorState == 0) {
motorState = 1;
}
else {
motorState = 0;
}
}
buttonOld = buttonNew;
if (motorState == 1) {
Xval = analogRead(X);
analogWrite(engine, Xval);
}
else {
digitalWrite(engine, LOW);
}
delay(10);
Serial.print("button");
Serial.print(SWval);
Serial.print(" X=");
Serial.println(Xval);
}