Switch case issue

Dear Experts,

I wrote the following code to get input from the keyboard and display Time & Temperature in serial monitor based on the input.

But when I ran the program it is always evaluating only case 'a', i.e if I press "a" in the keyboard it is displaying time but when i press "b" it is not displaying temperature and if press any other keys it is not displaying default statement. Please help me to figure out the issue in the program.

void loop () {
if (Serial.available() > 0) {
int inByte = Serial.read();
switch (inByte) {
case 'a':
DateTime now = rtc.now();
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
delay(3000);
Serial.print('\n');
Serial.print(now.day(), DEC);
Serial.print("/");
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.year(), DEC);
Serial.print('\n');
Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
break;
case 'b':
Serial.print("Temperature: ");
Serial.print(rtc.getTemperature());
Serial.println(" C");
delay(5000);
break;
default:
Serial.println("Other keys");
break;

}

}
}

My advice is to add a debug Serial.println() call that prints the value of inByte so you can see what's happening.

Dear Pert,

Thank you for your advice. I have added Serial.println , what I found was I am getting number 10 in addition to the ascii number of the entered key. I am not sure from where it is coming , below is the code and output

void loop () {
if (Serial.available() > 0) {
int inByte = Serial.read();
Serial.println(inByte);
switch (inByte) {
case 'a':
DateTime now = rtc.now();
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
delay(3000);
Serial.print('\n');
Serial.print(now.day(), DEC);
Serial.print("/");
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.year(), DEC);
Serial.print('\n');
Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
break;
case 2:
Serial.print("Temperature: ");
Serial.print(rtc.getTemperature());
Serial.println(" C");
delay(5000);
break;
default:
Serial.println("Default");
break;

}

}
}

When I press a

Output:

10:51:40.991 -> 97
10:51:40.991 -> 10:51
10:51:44.006 -> 2/10/2019
10:51:44.006 -> Wednesday10

When I pres b

output :

10:53:50.291 -> 98
10:53:50.291 -> 10

10 is the linefeed character. Serial monitor sends it when you press enter on your keyboard. I don't think it's the problem here though.

Does your sketch say

case 'b':

or

case 2:
?

It's the line end: set your monitor to no line ending, bottom right corner.

This simplified code:

void setup()
{
  Serial.begin(9600);
  Serial.println("setup done");
  } //setup

void loop ()
{
  if (Serial.available() > 0)
  {
    int inByte = Serial.read();
    Serial.println(inByte);
    switch (inByte)
    {
      case 'a':
        Serial.println("in case a");
        break;
      case 'b':
        Serial.println("    in case b");
        break;
      default:
        Serial.println("             Other keys");
        break;
    }
  }
} //loop

... gives this output:

setup done
97
in case a
98
    in case b
113
             Other keys

.

Even better, this (note change XXXXXX):

void setup()
{
  Serial.begin(9600);
  Serial.println("setup done");
  } //setup

void loop ()
{
  if (Serial.available() > 0)
  {
    char inByte = Serial.read(); //XXXXXXXXXXXX change int to char
    Serial.println(inByte);
    switch (inByte)
    {
      case 'a':
        Serial.println("in case a");
        break;
      case 'b':
        Serial.println("    in case b");
        break;
      default:
        Serial.println("             Other keys");
        break;
    }
  }
} //loop

... gives this:

setup done
a
in case a
b
    in case b
q
             Other keys

line end and baud.GIF

Sorry I don't think my question was clear before.

The second version of the code you posted (in reply #2) doesn't have a line in the switch case for case 'b':

Is this the version of the code that's giving you problems?

No GypsumFantastic, it was typo error. But in the original code there is 'b' in the place of 2.

Dear FEBaily,

Thank you for the detailed response. The code which you wrote(below code) works perfectly.

void setup()
{
Serial.begin(9600);
Serial.println("setup done");
} //setup

void loop ()
{
if (Serial.available() > 0)
{
char inByte = Serial.read(); //XXXXXXXXXXXX change int to char
Serial.println(inByte);
switch (inByte)
{
case 'a':
Serial.println("in case a");
break;
case 'b':
Serial.println(" in case b");
break;
default:
Serial.println(" Other keys");
break;
}
}
} //loop

But when I include my statements under the switch case again it is not working again. I included my completed code. If possible please go through it and help me to find out the issue. I am also trying to figure out the bug, if I found I will post it here.

Thank you all once again for helping me.

Time__Date_and_Temperature_in_Serial_Monitor_with_Switch_Case.ino (1.46 KB)

viknesh_V:
But when I include my statements under the switch case ....

Why don't you try to put your statements in one at a time to try see where / when the problem occurs?

(I don't have an rtc,or the library installed)

There seems to be a problem with the following line being inside the switch..case statement:

        DateTime now = rtc.now();

The compiler gives the message:

note: crosses initialization of 'DateTime now'

and also gives a warning about jumping to case label for the 2nd case statement. Try moving that line to immediately before the switch..case statement and see if it clears up the problem.

(edit)
The full compiler output makes it a little clearer what is happening (filename removed for readability). It appears the compiler has a problem with declaring a variable inside the case statement.

 In function 'void loop()':
warning: jump to case label [-fpermissive]
       case 'b':
            ^~~
note:   crosses initialization of 'DateTime now'
         DateTime now = rtc.now();
                  ^~~

Enclose the code for the case statement in { } if you are declaring a variable inside the case code

Dear All,

Thank you so much for your inputs. What "david_2018" found was correct, when I put the "DateTime now = rtc.now();" function above the switch statement, code starts to work perfectly.

@david_2018, if you could let me know how did you get "crosses initialization of 'DateTime now' " it would helpful for me to debug my codes in the future.

I don't get any warning or error message when I wrote "DateTime now = rtc.now();" in my complier. I have attached screenshot for your reference.

I don't get any warning or error message when I wrote "DateTime now = rtc.now();" in my complier. I have attached screenshot for your reference.

What have you got "Show verbose output" and "Compiler warnings" set to in IDE preferences ?

I made a little test sketch that contains the same crossed initialization type error. It compiles fine in 1.8.10.

Even with verbose compiler preference set, there are no warnings or errors.

I don't have an Arduino here so I can't run it unfortunately.

Sketch:

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  int test = random(1, 3);

  switch (test)
  {
    case 1:
      int thisint = 5 * test; 
      Serial.println(thisint);
      break;
    case 2:
      thisint = 6 * test;
      Serial.println(thisint);
      break;
  }
  delay(5000);
}

Compiler output:

/Applications/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/julianchurch/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/julianchurch/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/julianchurch/Documents/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10810 -build-path /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597 -warnings=none -build-cache /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_cache_834864 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -verbose /Users/julianchurch/Documents/Arduino/SwitchCaseDemo/SwitchCaseDemo.ino
/Applications/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /Applications/Arduino.app/Contents/Java/hardware -hardware /Users/julianchurch/Library/Arduino15/packages -tools /Applications/Arduino.app/Contents/Java/tools-builder -tools /Applications/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/julianchurch/Library/Arduino15/packages -built-in-libraries /Applications/Arduino.app/Contents/Java/libraries -libraries /Users/julianchurch/Documents/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10810 -build-path /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597 -warnings=none -build-cache /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_cache_834864 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.avr-gcc.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=/Applications/Arduino.app/Contents/Java/hardware/tools/avr -verbose /Users/julianchurch/Documents/Arduino/SwitchCaseDemo/SwitchCaseDemo.ino
Using board 'uno' from platform in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr
Using core 'arduino' from platform in folder: /Applications/Arduino.app/Contents/Java/hardware/arduino/avr
Detecting libraries used...
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10810 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/variants/standard /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/sketch/SwitchCaseDemo.ino.cpp -o /dev/null
Generating function prototypes...
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10810 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/variants/standard /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/sketch/SwitchCaseDemo.ino.cpp -o /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/preproc/ctags_target_for_gcc_minus_e.cpp
/Applications/Arduino.app/Contents/Java/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/preproc/ctags_target_for_gcc_minus_e.cpp
Compiling sketch...
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10810 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/cores/arduino -I/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/variants/standard /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/sketch/SwitchCaseDemo.ino.cpp -o /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/sketch/SwitchCaseDemo.ino.cpp.o
Compiling libraries...
Compiling core...
Using precompiled core: /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_cache_834864/core/core_arduino_avr_uno_51f02b7210b938436b779d1c032618e1.a
Linking everything together...
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/SwitchCaseDemo.ino.elf /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/sketch/SwitchCaseDemo.ino.cpp.o /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/../arduino_cache_834864/core/core_arduino_avr_uno_51f02b7210b938436b779d1c032618e1.a -L/var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597 -lm
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/SwitchCaseDemo.ino.elf /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/SwitchCaseDemo.ino.eep
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy -O ihex -R .eeprom /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/SwitchCaseDemo.ino.elf /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/SwitchCaseDemo.ino.hex
/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-size -A /var/folders/qw/lyncygjx0s56b069kp0krsgw0000gn/T/arduino_build_611597/SwitchCaseDemo.ino.elf
Sketch uses 2240 bytes (6%) of program storage space. Maximum is 32256 bytes.
Global variables use 192 bytes (9%) of dynamic memory, leaving 1856 bytes for local variables. Maximum is 2048 bytes.

Using 1.8.5 I get

C:\Users\Bob\AppData\Local\Temp\arduino_modified_sketch_776436\sketch_oct02b.ino: In function 'void loop()':

C:\Users\Bob\AppData\Local\Temp\arduino_modified_sketch_776436\sketch_oct02b.ino:16:10: warning: jump to case label [-fpermissive]

     case 2:

          ^

C:\Users\Bob\AppData\Local\Temp\arduino_modified_sketch_776436\sketch_oct02b.ino:13:11: note:   crosses initialization of 'int thisint'

       int thisint = 5 * test;

           ^

and the output is always 5 which indicates that it never enters case 2, which was the original problem reported by the OP. Enclosing the code for each case in { and } solves the problem although it needs a different int declared for case 2 as thisint is out of scope

This looks like a case (no pun intended) where a warning should not be ignored. I am fairly sure that in earlier versions of the IDE an error occurred rather than just a warning