I wrote this code, it’s ignoring the else statement at the very end. If anyone could please help me out, that would be greatly appreciated.
#include “robot-config.h”
int main(){
while(1==1){
//drive forward
if(Controller1.Axis3.value()>=10){
RightMotor.spin(directionType::fwd,50,velocityUnits::pct);
LeftMotor.spin(directionType::fwd,50,velocityUnits::pct); }
//drive backwards
else{
if(Controller1.Axis3.value()<=-10){
RightMotor.spin(directionType::rev,50,velocityUnits::pct);
LeftMotor.spin(directionType::rev,50,velocityUnits::pct); }
//turn right
else{
if(Controller1.Axis1.value()>=10){
RightMotor.spin(directionType::fwd,50,velocityUnits::pct);
LeftMotor.spin(directionType::rev,50,velocityUnits::pct); }
//turn left
else{
if(Controller1.Axis1.value()<=10){
RightMotor.spin(directionType::rev,50,velocityUnits::pct);
LeftMotor.spin(directionType::fwd,50,velocityUnits::pct); }
//then stop
else{
RightMotor.stop(brakeType::brake);
LeftMotor.stop(brakeType::brake); }
}
}
}
}
}
Try to avoid using if statements inside of else statements. Use else if statements if possible. Looking at the “outside” of your code it goes like
if()
else()
else()
You can’t have 2 else statements in a row
leslie
October 30, 2019, 10:16pm
3
It should be compared to -10.
gbr
October 31, 2019, 12:21pm
4
@leslie definitely caught it, you’ll never get to the final else because the turn left logic is Axis1 >= 10 and turn right logic is Axis1 <= 10 . One of those will always be true before it can get to the final else statement.
The original code formatted with indentation (more readable)
#include “robot-config.h”
int main(){
while(1==1){
//drive forward
if(Controller1.Axis3.value()>=10){
RightMotor.spin(directionType::fwd,50,velocityUnits::pct);
LeftMotor.spin(directionType::fwd,50,velocityUnits::pct);
}
//drive backwards
else{
if(Controller1.Axis3.value()<=-10){
RightMotor.spin(directionType::rev,50,velocityUnits::pct);
LeftMotor.spin(directionType::rev,50,velocityUnits::pct);
}
//turn right
else{
if(Controller1.Axis1.value()>=10){
RightMotor.spin(directionType::fwd,50,velocityUnits::pct);
LeftMotor.spin(directionType::rev,50,velocityUnits::pct);
}
//turn left
else{
if(Controller1.Axis1.value()<=10){
RightMotor.spin(directionType::rev,50,velocityUnits::pct);
LeftMotor.spin(directionType::fwd,50,velocityUnits::pct);
}
//then stop
else {
RightMotor.stop(brakeType::brake);
LeftMotor.stop(brakeType::brake);
}
}
}
}
}
}