The essence of the program is to measure the temperature, and if the temperature is higher than 26 degrees, the servo rotates by 45 degrees, and if it's lower, it rotates by 179 degrees. However, a short circuit is occurring. At the moment of the first servo rotation, the temperature jumps to 40 degrees (the temperature is calculated from voltage), and after that, the servo continuously rotates back and forth because the temperature is fluctuating between 40 and 20 degrees. What could be the cause of this issue?
My code:
#include <Servo.h>Servo myServo;const int sensorPin = A0;const float baselineTemp = 20.0;int angle;void setup() { myServo.attach(9); Serial.begin(9600);}void loop() { int sensorVal = analogRead(sensorPin); Serial.println("Sensor Value: "); Serial.print(sensorVal); float voltage = (sensorVal/1024.0) * 5.0; Serial.println("Volts:"); Serial.print(voltage); Serial.println("Celcius:"); float temperature = (voltage - .5) * 100; Serial.print(temperature); if (temperature < baselineTemp) { myServo.write(179); } else { myServo.write(45); } delay(800);}Output in terminal:
sensorVal: 149 Volts:0.73 Celcius:22.75 sensorVal: 192 Volts:0.94 Celcius:43.75 sensorVal: 154 Volts:0.75 Celcius:25.20 sensorVal: 188 Volts:0.92 Celcius:41.80 sensorVal: 150 Volts:0.73 Celcius:23.24 sensorVal: 184 Volts:0.90 Celcius:39.84 sensorVal: 151- 1
- 1
What could be the cause of this issue?... the servojsotola– jsotola2023-09-11 19:40:34 +00:00CommentedSep 11, 2023 at 19:40 - @SimSon I have just one GND and it's connected to "-"Pain– Pain2023-09-11 19:49:25 +00:00CommentedSep 11, 2023 at 19:49
- upvote for removing the picture and posting textjsotola– jsotola2023-09-11 20:13:43 +00:00CommentedSep 11, 2023 at 20:13
- 1maybe the power supply voltage changes when the servo runsjsotola– jsotola2023-09-11 23:37:55 +00:00CommentedSep 11, 2023 at 23:37
1 Answer1
You need to power the servo through a separate power supply. High power devices such as motors etc. should not be powered via the Arduino's regulator. That is surely affecting the analogRead() and therefore also the temperature reading as already noted by @jsotola.
Secondly, you need to add some hysteresis here to prevent continuous thrashing when the temperature is around the baseline:
if (temperature < baselineTemp) { myServo.write(179); } else { myServo.write(45); }Maybe try something like :
if (temperature < baselineTemp - 1.0 ) { myServo.write(179); } elseif (temperature > baselineTemp + 1.0 ) { myServo.write(45); }You could also try adding a capacitor across the power rails of the temperature sensor say 10uF very close to the sensor itself.
Explore related questions
See similar questions with these tags.
