Created
February 28, 2017 01:54
-
-
Save todocono/353c213b5230a0af06ac120900534613 to your computer and use it in GitHub Desktop.
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
#define DEBUG | |
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 LDR0 = A0; // LDR sensor to GND and 1k to 1k resistor | |
const int LDR1 = A1; // LDR sensor to GND and 1k to 1k resistor | |
const int slow = 30; | |
const int fast = 120; | |
const int dark = 800; | |
const int bright = 150; | |
const int hyst = 50; | |
int initialLight; | |
void setup() { | |
#ifdef DEBUG | |
Serial.begin(9600); | |
#endif | |
initialLight = (analogRead(LDR0) + analogRead(LDR1) ) / 2; | |
} | |
void loop() { | |
int light0 = analogRead(LDR0); | |
int light1 = analogRead(LDR1); | |
#ifdef DEBUG | |
Serial.print( light0 ); | |
Serial.print( " " ); | |
Serial.println( light1 ); | |
#endif | |
if ( (light0 > (initialLight + hyst)) && (light1 > (initialLight + hyst))) { | |
carBack( fast, fast ); | |
} | |
else if ( (light0 < ( initialLight - hyst)) || ( (light1 < ( initialLight - hyst)) ) ) { | |
int speedMotor0 = map(light0, dark, bright, slow, fast); | |
int speedMotor1 = map(light1, dark, bright, slow, fast); | |
carAdvance( speedMotor0, speedMotor1); | |
} | |
else { | |
carStop(); | |
} | |
delay(10); | |
} | |
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