As I have not used my Arduino for a while I thought I would start on something simple which has turned into something not so simple. So I have a basic light sensor wired into my Arduino board and it is connected to the 5v via a 1k resistor then t the Grd and analog pin 0. I am almost 99% sure that the wiring is correct as I can clearly see a stable change in the analog reading when viewing it using Serial.prinln. Below is my code and my problem is that I can clearly see that when my bedroom light is on the analog reading is below 200 and that when it is off, it is above 200. Therefore I though a simple if statement would allow me to turn my bedroom light off and the LED turn on and vice-versa, however the LED just remains on at all times from the very start. Any help is appreciated and if pictures are required then please ask.
Thanks.
int ledPin = 13;
int sensor = 0;
int val;
void setup(){
pinMode(ledPin, OUTPUT);
pinMode(sensor, INPUT);
Serial.begin(9600);
}
void loop(){
val = analogRead(sensor);
Serial.println((byte)val);
if (val > 200)
{
digitalWrite(ledPin, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
}
delay(3000);
}
Hi, thanks for the replies. I tried the code with the changes to A0, and taken the pinMode out but it had no affect as expected. As for the added Serial.println I placed one in the first loop of the if statement as shown below and it printed a value out meaning it is going into the loop even though the value is clearly below 220. As for you statement James C4S, what to you mean by is it what I expected? I am not sure what to expect as I have never used a photo resistor before however the value clearly changes depending on the light levels?
Thanks.
int ledPin = 13;
int sensor = 0;
int val;
void setup(){
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
val = analogRead(sensor);
Serial.println((byte)val);
if (val > 200)
{
Serial.println((byte)val);
digitalWrite(ledPin, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
}
delay(5000);
}
Try taking out the cast to byte in the println call to ensure that val really has the value you think it does. The docs say analogRead can return values from 0..1023. If val has a value larger than 256, the cast to byte will reduce it down to the 0..255 range in the print statement, but the if will still be checking against the full (10-bit) value.
Fantastic! Thanks NutDriverLefty and everybody else for the help. As NutDriverLefty said I took out the byte and was actually getting serial readings of around 890 with the light on and 970 with it off, therefor I simply changed the if statement to say greater than 950 and it works perfectly. Below is the final code for any future reference. Thanks again!
int ledPin = 13;
int sensor = 0;
int val;
void setup(){
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop(){
val = analogRead(sensor);
Serial.println(val);
if (val > 950)
{
digitalWrite(ledPin, HIGH);
}
else
{
digitalWrite(ledPin, LOW);
}
}