const int stepsPerRevolution = 200; // Langkah per putaran untuk motor stepper
// Pin definisi untuk driver motor X pada MKS Gen L V1.0
const int motorPin1 = 8; // Pin arah (DIR) untuk motor X
const int motorPin2 = 9; // Pin langkah (STEP) untuk motor X
const int motorEnablePin = 10; // Pin enable (ENABLE) untuk motor X
int rpm = 60; // Kecepatan awal dalam RPM
unsigned long stepDelay = 0;
unsigned long stepCount = 0;
unsigned long lastStepTime = 0;
unsigned long lastReportTime = 0;
void setup() {
pinMode(motorPin1, OUTPUT);
pinMode(motorPin2, OUTPUT);
pinMode(motorEnablePin, OUTPUT);
digitalWrite(motorEnablePin, LOW); // Aktifkan motor driver
Serial.begin(9600);
Serial.println("Masukkan kecepatan (RPM): ");
calculateStepDelay(rpm);
lastReportTime = millis();
}
void loop() {
if (Serial.available() > 0) {
int newRpm = Serial.parseInt(); // Membaca kecepatan baru dari Serial Monitor
if (newRpm > 0) { // Memastikan nilai RPM valid
rpm = newRpm;
calculateStepDelay(rpm);
Serial.print("Kecepatan baru (RPM): ");
Serial.println(rpm);
}
}
rotateMotorContinuous();
reportCurrentRPM();
}
void calculateStepDelay(int rpm) {
// Hitung delay per langkah dalam mikrodetik
stepDelay = (60L * 1000000L) / (stepsPerRevolution * rpm);
}
void rotateMotorContinuous() {
unsigned long currentTime = micros();
if (currentTime - lastStepTime >= stepDelay) {
lastStepTime = currentTime;
// Step the motor
digitalWrite(motorPin2, HIGH);
delayMicroseconds(10); // Pulsa singkat untuk memastikan langkah diterima
digitalWrite(motorPin2, LOW);
stepCount++; // Increment step count
}
}
void reportCurrentRPM() {
unsigned long currentMillis = millis();
if (currentMillis - lastReportTime >= 1000) { // Setiap 1 detik
// Hitung RPM berdasarkan langkah yang diambil dalam 1 detik
float actualRPM = (stepCount / (float)stepsPerRevolution) * 60.0;
// Reset langkah hitungan
stepCount = 0;
lastReportTime = currentMillis;
// Tampilkan RPM yang terjadi
Serial.print("RPM terjadi: ");
Serial.println(actualRPM);
}
}