Hey i have been trying this code to stop my Redbot after it travels forward for a second but the problem is that i have tried break; and tried putting in a variable to stop it but it keeps on repeating the same function over and over again untill i press the reset button. Any help is much appreciated.....
// setting motor pins as variables
// Motor 1
int motorafb = 2; // Motor A - forward/backwards
int motorab = 4; // Motor A - brake
int motorahs = 5; // Motor A - Speed
int motorbfb = 7; // Motor B - forward/backwards
int motorbb = 8; // Motor B - brake
int motorbhs = 6; // Motor B - Speed
int state = 0;
int state2 = 0;
void setup() {
//Setup Motor A
pinMode(motorafb, OUTPUT); //Initiates Motor A pin
pinMode(motorab, OUTPUT); //Initiates Brake A pin
//Setup Motor B
pinMode(motorbfb, OUTPUT); //Initiates Motor B pin
pinMode(motorbb, OUTPUT); //Initiates Brake B pin
Serial.begin(9600);
}
// two functions which turn one motor on, the other off for 'spd' speed, and 'tme' Time
void TurnRight(int spd, int tme){
digitalWrite(motorafb, LOW);
digitalWrite(motorab, LOW);
analogWrite(motorahs, spd);
digitalWrite(motorbfb, 'HIGH');
digitalWrite(motorbb, LOW);
analogWrite(motorbhs, spd);
delay(tme);
}
void TurnLeft(int spd, int tme){
digitalWrite(motorafb, HIGH);
digitalWrite(motorab, LOW);
analogWrite(motorahs, spd);
digitalWrite(motorbfb, LOW);
digitalWrite(motorbb, LOW);
analogWrite(motorbhs, spd);
delay(tme);
}
// Function to go power both motors for 'spd' speed, and 'tme' time
void GoForward(int spd, int tme){
digitalWrite(motorafb, HIGH);
digitalWrite(motorab, LOW);
analogWrite(motorahs, spd);
digitalWrite(motorbfb, HIGH);
digitalWrite(motorbb, LOW);
analogWrite(motorbhs, spd);
delay(tme);
}
// Function to stop for a set amount of time - tme
void Stop(int tme){
digitalWrite(motorab, HIGH);
digitalWrite(motorbb, HIGH);
analogWrite(motorahs, 0);
analogWrite(motorbhs, 0);
delay(tme);
}
void loop(){
// Now we can use them like this
if(Serial.available() > 0){
if(Serial.read() == 'D'){
state =1 - state;
}
if(state == 1){
GoForward(255, 500); // So this will go forward full speed (255) fpr 500ms
Stop(1000); // Sits Stopped for 1000ms
}
state = 0;
}
{
if (Serial.read() == 'F'){
state2 =1 -state2;
}
if(state2 == 1){
TurnRight(255, 1000);// turns Right at full speed for 1000ms
Stop(1000);// Sits Stopped for 1000ms
}
state2 = 0 ;
}
}