Pages: [1]   Go Down
Author Topic: Interacting with user over serial.. Serial.read()  (Read 394 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 3
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

I am having problems reading in from the usb/serial rs232 to the arduino. The function Serial.read() is being ignored for some reason. I have tried many different ways, but nothing is helping.
In the following sketch, the function set_time() is only printing the strings but is not waiting for the user inputs, am I doing something wrong?

Code:
#include <Wire.h>

void intro()
{
   Serial.println("What would you like to do:");
   Serial.println("\t1) Set the time and date");
   Serial.println("\t2) Display the time in a loop until a key is hit (update every sec).");
   Serial.println("Yor selection: ");
}

void setup()
{
  //Wire.begin();
  Serial.begin(9600);
  Serial.println("Hello Welcome to the clock, designed to test how I2C works with the DS1307\n");
  intro();
}

void set_time()
{
 int  yr[2], mn[2], dt[2], dy, hr[2], mi[2], sec[2], day[2];

 Serial.println("Set time.");
 Serial.flush();
//  if (Serial.available() > 0) {
 Serial.print("Enter the year (00-99): ");
 yr[0] = Serial.read();
 yr[1] = Serial.read();
 Serial.print("Enter the month (01-12): ");
 mn[0] = Serial.read();
 mn[1] = Serial.read();
 Serial.print("Enter the date (01-31): ");
 dt[0] = Serial.read();
 dt[1] = Serial.read();
 Serial.print("Enter the day (1-7): ");
 dy = Serial.read();
 Serial.print("Enter the hour (01-23): ");
 hr[0] = Serial.read();
 hr[1] = Serial.read();
// hr = hr & 0x3f;      /* force clock to 24 hour mode */
 Serial.print("Enter the minute (00-59): ");
 mi[0] = Serial.read();
 mi[1] = Serial.read();
 Serial.print("Enter the second (00-59): ");
 sec[0] = Serial.read();
 sec[1] = Serial.read();
//  }
}

void display_time()
{
 Serial.println("Display time.");
}

void loop()
{
  int m=0;
  if (Serial.available() > 0) {
   m = Serial.read();
    if (m==49)
     set_time();
    else if (m==50)
     display_time();
    else
    {
     Serial.print("Wrong selection: ");
     Serial.println(m,BYTE);
    }
   intro();
  }
}

Thanks for your help.
Logged

0
Offline Offline
Faraday Member
**
Karma: 7
Posts: 2526
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Serial.read will return if there is nothing in the input buffer; you need to check and see if something is available, then read it.  For example
Code:
   while (!Serial.available())
      {;}
    c = Serial.read();
This code loops until something is available to read.

I think you can also check the Serial.read return status to find out if the read was succesful, but check the documentation to be sure.

-j
Logged

Pages: [1]   Go Up
Jump to: