Сервомотор MG996R

// Copyright (c) 2026 ЦПМК по информатике
// Licensed under the MIT License.
// https://robot.mipt.ru/
#include <Servo.h>
Servo myservo; // Создаем объект Servo
int currentPos = 90; // Начальная позиция (например, 90 градусов)
int targetPos = 90; // Целевая позиция
int speed = 20; // Задержка в мс (меньше = быстрее)
void setup() {
myservo.attach(9); // Серво подключен к 9 пину
myservo.write(currentPos); // Устанавливаем начальное положение
Serial.begin(9600); // Инициализация Serial порта
Serial.println("Введите угол 0-180:");
}
void loop() {
// Проверяем, есть ли данные в Serial
if (Serial.available() > 0) {
// Считываем введенное число
int incomingPos = Serial.parseInt();
// Ограничиваем угол диапазоном 0-180
if (incomingPos >= 0 && incomingPos <= 180) {
targetPos = incomingPos;
Serial.print("Цель: ");
Serial.println(targetPos);
}
}
// Плавное движение к цели
if (currentPos < targetPos) {
currentPos++;
myservo.write(currentPos);
delay(speed); // Регулировка скорости [3]
}
else if (currentPos > targetPos) {
currentPos--;
myservo.write(currentPos);
delay(speed); // Регулировка скорости [3]
}
}