Hi everyone,
I'm a newbie to arduino and electronics, and I'm trying to make a toy for my little brother. I've been trying
to get this thing to work, and I successfully got the thing to move and react, but I'm trying to implement a
photosensor to act as an on/off switch and I can't figure it out.
Any ideas?
#include <Servo.h>Â Â //
#include <NewPing.h>Â //
Servo leftServo;Â Â Â //Left Wheeel
Servo rightServo;Â Â Â //Right Wheel
#define TRIGGER_PINÂ 6Â //The red sensor wire
#define ECHO_PINÂ Â 7Â //The blue sensor wire. And put the black wire in GRND and the green wire in 5V
#define MAX_DISTANCE 100
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
unsigned int time;
int distance;
int triggerDistance = 30;
int fDistance;
int lDistance;
int rDistance;
int sensorValue;
int switchState = 0; //int switch State = 0; //default behavior, in the dark, it doesn't move
int triggerOn;
int triggerOff;
void setup()
{
 Serial.begin(9600);
 leftServo.attach(9);
 leftServo.write(90);
 rightServo.attach(8);
 rightServo.write(90);
}
void loop() {
 scan();
 fDistance = distance;         //type scan every time you want it to scan
 if (fDistance < triggerDistance) {
  moveBackward();
  delay(1000);
  moveRight();
  delay(500);
  moveStop();             //Tell it to stop after turning
  scan();
  rDistance = distance;
  moveLeft();
  delay(1000);
  moveStop();
  scan();
  lDistance = distance;
  if (lDistance < rDistance) {
   moveRight();
   delay(1000);
   moveForward();
  } else {
   moveForward();
  }
 } else {
  moveForward();
 }
}
void scan() {
 time = sonar.ping();
 distance = time / US_ROUNDTRIP_CM;
 if (distance == 0) {
  distance = 100;          // If the distance sensor picks up nothing, set the distance to max and just go forward, GET OUTTA HERE
 }
 delay(10);
}
void moveBackward() {
 rightServo.write(180);
 leftServo.write(0);
}
void moveForward() {
 rightServo.write(0);
 leftServo.write(280);
}
void moveRight() {
 rightServo.write(0);
 leftServo.write(0);
}
void moveLeft() {
 rightServo.write(180);
 leftServo.write(180);
}
void moveStop() {
 rightServo.write(90);
 leftServo.write(95);
}