/*
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// # # # # # ###### ####### ####### # #######
// ## ## # # ## # # # # # # # # #
// # # # # # # # # # # # # # # # # #
// # # # # # # # # # # # # # # # #####
// # # ####### # # # # # # # # ####### #
// # # # # # ## # # # # # # # #
// # # # # # # ###### ####### ####### # # #
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
#include <Servo.h>
Servo myServo;
const int buttonUp = A1;
const int buttonDown = A0;
const int potPin = A2;
int pos = 90; // Posisi servo saat ini
unsigned long lastPressTime = 0;
const unsigned long timeout = 10000; // 10 detik
void setup() {
Serial.begin(9600);
Serial.println(F("MANDOZAF SERVO BUTTON"));
Serial.println(F("by MANDOZAF"));
Serial.println();
myServo.attach(9); // Hubungkan servo ke pin 9
pinMode(buttonUp, INPUT_PULLUP);
pinMode(buttonDown, INPUT_PULLUP);
myServo.write(pos);
}
void loop() {
// Baca nilai potensiometer dan ubah menjadi posisi servo (0-180 derajat)
int potValue = analogRead(potPin);
int normalPos = map(potValue, 0, 1023, 70, 110);
if (!digitalRead(buttonUp)) {
pos += 1; // Naikkan posisi servo
if (pos > 180) pos = normalPos + 40; // Batas atas posisi servo
myServo.write(pos);
lastPressTime = millis(); // Reset timer
Serial.print("pos = "); Serial.println(pos);
}
if (!digitalRead(buttonDown)) {
pos -= 1; // Turunkan posisi servo
if (pos < 0) pos = normalPos - 50; // Batas bawah posisi servo
myServo.write(pos);
lastPressTime = millis(); // Reset timer
Serial.print("pos = "); Serial.println(pos);
}
// Jika tidak ada tombol ditekan selama 10 detik, kembalikan ke posisi normal (sesuai potensiometer)
if (millis() - lastPressTime > timeout) {
pos = normalPos; // Set posisi normal dari potensiometer
myServo.write(pos);
Serial.print("normal pos = "); Serial.println(pos);
}
delay(15); // Penundaan untuk menghaluskan gerakan servo
}