Lesson 14 Automatically Tracking Light Source

Share for us

Introduction

In this lesson, we will use a servo motor, a photoresistor and a pull-down resistor to assemble an automatically tracking light source system.

Components

– 1 * SunFounder Uno board

– 1 * Servo motor

– 1 * Photoresistor

– 1 * Resistor (10KΩ)

– Several jumper wires

– 1 * USB data cable

Experimental Principle

The servo motor and the photoresistor scan and look for light source in 180 degree and record the location of light source. After finishing scanning, the servo motor and the photoresistor stop at the direction of light source.

Experimental Procedures

Step 1: Build the circuit

Note: you need to bind one end of the resistor and photoresistor to the wing of the servo, as shown below:

The schematic diagram

Step 2: Program (Please refer to the example code in LEARN -> Get Tutorials on our website)

Step 3: Compile the program

Step 4: Burn the program into the SunFounder Uno board

Now, if you use a flashlight to shine the photoresistor, you will see the servo motor and the photoresistor rotate, and finally stop at the direction of light source.

Code


/********************************************************************
* name : Automatically Tracking Light Source
* function : if you use a flashlight to shine the photoresistor,
* you will see the servo motor and the photoresistor rotate, 
* and finally stop at the direction of light source.
***********************************************************************/
//Email: support@sunfounder.com
//Website: www.sunfounder.com#include <Servo.h>
const int photocellPin = A0;
/************************************************/
Servo myservo;//create servo object to control a servoint outputValue = 0;
int angle[] = {0,10, 20, 30, 40, 50, 60,70, 80, 90, 100,110,120,130,140,150,160,170,180};
int maxVal = 0;
int maxPos = 0;
/*************************************************/
void setup()
{
  Serial.begin(9600);
  myservo.attach(9);//attachs the servo on pin 9 to servo object
}
/*************************************************/
void loop()
{
  for(int i = 0; i < 19; i ++)
  {
    myservo.write(angle[i]);
    outputValue = analogRead(photocellPin);
    Serial.println(outputValue);
    if(outputValue > maxVal)
    {
      maxVal = outputValue;
      maxPos =i;
    }
    delay(200);
  }
  myservo.write(angle[ maxPos]);
  while(1);
}

Video