Pages: [1]   Go Down
Author Topic: Simple count down timer problem  (Read 417 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 12
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
   //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.
Logged

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
      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.
Logged

Malaysia
Offline Offline
Sr. Member
****
Karma: 7
Posts: 393
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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:
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.
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 12
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: