2011-08-30 21:33:32 +02:00
|
|
|
/*
|
|
|
|
Conditionals - If statement
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
This example demonstrates the use of if() statements.
|
|
|
|
It reads the state of a potentiometer (an analog input) and turns on an LED
|
2017-07-14 21:34:00 +02:00
|
|
|
only if the potentiometer goes above a certain threshold level. It prints the
|
|
|
|
analog value regardless of the level.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
The circuit:
|
2017-07-12 22:18:23 +02:00
|
|
|
- potentiometer
|
|
|
|
Center pin of the potentiometer goes to analog pin 0.
|
|
|
|
Side pins of the potentiometer go to +5V and ground.
|
2017-07-15 00:30:34 +02:00
|
|
|
- LED connected from digital pin 13 to ground
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-14 21:34:00 +02:00
|
|
|
- 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.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
created 17 Jan 2009
|
|
|
|
modified 9 Apr 2012
|
|
|
|
by Tom Igoe
|
2011-08-30 21:33:32 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
This example code is in the public domain.
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2017-07-15 00:30:34 +02:00
|
|
|
http://www.arduino.cc/en/Tutorial/IfStatement
|
2017-07-15 00:35:58 +02:00
|
|
|
*/
|
2013-10-21 09:58:40 +02:00
|
|
|
|
2011-08-30 21:33:32 +02:00
|
|
|
// These constants won't change:
|
|
|
|
const int analogPin = A0; // pin that the sensor is attached to
|
|
|
|
const int ledPin = 13; // pin that the LED is attached to
|
|
|
|
const int threshold = 400; // an arbitrary threshold level that's in the range of the analog input
|
|
|
|
|
|
|
|
void setup() {
|
|
|
|
// initialize the LED pin as an output:
|
|
|
|
pinMode(ledPin, OUTPUT);
|
|
|
|
// initialize serial communications:
|
|
|
|
Serial.begin(9600);
|
|
|
|
}
|
|
|
|
|
|
|
|
void loop() {
|
|
|
|
// read the value of the potentiometer:
|
|
|
|
int analogValue = analogRead(analogPin);
|
|
|
|
|
|
|
|
// if the analog value is high enough, turn on the LED:
|
|
|
|
if (analogValue > threshold) {
|
|
|
|
digitalWrite(ledPin, HIGH);
|
2015-07-06 15:18:33 +02:00
|
|
|
} else {
|
2013-10-21 09:58:40 +02:00
|
|
|
digitalWrite(ledPin, LOW);
|
2011-08-30 21:33:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// print the analog value:
|
|
|
|
Serial.println(analogValue);
|
2012-04-09 16:48:11 +02:00
|
|
|
delay(1); // delay in between reads for stability
|
2011-08-30 21:33:32 +02:00
|
|
|
}
|