04.07.2013 Views

Arduino Cookbook - Cdn.oreilly.com

Arduino Cookbook - Cdn.oreilly.com

Arduino Cookbook - Cdn.oreilly.com

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The following sketch reads the light level of an LDR connected to analog pin 0. The<br />

light level striking the LDR will change the blink rate of the internal LED connected to<br />

pin 13:<br />

const int ledPin = 13; // LED connected to digital pin 13<br />

const int sensorPin = 0; // connect sensor to analog input 0<br />

void setup()<br />

{<br />

pinMode(ledPin, OUTPUT); // enable output on the led pin<br />

}<br />

void loop()<br />

{<br />

int rate = analogRead(sensorPin); // read the analog input<br />

digitalWrite(ledPin, HIGH); // set the LED on<br />

delay(rate); // wait duration dependent on light level<br />

digitalWrite(ledPin, LOW); // set the LED off<br />

delay(rate);<br />

}<br />

Discussion<br />

The value of the 4.7K resistor is not critical. Anything from 1K to 10K can be used. The<br />

light level on the LDR will change the voltage level on analog pin 0. The analogRead<br />

<strong>com</strong>mand (see Chapter 6) provides a value that ranges from around 200 when the LDR<br />

is dark to 800 or so when it is very bright. This value determines the duration of the<br />

LED on and off times, so the blink time increases with light intensity.<br />

You can scale the blink rate by using the <strong>Arduino</strong> map function as follows:<br />

const int ledPin = 13; // LED connected to digital pin 13<br />

const int sensorPin = 0; // connect sensor to analog input 0<br />

// the next two lines set the min and max delay between blinks<br />

const int minDuration = 100; // minimum wait between blinks<br />

const int maxDuration = 1000; // maximum wait between blinks<br />

void setup()<br />

{<br />

pinMode(ledPin, OUTPUT); // enable output on the led pin<br />

}<br />

void loop()<br />

{<br />

int rate = analogRead(sensorPin); // read the analog input<br />

// the next line scales the blink rate between the min and max values<br />

rate = map(rate, 200,800,minDuration, maxDuration); // convert to blink rate<br />

rate = constrain(rate, minDuration,maxDuration); // constrain the value<br />

18 | Chapter 1: Getting Started

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!