Loop in a Switch Case Statment

Please Help .I whan to run sets of controle setings on motors and servos with a buton pres.
I do this thrue a Swich case statment. The motor controls works 100% But a sweep on a servo only repeats ons.
How do i loop the servo code in a case. In other words how do i loop within a case ? As in a normal sweep on a servo wich repeats indefnatly within a norman voil loop.

This in the part of my code.

void loop() {
  // check the status of the switch
  switchState = digitalRead(switchPin);

  // compare the switchState to its previous state
  if (switchState != prevSwitchState) {

    if (switchState == LOW) {

      buttonPushCounter ++;
      buttonPushCounter %= 6;
      // clean up the screen before printing a new reply
      lcd.clear();
      // set the cursor to column 0, line 0     
      lcd.setCursor(0, 0);
      // print some text
      lcd.print("Motor setup");
      // move the cursor to the second line
      lcd.setCursor(0, 1);

      // choose a saying to print baed on the value in reply 

      switch (buttonPushCounter)
      {
      case 0:
        lcd.print("1");
        //delay(3000);
        digitalWrite(9, HIGH);  //Engage the Brake for Channel A
        digitalWrite(9, HIGH);  //Engage the Brake for Channel B
        //delay(1000);


        //Motor A forward @ full speed
        digitalWrite(12, HIGH); //Establishes forward direction of Channel A
        digitalWrite(9, LOW);   //Disengage the Brake for Channel A

        analogWrite(3, 255);   //Spins the motor on Channel A at full speed

        //Motor B backward @ half speed
        digitalWrite(13, LOW);  //Establishes backward direction of Channel B
        digitalWrite(8, LOW);   //Disengage the Brake for Channel B
        analogWrite(11, 123);    //Spins the motor on Channel B at half speed

{ 
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees 
  {                                  // in steps of 1 degree 
    myservo.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees 
  {                                
    myservo.write(pos);              // tell servo to go to position in variable 'pos' 
    delay(15);                       // waits 15ms for the servo to reach the position 
  } 

        break;

Take your switch block out of the if (switchState != prevSwitchState) block, you want it to set motor speed etc. regardless of whether the button has just been pressed. You don't want to loop inside of your switch case blocks, because then you won't be able to detect button presses.

I also noticed as a side point, you've got:

digitalWrite(9, HIGH);  //Engage the Brake for Channel A
digitalWrite(9, HIGH);  //Engage the Brake for Channel B

Then later on:

digitalWrite(8, LOW);   //Disengage the Brake for Channel B

Just check all of your pin numbers are correct

How do i loop the servo code in a case. In other words how do i loop within a case ? As in a normal sweep on a servo wich repeats indefnatly within a norman voil loop.

First, you fix all the typos. I have no idea who "normal voil" is or why he is loopy.

The servo sweep needs to be part of the case statement, as i want to have a sets of settings per case, for motors as well as servos. My problem is that the servo sweep only executes once within the case statement and i need it to loop the same as in a void loop.

Code controlling the 2 motors works fine.

Any help would be appreciated.

Your program will only get to the servo sweep section if several things are true

switchState != prevSwitchState
and switchState == LOW
and buttonPushCounter == 0

Do you need all of them nested as you have or could you take the switch/case out of the loop that tests the button state ?

This is my first go at Arduino programming so I'm not sure if it needs to be nested as i have it at the moment.
The basic premise is this. If i press a button, code executes first case. Case 0 is a set of speeds for two motors and 2 sweeps for 2 servos. Next button press jumps to next case ( Case 1 ). witch is a set of different speeds of motors ,sweeps for servos. The servo sweeps needs repeat and not just execute once (as it is doing at the moment)

Try something like this pseudo code

start of loop
  if button is pressed and state is LOW
    update buttonPushCounter
  end of if
  
  start of switch using buttonPushCounter
    case 0
      actions
      break
    case 1
      actions
      break
    etc etc
  end of switch
end of loop

This way, each time through the switch/case the code for the current case will be executed so the servo will sweep each time.

NOTE - using delay() inside the switch/case will slow down reaction to button presses

Still cannot get the servo to repeat sweep within a case. Any other suggestions?
Anyone..... Anyone .... anyone ,Bueller?

Any other suggestions?

Post your code

My Complete code:

#include <LiquidCrystal.h>
#include <Servo.h> 
Servo myservo;  
LiquidCrystal lcd(10, 7, 4, 2, 1, 0);

// set up a constant for the switchPin
const int switchPin = 6;

// variable to hold the value of the switchPin
int switchState = 0;

int pos = 0;    // variable to store the servo position 

// variable to hold previous value of the switchpin
int prevSwitchState = 0;

int buttonPushCounter = 0;   // counter for the number of button presses

void setup() {
  // set up the number of columns and rows on the LCD 
  lcd.begin(16, 2);

  // set up the switch pin as an input
  pinMode(switchPin,INPUT);

  myservo.attach(5);  // attaches the servo on pin 9 to the servo object 



  // Print a message to the LCD.
  lcd.print("Laser Ready");
  // set the cursor to column 0, line 1
  // line 1 is the second row, since counting begins with 0
  lcd.setCursor(0, 1);
  // print to the second line
  lcd.print("Press button");

  //Setup Channel A
  pinMode(12, OUTPUT); //Initiates Motor Channel A pin
  pinMode(9, OUTPUT); //Initiates Brake Channel A pin

  //Setup Channel B
  pinMode(13, OUTPUT); //Initiates Motor Channel A pin
  pinMode(8, OUTPUT);  //Initiates Brake Channel A pin
} 

void loop() {
  // check the status of the switch
  switchState = digitalRead(switchPin);

  // compare the switchState to its previous state
  if (switchState != prevSwitchState) {

    if (switchState == LOW) {

      buttonPushCounter ++;
      buttonPushCounter %= 6;
      // clean up the screen before printing a new reply
      lcd.clear();
      // set the cursor to column 0, line 0     
      lcd.setCursor(0, 0);
      // print some text
      lcd.print("Motor setup");
      // move the cursor to the second line
      lcd.setCursor(0, 1);

      // choose a saying to print baed on the value in reply 

      switch (buttonPushCounter)
      {
      case 0:
        lcd.print("1");

        digitalWrite(9, HIGH);  //Engage the Brake for Channel A
        digitalWrite(9, HIGH);  //Engage the Brake for Channel B



        //Motor A forward @ full speed
        digitalWrite(12, HIGH); //Establishes forward direction of Channel A
        digitalWrite(9, LOW);   //Disengage the Brake for Channel A

        analogWrite(3, 255);   //Spins the motor on Channel A at full speed

        //Motor B backward @ half speed
        digitalWrite(13, LOW);  //Establishes backward direction of Channel B
        digitalWrite(8, LOW);   //Disengage the Brake for Channel B
        analogWrite(11, 123);    //Spins the motor on Channel B at half speed

        { 
          for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees 
          {                                  // in steps of 1 degree 
            myservo.write(pos);              // tell servo to go to position in variable 'pos' 
            delay(15);                       // waits 15ms for the servo to reach the position 
          } 
          for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees 
          {                                
            myservo.write(pos);              // tell servo to go to position in variable 'pos' 
            delay(15);                       // waits 15ms for the servo to reach the position 
          } 

          break;

        case 1:
          lcd.print("2");
          //delay(3000);
          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B
          // delay(1000);
          //Motor A forward @ full speed
          digitalWrite(12, LOW);  //Establishes backward direction of Channel A
          digitalWrite(9, LOW);   //Disengage the Brake for Channel A
          analogWrite(3, 123);    //Spins the motor on Channel A at half speed

          //Motor B forward @ full speed
          digitalWrite(13, HIGH); //Establishes forward direction of Channel B
          digitalWrite(8, LOW);   //Disengage the Brake for Channel B
          analogWrite(11, 255);   //Spins the motor on Channel B at full speed
          break;

        case 2:
          lcd.print("3");
          break;

        case 3:
          lcd.print("4");
          break;

        case 4:
          lcd.print("5");
          break;

        case 5:
          lcd.print("Stop Motors");
          digitalWrite(9, HIGH);  //Engage the Brake for Channel A
          digitalWrite(9, HIGH);  //Engage the Brake for Channel B
          break;


        }
      }
    }
    // save the current switch state as the last state 
    prevSwitchState = switchState;
  }
}

You still have your switch/case test inside the test for the button being pressed, not separate from it as has been suggested a couple of times.

dEE4dog:
My Complete code:

void loop() {

// check the status of the switch
  switchState = digitalRead(switchPin);

// compare the switchState to its previous state
  if (switchState != prevSwitchState) {
....
     // save the current switch state as the last state
    prevSwitchState = switchState;
  }
}

If switchState hasn't changed, your program will miss out all the code between the {...}.
Close the if statements after setting the LCD output and use else{...}

Also you can use just one if statement:

if (switchState != prevSwitchState && switchState == LOW) {...}

Thanks for all the reply's. As i said I'm new to programming and arduino. So some of the explanations goes way over my head! But i'm slowly getting there. :sweat_smile:

plzz help MY CODE is on led speed take user input to select speed but in void loop after case # error accrued which is (

now.ino: In function ‘void loop()’:
now:51: error: jump to case label [-fpermissive]
now:46: error: crosses initialization of ‘int ley’
now.ino: At global scope:
now:61: error: expected declaration before ‘}’ token
jump to case label [-fpermissive]
)
my code is
#include <LiquidCrystal.h>
#include <Keypad.h>

const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns
char keys[ROWS][COLS] = {
{‘1’,‘2’,‘3’},
{‘4’,‘5’,‘6’},
{‘7’,‘8’,‘9’},
{’#’,‘0’,’*’}
};
byte rowPins[ROWS] = {26, 30, 34, 38}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {42, 46, 50}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int buttonPin = 7;
const int ledPin = 13;
int buttonState = 0;

void setup() {
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
lcd.begin(16, 2);
lcd.setCursor(4,0);
lcd.print(“AHTESHAM”);
delay(1000);
lcd.clear();
lcd.setCursor(3,0);
lcd.print(“AHTESHAM”);
lcd.setCursor(3,1);
lcd.print(“AHTESHAM”);
delay(1500);
lcd.clear();
lcd.setCursor(0,0);
lcd.print(“select spd=#”);
delay(500);
}
void loop() {
buttonState = digitalRead(buttonPin);
char key = keypad.getKey();
if (key!=NO_KEY){
switch (key){
case ‘#’:
int ley=1;
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" select=1-9 “);
break;
case ‘1’:
if(ley==1)
lcd.clear();
lcd.setCursor(0,0);
lcd.print(” led blink ");
while(1){
digitalWrite(ledPin, HIGH); // turn the LED on (HIGH is the voltage level)
delay(50); // wait for a second
digitalWrite(ledPin, LOW); // turn the LED off by making the voltage LOW
delay(50);
}}}}}

You need some {} to isolate your variable definitions in the individual cases or move the definition of ley to function scope

You also need to use code tags and the auto format tool

}}}}}

And you MUST stop doing that shit. One } per line. Use Tools + Auto Format to fix your piss-poor indenting.