/*
Conditionals - If statement
This example demonstrates the use of if() statements.
It reads the state of a potentiometer (an analog input) and turns on a particular LED
only if the potentiometer goes above a certain threshold level. It prints the
analog value regardless of the level. A high threshold range will light a red LED, a middle range will light a yellow LED
and a low range will light a green LED
The circuit:
- potentiometer
Center pin of the potentiometer goes to analog pin 0.
Side pins of the potentiometer go to +5V and ground.
- LED connected from digital pins to ground through 220 ohm resistors
- Note: On most Arduino boards, there is already an LED on the board connected
to pin 13, so you don't need any extra components for this example.
created 17 Jan 2009
modified 3/7/2024
by Steve Silva
This example code is in the public domain.
https://www.arduino.cc/en/Tutorial/BuiltInExamples/ifStatementConditional
Class Exercise
1. Change the program to light the red LED when the analog input is greater than 700,
2. Light the yellow LED between 300 to 699,
3. Green LED 299 to 100 and all three LEDs should light when the value is below 100.
*/
// These constants won't change:
const int analogPin = A0; // pin that the sensor is attached to
const int ledPinR = 13; // pin that the Red LED is attached to
const int ledPinY = 11; // pin that the Yellow LED is attached to
const int ledPinG = 9; // pin that the Green LED is attached to
const int thresholdHigh = 750; // an arbitrary threshold level that's in the range of the analog input
const int thresholdMed = 500; // an arbitrary threshold level that's in the range of the analog input
void setup()
{
// initialize the LED pin as an output:
pinMode(ledPinR, OUTPUT);
pinMode(ledPinY, OUTPUT);
pinMode(ledPinG, OUTPUT);
// initialize serial communications:
Serial.begin(9600);
}
void loop()
{
// read the value of the potentiometer:
int analogValue = analogRead(analogPin);
digitalWrite(ledPinR, LOW);
digitalWrite(ledPinY, LOW);
digitalWrite(ledPinG, LOW);
// if the analog value is high enough, turn on the LED:
// If the resistance value is greater than or equal to 750 ohms, turn on Red LED
if (analogValue >= thresholdHigh)
{
digitalWrite(ledPinR, HIGH);
}
// if the resistance value is between 500 to 749 ohms, turn on Yellow LED
else if ((analogValue > thresholdMed) && (analogValue < thresholdHigh))
{
digitalWrite(ledPinY, HIGH);
}
// Otherwise the resistance value is less than 500 turn on Green LED
else
{
digitalWrite(ledPinG, HIGH);
}
// print the analog value:
Serial.println(analogValue);
delay(1); // delay in between reads for stability
}