PulseIn returning 0 when operation applied

Hi, im super confused why my output keeps changing when I apply a mathematical operator to my pulseIn output. When I don't apply this operator is outputs a correct value (the time period), however the instant I want to convert it to seconds, it instantly only return 0, anyone know why?

  int RPMin = 50; //RPM input
  int val = 0;
  unsigned long startMillis = 0;
  unsigned long endMillis = 0;
  float TimeDiff = 0;
  float Speed = 0;
  float Speed2 = 0;
  
  unsigned long Currenttime = 0;
  unsigned long TimePeriod = 0;
  float TimePeriodSec = 0;
  

void setup() {
  // put your setup code here, to run once:
  pinMode(RPMin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
val = digitalRead(RPMin);
//Serial.print(val);
Currenttime = millis();
if (val == HIGH){
  startMillis = Currenttime;
  TimePeriod = pulseIn(RPMin, LOW);
  endMillis = millis();
  TimeDiff = endMillis - startMillis;
  //Serial.println(TimePeriod);
  TimePeriodSec = TimePeriod/1000000;
  TimeDiff = TimeDiff/1000;
  Speed = 1/TimeDiff;
  Speed2 = 1/(TimePeriod*2);
  
  Serial.print("Time Difference: ");
  Serial.println(TimeDiff);
  Serial.print("Speed: ");
  Serial.println(Speed);
  Serial.print("Speed Method 2: ");
  Serial.println(Speed2);
}
}```

Essentially when i remove the line `TimePeriodSec = TimePeriod/1000000`, it allows TimePeriod to output a correct value, but when it is included TimePeriod will be equal to 0

try calculating using floats

TimePeriodSec = TimePeriod/1000000.0f;

'TimePeriod is an unsigned long int and '1000000' is a long int. The division is done in integers so you only get whole seconds. It doesn't matter to the calculation that you are going to store the result in a 'float'.

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