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
![](https://learn.sunfounder.com/wp-content/uploads/2020/10/1.png)
Note: you need to bind one end of the resistor and photoresistor to the wing of the servo, as shown below:
![](https://learn.sunfounder.com/wp-content/uploads/2020/10/Automatically_Tracking_Light_Source2.png.jpg)
The schematic diagram
![](https://learn.sunfounder.com/wp-content/uploads/2020/10/Automatically_Tracking_Light_Source3.png)
Step 2: Program (Please refer to the example code in LEARN -> Get Tutorials on our website)
Step 3: Compile the code
Step 4: Upload the sketch to the SunFounder Uno board
Now, if you use a flashlight to shine the photoresistor, you will see the servo motor and the photoresistor rotate, finally stop at the direction of light source.
![](https://learn.sunfounder.com/wp-content/uploads/2020/10/Automatically_Tracking_Light_Source4.jpg)
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]);//write the angle to servo outputValue = analogRead(photocellPin);//read the value of A0 Serial.println(outputValue);//print it if(outputValue > maxVal)//if the current value of A0 is greater than previous { maxVal = outputValue;//write down the value maxPos =i;// } delay(200); } myservo.write(angle[ maxPos]);//write the angle to servo which A0 has greatest value while(1); } |
Video