Go Down

Topic: LDR Sensor with Adafruit Motor Shield (Read 937 times) previous topic - next topic


I've got a problem with adding ldr sensor to arduino code i did try many codes but they didn't work and i don't know why. Someone out there please help me it's my school project.
Here is the code;

#include <AFMotor.h>

int ldrPin = A0;
int lightValue = 0;
AF_DCMotor motor(4); // define motor on channel 4 with 1KHz default PWM
AF_DCMotor left_motor(1);  // define motor on channel 1 with 64KHz PWM

void setup() {
 Serial.begin(9600);           // set up Serial library at 9600 bps
 Serial.println("Motor test!");
 motor.setSpeed(200);     // set the speed to 200/255
 lightValue = analogRead(ldrPin);

void loop() {
 lightValue = analogRead(ldrPin);
 if(lightValue < 5)
 left_motor.run(FORWARD);  // turn it on going forward
 left_motor.run(BACKWARD);  // turn it on going forwar


Does it compile?- if not, what compile errors did you get?

If it did compile, it helps to be more specific than saying  "i did try many codes but they didn't work".... what exactly doesn't work and in what way.

I would advise putting 3 more serial prints in... one just after you read the ldrpin to show what the reading is, and one in each "leg" of the if / else to say it got to the "if" or to the "else" then you'll know how well your logic is working.

Lose the serial begin inside loop().

Also it's better to put the code in the code tags (the #), not quote....


Mar 23, 2013, 03:52 pm Last Edit: Mar 23, 2013, 03:55 pm by Erdin Reason: 1
This sets the pin for LDR to input, but you use the pinMode() with lightValue, not with the ldrPin.
I think there is no need for pinMode() if you use analogRead(), but I'm not sure.
Code: [Select]

// not good
lightValue = analogRead(ldrPin);

Code: [Select]

// better
lightValue = analogRead(ldrPin);

Is the LDR connected to A0 and GND ? You also need a pull-up resistor (perhaps 22k) from A0 to 5V.



Well, i compile it and it doesn't give any error and i used ldr sensor which have 3 pins +5V,GND and Analog Input. I haven't got a time to test the code that you post, but i try and reply it again.

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131