Professional Documents
Culture Documents
CSCI373_Week_06 - Photoresistor
CSCI373_Week_06 - Photoresistor
CSCI373_Week_06 - Photoresistor
Week 06
The PhotoResistor
The photoresistor
A photoresistor or photocell is a light-controlled variable resistor. The
resistance of a photoresistor decreases with increasing incident light
intensity. A photoresistor can be applied in light-sensitive detector
circuits, and light- and dark-activated switching circuits.
The resistor can go in either orientation.
The function map
map(sensorValue, 0, 1023, 0, 255)
int sensorValue = 0;
void setup()
{
pinMode(A0, INPUT);
Serial.begin(9600);
pinMode(9, OUTPUT);
}
The photo resistor
void loop(){
//read the value from the sensor (from 0 to 1024)
sensorValue = analogRead(A0);
// print the sensor reading so you know its range
Serial.println(sensorValue);
// map the sensor reading to a range for the LED
// analogWrite(): setting the brightness of the LED
analogWrite(9, map(sensorValue, 0, 1023, 0, 255));
delay(100); // Wait for 100 millisecond(s)
}
Practice Exercise…
Practice Exercise:
In this experiment, we will use eight LEDs to indicate
light intensity.
The higher the light intensity is, the more the LED is lit.
When the light intensity is high enough, all the LEDs
will be lit.
When there is no light, all the LEDs will go out.
const int NbrLEDs = 8;
const int ledPins[] = {5, 6, 7, 8, 9, 10, 11, 12};
const int photocellPin = A0;
int sensorValue = 0; // value read from theSensor
int ledLevel = 0; // sensor value converted into LED 'bars’
void setup() {
for (int led = 0; led < NbrLEDs; led++){
pinMode(ledPins[led], OUTPUT); // make all the LED pins outputs
}}
void loop() {
sensorValue = analogRead(photocellPin);
ledLevel = map(sensorValue, 0, 300, 0, NbrLEDs); // map to the number of LEDs
for (int led = 0; led < NbrLEDs; led++){
if (led < ledLevel ) {
digitalWrite(ledPins[led], HIGH); // turn on pins less than the level
}else
{ digitalWrite(ledPins[led],LOW); // turn off pins higher than// the level
}}}