I was able to measure the speed thanks to the help of all you contributors but when adding the code to control the motor I made slight (I believe necessary) adjustments. But when I measure my speed now it doesn't work anymore..
The variable b used in ISR Clock() is at risk. You shouldn't read the 2 byte int b without blocking the interrupt. The same goes for assigning an int incremented in an interrupt.
if (b > 2) {
Serial.print("vitesse ");
Serial.print(vitesse);
Serial.print(" dT ");
Serial.println(dT_op);
b = 0;
I suggest:
nointerrupts();
int TmpB = B;
interrupts();
if (TmpB > 2) {
Serial.print("vitesse ");
Serial.print(vitesse);
Serial.print(" dT ");
Serial.println(dT_op);
nointerrupts();
b = 0;
interrupts();
//Constants PID
float kp = 10;
//Error
float e = target - vitesse;
if (e < 0) {
e = 0;
}
//Corrector
float u = kp * e;
//Motor power
float pwr = fabs(u);
if ( pwr > 255 ) {
pwr = 255;
}
//signal the motor
analogWrite(motor, pwr);
This just can't be right. You use the error to produce an absolute pwm. I would like You to use the previous pwm value and the error value in some way.
I'm using an Arduino Mega so pins 2-13 are pwn pins if I'm correct. The frequency on the 4th is different from others. Do I need to take that into account?