Last active
February 15, 2017 03:15
-
-
Save todocono/f7b2c03861c0d6228cd3e262b81ded78 to your computer and use it in GitHub Desktop.
LDR example for DFRobot Arduino
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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