// Here is my code before i will explain it ,initially i make a code such if the pulsein duration is
greater than 1500 ,servo need to attach and rotate at speed of 1400 microseconds ,but when ikt between 900 to 1500 it need to detach ,and also i added a timer interrupt for that if encoder value is less than -585 value servo need to rotate at 1500microseconds ,but when i make simulation , the arduino directly detecting -970 value at it is rotating at 1500 microseconds ,not recongizing exact position of encoder at value greater than -585
here is the code ,iam using arduino mega
#include "Servo.h"
#include "Encoder.h"
#include <TimerOne.h>
Servo servo;
int encoderPin1 = 2;
int encoderPin2 = 3;
Encoder myEncoder(encoderPin1, encoderPin2);
volatile int lastEncoded = 0;
volatile long encoderValue = 0;
const int Servo_Pin = 8;
const int pulsePin = 7;
volatile bool lastState = false;
void setup() {
Serial.begin(9600);
pinMode(encoderPin1, INPUT);
pinMode(encoderPin2, INPUT);
pinMode(pulsePin, INPUT);
digitalWrite(encoderPin1, HIGH);
digitalWrite(encoderPin2, HIGH);
servo.attach(Servo_Pin);
Timer1.initialize(100000); // Initialize timer for 100 ms
Timer1.attachInterrupt(timerIsr); // Attach the timer interrupt
}
void loop() {
long currentEncoderValue = myEncoder.read();
Serial.print("Encoder Position: ");
Serial.println(currentEncoderValue);
unsigned long duration = pulseIn(pulsePin, HIGH); // Read the pulse
Serial.println("Duration:");
Serial.println(duration);
if (duration > 1500 && !lastState) {
// Allow the encoder to start counting again
myEncoder.write(currentEncoderValue); // Preserve current value
servo.attach(Servo_Pin);
servo.writeMicroseconds(1400);
Serial.println("Servo activated.");
lastState = true;
}
else if (duration > 900 && duration < 1500) {
// Reset encoder value
myEncoder.write(0);
servo.detach();
lastState = false;
Serial.println("Encoder value reset to 0.");
}
delay(1000); // Keep this delay to avoid flooding the Serial Monitor
}
void timerIsr() {
long currentEncoderValue = myEncoder.read();
if (currentEncoderValue <-585) {
servo.attach(Servo_Pin);
servo.writeMicroseconds(1500);
Serial.print("Encoder value exceeded limit: ");
Serial.println(currentEncoderValue);
Serial.println("Servo stopped due to large encoder movement");
// Optionally reset the encoder here if needed
}
}