Skip to content

Instantly share code, notes, and snippets.

@todocono
Created February 28, 2017 01:54
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/353c213b5230a0af06ac120900534613 to your computer and use it in GitHub Desktop.
Save todocono/353c213b5230a0af06ac120900534613 to your computer and use it in GitHub Desktop.
#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