REQ: Serial.available() < 2 as single value

Hello All,

I'm very basic and have a basic question (did search but couldn't find an answer)

I'm expecting to receive two characters from serial port but as I understand arduino receives one character at a time. I would highly appreciate if someone could guide me the way to receive more than one characters and how to use it a single value (i.e. x="abc")

thank you for your time and help

cheers

You can map each reading onto a char array. Then just read the char array.

char input[2];

if(Serial.available()) {
   input[0] = Serial.read();
   input[1] = Serial.read();
}

Serial.print(input);

This does ignore the fact that there might not be data there for both reads.

This code will echo a recieved string back to you. The last four characters will be printed.

const byte MAX_LENGTH_OF_INPUT = 4;

char recieved[MAX_LENGTH_OF_INPUT+1] = {'\0'};

void setup()
{
Serial.begin(9600);
}

void loop()
{
byte index = 0;
if (Serial.available()) {
delay( 50 );
do {
recieved[index++]=Serial.read();
} while(Serial.available()&&index<MAX_LENGTH_OF_INPUT);
}else{
Serial.println(recieved);
}
}

if(Serial.available()) {
   input[0] = Serial.read();
   input[1] = Serial.read();
}

What if "Serial.available()" only returns 1?

Yep AWOL. I put a note at the end that said it assumes there is data for both available.

you guys rock, thanks a lot "icecool2" n "AlphaBeta"

What you want is probably something like:

void serial_readstring(byte *buffer, byte length)
{
  while (length > 0) {
    if (Serial.available()) {
      *buffer++ = Serial.read();
      length -= 1;
    }
  }
}

Call it like:

byte serialbuf[10];

void loop()
{
   serial_readstring(serialbuf, 5);
   Serial.println((char *)serialbuf);
}

lovely that should do the trick for me

cheers westfw