Using a photosensor as an on-off switch

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? :confused:

#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);
}

With that code you want the light sensor in a power control circuit outside of the Arduino and motors.
Don't bother getting the Arduino to do it, all those delays will make a "Stop Sometime Later Please" switch. But if it can permit or cut power to the whole project then it will be a stop switch.

OTOH you can learn to code without blocking delays and have a stop in 1 millisecond or less switch.

One beginner tutorial on the subject. There are many.

Thank you! :smiley: I'll try this out.