Go Down

Topic: Simple count down timer problem (Read 488 times) previous topic - next topic

Code: [Select]

   //Timer2


void setup()
{
  Serial.begin(9600);
  Serial.println("Enter seconds to time");
}

void loop()
{
 
  timer();
}

void timer()
{
 
 
  if (Serial.available()> 0)
  {

      float timeInput = Serial.read(); // Take input from serial monitor.
 
  timeInput = timeInput - 48; // Todo: for some reason processor adds 48 to input, this corrects that.
  timeInput = timeInput * 1000;  //Converts time input to milliseconds.
   
     
      Serial.println(timeInput/1000);
      delay(timeInput); // Counts down to zero timeInput.
         
     
     
   
  Serial.println("Timer Done!");
   

  }
}


There are two problems I am having with this sketch.  When I input a number of seconds to count down, the compiler adds 48 to it.  Further, if I input a two digit number such as 12, it treats the 1 then the 2
as separate entries. The sketch does work for a single-digit entry.  Thanks.

PaulS

Code: [Select]
      float timeInput = Serial.read(); // Take input from serial monitor.
Serial.read() does not return a float.

Quote
When I input a number of seconds to count down, the compiler adds 48 to it.

No, it doesn't. It sends (assuming you are using the Serial Monitor) the value as a string. You are expecting the whole string to be read as a number. That doesn't happen. YOU have to read the string and convert it to a number.

ash901226

Arduino take a sequence of number and treat every digit as its own digit. what you need is someway of telling the arduino that the sequence of number is not just a single digit thing but a whole.

i found out that sending a terminator help alot
maybe you could use a special character like "/" or "*" as to tell the arduino this is the end

like
Code: [Select]

while(Serial.read()!="/")
{
 int val=Serial.read;
 int Sum=Sum*10+val;
 }

the snippet does not work, but it should show you how it is done.

Thank you all.  I will work on the string conversion.

Go Up
 


Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

Arduino
via Egeo 16
Torino, 10131
Italy