#include <Servo.h>;
Servo myservo;


int srednee = 0;
//int xuy;
int xuy = 0;
int y = 0;
int8_t test = 0;
unsigned long timer = 0;
int nextgrad = 0;
int8_t currentspeed;
word ran = 1000;
uint32_t timer2 = 0;
bool invert;
word sp=1;
bool start;


void setup() {
  Serial.begin(115200);
  // put your setup code here, to run once:
  myservo.attach(2);
  myservo.write(0);
  //current=myservo.read();
  delay(3000);
  //xuy=0;

}

bool servo_smoth(byte grad , float speed) {
  static int current;
  if (abs(nextgrad - grad) > 1) {
    if (millis() - timer > speed) {
      xuy++;
      srednee = (grad - current) / 2;
      nextgrad = round(-srednee * (cos((speed * xuy) / 100)) + srednee + current);
      myservo.write(nextgrad);
      timer = millis();
      // Serial.print("x: ");  Serial.print(xuy);
      Serial.print("gr:");  Serial.print(","); Serial.print(grad); Serial.print(",");
      Serial.print("ng:"); Serial.print(","); Serial.print(nextgrad); Serial.print(",");
      Serial.print("ng-g:");Serial.print(","); Serial.println(nextgrad != grad);
     // Serial.print("test  "); Serial.println(timer);
     return false;
    }

  } else {
    current = nextgrad;
    xuy = 0;
    return true;
    //  myservo.detach()
  }










}




void loop() {
  // put your main code here, to run repeatedly:

// тест на случайный градус
/* if (millis() - timer2 > ran) {
    ran = random(10)*1000;
    sp= random(1,10);
     y = random(180);
    invert = !invert;
    timer2 = millis();
  } */

start = servo_smoth(y , sp);
  if  (start ) { 
 //   ran = random(10)*1000;
    sp= random(1,40);
    y = random(180);
  //  invert = !invert;
  //  timer2 = millis();
  } else {start=false;}
  


  
 
}