Hi,
I'm programming a file to command a servo and to read the number of rotations per second of the servo.
Here is the code:
int neutralAngleSR = 1401; //neutral position of the right servo
int countTransitionMarks = 44;
float deltaT;
int count;
float rps;
unsigned long timeold;
void setup(){
Serial.begin(9600);
DDRB = (1 << DDB1) | (1 << DDB2);
//initialize phase & frequency correct PWM outputs
TCCR1A = 1 << COM1A1 | 0 << COM1A0 | 1 << COM1B1 | 0 << COM1B0 | 0 << WGM11 | 0 << WGM10;
//timer clock = F_CPU/8, Phase and Frequency Correct PWM mode => 1us resolution
TCCR1B = 1 << WGM13 | 0 << WGM12 | 0 << CS12 | 1 << CS11 | 0 << CS10;
ICR1 = 20000; //period = 20ms
OCR1B = 1401; //neutral
//FALLING or RISING
attachInterrupt(0, rps_fun, FALLING);
count = 0;
rps = 0;
timeold = 0;
}
void loop(){
//Update RPS every second
delay(1000);
//Don't process interrupts during calculations
detachInterrupt(0);
//^t calculation (seconds)
deltaT = ((millis() - timeold)/1000);
//RPS calculation
rps = count/countTransitionMarks*deltaT;
//Print out
Serial.println("Contagem:");
Serial.println(count);
Serial.println("^t:");
Serial.println(deltaT);
Serial.println("RPS=");
Serial.println(rps);
count = 0;
timeold = millis();
//Restart the interrupt processing
attachInterrupt(0, rps_fun, FALLING);
char letra;
if(Serial.available() > 0){
letra=Serial.read();
//avançar
if(letra == 'w'){
goForward();
}
//stop
if(letra == 's'){
stopMotion();
}
//recuar
else if(letra == 'x'){
goBack();
}
}
}
void rps_fun(){
//Update count
count++;
}
void goForward(){
int angleSR = neutralAngleSR - 20;
OCR1B = angleSR; //tell servo to go to position in variable 'angle'
delay(20); //waits 20ms between servo commands
Serial.println("Avanco");
}
void stopMotion(){
int angleSR = neutralAngleSR;
OCR1B = angleSR; //tell servo to go to position in variable 'angle'
delay(20); //waits 20ms between servo commands
Serial.println("Stop");
}
void goBack(){
int angleSR = neutralAngleSR + 20;
OCR1B = angleSR; //tell servo to go to position in variable 'angle'
delay(20); //waits 20ms between servo commands
Serial.println("Recuo");
}
I don't know why but the result of the calculation that appears on the console is always 0.00. Also, the value of the time when is not 1 second (when is shorter) appears 0.00 too.
Thanks for future replies.
Best regards!