Control nema 17 stepper motor with TB6560+1 limit switch+rotary encoder

Hi...
I am trying to control a nema 17 stepper motor with TB6560 motor driver and one limit switch. Everything is working fine. but now i want to control the speed also with the rotary encoder KY040 i.e include encoder also.
The code that i was using till now is :-
// defines pins numbers
const int stepPin = 9;
const int dirPin = 10;
const int enPin = 11;
const int homeSwitchPin = 12;

void setup() {

Serial.begin(9600);

// Sets the two pins as Outputs
pinMode(stepPin,OUTPUT);
pinMode(dirPin,OUTPUT);
pinMode(homeSwitchPin , INPUT);
pinMode(enPin,OUTPUT);
digitalWrite(enPin,LOW);

// Set Dir to Home switch
digitalWrite(dirPin,LOW); // Enables the motor to move in a particular direction

}
void loop() {

int homeSw = digitalRead( homeSwitchPin);

if( homeSw == HIGH && (digitalRead(dirPin) == LOW) ){

motorStep(1);

}
else if( homeSw == LOW && (digitalRead(dirPin) == LOW) ){
digitalWrite(dirPin,HIGH);
delay(2000);
}

if( (digitalRead(dirPin) == HIGH) ){

motorStep(3500);
digitalWrite(dirPin,LOW);
delay(2000);
}

}
void motorStep( int MAX){

for(int x = 0; x < MAX; x++) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(500);
digitalWrite(stepPin,LOW);
delayMicroseconds(500);
}
}

This was my code with 1 limt switch. Now i want to add the code for the encoder also. so please someone provide me the code for encoder with this limit switch code

Please with 4 posts you are no longer a newbie here. Read how to use the forum and correct your post above and add code tags around your code:
[code]`` [color=blue]// your code is here[/color] ``[/code].

It should look like this:// your code is here
(Also press ctrl-T (PC) or cmd-T (Mac) in the IDE before copying to indent your code properly)

————-
There are many encoder libraries and basic codes - what have you explored?

Big Delays in a code that needs to be reactive are never a good thing

Have a look at the examples in this Simple Stepper Code - especially the second non-blocking example that does not use delay()

...R
Stepper Motor Basics

Do you have a pulldown (10k) resistor on pin 12? If not it may be "floating" and giving false HIGHs.