Switch (case) Statement, used with sensor input
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. This tutorial shows you how to use it to switch between four desired states of a photo resistor: really dark, dim, medium, and bright.
This program first reads the photoresistor. Then it uses the
map() function to map its output to one of four values: 0, 1, 2, or 3. Finally, it uses the
switch() statement to print one of four messages back to the computer depending on which of the four values is returned.
photoresistor, or another analog sensor
10k ohm resistors
The photoresistor is connected to analog in pin 0 using a voltage divider circuit. A 10K ohm resistor makes up the other side of the voltage divider, running from Analog in 0 to ground. The
analogRead() function returns a range of about 0 to 600 from this circuit in a reasonably lit indoor space.
Arrays - A variation on the For Loop example that demonstrates how to use an array.
ForLoopIteration - Control multiple LEDs with a for loop.
IfStatementConditional - Use an ‘if statement' to change the output conditions based on changing the input conditions.
switchCase2 - A second switch-case example, showing how to take different actions based on the characters received in the serial port.
WhileStatementConditional - How to use a while loop to calibrate a sensor while a button is being read.
Last revision 2015/08/11 by SM