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

[box color=”#985D00″ bg=”#FFF8CB” font=”verdana” fontsize=”14 ” radius=”20 ” border=”#985D12″ float=”right” head=”Major Components in Project” headbg=”#FFEB70″ headcolor=”#985D00″]

Hardware Required

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

[/box]


About The Author

Ibrar Ayyub

I am an experienced technical writer with a Master's degree in computer science from BZU Multan University. I have written for various industries, mainly home automation and engineering. My writing style is clear and simple, and I am skilled in using infographics and diagrams. I am a great researcher and am able to present information in a well-organized and logical manner.

Follow Us:
LinkedinTwitter

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top