If the students need help with their code, it is a good practice to first encourage them to solve the problem by themselves. Try asking questions and troubleshooting collaboratively.
Questions:
- Have you checked the console - are there error messages when you upload the code? What do the messages say?
- Have you checked your circuit, could there be bad connection?
- Can you describe what you were trying to do? Describe the problem in as much detail as you can! (Often a problem gets solved just by explaining it to another person - a classmate or the teacher!)
- Do you remember an earlier task or exercise where you learned about the part you’re struggling with? Have you tried looking at those earlier examples?
- Has anyone else in the classroom run into the same problem? Could they explain how they solved it? (Peer learning is a powerful experience both for the one who’s instructing - the person who already managed to solve the problem on their own - and the one who’s receiving instructions. More powerful than simply hearing the right answer from the teacher!)
- If none of these tips are successful, look at the student’s code and try to troubleshoot together with them. Show parts of the ready-made code as the last means.
NOTE: if the student has decided to code their own solution which is different from this example, that’s great! It’s completely possible to code this exercise in a different fashion. However, the ready-made code example below may not be very helpful in this case.
Code Example
//include the servo library:
#include <Servo.h>
//variables for storing values from LDRs:
int ldr1;
int ldr2;
//variable for the servo angle, initial value 90:
int angle=90;
//create a servo object:
Servo myServo;
void setup() {
myServo.attach(11); //servo is connected to pin 11
myServo.write(angle); // set servo to starting ange
Serial.begin(9600); //start serial communication
}
void loop() {
//read both sensor values and and store to variables:
ldr1 = analogRead(A0);
ldr2 = analogRead(A1);
//if value from ldr1 is bigger than ldr2,
//decrease the angle by 2 degrees:
if (ldr1 > ldr2){
angle = angle - 2;
//else increase the angle:
} else if (ldr1 <= ldr2){
angle = angle + 2;
}
//check if the angle has reached the maximum.
//if it has, set angle to 180.
if (angle > 180){
angle = 180;
}
//check if the angle has reached the minimum.
//if it has, set angle to 0:
if (angle < 0){
angle = 0;
}
//print values for debugging purposes:
Serial.print("ldr1: ");
Serial.print(ldr1);
Serial.print(" ldr2: ");
Serial.print(ldr2);
Serial.print(" angle: ");
Serial.println(angle);
//finally, set the servo to an angle:
myServo.write(angle);
//a small delay:
delay(20);
}