We tried now also to not use delay, rather millis(), kind of the BlinkWithoutDelay()-method. We made it rotate successfully, but we are still not able to measure position. Output is " End. Pos: 836
", and varies between 790 and 840, but is supposed to be 1000, and should be very accurate, at least we want it to be.
Code:
int Pul = 8; // PUL+ from driver
int Dir = 9; // DIR+ from driver
int Ena = 10; // ENA+ from driver
int ENCB = 6; //EB+ from encoder
int ENCA = 5; //EA+ from encoder
int a = 0;
int b = 0;
int interval_tall = 1;
unsigned long previousMillis = 0;
unsigned long currentMillis = 0;
bool CCW = true;
volatile int pos = 0;
void setup() {
Serial.begin(115200); //Baudrate of 115200 or 9600
pinMode(Pul, OUTPUT);
pinMode(Dir, OUTPUT);
pinMode(Ena, OUTPUT);
pinMode(ENCA,INPUT);
pinMode(ENCB,INPUT);
attachInterrupt(digitalPinToInterrupt(ENCA),readEncoder,RISING);
digitalWrite(Dir,LOW);// dir LOW - clockwise direction of roation (HIGH - CCW)
Serial.print("Start. Pos: "); //To print and track the position per step
Serial.println(pos);
Serial.println("----------");
for (int i=0; i <= 400; i++){ //This loop will perform one revolution
digitalWrite(Pul, HIGH);
currentMillis = millis();
while((unsigned long)(currentMillis - previousMillis) < interval_tall){
currentMillis = millis();
}
previousMillis = currentMillis;
digitalWrite(Pul, LOW);
while((unsigned long)(currentMillis - previousMillis) < interval_tall){
currentMillis = millis();
}
previousMillis = currentMillis;
//Serial.println(i); //print and track step compared to measured rotation
/*
Serial.print(" : ");
Serial.println(pos);
/*
Serial.print(" : ");
Serial.print(currentMillis);
Serial.println(" : ");
//Serial.println(previousMillis);
*/
}
Serial.print("End. Pos: ");
Serial.println(pos);
Serial.println("----------");
}
// Nothing needed in loop, just want to measure simple rotation back and forth for now
void loop() {
}
void readEncoder(){ //Interrupt function that gets called everytime EA+ rises
b = digitalRead(ENCB); //If EB+ already has risen, increase pos-vlaue by 1, else decrease
if(b > 0){
pos++;
}
else{
pos--;
}
}