Hi there, I am trying to make a project using arduino UNO and some slot cars. I am using a tachometer to change the motor speed of the cars. I am using pwm to do that using a circuit with a TIP120. Here are the squematics :
I'm using external dc 12V . I added a reed switch that goes to digital pin2 and gnd.
So I calculate rpm with the reed switch, and depending the rpm; I map that value to pwm value for the motor.
Everything works great when I connect that to the motor, so everything works as excepted. BUT , when I put the motor (the slot car) in the circuit and starts spinning the interrupts seems to not work anymore as intended. Times given in interrupts are going so high and therefore rpms are not being well calculated...
Is that a problem with noise? Am I doing something wrong with the interrupts?
thanks in advance.
I paste the code:
int sensor = 2;
volatile float time= 0;
volatile float time_last = 0;
volatile int rpm_array[5] = {0,0,0,0,0};
long debouncing = 15;
int led = 9; // the pin that the MOTOR is attached to
volatile int pwm_value = 0; // pwm_value
void setup()
{
//Digital Pin 2 Set As An Interrupt
pinMode(led, OUTPUT);
pinMode(sensor, INPUT);
digitalWrite(sensor, HIGH);
attachInterrupt(0, reed_interrupt, FALLING);
Serial.begin(9600);
}
//Main Loop To Calculate RPM and Update LCD Display
void loop()
{
int rpm = 0;
while(1){
if(rpm < 500){
brightness = map(rpm,0,400,40,190);
analogWrite(led, pwm_value);
}
if(time > 0)
{
//5 Sample Moving Average To Smooth Out The Data
rpm_array[0] = rpm_array[1];
rpm_array[1] = rpm_array[2];
rpm_array[2] = rpm_array[3];
rpm_array[3] = rpm_array[4];
noInterrupts();
rpm_array[4] = 60*(1000000/(time));
interrupts();
//Last 5 Average RPM Counts Equals....
rpm = (rpm_array[0] + rpm_array[1] + rpm_array[2] + rpm_array[3] + rpm_array[4]) / 5;
}
/*
Serial.print("rpm:");
Serial.print(rpm);
Serial.print(" pwm:");
Serial.println(pwm_value);
// time for serial
delay(40);
*/
}
}
//Capture reed switch Interrupt
void reed_interrupt()
{
if((long)(micros() - time_last) >= debouncing *1000){
time = (micros() - time_last);
time_last = micros();
}
}
