While Example
/*
This code is meant to demonstrate a "while statement"
While the potenitometer is moving, turn an LED
NEEDED:
-Arduino
-Solderless Breadboard
-220 OHM resistor at pin 13
-Long leg (Anode) of LED attached to resistor, short leg attached to ground pin.
-Potentiometer (resistance level doesn't matter), one side connected to ground pin, other side connect to 5volt pin and center pin connected to A0
NOTE: If your Arduino has a built in LED at pin 13, you do not need the LED and resistor.
Created OCT 2013 by
Michael James
http://www.OpenSourceHardwareGroup.com/FlyingNinjaMarsupials
This code is in the public domain
*/
//Pin assignments
int ledPin=13; //the pin that the led is attached to
int potPin=A0; //the pin that the potentiometer middle leg is attached to
//variables for tracking the position of the potentiometer
int currentPosition; //tracks the current position of the Potentiometer
int lastPosition; // this tracks the last position of the Potentiometer
//Control panel variables - change these to adjust how the sketch performs
int timer=100; //the duration the LED stays lit when the potentiometer is moved
int tuning=1; //this adjsuts how much the potentiometer must change inorder to turn on the LED.
//if it is too low, the LED might always blink
void setup() {
//Set the mode of the pins
pinMode(ledPin, OUTPUT);
pinMode(potPin, INPUT);
Serial.begin(9600);
}
void loop() {
//check the current position of the potentiometer
currentPosition = analogRead(potPin);
//check if the potentiometer moved
while(abs(currentPosition - lastPosition) > tuning) {
Serial.println(currentPosition);
digitalWrite(ledPin, HIGH); //Turn on the LED
//write 5 volts to ledPin
delay(timer); //allow the LED to stay illuminated for this amount of time
lastPosition = currentPosition; //assign the current position to the previous postion
currentPosition = analogRead(potPin); //update current position
} //close while
//When the potentiometer is not moving, turn off the LED
//write 0 volts to ledPin
digitalWrite(ledPin, LOW);
}//close loop