Use of Serial.available and Serial.read



// SerialInput_1 (Arduino)
//
// Illustrates reading from the serial port.
//
// Opens the serial port (Serial.begin), flushes the serial port buffer by continually 
// reading (Serial.read) until Serial.available is 0.
//
// The program then continually loops.  If Serial.available is not zero, a character
// is read and if it is a numeric character, it is converted to an integer and this number
// of dots are written to the terminal.  Note that this is only a single digit.
//
// ***************************
// Important Note.
//
// In file arduino-0007\lib\targets\wiring.c, the implementation of serialAvailable is incorrect.
// It must be modified as shown below;
//
// int serialAvailable()
//{
// 	return (RX_BUFFER_SIZE + rx_buffer_head - rx_buffer_tail) % RX_BUFFER_SIZE;
//	//return (rx_buffer_head - rx_buffer_tail) % RX_BUFFER_SIZE; // <<<<<flaw here 
//}
//
// copyright, Peter H Anderson, June 3, '07

#define TRUE !0
#define FALSE 0

void flush_buffer(void);
int is_num(char ch);

void setup()
{
  Serial.begin(9600);
  delay(100); 
  flush_buffer();
  // Serial.read();
}

void loop()
{
  int  num_chars, num, n;
  char ch;
  
  if (Serial.available())
  {
     ch = Serial.read();
     // Serial.print(ch); // used for debugging
     if (is_num(ch))
     {
         num = ch - '0'; // convert to number
         for (n=0; n<num; n++)
         {
            Serial.print("."); // print num dots
         }
         Serial.print("\n");   // followed by a newline            
     }       
  }
}

int is_num(char ch)
{
   if ((ch >= '0') && (ch <= '9'))
   {
       return(TRUE);
   }
   else
   {
       return(FALSE);
   }
}

void flush_buffer(void)
{
  int num;
  while(1)
  {
    num = Serial.available();
    if (num == 0)
    {
      break;
    }
    else
    {
       Serial.read();
    }
  }
}
Open a demo forex trading account and first double your account three times!