Go Down

Topic: Interacting with user over serial.. Serial.read() (Read 644 times) previous topic - next topic


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: [Select]

#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()
 Serial.println("Hello Welcome to the clock, designed to test how I2C works with the DS1307\n");

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

Serial.println("Set time.");
//  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)
   else if (m==50)
    Serial.print("Wrong selection: ");

Thanks for your help.


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: [Select]
   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.


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!

via Egeo 16
Torino, 10131