Switch Statement used with serial input using Arduino

An if statement allows you to choose between two discrete options, TRUE or FALSE. When there are more than two options, you can use multiple if statements, or you can use the switch statement. Switch allows you to choose between several discrete options.

Switch Statement used with serial input using Arduino

This tutorial shows you how to use switch to turn on one of several different LEDs based on a byte of data received serially. The sketch listens for serial input, and turns on a different LED for the characters a, b, c, d, or e.

Circuit

Five LEDs are attached to digital pins 2, 3, 4, 5, and 6 in series through 220 ohm resistors.

To make this sketch work, your Arduino must be connected to your computer. Open the Serial Monitor, and send the characters a, b, c, d, or e, or anything else.

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic:

Switch Statement used with serial input using Arduino schematic

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

[box color=”#985D00″ bg=”#FFF8CB” font=”verdana” fontsize=”14 ” radius=”20 ” border=”#985D12″ float=”right” head=”Major Components in Project” headbg=”#FFEB70″ headcolor=”#985D00″]

Hardware Required

  • Arduino Board
  • (5) LEDs
  • (5) 220 ohm resistors
  • breadboard
  • hook-up wire

[/box]

About The Author

Scroll to Top
Read previous post:
Get-started-in-robotics-and-microcontrollers-with-this-bundle
Get started in robotics and microcontrollers with this bundle

latforms are both useful to know at a professional level, and simply fun to engineer and code. The 2022 Complete Raspberry...

Close