Using Decimals in an Equation

I am creating a piece of code that will turn on a buzzer for the duration that i want and whatever delays i want. I am using a digitalWrite function to use these buzzers. I know about all the other commands to use the buzzer e.g. tone, toneAC. However i need to be using the digitalWrite command.

Anyway, i am trying to work out the duration for my program to loop. I start off with inputting Timer On and Timer Off (in microseconds) into the serial monitor followed by the duration (in seconds).
I have worked out that i need to use this equation. loops = duration / (tOn+tOff);
as the tOn and tOff are in microseconds before i do this formula i need to divide it by 1000000 to get the inputted numbers into microseconds as the duration is counted in seconds.

This is where the problem comes in. In the Serial Monitor, it outputs "0", if anyone has a fix for this please help another out.

String msg1 = "Timer On(Microseconds): ";
String msg2 = "Timer Off(Microseconds): ";
String msg3 = "Duration(Seconds): ";

int tOn;
int tOff;
float timer1;
float timer2;
int duration;
int loops;

void setup() 

void loop() 
  //Code for Inputting Timer On
  tOn = Serial.parseInt();
  timer1 = tOn / 1000000;

  //Code for Inputting Timer Off
  tOff = Serial.parseInt();
  timer2 = tOff / 1000000;

  //Code for Inputting the Duration
  duration = Serial.parseInt();

  loops = duration / (timer1+timer2);

timer1 = tOn / 1000000;

since tOn is an integer, the calculation is performed using integer math where the result will be zero if tOn is anything less than 1000000.

timer1 = tOn / 1000000.0;
will perform the calculation with floating pt math because 1000000.0 is a float

(Sorry about the duplicate answer. This new version of the forum software is going to take some time to get used to.)

'tOn' is an integer and 1000000 is an integer. The result will be truncated and only give integer seconds. If you want any decimal places, try: "tOn / 1000000.0". That makes the constant a 'float' constant and the math is then done in floats.

Yeah thats the same as @gcjr answer which was the solution. Thanks anyway!

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