Hello all! I’m currently building a humanoid robot as my first project and one of its functions will be to detect temperature,and, if the temperature is above a certain threshold, it will generate a response by moving a servo. Any critiques of my code would be greatly appreciated! While answering please keep in mind that, while I have about 6 months experience in C++, I only have about 3 weeks experience in Arduino. All help is greatly appreciated!
EDIT: Also, I’ve seen two methods of moving servos: simply using the write function, and also using a for loop to cause the servo to go though every degree of rotation. Which is more efficient? Is the second method simply more work than necessary?
#include <Servo.h>
bool command_given = false;
Servo hobbyServo1; // initialize our servos
Servo hobbyServo2;
String commandprompt = "Please enter a command : ";
void setup() {
Serial.begin(9600); // Establish a com with the computer serial so that the analog output can be measured.
hobbyServo1.attach(10); // Attach the servos to a pin
hobbyServo2.attach(11);
hobbyServo1.write(1); // Set the initial position of the servos
hobbyServo2.write(90);
}
void loop() {
int sensor = analogRead(A0); // Attach the sensor to analog 0
float voltage = sensor * 5 / 1023;
float temp = voltage * 100; // For all LM35DZ sensors, 10mV = 1 degree Celcius
delay(500);
if (temp > 80) {
//execute servo movement: Servo 1 will move the sensor arm UP 179 degrees, Servo 2 will move the torso away from the stimulus and then Servo 1 will move DOWN 179 to its original position.
hobbyServo1.write(179); // Send hobbyServo to 179 degrees
delay(3000);
hobbyServo2.write(179);
delay(3000);
hobbyServo1.write(1);
delay(3000);
//Reset hobbyServo2 to its default position via user input. I'm not using a delay because I will be presenting this robot and this will give me time to explain and then remove the stimulus.
while (command_given = false) {
Serial.println(commandprompt);
while (Serial.available() <= 0){
// Wait for the user to input a command in the Serial moniter
}
char command = Serial.read();
if (command == 1) {
Serial.println("You entered command [1]: RESET ");
//Reset hobbyServo 2
hobbyServo2.write(90);
delay(5000);
command_given = true;
}
}
}
}