آموزش صفر تا صد راه اندازی سروو موتور با برد آردینو (طراحی ، ساخت ، برنامه ریزی و اجرا )
A simple light follower with Analog 180° Micro Servo
1. How does it work?
The choice to go up or down in order to follow the light is done in a very simple way. There are four LDR two up and two down. Arduino reads the analog value of all LDR, if the average of the two upper values is greater than the two lower the light is up so the angle of the microservo is incremented otherwise decremented.
2. A little clarification
Since the average is not a fixed number, as you can see in the code, a threshold is used. In this way the angle is changed if and only if the two averages are widely different.
const int threshold = 50; [.....] down_average = (A0_val + A1_val)/2; up_average = (A2_val + A3_val)/2; diff = abs(up_average-down_average); if ((up_average > down_average) && (diff > threshold)) { if (val < 180) //if different from max val { val++; myservo.write(val); } } if((down_average > up_average) && (diff > threshold)) { if (val > 0) //if different from min val { val--; myservo.write(val); } }
4. Print & cut
Download the attached file, print it, glue it on the cardboard and cut all the pieces for yours light follower. You should obtain something like this.
10. Glue the breadboard on the base
Glue the breadboard on the base. Tou can use the biadesive tape of the breadboard.
12. Well done
Well done. Now you have all the necessary. Download the code on your Arduino and enjoy with your light follower!
/* A simple light follower author: Arturo Guadalupi <a.guadalupi@arduino.cc> */ #include <Servo.h> Servo myservo; int up_average; int down_average; int A0_val; int A1_val; int A2_val; int A3_val; int val = 90; int diff; const int threshold = 50; void setup() { pinMode(A0, INPUT); pinMode(A1, INPUT); pinMode(A2, INPUT); pinMode(A3, INPUT); myservo.attach(11); myservo.write(val); } void loop() { A0_val = analogRead(A0); //reading data from sensors A1_val = analogRead(A1); A2_val = analogRead(A2); A3_val = analogRead(A3); down_average = (A0_val + A1_val)/2; //the sum of the two lower sensors /2 up_average = (A2_val + A3_val)/2; //the sum of the two upper sensors /2 diff = abs(up_average-down_average); //checking the difference between the two averages if ((up_average > down_average) && (diff > threshold)) { if (val < 180) //if different from max val { val++; myservo.write(val); } } if((down_average > up_average) && (diff > threshold)) { if (val > 0) //if different from min val { val--; myservo.write(val); } } delay(25); }