# Using Decimals in an Equation

Hi
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()
{
pinMode(buzzPin,OUTPUT);
Serial.begin(9600);
}

void loop()
{
//Code for Inputting Timer On
Serial.print(msg1);
while(Serial.available()==0)
{

}
tOn = Serial.parseInt();
timer1 = tOn / 1000000;
Serial.println(tOn);

//Code for Inputting Timer Off
Serial.print(msg2);
while(Serial.available()==0)
{

}
tOff = Serial.parseInt();
timer2 = tOff / 1000000;
Serial.println(tOff);

//Code for Inputting the Duration
Serial.print(msg3);
while(Serial.available()==0)
{

}
duration = Serial.parseInt();
Serial.println(duration);

loops = duration / (timer1+timer2);
Serial.println(loops);
``````

` 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.