Hello, I have a problem measuring speed of dc motor with encoder.
Optical encoder triggers interrupt on every pulse (4 pulse per one rotation of shaft) which calculates angular speed of motor, but speed remains constant all the time (it' zero or 5600). I have to measure speed of 2 dc motors with 2 encoders and then I have to cross couple motors so they both go with the same speed. Here is the code:
//volatile int ug1 = 0;
//volatile int ug2 = 0;
volatile float brz1 = 0;
//volatile float brz2 = 0;
//volatile float T1 = 0;
//volatile float T2 = 0;
volatile float t1 = 0;
volatile float dt1 = 0;
void desni(){
dt1 = micros() ;
t1 += dt1;
brz1 = 1/4 * 1/dt1 * 1000000 * 60;
}
//void levi(){
// ug2++;
// brz2 = (ug2 - (ug2-1))/ (millis() - T2);
// T2 = millis() ;
//}
void setup(){
//attachInterrupt(0, levi, RISING);
attachInterrupt(1, desni, RISING);
Serial.begin(9600);
delay(5000);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
analogWrite(6, 150);
analogWrite(7, 0);
analogWrite(4, 0);
analogWrite(5, 150);
}
void loop(){
// Serial.print("Levi: ");
//Serial.println(brz2);
Serial.print("Desni: ");
Serial.println(brz1);
delay(500);
}
I suspect that problem lays in the frequency of interrupt triggering.
Sorry for my bad english, thank you in advance.
Post a photo of your circuit wiring.
I think you misunderstand micros().
micros() is the number of microseconds since the Arduino started. For example it might be a large number like 4,347,765 and the next time you take a reading it might be 4,347,773.
What you need to measure the speed is the difference between the value this time and the previous time.
Your interrupt routine might be something like this
void desni() {
newMicros = micros();
}
Then in loop() you can calculate the speed
void loop() {
microsBetweenInterrupts = prevMicros - newMicros;
prevMicros = newMicros;
// speed is worked out from the microsBetweenInterrupts
}
Note that variables that are used with micros should be defined as unsigned long.
...R
You migh whant to read Arduino cookbook (by Michael Margolis) page 620. It worked great for me :D!
Thank you all for quick reply. I managed to solve problem.
Here is the code, maybe someone will find it helpful.
volatile int puls = 0;
long vrem = 0;
long pvrem = 0;
long psvrem = 0;
float brz = 0;
long svrem = 0;
void pc(){
puls ++;
}
void setup(){
attachInterrupt(0, pc, RISING);
Serial.begin(9600);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
digitalWrite(4, LOW);
digitalWrite(5, HIGH);
pvrem = millis();
psvrem = millis();
}
void loop(){
vrem = millis() - pvrem;
svrem = millis() - psvrem;
if ( vrem > 10){
brz = (float) puls / vrem;
pvrem = millis();
puls = 0;
}
if ( svrem > 1000){
Serial.print("Brzina: ");
Serial.println(brz);
psvrem = 0;
}
}