Saturday, July 23, 2016

Filled Under: , , ,

While Loop

05. Control library while whileloop

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.





Step 1: What You Need?



Don't have components? Don't worry. Just click the component's name. 


Step 2: Build Your Circuit.



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.


Step 3: Upload The Code.





1. Select the Arduino board type: Select Tools >> Board >> Select your correct Arduino board used.

2. Find the port number by accessing device manager on Windows. See the section Port (COM&LPT) and look for an open port named "Arduino Uno (COMxx)". If you are using a different board, you will find a name accordingly. What matters is the xx in COMxx part. In my case, it's COM3. So my port number is 3.

Select the right port: Tools >> Port >> Select the port number.

3. You can find this code in the example of Arduino IDE.
Select File >> Examples >> 05.Control >> WhileStatementConditional

Click press the "upload" button (see the button with right arrow mark).

Download: 




Unknown

Author & Editor

My Robot Education Sdn. Bhd. (Robotedu.my) was founded in 2015 as the first robotics education centre in Malaysia to provide Arduino-based robotics courses for youths. Our vision is to be able to provide robotics education to every youth in Malaysia.

0 comments:

Post a Comment

 

  • Copyright © Arduino Tutorial ™ is a registered trademark.
    Designed by Templateism. Hosted on Blogger Templates.