Tutorial 14: Arduino Switch Case Statements and Keyboard Input

Arduino Course for Absolute Beginners

Arduino Switch Case Statements & Keyboard Input

How is it the QWERTY keyboard has been around so long? We used to “hunt & gather” now we “hunt & peck” (or at least I do).

It seems the keyboard is a long lasting human interface device that will be around for at least until the singularity, so we might as well make the best use of it.

This lesson introduces the use of the keyboard to communicate with the Arduino. As in the last lesson, the primary function to accomplish this task is a switch case statement in cahoots with the read() function from the Serial library.If you started this book at the beginning, then you are familiar will all the functions in this lesson. Here the functions are used in a slightly different application.

You type letters on the keyboard that are read by the Arduino and tested against different cases. If a letter matches a case, an LED lights for that case – if the letter does not match any cases, a default statement is used to turn off all the LEDs.


If you like this tutorial, click here to check out FREE Video Arduino course – thousands of people have really enjoyed it.

You Will Need

  1. 220 Ohm Resistor (5)
  2. LEDs (5)
  3. Jumper Wires (1)
  4. Medium bag of chocolate candies

Step-by-Step Instructions

  1. Connect one side of a resistor to pin 2, connect the other side into a row on the breadboard.
  2. Connect the long leg of the LED to the row in the breadboard where you attached the resistor.
  3. Connect the short leg of the LED to one of the power strip columns on the breadboard.
  4. Now connect a resistor to pin 3, and put the other leg in a row on the breadboard (a different row than your first LED).
  5. Connect an LED in the same manner – make sure the short leg goes in the SAME power strip column as the previous LED.
  6. Repeat this through pin 6.
  7. Using a jumper wire, connect the common power strip to a GND pin on the Arduino.
  8. Connect the Arduino to your computer.
  9. Open up the Arduino IED.
  10. Open the sketch for this section.
  11. Click the Verify button (top left). The button will turn orange and then blue once finished.
  12. Click the Upload button. The button will turn orange and then blue when finished.
  13. Now press the letters a, b, c, d and e on your keyboard and watch the LEDs light up.

Switch Case Board 2

This image made with Fritzing.

The Arduino Code

/*
  Switch statement  with serial input

 Demonstrates the use of a switch statement.  The switch
 statement allows you to choose from among a set of discrete values
 of a variable.  It's like a series of if statements.

 To see this sketch in action, open the Serial monitor and send any character.
 The characters a, b, c, d, and e, will turn on LEDs.  Any other character will turn
 the LEDs off.

 The circuit:
 * 5 LEDs attached to digital pins 2 through 6 through 220-ohm resistors

 created 1 Jul 2009
 by Tom Igoe

This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/SwitchCase2
 */

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  // initialize the LED pins:
  for (int thisPin = 2; thisPin < 7; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  // read the sensor:
  if (Serial.available() > 0) {
    int inByte = Serial.read();
    // do something different depending on the character received.
    // The switch statement expects single number values for each case;
    // in this exmaple, though, you're using single quotes to tell
    // the controller to get the ASCII value for the character.  For
    // example 'a' = 97, 'b' = 98, and so forth:

    switch (inByte) {
      case 'a':
        digitalWrite(2, HIGH);
        break;
      case 'b':
        digitalWrite(3, HIGH);
        break;
      case 'c':
        digitalWrite(4, HIGH);
        break;
      case 'd':
        digitalWrite(5, HIGH);
        break;
      case 'e':
        digitalWrite(6, HIGH);
        break;
      default:
        // turn all the LEDs off:
        for (int thisPin = 2; thisPin < 7; thisPin++) {
          digitalWrite(thisPin, LOW);
        }
    }
  }
}

Discuss the Sketch

This sketch does not begin with any variable declarations – it jumps directly into the setup() function. It starts by opening serial communications with the begin() function from the Serial library. Then it moves to setting the mode of the pins using a for loop and the pinMode() function.

for (int thisPin = 2; thisPin < 7; thisPin++) {

pinMode(thisPin, OUTPUT);

}

In this way, each pin with an LED attached is set as an OUTPUT. The for loop method of initializing pins should be familiar – check out the For Loop Iteration section to brush up if you need to.

Once complete with setup() we move to the body of the code in the loop() function. Start the for loop with an if statement – a pretty important one at that – everything inside the loop depends on the if statement. If the condition in the if statement is not met – nothing new happens at all! So what is the condition of this power mongering if statement?

if (Serial.available() > 0)

This condition implements a function called available() from the Serial library. The available() function checks at the serial port to see if any bytes are available and returns the number of bytes. If bytes are available the condition of the if statement will be met because Serial.available() will return a number larger than 0.

So why would bytes be available?

In this case, we are using the computer keyboard to write bytes to the serial port. Each character on your keyboard has an associated numerical value – called its ASCII value – which is one byte. When you type the letter ‘c’ for example, the number 67 will be sent to the serial port.

This condition asks, “Has a key been pressed on the computer?” If the answer is yes, then the if statement is executed, if the answer in no, then the if statement is ignored. So what happens if a key is pressed?

The first thing we want to do is read the data at the serial port. We do this with the read() function from the Serial library:

int inByte = Serial.read();

We create an integer variable called inByte and we let it equal the value read at the serial port. If we had typed ‘c’, then the value of inByte would be 67. If we had typed ‘x’, the value of inByte would be assigned 88. Once this value is captured in a variable, we need to test to see if it is one of the letters we want. If it is a letter we are looking for, then we light up an LED, if not then we turn off all the LEDs.

A switch case statement is just the tool for this job:

switch (inByte) {

case ‘a’:

  digitalWrite(2, HIGH);

  break

  ;

case ‘b’:

  digitalWrite(3, HIGH);

  break

  ;

case ‘c’:

  digitalWrite(4, HIGH);

  break

  ;

case ‘d’:

  digitalWrite(5, HIGH);

  break

  ;

case ‘e’:

  digitalWrite(6, HIGH);

  break

  ;

The switch case statement compares the value of inByte to five different cases. If the case is met, then its code turns on the LED at a specified pin using digitalWrite(). If a match is not found, we use an awesome feature of the switch case statement called a default.

Default allows us to have a backup plan if the incoming byte does not match any of the cases. In this default statement we use a for loop to digitally write LOW voltage to all the pins:

for (int thisPin = 2; thisPin < 7; thisPin++) {

digitalWrite(thisPin, LOW);

}

This switch case allows us to turn on different LEDs with specific keystrokes, and turns off all the LEDs when a keystroke does not match one of the specified cases.

Please notice the closing curly braces at the end of this program. There are a ton! How can you tell which one is which? It can get confusing – often what I do is use comments at the end of curly braces to identify its corresponding function:

          }//close for loop

       }//close switch case

    }//close if statement

}//close loop()

For some people, this is a little much, but I find it helps me keep all the closing curly braces straight. When we have functions that operate inside other functions, like the switch case statement inside the if statement, this is called nesting.

Nesting allows us to add layers of logic to our programs, but can get a little confusing if you are not paying close attention and using precise comments.

Try On Your Own

  • Add an additional case to the switch case statement. You will have to expand the map() range to do this.
  • Add an additional case to the switch case statement that will turn on all the LEDs with one keystroke.
  • Add a sixth LED at pin 7 and a case that will illuminate it.

Further Reading

installing Arduino libraries

Installing Arduino Libraries | Beginners Guide

IoT sewage project

Pumping poo! An IoT sewage project

ESP32 webOTA updates

How to update ESP32 firmware using web OTA [Guide + Code]

error message Brackets Thumbnail V1

expected declaration before ‘}’ token [SOLVED]

Compilation SOLVED | 1

Compilation error: expected ‘;’ before [SOLVED]

Learn how to structure your code