When measuring the speed with opta, it gives randomly incorrect values

There is a protrusion on the electric motor housings. The sensor gives a signal when it sees this protrusion. I want to see the time of 1 revolution of the motor. The average motor speed is 100 rpm. I wrote the program as follows. I see an average value of 500ms. But it gives small values ​​from time to time. I thought it was a serial communication error, but it is not a communication error.
Why do you think it gives low values?

unsigned long newTime = 0;
unsigned long cycleTime = 0;
bool  risingedge1 = LOW;

void setup()
{
pinMode (LED_D0, OUTPUT); //Motor
pinMode (LED_D1, OUTPUT);
pinMode (LEDR, OUTPUT); //Active_Input
pinMode (LED_BUILTIN, OUTPUT); //PLC_Active
pinMode (D0, OUTPUT); //Motor
pinMode (A0, INPUT); //Stop_B normally closed contact button
pinMode (A1, INPUT); //Start_B
pinMode (A5, INPUT); //Sensor
Serial.begin(9600);
}

void loop()
{

digitalWrite (LED_BUILTIN, HIGH); // If the PLC is working, the green LED will light up.

if (!digitalRead(A0)==HIGH || digitalRead(A1)==HIGH || digitalRead(A5)==HIGH) // If any of the buttons are pressed, the red LED will light up.
{
digitalWrite (LEDR, HIGH);
}

if (!digitalRead(A0)==LOW && digitalRead(A1)==LOW && digitalRead(A5)==LOW) //If the hand is removed from the button, the red LED will turn off.
{
digitalWrite (LEDR, LOW);
}

if (digitalRead(A1)==HIGH )
{
digitalWrite (D0, HIGH);
digitalWrite (LED_D0, HIGH);
}

if (!digitalRead(A0)==HIGH)
{
digitalWrite (D0, LOW);
digitalWrite (LED_D0, LOW);
} 

if (digitalRead(D0)==HIGH && digitalRead(A5)==HIGH &&  risingedge1==LOW)
{
risingedge1=HIGH;
cycleTime=millis()-newTime;
Serial.println(cycleTime); 
newTime=millis();
}

if (digitalRead(A5)==LOW &&  risingedge1==HIGH)
{
 risingedge1=LOW;
}

}

serial communication output
525
583
592
598
591
592
584
584
581
575
575
574
579
577
579
591
594
61
528
590
582
583
63
515
575

Hi, try changing this to INPUT_PULLDOWN

Thanks, I'll try.

I solved the problem. The sensor was faulty and was giving parasitic voltage. I changed the sensor and it was fixed.

1 Like

Take care (as @steve9 said) of undetermined logic states, independently of faulty sensors. To attach the digital line to an convenient default logic level is a good practice. Anyway, the correct software implementation is:

good -> the use of interrupts
far better-> use the digital signal rising/falling edge to read&reset a MCU timer

Hope this helps.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.