Go Down

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

rduiohd

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;
Quote

#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
 left_motor.setSpeed(200);
 lightValue = analogRead(ldrPin);
 pinMode(lightValue,INPUT);
 delay(1000);
}

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


JimboZA

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....
"Could you do the egg bacon spam and sausage without the spam then? "

No PMs for help please.
DO NOT power servos from Arduino 5V: give them their own power and connect the grounds.

Erdin

#2
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);
  pinMode(lightValue,INPUT);


Code: [Select]

// better
pinMode(ldrPin,INPUT);
lightValue = analogRead(ldrPin);


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

JimboZA

"Could you do the egg bacon spam and sausage without the spam then? "

No PMs for help please.
DO NOT power servos from Arduino 5V: give them their own power and connect the grounds.

rduiohd

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