How to use a while loop to calibrate the value of an analog sensor using Arduino




Sometimes you want everything in the program to stop while a given condition is true. You can do this using a while loop. This example shows how to use a while loop to calibrate the value of an analog sensor.

In the main loop, the sketch below reads the value of a photoresistor on analog pin 0 and uses it to fade an LED on pin 9. But while a button attached to digital pin 2 is pressed, the program runs a method called calibrate() that looks for the highest and lowest values of the analog sensor. When you release the button, the sketch continues with the main loop.

This technique lets you update the maximum and minimum values for the photoresistor when the lighting conditions change.

Circuit

Arduino while loop




Connect your analog sensor (e.g. potentiometer, light sensor) on analog input 2 with a 10K ohm resistor to ground. Connect your button to digital pin, again with a 10K ohm resistor to ground. Connect your LED to digital pin 9, with a 220 ohm resistor in series.

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

Schematic:

Arduino while loop schematic

Code

/*
Conditionals – while statement
This example demonstrates the use of  while() statements.
While the pushbutton is pressed, the sketch runs the calibration routine.
The  sensor readings during the while loop define the minimum and maximum
of expected values from the photo resistor.
This is a variation on the calibrate example.
The circuit:
* photo resistor connected from +5V to analog in pin 0
* 10K resistor connected from ground to analog in pin 0
* LED connected from digital pin 9 to ground through 220 ohm resistor
* pushbutton attached from pin 2 to +5V
* 10K resistor attached from pin 2 to ground
created 17 Jan 2009
modified 30 Aug 2011
by Tom Igoe

Major Components in Project

Hardware Required

  • Arduino Board
  • (1) digital pushbutton or switch
  • (1) photocell, or analog sensor
  • (2) 10k ohm resistors
  • breadboard




Clip to Evernote

Leave a Comment

(Spamcheck Enabled)

Read previous post:
arduino l3dgecomm
Arduino-l3dgecomm – Integrating L3DGEWorld and Arduino

L3DGEWorld is a tool for monitoring and interacting with networks and computer systems. Within a 3D world, entities bounce, spin,...

Close
Scroll to top