Light sensor
Thursday, October 18th, 2007My next idea was to play around with the light sensor.
The idea of a practical use was following:
Most of the times I carry my mobile phone in my bag – so I have many missed calls, because I can’t hear it ringing (especially when listening to music). So I wanted to make something, that would notify my when the phone is ringing. Nowadays most mobile phones turn on their displays when you ring them – here the light sensor could be used. I’d create a small pocket for my phone in my bag, with the light sensor integrated and facing the display of the mobile phone. All I need then is a program, that would detect the light from the display and then turn the beeper on.
The program:
- monitor block – to see the values coming from the light sensor and thus to set the correct treshold value
- “if” block – to tell the board that if a certain value from the sensor is lower than a treshold (values rise as less ligt shines on sensor/more light means smaller number outputs – 1023 is the top value) to turn the beeper on
- “on” block next to the “if” block – simply to turn on the digital output (beeper in our case)
- “off” block to turn off the digital output when the value is less than the set treshold
Code:
int val= 0;
int compare=0;
int Pin7 = 7;
int Pin2 = 2;
void setup(){
pinMode(Pin2, INPUT);
pinMode(Pin7, OUTPUT);
Serial.begin(9600);
}
void loop(){
int analogValue;
analogValue = analogRead(2);
Serial.println(analogValue);
delay(10);
val = analogRead(Pin2);
compare=900;
if (val > compare){
digitalWrite(Pin7, HIGH);
}
else {
digitalWrite(Pin7, LOW);
}
}
And it works!!!
But:
I ahad several problems while working on this code:
- first of all, from reasons unknown to me the code has to be corrected after you switch from the block to the text view. the else statement in the condition looked originally like this:
else {
}
digitalWrite(Pin7, LOW);
The instruction to turn off the digital pin was out of curly brackets, so I had to move it in.
- I also don’t quite understand the if condition itself – it says, that if the value from the sensor is more that 900 (treshold value) it will turn the digital pin on, but it works the opposite way. I had to change the code itself after I turned it on for the first time and it did not worked as I wanted. I’m playing around with it right now and I see the values coming from the sensor – if they are above 900 the beeper is off and vice versa…strange to me…