Hi, I have started a new project which invloves a servo, a DC motor, one potentiometer and 2 pushbuttons. Initially only the servo should start, whose speed is controlled by the potentiometer. When I press the pushbutton, the servo should stop and the DC motor should start, with it's speed controlled by the same potentiometer and it's direction by the second pushbutton. Instead of this on start only the DC motor powers up and rest of them don't work. I am not understanding what is wrong with my code. Kindly help.
#include <Servo.h>
#define potPin A0
int pos = 0;
int val = 0;
#define button 7
#define BUTTON 3
#define pot A0
#define pwm1 10
#define pwm2 9
Servo servo_9;
boolean motor_dir = 0;
int motor_speed;
int buttonNew;
int buttonOld=1;
int buttonPushCounter = 0;
int lastButtonState = 0;
void setup() {
pinMode(button, INPUT_PULLUP);
pinMode(BUTTON, INPUT_PULLUP);
pinMode(pwm1, OUTPUT);
pinMode(pwm2, OUTPUT);
servo_9.attach(9, 500, 2500);
Serial.begin(9600);
}
void loop()
{
buttonNew=digitalRead(BUTTON);
if (buttonNew != lastButtonState) {
if (buttonNew == HIGH) {
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
} else {
Serial.println("off");
}
delay(50);
}
lastButtonState = buttonNew;
if(buttonOld==0 && buttonNew==1){
motor_speed = analogRead(pot);
if(motor_dir)
analogWrite(pwm1, motor_speed);
else
analogWrite(pwm2, motor_speed);
if(!digitalRead(button)){
while(!digitalRead(button));
motor_dir = !motor_dir;
if(motor_dir)
digitalWrite(pwm2, 0);
else
digitalWrite(pwm1, 0);
}
else{
int val = analogRead(0);
for (pos = 0; pos <= 180; pos += 1) {
servo_9.write(pos);
delay(val);
}
for (pos = 180; pos >= 0; pos -= 1) {
servo_9.write(pos);
delay(val);
}
}
buttonOld=buttonNew;
}
}