Skip to content

Instantly share code, notes, and snippets.

@todocono
Last active February 15, 2017 03:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todocono/f7b2c03861c0d6228cd3e262b81ded78 to your computer and use it in GitHub Desktop.
Save todocono/f7b2c03861c0d6228cd3e262b81ded78 to your computer and use it in GitHub Desktop.
LDR example for DFRobot Arduino
const int speedPin_M1 = 5; //M1 Speed Control
const int speedPin_M2 = 6; //M2 Speed Control
const int directionPin_M1 = 4; //M1 Direction Control
const int directionPin_M2 = 7; //M1 Direction Control
const int LDR = A0; // Analog input pin that the potentiometer is attached to
int speedMotors = 0;
const int slow = 50;
const int fast =255;
const int dark = 200;
const int ambi = 500;
const int light = 800;
const int hyst = 50;
void setup() {
}
void loop() {
int light = analogRead(LDR);
if ( light > 650 ) {
speedMotors = map(light, 650, 800, slow, fast);
carAdvance( speedMotors, speedMotors);
}
else if ( (light < 650) && (light > 300) ) {
carStop();
}
else if (light < 250) {
carBack( fast, fast );
}
}
void carStop() { // Motor Stop
digitalWrite(speedPin_M2, 0);
digitalWrite(directionPin_M1, LOW);
digitalWrite(speedPin_M1, 0);
digitalWrite(directionPin_M2, LOW);
}
void carBack(int leftSpeed, int rightSpeed) { //Move backward
analogWrite (speedPin_M2, leftSpeed); //PWM Speed Control
digitalWrite(directionPin_M1, HIGH);
analogWrite (speedPin_M1, rightSpeed);
digitalWrite(directionPin_M2, HIGH);
}
void carAdvance(int leftSpeed, int rightSpeed) { //Move forward
analogWrite (speedPin_M2, leftSpeed);
digitalWrite(directionPin_M1, LOW);
analogWrite (speedPin_M1, rightSpeed);
digitalWrite(directionPin_M2, LOW);
}
void carTurnLeft(int leftSpeed, int rightSpeed) { //Turn Left
analogWrite (speedPin_M2, leftSpeed);
digitalWrite(directionPin_M1, LOW);
analogWrite (speedPin_M1, rightSpeed);
digitalWrite(directionPin_M2, HIGH);
}
void carTurnRight(int leftSpeed, int rightSpeed) { //Turn Right
analogWrite (speedPin_M2, leftSpeed);
digitalWrite(directionPin_M1, HIGH);
analogWrite (speedPin_M1, rightSpeed);
digitalWrite(directionPin_M2, LOW);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment