Sometimes Servo Run like Crazy

hi, i am on a "stove oven Heating project. " a servo controls air inlet of a oven. it works proper in most case but sometimes ( i connot understand in which case) it goes crazy about 1-2 sec. i mean it sweeps 20,160,50,90.... etc degrees very rapidly like 10 ms for each degree. of course i picked theese angles randomly. and it do it approximatelly every 30 sec. i try to solve this problem by adding delay(2000) of each servo control command but it didnt help. my servo work proper when u make simple project or examples.
i added my servo video as gif
i am noob and if you have any comment on my code i want to hear them.

could you pls help me? thank you


#include <Wire.h>
#include <FaBoLCD_PCF8574.h>
FaBoLCD_PCF8574 lcd;

#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <DHT_U.h>
#define DHTPIN 2 
#define DHTTYPE    DHT11 
DHT dht(DHTPIN, DHTTYPE);
uint32_t delayMS;


#include<Servo.h>
Servo Myservo;

const int LED_RED=9; //Red LED
const int LED_GREEN=8; //Green LED
const int RELAY=12; //Lock Relay or motor
const int up_key=7;
const int down_key=6;
// #define up_key 8
// #define down_key 7
// #define LED_RED 9
// #define LED_GREEN 8
int SetPoint=25;
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 1000;              //ortalama sıcaklık hesaplama süresi
unsigned long previousMillis2 = 0;        // will store last time LED was updated
const long interval2 = 10000;          //wait time before make new action

double T0=20;//anlık sıcaklık
double T1=20.5;//interval önceki sıcaklık
double T2=20.6;
int step1=10; //step size for inc
int step2=20;
int pos=90;


//ortalama sıcaklık için 

const int numReadings = 60;
double readings[numReadings];      // array the readings from the analog input
int readIndex = 0;              // the index of the current reading                 
double average = 20.5;  
double total = numReadings*average;// the running total

const int numReadings2 = 10;
double readings2[numReadings2];      // 2. sayaç
int readIndex2 = 0;              // 2.sayaç
double average2 = 20.7; 
double total2 = numReadings2*average2;                  // 2.sayaç 
//test-----------------------
int a=0;

//test----------



void setup() {
  
pinMode(LED_RED,OUTPUT);
pinMode(LED_GREEN,OUTPUT);  
pinMode(RELAY,OUTPUT);  
pinMode(up_key,INPUT);
pinMode(down_key,INPUT);
digitalWrite(up_key,HIGH);
digitalWrite(down_key,HIGH);


//--------------------------  

Serial.begin(9600);

lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("sicaklik=");
lcd.setCursor(0, 1);
lcd.print("ayar=");

dht.begin();
sensor_t sensor;

digitalWrite(LED_GREEN,HIGH);  //Green LED Off
digitalWrite(LED_RED,LOW);     //Red LED On
digitalWrite(RELAY,LOW);       //Turn off Relay
Myservo.attach(10);

//ortalama sıcaklık
// initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 20;}
  for (int thisReading2 = 0; thisReading2 < numReadings2; thisReading2++) {
    readings2[thisReading2] = 20;}
 delay(2000);

}

void Turnoff(){
 Myservo.write(0);
 delay(3000);
  
   digitalWrite(RELAY,LOW);    //Turn off heater
   digitalWrite(LED_RED,LOW);
   digitalWrite(LED_GREEN,HIGH);  //Turn on Green LED

}

void Turnon(){


 Myservo.write(170);
 delay(3000);
  
  digitalWrite(RELAY,HIGH);    //Turn on heater %100
  digitalWrite(LED_GREEN,LOW);
  digitalWrite(LED_RED,HIGH);  //Turn on RED LED  

}


void servopos(int position){
    Serial.print("servopos cagirildi---+++--+++---:");Serial.println(position);
    Myservo.write(position);
    delay(2000);
    digitalWrite(RELAY,HIGH);    //Turn on heater %50
    digitalWrite(LED_GREEN,HIGH);
    digitalWrite(LED_RED,HIGH);  //Turn on RED LED 
    

}


void loop() {

//Buton led test

//   if(digitalRead(up_key)==1){
//      digitalWrite(LED_RED,HIGH);
//       digitalWrite(LED_GREEN,HIGH);
//     }
//   else{
//     digitalWrite(LED_RED,LOW);
//     digitalWrite(LED_GREEN,LOW);
//     }

//   if(digitalRead(down_key)==1){
//      digitalWrite(LED_GREEN,HIGH);
//     }
//   else{
//     digitalWrite(LED_GREEN,LOW);
//     }
    
//Servo test
// Myservo.write(a);
// delay(1000);
// if (a<180) a=a+20;
//dht lcd yazdırma
// float temp=dht.readTemperature();
// float hum=dht.readHumidity();
// lcd.setCursor(7,0);
// lcd.print(temp);
// lcd.setCursor(7,1);
// lcd.print(hum);
// Serial.println(temp);
// Serial.println(hum);
Serial.print("pos");Serial.println(pos);
Serial.print("T0");Serial.println(T0);
Serial.print("total");Serial.println(total);
Serial.print("T1");Serial.println(T1);
Serial.print("readings");
for (int i = 0; i < 30; i++) Serial.print(readings[i]);
Serial.println("------------");


// test sonu------------------

T0=dht.readTemperature();

unsigned long currentMillis = millis();

//Ortalama sıcaklık T1 array hesaplama
 if (currentMillis - previousMillis >= interval) 
 {
  Serial.print("calc_t1 cagirildi read index:");Serial.println(readIndex);
  previousMillis = currentMillis;  
  total = total - readings[readIndex];
  readings[readIndex] = T0;
  total = total + readings[readIndex];
  readIndex = readIndex + 1;
  if (readIndex >= numReadings) 
    {
      readIndex = 0;
    }
  T1 = float(total) / float(numReadings);
//ortalama sıcaklık için t2 hesaplama. anlık karar verdiği için hesaplandı
  Serial.print("calc_t2 cagirildi read index:");Serial.println(readIndex2);
  previousMillis = currentMillis;  
  total2 = total2 - readings2[readIndex2];
  readings2[readIndex2] = T0;
  total2 = total2 + readings2[readIndex2];
  readIndex2 = readIndex2 + 1;
  if (readIndex2 >= numReadings2) 
    {
      readIndex2 = 0;
    }
  T2 = float(total2) / float(numReadings2);


  }

//lcd ön işlem
  lcd.setCursor(0,0);
  lcd.print("oda:");    //Do not display entered keys
  lcd.setCursor(4,0);
  lcd.print(T0); 
  lcd.setCursor(10,0);
  lcd.print(T2); 
  lcd.setCursor(15,0);
   if (T2>T1) lcd.print("+");
  if (T1>T2) lcd.print("-");
  {
    /* code */
  }
  
  
 
  //Get user input for setpoints  
  if(digitalRead(down_key)==1)
  {
    if(SetPoint>15)
    {
      SetPoint--;    
    }
  }
  if(digitalRead(up_key)==1)
  {
    if(SetPoint<30)
    {
      SetPoint++;
    }
  }


 //Display Set point on LCD
  lcd.setCursor(0,1);
  lcd.print("set:");
  lcd.print(SetPoint);
  lcd.print(" T1:");
  lcd.setCursor(11,1);
  lcd.print(T1);


//Check T2 is in limit
if(T2 > (SetPoint+4)) 
  {
  Turnoff();
  }
else if (T2<(SetPoint-4))
  {
  Turnon();
  }


//AKILLI KARŞILAŞTIRMA
//eğer oda istenenden biraz sıcaksa
if ((T2>(SetPoint)) && (currentMillis - previousMillis2 >= interval2) )
  {
    //ve oda ısınıyorsa
    if ((T1<T2)&&(pos>step1))
    {     
        pos=(pos-step1);   
        Serial.print("biraz sicak");Serial.println(pos);
        servopos(pos) ;

    }
    //ve oda soğuyorsa
    
    previousMillis2 = currentMillis;
  }

  //eğer oda istenenden biraz soğuksa
if ( (T2<SetPoint) && (currentMillis - previousMillis2 >= interval2) )
  {
   //VE ODA SOĞUYORSA
    if ((T1>T2)&&(pos<170))
    {
      pos = (pos+step1);
      Serial.print("biraz soguk");Serial.println(pos);
      servopos(pos);
    }
    
    previousMillis2 = currentMillis;
  }



  delay(100); //Update at every 
  
}



 

servofail2.47.zip (153.5 KB)

Servos usually misbehave if you have an inadequate power supply or a wiring problem. Do not use breadboards for servos, as they are for low power logic circuitry, and the breadboard tracks will burn.

Please post links to the power supply, the exact servo you have, and a picture of your wiring (or schematic diagram).

You have this function servopos

If the bug comes from the code you should see a lot of serial output from this function. If you do not see serial-output in the serial-monitor it is a hardware-problem.

best regards Stefan

looks like the reading/updating of temperatures and servicing the servo are at different rates: interval (1 sec) and interval2 (10 sec) while there is processing outside of these blocks that executes each iteration of loop() slowed only by the 100 msec delay at the end of loop()

why no just process everything once a second?

and why the need and comparisons between T1 and T2?

Thank you. İ added serial.print for this purpose. But when i look at serial output it seems normal. 1 call and wait delay time but servo go crazy sometime

İt could be . How much power 9g servos consume nd how much power produce a Arduino uno?

If you try to supply the servos from the arduino this is way too much overload.

The Arduino Uno will draw 50 to 200 mA depending what is connected to it.
9g Servos can draw more than 1A under heavy load. So if your powersupply has only 500mA this is way too low. Mimium 2A better 3A.

As soon as working with micocorntrollers goes beyond blinking some LEDs a digital multimeter (DMM) is a must. If you have no DMM buy one. Any DMM in the 20€/$-class will do

Me personal I recommend this one
Very good price perfomance ratio and some extra features

best regards Stefan

Actually i was not sure how to approach this problem. Probably there is more convenient way to make it. İ will very glad if you show me.

İ need repeat every cycle different time. Because i don't want to change angle of servo very rapidly. So i wait interval2 time before make any change to servo.

İ need to compare T1 and T2 because i want to understand if room is getting hotter or colder. So i compare avarage of Last 1 min temperature and avarage of Last 10 sec.

And there is a way to make paralel cycle?

not sure what the problem is. not clear what the program is trying to do. when i simulated code and raised temperature, i saw servo change monotonically (not randomly)

why not compare T1 to previous value of T1 (e.g. T1_last)?

why not a small change in angle every period?

what does the servo do? why does the angle depend on the temperature?

u re beast men: D i directly connect my servos to ardunio and problem solved. thanks a lot

my servo start runnig normally after i connect directly to the ardunio.
problem is to control air inlet of a stove depending on a room temperature. but stove react slowly to air inlet. so i need to calculate avarage temparature of last 60 sec and 10 sec. and i also need another counter for not changing servo too rapidly. maybe putting counter (previousmilis, previous milis2) is not good choice but i didnt find any better solution

because sensor is not very precise so when i do that code make decesions very quick and false. so i need avarage of room temps

because small changes dont have any affect of stove. i need make big changes and wait. but i understand ur point. i can try it

servo controls air inlet of the stove. so it controls the heater.
i want to make room temperature stable. so for example when the room is getting hotter air inlet(servo) must go lower angle.

thank you.

consider which i think is cleaner

#undef MyHW
#ifdef MyHW

struct FaBoLCD_PCF8574 {
    FaBoLCD_PCF8574 (void)    { }

    void begin (int x, int y)     { Serial.begin (9600); };
    void clear (void)             { Serial.println (); };
    void setCursor (int x, int y) {
        if (0 == x)
            Serial.println ();
        else
            Serial.print (" ");
    };

    void print (int i)            { Serial.print (i); }
    void print (const char *s)    { Serial.print (s); }
};

enum { DHT11 };
struct DHT {
    int temp = 20;

    DHT (int pin, int type)   { }
    void begin (void)         { }
    int  readTemperature (void) {
        if (Serial.available ())  {
            char s [40];
            int n = Serial.readBytesUntil ('\n', s, sizeof (s));
            s [n] = 0;
            temp = atoi (s);
        }

        return temp;
    }
};

struct sensor_t {
    sensor_t (void) { }
};

const byte PinLedRed  = 13;
const byte PinLedGrn  = 12;
const byte PinRelay   = 11;

const byte PinButs [] = { A1, A2 };

// ---------------------------------------------------------
#else
# include <FaBoLCD_PCF8574.h>
# include <Adafruit_Sensor.h>
# include <DHT.h>
# include <DHT_U.h>

const int PinLedRed=9; //Red LED
const int PinLedGrn=8; //Green LED
const int PinRelay=12; //Lock Relay or motor

const byte PinButs [] = { 7, 6 };
#endif

// -----------------------------------------------------------------------------
#include <Wire.h>

FaBoLCD_PCF8574 lcd;

#define DHTPIN 2
#define DHTTYPE    DHT11
DHT dht (DHTPIN, DHTTYPE);
uint32_t delayMS;

#include<Servo.h>
Servo myServo;

#define N_BUT   sizeof(PinButs)
byte butState [N_BUT];

enum { BUT_UP, BUT_DOWN };

const unsigned long Interval = 1000;
unsigned long msecLst;

int    setPoint = 25;
double temp;
double tempAvg;
double tempLst;
const  double tempDelta  = 0.5;

#define K       0.25

int servoPos;
int servoStep = 10; //step size for inc

bool relayState;

char s [80];
char t [80];

enum { Off = LOW, On = HIGH };

// -----------------------------------------------------------------------------
void
relaySet (
    bool state)
{
    if (relayState == state)
        return;

    lcd.setCursor (0, 2);
    lcd.print   ("relaySet: ");
    lcd.print   (state);

    myServo.write (On == state ? 170 : 0);

    digitalWrite (PinRelay,  state);
    digitalWrite (PinLedRed, state);
    digitalWrite (PinLedGrn, ! state);

    relayState = state;
}

// ---------------------------------------------------------
#if 0
void
servopos (
    int position)
{
    Serial.print ("servopos cagirildi---+++--+++---:");
    Serial.println (position);
    Myservo.write (position);
 // delay (2000);
    digitalWrite (PinRelay,HIGH);    //Turn on heater %50
    digitalWrite (PinLedGrn,HIGH);
    digitalWrite (PinLedRed,HIGH);  //Turn on RED LED
}
#endif

// -----------------------------------------------------------------------------
int
butChk (void)
{
    for (unsigned n = 0; n < N_BUT; n++)  {
        byte but = digitalRead (PinButs [n]);

        if (butState [n] != but)  {
            butState [n] = but;
            delay (10);

            if (LOW == but)
                return n;
        }
    }

    return -1;
}

// -----------------------------------------------------------------------------
void loop () {
    unsigned long msec = millis ();

    if ( (msec - msecLst) >= Interval)
    {
        msecLst = msec;

        tempLst  = temp;
        temp     = dht.readTemperature ();
        tempAvg += (temp - tempAvg) * K;

        // adjust relay & servo
        if (temp > (setPoint + 4))  {
            relaySet (Off);
            if (temp > tempAvg + tempDelta)
                if (180 > servoPos)  {
                    servoPos += servoStep;
                }
        }
        else if (temp < (setPoint - 4))  {
            relaySet (On);
            if (temp < tempAvg - tempDelta)
                if (0 < servoPos) {
                    servoPos -= servoStep;
                }
        }

        myServo.write (servoPos);
    
        // lcd ön işlem
        lcd.setCursor (0,0);
        lcd.print     ("oda:");    //Do not display entered keys
    
        lcd.setCursor (4,0);
        lcd.print     (temp);
    
        lcd.setCursor (10,0);
        dtostrf (tempAvg, 5, 2, t);
        lcd.print     (t);
    
        lcd.setCursor (15,0);
        lcd.print     (temp > tempAvg + tempDelta ? "+"
                     : temp < tempAvg - tempDelta ? "-" : "");
    
        //Display Set point on LCD
        lcd.setCursor (0,1);
        lcd.print     ("set: ");
        lcd.print     (setPoint);
    
        lcd.setCursor (10,0);
        lcd.print     (tempLst);
    
        lcd.setCursor (15,0);
        lcd.print     (servoPos);
    }

    //Get user input for setpoints
    switch (butChk ()) {
    case BUT_DOWN:
        if (setPoint > 15)
            setPoint--;
        break;

    case BUT_UP:
        if (setPoint < 30)
            setPoint++;
        break;
    }
}

// -----------------------------------------------------------------------------
void setup () {
    Serial.begin (9600);

    pinMode (PinLedRed, OUTPUT);
    pinMode (PinLedGrn, OUTPUT);
    pinMode (PinRelay,  OUTPUT);

    relaySet (Off);

    for (unsigned n = 0; n < N_BUT; n++)  {
        pinMode (PinButs [n], INPUT_PULLUP);
        butState [n] = digitalRead (PinButs [n]);
    }
    
    lcd.begin (16, 2);
    lcd.print ("sicaklik=");
    lcd.setCursor (0, 1);
    lcd.print ("ayar=");

    dht.begin ();
    sensor_t sensor;
    myServo.attach (10);

    tempAvg = dht.readTemperature ();
}

the above uses leaky integration to average the temperature reading

sounds like the airflow controls the stove temperature and a PID controller may be helpful in dealing with the lags