i am working on a script that will get a motor to run or stop based on a distance and if a button is pressed.
I am still in the beginning but i am getting stuck at the step of toggling the button (adding the distance stuff later)
for now i want to push the button let the motor run forward.. push the button again make the motor stop. (will try to add the rest of the functionality later myself)
i have looked at multiple posts already but can't figure it out.. is amost if the
if (but1==LOW) doesn;t register
//motor constants
const int forwardPin = 12;
const int backwardPin = 13;
const int delayTime = 500;
//button constants
const int but1pin =2;
int but1;
int buttonState = 1;
unsigned long currentMillis; // Store current millis().
unsigned long previousMillis; // store last measured millis().
void setup() {
Serial.begin(9600);
Serial.println("Started!");
Serial.println("");
//motor setup
pinMode (forwardPin, OUTPUT);
pinMode (backwardPin, OUTPUT);
// button setup
pinMode(but1pin, INPUT);
}
void loop() {
currentMillis = millis();
but1= digitalRead(but1pin);
if(currentMillis - previousMillis > 25){ // Millis timer fuction, to get little bugs out while measuring. the 25 value stands for the delay, do not go below 25.
if((but1== LOW) && buttonState ==1){
buttonState==0;
}
else if((but1==HIGH)&& buttonState==0){
buttonState==1;
}
delay(100);
if(buttonState == 2){
MotorForward();
}
if(buttonState == 1){
MotorBackward();
}
if(buttonState == 0){
MotorStop();
}
Serial.println(but1);
Serial.println(buttonState);
}
}
void MotorForward(){
digitalWrite(forwardPin,HIGH);
digitalWrite(backwardPin,LOW);
Serial.println("Forward");
}
void MotorBackward(){
digitalWrite(forwardPin,LOW);
digitalWrite(backwardPin,HIGH);
Serial.println("backward");
}
void MotorStop(){
digitalWrite(forwardPin,LOW);
digitalWrite(backwardPin,LOW);
Serial.println("stop");
}